summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--PICA_client.c138
-rw-r--r--PICA_client.h4
-rw-r--r--PICA_node.c1420
-rw-r--r--pica-client/accounts.cpp160
-rw-r--r--pica-client/accounts.h48
-rw-r--r--pica-client/accountswindow.cpp338
-rw-r--r--pica-client/accountswindow.h32
-rw-r--r--pica-client/askpassword.cpp98
-rw-r--r--pica-client/askpassword.h28
-rw-r--r--pica-client/chatwindow.cpp497
-rw-r--r--pica-client/chatwindow.h89
-rw-r--r--pica-client/contactlistwidget.cpp284
-rw-r--r--pica-client/contactlistwidget.h50
-rw-r--r--pica-client/contacts.cpp214
-rw-r--r--pica-client/contacts.h60
-rw-r--r--pica-client/dhparam.cpp94
-rw-r--r--pica-client/dhparam.h24
-rw-r--r--pica-client/dialogs/addaccountdialog.cpp118
-rw-r--r--pica-client/dialogs/addaccountdialog.h34
-rw-r--r--pica-client/dialogs/filetransferdialog.cpp472
-rw-r--r--pica-client/dialogs/filetransferdialog.h117
-rw-r--r--pica-client/dialogs/forgedcertdialog.cpp48
-rw-r--r--pica-client/dialogs/forgedcertdialog.h26
-rw-r--r--pica-client/dialogs/registeraccountdialog.cpp316
-rw-r--r--pica-client/dialogs/registeraccountdialog.h58
-rw-r--r--pica-client/dialogs/settingsdialog.cpp90
-rw-r--r--pica-client/dialogs/settingsdialog.h8
-rw-r--r--pica-client/dialogs/showpicaiddialog.cpp36
-rw-r--r--pica-client/dialogs/showpicaiddialog.h12
-rw-r--r--pica-client/dialogs/viewcertdialog.cpp42
-rw-r--r--pica-client/dialogs/viewcertdialog.h18
-rw-r--r--pica-client/filetransfercontroller.cpp242
-rw-r--r--pica-client/filetransfercontroller.h56
-rw-r--r--pica-client/history.cpp156
-rw-r--r--pica-client/history.h36
-rw-r--r--pica-client/main.cpp550
-rw-r--r--pica-client/mainwindow.cpp154
-rw-r--r--pica-client/mainwindow.h53
-rw-r--r--pica-client/msguirouter.cpp202
-rw-r--r--pica-client/msguirouter.h32
-rw-r--r--pica-client/nodes.cpp76
-rw-r--r--pica-client/nodes.h24
-rw-r--r--pica-client/nodethread.cpp196
-rw-r--r--pica-client/nodethread.h30
-rw-r--r--pica-client/openssltool.cpp223
-rw-r--r--pica-client/openssltool.h22
-rw-r--r--pica-client/picaactioncenter.cpp52
-rw-r--r--pica-client/picaactioncenter.h49
-rw-r--r--pica-client/picasystray.cpp66
-rw-r--r--pica-client/picasystray.h32
-rw-r--r--pica-client/settings.cpp50
-rw-r--r--pica-client/settings.h12
-rw-r--r--pica-client/skynet.cpp797
-rw-r--r--pica-client/skynet.h189
-rw-r--r--pica-client/sound.cpp10
-rw-r--r--pica-client/sound.h8
56 files changed, 4162 insertions, 4128 deletions
diff --git a/PICA_client.c b/PICA_client.c
index 60ea14e..59fcc03 100644
--- a/PICA_client.c
+++ b/PICA_client.c
@@ -216,7 +216,7 @@ static int verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
if (!preverify_ok)
{
printf("verify error:num=%d:%s:depth=%d:%s\n", err,
- X509_verify_cert_error_string(err), depth, buf);
+ X509_verify_cert_error_string(err), depth, buf);
}
@@ -826,10 +826,10 @@ static unsigned int procmsg_CLNODELIST(unsigned char* buf, unsigned int nb, void
case PICA_PROTO_NEWNODE_IPV4:
callbacks.nodelist_cb(
- PICA_PROTO_NEWNODE_IPV4,
- buf + pos + 1,
- inet_ntop(AF_INET, buf + pos + 1, ipaddr_string, INET6_ADDRSTRLEN),
- ntohs(*(uint16_t*)(buf + pos + 5))
+ PICA_PROTO_NEWNODE_IPV4,
+ buf + pos + 1,
+ inet_ntop(AF_INET, buf + pos + 1, ipaddr_string, INET6_ADDRSTRLEN),
+ ntohs(*(uint16_t*)(buf + pos + 5))
);
pos += PICA_PROTO_NODELIST_ITEM_IPV4_SIZE;
@@ -838,10 +838,10 @@ static unsigned int procmsg_CLNODELIST(unsigned char* buf, unsigned int nb, void
case PICA_PROTO_NEWNODE_IPV6:
callbacks.nodelist_cb(
- PICA_PROTO_NEWNODE_IPV6,
- buf + pos + 1,
- inet_ntop(AF_INET6, buf + pos + 1, ipaddr_string, INET6_ADDRSTRLEN),
- ntohs(*(uint16_t*)(buf + pos + 17))
+ PICA_PROTO_NEWNODE_IPV6,
+ buf + pos + 1,
+ inet_ntop(AF_INET6, buf + pos + 1, ipaddr_string, INET6_ADDRSTRLEN),
+ ntohs(*(uint16_t*)(buf + pos + 17))
);
pos += PICA_PROTO_NODELIST_ITEM_IPV6_SIZE;
@@ -855,10 +855,10 @@ static unsigned int procmsg_CLNODELIST(unsigned char* buf, unsigned int nb, void
buf[pos + 2 + buf[pos + 1]] = '\0'; // and replace it with string terminating zero
callbacks.nodelist_cb(
- PICA_PROTO_NEWNODE_DNS,
- buf + pos + 2,
- buf + pos + 2,
- port
+ PICA_PROTO_NEWNODE_DNS,
+ buf + pos + 2,
+ buf + pos + 2,
+ port
);
buf[pos + 2 + buf[pos + 1]] = temp_zeroswap;
@@ -1050,7 +1050,7 @@ static unsigned int procmsg_FILEFRAGMENT(unsigned char* buf, unsigned int nb, vo
*Allow incoming FILEFRAGMENTs while paused
*/
if (chan->recvfilestate != PICA_CHANRECVFILESTATE_RECEIVING
- && chan->recvfilestate != PICA_CHANRECVFILESTATE_PAUSED)
+ && chan->recvfilestate != PICA_CHANRECVFILESTATE_PAUSED)
return 0;
if (nb - 4 != *(uint16_t*)(buf + 2))
@@ -1100,7 +1100,7 @@ static unsigned int procmsg_FILECONTROL(unsigned char* buf, unsigned int nb, voi
fprintf(stderr, "procmsg_FILECONTROL sender_cmd = %i receiver_cmd = %i\n", sender_cmd, receiver_cmd);//debug
if ((chan->sendfilestate == PICA_CHANSENDFILESTATE_IDLE || chan->sendfilestate == PICA_CHANSENDFILESTATE_SENTREQ)
- && receiver_cmd != PICA_PROTO_FILECONTROL_VOID)
+ && receiver_cmd != PICA_PROTO_FILECONTROL_VOID)
return 0;
if (chan->recvfilestate == PICA_CHANRECVFILESTATE_IDLE && sender_cmd != PICA_PROTO_FILECONTROL_VOID)
@@ -1261,8 +1261,8 @@ int PICA_client_init(struct PICA_client_callbacks *clcbs)
}
static int check_pkey_passphrase(const char *pkey_file,
- int (*password_cb)(char *buf, int size, int rwflag, void *userdata),
- void *userdata)
+ int (*password_cb)(char *buf, int size, int rwflag, void *userdata),
+ void *userdata)
{
RSA *rsa;
FILE *f;
@@ -1391,10 +1391,10 @@ error_ret_0: //(0)
}
int PICA_open_acc(const char *cert_file,
- const char *pkey_file,
- const char *dh_param_file,
- int (*password_cb)(char *buf, int size, int rwflag, void *userdata),
- struct PICA_acc **acc)
+ const char *pkey_file,
+ const char *dh_param_file,
+ int (*password_cb)(char *buf, int size, int rwflag, void *userdata),
+ struct PICA_acc **acc)
{
int ret, ret_err;
DH *dh = NULL;
@@ -1614,8 +1614,8 @@ static int directc2c_stage2_starttls(struct PICA_directc2c *d, struct PICA_c2c *
//....
int PICA_new_c2n(const struct PICA_acc *acc, const char *nodeaddr, unsigned int port,
- enum PICA_directc2c_config direct_c2c_mode, struct PICA_listener *l,
- struct PICA_c2n **ci)
+ enum PICA_directc2c_config direct_c2c_mode, struct PICA_listener *l,
+ struct PICA_c2n **ci)
{
PICA_TRACEFUNC
int ret, ret_err;
@@ -1753,12 +1753,12 @@ ret=SSL_accept(cid->ssl_comm);
/////////////////state_
cid->state = PICA_C2N_STATE_WAITINGTLS;
if (ret!=1)
- {
- //printf("SSL_accept ret=%i\n SSL_get_error=%i\n",ret,SSL_get_error(cid->ssl_comm,ret));//debug
- //ERR_CHECK
- ret_err=PICA_ERRSSL;
- goto error_ret_4;
- }*/ /*
+{
+//printf("SSL_accept ret=%i\n SSL_get_error=%i\n",ret,SSL_get_error(cid->ssl_comm,ret));//debug
+ //ERR_CHECK
+ret_err=PICA_ERRSSL;
+goto error_ret_4;
+}*/ /*
cid->state = PICA_C2N_STATE_CONNECTED;//<<<!!!
{
@@ -1767,9 +1767,9 @@ struct PICA_proto_msg *mp;
mp = c2n_writebuf_push( cid, PICA_PROTO_CLNODELISTREQ, PICA_PROTO_CLNODELISTREQ_SIZE);
if (mp)
- {
- RAND_pseudo_bytes(mp->tail, 2);
- }
+{
+RAND_pseudo_bytes(mp->tail, 2);
+}
}
*/
@@ -1877,7 +1877,7 @@ static int check_async_connect_result(int sock, struct sockaddr* a, int addrlen)
if (0 == getsockopt(sock, SOL_SOCKET, SO_ERROR, &optval, &optlen) && optval == 0)
#else
if (SOCKET_ERROR == connect(sock, a, addrlen) &&
- WSAEISCONN == WSAGetLastError())
+ WSAEISCONN == WSAGetLastError())
#endif
ret = PICA_OK;
@@ -1927,7 +1927,7 @@ static int process_c2n(struct PICA_c2n *c2n, fd_set *rfds, fd_set *wfds)
else
{
if (c2n->node_ver_major > PICA_PROTO_VER_HIGH ||
- (c2n->node_ver_major == PICA_PROTO_VER_HIGH && c2n->node_ver_minor > PICA_PROTO_VER_LOW))
+ (c2n->node_ver_major == PICA_PROTO_VER_HIGH && c2n->node_ver_minor > PICA_PROTO_VER_LOW))
ret = PICA_ERRPROTONEW;
else
ret = PICA_ERRPROTOOLD;
@@ -2037,15 +2037,15 @@ static int process_c2c(struct PICA_c2c *c2c, fd_set *rfds, fd_set *wfds)
ret = PICA_ERRSSL;
}
else if (sslret == 1)
- {
- ret = c2c_verify_peer_cert(c2c);
+ {
+ ret = c2c_verify_peer_cert(c2c);
- if (ret == PICA_OK && c2c->outgoing)
- ret = c2c_stage4_sendc2cconnreq(c2c);
+ if (ret == PICA_OK && c2c->outgoing)
+ ret = c2c_stage4_sendc2cconnreq(c2c);
- if (ret == PICA_OK && c2c->outgoing == 0)
- c2c->state = PICA_C2C_STATE_WAITINGC2CPROTOVER;
- }
+ if (ret == PICA_OK && c2c->outgoing == 0)
+ c2c->state = PICA_C2C_STATE_WAITINGC2CPROTOVER;
+ }
}
break;
@@ -2067,7 +2067,7 @@ static int process_c2c(struct PICA_c2c *c2c, fd_set *rfds, fd_set *wfds)
case PICA_C2C_STATE_ACTIVE:
if (FD_ISSET(c2c->sck_data, wfds)
- || c2c->directc2c_state == PICA_DIRECTC2C_STATE_ACTIVE && FD_ISSET(c2c->direct->sck, wfds))
+ || c2c->directc2c_state == PICA_DIRECTC2C_STATE_ACTIVE && FD_ISSET(c2c->direct->sck, wfds))
{
if (c2c->write_pos > 0)
{
@@ -2080,7 +2080,7 @@ static int process_c2c(struct PICA_c2c *c2c, fd_set *rfds, fd_set *wfds)
}
if (ret == PICA_OK && (FD_ISSET(c2c->sck_data, rfds)
- || c2c->directc2c_state == PICA_DIRECTC2C_STATE_ACTIVE && FD_ISSET(c2c->direct->sck, rfds)))
+ || c2c->directc2c_state == PICA_DIRECTC2C_STATE_ACTIVE && FD_ISSET(c2c->direct->sck, rfds)))
{
ret = PICA_read_c2c(c2c);
}
@@ -2094,12 +2094,12 @@ static int process_c2c(struct PICA_c2c *c2c, fd_set *rfds, fd_set *wfds)
}
if (ret != PICA_OK)
- {
- if (c2c->state > PICA_C2C_STATE_NEW && c2c->state < PICA_C2C_STATE_ACTIVE)
- callbacks.c2c_failed_cb(c2c->peer_id);
- else
- callbacks.c2c_closed_cb(c2c->peer_id, ret);
- }
+ {
+ if (c2c->state > PICA_C2C_STATE_NEW && c2c->state < PICA_C2C_STATE_ACTIVE)
+ callbacks.c2c_failed_cb(c2c->peer_id);
+ else
+ callbacks.c2c_closed_cb(c2c->peer_id, ret);
+ }
return ret;
}
@@ -2232,7 +2232,7 @@ static void process_directc2c(struct PICA_c2n *c2n, fd_set *rfds, fd_set *wfds)
switch(d->state)
{
- case PICA_DIRECTC2C_CONNSTATE_CONNECTING:
+ case PICA_DIRECTC2C_CONNSTATE_CONNECTING:
if (FD_ISSET(d->sck, wfds))
{
@@ -2249,14 +2249,14 @@ static void process_directc2c(struct PICA_c2n *c2n, fd_set *rfds, fd_set *wfds)
}
break;
- case PICA_DIRECTC2C_CONNSTATE_WAITINGTLS:
+ case PICA_DIRECTC2C_CONNSTATE_WAITINGTLS:
if (FD_ISSET(d->sck, wfds) || FD_ISSET(d->sck, rfds))
{
ret = SSL_connect(d->ssl);
if (ret != 1)
{
- if (SSL_get_error(d->ssl, ret)== SSL_ERROR_WANT_WRITE)
+ if (SSL_get_error(d->ssl, ret) == SSL_ERROR_WANT_WRITE)
d->want_write = 1;
ret = process_async_ssl_errors(d->ssl, ret);
@@ -2291,7 +2291,7 @@ static void process_directc2c(struct PICA_c2n *c2n, fd_set *rfds, fd_set *wfds)
}
break;
- case PICA_DIRECTC2C_CONNSTATE_FAILED:
+ case PICA_DIRECTC2C_CONNSTATE_FAILED:
ret = directc2c_connect_next(d, c2c);
if (ret == PICA_ERRNOTFOUND)
@@ -2302,7 +2302,7 @@ static void process_directc2c(struct PICA_c2n *c2n, fd_set *rfds, fd_set *wfds)
}
break;
- case PICA_DIRECTC2C_CONNSTATE_ACTIVE:
+ case PICA_DIRECTC2C_CONNSTATE_ACTIVE:
c2c->directc2c_state = PICA_DIRECTC2C_STATE_ACTIVE;
break;
@@ -2435,9 +2435,9 @@ static int process_listener(struct PICA_listener *lst, fd_set *rfds, fd_set *wfd
struct PICA_directc2c *kill_ptr = NULL;
if ((ret = process_listener_conn(conn, rfds, wfds)) != PICA_OK)
- {
- kill_ptr = conn;
- }
+ {
+ kill_ptr = conn;
+ }
//fprintf(stderr, "process_listener_conn() returned %i\n", ret);
@@ -2492,7 +2492,7 @@ int PICA_event_loop(struct PICA_c2n **connections, int timeout)
fdset_add(&rfds, (*ic2n)->sck_comm, &nfds);
if ((*ic2n)->write_pos || (*ic2n)->state == PICA_C2N_STATE_CONNECTING
- || (*ic2n)->want_write/*(*ic2n)->state == PICA_C2N_STATE_WAITINGTLS*/)
+ || (*ic2n)->want_write/*(*ic2n)->state == PICA_C2N_STATE_WAITINGTLS*/)
{
(*ic2n)->want_write = 0;
fdset_add(&wfds, (*ic2n)->sck_comm, &nfds);
@@ -2525,7 +2525,7 @@ int PICA_event_loop(struct PICA_c2n **connections, int timeout)
fdset_add(&rfds, ic2c->sck_data, &nfds);
if ((ic2c->write_pos || ic2c->state == PICA_C2C_STATE_CONNECTING || (ic2c->state == PICA_C2C_STATE_WAITINGTLS && ic2c->want_write)
- || ic2c->sendfilestate == PICA_CHANSENDFILESTATE_SENDING) && ic2c->directc2c_state != PICA_DIRECTC2C_STATE_ACTIVE)
+ || ic2c->sendfilestate == PICA_CHANSENDFILESTATE_SENDING) && ic2c->directc2c_state != PICA_DIRECTC2C_STATE_ACTIVE)
{
ic2c->want_write = 0;
fdset_add(&wfds, ic2c->sck_data, &nfds);
@@ -2533,7 +2533,7 @@ int PICA_event_loop(struct PICA_c2n **connections, int timeout)
}
if (ic2c->state == PICA_C2C_STATE_ACTIVE && (ic2c->directc2c_state == PICA_DIRECTC2C_STATE_CONNECTING || ic2c->directc2c_state == PICA_DIRECTC2C_STATE_ACTIVE)
- && ic2c->direct && ic2c->direct->state >= PICA_DIRECTC2C_CONNSTATE_CONNECTING)
+ && ic2c->direct && ic2c->direct->state >= PICA_DIRECTC2C_CONNSTATE_CONNECTING)
{
fdset_add(&rfds, ic2c->direct->sck, &nfds);
@@ -2838,10 +2838,10 @@ int PICA_read_c2c(struct PICA_c2c *chn)
SSL *ssl_to_read = chn->ssl;
if (chn->state != PICA_C2C_STATE_WAITINGREP && chn->state != PICA_C2C_STATE_WAITINGC2CPROTOVER && chn->state != PICA_C2C_STATE_ACTIVE)
- {
- fputs("PICA_read_c2c() was called for incorrect state!\n", stderr);
- exit(-1);
- }
+ {
+ fputs("PICA_read_c2c() was called for incorrect state!\n", stderr);
+ exit(-1);
+ }
if (chn->switched_to_directc2c_read)
ssl_to_read = chn->direct->ssl;
@@ -3140,7 +3140,7 @@ int PICA_cancel_file(struct PICA_c2c *chan, int sending)
if (sending)
{
if (chan->sendfilestate != PICA_CHANSENDFILESTATE_SENDING
- && chan->sendfilestate != PICA_CHANSENDFILESTATE_PAUSED)
+ && chan->sendfilestate != PICA_CHANSENDFILESTATE_PAUSED)
return PICA_ERRINVARG;
fclose(chan->sendfile_stream);
@@ -3152,7 +3152,7 @@ int PICA_cancel_file(struct PICA_c2c *chan, int sending)
else
{
if (chan->recvfilestate != PICA_CHANRECVFILESTATE_RECEIVING
- && chan->recvfilestate != PICA_CHANRECVFILESTATE_PAUSED)
+ && chan->recvfilestate != PICA_CHANRECVFILESTATE_PAUSED)
return PICA_ERRINVARG;
fclose(chan->recvfile_stream);
@@ -3375,9 +3375,9 @@ const char *PICA_inet_ntop(int af, const void *src, char *dst, size_t size)
case AF_INET6:
sprintf(dst, "%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x:%x%02x", chsrc[0], chsrc[1], chsrc[2], chsrc[3],
- chsrc[4], chsrc[5], chsrc[6], chsrc[7],
- chsrc[8], chsrc[9], chsrc[10], chsrc[11],
- chsrc[12], chsrc[13], chsrc[14], chsrc[15]);
+ chsrc[4], chsrc[5], chsrc[6], chsrc[7],
+ chsrc[8], chsrc[9], chsrc[10], chsrc[11],
+ chsrc[12], chsrc[13], chsrc[14], chsrc[15]);
break;
default:
diff --git a/PICA_client.h b/PICA_client.h
index b56e034..4a3e12a 100644
--- a/PICA_client.h
+++ b/PICA_client.h
@@ -334,8 +334,8 @@ int PICA_get_id_from_cert_string(const char *cert_pem, unsigned char *id);
int PICA_client_init(struct PICA_client_callbacks *clcbs);
int PICA_new_c2n(const struct PICA_acc *acc, const char *nodeaddr, unsigned int port,
- enum PICA_directc2c_config direct_c2c_mode, struct PICA_listener *l,
- struct PICA_c2n **ci);
+ enum PICA_directc2c_config direct_c2c_mode, struct PICA_listener *l,
+ struct PICA_c2n **ci);
int PICA_new_c2c(struct PICA_c2n *ci, const unsigned char *peer_id, struct PICA_listener *l, struct PICA_c2c **chn);
diff --git a/PICA_node.c b/PICA_node.c
index 951e8d9..fdd1759 100644
--- a/PICA_node.c
+++ b/PICA_node.c
@@ -1,4 +1,4 @@
-//Программа является узлом сети
+//Программа является узлом сети
//
#include <stdio.h>
#include <stdlib.h>
@@ -122,7 +122,7 @@ struct newconn* newconn_add(struct newconn *ncs, int *pos);
void PICA_node_joinskynet(const char* addrlistfilename, const char *my_addr);
-//описание формата сообщений, которые могут приходить _ОТ_ клиентов по управляющему защищенному соединению
+//описание формата сообщений, которые могут приходить _ОТ_ клиентов по управляющему защищенному соединению
#define MSGINFO_MSGSNUM(arr) (sizeof(arr)/sizeof(struct PICA_msginfo))
struct PICA_msginfo _msginfo_comm[] =
@@ -138,8 +138,8 @@ struct PICA_msginfo _msginfo_comm[] =
struct PICA_msginfo _msginfo_node[] =
{
{PICA_PROTO_INITRESPOK, PICA_MSG_FIXED_SIZE, PICA_PROTO_INITRESPOK_SIZE, procmsg_NODERESP},
- {PICA_PROTO_VERDIFFER , PICA_MSG_FIXED_SIZE, PICA_PROTO_VERDIFFER_SIZE, procmsg_NODERESP},
- {PICA_PROTO_NEWNODE_IPV4 , PICA_MSG_FIXED_SIZE, PICA_PROTO_NEWNODE_IPV4_SIZE, procmsg_NEWNODE},
+ {PICA_PROTO_VERDIFFER, PICA_MSG_FIXED_SIZE, PICA_PROTO_VERDIFFER_SIZE, procmsg_NODERESP},
+ {PICA_PROTO_NEWNODE_IPV4, PICA_MSG_FIXED_SIZE, PICA_PROTO_NEWNODE_IPV4_SIZE, procmsg_NEWNODE},
{PICA_PROTO_NODELISTREQ, PICA_MSG_FIXED_SIZE, PICA_PROTO_NODELISTREQ_SIZE, procmsg_NODELISTREQ},
{PICA_PROTO_NODELIST, PICA_MSG_VAR_SIZE, PICA_MSG_VARSIZE_INT16, procmsg_NODELIST},
@@ -176,14 +176,14 @@ static int verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
X509_NAME_oneline(X509_get_subject_name(err_cert), buf, 256);
if (err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT && depth == 0)
- preverify_ok = 1;
+ preverify_ok = 1;
if (!preverify_ok)
{
PICA_info("certificate verification error:num=%d:%s:depth=%d:%s\n", err, X509_verify_cert_error_string(err), depth, buf);
}
- return preverify_ok;
+ return preverify_ok;
}
unsigned int procmsg_INITREQ(unsigned char* buf, unsigned int size, void* ptr)
@@ -195,36 +195,36 @@ unsigned int procmsg_INITREQ(unsigned char* buf, unsigned int size, void* ptr)
if (buf[2] == PICA_PROTO_VER_HIGH && buf[3] == PICA_PROTO_VER_LOW)
{
- struct client *c;
+ struct client *c;
c = client_list_addnew(nc);
- if (!c)
- return 0;
-
- newconn_free(nc);
+ if (!c)
+ return 0;
+
+ newconn_free(nc);
if ((mp = client_wbuf_push(c, PICA_PROTO_INITRESPOK, PICA_PROTO_INITRESPOK_SIZE)))
{
mp->tail[0] = 'O';
mp->tail[1] = 'K';
}
-
+
c->state = PICA_CLSTATE_SENDINGRESP;
}///////---------<<<<<<<<<<< new client
else
{
- //// PICA_PROTO_VERDIFFER
+ //// PICA_PROTO_VERDIFFER
send(nc->sck, msg_VERDIFFER, msg_VERDIFFER_len, 0);
- if (buf[2] > PICA_PROTO_VER_HIGH || (buf[2] == PICA_PROTO_VER_HIGH && buf[3] > PICA_PROTO_VER_LOW))
+ if (buf[2] > PICA_PROTO_VER_HIGH || (buf[2] == PICA_PROTO_VER_HIGH && buf[3] > PICA_PROTO_VER_LOW))
{
- PICA_warn("Client has newer protocol version than node. Please check if update for pica-node is available");
+ PICA_warn("Client has newer protocol version than node. Please check if update for pica-node is available");
}
- else
+ else
{
- PICA_info("Client has older protocol version. Disconnecting ...");
+ PICA_info("Client has older protocol version. Disconnecting ...");
}
- return 0;
+ return 0;
}
return 1;
@@ -251,44 +251,44 @@ unsigned int procmsg_CONNID(unsigned char* buf, unsigned int size, void* ptr)
if (!link)
{
- PICA_debug3("corresponding cclink not found");
- return 0;
+ PICA_debug3("corresponding cclink not found");
+ return 0;
}
if (link->state != PICA_CCLINK_LOCAL_WAITCONNCLE && link->state != PICA_CCLINK_LOCAL_WAITCONNCLR
&& link->state != PICA_CCLINK_N2NCLR_WAITCONNCLR && link->state != PICA_CCLINK_N2NCLE_WAITCONNCLE)
{
- PICA_debug2("found cclink is not in expected state");
- return 0;
+ PICA_debug2("found cclink is not in expected state");
+ return 0;
}
-
+
{
struct client *c;
//проверка IP адреса.
//IP адрес должен совпадать с адресом клиента в управляющем соединении
if (link->state == PICA_CCLINK_LOCAL_WAITCONNCLE || link->state == PICA_CCLINK_N2NCLE_WAITCONNCLE)
- c = link->p2;
+ c = link->p2;
else if (link->state == PICA_CCLINK_LOCAL_WAITCONNCLR || link->state == PICA_CCLINK_N2NCLR_WAITCONNCLR)
- c = link->p1;
+ c = link->p1;
if (nc->addr.sin_addr.s_addr != c->addr.sin_addr.s_addr)
- {
- PICA_warn("CONNID: IP check failed. IP address of sender does not match IP in c2n connection");
- return 0;
- }
+ {
+ PICA_warn("CONNID: IP check failed. IP address of sender does not match IP in c2n connection");
+ return 0;
+ }
}
if (link->state == PICA_CCLINK_LOCAL_WAITCONNCLE)
{
if((mp = client_wbuf_push(link->p1, PICA_PROTO_FOUND, PICA_PROTO_FOUND_SIZE)))
{
- memcpy(mp->tail, callee_id, PICA_ID_SIZE);
+ memcpy(mp->tail, callee_id, PICA_ID_SIZE);
}
- else
+ else
{
- cclink_list_delete(link);
- return 0;
+ cclink_list_delete(link);
+ return 0;
}
}
@@ -296,13 +296,13 @@ unsigned int procmsg_CONNID(unsigned char* buf, unsigned int size, void* ptr)
{
if((mp = nodelink_wbuf_push(link->caller_node, PICA_PROTO_N2NALLOW, PICA_PROTO_N2NALLOW_SIZE)))
{
- memcpy(mp->tail, caller_id, PICA_ID_SIZE);
- memcpy(mp->tail + PICA_ID_SIZE, callee_id, PICA_ID_SIZE);
+ memcpy(mp->tail, caller_id, PICA_ID_SIZE);
+ memcpy(mp->tail + PICA_ID_SIZE, callee_id, PICA_ID_SIZE);
}
- else
+ else
{
- cclink_list_delete(link);
- return 0;
+ cclink_list_delete(link);
+ return 0;
}
}
PICA_debug3("CONNID processed successfully");
@@ -321,13 +321,13 @@ unsigned int procmsg_NODECONNREQ(unsigned char* buf, unsigned int size, void* pt
if (buf[2] == PICA_PROTO_VER_HIGH &&
buf[3] == PICA_PROTO_VER_LOW)
{
- ////-прием входящего подключения
- //--------------------------
- struct nodelink *nl;
+ ////-прием входящего подключения
+ //--------------------------
+ struct nodelink *nl;
nl = nodelink_list_addnew(nc);
- newconn_free(nc);
- if (!nl)
- return 0;
+ newconn_free(nc);
+ if (!nl)
+ return 0;
if ((mp = nodelink_wbuf_push(nl, PICA_PROTO_INITRESPOK, PICA_PROTO_INITRESPOK_SIZE)))
{
@@ -337,20 +337,20 @@ unsigned int procmsg_NODECONNREQ(unsigned char* buf, unsigned int size, void* pt
}
else
{
- //// PICA_PROTO_VERDIFFER
+ //// PICA_PROTO_VERDIFFER
send(nc->sck, msg_VERDIFFER, msg_VERDIFFER_len, 0);
- if (buf[2] > PICA_PROTO_VER_HIGH || (buf[2] == PICA_PROTO_VER_HIGH && buf[3] > PICA_PROTO_VER_LOW))
+ if (buf[2] > PICA_PROTO_VER_HIGH || (buf[2] == PICA_PROTO_VER_HIGH && buf[3] > PICA_PROTO_VER_LOW))
{
- PICA_warn("Node %s has newer protocol version [%u, %u]. Please check if update for pica-node is available",
- inet_ntoa(nc->addr.sin_addr), buf[2], buf[3]);
+ PICA_warn("Node %s has newer protocol version [%u, %u]. Please check if update for pica-node is available",
+ inet_ntoa(nc->addr.sin_addr), buf[2], buf[3]);
}
- else
+ else
{
- PICA_info("Node %s has older protocol version. Disconnecting ...", inet_ntoa(nc->addr.sin_addr));
+ PICA_info("Node %s has older protocol version. Disconnecting ...", inet_ntoa(nc->addr.sin_addr));
}
- return 0;
+ return 0;
}
return ;
@@ -364,16 +364,16 @@ void mapfunc_sendsearchreq(struct nodelink *p, const unsigned char *id)
mp = nodelink_wbuf_push(p, PICA_PROTO_SEARCH, PICA_PROTO_SEARCH_SIZE);
if (mp)
- memcpy(mp->tail, id, PICA_ID_SIZE);
+ memcpy(mp->tail, id, PICA_ID_SIZE);
}
int nodelink_send_searchreq(const unsigned char *id)
{
if (!nodelink_list_count)
- return 0;
+ return 0;
LISTMAP(nodelink, nodelink, mapfunc_sendsearchreq, id);
-
+
return 1;
}
@@ -391,43 +391,43 @@ unsigned int procmsg_CONNREQOUTG(unsigned char* buf, unsigned int size, void* pt
if ((o = client_tree_search(callee_id)))
{
- if (cclink_list_search(i->id, callee_id))
+ if (cclink_list_search(i->id, callee_id))
{
PICA_info("duplicate request for existing c2c connection is ignored");
- return 1;
+ return 1;
}
- if (memcmp(i->id, callee_id, PICA_ID_SIZE) == 0)
+ if (memcmp(i->id, callee_id, PICA_ID_SIZE) == 0)
{
PICA_info("request to create c2c connection to self is ignored");
- return 1;
+ return 1;
}
- //отправить o _CONNREQINC
+ //отправить o _CONNREQINC
if ((mp = client_wbuf_push(o, PICA_PROTO_CONNREQINC, PICA_PROTO_CONNREQINC_SIZE)))
{
- memcpy(mp->tail, i->id, PICA_ID_SIZE);
+ memcpy(mp->tail, i->id, PICA_ID_SIZE);
cclink_list_addlocal(i, o);
-
- o->tmst = time(0);
- o->disconnect_ticking = 1;//if client does not reply in given time period, client is disconnected
- return 1;
+
+ o->tmst = time(0);
+ o->disconnect_ticking = 1;//if client does not reply in given time period, client is disconnected
+ return 1;
}
-
- return 1;//сообщение отправить не удалось, но все равно возвращаем 1
+
+ return 1;//сообщение отправить не удалось, но все равно возвращаем 1
}
-
+
if (cclink_list_findwaitsearch(callee_id)/*search request for this id is already in progress*/
- || nodelink_send_searchreq(callee_id) /*make new search*/)
+ || nodelink_send_searchreq(callee_id) /*make new search*/)
{
cclink_list_addn2nclr(i, callee_id);
- return 1;
+ return 1;
}
-
+
//отправить i _NOTFOUND
if ((mp = client_wbuf_push(i, PICA_PROTO_NOTFOUND, PICA_PROTO_NOTFOUND_SIZE)))
{
- memcpy(mp->tail, callee_id, PICA_ID_SIZE);
+ memcpy(mp->tail, callee_id, PICA_ID_SIZE);
}
return 1;
@@ -450,11 +450,11 @@ unsigned int procmsg_CONNALLOW(unsigned char* buf, unsigned int size, void* ptr)
link = cclink_list_search(caller_id, callee->id);
if (!link)
- return 0;
+ return 0;
if (link->state != PICA_CCLINK_LOCAL_WAITREP &&
link->state != PICA_CCLINK_N2NCLE_WAITREP)
- return 0;
+ return 0;
cclink_setwaitconn(link);
@@ -479,32 +479,32 @@ unsigned int procmsg_CONNDENY(unsigned char* buf, unsigned int size, void* ptr)
link = cclink_list_search(caller_id, callee->id);
if (!link)
- return 0;
+ return 0;
caller = link -> p1;//check for NULL if not LOCAL
if (link->state != PICA_CCLINK_LOCAL_WAITREP &&
link->state != PICA_CCLINK_N2NCLE_WAITREP)
{
- cclink_list_delete(link);
- return 0;
+ cclink_list_delete(link);
+ return 0;
}
if (link->state == PICA_CCLINK_LOCAL_WAITREP)
{
- //отправить caller _NOTFOUND
+ //отправить caller _NOTFOUND
if ((mp = client_wbuf_push(caller, PICA_PROTO_NOTFOUND, PICA_PROTO_NOTFOUND_SIZE)))
{
- memcpy(mp->tail, callee->id, PICA_ID_SIZE);
+ memcpy(mp->tail, callee->id, PICA_ID_SIZE);
}
}
else if (link->state == PICA_CCLINK_N2NCLE_WAITREP)
{
- //отправить caller N2NNOTFOUND
+ //отправить caller N2NNOTFOUND
if ((mp = nodelink_wbuf_push(link->caller_node, PICA_PROTO_N2NNOTFOUND, PICA_PROTO_N2NNOTFOUND_SIZE)))
{
- memcpy(mp->tail, caller_id, PICA_ID_SIZE);
- memcpy(mp->tail + PICA_ID_SIZE, callee->id, PICA_ID_SIZE);
+ memcpy(mp->tail, caller_id, PICA_ID_SIZE);
+ memcpy(mp->tail + PICA_ID_SIZE, callee->id, PICA_ID_SIZE);
}
}
@@ -525,7 +525,7 @@ unsigned int procmsg_PINGREQ_client(unsigned char* buf, unsigned int size, void*
RAND_pseudo_bytes(mp->tail, 2);
}
else
- return 0;
+ return 0;
return 1;
}
@@ -554,7 +554,7 @@ unsigned int procmsg_PINGREQ_node(unsigned char* buf, unsigned int size, void* p
RAND_pseudo_bytes(mp->tail, 2);
}
else
- return 0;
+ return 0;
return 1;
}
@@ -582,39 +582,39 @@ unsigned int procmsg_NODERESP(unsigned char* buf, unsigned int size, void* ptr)
{
case PICA_PROTO_INITRESPOK:
if (buf[2] != 'O' || buf[3] != 'K')
- return 0;
+ return 0;
+
-
mp = nodelink_wbuf_push(n, PICA_PROTO_NEWNODE_IPV4, PICA_PROTO_NEWNODE_IPV4_SIZE);//IPv6
if (mp)
- {
+ {
*((in_addr_t*)(mp->tail)) = inet_addr(nodecfg.announced_addr);
*((in_port_t*)(mp->tail + 4)) = (nodecfg.listen_port ? htons(atoi(nodecfg.listen_port)) : htons(PICA_COMM_PORT)); //CONF;
- }
+ }
else
- return 0;
+ return 0;
mp = nodelink_wbuf_push(n, PICA_PROTO_NODELISTREQ, PICA_PROTO_NODELISTREQ_SIZE);
if (mp)
- {
+ {
RAND_pseudo_bytes(mp->tail, 2);
- }
+ }
else
- return 0;
-
- break;
+ return 0;
+
+ break;
case PICA_PROTO_VERDIFFER:
if (buf[2] > PICA_PROTO_VER_HIGH || (buf[3] > PICA_PROTO_VER_LOW && buf[2] == PICA_PROTO_VER_HIGH))
{
- PICA_warn("make update of node software - peer node has newer protocol version");
+ PICA_warn("make update of node software - peer node has newer protocol version");
}
- else
+ else
{
//peer node has older software version
- PICA_info("peer node has older protocol version");
+ PICA_info("peer node has older protocol version");
}
- return 0;
- break;
+ return 0;
+ break;
}
return 1;
@@ -629,42 +629,42 @@ unsigned int procmsg_NEWNODE(unsigned char* buf, unsigned int size, void* ptr)
switch (buf[0])
{
- case PICA_PROTO_NEWNODE_IPV4:
+ case PICA_PROTO_NEWNODE_IPV4:
PICA_debug1("NEWNODE_IPV4: ip %.16s port %hu\n", inet_ntoa(*(struct in_addr*)(buf + 2)), ntohs(*(in_port_t*)(buf + 6)));
- {
- struct PICA_nodeaddr_ipv4 na_ipv4;
-
+ {
+ struct PICA_nodeaddr_ipv4 na_ipv4;
+
na_ipv4.magick = PICA_PROTO_NEWNODE_IPV4;
na_ipv4.addr = *(in_addr_t*)(buf + 2);
na_ipv4.port = *(in_port_t*)(buf + 6);
-
- if (nodelink_search_by_ipv4addr(na_ipv4.addr, na_ipv4.port)) //connection with this node is already established
- {
- PICA_debug1("disconnecting node %.16s:%hu - connection with this node is already established", inet_ntoa(*(struct in_addr*)&na_ipv4.addr), ntohs(na_ipv4.port));
- return 0;
- }
- if (nodecfg.disable_reserved_addrs && PICA_is_reserved_addr_ipv4(na_ipv4.addr))
- {
- PICA_debug1("disconnecting node %.16s:%hu - private IP ranges are rejected by node configuration",
- inet_ntoa(*(struct in_addr*)&na_ipv4.addr), ntohs(na_ipv4.port)
- );
- return 0;
- }
-
+ if (nodelink_search_by_ipv4addr(na_ipv4.addr, na_ipv4.port)) //connection with this node is already established
+ {
+ PICA_debug1("disconnecting node %.16s:%hu - connection with this node is already established", inet_ntoa(*(struct in_addr*)&na_ipv4.addr), ntohs(na_ipv4.port));
+ return 0;
+ }
+
+ if (nodecfg.disable_reserved_addrs && PICA_is_reserved_addr_ipv4(na_ipv4.addr))
+ {
+ PICA_debug1("disconnecting node %.16s:%hu - private IP ranges are rejected by node configuration",
+ inet_ntoa(*(struct in_addr*)&na_ipv4.addr), ntohs(na_ipv4.port)
+ );
+ return 0;
+ }
+
sprintf(na.addr, "%.16s", inet_ntoa(*(struct in_addr*)&na_ipv4.addr));
- na.port = ntohs(na_ipv4.port);
-
- //int nodelink_attach_nodeaddr(struct nodelink *nl, unsigned int addr_type, void* nodeaddr, unsigned int nodeaddr_size)
+ na.port = ntohs(na_ipv4.port);
+
+ //int nodelink_attach_nodeaddr(struct nodelink *nl, unsigned int addr_type, void* nodeaddr, unsigned int nodeaddr_size)
nodelink_attach_nodeaddr(n, na_ipv4.magick, &na_ipv4, sizeof(struct PICA_nodeaddr_ipv4));
- }
- break;
+ }
+ break;
case PICA_PROTO_NEWNODE_IPV6:
#warning "TO DO"
- break;
+ break;
case PICA_PROTO_NEWNODE_DNS:
#warning "TODO"
- break;
+ break;
}
PICA_nodeaddr_save(nodecfg.nodes_db_file, &na);//CONF filename
@@ -686,17 +686,17 @@ unsigned int procmsg_NODELISTREQ(unsigned char* buf, unsigned int size, void* pt
switch(buf[0])
{
case PICA_PROTO_CLNODELISTREQ:
- c = (struct client *)ptr;
- break;
+ c = (struct client *)ptr;
+ break;
case PICA_PROTO_NODELISTREQ:
- n = (struct nodelink *)ptr;
- break;
+ n = (struct nodelink *)ptr;
+ break;
}
nl_buf = (unsigned char*)malloc(65536);
if (!nl_buf)
- return 0;//ERR
+ return 0;//ERR
{
@@ -711,32 +711,32 @@ unsigned int procmsg_NODELISTREQ(unsigned char* buf, unsigned int size, void* pt
nlp = nodelink_list_head;
while(nlp && nl_size < 65532)//MAP
{
- switch(nlp->addr_type)
+ switch(nlp->addr_type)
{
- case PICA_PROTO_NEWNODE_IPV4:
- if ( PICA_PROTO_NODELISTREQ == buf[0] &&
+ case PICA_PROTO_NEWNODE_IPV4:
+ if ( PICA_PROTO_NODELISTREQ == buf[0] &&
((struct PICA_nodeaddr_ipv4*)nlp->node_addr)->addr == ((struct PICA_nodeaddr_ipv4*)n->node_addr)->addr &&
((struct PICA_nodeaddr_ipv4*)nlp->node_addr)->port == ((struct PICA_nodeaddr_ipv4*)n->node_addr)->port )
- break;//exclude requester's address
-
+ break;//exclude requester's address
+
nl_buf[nl_size] = PICA_PROTO_NEWNODE_IPV4;
*((in_addr_t*)(nl_buf + nl_size + 1)) = ((struct PICA_nodeaddr_ipv4*)nlp->node_addr)->addr;
*((in_port_t*)(nl_buf + nl_size + 5)) = ((struct PICA_nodeaddr_ipv4*)nlp->node_addr)->port;
- nl_size += PICA_PROTO_NODELIST_ITEM_IPV4_SIZE;//CONF
- break;
+ nl_size += PICA_PROTO_NODELIST_ITEM_IPV4_SIZE;//CONF
+ break;
}
-//#warning "set limit on list size, <65532 bytes!!!"
- nlp = nlp->next;
+//#warning "set limit on list size, <65532 bytes!!!"
+ nlp = nlp->next;
}
switch(buf[0])
{
case PICA_PROTO_CLNODELISTREQ:
mp = client_wbuf_push( c, PICA_PROTO_CLNODELIST, nl_size + 4);
- break;
+ break;
case PICA_PROTO_NODELISTREQ:
mp = nodelink_wbuf_push( n, PICA_PROTO_NODELIST, nl_size + 4);
- break;
+ break;
}
if (mp)
@@ -773,17 +773,17 @@ unsigned int procmsg_NODELIST(unsigned char* buf, unsigned int size, void* ptr)
nodelink_attach_nodeaddr(n, na_ipv4.magick, &na_ipv4, sizeof(struct PICA_nodeaddr_ipv4));
listleft -= PICA_PROTO_NODELIST_ITEM_IPV4_SIZE;
- break;
+ break;
}
- continue;
+ continue;
}
- else
+ else
{
- struct PICA_nodeaddr na;
- //char addr[256];
- struct newconn nc;
- struct nodelink *nlp;
- int skip_save = 0;
+ struct PICA_nodeaddr na;
+ //char addr[256];
+ struct newconn nc;
+ struct nodelink *nlp;
+ int skip_save = 0;
memset(na.addr, 0, 256);
memset(&nc, 0, sizeof(struct newconn));
@@ -796,9 +796,9 @@ unsigned int procmsg_NODELIST(unsigned char* buf, unsigned int size, void* ptr)
na_ipv4.port = *(in_port_t*)(buf + size - listleft + 5);
sprintf(na.addr, "%.16s", inet_ntoa(*(struct in_addr*)&na_ipv4.addr));
- na.port = ntohs(na_ipv4.port);
-
- //nodewait_start_connection(&na);
+ na.port = ntohs(na_ipv4.port);
+
+ //nodewait_start_connection(&na);
// if (try_connect_to_node(na.addr,ntohs(na_ipv4.port),&nc))
// if (try_get_reply(&nc))
// {
@@ -807,21 +807,21 @@ unsigned int procmsg_NODELIST(unsigned char* buf, unsigned int size, void* ptr)
// nodelink_attach_nodeaddr(nlp,na_ipv4.magick,&na_ipv4,sizeof(struct PICA_nodeaddr_ipv4));
// PICA_debug1("LINKED NODE:%s\n",inet_ntoa(*(struct in_addr*)&na_ipv4.addr));
// }
-
- PICA_debug3("NODELIST item %.16s:%hu", inet_ntoa(*(struct in_addr*)&na_ipv4.addr), ntohs(na_ipv4.port));
-
- if (nodecfg.disable_reserved_addrs && PICA_is_reserved_addr_ipv4(na_ipv4.addr))
- {
- skip_save = 1;
- PICA_debug1("Received NODELIST item %.16s:%hu is in private range, skipping",
- inet_ntoa(*(struct in_addr*)&na_ipv4.addr), ntohs(na_ipv4.port)
- );
- }
+
+ PICA_debug3("NODELIST item %.16s:%hu", inet_ntoa(*(struct in_addr*)&na_ipv4.addr), ntohs(na_ipv4.port));
+
+ if (nodecfg.disable_reserved_addrs && PICA_is_reserved_addr_ipv4(na_ipv4.addr))
+ {
+ skip_save = 1;
+ PICA_debug1("Received NODELIST item %.16s:%hu is in private range, skipping",
+ inet_ntoa(*(struct in_addr*)&na_ipv4.addr), ntohs(na_ipv4.port)
+ );
+ }
listleft -= PICA_PROTO_NODELIST_ITEM_IPV4_SIZE;
- break;
+ break;
}
- if (!skip_save)
- PICA_nodeaddr_save(nodecfg.nodes_db_file, &na);//CONF filename
+ if (!skip_save)
+ PICA_nodeaddr_save(nodecfg.nodes_db_file, &na);//CONF filename
}
}
@@ -842,10 +842,10 @@ unsigned int procmsg_N2NFOUND(unsigned char* buf, unsigned int size, void* ptr)
cclink_attach_remotecle_node(cc, n);
if((mp = nodelink_wbuf_push(n, PICA_PROTO_N2NCONNREQOUTG, PICA_PROTO_N2NCONNREQOUTG_SIZE)))
{
- memcpy(mp->tail, cc->caller_id, PICA_ID_SIZE);
- memcpy(mp->tail + PICA_ID_SIZE, callee_id, PICA_ID_SIZE);
-
- }
+ memcpy(mp->tail, cc->caller_id, PICA_ID_SIZE);
+ memcpy(mp->tail + PICA_ID_SIZE, callee_id, PICA_ID_SIZE);
+
+ }
}
return 1;
}
@@ -863,7 +863,7 @@ unsigned int procmsg_SEARCH(unsigned char* buf, unsigned int size, void* ptr)
{
if ((mp = nodelink_wbuf_push(n, PICA_PROTO_N2NFOUND, PICA_PROTO_N2NFOUND_SIZE)))
{
- memcpy(mp->tail, callee_id, PICA_ID_SIZE);
+ memcpy(mp->tail, callee_id, PICA_ID_SIZE);
}
}
return 1;
@@ -885,16 +885,16 @@ unsigned int procmsg_N2NCONNREQOUTG(unsigned char* buf, unsigned int size, void*
{
if ((mp = client_wbuf_push(callee, PICA_PROTO_CONNREQINC, PICA_PROTO_CONNREQINC_SIZE)))
{
- memcpy(mp->tail, caller_id, PICA_ID_SIZE);
- cclink_list_addn2ncle(caller_id, n, callee);
+ memcpy(mp->tail, caller_id, PICA_ID_SIZE);
+ cclink_list_addn2ncle(caller_id, n, callee);
}
}
else
{
if ((mp = nodelink_wbuf_push(n, PICA_PROTO_N2NNOTFOUND, PICA_PROTO_N2NNOTFOUND_SIZE)))
{
- memcpy(mp->tail, caller_id, PICA_ID_SIZE);
- memcpy(mp->tail + PICA_ID_SIZE, callee_id, PICA_ID_SIZE);
+ memcpy(mp->tail, caller_id, PICA_ID_SIZE);
+ memcpy(mp->tail + PICA_ID_SIZE, callee_id, PICA_ID_SIZE);
}
}
return 1;
@@ -918,8 +918,8 @@ unsigned int procmsg_N2NALLOW(unsigned char* buf, unsigned int size, void* ptr)
{
if ((mp = client_wbuf_push(cc->p1, PICA_PROTO_FOUND, PICA_PROTO_FOUND_SIZE)))
{
- memcpy(mp->tail, callee_id, PICA_ID_SIZE);
- cclink_setwaitconn(cc);
+ memcpy(mp->tail, callee_id, PICA_ID_SIZE);
+ cclink_setwaitconn(cc);
}
}
return 1;
@@ -943,9 +943,9 @@ unsigned int procmsg_N2NNOTFOUND(unsigned char* buf, unsigned int size, void* pt
{
if ((mp = client_wbuf_push(cc->p1, PICA_PROTO_NOTFOUND, PICA_PROTO_NOTFOUND_SIZE)))
{
- memcpy(mp->tail, callee_id, PICA_ID_SIZE);
+ memcpy(mp->tail, callee_id, PICA_ID_SIZE);
}
- cclink_list_delete(cc);
+ cclink_list_delete(cc);
}
return 1;
@@ -966,7 +966,7 @@ unsigned int procmsg_N2NMSG(unsigned char* buf, unsigned int size, void* ptr)
receiver_id = buf + 4 + PICA_ID_SIZE;
if (len < 2 * PICA_ID_SIZE)
- return 0;
+ return 0;
datalen = len - 2 * PICA_ID_SIZE;
@@ -974,36 +974,36 @@ unsigned int procmsg_N2NMSG(unsigned char* buf, unsigned int size, void* ptr)
if (cc && cc->state == PICA_CCLINK_N2NCLE_ACTIVE)
{
- if (datalen + cc->bufpos_p1p2 > cc->buflen_p1p2)
+ if (datalen + cc->bufpos_p1p2 > cc->buflen_p1p2)
{
- cclink_list_delete(cc);//CLOSING CCLINK DUE TO BUFER OVERRUN --------- FIXME FIX FIX FIX
- return 1;
+ cclink_list_delete(cc);//CLOSING CCLINK DUE TO BUFER OVERRUN --------- FIXME FIX FIX FIX
+ return 1;
}
- memcpy(cc->buf_p1p2 + cc->bufpos_p1p2, buf + 4 + 2 * PICA_ID_SIZE, datalen);
- cc->bufpos_p1p2 += datalen;
- return 1;
+ memcpy(cc->buf_p1p2 + cc->bufpos_p1p2, buf + 4 + 2 * PICA_ID_SIZE, datalen);
+ cc->bufpos_p1p2 += datalen;
+ return 1;
}
///////////////
cc = cclink_list_search(receiver_id, sender_id);
if (cc && cc->state == PICA_CCLINK_N2NCLR_ACTIVE)
{
- if (datalen + cc->bufpos_p2p1 > cc->buflen_p2p1)
+ if (datalen + cc->bufpos_p2p1 > cc->buflen_p2p1)
{
- cclink_list_delete(cc);//CLOSING CCLINK DUE TO BUFER OVERRUN --------- FIXME FIX FIX FIX
- return 1;
+ cclink_list_delete(cc);//CLOSING CCLINK DUE TO BUFER OVERRUN --------- FIXME FIX FIX FIX
+ return 1;
}
memcpy(cc->buf_p2p1 + cc->bufpos_p2p1, buf + 4 + 2 * PICA_ID_SIZE, datalen);
- cc->bufpos_p2p1 += datalen;
- return 1;
+ cc->bufpos_p2p1 += datalen;
+ return 1;
}
if ((mp = nodelink_wbuf_push(n, PICA_PROTO_N2NNOTFOUND, PICA_PROTO_N2NNOTFOUND_SIZE)))
{
- memcpy(mp->tail, sender_id, PICA_ID_SIZE);
- memcpy(mp->tail + PICA_ID_SIZE, receiver_id, PICA_ID_SIZE);
+ memcpy(mp->tail, sender_id, PICA_ID_SIZE);
+ memcpy(mp->tail + PICA_ID_SIZE, receiver_id, PICA_ID_SIZE);
}
return 1;
@@ -1016,9 +1016,9 @@ struct cclink* cclink_list_findwaitsearch(const unsigned char *callee_id)
c = cclink_list_head;
while(c)
{
- if (memcmp(c->callee_id, callee_id, PICA_ID_SIZE) == 0
+ if (memcmp(c->callee_id, callee_id, PICA_ID_SIZE) == 0
&& c->state == PICA_CCLINK_N2NCLR_WAITSEARCH)
- return c;
+ return c;
c = c->next;
}
return 0;
@@ -1031,18 +1031,18 @@ struct cclink* cclink_list_search(const unsigned char *caller_id, const unsigned
while(c)
{
- if (memcmp(c->caller_id, caller_id, PICA_ID_SIZE) == 0
- && memcmp(c->callee_id, callee_id, PICA_ID_SIZE) == 0)
- return c;
+ if (memcmp(c->caller_id, caller_id, PICA_ID_SIZE) == 0
+ && memcmp(c->callee_id, callee_id, PICA_ID_SIZE) == 0)
+ return c;
c = c->next;
}
return 0;
}
-void cclink_list_delete(struct cclink *l)
+void cclink_list_delete(struct cclink *l)
{
PICA_debug1("cclink_list_delete(%p)", (void*)l);
-//удаление из глобального списка
+//удаление из глобального списка
if (l->prev)
l->prev->next = l->next;
else
@@ -1055,33 +1055,33 @@ void cclink_list_delete(struct cclink *l)
if (l->p1)
{
- if (l->sck_p1)
+ if (l->sck_p1)
{
- SHUTDOWN(l->sck_p1);
- CLOSE(l->sck_p1);
- PICA_debug2("closed socket %i", l->sck_p1);
+ SHUTDOWN(l->sck_p1);
+ CLOSE(l->sck_p1);
+ PICA_debug2("closed socket %i", l->sck_p1);
}
}//caller_id is stored in p1 structure
else
- free(l->caller_id);//caller_id was allocated by malloc
+ free(l->caller_id);//caller_id was allocated by malloc
if (l->p2)
{
- if (l->sck_p2)
+ if (l->sck_p2)
{
- SHUTDOWN(l->sck_p2);
- CLOSE(l->sck_p2);
- PICA_debug2("closed socket %i", l->sck_p2);
+ SHUTDOWN(l->sck_p2);
+ CLOSE(l->sck_p2);
+ PICA_debug2("closed socket %i", l->sck_p2);
}
}
else
- free(l->callee_id);
+ free(l->callee_id);
if (l->buf_p1p2)
- free(l->buf_p1p2);
+ free(l->buf_p1p2);
if (l->buf_p2p1)
- free(l->buf_p2p1);
+ free(l->buf_p2p1);
free(l);
cclink_list_count--;
@@ -1094,15 +1094,15 @@ void cclink_list_delete_by_client(struct client *cl)
while(l)
{
- if (l->p1 == cl || l->p2 == cl)
- kill_ptr = l;
-
- l = l->next;
+ if (l->p1 == cl || l->p2 == cl)
+ kill_ptr = l;
+
+ l = l->next;
- if (kill_ptr)
+ if (kill_ptr)
{
- cclink_list_delete(kill_ptr);
- kill_ptr = 0;
+ cclink_list_delete(kill_ptr);
+ kill_ptr = 0;
}
}
@@ -1116,15 +1116,15 @@ void cclink_list_delete_by_nodelink(struct nodelink *node)
while(l)
{
- if (l->caller_node == node || l->callee_node == node)
- kill_ptr = l;
-
- l = l->next;
+ if (l->caller_node == node || l->callee_node == node)
+ kill_ptr = l;
+
+ l = l->next;
- if (kill_ptr)
+ if (kill_ptr)
{
- cclink_list_delete(kill_ptr);
- kill_ptr = 0;
+ cclink_list_delete(kill_ptr);
+ kill_ptr = 0;
}
}
}
@@ -1140,7 +1140,7 @@ struct cclink* cclink_list_add(struct client *clr, struct client *cle)
l = (struct cclink*)calloc(sizeof(struct cclink), 1);
if (!l)
- return 0;
+ return 0;
//l->state=PICA_LINKSTATE_WAITREP;
@@ -1178,8 +1178,8 @@ void cclink_list_addlocal(struct client *clr, struct client *cle)
if (l)
{
l->state = PICA_CCLINK_LOCAL_WAITREP;
- l->caller_id = l->p1->id;
- l->callee_id = l->p2->id;
+ l->caller_id = l->p1->id;
+ l->callee_id = l->p2->id;
}
}
@@ -1193,13 +1193,13 @@ void cclink_list_addn2nclr(struct client *clr, const unsigned char *callee_id)
if (l)
{
l->state = PICA_CCLINK_N2NCLR_WAITSEARCH;
- l->caller_id = l->p1->id;
- l->callee_id = (unsigned char*)malloc(PICA_ID_SIZE);
+ l->caller_id = l->p1->id;
+ l->callee_id = (unsigned char*)malloc(PICA_ID_SIZE);
- if (l->callee_id == NULL)
- PICA_fatal("memory allocation failed");
+ if (l->callee_id == NULL)
+ PICA_fatal("memory allocation failed");
- memcpy(l->callee_id, callee_id, PICA_ID_SIZE);
+ memcpy(l->callee_id, callee_id, PICA_ID_SIZE);
}
}
@@ -1221,14 +1221,14 @@ void cclink_list_addn2ncle(const unsigned char *caller_id, struct nodelink *call
if (l)
{
l->state = PICA_CCLINK_N2NCLE_WAITREP;
- l->caller_id = (unsigned char*)malloc(PICA_ID_SIZE);
+ l->caller_id = (unsigned char*)malloc(PICA_ID_SIZE);
- if (l->caller_id == NULL)
- PICA_fatal("memory allocation failed");
+ if (l->caller_id == NULL)
+ PICA_fatal("memory allocation failed");
- memcpy(l->caller_id, caller_id, PICA_ID_SIZE);
- l->callee_id = l->p2->id;
- l->caller_node = caller_node;
+ memcpy(l->caller_id, caller_id, PICA_ID_SIZE);
+ l->callee_id = l->p2->id;
+ l->caller_node = caller_node;
}
}
@@ -1239,16 +1239,16 @@ void cclink_setwaitconn(struct cclink *ccl)
{
case PICA_CCLINK_LOCAL_WAITREP:
ccl->state = PICA_CCLINK_LOCAL_WAITCONNCLE;
- //
- break;
+ //
+ break;
case PICA_CCLINK_N2NCLR_WAITREP:
ccl->state = PICA_CCLINK_N2NCLR_WAITCONNCLR;
- break;
+ break;
case PICA_CCLINK_N2NCLE_WAITREP:
ccl->state = PICA_CCLINK_N2NCLE_WAITCONNCLE;
- break;
+ break;
default:
- ;
+ ;
}
}
@@ -1258,11 +1258,11 @@ int cclink_allocbufs(struct cclink *ccl)
ccl->buf_p2p1 = malloc(DEFAULT_BUF_SIZE);
if (!ccl->buf_p1p2 || !ccl->buf_p2p1)
{
- if (ccl->buf_p1p2)
- free(ccl->buf_p1p2);
- if (ccl->buf_p2p1)
- free(ccl->buf_p2p1);
- return 0;
+ if (ccl->buf_p1p2)
+ free(ccl->buf_p1p2);
+ if (ccl->buf_p2p1)
+ free(ccl->buf_p2p1);
+ return 0;
}
ccl->buflen_p1p2 = DEFAULT_BUF_SIZE;
ccl->buflen_p2p1 = DEFAULT_BUF_SIZE;
@@ -1274,36 +1274,36 @@ void cclink_activate(struct cclink *ccl, SOCKET s)
switch(ccl->state)
{
case PICA_CCLINK_LOCAL_WAITCONNCLE:
- ccl->sck_p2 = s;
- ccl->state = PICA_CCLINK_LOCAL_WAITCONNCLR;
- break;
+ ccl->sck_p2 = s;
+ ccl->state = PICA_CCLINK_LOCAL_WAITCONNCLR;
+ break;
case PICA_CCLINK_LOCAL_WAITCONNCLR:
- ccl->sck_p1 = s;
- if (!cclink_allocbufs(ccl))
+ ccl->sck_p1 = s;
+ if (!cclink_allocbufs(ccl))
{
- cclink_list_delete(ccl);
- return;
+ cclink_list_delete(ccl);
+ return;
}
- ccl->state = PICA_CCLINK_LOCAL_ACTIVE;
- break;
+ ccl->state = PICA_CCLINK_LOCAL_ACTIVE;
+ break;
case PICA_CCLINK_N2NCLR_WAITCONNCLR:
- ccl->sck_p1 = s;
- if (!cclink_allocbufs(ccl))
+ ccl->sck_p1 = s;
+ if (!cclink_allocbufs(ccl))
{
- cclink_list_delete(ccl);
- return;
+ cclink_list_delete(ccl);
+ return;
}
- ccl->state = PICA_CCLINK_N2NCLR_ACTIVE;
- break;
+ ccl->state = PICA_CCLINK_N2NCLR_ACTIVE;
+ break;
case PICA_CCLINK_N2NCLE_WAITCONNCLE:
- ccl->sck_p2 = s;
- if (!cclink_allocbufs(ccl))
+ ccl->sck_p2 = s;
+ if (!cclink_allocbufs(ccl))
{
- cclink_list_delete(ccl);
- return;
+ cclink_list_delete(ccl);
+ return;
}
- ccl->state = PICA_CCLINK_N2NCLE_ACTIVE;
- break;
+ ccl->state = PICA_CCLINK_N2NCLE_ACTIVE;
+ break;
}
}
@@ -1327,12 +1327,12 @@ int PICA_node_init()
listen_comm_sck = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listen_comm_sck == -1)
- PICA_fatal("unable to get socket - %s", strerror(errno));
+ PICA_fatal("unable to get socket - %s", strerror(errno));
flag = 1; //enable SO_REUSEADDR
if (0 != setsockopt(listen_comm_sck, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag)))
{
- PICA_error("failed to set SO_REUSEADDR on socket: %s", strerror(errno));
+ PICA_error("failed to set SO_REUSEADDR on socket: %s", strerror(errno));
}
memset(&sd, 0, sizeof(sd));
@@ -1344,12 +1344,12 @@ int PICA_node_init()
ret = bind(listen_comm_sck, (struct sockaddr*)&sd, sizeof(sd));
if (ret == -1)
- PICA_fatal("unable to bind socket - %s", strerror(errno));
+ PICA_fatal("unable to bind socket - %s", strerror(errno));
ret = listen(listen_comm_sck, 20);
if (ret == -1)
- PICA_fatal("unable to listen socket - %s", strerror(errno));
+ PICA_fatal("unable to listen socket - %s", strerror(errno));
{
int ret_comm;
@@ -1364,23 +1364,23 @@ int PICA_node_init()
// ret_data=ioctl(listen_node_sck,FIONBIO,(int*)&arg);
#endif
if (ret_comm == -1)
- PICA_fatal("unable to set non-blocking mode on socket - %s", strerror(errno));
+ PICA_fatal("unable to set non-blocking mode on socket - %s", strerror(errno));
}
-//#ifdef NO_RAND_DEV
+//#ifdef NO_RAND_DEV
//PICA_rand_seed();
//#endif
ctx = SSL_CTX_new(TLSv1_2_method());
if (!ctx)
- PICA_fatal("unable to create SSL_CTX object");
+ PICA_fatal("unable to create SSL_CTX object");
ret = SSL_CTX_load_verify_locations(ctx, nodecfg.CA_cert_file, 0);
if (!ret)
- PICA_fatal("call to SSL_CTX_load_verify_locations failed(). Check if %s exists and is accesible", nodecfg.CA_cert_file);
+ PICA_fatal("call to SSL_CTX_load_verify_locations failed(). Check if %s exists and is accesible", nodecfg.CA_cert_file);
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, verify_callback);
@@ -1436,7 +1436,7 @@ struct newconn* newconn_add(struct newconn *ncs, int *pos)
int min_pos = 0;
if (*pos < MAX_NEWCONNS && !ncs[*pos].sck)
{
- goto ret;
+ goto ret;
}
else
{
@@ -1449,15 +1449,15 @@ struct newconn* newconn_add(struct newconn *ncs, int *pos)
min = ncs[*pos].tmst;
min_pos = *pos;
}
- (*pos)++;
+ (*pos)++;
}
if ( (*pos) == MAX_NEWCONNS)
{
*pos = min_pos;
- SHUTDOWN(ncs[min_pos].sck);
- CLOSE(ncs[min_pos].sck);
- PICA_debug2("closed socket %i", ncs[min_pos].sck);
+ SHUTDOWN(ncs[min_pos].sck);
+ CLOSE(ncs[min_pos].sck);
+ PICA_debug2("closed socket %i", ncs[min_pos].sck);
}
}
@@ -1479,40 +1479,40 @@ int client_tree_add(struct client *ci)
if (client_tree_root)
{
i = client_tree_root;
-
- do
+
+ do
{
int cmp;
cmp = memcmp(ci->id, i->id, PICA_ID_SIZE);
if (cmp == 0)
- return 0;
+ return 0;
if (cmp < 0) // ci->id < i->id
{
- if (i->left)
+ if (i->left)
i = i->left;
- else
+ else
{
i->left = ci;
ci->up = i;
- return 1;
+ return 1;
}
}
- else
+ else
{
- if (i->right)
+ if (i->right)
i = i->right;
- else
+ else
{
i->right = ci;
ci->up = i;
- return 1;
+ return 1;
}
}
}
- while(1);
+ while(1);
}
else
client_tree_root = ci;
@@ -1532,11 +1532,11 @@ struct client* client_tree_search(const unsigned char *id)
int cmp = memcmp(id, i_ptr->id, PICA_ID_SIZE);
if (cmp == 0)
- return i_ptr;
+ return i_ptr;
if (cmp < 0) //id < i_ptr->id
i_ptr = i_ptr->left;
- else
+ else
i_ptr = i_ptr->right;
}
@@ -1548,65 +1548,65 @@ void client_tree_print(struct client *c)
{
if (!c)
{
- puts("NULL");
- return;
+ puts("NULL");
+ return;
}
printf("%p: %u LEFT: %p, RIGHT: %p\n", (void*)c, c->id, (void*)c->left, (void*)c->right);
if (c->left)
- client_tree_print(c->left);
+ client_tree_print(c->left);
if (c->right)
- client_tree_print(c->right);
+ client_tree_print(c->right);
}
-//удаление структуры из дерева
+//удаление структуры из дерева
void client_tree_remove(struct client* ci)
{
struct client** p_link;//указывает на left или right в родительском узле
if (!ci->up)
{
- p_link = &client_tree_root;
+ p_link = &client_tree_root;
}
else
{
if (ci == ci->up->left)
p_link = &(ci->up->left);
- else
+ else
p_link = &(ci->up->right);
}
-
-
+
+
if (!ci->left && !ci->right)
{
*p_link = 0;
- return;
+ return;
}
if (ci->left && !ci->right)
{
ci->left->up = ci->up;
*p_link = ci->left;
- return;
+ return;
}
if (!ci->left && ci->right)
{
ci->right->up = ci->up;
*p_link = ci->right;
- return;
+ return;
}
{
- struct client *lm;
+ struct client *lm;
lm = ci->right;
while(lm->left) lm = lm->left; //поиск самого левого узла правого поддерева
if (lm != ci->right)
- {
+ {
lm->up->left = lm->right;
lm->right = ci->right;
}
@@ -1628,8 +1628,8 @@ struct client *client_list_addnew(struct newconn *nc)
if (!ci->ssl_comm)
{
- free(ci);
- return 0;
+ free(ci);
+ return 0;
}
if (client_list_end)
@@ -1653,8 +1653,8 @@ struct client *client_list_addnew(struct newconn *nc)
ci->r_buf = calloc(1, DEFAULT_BUF_SIZE);
if (!ci->r_buf)
{
- free(ci);
- return 0;
+ free(ci);
+ return 0;
}
ci->buflen_r = DEFAULT_BUF_SIZE;
@@ -1681,17 +1681,17 @@ void client_list_delete(struct client* ci)
//удаление из дерева
if (client_tree_search(ci->id) == ci)
{
- client_tree_remove(ci);
- client_tree_print(client_tree_root);
+ client_tree_remove(ci);
+ client_tree_print(client_tree_root);
}
cclink_list_delete_by_client(ci);
if (ci->r_buf)
- free(ci->r_buf);
+ free(ci->r_buf);
if (ci->w_buf)
- free(ci->w_buf);
+ free(ci->w_buf);
CLOSE(ci->sck_comm);
PICA_debug2("closed socket %i", ci->sck_comm);
@@ -1705,28 +1705,28 @@ struct PICA_proto_msg* client_wbuf_push
if (!c->w_buf)
{
c->w_buf = calloc(1, DEFAULT_BUF_SIZE + (size / DEFAULT_BUF_SIZE) * DEFAULT_BUF_SIZE );
- if (!c->w_buf)
+ if (!c->w_buf)
{
- PICA_error("calloc() failed. Out of memory");
- return 0;
+ PICA_error("calloc() failed. Out of memory");
+ return 0;
}
c->buflen_w = DEFAULT_BUF_SIZE + (size / DEFAULT_BUF_SIZE) * DEFAULT_BUF_SIZE;
}
if ((c->buflen_w - c->w_pos) < size)
{
- unsigned char *p;
+ unsigned char *p;
p = realloc(c->w_buf, size + c->w_pos);
- if (p)
+ if (p)
{
c->w_buf = p;
c->buflen_w = size + c->w_pos;
}
- else
- return 0;
+ else
+ return 0;
}
-
+
struct PICA_proto_msg *mp = (struct PICA_proto_msg *)(c->w_buf + c->w_pos);
mp->head[0] = mp->head[1] = msgid;
c->w_pos += size;
@@ -1741,8 +1741,8 @@ int client_rbuf_grow(struct client *c)
if (!p)
{
- PICA_error("realloc() failed");
- return 0;
+ PICA_error("realloc() failed");
+ return 0;
}
c->r_buf = p;
c->buflen_r += DEFAULT_BUF_SIZE;
@@ -1757,7 +1757,7 @@ struct nodelink *nodelink_list_addnew(struct newconn *nc)
nl = (struct nodelink*)calloc(1, sizeof(struct nodelink));
if (!nl)
- return 0;
+ return 0;
if (nodelink_list_end)
{
@@ -1777,8 +1777,8 @@ struct nodelink *nodelink_list_addnew(struct newconn *nc)
nl->r_buf = calloc(1, DEFAULT_BUF_SIZE);
if (!nl->r_buf)
{
- free(nl);
- return 0;
+ free(nl);
+ return 0;
}
nl->buflen_r = DEFAULT_BUF_SIZE;
@@ -1791,15 +1791,15 @@ struct nodelink *nodelink_list_addnew(struct newconn *nc)
void nodelink_list_delete(struct nodelink *n)
{
PICA_debug1("nodelink_list_delete(%p)", (void*)n);
-
+
if (n->r_buf)
- free(n->r_buf);
+ free(n->r_buf);
if (n->w_buf)
- free(n->w_buf);
+ free(n->w_buf);
if (n->node_addr)
- free(n->node_addr);
+ free(n->node_addr);
CLOSE(n->sck);
PICA_debug2("closed socket %i", n->sck);
@@ -1824,16 +1824,16 @@ int nodelink_attach_nodeaddr(struct nodelink *nl, unsigned int addr_type, void*
{
if (nl && nodeaddr)
{
- if (nl->node_addr)
- free(nl->node_addr);
-
+ if (nl->node_addr)
+ free(nl->node_addr);
+
nl->node_addr = malloc(nodeaddr_size);
- if (!nl->node_addr)
- return 0;//ERR_CHECK
+ if (!nl->node_addr)
+ return 0;//ERR_CHECK
memcpy(nl->node_addr, nodeaddr, nodeaddr_size);
nl->addr_type = addr_type;
- return 1;
+ return 1;
}
return 0;
}
@@ -1846,8 +1846,8 @@ int nodelink_rbuf_grow(struct nodelink *nl)
if (!p)
{
- PICA_error("realloc() failed");
- return 0;
+ PICA_error("realloc() failed");
+ return 0;
}
nl->r_buf = p;
nl->buflen_r += DEFAULT_BUF_SIZE;
@@ -1859,32 +1859,32 @@ struct PICA_proto_msg* nodelink_wbuf_push
(struct nodelink *nl, unsigned int msgid, unsigned int size)
{
struct PICA_proto_msg *mp;
-
+
if (!nl->w_buf)
{
nl->w_buf = calloc(1, DEFAULT_BUF_SIZE );
- if (!nl->w_buf)
+ if (!nl->w_buf)
{
- PICA_error("calloc() failed. Out of memory");
- return 0;
+ PICA_error("calloc() failed. Out of memory");
+ return 0;
}
nl->buflen_w = DEFAULT_BUF_SIZE;
}
if ((nl->buflen_w - nl->w_pos) < size)
{
- unsigned char *p;
+ unsigned char *p;
p = realloc(nl->w_buf, size + nl->w_pos);
- if (p)
+ if (p)
{
nl->w_buf = p;
nl->buflen_w = size + nl->w_pos;
}
- else
- return 0;
+ else
+ return 0;
}
-
+
mp = (struct PICA_proto_msg *)(nl->w_buf + nl->w_pos);
mp->head[0] = mp->head[1] = msgid;
nl->w_pos += size;
@@ -1898,15 +1898,15 @@ struct nodelink *nodelink_search_by_ipv4addr(in_addr_t ip, in_port_t port)
nl = nodelink_list_head;
while(nl && !(
- (nl->addr.sin_addr.s_addr == ip && nl->addr.sin_port == port) ||
- (nl->node_addr && nl->addr_type == PICA_PROTO_NEWNODE_IPV4 &&
- ((struct PICA_nodeaddr_ipv4*)nl->node_addr) ->addr == ip &&
- ((struct PICA_nodeaddr_ipv4*)nl->node_addr) ->port == port
- )
- )
- )
+ (nl->addr.sin_addr.s_addr == ip && nl->addr.sin_port == port) ||
+ (nl->node_addr && nl->addr_type == PICA_PROTO_NEWNODE_IPV4 &&
+ ((struct PICA_nodeaddr_ipv4*)nl->node_addr) ->addr == ip &&
+ ((struct PICA_nodeaddr_ipv4*)nl->node_addr) ->port == port
+ )
+ )
+ )
{
- nl = nl->next;
+ nl = nl->next;
}
return nl;
@@ -1923,7 +1923,7 @@ void process_timeouts_newconn()
for (i = 0; i < MAX_NEWCONNS; i++)
{
- if (newconns[i].sck)
+ if (newconns[i].sck)
{
if (newconns[i].tmst < t)
{
@@ -1948,23 +1948,23 @@ void process_timeouts_c2c()
while(il)
{
- switch(il->state)
+ switch(il->state)
{
- case PICA_CCLINK_LOCAL_ACTIVE:
+ case PICA_CCLINK_LOCAL_ACTIVE:
case PICA_CCLINK_N2NCLR_ACTIVE:
case PICA_CCLINK_N2NCLE_ACTIVE:
- //idle timeout (>=60sec), update timestamp at process_c2c
+ //idle timeout (>=60sec), update timestamp at process_c2c
- break;
+ break;
default:
if ((time(0) - il->tmst) > TMO_CCLINK_WAITACTIVE)
{
- struct cclink *dl;
+ struct cclink *dl;
dl = il;
il = il->next;
- cclink_list_delete(dl);
- continue;
+ cclink_list_delete(dl);
+ continue;
}
}
il = il->next;
@@ -1983,48 +1983,48 @@ void process_timeouts_c2n()
while(i_ptr)
{
- if (i_ptr->disconnect_ticking)
+ if (i_ptr->disconnect_ticking)
{
- if (cur_time >= i_ptr->tmst)
+ if (cur_time >= i_ptr->tmst)
{
- if ((cur_time - i_ptr->tmst) > NOREPLY_TIMEOUT)
- kill_ptr = i_ptr;
+ if ((cur_time - i_ptr->tmst) > NOREPLY_TIMEOUT)
+ kill_ptr = i_ptr;
}
- else
+ else
{
//2038 year has come, and this code is still working somewhere with 32bit Unix timestamps :)
- if ((i_ptr->tmst - cur_time ) > NOREPLY_TIMEOUT)
- kill_ptr = i_ptr;
+ if ((i_ptr->tmst - cur_time ) > NOREPLY_TIMEOUT)
+ kill_ptr = i_ptr;
}
}
- else
+ else
{
- if (cur_time >= i_ptr->tmst)
+ if (cur_time >= i_ptr->tmst)
{
- if ((cur_time - i_ptr->tmst) > KEEPALIVE_TIMEOUT)
+ if ((cur_time - i_ptr->tmst) > KEEPALIVE_TIMEOUT)
{
- struct PICA_proto_msg *mp;
-
- if ((mp = client_wbuf_push(i_ptr, PICA_PROTO_PINGREQ, PICA_PROTO_PINGREQ_SIZE)))
+ struct PICA_proto_msg *mp;
+
+ if ((mp = client_wbuf_push(i_ptr, PICA_PROTO_PINGREQ, PICA_PROTO_PINGREQ_SIZE)))
{
- PICA_debug3("sending PINGREQ to %p", i_ptr);
+ PICA_debug3("sending PINGREQ to %p", i_ptr);
RAND_pseudo_bytes(mp->tail, 2);
-
- i_ptr->tmst = time(0);
- i_ptr->disconnect_ticking = 1;
+
+ i_ptr->tmst = time(0);
+ i_ptr->disconnect_ticking = 1;
}
- else
- kill_ptr = i_ptr;
+ else
+ kill_ptr = i_ptr;
}
}
}
-
- i_ptr = i_ptr->next;
- if (kill_ptr)
+ i_ptr = i_ptr->next;
+
+ if (kill_ptr)
{
- PICA_info("Disconnecting user %u due to noreply timeout", kill_ptr -> id);
- client_list_delete(kill_ptr);
+ PICA_info("Disconnecting user %u due to noreply timeout", kill_ptr -> id);
+ client_list_delete(kill_ptr);
kill_ptr = 0;
}
}
@@ -2042,48 +2042,48 @@ void process_timeouts_n2n()
while(i_ptr)
{
- if (i_ptr->disconnect_ticking)
+ if (i_ptr->disconnect_ticking)
{
- if (cur_time >= i_ptr->tmst)
+ if (cur_time >= i_ptr->tmst)
{
- if ((cur_time - i_ptr->tmst) > NOREPLY_TIMEOUT)
- kill_ptr = i_ptr;
+ if ((cur_time - i_ptr->tmst) > NOREPLY_TIMEOUT)
+ kill_ptr = i_ptr;
}
- else
+ else
{
//2038 year has come, and this code is still working somewhere with 32bit Unix timestamps :)
- if ((i_ptr->tmst - cur_time ) > NOREPLY_TIMEOUT)
- kill_ptr = i_ptr;
+ if ((i_ptr->tmst - cur_time ) > NOREPLY_TIMEOUT)
+ kill_ptr = i_ptr;
}
}
- else
+ else
{
- if (cur_time >= i_ptr->tmst)
+ if (cur_time >= i_ptr->tmst)
{
- if ((cur_time - i_ptr->tmst) > KEEPALIVE_TIMEOUT)
+ if ((cur_time - i_ptr->tmst) > KEEPALIVE_TIMEOUT)
{
- struct PICA_proto_msg *mp;
-
- if ((mp = nodelink_wbuf_push(i_ptr, PICA_PROTO_PINGREQ, PICA_PROTO_PINGREQ_SIZE)))
+ struct PICA_proto_msg *mp;
+
+ if ((mp = nodelink_wbuf_push(i_ptr, PICA_PROTO_PINGREQ, PICA_PROTO_PINGREQ_SIZE)))
{
- PICA_debug3("sending PINGREQ to node %p", i_ptr);
+ PICA_debug3("sending PINGREQ to node %p", i_ptr);
RAND_pseudo_bytes(mp->tail, 2);
-
- i_ptr->tmst = time(0);
- i_ptr->disconnect_ticking = 1;
+
+ i_ptr->tmst = time(0);
+ i_ptr->disconnect_ticking = 1;
}
- else
- kill_ptr = i_ptr;
+ else
+ kill_ptr = i_ptr;
}
}
}
-
- i_ptr = i_ptr->next;
- if (kill_ptr)
+ i_ptr = i_ptr->next;
+
+ if (kill_ptr)
{
- PICA_info("Disconnecting node %p due to noreply timeout", kill_ptr);
- nodelink_list_delete(kill_ptr);
+ PICA_info("Disconnecting node %p due to noreply timeout", kill_ptr);
+ nodelink_list_delete(kill_ptr);
kill_ptr = 0;
}
}
@@ -2098,8 +2098,8 @@ int process_timeouts()
if (time(0) - skynet_refresh_tmst > SKYNET_REFRESH_TIMEOUT && !nodewait_list)
{
- PICA_debug3("refreshing nodelist database");
- PICA_node_joinskynet(nodecfg.nodes_db_file, nodecfg.announced_addr);
+ PICA_debug3("refreshing nodelist database");
+ PICA_node_joinskynet(nodecfg.nodes_db_file, nodecfg.announced_addr);
}
return 1;
}
@@ -2122,7 +2122,7 @@ void newconn_set_fds(fd_set *readfds, int *nfds)
int i;
for (i = 0; i < MAX_NEWCONNS; i++)
- if (newconns[i].sck)
+ if (newconns[i].sck)
set_select_fd(newconns[i].sck, readfds, nfds);
}
@@ -2148,7 +2148,7 @@ void c2c_set_fds(fd_set *readfds, int *nfds)
{
if ( !cc->jam_p1p2 && (cc->state == PICA_CCLINK_LOCAL_ACTIVE || cc->state == PICA_CCLINK_N2NCLR_ACTIVE) )
set_select_fd(cc->sck_p1, readfds, nfds);
-
+
if ( !cc->jam_p2p1 && (cc->state == PICA_CCLINK_LOCAL_ACTIVE || cc->state == PICA_CCLINK_N2NCLE_ACTIVE) )
set_select_fd(cc->sck_p2, readfds, nfds);
@@ -2178,17 +2178,17 @@ void process_listen_read(fd_set *readfds)
{
s = accept(listen_comm_sck, (struct sockaddr*)&addr, &addrsize);
- if (s >= 0)
+ if (s >= 0)
{
nc = newconn_add(newconns, &newconns_pos);
-
- nc->sck = s;
- nc->addr = addr;
- PICA_debug1("accepted connection from %.16s, new socket %i", inet_ntoa(addr.sin_addr), s);//IPv6
+
+ nc->sck = s;
+ nc->addr = addr;
+ PICA_debug1("accepted connection from %.16s, new socket %i", inet_ntoa(addr.sin_addr), s);//IPv6
}
- else
+ else
{
- PICA_error("unable to accept connection: %s", strerror(errno));
+ PICA_error("unable to accept connection: %s", strerror(errno));
}
}
@@ -2206,17 +2206,17 @@ void process_newconn_read(fd_set *readfds)
if (ret <= 0)
{
- //perror("process_newconn_read - recv:");//debug
+ //perror("process_newconn_read - recv:");//debug
newconn_close(newconns + i);
- continue;
+ continue;
}
newconns[i].pos += ret;
-
+
if(!PICA_processdatastream(newconns[i].buf, &(newconns[i].pos), newconns + i /*arg*/, _msginfo_newconn, MSGINFO_MSGSNUM(_msginfo_newconn) ))
{
newconn_close(newconns + i);
}
- //FD_CLR(newconns[i].sck,readfds);
+ //FD_CLR(newconns[i].sck,readfds);
}
}
@@ -2233,47 +2233,47 @@ void process_c2n_read(fd_set *readfds)
while (i_ptr)
{
if (FD_ISSET(i_ptr->sck_comm, readfds))
- switch(i_ptr->state)
- {
- case PICA_CLSTATE_CONNECTED:
+ switch(i_ptr->state)
+ {
+ case PICA_CLSTATE_CONNECTED:
ret = SSL_read(i_ptr->ssl_comm, i_ptr->r_buf + i_ptr->r_pos, i_ptr->buflen_r - i_ptr->r_pos);
-
- if (!ret)
+
+ if (!ret)
kill_ptr = i_ptr;
if (ret < 0)
switch(SSL_get_error(i_ptr->ssl_comm, ret))
- {
- case SSL_ERROR_WANT_WRITE:
- case SSL_ERROR_WANT_READ:
- break;
- default:
+ {
+ case SSL_ERROR_WANT_WRITE:
+ case SSL_ERROR_WANT_READ:
+ break;
+ default:
kill_ptr = i_ptr;
- }
-
+ }
+
if (ret > 0)
- {
+ {
i_ptr->r_pos += ret;
if(!PICA_processdatastream(i_ptr->r_buf, &(i_ptr->r_pos), i_ptr, _msginfo_comm, MSGINFO_MSGSNUM(_msginfo_comm) ))
kill_ptr = i_ptr;
-
- if (i_ptr->buflen_r == i_ptr->r_pos)
- if (!client_rbuf_grow(i_ptr))
- kill_ptr = i_ptr;
- }
- break;
- case PICA_CLSTATE_TLSNEGOTIATION:
+ if (i_ptr->buflen_r == i_ptr->r_pos)
+ if (!client_rbuf_grow(i_ptr))
+ kill_ptr = i_ptr;
+
+ }
+ break;
+ case PICA_CLSTATE_TLSNEGOTIATION:
i_ptr->w_pos = 1; //????
- //-------------- <<<<<<<<<<<<<<<<<<<<<<<<----------------------------------------
- break;
- };
-
+ //-------------- <<<<<<<<<<<<<<<<<<<<<<<<----------------------------------------
+ break;
+ };
+
i_ptr = i_ptr->next;
-
- if (kill_ptr)
+
+ if (kill_ptr)
{
- client_list_delete(kill_ptr);
+ client_list_delete(kill_ptr);
kill_ptr = 0;
}
}
@@ -2299,7 +2299,7 @@ void process_c2c_read(fd_set *readfds)
{
cc->bufpos_p1p2 += ret;
}
- else
+ else
kill_ptr = cc;
}
@@ -2312,16 +2312,16 @@ void process_c2c_read(fd_set *readfds)
{
cc->bufpos_p2p1 += ret;
}
- else
+ else
kill_ptr = cc;
}
cc = cc->next;
-
- if (kill_ptr)
+
+ if (kill_ptr)
{
- cclink_list_delete(kill_ptr);
+ cclink_list_delete(kill_ptr);
kill_ptr = 0;
}
}
@@ -2340,31 +2340,31 @@ void process_n2n_read(fd_set *readfds)
if (FD_ISSET(nl->sck, readfds))
{
ret = recv(nl->sck, nl->r_buf + nl->r_pos, nl->buflen_r - nl->r_pos, 0);
-
+
if (ret <= 0)
{
- if (ret < 0)
- PICA_debug3("recv() failed in process_n2n_read(): %s", strerror(errno));
+ if (ret < 0)
+ PICA_debug3("recv() failed in process_n2n_read(): %s", strerror(errno));
kill_ptr = nl;
}
- else
+ else
{
nl->r_pos += ret;
-
+
if(!PICA_processdatastream(nl->r_buf, &(nl->r_pos), nl, _msginfo_node, MSGINFO_MSGSNUM(_msginfo_node) ))
kill_ptr = nl;
- if (nl->buflen_r == nl->r_pos)
- if (!nodelink_rbuf_grow(nl))
+ if (nl->buflen_r == nl->r_pos)
+ if (!nodelink_rbuf_grow(nl))
kill_ptr = nl;
}
}
-
+
nl = nl->next;
-
- if (kill_ptr)
+
+ if (kill_ptr)
{
- nodelink_list_delete(kill_ptr);
+ nodelink_list_delete(kill_ptr);
kill_ptr = 0;
}
}
@@ -2380,27 +2380,27 @@ void process_c2n_write()
while(i_ptr)
{
- //---------
- switch(i_ptr->state)
+ //---------
+ switch(i_ptr->state)
{
case PICA_CLSTATE_CONNECTED:
- if (!i_ptr->w_pos)
- break;
+ if (!i_ptr->w_pos)
+ break;
- if (!i_ptr->btw_ssl)
+ if (!i_ptr->btw_ssl)
i_ptr->btw_ssl = i_ptr->w_pos;
-
+
ret = SSL_write(i_ptr->ssl_comm, i_ptr->w_buf, i_ptr->btw_ssl);
-
+
PICA_debug3("process_c2n_write: ret of SSL_write()=%i", ret);
-
+
if (ret == i_ptr->btw_ssl)
{
i_ptr->w_pos -= i_ptr->btw_ssl;
i_ptr->btw_ssl = 0;
}
- if (!ret)
+ if (!ret)
kill_ptr = i_ptr;
if (ret < 0)
@@ -2409,75 +2409,75 @@ void process_c2n_write()
if (ret != SSL_ERROR_WANT_WRITE && ret != SSL_ERROR_WANT_READ)
kill_ptr = i_ptr;
}
- break;
+ break;
case PICA_CLSTATE_SENDINGRESP:
ret = send(i_ptr->sck_comm, i_ptr->w_buf, i_ptr->w_pos, 0);
- if (!ret)
+ if (!ret)
kill_ptr = i_ptr;
-
+
if (ret == SOCKET_ERROR)
- ;//ERR_CHECK
-
- if (ret < i_ptr->w_pos)
+ ;//ERR_CHECK
+
+ if (ret < i_ptr->w_pos)
memmove(i_ptr->w_buf, i_ptr->w_buf + ret, i_ptr->w_pos - ret); //ring buffer is better (??)
i_ptr->w_pos -= ret;
-
- if (!i_ptr->w_pos)
+
+ if (!i_ptr->w_pos)
i_ptr->state = PICA_CLSTATE_TLSNEGOTIATION;
-
- break;
+
+ break;
case PICA_CLSTATE_TLSNEGOTIATION:
i_ptr->w_pos = 0;
ret = SSL_connect(i_ptr->ssl_comm);
-
+
PICA_debug3("process_c2n_write: SSL_connect()=%i", ret);
-
- if (!ret)
+
+ if (!ret)
kill_ptr = i_ptr;
-
+
if (ret < 0)
{
- int eret;
+ int eret;
eret = SSL_get_error(i_ptr->ssl_comm, ret);
- switch(eret)
+ switch(eret)
{
case SSL_ERROR_WANT_WRITE:
i_ptr->w_pos = 1;
- PICA_debug3("SSL_ERROR_WANT_WRITE");
- break;
+ PICA_debug3("SSL_ERROR_WANT_WRITE");
+ break;
case SSL_ERROR_WANT_READ:
- PICA_debug3("SSL_ERROR_WANT_READ");
- break;
+ PICA_debug3("SSL_ERROR_WANT_READ");
+ break;
default:
- PICA_debug3("SSL_get_error() = %i", eret);
+ PICA_debug3("SSL_get_error() = %i", eret);
kill_ptr = i_ptr;
}
}
if (ret == 1)
- //проверить сертификат пользователя
- {
- X509* client_cert;
+ //проверить сертификат пользователя
+ {
+ X509* client_cert;
- PICA_info("SSL c2n connection established using %s cipher", SSL_get_cipher(i_ptr->ssl_comm));
+ PICA_info("SSL c2n connection established using %s cipher", SSL_get_cipher(i_ptr->ssl_comm));
client_cert = SSL_get_peer_certificate (i_ptr->ssl_comm);
- if (!client_cert)
- {
- //ERR_CHECK //нет сертификата
+ if (!client_cert)
+ {
+ //ERR_CHECK //нет сертификата
kill_ptr = i_ptr;
- }
+ }
- ret = PICA_id_from_X509(client_cert, i_ptr->id);
-
- if (ret == 0)
- {
- PICA_error("Unable to get client id from certificate");
+ ret = PICA_id_from_X509(client_cert, i_ptr->id);
+
+ if (ret == 0)
+ {
+ PICA_error("Unable to get client id from certificate");
kill_ptr = i_ptr;
- }
-
- X509_free(client_cert);
+ }
+
+ X509_free(client_cert);
//reject all-zeroes ID
{
@@ -2490,32 +2490,32 @@ void process_c2n_write()
}
if (!kill_ptr && client_tree_search(i_ptr->id))
- {
- PICA_info("Disconnecting client %p because other user with same ID = %u is already connected", i_ptr, i_ptr->id);
+ {
+ PICA_info("Disconnecting client %p because other user with same ID = %u is already connected", i_ptr, i_ptr->id);
memset(i_ptr->id, 0, PICA_ID_SIZE);//reset id to all zeros to prevent removing existing ID from previous connection from client_tree
- ret = 0;//id already exists in tree
- }
- else
- {
+ ret = 0;//id already exists in tree
+ }
+ else
+ {
ret = client_tree_add(i_ptr);
- client_tree_print(client_tree_root);
- }
- if (!ret)
- {
- //ERR_CHECK //не уникальный id
+ client_tree_print(client_tree_root);
+ }
+ if (!ret)
+ {
+ //ERR_CHECK //не уникальный id
kill_ptr = i_ptr;
- }
+ }
i_ptr->state = PICA_CLSTATE_CONNECTED;
+ }
+ break;
}
- break;
- }
- //---------
+ //---------
i_ptr = i_ptr->next;
- if (kill_ptr)
+ if (kill_ptr)
{
- client_list_delete(kill_ptr);
+ client_list_delete(kill_ptr);
kill_ptr = 0;
}
}
@@ -2531,33 +2531,33 @@ void process_c2c_write()
while(cc)
{
- if (cc->bufpos_p1p2/* && (cc->state==PICA_CCLINK_LOCAL_ACTIVE || cc->state==PICA_CCLINK_N2NCLE_ACTIVE)*/)
+ if (cc->bufpos_p1p2/* && (cc->state==PICA_CCLINK_LOCAL_ACTIVE || cc->state==PICA_CCLINK_N2NCLE_ACTIVE)*/)
{
if (cc->state == PICA_CCLINK_N2NCLR_ACTIVE) //receiver is on remote node
{
- int sendlen;
- struct PICA_proto_msg *mp;
-
- sendlen = (cc->bufpos_p1p2 > PICA_PROTO_N2NMSG_MAXDATASIZE) ? PICA_PROTO_N2NMSG_MAXDATASIZE : cc->bufpos_p1p2;
+ int sendlen;
+ struct PICA_proto_msg *mp;
+
+ sendlen = (cc->bufpos_p1p2 > PICA_PROTO_N2NMSG_MAXDATASIZE) ? PICA_PROTO_N2NMSG_MAXDATASIZE : cc->bufpos_p1p2;
if(mp = nodelink_wbuf_push(cc->callee_node, PICA_PROTO_N2NMSG, sendlen + 4 + 2 * PICA_ID_SIZE))
{
- *((unsigned short*)mp->tail) = 2 * PICA_ID_SIZE + sendlen;
- memcpy(mp->tail + 2, cc->caller_id, PICA_ID_SIZE);
- memcpy(mp->tail + 2 + PICA_ID_SIZE, cc->callee_id, PICA_ID_SIZE);
- memcpy(mp->tail + 2 + 2 * PICA_ID_SIZE, cc->buf_p1p2, sendlen);
+ *((unsigned short*)mp->tail) = 2 * PICA_ID_SIZE + sendlen;
+ memcpy(mp->tail + 2, cc->caller_id, PICA_ID_SIZE);
+ memcpy(mp->tail + 2 + PICA_ID_SIZE, cc->callee_id, PICA_ID_SIZE);
+ memcpy(mp->tail + 2 + 2 * PICA_ID_SIZE, cc->buf_p1p2, sendlen);
ret = sendlen;
}
- else
+ else
ret = 0;
}
- else
+ else
ret = send(cc->sck_p2, cc->buf_p1p2, cc->bufpos_p1p2, MSG_NOSIGNAL);
PICA_debug3("process_c2c_write: send p1p2: ret=%i", ret);
if (ret > 0)
{
- if (ret < cc->bufpos_p1p2)
+ if (ret < cc->bufpos_p1p2)
memmove(cc->buf_p1p2, cc->buf_p1p2 + ret, cc->bufpos_p1p2 - ret); //may be it's better to implement ring buffer here
cc->bufpos_p1p2 -= ret;
cc->jam_p1p2 = 0;
@@ -2573,7 +2573,7 @@ void process_c2c_write()
ret = WSAGetLastError();
if (ret == WSAEWOULDBLOCK || ret == WSAENOBUFS)
cc->jam_p1p2 = 1;
- else
+ else
{
kill_ptr = cc;
}
@@ -2581,41 +2581,41 @@ void process_c2c_write()
ret = errno;
if (ret == EAGAIN || ret == ENOBUFS)
cc->jam_p1p2 = 1;
- else
+ else
{
kill_ptr = cc;
}
#endif
}
-
+
}
- if (cc->bufpos_p2p1 /*&& (cc->state==PICA_CCLINK_LOCAL_ACTIVE || cc->state==PICA_CCLINK_N2NCLR_ACTIVE)*/)
+ if (cc->bufpos_p2p1 /*&& (cc->state==PICA_CCLINK_LOCAL_ACTIVE || cc->state==PICA_CCLINK_N2NCLR_ACTIVE)*/)
{
if (cc->state == PICA_CCLINK_N2NCLE_ACTIVE) //receiver is on remote node
{
- int sendlen;
- struct PICA_proto_msg *mp;
-
- sendlen = (cc->bufpos_p2p1 > PICA_PROTO_N2NMSG_MAXDATASIZE) ? PICA_PROTO_N2NMSG_MAXDATASIZE : cc->bufpos_p2p1;
+ int sendlen;
+ struct PICA_proto_msg *mp;
+
+ sendlen = (cc->bufpos_p2p1 > PICA_PROTO_N2NMSG_MAXDATASIZE) ? PICA_PROTO_N2NMSG_MAXDATASIZE : cc->bufpos_p2p1;
if(mp = nodelink_wbuf_push(cc->caller_node, PICA_PROTO_N2NMSG, sendlen + 4 + 2 * PICA_ID_SIZE))
{
- *((unsigned short*)mp->tail) = 2 * PICA_ID_SIZE + sendlen;
- memcpy(mp->tail + 2, cc->callee_id, PICA_ID_SIZE);
- memcpy(mp->tail + 2 + PICA_ID_SIZE, cc->caller_id, PICA_ID_SIZE);
+ *((unsigned short*)mp->tail) = 2 * PICA_ID_SIZE + sendlen;
+ memcpy(mp->tail + 2, cc->callee_id, PICA_ID_SIZE);
+ memcpy(mp->tail + 2 + PICA_ID_SIZE, cc->caller_id, PICA_ID_SIZE);
memcpy(mp->tail + 2 + 2 * PICA_ID_SIZE, cc->buf_p2p1, sendlen);
ret = sendlen;
}
- else
+ else
ret = 0;
}
- else
+ else
ret = send(cc->sck_p1, cc->buf_p2p1, cc->bufpos_p2p1, MSG_NOSIGNAL);
PICA_debug3("process_c2c_write: send p2p1: ret=%i", ret);
if (ret > 0)
{
- if (ret < cc->bufpos_p2p1)
+ if (ret < cc->bufpos_p2p1)
memmove(cc->buf_p2p1, cc->buf_p2p1 + ret, cc->bufpos_p2p1 - ret); //may be it's better to implement ring buffer here
cc->bufpos_p2p1 -= ret;
cc->jam_p2p1 = 0;
@@ -2631,7 +2631,7 @@ void process_c2c_write()
ret = WSAGetLastError();
if (ret == WSAEWOULDBLOCK || ret == WSAENOBUFS)
cc->jam_p2p1 = 1;
- else
+ else
{
kill_ptr = cc;
}
@@ -2639,21 +2639,21 @@ void process_c2c_write()
ret = errno;
if (ret == EAGAIN || ret == ENOBUFS)
cc->jam_p2p1 = 1;
- else
+ else
{
kill_ptr = cc;
}
#endif
-
+
}
-
+
}
-
+
cc = cc->next;
-
- if (kill_ptr)
+
+ if (kill_ptr)
{
- cclink_list_delete(kill_ptr);
+ cclink_list_delete(kill_ptr);
kill_ptr = 0;
}
}
@@ -2675,7 +2675,7 @@ void process_n2n_write()
if (ret > 0)
{
- if (ret < nl->w_pos)
+ if (ret < nl->w_pos)
memmove(nl->w_buf, nl->w_buf + ret, nl->w_pos - ret); //may be it's better to implement ring buffer here
nl->w_pos -= ret;
}
@@ -2696,10 +2696,10 @@ void process_n2n_write()
}
nl = nl->next;
-
- if (kill_ptr)
+
+ if (kill_ptr)
{
- nodelink_list_delete(kill_ptr);
+ nodelink_list_delete(kill_ptr);
kill_ptr = 0;
}
}
@@ -2711,91 +2711,91 @@ void process_nodewait()
while(nw)
{
- //PICA_debug3("checking nodewait pointer %p", nw);
- switch(nw->state)
- {
- case PICA_NODEWAIT_RESOLVED:
+ //PICA_debug3("checking nodewait pointer %p", nw);
+ switch(nw->state)
{
- int skip = 0;
- struct nodelink *nl;
-
- nl = nodelink_list_head;
+ case PICA_NODEWAIT_RESOLVED:
+ {
+ int skip = 0;
+ struct nodelink *nl;
+
+ nl = nodelink_list_head;
- while(nl && !skip)//check existing connections
+ while(nl && !skip)//check existing connections
{
- struct addrinfo *p_ai = nw->ai;
+ struct addrinfo *p_ai = nw->ai;
- while(p_ai) //IPv6
+ while(p_ai) //IPv6
{
- struct sockaddr_in in = *(struct sockaddr_in*)p_ai->ai_addr;
+ struct sockaddr_in in = *(struct sockaddr_in*)p_ai->ai_addr;
- if (nl->addr.sin_family == in.sin_family && nl->addr.sin_addr.s_addr == in.sin_addr.s_addr && nl->addr.sin_port == in.sin_port)
+ if (nl->addr.sin_family == in.sin_family && nl->addr.sin_addr.s_addr == in.sin_addr.s_addr && nl->addr.sin_port == in.sin_port)
{
- skip = 1;
- break;
+ skip = 1;
+ break;
}
- p_ai = p_ai->ai_next;
+ p_ai = p_ai->ai_next;
}
- nl = nl->next;
+ nl = nl->next;
}
- if (!skip)
- nodewait_start_connect(nw);
- else
+ if (!skip)
+ nodewait_start_connect(nw);
+ else
{
- PICA_debug3("skipping node %.255s %u , connection already exist", nw->addr.addr, nw->addr.port);
- kill_ptr = nw;
+ PICA_debug3("skipping node %.255s %u , connection already exist", nw->addr.addr, nw->addr.port);
+ kill_ptr = nw;
}
}
- break;
+ break;
- case PICA_NODEWAIT_CONNECTED:
+ case PICA_NODEWAIT_CONNECTED:
{
- struct nodelink *nlp;
-
- PICA_debug1("connected to %.255s %u, sending request ", nw->addr.addr, nw->addr.port);
- PICA_debug2("connection socket is %i", nw->nc.sck);
+ struct nodelink *nlp;
+
+ PICA_debug1("connected to %.255s %u, sending request ", nw->addr.addr, nw->addr.port);
+ PICA_debug2("connection socket is %i", nw->nc.sck);
nlp = nodelink_list_addnew(&nw->nc);
- if (nlp)
+ if (nlp)
{
- struct PICA_proto_msg *mp;
- mp = nodelink_wbuf_push(nlp, PICA_PROTO_NODECONNREQ, PICA_PROTO_NODECONNREQ_SIZE);
- if (mp)
+ struct PICA_proto_msg *mp;
+ mp = nodelink_wbuf_push(nlp, PICA_PROTO_NODECONNREQ, PICA_PROTO_NODECONNREQ_SIZE);
+ if (mp)
{
- mp->tail[0] = PICA_PROTO_VER_HIGH;
- mp->tail[1] = PICA_PROTO_VER_LOW;
+ mp->tail[0] = PICA_PROTO_VER_HIGH;
+ mp->tail[1] = PICA_PROTO_VER_LOW;
}
}
- PICA_nodeaddr_update(nodecfg.nodes_db_file, &nw->addr, 1);
- kill_ptr = nw;
+ PICA_nodeaddr_update(nodecfg.nodes_db_file, &nw->addr, 1);
+ kill_ptr = nw;
}
- break;
+ break;
- case PICA_NODEWAIT_RESOLVING_FAILED:
+ case PICA_NODEWAIT_RESOLVING_FAILED:
{
- PICA_debug1("resolving %.255s %u failed: %s", nw->addr.addr, nw->addr.port, gai_strerror(nw->ai_errorcode));
- PICA_nodeaddr_update(nodecfg.nodes_db_file, &nw->addr, 0);
- kill_ptr = nw;
+ PICA_debug1("resolving %.255s %u failed: %s", nw->addr.addr, nw->addr.port, gai_strerror(nw->ai_errorcode));
+ PICA_nodeaddr_update(nodecfg.nodes_db_file, &nw->addr, 0);
+ kill_ptr = nw;
}
- break;
+ break;
- case PICA_NODEWAIT_CONNECT_FAILED:
+ case PICA_NODEWAIT_CONNECT_FAILED:
{
- PICA_debug1("connection to %.255s %u failed", nw->addr.addr, nw->addr.port);
- PICA_debug2("socket %i is closed", nw->nc.sck);
- PICA_nodeaddr_update(nodecfg.nodes_db_file, &nw->addr, 0);
- kill_ptr = nw;
+ PICA_debug1("connection to %.255s %u failed", nw->addr.addr, nw->addr.port);
+ PICA_debug2("socket %i is closed", nw->nc.sck);
+ PICA_nodeaddr_update(nodecfg.nodes_db_file, &nw->addr, 0);
+ kill_ptr = nw;
+ }
+ break;
}
- break;
- }
-
- nw = nw->next;
- if (kill_ptr)
+ nw = nw->next;
+
+ if (kill_ptr)
{
- nodewait_list_delete(kill_ptr);
- kill_ptr = 0;
+ nodewait_list_delete(kill_ptr);
+ kill_ptr = 0;
}
}
@@ -2806,12 +2806,12 @@ int node_loop()
fd_set fds;
struct timeval tv;
int nfds, ret;
-
+
do
{
- nfds = 0;
-
- FD_ZERO(&fds);
+ nfds = 0;
+
+ FD_ZERO(&fds);
tv.tv_sec = SELECT_TIMEOUT;
tv.tv_usec = 0;
@@ -2820,32 +2820,32 @@ int node_loop()
c2n_set_fds(&fds, &nfds);
c2c_set_fds(&fds, &nfds);
n2n_set_fds(&fds, &nfds);
-
+
ret = select(nfds + 1, &fds, 0, 0, &tv);
-
+
if (ret < 0)
{
- perror("node_loop-select error ");
- //ERR_CHECK
- return -1;
+ perror("node_loop-select error ");
+ //ERR_CHECK
+ return -1;
}
if (ret > 0)
{
- process_c2n_read(&fds);
- process_c2c_read(&fds);
- process_n2n_read(&fds);
- process_newconn_read(&fds);
- process_listen_read(&fds);
- }
-
-
- process_c2n_write();
- process_c2c_write();
- process_n2n_write();
-
- process_timeouts();
- process_nodewait();
+ process_c2n_read(&fds);
+ process_c2c_read(&fds);
+ process_n2n_read(&fds);
+ process_newconn_read(&fds);
+ process_listen_read(&fds);
+ }
+
+
+ process_c2n_write();
+ process_c2c_write();
+ process_n2n_write();
+
+ process_timeouts();
+ process_nodewait();
}
while(1);////<<<<<<<<<<
return 0;
@@ -2889,36 +2889,36 @@ void process_cmdline(int argc, char** argv)
while((opt = getopt(argc, argv, "f:hvV")) != -1)
{
- switch(opt)
+ switch(opt)
{
case 'f':
- nodecfg.config_file = strdup(optarg);
- break;
-
+ nodecfg.config_file = strdup(optarg);
+ break;
+
case 'h':
- print_usage();
- exit(0);
- break;
-
+ print_usage();
+ exit(0);
+ break;
+
case 'v':
- verbosity++;
-
- break;
-
+ verbosity++;
+
+ break;
+
case 'V':
- print_version();
- exit(0);
- break;
-
+ print_version();
+ exit(0);
+ break;
+
default:
- PICA_error("unknown option - %c", optopt);
- print_usage();
- exit(-1);
+ PICA_error("unknown option - %c", optopt);
+ print_usage();
+ exit(-1);
}
}
if (verbosity > 3)
- verbosity = 3;
+ verbosity = 3;
PICA_set_loglevel(PICA_LOG_INFO + verbosity);
}
@@ -2933,54 +2933,54 @@ void PICA_node_joinskynet(const char* addrlistfilename, const char *my_addr)
ret = PICA_nodeaddr_list_load(addrlistfilename, &addrlist_h);//MEM
if (ret <= 0)
- return;
+ return;
nap = addrlist_h;
while(nap)
{
- int skip = 0;
+ int skip = 0;
- if (0 == strncmp(nap->addr, my_addr, 256) && nap->port == atoi(nodecfg.listen_port))
+ if (0 == strncmp(nap->addr, my_addr, 256) && nap->port == atoi(nodecfg.listen_port))
{
- PICA_debug3("Skipping self address %.255s port %u", nap->addr, nap->port);
- skip = 1;
+ PICA_debug3("Skipping self address %.255s port %u", nap->addr, nap->port);
+ skip = 1;
}
-
- if (nodecfg.disable_reserved_addrs && INADDR_NONE != inet_addr(nap->addr) && PICA_is_reserved_addr_ipv4(inet_addr(nap->addr)))
+
+ if (nodecfg.disable_reserved_addrs && INADDR_NONE != inet_addr(nap->addr) && PICA_is_reserved_addr_ipv4(inet_addr(nap->addr)))
{
- PICA_debug3("Skipping IP from private range %.255s port %u", nap->addr, nap->port);
- skip = 1;
+ PICA_debug3("Skipping IP from private range %.255s port %u", nap->addr, nap->port);
+ skip = 1;
}
-
- nl = nodelink_list_head;
- //check if connection to node with current address is already established
- while(nl && !skip)
+
+ nl = nodelink_list_head;
+ //check if connection to node with current address is already established
+ while(nl && !skip)
{
- if (nl->node_addr)
+ if (nl->node_addr)
{
- switch(nl->addr_type)
+ switch(nl->addr_type)
{
- case PICA_PROTO_NEWNODE_IPV4:
- if (0 == strncmp(nap->addr, inet_ntoa(*(struct in_addr*) & (((struct PICA_nodeaddr_ipv4*)nl->node_addr)->addr)) , 16)
- &&
- nap->port == ntohs(((struct PICA_nodeaddr_ipv4*)nl->node_addr)->port))
- skip = 1;
- break;
- //IPv6
+ case PICA_PROTO_NEWNODE_IPV4:
+ if (0 == strncmp(nap->addr, inet_ntoa(*(struct in_addr*) & (((struct PICA_nodeaddr_ipv4*)nl->node_addr)->addr)), 16)
+ &&
+ nap->port == ntohs(((struct PICA_nodeaddr_ipv4*)nl->node_addr)->port))
+ skip = 1;
+ break;
+ //IPv6
}
}
-
+
if (0 == strncmp(nap->addr, inet_ntoa(nl->addr.sin_addr), 16) && nap->port == ntohs(nl->addr.sin_port))
- skip = 1;
-
-
- nl = nl->next;
+ skip = 1;
+
+
+ nl = nl->next;
}
-
- if (!skip)
- nodewait_start_resolve(nap);
-
+
+ if (!skip)
+ nodewait_start_resolve(nap);
+
nap = nap->next;
}
@@ -2996,7 +2996,7 @@ int main(int argc, char** argv)
if (!PICA_nodeconfig_load(nodecfg.config_file))
{
- PICA_fatal("Unable to load configuration. Please check if config file %s exists and has correct permissions", nodecfg.config_file);
+ PICA_fatal("Unable to load configuration. Please check if config file %s exists and has correct permissions", nodecfg.config_file);
}
PICA_debug1("nodecfg.config_file = %s", nodecfg.config_file);
@@ -3006,20 +3006,20 @@ int main(int argc, char** argv)
PICA_debug1("nodecfg.disable_reserved_addrs = %s", nodecfg.disable_reserved_addrs ? "yes" : "no");
if (!PICA_node_init())
- return -1;
+ return -1;
if (INADDR_NONE == inet_addr(nodecfg.announced_addr) || INADDR_ANY == inet_addr(nodecfg.announced_addr))
{
- PICA_fatal("announced_addr (%.16s) is invalid or not configured. Please set correct public IP address of your pica-node instance in config file.",
- nodecfg.announced_addr
- );
+ PICA_fatal("announced_addr (%.16s) is invalid or not configured. Please set correct public IP address of your pica-node instance in config file.",
+ nodecfg.announced_addr
+ );
}
-
+
if (nodecfg.disable_reserved_addrs && PICA_is_reserved_addr_ipv4(inet_addr(nodecfg.announced_addr)))
{
- PICA_fatal("announced_addr (%.16s) is in private range and is unacceptable for global Internet. Private ranges are disabled by node configuration.",
- nodecfg.announced_addr
- );
+ PICA_fatal("announced_addr (%.16s) is in private range and is unacceptable for global Internet. Private ranges are disabled by node configuration.",
+ nodecfg.announced_addr
+ );
}
PICA_node_joinskynet(nodecfg.nodes_db_file, nodecfg.announced_addr);//CONF-CONF имя файла с адресами узлов, свой адрес
diff --git a/pica-client/accounts.cpp b/pica-client/accounts.cpp
index a1cfdd0..cf565d8 100644
--- a/pica-client/accounts.cpp
+++ b/pica-client/accounts.cpp
@@ -5,133 +5,133 @@ Accounts::AccountRecord Accounts::current_account;
Accounts::AccountRecord & Accounts::GetCurrentAccount()
{
- return Accounts::current_account;
+ return Accounts::current_account;
}
void Accounts::SetCurrentAccount(Accounts::AccountRecord &rec)
{
- Accounts::current_account = rec;
+ Accounts::current_account = rec;
}
Accounts::Accounts(QString storage)
{
- dbconn=QSqlDatabase::addDatabase("QSQLITE");
- dbconn.setDatabaseName(storage);
+ dbconn = QSqlDatabase::addDatabase("QSQLITE");
+ dbconn.setDatabaseName(storage);
- if (!dbconn.open())
- {
- lasterr=dbconn.lastError();
- return;
- }
+ if (!dbconn.open())
+ {
+ lasterr = dbconn.lastError();
+ return;
+ }
- QSqlQuery query;
+ QSqlQuery query;
- query.exec("PRAGMA foreign_keys=ON;");
+ query.exec("PRAGMA foreign_keys=ON;");
- //check result, if foreign keys support is on
+ //check result, if foreign keys support is on
}
void Accounts::Add(AccountRecord &acc)
{
- QSqlQuery query;
+ QSqlQuery query;
- query.prepare("insert into accounts (id, name, cert_file, pkey_file, ca_file) values (:id, :name, :cert_file, :pkey_file, :ca_file);");
- query.bindValue(":id",acc.id);
- query.bindValue(":name",acc.name);
- query.bindValue(":cert_file",acc.cert_file);
- query.bindValue(":pkey_file",acc.pkey_file);
- query.bindValue(":ca_file",acc.CA_file);
- query.exec();
+ query.prepare("insert into accounts (id, name, cert_file, pkey_file, ca_file) values (:id, :name, :cert_file, :pkey_file, :ca_file);");
+ query.bindValue(":id", acc.id);
+ query.bindValue(":name", acc.name);
+ query.bindValue(":cert_file", acc.cert_file);
+ query.bindValue(":pkey_file", acc.pkey_file);
+ query.bindValue(":ca_file", acc.CA_file);
+ query.exec();
- lasterr=query.lastError();
+ lasterr = query.lastError();
}
void Accounts::Delete(QByteArray id)
{
- QSqlQuery query;
+ QSqlQuery query;
- query.prepare("delete from accounts where id=:id");
- query.bindValue(":id",id);
- query.exec();
+ query.prepare("delete from accounts where id=:id");
+ query.bindValue(":id", id);
+ query.exec();
- lasterr=query.lastError();
+ lasterr = query.lastError();
}
QList<Accounts::AccountRecord> Accounts::GetAccounts()
{
- AccountRecord r;
- QList<Accounts::AccountRecord> L;
- QSqlQuery query;
-
- //
- query.setForwardOnly(true);
- query.exec("select id, name, cert_file, pkey_file, ca_file from accounts");
- lasterr=query.lastError();
-
- if (lasterr.isValid())
- return L;
-
- while(query.next())
- {
- r.id = query.value(0).toByteArray();
- r.name = query.value(1).toString();
- r.cert_file = query.value(2).toString();
- r.pkey_file = query.value(3).toString();
- r.CA_file = query.value(4).toString();
-
- L<<r;
- }
-
- return L;
+ AccountRecord r;
+ QList<Accounts::AccountRecord> L;
+ QSqlQuery query;
+
+ //
+ query.setForwardOnly(true);
+ query.exec("select id, name, cert_file, pkey_file, ca_file from accounts");
+ lasterr = query.lastError();
+
+ if (lasterr.isValid())
+ return L;
+
+ while(query.next())
+ {
+ r.id = query.value(0).toByteArray();
+ r.name = query.value(1).toString();
+ r.cert_file = query.value(2).toString();
+ r.pkey_file = query.value(3).toString();
+ r.CA_file = query.value(4).toString();
+
+ L << r;
+ }
+
+ return L;
}
QString Accounts::GetName(QByteArray id)
{
- QSqlQuery query;
+ QSqlQuery query;
- query.prepare("select name from accounts where id=:id");
- query.bindValue(":id", id);
- query.exec();
+ query.prepare("select name from accounts where id=:id");
+ query.bindValue(":id", id);
+ query.exec();
- lasterr=query.lastError();
+ lasterr = query.lastError();
- if (lasterr.isValid())
- return QString::null;
+ if (lasterr.isValid())
+ return QString::null;
- query.next();
+ query.next();
- return query.value(0).toString();
+ return query.value(0).toString();
}
bool Accounts::isOK()
{
- return !lasterr.isValid();
+ return !lasterr.isValid();
}
QString Accounts::GetLastError()
{
- return lasterr.text();
+ return lasterr.text();
}
bool Accounts::CheckFiles(AccountRecord &acc, QString &error_string)
{
- if (!QFile::exists(acc.cert_file))
- {
- error_string = QObject::tr("Certificate file %1 does not exist").arg(acc.cert_file);
- return false;
- }
-
- if (!QFile::exists(acc.pkey_file))
- {
- error_string = QObject::tr("Private key file %1 does not exist").arg(acc.pkey_file);
- return false;
- }
-
- if (!QFile::exists(acc.CA_file))
- {
- error_string = QObject::tr("Certificate Authority file %1 does not exist").arg(acc.CA_file);
- return false;
- }
-
- return true;
+ if (!QFile::exists(acc.cert_file))
+ {
+ error_string = QObject::tr("Certificate file %1 does not exist").arg(acc.cert_file);
+ return false;
+ }
+
+ if (!QFile::exists(acc.pkey_file))
+ {
+ error_string = QObject::tr("Private key file %1 does not exist").arg(acc.pkey_file);
+ return false;
+ }
+
+ if (!QFile::exists(acc.CA_file))
+ {
+ error_string = QObject::tr("Certificate Authority file %1 does not exist").arg(acc.CA_file);
+ return false;
+ }
+
+ return true;
}
diff --git a/pica-client/accounts.h b/pica-client/accounts.h
index 8cb6592..f147888 100644
--- a/pica-client/accounts.h
+++ b/pica-client/accounts.h
@@ -9,32 +9,32 @@
class Accounts
{
public:
- struct AccountRecord
- {
- QByteArray id;
- QString name;
- QString cert_file;
- QString pkey_file;
- QString CA_file;
- };
-
- Accounts(QString storage);
- void Add(AccountRecord& acc);
- void Delete(QByteArray id);
- QList<AccountRecord> GetAccounts();
- QString GetName(QByteArray id);
- bool isOK();
- QString GetLastError();
-
- static bool CheckFiles(AccountRecord& acc, QString &error_string);
-
- static AccountRecord &GetCurrentAccount();
- static void SetCurrentAccount(AccountRecord &rec);
+ struct AccountRecord
+ {
+ QByteArray id;
+ QString name;
+ QString cert_file;
+ QString pkey_file;
+ QString CA_file;
+ };
+
+ Accounts(QString storage);
+ void Add(AccountRecord& acc);
+ void Delete(QByteArray id);
+ QList<AccountRecord> GetAccounts();
+ QString GetName(QByteArray id);
+ bool isOK();
+ QString GetLastError();
+
+ static bool CheckFiles(AccountRecord& acc, QString &error_string);
+
+ static AccountRecord &GetCurrentAccount();
+ static void SetCurrentAccount(AccountRecord &rec);
private:
- static AccountRecord current_account;
- QSqlDatabase dbconn;
- QSqlError lasterr;
+ static AccountRecord current_account;
+ QSqlDatabase dbconn;
+ QSqlError lasterr;
};
diff --git a/pica-client/accountswindow.cpp b/pica-client/accountswindow.cpp
index 7295856..a6d4fb4 100644
--- a/pica-client/accountswindow.cpp
+++ b/pica-client/accountswindow.cpp
@@ -13,211 +13,211 @@
#include <cstring>
AccountsWindow::AccountsWindow(QWidget *parent) :
- QMainWindow(parent),
- accounts(config_dbname)
+ QMainWindow(parent),
+ accounts(config_dbname)
{
- QVBoxLayout *layout;
- layout = new QVBoxLayout;
-
- cb_accounts = new QComboBox();
- bt_login = new QPushButton(tr("Log In"));
- bt_registernew = new QPushButton(tr("Create New Account..."));
- bt_addimport = new QPushButton(tr("Add (Import) existing account..."));
- bt_delete = new QPushButton(tr("Delete Account"));
-
- {
- QFont f;
- f= bt_login->font();
- f.setBold(true);
- bt_login->setFont(f);
-
- f = cb_accounts->font();
- f.setStyleHint(QFont::Monospace);
- f.setFixedPitch(true);
- f.setBold(true);
- f.setFamily("Liberation Mono");
- cb_accounts->setFont(f);
- }
-
- layout->addWidget(cb_accounts);
- layout->addWidget(bt_login);
- layout->addWidget(bt_registernew);
- layout->addWidget(bt_addimport);
- layout->addWidget(bt_delete);
-
- QWidget *central = new QWidget(this);
- setCentralWidget(central);
-
- centralWidget()->setLayout(layout);
-
- setWindowIcon(picapica_ico_sit);
-
- connect(bt_login,SIGNAL(clicked()),this,SLOT(login_click()));
- connect(bt_registernew,SIGNAL(clicked()),this,SLOT(register_click()));
- connect(bt_addimport,SIGNAL(clicked()),this,SLOT(add_click()));
- connect(bt_delete,SIGNAL(clicked()),this,SLOT(delete_click()));
-
- LoadAccounts();
+ QVBoxLayout *layout;
+ layout = new QVBoxLayout;
+
+ cb_accounts = new QComboBox();
+ bt_login = new QPushButton(tr("Log In"));
+ bt_registernew = new QPushButton(tr("Create New Account..."));
+ bt_addimport = new QPushButton(tr("Add (Import) existing account..."));
+ bt_delete = new QPushButton(tr("Delete Account"));
+
+ {
+ QFont f;
+ f = bt_login->font();
+ f.setBold(true);
+ bt_login->setFont(f);
+
+ f = cb_accounts->font();
+ f.setStyleHint(QFont::Monospace);
+ f.setFixedPitch(true);
+ f.setBold(true);
+ f.setFamily("Liberation Mono");
+ cb_accounts->setFont(f);
+ }
+
+ layout->addWidget(cb_accounts);
+ layout->addWidget(bt_login);
+ layout->addWidget(bt_registernew);
+ layout->addWidget(bt_addimport);
+ layout->addWidget(bt_delete);
+
+ QWidget *central = new QWidget(this);
+ setCentralWidget(central);
+
+ centralWidget()->setLayout(layout);
+
+ setWindowIcon(picapica_ico_sit);
+
+ connect(bt_login, SIGNAL(clicked()), this, SLOT(login_click()));
+ connect(bt_registernew, SIGNAL(clicked()), this, SLOT(register_click()));
+ connect(bt_addimport, SIGNAL(clicked()), this, SLOT(add_click()));
+ connect(bt_delete, SIGNAL(clicked()), this, SLOT(delete_click()));
+
+ LoadAccounts();
}
void AccountsWindow::LoadAccounts()
{
- cb_accounts->clear();
- L.clear();
- L=accounts.GetAccounts();
-
- if (0==L.count())
- {
- cb_accounts->addItem(tr(" ---No Accounts --"));
-
- bt_login->setDisabled(true);
- }
- else
- {
- for (int i=0;i<L.count();i++)
- cb_accounts->addItem(QString("%1 (%2...)").arg(L[i].name).arg(L[i].id.toBase64().left(8).constData()),L[i].id);
-
- bt_login->setEnabled(true);
- }
+ cb_accounts->clear();
+ L.clear();
+ L = accounts.GetAccounts();
+
+ if (0 == L.count())
+ {
+ cb_accounts->addItem(tr(" ---No Accounts --"));
+
+ bt_login->setDisabled(true);
+ }
+ else
+ {
+ for (int i = 0; i < L.count(); i++)
+ cb_accounts->addItem(QString("%1 (%2...)").arg(L[i].name).arg(L[i].id.toBase64().left(8).constData()), L[i].id);
+
+ bt_login->setEnabled(true);
+ }
}
void AccountsWindow::login_click()
{
- int L_index;
-
- for (int i=0;i<L.count();i++)
- {
- if (L[i].id == cb_accounts->itemData(cb_accounts->currentIndex()))
- {
- L_index = i;
- break;
- }
- }
-
- {
- QString error_str;
- if (!Accounts::CheckFiles(L[L_index],error_str))
- {
- QMessageBox mbx;
- mbx.setText(error_str);
- mbx.exec();
- return;
- }
- }
-
- Accounts::SetCurrentAccount(L[L_index]);
-
- skynet->Join(L[L_index]);
-
- mainwindow = new MainWindow();
- mainwindow->show();
- this->hide();
+ int L_index;
+
+ for (int i = 0; i < L.count(); i++)
+ {
+ if (L[i].id == cb_accounts->itemData(cb_accounts->currentIndex()))
+ {
+ L_index = i;
+ break;
+ }
+ }
+
+ {
+ QString error_str;
+ if (!Accounts::CheckFiles(L[L_index], error_str))
+ {
+ QMessageBox mbx;
+ mbx.setText(error_str);
+ mbx.exec();
+ return;
+ }
+ }
+
+ Accounts::SetCurrentAccount(L[L_index]);
+
+ skynet->Join(L[L_index]);
+
+ mainwindow = new MainWindow();
+ mainwindow->show();
+ this->hide();
}
void AccountsWindow::CreateAccount(QString CertFilename, QString PkeyFilename, bool copyfiles)
{
- QByteArray id(PICA_ID_SIZE, 0);
- int ret;
-
- ret = PICA_get_id_from_cert_file(CertFilename.toUtf8().constData(), (unsigned char*)id.data());
-
- if (0 == ret)
- {
- QMessageBox mbx;
- mbx.setText("Invalid certificate");
- mbx.exec();
- return;
- }
-
- QString name = OpenSSLTool::NameFromCertFile(CertFilename);
-
- Accounts::AccountRecord rec;
- QString certfilename, pkeyfilename;
-
- if (copyfiles)
- {
- QDir dir(config_dir);
- dir.mkdir(name + '_' + id.toHex().constData());
- dir.cd(name + '_' + id.toHex().constData());
-
- certfilename=dir.absolutePath()+"/" + id.toHex().constData() + "_cert.pem";
- pkeyfilename=dir.absolutePath()+"/" + id.toHex().constData() + "_pkey.pem";
-
- QFile::copy(CertFilename,certfilename);
- QFile::copy(PkeyFilename,pkeyfilename);
- }
- else
- {
- certfilename = CertFilename;
- pkeyfilename = PkeyFilename;
- }
-
- rec.id=id;
- rec.name=name;
- rec.cert_file=certfilename;
- rec.pkey_file=pkeyfilename;
- rec.CA_file= config_defaultCA;//;certfilename
-
- accounts.Add(rec);
-
- if (!accounts.isOK())
- {
- QMessageBox mbx;
- mbx.setText(accounts.GetLastError());
- mbx.exec();
- }
- else
- {
- ShowPicaIdDialog d(name, id, tr("New account is created"));
- d.exec();
- }
- LoadAccounts();
+ QByteArray id(PICA_ID_SIZE, 0);
+ int ret;
+
+ ret = PICA_get_id_from_cert_file(CertFilename.toUtf8().constData(), (unsigned char*)id.data());
+
+ if (0 == ret)
+ {
+ QMessageBox mbx;
+ mbx.setText("Invalid certificate");
+ mbx.exec();
+ return;
+ }
+
+ QString name = OpenSSLTool::NameFromCertFile(CertFilename);
+
+ Accounts::AccountRecord rec;
+ QString certfilename, pkeyfilename;
+
+ if (copyfiles)
+ {
+ QDir dir(config_dir);
+ dir.mkdir(name + '_' + id.toHex().constData());
+ dir.cd(name + '_' + id.toHex().constData());
+
+ certfilename = dir.absolutePath() + "/" + id.toHex().constData() + "_cert.pem";
+ pkeyfilename = dir.absolutePath() + "/" + id.toHex().constData() + "_pkey.pem";
+
+ QFile::copy(CertFilename, certfilename);
+ QFile::copy(PkeyFilename, pkeyfilename);
+ }
+ else
+ {
+ certfilename = CertFilename;
+ pkeyfilename = PkeyFilename;
+ }
+
+ rec.id = id;
+ rec.name = name;
+ rec.cert_file = certfilename;
+ rec.pkey_file = pkeyfilename;
+ rec.CA_file = config_defaultCA; //;certfilename
+
+ accounts.Add(rec);
+
+ if (!accounts.isOK())
+ {
+ QMessageBox mbx;
+ mbx.setText(accounts.GetLastError());
+ mbx.exec();
+ }
+ else
+ {
+ ShowPicaIdDialog d(name, id, tr("New account is created"));
+ d.exec();
+ }
+ LoadAccounts();
}
void AccountsWindow::register_click()
{
- RegisterAccountDialog d;
- d.exec();
+ RegisterAccountDialog d;
+ d.exec();
- if (d.result())
- {
- CreateAccount(d.GetCertFilename(), d.GetPkeyFilename(), true);
+ if (d.result())
+ {
+ CreateAccount(d.GetCertFilename(), d.GetPkeyFilename(), true);
- QFile::remove(d.GetCertFilename());
- QFile::remove(d.GetPkeyFilename());
- }
+ QFile::remove(d.GetCertFilename());
+ QFile::remove(d.GetPkeyFilename());
+ }
}
void AccountsWindow::add_click()
{
- AddAccountDialog d;
- d.exec();
+ AddAccountDialog d;
+ d.exec();
- if (d.result())
- {
- CreateAccount(d.GetCertFilename(), d.GetPkeyFilename(), d.isCopyFilesChecked());
- }
+ if (d.result())
+ {
+ CreateAccount(d.GetCertFilename(), d.GetPkeyFilename(), d.isCopyFilesChecked());
+ }
}
void AccountsWindow::delete_click()
{
- QByteArray id = (cb_accounts->itemData(cb_accounts->currentIndex())).toByteArray();
+ QByteArray id = (cb_accounts->itemData(cb_accounts->currentIndex())).toByteArray();
- if (QMessageBox::No==
- QMessageBox::question(this,tr("Deleting account"),tr("Are you sure you want to delete account %1 ?").arg(id.toBase64().constData()),QMessageBox::Yes,QMessageBox::No))
- return;
+ if (QMessageBox::No ==
+ QMessageBox::question(this, tr("Deleting account"), tr("Are you sure you want to delete account %1 ?").arg(id.toBase64().constData()), QMessageBox::Yes, QMessageBox::No))
+ return;
- //TODO ask user if he wants to wipe certificate and private key too
+ //TODO ask user if he wants to wipe certificate and private key too
- accounts.Delete(id);
+ accounts.Delete(id);
- LoadAccounts();
+ LoadAccounts();
}
void AccountsWindow::closeEvent(QCloseEvent *e)
{
- QApplication::instance()->quit();
- QMainWindow::closeEvent(e);
+ QApplication::instance()->quit();
+ QMainWindow::closeEvent(e);
}
diff --git a/pica-client/accountswindow.h b/pica-client/accountswindow.h
index 1a6175b..c4f0fd8 100644
--- a/pica-client/accountswindow.h
+++ b/pica-client/accountswindow.h
@@ -9,24 +9,24 @@
class AccountsWindow : public QMainWindow
{
- Q_OBJECT
+ Q_OBJECT
public:
- explicit AccountsWindow(QWidget *parent = 0);
+ explicit AccountsWindow(QWidget *parent = 0);
private:
- QComboBox *cb_accounts;
- QPushButton *bt_login;
- QPushButton *bt_registernew;
- QPushButton *bt_addimport;
- QPushButton *bt_delete;
+ QComboBox *cb_accounts;
+ QPushButton *bt_login;
+ QPushButton *bt_registernew;
+ QPushButton *bt_addimport;
+ QPushButton *bt_delete;
- Accounts accounts;
- QList<Accounts::AccountRecord> L;
+ Accounts accounts;
+ QList<Accounts::AccountRecord> L;
- void LoadAccounts();
- void CreateAccount(QString CertFilename, QString PkeyFilename, bool copyfiles);
+ void LoadAccounts();
+ void CreateAccount(QString CertFilename, QString PkeyFilename, bool copyfiles);
- void closeEvent(QCloseEvent *);
+ void closeEvent(QCloseEvent *);
signals:
@@ -34,10 +34,10 @@ signals:
public slots:
private slots:
- void login_click();
- void register_click();
- void add_click();
- void delete_click();
+ void login_click();
+ void register_click();
+ void add_click();
+ void delete_click();
};
diff --git a/pica-client/askpassword.cpp b/pica-client/askpassword.cpp
index 70f8644..cf21ed4 100644
--- a/pica-client/askpassword.cpp
+++ b/pica-client/askpassword.cpp
@@ -12,87 +12,87 @@ int AskPassword::is_cancelled = 0;
int AskPassword::is_set = 0;
AskPassword::AskPassword(QObject *parent) :
- QObject(parent)
+ QObject(parent)
{
- connect(this,SIGNAL(password_requested()),this,SLOT(password_dialog()), Qt::BlockingQueuedConnection);
+ connect(this, SIGNAL(password_requested()), this, SLOT(password_dialog()), Qt::BlockingQueuedConnection);
}
AskPassword::~AskPassword()
{
- memset(current_password, 0, sizeof(current_password));
+ memset(current_password, 0, sizeof(current_password));
}
int AskPassword::ask_password_cb(char *buf, int size, int rwflag, void *userdata)
{
- //QString pswd;
- //QByteArray id = QByteArray((const char*) userdata, PICA_ID_SIZE);
+ //QString pswd;
+ //QByteArray id = QByteArray((const char*) userdata, PICA_ID_SIZE);
- if (is_cancelled)
- return 0;
+ if (is_cancelled)
+ return 0;
- passwd_mutex.lock();
+ passwd_mutex.lock();
- if (!is_set || is_invalid)
- {
- if (askpassword->thread() != QThread::currentThread())
- askpassword->emit_sig();
- else
- askpassword->password_dialog();
- }
+ if (!is_set || is_invalid)
+ {
+ if (askpassword->thread() != QThread::currentThread())
+ askpassword->emit_sig();
+ else
+ askpassword->password_dialog();
+ }
- if (is_set)
- {
- strncpy(buf, current_password, size);
- buf[size - 1] = 0;
- }
+ if (is_set)
+ {
+ strncpy(buf, current_password, size);
+ buf[size - 1] = 0;
+ }
- passwd_mutex.unlock();
+ passwd_mutex.unlock();
- return is_set ? (strlen(buf)) : 0;
+ return is_set ? (strlen(buf)) : 0;
}
void AskPassword::emit_sig()
{
- emit password_requested();
+ emit password_requested();
}
void AskPassword::clear()
{
- passwd_mutex.lock();
- is_invalid = 0;
- is_set = 0;
- is_cancelled = 0;
- memset(current_password, 0, sizeof(current_password));
- passwd_mutex.unlock();
+ passwd_mutex.lock();
+ is_invalid = 0;
+ is_set = 0;
+ is_cancelled = 0;
+ memset(current_password, 0, sizeof(current_password));
+ passwd_mutex.unlock();
}
void AskPassword::setInvalidPassword()
{
- passwd_mutex.lock();
- is_invalid = 1;
- memset(current_password, 0, sizeof(current_password));
- passwd_mutex.unlock();
+ passwd_mutex.lock();
+ is_invalid = 1;
+ memset(current_password, 0, sizeof(current_password));
+ passwd_mutex.unlock();
}
void AskPassword::password_dialog()
{
- bool ok = false;
- QString title = is_invalid ? QObject::tr("Invalid passphrase, try again") : QObject::tr("Enter private key passphrase");
- QString text = QObject::tr(QString("Passphrase for account %1 \n (%2)")
- .arg(Accounts::GetCurrentAccount().name)
- .arg(Accounts::GetCurrentAccount().id.toBase64().constData()).toUtf8().constData());
- QString psw = QInputDialog::getText((QWidget*)mainwindow,title,text,QLineEdit::Password,QString(),&ok);
-
- if (ok)
- {
- strncpy(current_password, psw.toUtf8().constData(), sizeof(current_password));
- current_password[sizeof(current_password) - 1] = 0;
- is_set = 1;
- is_invalid = 0;
- }
- else
- is_cancelled = 1;
+ bool ok = false;
+ QString title = is_invalid ? QObject::tr("Invalid passphrase, try again") : QObject::tr("Enter private key passphrase");
+ QString text = QObject::tr(QString("Passphrase for account %1 \n (%2)")
+ .arg(Accounts::GetCurrentAccount().name)
+ .arg(Accounts::GetCurrentAccount().id.toBase64().constData()).toUtf8().constData());
+ QString psw = QInputDialog::getText((QWidget*)mainwindow, title, text, QLineEdit::Password, QString(), &ok);
+
+ if (ok)
+ {
+ strncpy(current_password, psw.toUtf8().constData(), sizeof(current_password));
+ current_password[sizeof(current_password) - 1] = 0;
+ is_set = 1;
+ is_invalid = 0;
+ }
+ else
+ is_cancelled = 1;
}
diff --git a/pica-client/askpassword.h b/pica-client/askpassword.h
index 9deb691..699054e 100644
--- a/pica-client/askpassword.h
+++ b/pica-client/askpassword.h
@@ -7,27 +7,27 @@
class AskPassword : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- explicit AskPassword(QObject *parent = 0);
- ~AskPassword();
- static int ask_password_cb(char *buf, int size, int rwflag, void *userdata);
- static void setInvalidPassword();
- static void clear();
+ explicit AskPassword(QObject *parent = 0);
+ ~AskPassword();
+ static int ask_password_cb(char *buf, int size, int rwflag, void *userdata);
+ static void setInvalidPassword();
+ static void clear();
private:
- void emit_sig();
- static QMutex passwd_mutex;
- static char current_password[256];
- static int is_cancelled;
- static int is_invalid;
- static int is_set;
+ void emit_sig();
+ static QMutex passwd_mutex;
+ static char current_password[256];
+ static int is_cancelled;
+ static int is_invalid;
+ static int is_set;
signals:
- void password_requested();
+ void password_requested();
public slots:
- void password_dialog();
+ void password_dialog();
};
#endif // ASKPASSWORD_H
diff --git a/pica-client/chatwindow.cpp b/pica-client/chatwindow.cpp
index 87c7193..36dc584 100644
--- a/pica-client/chatwindow.cpp
+++ b/pica-client/chatwindow.cpp
@@ -12,367 +12,370 @@
ChatWindow::ChatWindow(QByteArray peer_id) :
- QWidget(0), peer_id_(peer_id), hist(config_dbname, Accounts::GetCurrentAccount().id)
+ QWidget(0), peer_id_(peer_id), hist(config_dbname, Accounts::GetCurrentAccount().id)
{
- QVBoxLayout *layout;
+ QVBoxLayout *layout;
- set_peer_name();
- {
- Contacts ct(config_dbname, Accounts::GetCurrentAccount().id);
+ set_peer_name();
+ {
+ Contacts ct(config_dbname, Accounts::GetCurrentAccount().id);
- QList<Contacts::ContactRecord> L = ct.GetContacts(Contacts::temporary);
- addcontactquestion = false;
- for (int i = 0; i < L.size(); i++)
- {
- if (L[i].id == peer_id_)
- {
- addcontactquestion = true;
- break;
- }
- }
- }
- {
- Accounts ac(config_dbname);
- my_name_ = ac.GetName(Accounts::GetCurrentAccount().id);
+ QList<Contacts::ContactRecord> L = ct.GetContacts(Contacts::temporary);
+ addcontactquestion = false;
+ for (int i = 0; i < L.size(); i++)
+ {
+ if (L[i].id == peer_id_)
+ {
+ addcontactquestion = true;
+ break;
+ }
+ }
+ }
+ {
+ Accounts ac(config_dbname);
+ my_name_ = ac.GetName(Accounts::GetCurrentAccount().id);
- if (my_name_.isEmpty())
- my_name_ = Accounts::GetCurrentAccount().id.toBase64();
- }
+ if (my_name_.isEmpty())
+ my_name_ = Accounts::GetCurrentAccount().id.toBase64();
+ }
- layout = new QVBoxLayout;
+ layout = new QVBoxLayout;
- chatw = new QTextEdit(this);
- sendtextw = new TextSend(this);
+ chatw = new QTextEdit(this);
+ sendtextw = new TextSend(this);
- connect(sendtextw, SIGNAL(send_pressed()), this, SLOT(send_message()));
+ connect(sendtextw, SIGNAL(send_pressed()), this, SLOT(send_message()));
- sendtextw->setMinimumHeight(48);
- sendtextw->setMinimumWidth(240);
- sendtextw->setAcceptRichText(false);
+ sendtextw->setMinimumHeight(48);
+ sendtextw->setMinimumWidth(240);
+ sendtextw->setAcceptRichText(false);
- chatw->setReadOnly(true);
+ chatw->setReadOnly(true);
- layout->addWidget(chatw, 3);
- layout->addWidget(sendtextw, 1, Qt::AlignBottom);
+ layout->addWidget(chatw, 3);
+ layout->addWidget(sendtextw, 1, Qt::AlignBottom);
- if (addcontactquestion)
- {
- QHBoxLayout *hl = new QHBoxLayout();
+ if (addcontactquestion)
+ {
+ QHBoxLayout *hl = new QHBoxLayout();
- lbAddCtQuestion = new QLabel(tr("Do you want to add \"%1\" to your contact list?").arg(peer_name_));
- btAddCtYes = new QPushButton(tr("Yes"));
- btAddCtNo = new QPushButton(tr("No"));
- btAddCtBlacklist = new QPushButton(tr("Add to blacklist"));
+ lbAddCtQuestion = new QLabel(tr("Do you want to add \"%1\" to your contact list?").arg(peer_name_));
+ btAddCtYes = new QPushButton(tr("Yes"));
+ btAddCtNo = new QPushButton(tr("No"));
+ btAddCtBlacklist = new QPushButton(tr("Add to blacklist"));
- layout->insertWidget(2, lbAddCtQuestion, Qt::AlignLeft);
+ layout->insertWidget(2, lbAddCtQuestion, Qt::AlignLeft);
- hl->addWidget(btAddCtYes);
- hl->addWidget(btAddCtNo);
- hl->addWidget(btAddCtBlacklist);
+ hl->addWidget(btAddCtYes);
+ hl->addWidget(btAddCtNo);
+ hl->addWidget(btAddCtBlacklist);
- layout->insertLayout(3, hl);
+ layout->insertLayout(3, hl);
- connect(btAddCtYes, SIGNAL(clicked()), this, SLOT(addct_yes()));
- connect(btAddCtNo, SIGNAL(clicked()), this, SLOT(addct_no()));
- connect(btAddCtBlacklist, SIGNAL(clicked()), this, SLOT(addct_blacklist()));
- }
+ connect(btAddCtYes, SIGNAL(clicked()), this, SLOT(addct_yes()));
+ connect(btAddCtNo, SIGNAL(clicked()), this, SLOT(addct_no()));
+ connect(btAddCtBlacklist, SIGNAL(clicked()), this, SLOT(addct_blacklist()));
+ }
- setLayout(layout);
+ setLayout(layout);
- setWindowIcon(picapica_ico_sit);
+ setWindowIcon(picapica_ico_sit);
- QWidget::setAttribute(Qt::WA_DeleteOnClose);
- QWidget::setAttribute(Qt::WA_QuitOnClose, false);
+ QWidget::setAttribute(Qt::WA_DeleteOnClose);
+ QWidget::setAttribute(Qt::WA_QuitOnClose, false);
- menu = new QMenuBar(this);
- hist24h = new QAction(tr("Last 24 &Hours"), this);
- hist1week = new QAction(tr("Last &Week"), this);
- histAll = new QAction(tr("&All"), this);
+ menu = new QMenuBar(this);
+ hist24h = new QAction(tr("Last 24 &Hours"), this);
+ hist1week = new QAction(tr("Last &Week"), this);
+ histAll = new QAction(tr("&All"), this);
- {
- QMenu *m;
- m = menu->addMenu(tr("&History"));
- m = m->addMenu(tr("Show History"));
- m->addAction(hist24h);
- m->addAction(hist1week);
- m->addAction(histAll);
- }
- layout->insertSpacing(0, menu->size().height());
+ {
+ QMenu *m;
+ m = menu->addMenu(tr("&History"));
+ m = m->addMenu(tr("Show History"));
+ m->addAction(hist24h);
+ m->addAction(hist1week);
+ m->addAction(histAll);
+ }
+ layout->insertSpacing(0, menu->size().height());
- connect(hist24h, SIGNAL(triggered()), this, SLOT(show_history24h()));
- connect(hist1week, SIGNAL(triggered()), this, SLOT(show_history1w()));
- connect(histAll,SIGNAL(triggered()), this, SLOT(show_historyAll()));
+ connect(hist24h, SIGNAL(triggered()), this, SLOT(show_history24h()));
+ connect(hist1week, SIGNAL(triggered()), this, SLOT(show_history1w()));
+ connect(histAll, SIGNAL(triggered()), this, SLOT(show_historyAll()));
}
void ChatWindow::put_message(QString msg, QByteArray id, bool is_me)
{
- QString color, name;
- QTextCharFormat fmt;
- int pos;
-
- if (is_me)
- {
- color = "#0000ff";
- name = my_name_;
- }
- else
- {
- color = "#ff0000";
-
- if (id == peer_id_)
- name = peer_name_;
- else
- name = id.toBase64();
- }
-
- pos = draw_message(msg, name, QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"), color, false);
-
- if (is_me)
- undelivered_msgs.append(pos);
+ QString color, name;
+ QTextCharFormat fmt;
+ int pos;
+
+ if (is_me)
+ {
+ color = "#0000ff";
+ name = my_name_;
+ }
+ else
+ {
+ color = "#ff0000";
+
+ if (id == peer_id_)
+ name = peer_name_;
+ else
+ name = id.toBase64();
+ }
+
+ pos = draw_message(msg, name, QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"), color, false);
+
+ if (is_me)
+ undelivered_msgs.append(pos);
}
int ChatWindow::draw_message(QString msg, QString nickname, QString datetime, QString color, bool is_delivered)
{
- QTextCharFormat fmt;
- QString delivered_mark;
- int ret;
-
- if (is_delivered)
- delivered_mark = "+";
- else
- delivered_mark = "&nbsp;";
-
- QTextCursor c(chatw->document());
- c.movePosition(QTextCursor::End, QTextCursor::MoveAnchor);
-
- ret = c.position();
-
- chatw->moveCursor(QTextCursor::End, QTextCursor::MoveAnchor);
- fmt = chatw->currentCharFormat();
- chatw->insertHtml(
- QString("<b><font color=%1>%2(%3) %4 : </font></b>").
- arg(color).
- arg(delivered_mark).
- arg(datetime).
- arg(nickname)
- );
- chatw->setCurrentCharFormat(fmt);
- chatw->insertPlainText(msg + '\n');
-
- chatw->moveCursor(QTextCursor::End, QTextCursor::MoveAnchor);
-
- return ret;
+ QTextCharFormat fmt;
+ QString delivered_mark;
+ int ret;
+
+ if (is_delivered)
+ delivered_mark = "+";
+ else
+ delivered_mark = "&nbsp;";
+
+ QTextCursor c(chatw->document());
+ c.movePosition(QTextCursor::End, QTextCursor::MoveAnchor);
+
+ ret = c.position();
+
+ chatw->moveCursor(QTextCursor::End, QTextCursor::MoveAnchor);
+ fmt = chatw->currentCharFormat();
+ chatw->insertHtml(
+ QString("<b><font color=%1>%2(%3) %4 : </font></b>").
+ arg(color).
+ arg(delivered_mark).
+ arg(datetime).
+ arg(nickname)
+ );
+ chatw->setCurrentCharFormat(fmt);
+ chatw->insertPlainText(msg + '\n');
+
+ chatw->moveCursor(QTextCursor::End, QTextCursor::MoveAnchor);
+
+ return ret;
}
void ChatWindow::print_history(QList<History::HistoryRecord> H)
{
- chatw->clear();
-
- while(!H.isEmpty())
- {
- History::HistoryRecord r = H.takeFirst();
- QString color, name;
- QDateTime dt;
-
- if (r.is_me)
- {
- color = "#0000ff";
- name = my_name_;
- }
- else
- {
- color = "#ff0000";
-
- if (r.peer_id == peer_id_)
- name = peer_name_;
- else
- name = r.peer_id.toBase64();
- }
-
- dt.setTime_t(r.timestamp);
- //put_message(r.message, r.peer_id, r.is_me);
- draw_message(r.message, name, dt.toString("yyyy-MM-dd hh:mm:ss"), color, r.is_delivered);
- }
+ chatw->clear();
+
+ while(!H.isEmpty())
+ {
+ History::HistoryRecord r = H.takeFirst();
+ QString color, name;
+ QDateTime dt;
+
+ if (r.is_me)
+ {
+ color = "#0000ff";
+ name = my_name_;
+ }
+ else
+ {
+ color = "#ff0000";
+
+ if (r.peer_id == peer_id_)
+ name = peer_name_;
+ else
+ name = r.peer_id.toBase64();
+ }
+
+ dt.setTime_t(r.timestamp);
+ //put_message(r.message, r.peer_id, r.is_me);
+ draw_message(r.message, name, dt.toString("yyyy-MM-dd hh:mm:ss"), color, r.is_delivered);
+ }
}
void ChatWindow::msg_from_peer(QString msg)
{
- if (isMinimized())
- showNormal();
+ if (isMinimized())
+ showNormal();
- put_message(msg, peer_id_, false);
- hist.Add(peer_id_, msg, false);
+ put_message(msg, peer_id_, false);
+ hist.Add(peer_id_, msg, false);
}
void ChatWindow::msg_delivered()
{
- if (undelivered_msgs.isEmpty())
- {
- // undelivered_msgs can be empty if new chatwindow instance was created
- // and undelivered message from previous chat session is delivered
- // after that.
-
- QByteArray my_id = Accounts::GetCurrentAccount().id;
- QMap<QByteArray, QList<QString> > undl = hist.GetUndeliveredMessages();
-
- if (!undl[my_id].isEmpty())
- put_message(undl[my_id].first(), my_id , true);
- }
-
- if (!undelivered_msgs.isEmpty())
- {
- QTextCursor c(chatw->document());
- c.setPosition(undelivered_msgs.first());
- c.deleteChar();
- c.insertText("+");
- undelivered_msgs.removeFirst();
- }
-
- hist.SetDelivered(peer_id_);
+ if (undelivered_msgs.isEmpty())
+ {
+ // undelivered_msgs can be empty if new chatwindow instance was created
+ // and undelivered message from previous chat session is delivered
+ // after that.
+
+ QByteArray my_id = Accounts::GetCurrentAccount().id;
+ QMap<QByteArray, QList<QString> > undl = hist.GetUndeliveredMessages();
+
+ if (!undl[my_id].isEmpty())
+ put_message(undl[my_id].first(), my_id, true);
+ }
+
+ if (!undelivered_msgs.isEmpty())
+ {
+ QTextCursor c(chatw->document());
+ c.setPosition(undelivered_msgs.first());
+ c.deleteChar();
+ c.insertText("+");
+ undelivered_msgs.removeFirst();
+ }
+
+ hist.SetDelivered(peer_id_);
}
void ChatWindow::msg_informational(QString text)
{
- QString color;
- QTextCharFormat fmt;
+ QString color;
+ QTextCharFormat fmt;
- color = "#303030";
+ color = "#303030";
- fmt = chatw->currentCharFormat();
+ fmt = chatw->currentCharFormat();
- chatw->insertHtml(
- QString("<i><font color=%1>(%2)</font></i>").
- arg(color).
- arg(text)
- );
- chatw->insertPlainText("\n");
+ chatw->insertHtml(
+ QString("<i><font color=%1>(%2)</font></i>").
+ arg(color).
+ arg(text)
+ );
+ chatw->insertPlainText("\n");
- chatw->setCurrentCharFormat(fmt);
- chatw->moveCursor(QTextCursor::End, QTextCursor::KeepAnchor);
+ chatw->setCurrentCharFormat(fmt);
+ chatw->moveCursor(QTextCursor::End, QTextCursor::KeepAnchor);
}
bool ChatWindow::isEmptyMessage(const QString &msg) const
{
- int size = msg.size();
- for (int i = 0; i < size; ++i) {
- if (!msg.at(i).isSpace()) {
- return false;
- }
- }
- return true;
+ int size = msg.size();
+ for (int i = 0; i < size; ++i)
+ {
+ if (!msg.at(i).isSpace())
+ {
+ return false;
+ }
+ }
+ return true;
}
void ChatWindow::send_message()
{
- QString message = sendtextw->toPlainText();
- if (!isEmptyMessage(message)) {
- put_message(message, Accounts::GetCurrentAccount().id, true);
- hist.Add(peer_id_, message, true);
-
- if (!hist.isOK())
- {
- QMessageBox mbx;
- mbx.setText(hist.GetLastError());
- mbx.exec();
- }
-
- emit msg_input(message, this);
-
- sendtextw->clear();
- }
+ QString message = sendtextw->toPlainText();
+ if (!isEmptyMessage(message))
+ {
+ put_message(message, Accounts::GetCurrentAccount().id, true);
+ hist.Add(peer_id_, message, true);
+
+ if (!hist.isOK())
+ {
+ QMessageBox mbx;
+ mbx.setText(hist.GetLastError());
+ mbx.exec();
+ }
+
+ emit msg_input(message, this);
+
+ sendtextw->clear();
+ }
}
void ChatWindow::closeEvent(QCloseEvent *e)
{
- emit chatwindow_close(this);
+ emit chatwindow_close(this);
- e->accept();
+ e->accept();
}
TextSend::TextSend(QWidget *parent) :
- QTextEdit(parent)
+ QTextEdit(parent)
{
}
void TextSend::keyPressEvent(QKeyEvent *e)
{
- if (e->key() == Qt::Key_Return && e->modifiers() == Qt::NoModifier )
- {
- emit send_pressed();
- return;
- }
+ if (e->key() == Qt::Key_Return && e->modifiers() == Qt::NoModifier )
+ {
+ emit send_pressed();
+ return;
+ }
- QTextEdit::keyPressEvent(e);
+ QTextEdit::keyPressEvent(e);
}
void ChatWindow::show_history24h()
{
- print_history(hist.GetMessages(peer_id_, QDateTime::currentDateTime().addDays(-1).toTime_t(),
- QDateTime::currentDateTime().toTime_t()));
+ print_history(hist.GetMessages(peer_id_, QDateTime::currentDateTime().addDays(-1).toTime_t(),
+ QDateTime::currentDateTime().toTime_t()));
}
void ChatWindow::show_history1w()
{
- print_history(hist.GetMessages(peer_id_, QDateTime::currentDateTime().addDays(-7).toTime_t(),
- QDateTime::currentDateTime().toTime_t()));
+ print_history(hist.GetMessages(peer_id_, QDateTime::currentDateTime().addDays(-7).toTime_t(),
+ QDateTime::currentDateTime().toTime_t()));
}
void ChatWindow::show_historyAll()
{
- print_history(hist.GetMessages(peer_id_, 0, QDateTime::currentDateTime().toTime_t()));
+ print_history(hist.GetMessages(peer_id_, 0, QDateTime::currentDateTime().toTime_t()));
}
void ChatWindow::addct_yes()
{
- Contacts ct(config_dbname, Accounts::GetCurrentAccount().id);
+ Contacts ct(config_dbname, Accounts::GetCurrentAccount().id);
- ct.Add(peer_id_, Contacts::regular);
- addct_removequestion();
+ ct.Add(peer_id_, Contacts::regular);
+ addct_removequestion();
- emit contacts_update();
+ emit contacts_update();
}
void ChatWindow::addct_no()
{
- addct_removequestion();
+ addct_removequestion();
}
void ChatWindow::addct_blacklist()
{
- Contacts ct(config_dbname, Accounts::GetCurrentAccount().id);
+ Contacts ct(config_dbname, Accounts::GetCurrentAccount().id);
- ct.Add(peer_id_, Contacts::blacklisted);
- addct_removequestion();
+ ct.Add(peer_id_, Contacts::blacklisted);
+ addct_removequestion();
}
void ChatWindow::addct_removequestion()
{
- if (addcontactquestion)
- {
- delete btAddCtYes;
- delete btAddCtNo;
- delete btAddCtBlacklist;
- delete lbAddCtQuestion;
- addcontactquestion = false;
- }
+ if (addcontactquestion)
+ {
+ delete btAddCtYes;
+ delete btAddCtNo;
+ delete btAddCtBlacklist;
+ delete lbAddCtQuestion;
+ addcontactquestion = false;
+ }
}
void ChatWindow::set_peer_name()
{
- QString title;
- Contacts ct(config_dbname, Accounts::GetCurrentAccount().id);
+ QString title;
+ Contacts ct(config_dbname, Accounts::GetCurrentAccount().id);
- peer_name_ = ct.GetContactName(peer_id_);
+ peer_name_ = ct.GetContactName(peer_id_);
- title = peer_name_;
+ title = peer_name_;
- if (peer_name_.isEmpty())
- peer_name_ = peer_id_.toBase64();
+ if (peer_name_.isEmpty())
+ peer_name_ = peer_id_.toBase64();
- title = QObject::tr("Chat with ") + title + " - " + peer_id_.toBase64();
- setWindowTitle(title);
+ title = QObject::tr("Chat with ") + title + " - " + peer_id_.toBase64();
+ setWindowTitle(title);
}
diff --git a/pica-client/chatwindow.h b/pica-client/chatwindow.h
index f898aab..087b580 100644
--- a/pica-client/chatwindow.h
+++ b/pica-client/chatwindow.h
@@ -13,72 +13,75 @@
class TextSend : public QTextEdit
{
- Q_OBJECT
+ Q_OBJECT
public:
- explicit TextSend(QWidget *parent);
+ explicit TextSend(QWidget *parent);
signals:
- void send_pressed();
+ void send_pressed();
private:
- void keyPressEvent(QKeyEvent *e);
+ void keyPressEvent(QKeyEvent *e);
};
class ChatWindow : public QWidget
{
- Q_OBJECT
+ Q_OBJECT
public:
- explicit ChatWindow(QByteArray peer_id);
+ explicit ChatWindow(QByteArray peer_id);
- QByteArray getPeerId() { return peer_id_;};
+ QByteArray getPeerId()
+ {
+ return peer_id_;
+ };
signals:
- void msg_input(QString msg, ChatWindow *sender_window);
- void chatwindow_close(ChatWindow *sender_window);
- void contacts_update();
+ void msg_input(QString msg, ChatWindow *sender_window);
+ void chatwindow_close(ChatWindow *sender_window);
+ void contacts_update();
public slots:
- void msg_from_peer(QString msg);
- void msg_delivered();
- void msg_informational(QString text);//юзер в оффлайне, набирает сообщение, и т.д. серым шрифтом, курсив
- void set_peer_name();
+ void msg_from_peer(QString msg);
+ void msg_delivered();
+ void msg_informational(QString text);//юзер в оффлайне, набирает сообщение, и т.д. серым шрифтом, курсив
+ void set_peer_name();
private:
- QTextEdit *chatw;
- TextSend *sendtextw;
- QByteArray peer_id_;
- QList<int> undelivered_msgs;
- History hist;
- QMenuBar *menu;
- QAction *hist24h;
- QAction *hist1week;
- QAction *histAll;
- QString peer_name_;
- QString my_name_;
- bool addcontactquestion;
- QPushButton *btAddCtYes;
- QPushButton *btAddCtNo;
- QPushButton *btAddCtBlacklist;
- QLabel *lbAddCtQuestion;
+ QTextEdit *chatw;
+ TextSend *sendtextw;
+ QByteArray peer_id_;
+ QList<int> undelivered_msgs;
+ History hist;
+ QMenuBar *menu;
+ QAction *hist24h;
+ QAction *hist1week;
+ QAction *histAll;
+ QString peer_name_;
+ QString my_name_;
+ bool addcontactquestion;
+ QPushButton *btAddCtYes;
+ QPushButton *btAddCtNo;
+ QPushButton *btAddCtBlacklist;
+ QLabel *lbAddCtQuestion;
- bool isEmptyMessage(const QString &msg) const;
- void put_message(QString msg, QByteArray id, bool is_me);
- int draw_message(QString msg, QString nickname, QString datetime, QString color, bool is_delivered);
- void print_history(QList<History::HistoryRecord> H);
+ bool isEmptyMessage(const QString &msg) const;
+ void put_message(QString msg, QByteArray id, bool is_me);
+ int draw_message(QString msg, QString nickname, QString datetime, QString color, bool is_delivered);
+ void print_history(QList<History::HistoryRecord> H);
- void closeEvent(QCloseEvent *e);
+ void closeEvent(QCloseEvent *e);
private slots:
- void send_message();
+ void send_message();
- void show_history24h();
- void show_history1w();
- void show_historyAll();
+ void show_history24h();
+ void show_history1w();
+ void show_historyAll();
- void addct_yes();
- void addct_no();
- void addct_blacklist();
- void addct_removequestion();
+ void addct_yes();
+ void addct_no();
+ void addct_blacklist();
+ void addct_removequestion();
};
#endif // CHATWINDOW_H
diff --git a/pica-client/contactlistwidget.cpp b/pica-client/contactlistwidget.cpp
index d73a3f4..9c607ac 100644
--- a/pica-client/contactlistwidget.cpp
+++ b/pica-client/contactlistwidget.cpp
@@ -12,202 +12,202 @@
#include <QTimer>
ContactListWidget::ContactListWidget(QWidget *parent) :
- QListWidget(parent)
+ QListWidget(parent)
{
- addcontactAct = new QAction(tr("&Add Contact..."), this);
- addcontactAct->setStatusTip(tr("add new contact"));
- connect(addcontactAct,SIGNAL(triggered()),this,SLOT(add_contact()));
+ addcontactAct = new QAction(tr("&Add Contact..."), this);
+ addcontactAct->setStatusTip(tr("add new contact"));
+ connect(addcontactAct, SIGNAL(triggered()), this, SLOT(add_contact()));
- delcontactAct = new QAction(tr("&Delete Contact"),this);
- connect(delcontactAct,SIGNAL(triggered()),this,SLOT(del_contact()));
+ delcontactAct = new QAction(tr("&Delete Contact"), this);
+ connect(delcontactAct, SIGNAL(triggered()), this, SLOT(del_contact()));
- startchatAct = new QAction(tr("Start &Chat"), this);
- connect(startchatAct, SIGNAL(triggered()), this, SLOT(start_chat()));
+ startchatAct = new QAction(tr("Start &Chat"), this);
+ connect(startchatAct, SIGNAL(triggered()), this, SLOT(start_chat()));
- viewcertAct = new QAction(tr("&View Certificate"), this);
- connect(viewcertAct, SIGNAL(triggered()), this, SLOT(view_cert()));
+ viewcertAct = new QAction(tr("&View Certificate"), this);
+ connect(viewcertAct, SIGNAL(triggered()), this, SLOT(view_cert()));
- showidAct = new QAction(tr("Show Pica Pica &ID"), this);
- connect(showidAct, SIGNAL(triggered()), this, SLOT(show_id()));
+ showidAct = new QAction(tr("Show Pica Pica &ID"), this);
+ connect(showidAct, SIGNAL(triggered()), this, SLOT(show_id()));
- sendfileAct = new QAction(tr("Send &File"), this);
- connect(sendfileAct, SIGNAL(triggered()), this, SLOT(send_file()));
+ sendfileAct = new QAction(tr("Send &File"), this);
+ connect(sendfileAct, SIGNAL(triggered()), this, SLOT(send_file()));
- connect(this, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(start_chat()));
+ connect(this, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(start_chat()));
- setContactsStorage(new Contacts(config_dbname, Accounts::GetCurrentAccount().id));
+ setContactsStorage(new Contacts(config_dbname, Accounts::GetCurrentAccount().id));
}
ContactListWidget::~ContactListWidget()
{
- delete storage;
+ delete storage;
}
void ContactListWidget::contextMenuEvent(QContextMenuEvent *event)
{
- QMenu menu(this);
+ QMenu menu(this);
- if (this->itemAt(event->pos()))
- menu.addAction(delcontactAct);
+ if (this->itemAt(event->pos()))
+ menu.addAction(delcontactAct);
- menu.addAction(addcontactAct);
+ menu.addAction(addcontactAct);
- if (this->itemAt(event->pos()))
- {
- menu.addAction(startchatAct);
- menu.addAction(viewcertAct);
- menu.addAction(showidAct);
- menu.addAction(sendfileAct);
- }
- menu.exec(event->globalPos());
+ if (this->itemAt(event->pos()))
+ {
+ menu.addAction(startchatAct);
+ menu.addAction(viewcertAct);
+ menu.addAction(showidAct);
+ menu.addAction(sendfileAct);
+ }
+ menu.exec(event->globalPos());
}
void ContactListWidget::setContactsStorage(Contacts *ct)
{
- clear();
- // this->addItems(ct->GetContacts());
- storage=ct;
- contact_records=ct->GetContacts();
-
- for (int i=0;i<contact_records.size();i++)
- {
- addItem(QString("(%1...) %2").arg(contact_records[i].id.toBase64().left(8).constData()).arg(contact_records[i].name));
- wgitem_to_recs[this->item(i)]=&contact_records[i];
- this->item(i)->setStatusTip(contact_records[i].id.toBase64());
- this->item(i)->setToolTip(contact_records[i].id.toBase64().constData());
- }
+ clear();
+ // this->addItems(ct->GetContacts());
+ storage = ct;
+ contact_records = ct->GetContacts();
+
+ for (int i = 0; i < contact_records.size(); i++)
+ {
+ addItem(QString("(%1...) %2").arg(contact_records[i].id.toBase64().left(8).constData()).arg(contact_records[i].name));
+ wgitem_to_recs[this->item(i)] = &contact_records[i];
+ this->item(i)->setStatusTip(contact_records[i].id.toBase64());
+ this->item(i)->setToolTip(contact_records[i].id.toBase64().constData());
+ }
}
void ContactListWidget::add_contact()
{
- bool ok;
- QString input=QInputDialog::getText(this,tr("Add New Contact"),tr("Pica Pica ID: "),QLineEdit::Normal,NULL,&ok);
-
- if (ok && !input.isEmpty())
- {
- QByteArray user_id = QByteArray::fromBase64(input.toAscii()).left(PICA_ID_SIZE);
-
- if (user_id.size() != PICA_ID_SIZE)
- {
- QMessageBox mbx;
- mbx.setIcon(QMessageBox::Warning);
- mbx.setText(tr("Invalid user ID"));
- mbx.exec();
- return;
- }
-
- for(int i=0;i<contact_records.size();i++)
- if (contact_records[i].id==user_id)
- {
- QMessageBox mbx;
- mbx.setIcon(QMessageBox::Warning);
- mbx.setText(tr("User \"(%1) %2\" already exists").arg(user_id.toBase64().constData()).arg(contact_records[i].name));
- mbx.exec();
- return;
- }
-
- Contacts::ContactRecord r;
-
- r.id=user_id;
- r.name="";
-
- storage->Add(user_id);
-
- if (!storage->isOK())
- {
- QMessageBox mbx;
- mbx.setIcon(QMessageBox::Warning);
- mbx.setText(storage->GetLastError());
- mbx.exec();
- return;
- }
-
- addItem(QString("(%1) ").arg(user_id.toBase64().constData()));
- contact_records.append(r);
- wgitem_to_recs[this->item(this->count()-1)]=&contact_records.last();
-
- }
+ bool ok;
+ QString input = QInputDialog::getText(this, tr("Add New Contact"), tr("Pica Pica ID: "), QLineEdit::Normal, NULL, &ok);
+
+ if (ok && !input.isEmpty())
+ {
+ QByteArray user_id = QByteArray::fromBase64(input.toAscii()).left(PICA_ID_SIZE);
+
+ if (user_id.size() != PICA_ID_SIZE)
+ {
+ QMessageBox mbx;
+ mbx.setIcon(QMessageBox::Warning);
+ mbx.setText(tr("Invalid user ID"));
+ mbx.exec();
+ return;
+ }
+
+ for(int i = 0; i < contact_records.size(); i++)
+ if (contact_records[i].id == user_id)
+ {
+ QMessageBox mbx;
+ mbx.setIcon(QMessageBox::Warning);
+ mbx.setText(tr("User \"(%1) %2\" already exists").arg(user_id.toBase64().constData()).arg(contact_records[i].name));
+ mbx.exec();
+ return;
+ }
+
+ Contacts::ContactRecord r;
+
+ r.id = user_id;
+ r.name = "";
+
+ storage->Add(user_id);
+
+ if (!storage->isOK())
+ {
+ QMessageBox mbx;
+ mbx.setIcon(QMessageBox::Warning);
+ mbx.setText(storage->GetLastError());
+ mbx.exec();
+ return;
+ }
+
+ addItem(QString("(%1) ").arg(user_id.toBase64().constData()));
+ contact_records.append(r);
+ wgitem_to_recs[this->item(this->count() - 1)] = &contact_records.last();
+
+ }
}
void ContactListWidget::del_contact()
{
-QMessageBox mbx;
-mbx.setText(QString(tr("Are you sure you want to remove user \"%1\" from your contact list?")).arg(currentItem()->text()));
-mbx.setIcon(QMessageBox::Question);
-mbx.addButton(QMessageBox::Yes);
-mbx.addButton(QMessageBox::No);
-mbx.setDefaultButton(QMessageBox::No);
-
-if (QMessageBox::Yes==mbx.exec())
- {
- QByteArray rm_id;
- QListWidgetItem *rm_ptr;
-
- storage->Delete(rm_id = wgitem_to_recs[currentItem()]->id);
- delete (rm_ptr=takeItem(currentRow()));
-
- for(int i=0;i<contact_records.size();i++)
- {
- if (contact_records[i].id==rm_id)
- {
- contact_records.removeAt(i);
- break;
- }
- }
-
- wgitem_to_recs.remove(rm_ptr);
- }
+ QMessageBox mbx;
+ mbx.setText(QString(tr("Are you sure you want to remove user \"%1\" from your contact list?")).arg(currentItem()->text()));
+ mbx.setIcon(QMessageBox::Question);
+ mbx.addButton(QMessageBox::Yes);
+ mbx.addButton(QMessageBox::No);
+ mbx.setDefaultButton(QMessageBox::No);
+
+ if (QMessageBox::Yes == mbx.exec())
+ {
+ QByteArray rm_id;
+ QListWidgetItem *rm_ptr;
+
+ storage->Delete(rm_id = wgitem_to_recs[currentItem()]->id);
+ delete (rm_ptr = takeItem(currentRow()));
+
+ for(int i = 0; i < contact_records.size(); i++)
+ {
+ if (contact_records[i].id == rm_id)
+ {
+ contact_records.removeAt(i);
+ break;
+ }
+ }
+
+ wgitem_to_recs.remove(rm_ptr);
+ }
}
void ContactListWidget::start_chat()
{
- msguirouter->start_chat(wgitem_to_recs[currentItem()]->id);
+ msguirouter->start_chat(wgitem_to_recs[currentItem()]->id);
}
void ContactListWidget::view_cert()
{
- QString cert_pem = storage->GetContactCert(wgitem_to_recs[currentItem()]->id);
-
- if (!storage->isOK())
- {
- QMessageBox mbx;
- mbx.setText(storage->GetLastError());
- mbx.exec();
- }
-
- if (!cert_pem.isEmpty())
- {
- ViewCertDialog vcd;
- vcd.SetCert(cert_pem);
- vcd.exec();
- }
- else
- {
- QMessageBox mbx;
- mbx.setText(tr("Certificate is not stored for this contact yet"));
- mbx.exec();
- }
+ QString cert_pem = storage->GetContactCert(wgitem_to_recs[currentItem()]->id);
+
+ if (!storage->isOK())
+ {
+ QMessageBox mbx;
+ mbx.setText(storage->GetLastError());
+ mbx.exec();
+ }
+
+ if (!cert_pem.isEmpty())
+ {
+ ViewCertDialog vcd;
+ vcd.SetCert(cert_pem);
+ vcd.exec();
+ }
+ else
+ {
+ QMessageBox mbx;
+ mbx.setText(tr("Certificate is not stored for this contact yet"));
+ mbx.exec();
+ }
}
void ContactListWidget::show_id()
{
- ShowPicaIdDialog d(wgitem_to_recs[currentItem()]->name,
- wgitem_to_recs[currentItem()]->id,
- tr("Contact's ID"));
- d.exec();
+ ShowPicaIdDialog d(wgitem_to_recs[currentItem()]->name,
+ wgitem_to_recs[currentItem()]->id,
+ tr("Contact's ID"));
+ d.exec();
}
void ContactListWidget::Reload()
{
- setContactsStorage(storage);
+ setContactsStorage(storage);
}
void ContactListWidget::send_file()
{
- ftctrl->send_file(wgitem_to_recs[currentItem()]->id);
+ ftctrl->send_file(wgitem_to_recs[currentItem()]->id);
}
diff --git a/pica-client/contactlistwidget.h b/pica-client/contactlistwidget.h
index c23ac37..a56561d 100644
--- a/pica-client/contactlistwidget.h
+++ b/pica-client/contactlistwidget.h
@@ -9,42 +9,42 @@
class ContactListWidget : public QListWidget
{
- Q_OBJECT
+ Q_OBJECT
public:
- explicit ContactListWidget(QWidget *parent = 0);
- ~ContactListWidget();
-
- QAction *addcontactAct;
- QAction *delcontactAct;
- QAction *startchatAct;
- QAction *viewcertAct;
- QAction *showidAct;
- QAction *sendfileAct;
+ explicit ContactListWidget(QWidget *parent = 0);
+ ~ContactListWidget();
+
+ QAction *addcontactAct;
+ QAction *delcontactAct;
+ QAction *startchatAct;
+ QAction *viewcertAct;
+ QAction *showidAct;
+ QAction *sendfileAct;
protected:
- void contextMenuEvent(QContextMenuEvent *event);
+ void contextMenuEvent(QContextMenuEvent *event);
private:
- void setContactsStorage(Contacts *ct);
- Contacts* storage;
- QList<Contacts::ContactRecord> contact_records;
- QMap<QListWidgetItem*,Contacts::ContactRecord*> wgitem_to_recs;
+ void setContactsStorage(Contacts *ct);
+ Contacts* storage;
+ QList<Contacts::ContactRecord> contact_records;
+ QMap<QListWidgetItem*, Contacts::ContactRecord*> wgitem_to_recs;
- //ChatWindow *cw_debug_remove;
+ //ChatWindow *cw_debug_remove;
signals:
public slots:
- void Reload();
+ void Reload();
private slots:
- void add_contact();
- void del_contact();
- void start_chat();
- void view_cert();
- void show_id();
- void send_file();
-
- //void debug_onmsginput(QString msg, ChatWindow *sender_window);//debug remove after debug
+ void add_contact();
+ void del_contact();
+ void start_chat();
+ void view_cert();
+ void show_id();
+ void send_file();
+
+ //void debug_onmsginput(QString msg, ChatWindow *sender_window);//debug remove after debug
};
#endif // CONTACTLISTWIDGET_H
diff --git a/pica-client/contacts.cpp b/pica-client/contacts.cpp
index 0ae0338..44bce24 100644
--- a/pica-client/contacts.cpp
+++ b/pica-client/contacts.cpp
@@ -4,180 +4,180 @@
//#include <QMessageBox>
Contacts::Contacts(QString storage, QByteArray user_account_id)
- : account_id_(user_account_id)
+ : account_id_(user_account_id)
{
- dbconn=QSqlDatabase::addDatabase("QSQLITE");
- dbconn.setDatabaseName(storage);
+ dbconn = QSqlDatabase::addDatabase("QSQLITE");
+ dbconn.setDatabaseName(storage);
- if (!dbconn.open())
- {
- lasterr=dbconn.lastError();
- return;
- }
+ if (!dbconn.open())
+ {
+ lasterr = dbconn.lastError();
+ return;
+ }
//check if table contacts exists
//...
- QSqlQuery query;
+ QSqlQuery query;
- query.exec("PRAGMA foreign_keys=ON;");
+ query.exec("PRAGMA foreign_keys=ON;");
- //check result, if foreign keys support is on
+ //check result, if foreign keys support is on
}
bool Contacts::isOK()
{
- return !lasterr.isValid();
+ return !lasterr.isValid();
}
QString Contacts::GetLastError()
{
- return lasterr.text();
+ return lasterr.text();
}
bool Contacts::Exists(QByteArray id)
{
- QSqlQuery query;
+ QSqlQuery query;
- query.setForwardOnly(true);
- query.prepare("select count(*) from contacts where account_id=:account_id and id=:id");
- query.bindValue(":account_id",account_id_);
- query.bindValue(":id", id);
- query.exec();
- lasterr=query.lastError();
+ query.setForwardOnly(true);
+ query.prepare("select count(*) from contacts where account_id=:account_id and id=:id");
+ query.bindValue(":account_id", account_id_);
+ query.bindValue(":id", id);
+ query.exec();
+ lasterr = query.lastError();
- query.next();
- if (query.value(0).toInt() == 1)
- return true;
+ query.next();
+ if (query.value(0).toInt() == 1)
+ return true;
- return false;
+ return false;
}
void Contacts::Add(QByteArray id, ContactType type)
{
- QSqlQuery query;
-
- if (!Exists(id))
- {
- query.prepare("insert into contacts (id, name, cert_pem, account_id, type) values (:id, NULL, NULL, :account_id, :type)");
- query.bindValue(":id",id);
- query.bindValue(":account_id",account_id_);
- query.bindValue(":type", type);
- query.exec();
- }
- else
- {
- query.prepare("update contacts set type=:type where id=:id and account_id=:account_id");
- query.bindValue(":type", type);
- query.bindValue(":id", id);
- query.bindValue(":account_id", account_id_);
- query.exec();
- }
-
- lasterr=query.lastError();
+ QSqlQuery query;
+
+ if (!Exists(id))
+ {
+ query.prepare("insert into contacts (id, name, cert_pem, account_id, type) values (:id, NULL, NULL, :account_id, :type)");
+ query.bindValue(":id", id);
+ query.bindValue(":account_id", account_id_);
+ query.bindValue(":type", type);
+ query.exec();
+ }
+ else
+ {
+ query.prepare("update contacts set type=:type where id=:id and account_id=:account_id");
+ query.bindValue(":type", type);
+ query.bindValue(":id", id);
+ query.bindValue(":account_id", account_id_);
+ query.exec();
+ }
+
+ lasterr = query.lastError();
}
void Contacts::Delete(QByteArray id)
{
- QSqlQuery query;
+ QSqlQuery query;
- query.prepare("delete from contacts where id=:id and account_id=:account_id");
- query.bindValue(":id",id);
- query.bindValue(":account_id",account_id_);
- query.exec();
+ query.prepare("delete from contacts where id=:id and account_id=:account_id");
+ query.bindValue(":id", id);
+ query.bindValue(":account_id", account_id_);
+ query.exec();
- lasterr=query.lastError();
+ lasterr = query.lastError();
}
QList<Contacts::ContactRecord> Contacts::GetContacts(ContactType type)
{
- QList<ContactRecord> L;
- ContactRecord r;
- QSqlQuery query;
-
- query.setForwardOnly(true);
- query.prepare("select id, name from contacts where account_id=:account_id and type=:type");
- query.bindValue(":account_id",account_id_);
- query.bindValue(":type", type);
- query.exec();
- lasterr=query.lastError();
-
- if (lasterr.isValid())
- return L;
-
- while(query.next())
- {
- r.id=query.value(0).toByteArray();
- r.name=query.value(1).toString();
- //CSTRL.append(" ("+query.value(0).toString()+") "+query.value(1).toString());
- L<<r;
- }
-
- return L;
+ QList<ContactRecord> L;
+ ContactRecord r;
+ QSqlQuery query;
+
+ query.setForwardOnly(true);
+ query.prepare("select id, name from contacts where account_id=:account_id and type=:type");
+ query.bindValue(":account_id", account_id_);
+ query.bindValue(":type", type);
+ query.exec();
+ lasterr = query.lastError();
+
+ if (lasterr.isValid())
+ return L;
+
+ while(query.next())
+ {
+ r.id = query.value(0).toByteArray();
+ r.name = query.value(1).toString();
+ //CSTRL.append(" ("+query.value(0).toString()+") "+query.value(1).toString());
+ L << r;
+ }
+
+ return L;
}
QString Contacts::GetContactCert(QByteArray id)
{
- QSqlQuery query;
+ QSqlQuery query;
- query.prepare("select cert_pem from contacts where id=:id and account_id=:account_id");
- query.bindValue(":id",id);
- query.bindValue(":account_id",account_id_);
- query.exec();
+ query.prepare("select cert_pem from contacts where id=:id and account_id=:account_id");
+ query.bindValue(":id", id);
+ query.bindValue(":account_id", account_id_);
+ query.exec();
- lasterr=query.lastError();
+ lasterr = query.lastError();
- if (lasterr.isValid())
- return QString::null;
+ if (lasterr.isValid())
+ return QString::null;
- query.next();
+ query.next();
- return query.value(0).toString();
+ return query.value(0).toString();
}
QString Contacts::GetContactName(QByteArray id)
{
- QSqlQuery query;
+ QSqlQuery query;
- query.prepare("select name from contacts where id=:id and account_id=:account_id");
- query.bindValue(":id",id);
- query.bindValue(":account_id",account_id_);
- query.exec();
+ query.prepare("select name from contacts where id=:id and account_id=:account_id");
+ query.bindValue(":id", id);
+ query.bindValue(":account_id", account_id_);
+ query.exec();
- lasterr=query.lastError();
+ lasterr = query.lastError();
- if (lasterr.isValid())
- return QString::null;
+ if (lasterr.isValid())
+ return QString::null;
- query.next();
+ query.next();
- return query.value(0).toString();
+ return query.value(0).toString();
}
void Contacts::SetContactCert(QByteArray id, QString &cert_pem)
{
- QSqlQuery query;
+ QSqlQuery query;
- query.prepare("update contacts set cert_pem=:cert_pem where id=:id and account_id=:account_id");
- query.bindValue(":cert_pem",cert_pem);
- query.bindValue(":id",id);
- query.bindValue(":account_id",account_id_);
- query.exec();
+ query.prepare("update contacts set cert_pem=:cert_pem where id=:id and account_id=:account_id");
+ query.bindValue(":cert_pem", cert_pem);
+ query.bindValue(":id", id);
+ query.bindValue(":account_id", account_id_);
+ query.exec();
- lasterr=query.lastError();
+ lasterr = query.lastError();
}
void Contacts::SetContactName(QByteArray id, QString name)
{
- QSqlQuery query;
+ QSqlQuery query;
- query.prepare("update contacts set name=:name where id=:id and account_id=:account_id");
- query.bindValue(":name",name);
- query.bindValue(":id",id);
- query.bindValue(":account_id",account_id_);
- query.exec();
+ query.prepare("update contacts set name=:name where id=:id and account_id=:account_id");
+ query.bindValue(":name", name);
+ query.bindValue(":id", id);
+ query.bindValue(":account_id", account_id_);
+ query.exec();
- lasterr=query.lastError();
+ lasterr = query.lastError();
}
diff --git a/pica-client/contacts.h b/pica-client/contacts.h
index 34c7742..f8ea807 100644
--- a/pica-client/contacts.h
+++ b/pica-client/contacts.h
@@ -10,38 +10,38 @@ class Contacts
{
public:
- enum ContactType
- {
- temporary = 0,
- regular = 1,
- blacklisted = 2
- };
-
- struct ContactRecord
- {
- QByteArray id;
- QString name;
-
- ContactType type;
- };
-
- Contacts(QString storage, QByteArray user_account_id);
-
- bool Exists(QByteArray id);
- void Add(QByteArray id, ContactType type = regular);
- void Delete(QByteArray id);
- QList<ContactRecord> GetContacts(ContactType type = regular);
- QString GetContactCert(QByteArray id);
- QString GetContactName(QByteArray id);
- void SetContactCert(QByteArray id, QString &cert_pem);
- void SetContactName(QByteArray id, QString name);
- QString GetLastError();
- bool isOK();
+ enum ContactType
+ {
+ temporary = 0,
+ regular = 1,
+ blacklisted = 2
+ };
+
+ struct ContactRecord
+ {
+ QByteArray id;
+ QString name;
+
+ ContactType type;
+ };
+
+ Contacts(QString storage, QByteArray user_account_id);
+
+ bool Exists(QByteArray id);
+ void Add(QByteArray id, ContactType type = regular);
+ void Delete(QByteArray id);
+ QList<ContactRecord> GetContacts(ContactType type = regular);
+ QString GetContactCert(QByteArray id);
+ QString GetContactName(QByteArray id);
+ void SetContactCert(QByteArray id, QString &cert_pem);
+ void SetContactName(QByteArray id, QString name);
+ QString GetLastError();
+ bool isOK();
private:
- QSqlDatabase dbconn;
- QSqlError lasterr;
- QByteArray account_id_;
+ QSqlDatabase dbconn;
+ QSqlError lasterr;
+ QByteArray account_id_;
};
#endif // CONTACTS_H
diff --git a/pica-client/dhparam.cpp b/pica-client/dhparam.cpp
index 0c3af31..090d6a4 100644
--- a/pica-client/dhparam.cpp
+++ b/pica-client/dhparam.cpp
@@ -7,89 +7,89 @@ DHParam *DHParam::dhparamgenerator = NULL;
QString DHParam::current_dhparam_file;
DHParam::DHParam(QObject *parent) :
- QObject(parent)
+ QObject(parent)
{
}
bool DHParam::VerifyDefault(QString *errormsg)
{
- if (!QFile::exists(config_defaultDHParam))
- {
- if (errormsg)
- *errormsg =
- QString(tr("Diffie-Hellman parameters file \"%1\" does not exist"))
- .arg(config_defaultDHParam);
+ if (!QFile::exists(config_defaultDHParam))
+ {
+ if (errormsg)
+ *errormsg =
+ QString(tr("Diffie-Hellman parameters file \"%1\" does not exist"))
+ .arg(config_defaultDHParam);
- return false;
- }
+ return false;
+ }
- return true;
+ return true;
}
bool DHParam::VerifyGenerated(QString *errormsg)
{
- if (!QFile::exists(config_dir + QDir::separator() + PICA_CLIENT_DHPARAMFILE))
- return false;
+ if (!QFile::exists(config_dir + QDir::separator() + PICA_CLIENT_DHPARAMFILE))
+ return false;
- return true;
+ return true;
}
bool DHParam::UseDefault()
{
- return QFile::copy(config_defaultDHParam, config_dir + QDir::separator() + PICA_CLIENT_DHPARAMFILE);
+ return QFile::copy(config_defaultDHParam, config_dir + QDir::separator() + PICA_CLIENT_DHPARAMFILE);
}
bool DHParam::StartNewDHParamGeneration(QString *errormsg)
{
- if (dhparamgenerator)
- {
- if (errormsg)
- *errormsg = QString(tr("Diffie-Hellman parameter generation process is already running"));
- return false;
- }
+ if (dhparamgenerator)
+ {
+ if (errormsg)
+ *errormsg = QString(tr("Diffie-Hellman parameter generation process is already running"));
+ return false;
+ }
- dhparamgenerator = new DHParam();
+ dhparamgenerator = new DHParam();
- if (!dhparamgenerator)
- return false;
+ if (!dhparamgenerator)
+ return false;
- QString tempdhfile = config_dir + QDir::separator() + PICA_CLIENT_DHPARAMFILE + ".temp";
+ QString tempdhfile = config_dir + QDir::separator() + PICA_CLIENT_DHPARAMFILE + ".temp";
- if (QFile::exists(tempdhfile))
- QFile::remove(tempdhfile);
+ if (QFile::exists(tempdhfile))
+ QFile::remove(tempdhfile);
- return dhparamgenerator -> osslt.GenDHParamSignal(PICA_CLIENT_DHPARAMBITS,
- tempdhfile, dhparamgenerator, SLOT(DHParamGenFinished(int,QProcess::ExitStatus)));
+ return dhparamgenerator -> osslt.GenDHParamSignal(PICA_CLIENT_DHPARAMBITS,
+ tempdhfile, dhparamgenerator, SLOT(DHParamGenFinished(int, QProcess::ExitStatus)));
}
QString DHParam::GetDHParamFilename()
{
- if (current_dhparam_file.isEmpty())
- {
- if (QFile::exists(config_dir + QDir::separator() + PICA_CLIENT_DHPARAMFILE))
- current_dhparam_file = config_dir + QDir::separator() + PICA_CLIENT_DHPARAMFILE;
- else
- current_dhparam_file = config_defaultDHParam;
- }
-
- return current_dhparam_file;
+ if (current_dhparam_file.isEmpty())
+ {
+ if (QFile::exists(config_dir + QDir::separator() + PICA_CLIENT_DHPARAMFILE))
+ current_dhparam_file = config_dir + QDir::separator() + PICA_CLIENT_DHPARAMFILE;
+ else
+ current_dhparam_file = config_defaultDHParam;
+ }
+
+ return current_dhparam_file;
}
void DHParam::DHParamGenFinished(int retval, QProcess::ExitStatus)
{
- if (retval == 0)
- {
- if (QFile::exists(config_dir + QDir::separator() + PICA_CLIENT_DHPARAMFILE))
- QFile::remove(config_dir + QDir::separator() + PICA_CLIENT_DHPARAMFILE);
+ if (retval == 0)
+ {
+ if (QFile::exists(config_dir + QDir::separator() + PICA_CLIENT_DHPARAMFILE))
+ QFile::remove(config_dir + QDir::separator() + PICA_CLIENT_DHPARAMFILE);
- QFile::rename(config_dir + QDir::separator() + PICA_CLIENT_DHPARAMFILE + ".temp",
- config_dir + QDir::separator() + PICA_CLIENT_DHPARAMFILE);
+ QFile::rename(config_dir + QDir::separator() + PICA_CLIENT_DHPARAMFILE + ".temp",
+ config_dir + QDir::separator() + PICA_CLIENT_DHPARAMFILE);
- current_dhparam_file = config_dir + QDir::separator() + PICA_CLIENT_DHPARAMFILE;
+ current_dhparam_file = config_dir + QDir::separator() + PICA_CLIENT_DHPARAMFILE;
- delete dhparamgenerator;
+ delete dhparamgenerator;
- dhparamgenerator = NULL;
- }
+ dhparamgenerator = NULL;
+ }
}
diff --git a/pica-client/dhparam.h b/pica-client/dhparam.h
index 74d5309..6210c14 100644
--- a/pica-client/dhparam.h
+++ b/pica-client/dhparam.h
@@ -8,28 +8,28 @@
class DHParam : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- explicit DHParam(QObject *parent = 0);
- static bool VerifyDefault(QString *errormsg);
- static bool VerifyGenerated(QString *errormsg);
- static bool UseDefault();
- static bool StartNewDHParamGeneration(QString *errormsg);
+ explicit DHParam(QObject *parent = 0);
+ static bool VerifyDefault(QString *errormsg);
+ static bool VerifyGenerated(QString *errormsg);
+ static bool UseDefault();
+ static bool StartNewDHParamGeneration(QString *errormsg);
- static QString GetDHParamFilename();
+ static QString GetDHParamFilename();
signals:
-
+
public slots:
private:
- static DHParam *dhparamgenerator;
- static QString current_dhparam_file;
+ static DHParam *dhparamgenerator;
+ static QString current_dhparam_file;
- OpenSSLTool osslt;
+ OpenSSLTool osslt;
private slots:
- void DHParamGenFinished(int retval, QProcess::ExitStatus);
+ void DHParamGenFinished(int retval, QProcess::ExitStatus);
};
#endif // DHPARAM_H
diff --git a/pica-client/dialogs/addaccountdialog.cpp b/pica-client/dialogs/addaccountdialog.cpp
index 8d31ca4..39c2ef3 100644
--- a/pica-client/dialogs/addaccountdialog.cpp
+++ b/pica-client/dialogs/addaccountdialog.cpp
@@ -8,107 +8,107 @@
#include "../../PICA_client.h"
AddAccountDialog::AddAccountDialog(QWidget *parent) :
- QDialog(parent)
+ QDialog(parent)
{
- QGridLayout *grid = new QGridLayout(this);
+ QGridLayout *grid = new QGridLayout(this);
- QLabel *lb_cert_file = new QLabel(tr("Pica Pica Certificate File:"));
- QLabel *lb_pkey_file = new QLabel(tr("Private Key File:"));
+ QLabel *lb_cert_file = new QLabel(tr("Pica Pica Certificate File:"));
+ QLabel *lb_pkey_file = new QLabel(tr("Private Key File:"));
- btOK = new QPushButton(tr("OK"));
- btCancel = new QPushButton(tr("Cancel"));
+ btOK = new QPushButton(tr("OK"));
+ btCancel = new QPushButton(tr("Cancel"));
- cert_filename = new QLineEdit();
- pkey_filename = new QLineEdit();
+ cert_filename = new QLineEdit();
+ pkey_filename = new QLineEdit();
- bt_browse_cert = new QPushButton("...");
- bt_browse_pkey = new QPushButton("...");
+ bt_browse_cert = new QPushButton("...");
+ bt_browse_pkey = new QPushButton("...");
- rb_copyfiles = new QRadioButton(tr("Copy files to config directory"));
- rb_readinplace = new QRadioButton(tr("Read files from selected place"));
+ rb_copyfiles = new QRadioButton(tr("Copy files to config directory"));
+ rb_readinplace = new QRadioButton(tr("Read files from selected place"));
- grid->addWidget(lb_cert_file,0,0,1,1);
+ grid->addWidget(lb_cert_file, 0, 0, 1, 1);
- grid->addWidget(cert_filename,1,0,1,1);
- grid->addWidget(bt_browse_cert,1,1,1,1);
+ grid->addWidget(cert_filename, 1, 0, 1, 1);
+ grid->addWidget(bt_browse_cert, 1, 1, 1, 1);
- grid->addWidget(lb_pkey_file,2,0,1,1);
+ grid->addWidget(lb_pkey_file, 2, 0, 1, 1);
- grid->addWidget(pkey_filename,3,0,1,1);
- grid->addWidget(bt_browse_pkey,3,1,1,1);
+ grid->addWidget(pkey_filename, 3, 0, 1, 1);
+ grid->addWidget(bt_browse_pkey, 3, 1, 1, 1);
- grid->addWidget(rb_copyfiles,4,0,1,1);
- grid->addWidget(rb_readinplace,5,0,1,1);
+ grid->addWidget(rb_copyfiles, 4, 0, 1, 1);
+ grid->addWidget(rb_readinplace, 5, 0, 1, 1);
- grid->addWidget(btOK,6,0,1,1,Qt::AlignRight);
- grid->addWidget(btCancel,6,1,1,1,Qt::AlignLeft);
- //===========
- rb_copyfiles->setChecked(true);
+ grid->addWidget(btOK, 6, 0, 1, 1, Qt::AlignRight);
+ grid->addWidget(btCancel, 6, 1, 1, 1, Qt::AlignLeft);
+ //===========
+ rb_copyfiles->setChecked(true);
- btOK->setMaximumWidth(90);
- btCancel->setMaximumWidth(90);
+ btOK->setMaximumWidth(90);
+ btCancel->setMaximumWidth(90);
- connect(btOK,SIGNAL(clicked()),this,SLOT(OK()));
- connect(btCancel,SIGNAL(clicked()),this,SLOT(Cancel()));
- connect(bt_browse_cert,SIGNAL(clicked()),this,SLOT(browse_cert()));
- connect(bt_browse_pkey,SIGNAL(clicked()),this,SLOT(browse_pkey()));
+ connect(btOK, SIGNAL(clicked()), this, SLOT(OK()));
+ connect(btCancel, SIGNAL(clicked()), this, SLOT(Cancel()));
+ connect(bt_browse_cert, SIGNAL(clicked()), this, SLOT(browse_cert()));
+ connect(bt_browse_pkey, SIGNAL(clicked()), this, SLOT(browse_pkey()));
- setLayout(grid);
+ setLayout(grid);
}
void AddAccountDialog::OK()
{
- {
- QString s;
- if (!QFile::exists(s=cert_filename->text()) || !QFile::exists(s=pkey_filename->text()) )
- {
- QMessageBox mbx;
- mbx.setText(tr("File %1 does not exist").arg(s));
- mbx.exec();
- return;
- }
-
- QByteArray id(PICA_ID_SIZE, 0);
-
- if (!PICA_get_id_from_cert_file(cert_filename->text().toUtf8().constData(), (unsigned char*)id.data()))
- {
- QMessageBox mbx;
- mbx.setText(tr("Invalid certificate file"));
- mbx.exec();
- return;
- }
- }
-
- done(1);
+ {
+ QString s;
+ if (!QFile::exists(s = cert_filename->text()) || !QFile::exists(s = pkey_filename->text()) )
+ {
+ QMessageBox mbx;
+ mbx.setText(tr("File %1 does not exist").arg(s));
+ mbx.exec();
+ return;
+ }
+
+ QByteArray id(PICA_ID_SIZE, 0);
+
+ if (!PICA_get_id_from_cert_file(cert_filename->text().toUtf8().constData(), (unsigned char*)id.data()))
+ {
+ QMessageBox mbx;
+ mbx.setText(tr("Invalid certificate file"));
+ mbx.exec();
+ return;
+ }
+ }
+
+ done(1);
}
void AddAccountDialog::Cancel()
{
- done(0);
+ done(0);
}
void AddAccountDialog::browse_cert()
{
- cert_filename->setText(QFileDialog::getOpenFileName(this,tr("Select Pica Pica Certificate"),"","PEM file (*.pem)"));
+ cert_filename->setText(QFileDialog::getOpenFileName(this, tr("Select Pica Pica Certificate"), "", "PEM file (*.pem)"));
}
void AddAccountDialog::browse_pkey()
{
- pkey_filename->setText(QFileDialog::getOpenFileName(this,tr("Select Private Key"),"","PEM file (*.pem)"));
+ pkey_filename->setText(QFileDialog::getOpenFileName(this, tr("Select Private Key"), "", "PEM file (*.pem)"));
}
QString AddAccountDialog::GetCertFilename()
{
- return cert_filename->text();
+ return cert_filename->text();
}
QString AddAccountDialog::GetPkeyFilename()
{
- return pkey_filename->text();
+ return pkey_filename->text();
}
bool AddAccountDialog::isCopyFilesChecked()
{
- return rb_copyfiles->isChecked();
+ return rb_copyfiles->isChecked();
}
diff --git a/pica-client/dialogs/addaccountdialog.h b/pica-client/dialogs/addaccountdialog.h
index 976d020..2f30a93 100644
--- a/pica-client/dialogs/addaccountdialog.h
+++ b/pica-client/dialogs/addaccountdialog.h
@@ -8,33 +8,33 @@
class AddAccountDialog : public QDialog
{
- Q_OBJECT
+ Q_OBJECT
public:
- explicit AddAccountDialog(QWidget *parent = 0);
- QString GetCertFilename();
- QString GetPkeyFilename();
- bool isCopyFilesChecked();
+ explicit AddAccountDialog(QWidget *parent = 0);
+ QString GetCertFilename();
+ QString GetPkeyFilename();
+ bool isCopyFilesChecked();
private:
- QPushButton *btOK;
- QPushButton *btCancel;
+ QPushButton *btOK;
+ QPushButton *btCancel;
- QLineEdit *cert_filename;
- QLineEdit *pkey_filename;
+ QLineEdit *cert_filename;
+ QLineEdit *pkey_filename;
- QPushButton *bt_browse_cert;
- QPushButton *bt_browse_pkey;
+ QPushButton *bt_browse_cert;
+ QPushButton *bt_browse_pkey;
- QRadioButton *rb_copyfiles;
- QRadioButton *rb_readinplace;
+ QRadioButton *rb_copyfiles;
+ QRadioButton *rb_readinplace;
signals:
public slots:
private slots:
- void OK();
- void Cancel();
- void browse_cert();
- void browse_pkey();
+ void OK();
+ void Cancel();
+ void browse_cert();
+ void browse_pkey();
};
diff --git a/pica-client/dialogs/filetransferdialog.cpp b/pica-client/dialogs/filetransferdialog.cpp
index 6007c64..0f7229f 100644
--- a/pica-client/dialogs/filetransferdialog.cpp
+++ b/pica-client/dialogs/filetransferdialog.cpp
@@ -8,308 +8,308 @@
#include <stdlib.h>
FileTransferDialog::FileTransferDialog(QByteArray peer_id, QString filename, quint64 size,
- TransferDirection drct, QWidget *parent) :
- peer_id_(peer_id),
- QDialog(parent),
- dir_(drct),
- filename_(filename),
- filesize_(size)
+ TransferDirection drct, QWidget *parent) :
+ peer_id_(peer_id),
+ QDialog(parent),
+ dir_(drct),
+ filename_(filename),
+ filesize_(size)
{
- Contacts ct(config_dbname, Accounts::GetCurrentAccount().id);
- peer_name_ = ct.GetContactName(peer_id_);
-
- if (peer_name_.isEmpty())
- peer_name_ = peer_id_.toBase64();
- else
- peer_name_ = QString("%1 (%2...)").arg(peer_name_).arg(peer_id_.toBase64().left(8).constData());
-
- QVBoxLayout *layout = new QVBoxLayout(this);
- QHBoxLayout *btlayout = new QHBoxLayout();
-
- lbFilename = new QLabel(this);
- lbPeer = new QLabel(this);
- lbProgressStatus = new QLabel(this);
- lbTransferSpeed = new QLabel(this);
- lbRemainingTime = new QLabel(this);
- lbTransferStatus = new QLabel(this);
-
- pgbar = new QProgressBar(this);
- leftbutton = new QPushButton(this);
- rightbutton = new QPushButton(this);
-
- layout->addWidget(lbFilename);
- layout->addWidget(lbPeer);
- layout->addWidget(lbProgressStatus);
- layout->addWidget(lbTransferSpeed);
- layout->addWidget(lbRemainingTime);
- layout->addWidget(pgbar);
- layout->addWidget(lbTransferStatus);
- layout->addLayout(btlayout);
-
- btlayout->addWidget(leftbutton);
- btlayout->addWidget(rightbutton);
-
- if (drct == RECEIVING)
- {
- leftbutton->setText(tr("Accept"));
- rightbutton->setText(tr("Deny"));
-
- lbPeer->setText("Sender: " + peer_name_);
-
- setWindowTitle(tr("Receiving file %1 from %2").arg(filename_).arg(peer_name_));
- }
- else if (drct == SENDING)
- {
- leftbutton->setText(tr("Pause"));
- rightbutton->setText(tr("Cancel"));
- leftbutton->setEnabled(false);
-
- lbPeer->setText("Receiver: " + peer_name_);
-
- setWindowTitle(tr("Sending file %1 to %2").arg(filename_).arg(peer_name_));
- }
- setTransferStatus(WAITINGFORACCEPT);
-
- lbFilename->setText(filename_);
-
- pgbar->setMinimum(0);
- pgbar->setMaximum(100);
-
- update(0);
-
- timer = new QTimer(this);
- connect(timer, SIGNAL(timeout()), this, SLOT(timeout()));
- timer->start(1000);
- progress_ = 0;
- prevprogress_ = 0;
-
- connect(leftbutton, SIGNAL(clicked()), this, SLOT(leftbuttonclick()));
- connect(rightbutton, SIGNAL(clicked()), this, SLOT(rightbuttonclick()));
+ Contacts ct(config_dbname, Accounts::GetCurrentAccount().id);
+ peer_name_ = ct.GetContactName(peer_id_);
+
+ if (peer_name_.isEmpty())
+ peer_name_ = peer_id_.toBase64();
+ else
+ peer_name_ = QString("%1 (%2...)").arg(peer_name_).arg(peer_id_.toBase64().left(8).constData());
+
+ QVBoxLayout *layout = new QVBoxLayout(this);
+ QHBoxLayout *btlayout = new QHBoxLayout();
+
+ lbFilename = new QLabel(this);
+ lbPeer = new QLabel(this);
+ lbProgressStatus = new QLabel(this);
+ lbTransferSpeed = new QLabel(this);
+ lbRemainingTime = new QLabel(this);
+ lbTransferStatus = new QLabel(this);
+
+ pgbar = new QProgressBar(this);
+ leftbutton = new QPushButton(this);
+ rightbutton = new QPushButton(this);
+
+ layout->addWidget(lbFilename);
+ layout->addWidget(lbPeer);
+ layout->addWidget(lbProgressStatus);
+ layout->addWidget(lbTransferSpeed);
+ layout->addWidget(lbRemainingTime);
+ layout->addWidget(pgbar);
+ layout->addWidget(lbTransferStatus);
+ layout->addLayout(btlayout);
+
+ btlayout->addWidget(leftbutton);
+ btlayout->addWidget(rightbutton);
+
+ if (drct == RECEIVING)
+ {
+ leftbutton->setText(tr("Accept"));
+ rightbutton->setText(tr("Deny"));
+
+ lbPeer->setText("Sender: " + peer_name_);
+
+ setWindowTitle(tr("Receiving file %1 from %2").arg(filename_).arg(peer_name_));
+ }
+ else if (drct == SENDING)
+ {
+ leftbutton->setText(tr("Pause"));
+ rightbutton->setText(tr("Cancel"));
+ leftbutton->setEnabled(false);
+
+ lbPeer->setText("Receiver: " + peer_name_);
+
+ setWindowTitle(tr("Sending file %1 to %2").arg(filename_).arg(peer_name_));
+ }
+ setTransferStatus(WAITINGFORACCEPT);
+
+ lbFilename->setText(filename_);
+
+ pgbar->setMinimum(0);
+ pgbar->setMaximum(100);
+
+ update(0);
+
+ timer = new QTimer(this);
+ connect(timer, SIGNAL(timeout()), this, SLOT(timeout()));
+ timer->start(1000);
+ progress_ = 0;
+ prevprogress_ = 0;
+
+ connect(leftbutton, SIGNAL(clicked()), this, SLOT(leftbuttonclick()));
+ connect(rightbutton, SIGNAL(clicked()), this, SLOT(rightbuttonclick()));
}
void FileTransferDialog::update(quint64 progress)
{
- progress_ = progress;
- percents = (double)progress / filesize_ * 100.0;
+ progress_ = progress;
+ percents = (double)progress / filesize_ * 100.0;
- lbProgressStatus->setText(bytestoHumanBase2(progress) + " / "
- + bytestoHumanBase2(filesize_) + QString(" %1 %").arg((int)percents));
+ lbProgressStatus->setText(bytestoHumanBase2(progress) + " / "
+ + bytestoHumanBase2(filesize_) + QString(" %1 %").arg((int)percents));
- pgbar->setValue(percents);
+ pgbar->setValue(percents);
- if (progress == filesize_)
- {
- setTransferStatus(FINISHED);
- }
+ if (progress == filesize_)
+ {
+ setTransferStatus(FINISHED);
+ }
}
void FileTransferDialog::setTransferStatus(TransferStatus st)
{
- bool isTerminalState = false;
-
- switch(st)
- {
- case WAITINGFORACCEPT:
- if (dir_ == SENDING)
- lbTransferStatus->setText(tr("Waiting for peer to accept the file"));
- else
- lbTransferStatus->setText(tr("Waiting for acceptance"));
- break;
-
- case DENIED:
- lbTransferStatus->setText(tr("Denied by peer"));
- isTerminalState = true;
- break;
-
- case SENDINGFILE:
- leftbutton->setEnabled(true);
- lbTransferStatus->setText(tr("Sending file"));
- break;
-
- case RECEIVINGFILE:
- lbTransferStatus->setText(tr("Receiving file"));
- break;
-
- case PAUSED:
- lbTransferStatus->setText(tr("Paused"));
- break;
-
- case CANCELLED:
- lbTransferStatus->setText(tr("Cancelled"));
- isTerminalState = true;
- break;
-
- case FINISHED:
- lbTransferStatus->setText(tr("Finished"));
- isTerminalState = true;
- break;
-
- case PEERDISCONNECTED:
- lbTransferStatus->setText(tr("Peer disconnected"));
- isTerminalState = true;
- break;
-
- case IOERROR:
- lbTransferStatus->setText(tr("I/O error"));
- isTerminalState = true;
- break;
- }
-
- if (isTerminalState)
- {
- leftbutton->setEnabled(false);
- rightbutton->setEnabled(false);
-
- QWidget::setAttribute(Qt::WA_DeleteOnClose);
- QWidget::setAttribute(Qt::WA_QuitOnClose, false);
- }
+ bool isTerminalState = false;
+
+ switch(st)
+ {
+ case WAITINGFORACCEPT:
+ if (dir_ == SENDING)
+ lbTransferStatus->setText(tr("Waiting for peer to accept the file"));
+ else
+ lbTransferStatus->setText(tr("Waiting for acceptance"));
+ break;
+
+ case DENIED:
+ lbTransferStatus->setText(tr("Denied by peer"));
+ isTerminalState = true;
+ break;
+
+ case SENDINGFILE:
+ leftbutton->setEnabled(true);
+ lbTransferStatus->setText(tr("Sending file"));
+ break;
+
+ case RECEIVINGFILE:
+ lbTransferStatus->setText(tr("Receiving file"));
+ break;
+
+ case PAUSED:
+ lbTransferStatus->setText(tr("Paused"));
+ break;
+
+ case CANCELLED:
+ lbTransferStatus->setText(tr("Cancelled"));
+ isTerminalState = true;
+ break;
+
+ case FINISHED:
+ lbTransferStatus->setText(tr("Finished"));
+ isTerminalState = true;
+ break;
+
+ case PEERDISCONNECTED:
+ lbTransferStatus->setText(tr("Peer disconnected"));
+ isTerminalState = true;
+ break;
+
+ case IOERROR:
+ lbTransferStatus->setText(tr("I/O error"));
+ isTerminalState = true;
+ break;
+ }
+
+ if (isTerminalState)
+ {
+ leftbutton->setEnabled(false);
+ rightbutton->setEnabled(false);
+
+ QWidget::setAttribute(Qt::WA_DeleteOnClose);
+ QWidget::setAttribute(Qt::WA_QuitOnClose, false);
+ }
}
void FileTransferDialog::pausedByPeer()
{
- leftbutton->setEnabled(false);
- setTransferStatus(PAUSED);
+ leftbutton->setEnabled(false);
+ setTransferStatus(PAUSED);
}
void FileTransferDialog::resumedByPeer()
{
- leftbutton->setEnabled(true);
- setTransferStatus( dir_ == SENDING ? SENDINGFILE : RECEIVINGFILE);
+ leftbutton->setEnabled(true);
+ setTransferStatus( dir_ == SENDING ? SENDINGFILE : RECEIVINGFILE);
}
void FileTransferDialog::cancelledByPeer()
{
- setTransferStatus(CANCELLED);
+ setTransferStatus(CANCELLED);
}
void FileTransferDialog::ioError()
{
- setTransferStatus(IOERROR);
+ setTransferStatus(IOERROR);
}
void FileTransferDialog::peerDisconnected()
{
- setTransferStatus(PEERDISCONNECTED);
+ setTransferStatus(PEERDISCONNECTED);
}
void FileTransferDialog::leftbuttonclick()
{
- if (dir_ == RECEIVING)
- {
- if (leftbutton->text() == tr("Accept"))
- {
- leftbutton->setText("Pause");
- rightbutton->setText("Cancel");
- emit acceptedFile(peer_id_);
- return;
- }
- }
-
- if (leftbutton->text() == tr("Pause"))
- {
- leftbutton->setText(tr("Resume"));
- emit pausedFile(peer_id_, this);
- setTransferStatus(PAUSED);
- }
- else if (leftbutton->text() == tr("Resume"))
- {
- leftbutton->setText(tr("Pause"));
- emit resumedFile(peer_id_, this);
- setTransferStatus(dir_ == SENDING ? SENDINGFILE : RECEIVINGFILE);
- }
+ if (dir_ == RECEIVING)
+ {
+ if (leftbutton->text() == tr("Accept"))
+ {
+ leftbutton->setText("Pause");
+ rightbutton->setText("Cancel");
+ emit acceptedFile(peer_id_);
+ return;
+ }
+ }
+
+ if (leftbutton->text() == tr("Pause"))
+ {
+ leftbutton->setText(tr("Resume"));
+ emit pausedFile(peer_id_, this);
+ setTransferStatus(PAUSED);
+ }
+ else if (leftbutton->text() == tr("Resume"))
+ {
+ leftbutton->setText(tr("Pause"));
+ emit resumedFile(peer_id_, this);
+ setTransferStatus(dir_ == SENDING ? SENDINGFILE : RECEIVINGFILE);
+ }
}
void FileTransferDialog::rightbuttonclick()
{
- if (dir_ == RECEIVING)
- {
- if (rightbutton->text() == tr("Deny"))
- {
- emit deniedFile(peer_id_);
- setTransferStatus(DENIED);
- return;
- }
- }
-
- if (rightbutton->text() == tr("Cancel"))
- {
-
- if (QMessageBox::No == QMessageBox::question(this, tr("Cancel File Transfer"),
- tr("Are you sure you want to cancel file transfer?"),
- QMessageBox::Yes | QMessageBox::No, QMessageBox::No))
- return;
-
- emit cancelledFile(peer_id_, this);
- setTransferStatus(CANCELLED);
- }
+ if (dir_ == RECEIVING)
+ {
+ if (rightbutton->text() == tr("Deny"))
+ {
+ emit deniedFile(peer_id_);
+ setTransferStatus(DENIED);
+ return;
+ }
+ }
+
+ if (rightbutton->text() == tr("Cancel"))
+ {
+
+ if (QMessageBox::No == QMessageBox::question(this, tr("Cancel File Transfer"),
+ tr("Are you sure you want to cancel file transfer?"),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No))
+ return;
+
+ emit cancelledFile(peer_id_, this);
+ setTransferStatus(CANCELLED);
+ }
}
QString FileTransferDialog::bytestoHumanBase2(quint64 bytes)
{
- const char* units[] = {"B", "KiB", "MiB", "GiB", "TiB", "PiB"};
- int i = 0;
- double size = bytes;
+ const char* units[] = {"B", "KiB", "MiB", "GiB", "TiB", "PiB"};
+ int i = 0;
+ double size = bytes;
- while (size > 1024)
- {
- size /= 1024;
- i++;
- }
+ while (size > 1024)
+ {
+ size /= 1024;
+ i++;
+ }
- return QString("%1 %2").arg(size, 6, 'f', i ? 2 : 0).arg(units[i]);
+ return QString("%1 %2").arg(size, 6, 'f', i ? 2 : 0).arg(units[i]);
}
QString FileTransferDialog::bytestoHumanBase10(quint64 bytes)
{
- const char* units[] = {"B", "kB", "MB", "GB", "TB", "PB"};
- int i = 0;
- double size = bytes;
+ const char* units[] = {"B", "kB", "MB", "GB", "TB", "PB"};
+ int i = 0;
+ double size = bytes;
- while (size > 1000)
- {
- size /= 1000;
- i++;
- }
+ while (size > 1000)
+ {
+ size /= 1000;
+ i++;
+ }
- return QString("%1 %2").arg(size, 6, 'f', i ? 2 : 0).arg(units[i]);
+ return QString("%1 %2").arg(size, 6, 'f', i ? 2 : 0).arg(units[i]);
}
QString FileTransferDialog::timeLeft(quint64 seconds)
{
- if (seconds < 60)
- {
- return QString(tr("%1 seconds")).arg(seconds);
- }
+ if (seconds < 60)
+ {
+ return QString(tr("%1 seconds")).arg(seconds);
+ }
- int minutes = seconds/60;
- int hours = minutes/60;
- double days = (double)hours/24.0;
+ int minutes = seconds / 60;
+ int hours = minutes / 60;
+ double days = (double)hours / 24.0;
- if (days > 1.0 )
- return QString(tr("%1 days")).arg(days, 6, 'f', 1);
+ if (days > 1.0 )
+ return QString(tr("%1 days")).arg(days, 6, 'f', 1);
- if (hours > 0)
- return QString("%1h:%2m").arg(hours).arg(minutes % 60);
+ if (hours > 0)
+ return QString("%1h:%2m").arg(hours).arg(minutes % 60);
- return QString("%1:%2").arg(minutes).arg((double)(seconds % 60), 2, 'f', 0, '0');
+ return QString("%1:%2").arg(minutes).arg((double)(seconds % 60), 2, 'f', 0, '0');
}
void FileTransferDialog::timeout()
{
- if (progress_ >= filesize_)
- return;
+ if (progress_ >= filesize_)
+ return;
- quint64 bps = progress_ - prevprogress_;
- prevprogress_ = progress_;
+ quint64 bps = progress_ - prevprogress_;
+ prevprogress_ = progress_;
- if (bps != 0)
- {
- quint64 secondsleft = (filesize_ - progress_)/bps;
+ if (bps != 0)
+ {
+ quint64 secondsleft = (filesize_ - progress_) / bps;
- lbRemainingTime->setText(timeLeft(secondsleft));
- }
- else
- lbRemainingTime->setText(QString());
+ lbRemainingTime->setText(timeLeft(secondsleft));
+ }
+ else
+ lbRemainingTime->setText(QString());
- lbTransferSpeed->setText(bytestoHumanBase10(bps) + tr("/s"));
+ lbTransferSpeed->setText(bytestoHumanBase10(bps) + tr("/s"));
}
diff --git a/pica-client/dialogs/filetransferdialog.h b/pica-client/dialogs/filetransferdialog.h
index 952b450..822dcf5 100644
--- a/pica-client/dialogs/filetransferdialog.h
+++ b/pica-client/dialogs/filetransferdialog.h
@@ -10,79 +10,82 @@
class FileTransferDialog : public QDialog
{
- Q_OBJECT
+ Q_OBJECT
public:
- enum TransferDirection
- {
- SENDING,
- RECEIVING
- };
+ enum TransferDirection
+ {
+ SENDING,
+ RECEIVING
+ };
- enum TransferStatus
- {
- WAITINGFORACCEPT,
- DENIED,
- SENDINGFILE,
- RECEIVINGFILE,
- PAUSED,
- CANCELLED,
- PEERDISCONNECTED,
- IOERROR,
- FINISHED
- };
+ enum TransferStatus
+ {
+ WAITINGFORACCEPT,
+ DENIED,
+ SENDINGFILE,
+ RECEIVINGFILE,
+ PAUSED,
+ CANCELLED,
+ PEERDISCONNECTED,
+ IOERROR,
+ FINISHED
+ };
- explicit FileTransferDialog(QByteArray peer_id, QString filename, quint64 size,
- TransferDirection drct, QWidget *parent = 0);
+ explicit FileTransferDialog(QByteArray peer_id, QString filename, quint64 size,
+ TransferDirection drct, QWidget *parent = 0);
- TransferDirection getTransferDirection() {return dir_;};
+ TransferDirection getTransferDirection()
+ {
+ return dir_;
+ };
private:
- QLabel *lbFilename;
- QLabel *lbPeer;
- QLabel *lbProgressStatus;
- QLabel *lbTransferSpeed;
- QLabel *lbRemainingTime;
- QLabel *lbTransferStatus;
- QProgressBar *pgbar;
- QPushButton *leftbutton;
- QPushButton *rightbutton;
+ QLabel *lbFilename;
+ QLabel *lbPeer;
+ QLabel *lbProgressStatus;
+ QLabel *lbTransferSpeed;
+ QLabel *lbRemainingTime;
+ QLabel *lbTransferStatus;
+ QProgressBar *pgbar;
+ QPushButton *leftbutton;
+ QPushButton *rightbutton;
- QByteArray peer_id_;
- QString peer_name_;
- TransferDirection dir_;
- QString filename_;
- quint64 filesize_;
+ QByteArray peer_id_;
+ QString peer_name_;
+ TransferDirection dir_;
+ QString filename_;
+ quint64 filesize_;
- double percents;
- quint64 progress_;
- quint64 prevprogress_;
+ double percents;
+ quint64 progress_;
+ quint64 prevprogress_;
- static QString bytestoHumanBase2(quint64 bytes);
- static QString bytestoHumanBase10(quint64 bytes);
- static QString timeLeft(quint64 seconds);
+ static QString bytestoHumanBase2(quint64 bytes);
+ static QString bytestoHumanBase10(quint64 bytes);
+ static QString timeLeft(quint64 seconds);
- QTimer *timer;
+ QTimer *timer;
signals:
- void pausedFile(QByteArray peer_id, FileTransferDialog *sender);
- void resumedFile(QByteArray peer_id, FileTransferDialog *sender);
- void cancelledFile(QByteArray peer_id, FileTransferDialog *sender);
- void acceptedFile(QByteArray peer_id);
- void deniedFile(QByteArray peer_id);
+ void pausedFile(QByteArray peer_id, FileTransferDialog *sender);
+ void resumedFile(QByteArray peer_id, FileTransferDialog *sender);
+ void cancelledFile(QByteArray peer_id, FileTransferDialog *sender);
+ void acceptedFile(QByteArray peer_id);
+ void deniedFile(QByteArray peer_id);
public slots:
- void update(quint64 progress);
- void setTransferStatus(enum TransferStatus st);
- void pausedByPeer();
- void resumedByPeer();
- void cancelledByPeer();
- void ioError();
- void peerDisconnected();
+ void update(quint64 progress);
+ void setTransferStatus(enum TransferStatus st);
+ void pausedByPeer();
+ void resumedByPeer();
+ void cancelledByPeer();
+ void ioError();
+ void peerDisconnected();
private slots:
- void timeout();
- void leftbuttonclick();
- void rightbuttonclick();
+ void timeout();
+ void leftbuttonclick();
+ void rightbuttonclick();
};
diff --git a/pica-client/dialogs/forgedcertdialog.cpp b/pica-client/dialogs/forgedcertdialog.cpp
index ccf144f..54244a2 100644
--- a/pica-client/dialogs/forgedcertdialog.cpp
+++ b/pica-client/dialogs/forgedcertdialog.cpp
@@ -4,50 +4,50 @@
#include <QLabel>
ForgedCertDialog::ForgedCertDialog(QByteArray peer_id, QString received_cert, QString stored_cert, QWidget *parent) :
- QDialog(parent),
- received_cert_(received_cert),
- stored_cert_(stored_cert)
+ QDialog(parent),
+ received_cert_(received_cert),
+ stored_cert_(stored_cert)
{
- QGridLayout *grid = new QGridLayout(this);
+ QGridLayout *grid = new QGridLayout(this);
- QLabel *scary_text = new QLabel(tr(
-"Previously stored and currently present certificates for user %1 do not match.\n\
+ QLabel *scary_text = new QLabel(tr(
+ "Previously stored and currently present certificates for user %1 do not match.\n\
This means that probably someone is trying to eavesdrop your communication\n\
using man-in-the-middle attack or impersonate the user.\n\
Connection aborted.").arg(peer_id.toBase64().constData()));
- btOK = new QPushButton(tr("OK"));
- btShow_stored_cert = new QPushButton(tr("View Stored Certificate..."));
- btShow_received_cert = new QPushButton(tr("View Received Certificate..."));
+ btOK = new QPushButton(tr("OK"));
+ btShow_stored_cert = new QPushButton(tr("View Stored Certificate..."));
+ btShow_received_cert = new QPushButton(tr("View Received Certificate..."));
- grid->addWidget(scary_text, 0,0, 1, 3, Qt::AlignCenter);
- grid->addWidget(btShow_stored_cert, 1, 0, Qt::AlignCenter);
- grid->addWidget(btShow_received_cert, 1, 2, Qt::AlignCenter);
- grid->addWidget(btOK, 2, 1, Qt::AlignCenter);
+ grid->addWidget(scary_text, 0, 0, 1, 3, Qt::AlignCenter);
+ grid->addWidget(btShow_stored_cert, 1, 0, Qt::AlignCenter);
+ grid->addWidget(btShow_received_cert, 1, 2, Qt::AlignCenter);
+ grid->addWidget(btOK, 2, 1, Qt::AlignCenter);
- setLayout(grid);
+ setLayout(grid);
- connect(btOK, SIGNAL(clicked()), this, SLOT(OK()));
- connect(btShow_stored_cert, SIGNAL(clicked()), this, SLOT(StoredCert()));
- connect(btShow_received_cert, SIGNAL(clicked()), this, SLOT(ReceivedCert()));
+ connect(btOK, SIGNAL(clicked()), this, SLOT(OK()));
+ connect(btShow_stored_cert, SIGNAL(clicked()), this, SLOT(StoredCert()));
+ connect(btShow_received_cert, SIGNAL(clicked()), this, SLOT(ReceivedCert()));
}
void ForgedCertDialog::OK()
{
- done(0);
+ done(0);
}
void ForgedCertDialog::ReceivedCert()
{
- ViewCertDialog vcd;
- vcd.SetCert(received_cert_);
- vcd.exec();
+ ViewCertDialog vcd;
+ vcd.SetCert(received_cert_);
+ vcd.exec();
}
void ForgedCertDialog::StoredCert()
{
- ViewCertDialog vcd;
- vcd.SetCert(stored_cert_);
- vcd.exec();
+ ViewCertDialog vcd;
+ vcd.SetCert(stored_cert_);
+ vcd.exec();
}
diff --git a/pica-client/dialogs/forgedcertdialog.h b/pica-client/dialogs/forgedcertdialog.h
index 5386f14..08f5d42 100644
--- a/pica-client/dialogs/forgedcertdialog.h
+++ b/pica-client/dialogs/forgedcertdialog.h
@@ -7,28 +7,28 @@
class ForgedCertDialog : public QDialog
{
- Q_OBJECT
+ Q_OBJECT
public:
- explicit ForgedCertDialog(QByteArray peer_id, QString received_cert, QString stored_cert, QWidget *parent = 0);
+ explicit ForgedCertDialog(QByteArray peer_id, QString received_cert, QString stored_cert, QWidget *parent = 0);
private:
- QString received_cert_;
- QString stored_cert_;
+ QString received_cert_;
+ QString stored_cert_;
+
+ QPushButton *btOK;
+ QPushButton *btShow_stored_cert;
+ QPushButton *btShow_received_cert;
- QPushButton *btOK;
- QPushButton *btShow_stored_cert;
- QPushButton *btShow_received_cert;
-
signals:
-
+
public slots:
private slots:
- void OK();
- void StoredCert();
- void ReceivedCert();
-
+ void OK();
+ void StoredCert();
+ void ReceivedCert();
+
};
#endif // FORGEDCERTDIALOG_H
diff --git a/pica-client/dialogs/registeraccountdialog.cpp b/pica-client/dialogs/registeraccountdialog.cpp
index e3600ed..090cfe3 100644
--- a/pica-client/dialogs/registeraccountdialog.cpp
+++ b/pica-client/dialogs/registeraccountdialog.cpp
@@ -6,102 +6,102 @@
RegisterAccountDialog::RegisterAccountDialog(QWidget *parent) :
- QDialog(parent)
+ QDialog(parent)
{
- QVBoxLayout *layout = new QVBoxLayout(this);
-
- QLabel *lbNickname = new QLabel(tr("Name:"));
- lbPassword = new QLabel(tr("Password:"));
- lbRepeatPassword = new QLabel(tr("Repeat password:"));
-
- nickname = new QLineEdit();
- btRegister = new QPushButton(tr("Create"));
-
- #ifndef WIN32
- cbUseDevRandom = new QCheckBox(tr("Use /dev/random as a random data source"));
- #endif
-
- cbSetPassword = new QCheckBox(tr("Set passphrase for the secret key"));
- password = new QLineEdit();
- repeatPassword = new QLineEdit();
- lbStatus = new QLabel(tr("Enter your name and press\n \"Create\" to create new Pica Pica certificate"));
- //btOK = new QPushButton(tr("OK"));
-
- password->setEchoMode(QLineEdit::Password);
- repeatPassword->setEchoMode(QLineEdit::Password);
-
- {
- QFont f;
- f= lbStatus->font();
- f.setBold(true);
- lbStatus->setFont(f);
- }
-
- layout->addWidget(lbNickname);
- layout->addWidget(nickname);
- #ifndef WIN32
- layout->addWidget(cbUseDevRandom);
- #endif
- layout->addWidget(cbSetPassword);
- layout->addWidget(lbPassword);
- layout->addWidget(password);
- layout->addWidget(lbRepeatPassword);
- layout->addWidget(repeatPassword);
- layout->addWidget(btRegister);
- layout->addWidget(lbStatus);
- //layout->addWidget(btOK);
-
- setLayout(layout);
-
- vld = new QRegExpValidator(QRegExp("[^\\#\\$&\"\'=\\(\\)\\\\/\\|`!<>\\{\\}\\[\\]\\+]+"), this);
- nickname->setValidator(vld);
-
- //connect(btOK, SIGNAL(clicked()), this, SLOT(OK()));
- connect(btRegister, SIGNAL(clicked()), this, SLOT(Register()));
- connect(cbSetPassword, SIGNAL(clicked()), this, SLOT(setPasswordClick()));
- #ifndef WIN32
- connect(cbUseDevRandom, SIGNAL(clicked()), this, SLOT(useDevRandomClick()));
- #endif
-
- setPasswordClick();
+ QVBoxLayout *layout = new QVBoxLayout(this);
+
+ QLabel *lbNickname = new QLabel(tr("Name:"));
+ lbPassword = new QLabel(tr("Password:"));
+ lbRepeatPassword = new QLabel(tr("Repeat password:"));
+
+ nickname = new QLineEdit();
+ btRegister = new QPushButton(tr("Create"));
+
+#ifndef WIN32
+ cbUseDevRandom = new QCheckBox(tr("Use /dev/random as a random data source"));
+#endif
+
+ cbSetPassword = new QCheckBox(tr("Set passphrase for the secret key"));
+ password = new QLineEdit();
+ repeatPassword = new QLineEdit();
+ lbStatus = new QLabel(tr("Enter your name and press\n \"Create\" to create new Pica Pica certificate"));
+ //btOK = new QPushButton(tr("OK"));
+
+ password->setEchoMode(QLineEdit::Password);
+ repeatPassword->setEchoMode(QLineEdit::Password);
+
+ {
+ QFont f;
+ f = lbStatus->font();
+ f.setBold(true);
+ lbStatus->setFont(f);
+ }
+
+ layout->addWidget(lbNickname);
+ layout->addWidget(nickname);
+#ifndef WIN32
+ layout->addWidget(cbUseDevRandom);
+#endif
+ layout->addWidget(cbSetPassword);
+ layout->addWidget(lbPassword);
+ layout->addWidget(password);
+ layout->addWidget(lbRepeatPassword);
+ layout->addWidget(repeatPassword);
+ layout->addWidget(btRegister);
+ layout->addWidget(lbStatus);
+ //layout->addWidget(btOK);
+
+ setLayout(layout);
+
+ vld = new QRegExpValidator(QRegExp("[^\\#\\$&\"\'=\\(\\)\\\\/\\|`!<>\\{\\}\\[\\]\\+]+"), this);
+ nickname->setValidator(vld);
+
+ //connect(btOK, SIGNAL(clicked()), this, SLOT(OK()));
+ connect(btRegister, SIGNAL(clicked()), this, SLOT(Register()));
+ connect(cbSetPassword, SIGNAL(clicked()), this, SLOT(setPasswordClick()));
+#ifndef WIN32
+ connect(cbUseDevRandom, SIGNAL(clicked()), this, SLOT(useDevRandomClick()));
+#endif
+
+ setPasswordClick();
}
void RegisterAccountDialog::useDevRandomClick()
{
#ifndef WIN32
- if (cbUseDevRandom->isChecked())
- {
- QMessageBox mbx;
- mbx.setText(tr("Using /dev/random is more preferable for generating long-term high-value cryptographic keys, but it can take 5 - 10 minutes to collect required amount of entropy. You'll have to press random keys on keyboard and move mouse randomly to provide random data. "));
- mbx.exec();
- }
+ if (cbUseDevRandom->isChecked())
+ {
+ QMessageBox mbx;
+ mbx.setText(tr("Using /dev/random is more preferable for generating long-term high-value cryptographic keys, but it can take 5 - 10 minutes to collect required amount of entropy. You'll have to press random keys on keyboard and move mouse randomly to provide random data. "));
+ mbx.exec();
+ }
#endif
}
void RegisterAccountDialog::setPasswordClick()
{
- if (cbSetPassword->isChecked())
- {
- password -> setDisabled(false);
- repeatPassword -> setDisabled(false);
-
- password->show();
- repeatPassword->show();
- lbPassword->show();
- lbRepeatPassword->show();
- }
- else
- {
- password -> setDisabled(true);
- repeatPassword -> setDisabled(true);
-
- password->setHidden(true);
- repeatPassword->setHidden(true);
- lbPassword->hide();
- lbRepeatPassword->hide();
- }
-
- adjustSize();
+ if (cbSetPassword->isChecked())
+ {
+ password -> setDisabled(false);
+ repeatPassword -> setDisabled(false);
+
+ password->show();
+ repeatPassword->show();
+ lbPassword->show();
+ lbRepeatPassword->show();
+ }
+ else
+ {
+ password -> setDisabled(true);
+ repeatPassword -> setDisabled(true);
+
+ password->setHidden(true);
+ repeatPassword->setHidden(true);
+ lbPassword->hide();
+ lbRepeatPassword->hide();
+ }
+
+ adjustSize();
}
//void RegisterAccountDialog::OK()
@@ -112,95 +112,95 @@ void RegisterAccountDialog::setPasswordClick()
void RegisterAccountDialog::Register()
{
- //check name
- QString name = nickname->text();
- QString rand = QString::null;
-
- if (name.toUtf8().size() > 63) //64 bytes - CN length in X509 certificate
- {
- QMessageBox mbx;
- mbx.setText(tr("Name is too long"));
- mbx.exec();
- return;
- }
-
- if (name.isEmpty())
- {
- QMessageBox mbx;
- mbx.setText(tr("You must enter account name"));
- mbx.exec();
- return;
- }
-
- if (cbSetPassword->isChecked())
- {
- if (password->text() != repeatPassword->text())
- {
- QMessageBox mbx;
- mbx.setText(tr("Passphrases do not match"));
- mbx.exec();
- return;
- }
- }
-
- #ifndef WIN32
- if (cbUseDevRandom->isChecked())
- {
- rand = "/dev/random";
- }
-
- cbUseDevRandom -> setDisabled(true);
- #endif
-
- cbSetPassword -> setDisabled(true);
-
- //1
- lbStatus->setText(tr("1) generating RSA keypair..."));
-
- nickname->setEnabled(false);
- btRegister->setEnabled(false);
-
- ost.GenRSAKeySignal(4096, config_dir + QDir::separator() + "privkey.pem", cbSetPassword->isChecked(),
- password->text(),rand, this, SLOT(stageSignCert(int,QProcess::ExitStatus)));
+ //check name
+ QString name = nickname->text();
+ QString rand = QString::null;
+
+ if (name.toUtf8().size() > 63) //64 bytes - CN length in X509 certificate
+ {
+ QMessageBox mbx;
+ mbx.setText(tr("Name is too long"));
+ mbx.exec();
+ return;
+ }
+
+ if (name.isEmpty())
+ {
+ QMessageBox mbx;
+ mbx.setText(tr("You must enter account name"));
+ mbx.exec();
+ return;
+ }
+
+ if (cbSetPassword->isChecked())
+ {
+ if (password->text() != repeatPassword->text())
+ {
+ QMessageBox mbx;
+ mbx.setText(tr("Passphrases do not match"));
+ mbx.exec();
+ return;
+ }
+ }
+
+#ifndef WIN32
+ if (cbUseDevRandom->isChecked())
+ {
+ rand = "/dev/random";
+ }
+
+ cbUseDevRandom -> setDisabled(true);
+#endif
+
+ cbSetPassword -> setDisabled(true);
+
+ //1
+ lbStatus->setText(tr("1) generating RSA keypair..."));
+
+ nickname->setEnabled(false);
+ btRegister->setEnabled(false);
+
+ ost.GenRSAKeySignal(4096, config_dir + QDir::separator() + "privkey.pem", cbSetPassword->isChecked(),
+ password->text(), rand, this, SLOT(stageSignCert(int, QProcess::ExitStatus)));
}
-void RegisterAccountDialog::stageSignCert(int retval,QProcess::ExitStatus)
+void RegisterAccountDialog::stageSignCert(int retval, QProcess::ExitStatus)
{
- if (retval != 0)
- {
- lbStatus->setText(tr("Error:\n") + ost.ReadStdErr());
- return;
- }
-
- lbStatus->setText(tr("2) Signing certificate..."));
-
- ost.GenCertSignal(config_dir + QDir::separator() + "cert.pem",
- config_dir + QDir::separator() + "privkey.pem",
- password->text(),nickname->text(),
- this,SLOT(stageFinished(int,QProcess::ExitStatus)));
+ if (retval != 0)
+ {
+ lbStatus->setText(tr("Error:\n") + ost.ReadStdErr());
+ return;
+ }
+
+ lbStatus->setText(tr("2) Signing certificate..."));
+
+ ost.GenCertSignal(config_dir + QDir::separator() + "cert.pem",
+ config_dir + QDir::separator() + "privkey.pem",
+ password->text(), nickname->text(),
+ this, SLOT(stageFinished(int, QProcess::ExitStatus)));
}
void RegisterAccountDialog::stageFinished(int retval, QProcess::ExitStatus)
{
- if (retval != 0)
- {
- lbStatus->setText(tr("Error:\n") + ost.ReadStdErr());
- return;
- }
+ if (retval != 0)
+ {
+ lbStatus->setText(tr("Error:\n") + ost.ReadStdErr());
+ return;
+ }
- CertFilename_ = config_dir + QDir::separator() + "cert.pem";
- PkeyFilename_ = config_dir + QDir::separator() + "privkey.pem";
+ CertFilename_ = config_dir + QDir::separator() + "cert.pem";
+ PkeyFilename_ = config_dir + QDir::separator() + "privkey.pem";
- done(1);
+ done(1);
}
QString RegisterAccountDialog::GetCertFilename()
{
- return CertFilename_;
+ return CertFilename_;
}
QString RegisterAccountDialog::GetPkeyFilename()
{
- return PkeyFilename_;
+ return PkeyFilename_;
}
diff --git a/pica-client/dialogs/registeraccountdialog.h b/pica-client/dialogs/registeraccountdialog.h
index 550d769..9771ccd 100644
--- a/pica-client/dialogs/registeraccountdialog.h
+++ b/pica-client/dialogs/registeraccountdialog.h
@@ -11,40 +11,40 @@
class RegisterAccountDialog : public QDialog
{
- Q_OBJECT
+ Q_OBJECT
public:
- explicit RegisterAccountDialog(QWidget *parent = 0);
- QString GetCertFilename();
- QString GetPkeyFilename();
-
+ explicit RegisterAccountDialog(QWidget *parent = 0);
+ QString GetCertFilename();
+ QString GetPkeyFilename();
+
private:
- //QPushButton *btOK;
- QPushButton *btRegister;
- QLineEdit *nickname;
- QLabel *lbStatus;
- QCheckBox *cbSetPassword;
- QLineEdit *password;
- QLineEdit *repeatPassword;
- QLabel *lbPassword ;
- QLabel *lbRepeatPassword;
- QCheckBox *cbUseDevRandom;
-
- QRegExpValidator *vld;
- OpenSSLTool ost;
- QByteArray cert_buf;
-
- QString CertFilename_;
- QString PkeyFilename_;
+ //QPushButton *btOK;
+ QPushButton *btRegister;
+ QLineEdit *nickname;
+ QLabel *lbStatus;
+ QCheckBox *cbSetPassword;
+ QLineEdit *password;
+ QLineEdit *repeatPassword;
+ QLabel *lbPassword ;
+ QLabel *lbRepeatPassword;
+ QCheckBox *cbUseDevRandom;
+
+ QRegExpValidator *vld;
+ OpenSSLTool ost;
+ QByteArray cert_buf;
+
+ QString CertFilename_;
+ QString PkeyFilename_;
signals:
-
+
private slots:
- //void OK();
- void Register();
- void setPasswordClick();
- void useDevRandomClick();
+ //void OK();
+ void Register();
+ void setPasswordClick();
+ void useDevRandomClick();
- void stageSignCert(int retval, QProcess::ExitStatus);
- void stageFinished(int retval, QProcess::ExitStatus);
+ void stageSignCert(int retval, QProcess::ExitStatus);
+ void stageFinished(int retval, QProcess::ExitStatus);
};
#endif // REGISTERACCOUNTDIALOG_H
diff --git a/pica-client/dialogs/settingsdialog.cpp b/pica-client/dialogs/settingsdialog.cpp
index 852cc95..d16bb63 100644
--- a/pica-client/dialogs/settingsdialog.cpp
+++ b/pica-client/dialogs/settingsdialog.cpp
@@ -73,23 +73,23 @@ SettingsDialog::SettingsDialog(QWidget *parent) :
tabW->addTab(soundstab, tr("Sounds"));
settingsLayout->addWidget(tabW);
- QHBoxLayout *buttonsLayout = new QHBoxLayout;
+ QHBoxLayout *buttonsLayout = new QHBoxLayout;
- btOk = new QPushButton(tr("&OK"), this);
- btCancel = new QPushButton(tr("Cancel"), this);
+ btOk = new QPushButton(tr("&OK"), this);
+ btCancel = new QPushButton(tr("Cancel"), this);
- buttonsLayout->addStretch(1);
- buttonsLayout->addWidget(btOk);
- buttonsLayout->addWidget(btCancel);
+ buttonsLayout->addStretch(1);
+ buttonsLayout->addWidget(btOk);
+ buttonsLayout->addWidget(btCancel);
- settingsLayout->addLayout(buttonsLayout);
+ settingsLayout->addLayout(buttonsLayout);
setLayout(settingsLayout);
- connect(btOk, SIGNAL(clicked()), this, SLOT(OK()));
- connect(btCancel, SIGNAL(clicked()), this, SLOT(Cancel()));
+ connect(btOk, SIGNAL(clicked()), this, SLOT(OK()));
+ connect(btCancel, SIGNAL(clicked()), this, SLOT(Cancel()));
- loadSettings();
+ loadSettings();
setWindowTitle(tr("Pica Pica Messenger Settings"));
}
@@ -103,66 +103,66 @@ void SettingsDialog::toggleIncomingConnections(bool checked)
void SettingsDialog::OK()
{
- storeSettings();
- done(1);
+ storeSettings();
+ done(1);
}
void SettingsDialog::Cancel()
{
- done(0);
+ done(0);
}
void SettingsDialog::loadSettings()
{
- Settings st(config_dbname);
+ Settings st(config_dbname);
- //Direct c2c connections
- int c2c_state;
+ //Direct c2c connections
+ int c2c_state;
- c2c_state = st.loadValue("direct_c2c.state", 1).toInt();
+ c2c_state = st.loadValue("direct_c2c.state", 1).toInt();
- switch (c2c_state)
- {
- case 0:
- rbDisableDirectConns->setChecked(true);
- break;
+ switch (c2c_state)
+ {
+ case 0:
+ rbDisableDirectConns->setChecked(true);
+ break;
- case 1:
- rbEnableOutgoingConns->setChecked(true);
- break;
+ case 1:
+ rbEnableOutgoingConns->setChecked(true);
+ break;
- case 2:
- rbEnableIncomingConns->setChecked(true);
- break;
+ case 2:
+ rbEnableIncomingConns->setChecked(true);
+ break;
- default:
- break;
- }
+ default:
+ break;
+ }
addr->lineEdit()->setText(st.loadValue("direct_c2c.public_addr", "0.0.0.0").toString());
- publicPort->setValue(st.loadValue("direct_c2c.public_port", 2298).toInt());
- localPort->setValue(st.loadValue("direct_c2c.local_port", 2298).toInt());
+ publicPort->setValue(st.loadValue("direct_c2c.public_port", 2298).toInt());
+ localPort->setValue(st.loadValue("direct_c2c.local_port", 2298).toInt());
}
void SettingsDialog::storeSettings()
{
- Settings st(config_dbname);
+ Settings st(config_dbname);
- //Direct c2c connections
- int c2c_state;
+ //Direct c2c connections
+ int c2c_state;
- if (rbDisableDirectConns->isChecked())
- c2c_state = 0;
- else if (rbEnableOutgoingConns->isChecked())
- c2c_state = 1;
- else if (rbEnableIncomingConns->isChecked())
- c2c_state = 2;
+ if (rbDisableDirectConns->isChecked())
+ c2c_state = 0;
+ else if (rbEnableOutgoingConns->isChecked())
+ c2c_state = 1;
+ else if (rbEnableIncomingConns->isChecked())
+ c2c_state = 2;
- st.storeValue("direct_c2c.state", QString::number(c2c_state));
+ st.storeValue("direct_c2c.state", QString::number(c2c_state));
st.storeValue("direct_c2c.public_addr", addr->lineEdit()->text());
- st.storeValue("direct_c2c.public_port", QString::number(publicPort->value()));
- st.storeValue("direct_c2c.local_port", QString::number(localPort->value()));
+ st.storeValue("direct_c2c.public_port", QString::number(publicPort->value()));
+ st.storeValue("direct_c2c.local_port", QString::number(localPort->value()));
}
diff --git a/pica-client/dialogs/settingsdialog.h b/pica-client/dialogs/settingsdialog.h
index 9b11630..f0ab0cd 100644
--- a/pica-client/dialogs/settingsdialog.h
+++ b/pica-client/dialogs/settingsdialog.h
@@ -31,12 +31,12 @@ private:
QPushButton *btOk;
QPushButton *btCancel;
- void loadSettings();
- void storeSettings();
+ void loadSettings();
+ void storeSettings();
private slots:
- void OK();
- void Cancel();
+ void OK();
+ void Cancel();
void toggleIncomingConnections(bool checked);
};
diff --git a/pica-client/dialogs/showpicaiddialog.cpp b/pica-client/dialogs/showpicaiddialog.cpp
index 8fed71e..4e45c30 100644
--- a/pica-client/dialogs/showpicaiddialog.cpp
+++ b/pica-client/dialogs/showpicaiddialog.cpp
@@ -4,33 +4,33 @@
#include <QStyle>
ShowPicaIdDialog::ShowPicaIdDialog(QString name, QByteArray id, QString caption, QWidget *parent) :
- QDialog(parent)
+ QDialog(parent)
{
- setWindowTitle(caption);
- QVBoxLayout *layout = new QVBoxLayout(this);
+ setWindowTitle(caption);
+ QVBoxLayout *layout = new QVBoxLayout(this);
- lbname_ = new QLabel(tr("Account: <b>%1</b>").arg(name));
- lbname_ ->setTextFormat(Qt::RichText);
+ lbname_ = new QLabel(tr("Account: <b>%1</b>").arg(name));
+ lbname_ ->setTextFormat(Qt::RichText);
- picaid_ = new QLineEdit();
+ picaid_ = new QLineEdit();
- picaid_ ->setText(id.toBase64().constData());
- picaid_->setReadOnly(true);
- picaid_->setSelection(0, picaid_->text().size());
- picaid_->setMinimumWidth(picaid_->fontMetrics().width(picaid_->text()) + 2 * picaid_->style()->pixelMetric(QStyle::PM_DefaultFrameWidth));
+ picaid_ ->setText(id.toBase64().constData());
+ picaid_->setReadOnly(true);
+ picaid_->setSelection(0, picaid_->text().size());
+ picaid_->setMinimumWidth(picaid_->fontMetrics().width(picaid_->text()) + 2 * picaid_->style()->pixelMetric(QStyle::PM_DefaultFrameWidth));
- btok_ = new QPushButton(tr("OK"));
- btok_->setDefault(true);
- btok_->setMaximumWidth(btok_->fontMetrics().width(btok_->text()) * 3 / 2 + 2 * btok_->style()->pixelMetric(QStyle::PM_ButtonMargin));
+ btok_ = new QPushButton(tr("OK"));
+ btok_->setDefault(true);
+ btok_->setMaximumWidth(btok_->fontMetrics().width(btok_->text()) * 3 / 2 + 2 * btok_->style()->pixelMetric(QStyle::PM_ButtonMargin));
- layout->addWidget(lbname_);
- layout->addWidget(picaid_);
- layout->addWidget(btok_, 0, Qt::AlignHCenter);
+ layout->addWidget(lbname_);
+ layout->addWidget(picaid_);
+ layout->addWidget(btok_, 0, Qt::AlignHCenter);
- connect(btok_, SIGNAL(clicked()), this, SLOT(Ok()));
+ connect(btok_, SIGNAL(clicked()), this, SLOT(Ok()));
}
void ShowPicaIdDialog::Ok()
{
- done(0);
+ done(0);
}
diff --git a/pica-client/dialogs/showpicaiddialog.h b/pica-client/dialogs/showpicaiddialog.h
index a566c12..5523bc3 100644
--- a/pica-client/dialogs/showpicaiddialog.h
+++ b/pica-client/dialogs/showpicaiddialog.h
@@ -10,17 +10,17 @@
class ShowPicaIdDialog : public QDialog
{
- Q_OBJECT
+ Q_OBJECT
public:
- explicit ShowPicaIdDialog(QString name, QByteArray id, QString caption, QWidget *parent = 0);
+ explicit ShowPicaIdDialog(QString name, QByteArray id, QString caption, QWidget *parent = 0);
private slots:
- void Ok();
+ void Ok();
private:
- QLabel *lbname_;
- QLineEdit *picaid_;
- QPushButton *btok_;
+ QLabel *lbname_;
+ QLineEdit *picaid_;
+ QPushButton *btok_;
};
diff --git a/pica-client/dialogs/viewcertdialog.cpp b/pica-client/dialogs/viewcertdialog.cpp
index f75e7f3..c94df25 100644
--- a/pica-client/dialogs/viewcertdialog.cpp
+++ b/pica-client/dialogs/viewcertdialog.cpp
@@ -5,42 +5,42 @@
#include <QFile>
ViewCertDialog::ViewCertDialog(QWidget *parent) :
- QDialog(parent)
+ QDialog(parent)
{
- QVBoxLayout *layout;
+ QVBoxLayout *layout;
- layout = new QVBoxLayout;
- cert_text = new QTextEdit(this);
- btOK = new QPushButton(tr("OK"));
- btOK->setMaximumWidth(45);
- this->setMinimumWidth(640);
- this->setMinimumHeight(480);
+ layout = new QVBoxLayout;
+ cert_text = new QTextEdit(this);
+ btOK = new QPushButton(tr("OK"));
+ btOK->setMaximumWidth(45);
+ this->setMinimumWidth(640);
+ this->setMinimumHeight(480);
- QTextCharFormat fmt;
+ QTextCharFormat fmt;
- fmt = cert_text->currentCharFormat();
- fmt.setFontFixedPitch(true);
- fmt.setFontStyleHint(QFont::Monospace);
- fmt.setFontFamily("Liberation Mono");
- cert_text->setCurrentCharFormat(fmt);
+ fmt = cert_text->currentCharFormat();
+ fmt.setFontFixedPitch(true);
+ fmt.setFontStyleHint(QFont::Monospace);
+ fmt.setFontFamily("Liberation Mono");
+ cert_text->setCurrentCharFormat(fmt);
- cert_text->setReadOnly(true);
+ cert_text->setReadOnly(true);
- layout->addWidget(cert_text);
- layout->addWidget(btOK, 0, Qt::AlignCenter);
+ layout->addWidget(cert_text);
+ layout->addWidget(btOK, 0, Qt::AlignCenter);
- setLayout(layout);
+ setLayout(layout);
- connect(btOK, SIGNAL(clicked()), this, SLOT(OK()));
+ connect(btOK, SIGNAL(clicked()), this, SLOT(OK()));
}
void ViewCertDialog::SetCert(QString cert_pem)
{
- cert_text->setPlainText(OpenSSLTool::CertTextFromString(cert_pem));
+ cert_text->setPlainText(OpenSSLTool::CertTextFromString(cert_pem));
}
void ViewCertDialog::OK()
{
- done(0);
+ done(0);
}
diff --git a/pica-client/dialogs/viewcertdialog.h b/pica-client/dialogs/viewcertdialog.h
index 013815c..c9a8ade 100644
--- a/pica-client/dialogs/viewcertdialog.h
+++ b/pica-client/dialogs/viewcertdialog.h
@@ -7,22 +7,22 @@
class ViewCertDialog : public QDialog
{
- Q_OBJECT
+ Q_OBJECT
public:
- explicit ViewCertDialog(QWidget *parent = 0);
- void SetCert(QString cert_pem);
-
+ explicit ViewCertDialog(QWidget *parent = 0);
+ void SetCert(QString cert_pem);
+
private:
- QTextEdit *cert_text;
- QPushButton *btOK;
+ QTextEdit *cert_text;
+ QPushButton *btOK;
signals:
-
+
public slots:
private slots:
- void OK();
-
+ void OK();
+
};
#endif // VIEWCERTDIALOG_H
diff --git a/pica-client/filetransfercontroller.cpp b/pica-client/filetransfercontroller.cpp
index 44dba15..c31b73a 100644
--- a/pica-client/filetransfercontroller.cpp
+++ b/pica-client/filetransfercontroller.cpp
@@ -7,247 +7,247 @@
#include <QFileInfo>
FileTransferController::FileTransferController(QObject *parent) :
- QObject(parent)
+ QObject(parent)
{
- connect(skynet, SIGNAL(IncomingFileRequestReceived(QByteArray,quint64,QString)),
- this, SLOT(file_request(QByteArray,quint64,QString)));
+ connect(skynet, SIGNAL(IncomingFileRequestReceived(QByteArray, quint64, QString)),
+ this, SLOT(file_request(QByteArray, quint64, QString)));
- connect(skynet, SIGNAL(FileProgress(QByteArray,quint64,quint64)),
- this, SLOT(file_progress(QByteArray,quint64,quint64)));
+ connect(skynet, SIGNAL(FileProgress(QByteArray, quint64, quint64)),
+ this, SLOT(file_progress(QByteArray, quint64, quint64)));
- connect(skynet, SIGNAL(OutgoingFileRequestAccepted(QByteArray)), this, SLOT(file_accepted_by_peer(QByteArray)));
+ connect(skynet, SIGNAL(OutgoingFileRequestAccepted(QByteArray)), this, SLOT(file_accepted_by_peer(QByteArray)));
- connect(skynet, SIGNAL(OutgoingFileRequestDenied(QByteArray)), this, SLOT(file_denied_by_peer(QByteArray)));
+ connect(skynet, SIGNAL(OutgoingFileRequestDenied(QByteArray)), this, SLOT(file_denied_by_peer(QByteArray)));
connect(skynet, SIGNAL(c2cClosed(QByteArray)), this, SLOT(file_peer_disconnected(QByteArray)));
}
void FileTransferController::file_peer_disconnected(QByteArray peer_id)
{
- if (ftdialogs_in.contains(peer_id))
- {
- ftdialogs_in[peer_id]->peerDisconnected();
- ftdialogs_in.remove(peer_id);
- }
+ if (ftdialogs_in.contains(peer_id))
+ {
+ ftdialogs_in[peer_id]->peerDisconnected();
+ ftdialogs_in.remove(peer_id);
+ }
- if (ftdialogs_out.contains(peer_id))
- {
- ftdialogs_out[peer_id]->peerDisconnected();
- ftdialogs_out.remove(peer_id);
- }
+ if (ftdialogs_out.contains(peer_id))
+ {
+ ftdialogs_out[peer_id]->peerDisconnected();
+ ftdialogs_out.remove(peer_id);
+ }
}
void FileTransferController::file_finished_incoming(QByteArray peer_id)
{
- if (ftdialogs_in.contains(peer_id))
+ if (ftdialogs_in.contains(peer_id))
- ftdialogs_in.remove(peer_id);
+ ftdialogs_in.remove(peer_id);
}
void FileTransferController::file_finished_outgoing(QByteArray peer_id)
{
- if (ftdialogs_out.contains(peer_id))
- {
- ftdialogs_out.remove(peer_id);
- qDebug() << "outgoing file transfer finished, removing dialog pointer\n";
- }
+ if (ftdialogs_out.contains(peer_id))
+ {
+ ftdialogs_out.remove(peer_id);
+ qDebug() << "outgoing file transfer finished, removing dialog pointer\n";
+ }
}
void FileTransferController::file_progress(QByteArray peer_id, quint64 bytes_sent, quint64 bytes_received)
{
- if (bytes_received > 0)
- {
- if (ftdialogs_in.contains(peer_id))
- {
- ftdialogs_in[peer_id]->update(bytes_received);
- }
- }
- else if (bytes_sent > 0)
- {
- if (ftdialogs_out.contains(peer_id))
- {
- ftdialogs_out[peer_id]->update(bytes_sent);
- }
- }
+ if (bytes_received > 0)
+ {
+ if (ftdialogs_in.contains(peer_id))
+ {
+ ftdialogs_in[peer_id]->update(bytes_received);
+ }
+ }
+ else if (bytes_sent > 0)
+ {
+ if (ftdialogs_out.contains(peer_id))
+ {
+ ftdialogs_out[peer_id]->update(bytes_sent);
+ }
+ }
}
void FileTransferController::file_request(QByteArray peer_id, quint64 file_size, QString filename)
{
- FileTransferDialog *ftd = new FileTransferDialog(peer_id, filename, file_size, FileTransferDialog::RECEIVING);
+ FileTransferDialog *ftd = new FileTransferDialog(peer_id, filename, file_size, FileTransferDialog::RECEIVING);
- ftdialogs_in[peer_id] = ftd;
- fnames[peer_id] = filename;
+ ftdialogs_in[peer_id] = ftd;
+ fnames[peer_id] = filename;
- connect(ftd, SIGNAL(acceptedFile(QByteArray)), this, SLOT(file_accepted_by_me(QByteArray)));
- connect(ftd, SIGNAL(deniedFile(QByteArray)), this, SLOT(file_denied_by_me(QByteArray)));
+ connect(ftd, SIGNAL(acceptedFile(QByteArray)), this, SLOT(file_accepted_by_me(QByteArray)));
+ connect(ftd, SIGNAL(deniedFile(QByteArray)), this, SLOT(file_denied_by_me(QByteArray)));
- ftd->show();
+ ftd->show();
}
void FileTransferController::file_accepted_by_peer(QByteArray peer_id)
{
- connect(skynet, SIGNAL(OutgoingFilePaused(QByteArray)), this, SLOT(file_paused_outgoing(QByteArray)));
- connect(skynet, SIGNAL(OutgoingFileResumed(QByteArray)), this, SLOT(file_resumed_outgoing(QByteArray)));
- connect(skynet, SIGNAL(OutgoingFileCancelled(QByteArray)), this, SLOT(file_cancelled_outgoing(QByteArray)));
- connect(skynet, SIGNAL(OutgoingFileIoError(QByteArray)), this, SLOT(file_ioerror_outgoing(QByteArray)));
- connect(skynet, SIGNAL(OutgoingFileFinished(QByteArray)), this, SLOT(file_finished_outgoing(QByteArray)));
+ connect(skynet, SIGNAL(OutgoingFilePaused(QByteArray)), this, SLOT(file_paused_outgoing(QByteArray)));
+ connect(skynet, SIGNAL(OutgoingFileResumed(QByteArray)), this, SLOT(file_resumed_outgoing(QByteArray)));
+ connect(skynet, SIGNAL(OutgoingFileCancelled(QByteArray)), this, SLOT(file_cancelled_outgoing(QByteArray)));
+ connect(skynet, SIGNAL(OutgoingFileIoError(QByteArray)), this, SLOT(file_ioerror_outgoing(QByteArray)));
+ connect(skynet, SIGNAL(OutgoingFileFinished(QByteArray)), this, SLOT(file_finished_outgoing(QByteArray)));
- ftdialogs_out[peer_id]->setTransferStatus(FileTransferDialog::SENDINGFILE);
+ ftdialogs_out[peer_id]->setTransferStatus(FileTransferDialog::SENDINGFILE);
}
void FileTransferController::file_denied_by_peer(QByteArray peer_id)
{
- ftdialogs_out[peer_id]->setTransferStatus(FileTransferDialog::DENIED);
+ ftdialogs_out[peer_id]->setTransferStatus(FileTransferDialog::DENIED);
}
void FileTransferController::file_paused_incoming(QByteArray peer_id)
{
- ftdialogs_in[peer_id]->pausedByPeer();
+ ftdialogs_in[peer_id]->pausedByPeer();
}
void FileTransferController::file_resumed_incoming(QByteArray peer_id)
{
- ftdialogs_in[peer_id]->resumedByPeer();
+ ftdialogs_in[peer_id]->resumedByPeer();
}
void FileTransferController::file_cancelled_incoming(QByteArray peer_id)
{
- ftdialogs_in[peer_id]->cancelledByPeer();
- ftdialogs_in.remove(peer_id);
+ ftdialogs_in[peer_id]->cancelledByPeer();
+ ftdialogs_in.remove(peer_id);
}
void FileTransferController::file_ioerror_incoming(QByteArray peer_id)
{
- ftdialogs_in[peer_id]->ioError();
- ftdialogs_in.remove(peer_id);
+ ftdialogs_in[peer_id]->ioError();
+ ftdialogs_in.remove(peer_id);
}
void FileTransferController::file_paused_outgoing(QByteArray peer_id)
{
- ftdialogs_out[peer_id]->pausedByPeer();
+ ftdialogs_out[peer_id]->pausedByPeer();
}
void FileTransferController::file_resumed_outgoing(QByteArray peer_id)
{
- ftdialogs_out[peer_id]->resumedByPeer();
+ ftdialogs_out[peer_id]->resumedByPeer();
}
void FileTransferController::file_cancelled_outgoing(QByteArray peer_id)
{
- ftdialogs_out[peer_id]->cancelledByPeer();
- ftdialogs_out.remove(peer_id);
+ ftdialogs_out[peer_id]->cancelledByPeer();
+ ftdialogs_out.remove(peer_id);
}
void FileTransferController::file_ioerror_outgoing(QByteArray peer_id)
{
- ftdialogs_out[peer_id]->ioError();
- ftdialogs_out.remove(peer_id);
+ ftdialogs_out[peer_id]->ioError();
+ ftdialogs_out.remove(peer_id);
}
void FileTransferController::file_accepted_by_me(QByteArray peer_id)
{
- QString filePathToSave = QFileDialog::getSaveFileName(ftdialogs_in[peer_id], tr("Save received file to"),
- fnames[peer_id], tr("Any file (* *.*)"));
+ QString filePathToSave = QFileDialog::getSaveFileName(ftdialogs_in[peer_id], tr("Save received file to"),
+ fnames[peer_id], tr("Any file (* *.*)"));
- skynet->AcceptFile(peer_id, filePathToSave);
+ skynet->AcceptFile(peer_id, filePathToSave);
- connect(ftdialogs_in[peer_id], SIGNAL(cancelledFile(QByteArray,FileTransferDialog*)), this, SLOT(file_cancelled_by_me(QByteArray,FileTransferDialog*)));
- connect(ftdialogs_in[peer_id], SIGNAL(pausedFile(QByteArray,FileTransferDialog*)), this, SLOT(file_paused_by_me(QByteArray,FileTransferDialog*)));
- connect(ftdialogs_in[peer_id], SIGNAL(resumedFile(QByteArray,FileTransferDialog*)), this, SLOT(file_resumed_by_me(QByteArray,FileTransferDialog*)));
+ connect(ftdialogs_in[peer_id], SIGNAL(cancelledFile(QByteArray, FileTransferDialog*)), this, SLOT(file_cancelled_by_me(QByteArray, FileTransferDialog*)));
+ connect(ftdialogs_in[peer_id], SIGNAL(pausedFile(QByteArray, FileTransferDialog*)), this, SLOT(file_paused_by_me(QByteArray, FileTransferDialog*)));
+ connect(ftdialogs_in[peer_id], SIGNAL(resumedFile(QByteArray, FileTransferDialog*)), this, SLOT(file_resumed_by_me(QByteArray, FileTransferDialog*)));
- connect(skynet, SIGNAL(IncomingFilePaused(QByteArray)), this, SLOT(file_paused_incoming(QByteArray)));
- connect(skynet, SIGNAL(IncomingFileResumed(QByteArray)), this, SLOT(file_resumed_incoming(QByteArray)));
- connect(skynet, SIGNAL(IncomingFileCancelled(QByteArray)), this, SLOT(file_cancelled_incoming(QByteArray)));
- connect(skynet, SIGNAL(IncomingFileIoError(QByteArray)), this, SLOT(file_ioerror_incoming(QByteArray)));
- connect(skynet,SIGNAL(IncomingFileFinished(QByteArray)), this, SLOT(file_finished_incoming(QByteArray)));
+ connect(skynet, SIGNAL(IncomingFilePaused(QByteArray)), this, SLOT(file_paused_incoming(QByteArray)));
+ connect(skynet, SIGNAL(IncomingFileResumed(QByteArray)), this, SLOT(file_resumed_incoming(QByteArray)));
+ connect(skynet, SIGNAL(IncomingFileCancelled(QByteArray)), this, SLOT(file_cancelled_incoming(QByteArray)));
+ connect(skynet, SIGNAL(IncomingFileIoError(QByteArray)), this, SLOT(file_ioerror_incoming(QByteArray)));
+ connect(skynet, SIGNAL(IncomingFileFinished(QByteArray)), this, SLOT(file_finished_incoming(QByteArray)));
- ftdialogs_in[peer_id]->setTransferStatus(FileTransferDialog::RECEIVINGFILE);
+ ftdialogs_in[peer_id]->setTransferStatus(FileTransferDialog::RECEIVINGFILE);
}
void FileTransferController::file_denied_by_me(QByteArray peer_id)
{
- skynet->DenyFile(peer_id);
+ skynet->DenyFile(peer_id);
- //delete ftdialogs_in[peer_id];
+ //delete ftdialogs_in[peer_id];
- ftdialogs_in.remove(peer_id);
+ ftdialogs_in.remove(peer_id);
}
void FileTransferController::file_cancelled_by_me(QByteArray peer_id, FileTransferDialog *from)
{
- bool sending = true;
+ bool sending = true;
- if (from->getTransferDirection() == FileTransferDialog::RECEIVING)
- {
- ftdialogs_in.remove(peer_id);
+ if (from->getTransferDirection() == FileTransferDialog::RECEIVING)
+ {
+ ftdialogs_in.remove(peer_id);
- sending = false;
- }
- else
- {
- ftdialogs_out.remove(peer_id);
- }
+ sending = false;
+ }
+ else
+ {
+ ftdialogs_out.remove(peer_id);
+ }
- skynet->CancelFile(peer_id, sending);
+ skynet->CancelFile(peer_id, sending);
}
void FileTransferController::file_paused_by_me(QByteArray peer_id, FileTransferDialog *from)
{
- bool sending = true;
+ bool sending = true;
- if (from->getTransferDirection() == FileTransferDialog::RECEIVING)
- sending = false;
+ if (from->getTransferDirection() == FileTransferDialog::RECEIVING)
+ sending = false;
- skynet->PauseFile(peer_id, sending);
+ skynet->PauseFile(peer_id, sending);
}
void FileTransferController::file_resumed_by_me(QByteArray peer_id, FileTransferDialog *from)
{
- bool sending = true;
+ bool sending = true;
- if (from->getTransferDirection() == FileTransferDialog::RECEIVING)
- sending = false;
+ if (from->getTransferDirection() == FileTransferDialog::RECEIVING)
+ sending = false;
- skynet->ResumeFile(peer_id, sending);
+ skynet->ResumeFile(peer_id, sending);
}
void FileTransferController::send_file(QByteArray peer_id)
{
- if (ftdialogs_out.contains(peer_id))
- {
+ if (ftdialogs_out.contains(peer_id))
+ {
msguirouter->notification(tr("There is already file transfer in progress. Wait until it is finished."), true);
- return;
- }
+ return;
+ }
- QString filepath = QFileDialog::getOpenFileName(0, tr("Select file to send"), QString(), tr("Any file (* *.*)"));
+ QString filepath = QFileDialog::getOpenFileName(0, tr("Select file to send"), QString(), tr("Any file (* *.*)"));
- if (filepath.isNull())
- return;
+ if (filepath.isNull())
+ return;
- QFileInfo fi(filepath);
+ QFileInfo fi(filepath);
- if (!fi.exists())
- {
- msguirouter->notification(tr("File \"%1\" does not exist.").arg(filepath), true);
- return;
- }
+ if (!fi.exists())
+ {
+ msguirouter->notification(tr("File \"%1\" does not exist.").arg(filepath), true);
+ return;
+ }
- if (fi.size() == 0)
- {
- msguirouter->notification(tr("Cannot send empty file."), true);
- }
+ if (fi.size() == 0)
+ {
+ msguirouter->notification(tr("Cannot send empty file."), true);
+ }
- skynet->SendFile(peer_id, filepath);
+ skynet->SendFile(peer_id, filepath);
- FileTransferDialog *ftd = new FileTransferDialog(peer_id, fi.fileName(), fi.size(), FileTransferDialog::SENDING);
+ FileTransferDialog *ftd = new FileTransferDialog(peer_id, fi.fileName(), fi.size(), FileTransferDialog::SENDING);
- ftdialogs_out[peer_id] = ftd;
+ ftdialogs_out[peer_id] = ftd;
- connect(ftdialogs_out[peer_id], SIGNAL(cancelledFile(QByteArray,FileTransferDialog*)), this, SLOT(file_cancelled_by_me(QByteArray,FileTransferDialog*)));
- connect(ftdialogs_out[peer_id], SIGNAL(pausedFile(QByteArray,FileTransferDialog*)), this, SLOT(file_paused_by_me(QByteArray,FileTransferDialog*)));
- connect(ftdialogs_out[peer_id], SIGNAL(resumedFile(QByteArray,FileTransferDialog*)), this, SLOT(file_resumed_by_me(QByteArray,FileTransferDialog*)));
+ connect(ftdialogs_out[peer_id], SIGNAL(cancelledFile(QByteArray, FileTransferDialog*)), this, SLOT(file_cancelled_by_me(QByteArray, FileTransferDialog*)));
+ connect(ftdialogs_out[peer_id], SIGNAL(pausedFile(QByteArray, FileTransferDialog*)), this, SLOT(file_paused_by_me(QByteArray, FileTransferDialog*)));
+ connect(ftdialogs_out[peer_id], SIGNAL(resumedFile(QByteArray, FileTransferDialog*)), this, SLOT(file_resumed_by_me(QByteArray, FileTransferDialog*)));
- ftd->show();
+ ftd->show();
}
diff --git a/pica-client/filetransfercontroller.h b/pica-client/filetransfercontroller.h
index ff6cb0b..fbc7d84 100644
--- a/pica-client/filetransfercontroller.h
+++ b/pica-client/filetransfercontroller.h
@@ -7,51 +7,51 @@
class FileTransferController : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- explicit FileTransferController(QObject *parent = 0);
+ explicit FileTransferController(QObject *parent = 0);
signals:
private:
- QMap<QByteArray, FileTransferDialog*> ftdialogs_in;
- QMap<QByteArray, FileTransferDialog*> ftdialogs_out;
+ QMap<QByteArray, FileTransferDialog*> ftdialogs_in;
+ QMap<QByteArray, FileTransferDialog*> ftdialogs_out;
- QMap<QByteArray, QString> fnames;
+ QMap<QByteArray, QString> fnames;
public slots:
- // from remote peer to me
- void file_progress(QByteArray peer_id, quint64 bytes_sent, quint64 bytes_received);
- void file_request(QByteArray peer_id, quint64 file_size, QString filename);
- void file_accepted_by_peer(QByteArray peer_id);
- void file_denied_by_peer(QByteArray peer_id);
+ // from remote peer to me
+ void file_progress(QByteArray peer_id, quint64 bytes_sent, quint64 bytes_received);
+ void file_request(QByteArray peer_id, quint64 file_size, QString filename);
+ void file_accepted_by_peer(QByteArray peer_id);
+ void file_denied_by_peer(QByteArray peer_id);
- void file_paused_incoming(QByteArray peer_id);
- void file_resumed_incoming(QByteArray peer_id);
- void file_cancelled_incoming(QByteArray peer_id);
- void file_ioerror_incoming(QByteArray peer_id);
+ void file_paused_incoming(QByteArray peer_id);
+ void file_resumed_incoming(QByteArray peer_id);
+ void file_cancelled_incoming(QByteArray peer_id);
+ void file_ioerror_incoming(QByteArray peer_id);
- void file_paused_outgoing(QByteArray peer_id);
- void file_resumed_outgoing(QByteArray peer_id);
- void file_cancelled_outgoing(QByteArray peer_id);
- void file_ioerror_outgoing(QByteArray peer_id);
+ void file_paused_outgoing(QByteArray peer_id);
+ void file_resumed_outgoing(QByteArray peer_id);
+ void file_cancelled_outgoing(QByteArray peer_id);
+ void file_ioerror_outgoing(QByteArray peer_id);
- void file_finished_incoming(QByteArray peer_id);
- void file_peer_disconnected(QByteArray peer_id);
+ void file_finished_incoming(QByteArray peer_id);
+ void file_peer_disconnected(QByteArray peer_id);
- //from me (file transfer dialog shown to user) to remote peer
- void file_accepted_by_me(QByteArray peer_id);
- void file_denied_by_me(QByteArray peer_id);
- void file_cancelled_by_me(QByteArray peer_id, FileTransferDialog *from);
- void file_paused_by_me(QByteArray peer_id, FileTransferDialog *from);
- void file_resumed_by_me(QByteArray peer_id, FileTransferDialog *from);
+ //from me (file transfer dialog shown to user) to remote peer
+ void file_accepted_by_me(QByteArray peer_id);
+ void file_denied_by_me(QByteArray peer_id);
+ void file_cancelled_by_me(QByteArray peer_id, FileTransferDialog *from);
+ void file_paused_by_me(QByteArray peer_id, FileTransferDialog *from);
+ void file_resumed_by_me(QByteArray peer_id, FileTransferDialog *from);
- void send_file(QByteArray peer_id);
+ void send_file(QByteArray peer_id);
- void file_finished_outgoing(QByteArray peer_id);
+ void file_finished_outgoing(QByteArray peer_id);
};
diff --git a/pica-client/history.cpp b/pica-client/history.cpp
index b3883dd..933e2a9 100644
--- a/pica-client/history.cpp
+++ b/pica-client/history.cpp
@@ -2,138 +2,138 @@
#include <QDebug>
History::History(QString storage, QByteArray my_id)
- : me_(my_id)
+ : me_(my_id)
{
- dbconn=QSqlDatabase::addDatabase("QSQLITE");
- dbconn.setDatabaseName(storage);
+ dbconn = QSqlDatabase::addDatabase("QSQLITE");
+ dbconn.setDatabaseName(storage);
- if (!dbconn.open())
- {
- lasterr=dbconn.lastError();
- return;
- }
+ if (!dbconn.open())
+ {
+ lasterr = dbconn.lastError();
+ return;
+ }
- QSqlQuery query;
+ QSqlQuery query;
- query.exec("PRAGMA foreign_keys=ON;");
+ query.exec("PRAGMA foreign_keys=ON;");
- //check result, if foreign keys support is on
+ //check result, if foreign keys support is on
}
void History::Add(QByteArray peer_id, QString message, bool is_me)
{
- QSqlQuery query;
+ QSqlQuery query;
- query.prepare(
- "insert into \"history\" (\"contact_id\", \"account_id\", \"is_me\", \"is_delivered\", \"message\", \"id\", \"timestamp\") \
+ query.prepare(
+ "insert into \"history\" (\"contact_id\", \"account_id\", \"is_me\", \"is_delivered\", \"message\", \"id\", \"timestamp\") \
values (:contact_id, :account_id, :is_me, :is_delivered, :message, null, strftime('%s','now'));"
- );
+ );
- query.bindValue(":contact_id", peer_id);
- query.bindValue(":account_id", me_);
+ query.bindValue(":contact_id", peer_id);
+ query.bindValue(":account_id", me_);
- if (is_me)
- {
- query.bindValue(":is_me", 1);
- query.bindValue(":is_delivered", 0);
- }
- else
- {
- query.bindValue(":is_me", 0);
- query.bindValue(":is_delivered", 1);
- }
+ if (is_me)
+ {
+ query.bindValue(":is_me", 1);
+ query.bindValue(":is_delivered", 0);
+ }
+ else
+ {
+ query.bindValue(":is_me", 0);
+ query.bindValue(":is_delivered", 1);
+ }
- query.bindValue(":message", message);
+ query.bindValue(":message", message);
- query.exec();
+ query.exec();
- lasterr=query.lastError();
+ lasterr = query.lastError();
}
void History::SetDelivered(QByteArray peer_id)
{
- QSqlQuery query;
+ QSqlQuery query;
- query.prepare("update history set is_delivered=1 where id in \
+ query.prepare("update history set is_delivered=1 where id in \
(select id from history where \
is_delivered=0 and is_me=1 and contact_id=:peer_id and account_id=:me order by id asc limit 1)"
- );
+ );
- query.bindValue(":peer_id", peer_id);
- query.bindValue(":me", me_);
+ query.bindValue(":peer_id", peer_id);
+ query.bindValue(":me", me_);
- query.exec();
- lasterr=query.lastError();
+ query.exec();
+ lasterr = query.lastError();
}
QList<History::HistoryRecord> History::GetMessages(QByteArray peer_id, quint32 start_timestamp, quint32 end_timestamp)
{
- QList<HistoryRecord> L;
- HistoryRecord r;
- QSqlQuery query;
+ QList<HistoryRecord> L;
+ HistoryRecord r;
+ QSqlQuery query;
- query.setForwardOnly(true);
- query.prepare("select contact_id, is_me, is_delivered, timestamp, message from history \
+ query.setForwardOnly(true);
+ query.prepare("select contact_id, is_me, is_delivered, timestamp, message from history \
where contact_id=:peer_id and account_id=:me and timestamp >= :start and timestamp <=:end order by id"
- );
+ );
- query.bindValue(":peer_id", peer_id);
- query.bindValue(":me", me_);
- query.bindValue(":start", start_timestamp);
- query.bindValue(":end", end_timestamp);
- query.exec();
+ query.bindValue(":peer_id", peer_id);
+ query.bindValue(":me", me_);
+ query.bindValue(":start", start_timestamp);
+ query.bindValue(":end", end_timestamp);
+ query.exec();
- lasterr=query.lastError();
+ lasterr = query.lastError();
- if (lasterr.isValid())
- return L;
+ if (lasterr.isValid())
+ return L;
- while(query.next())
- {
- r.peer_id = query.value(0).toByteArray();
- r.is_me = query.value(1).toBool();
- r.is_delivered = query.value(2).toBool();
- r.timestamp = query.value(3).toUInt();
- r.message = query.value(4).toString();
+ while(query.next())
+ {
+ r.peer_id = query.value(0).toByteArray();
+ r.is_me = query.value(1).toBool();
+ r.is_delivered = query.value(2).toBool();
+ r.timestamp = query.value(3).toUInt();
+ r.message = query.value(4).toString();
- L<<r;
- }
+ L << r;
+ }
- return L;
+ return L;
}
QMap<QByteArray, QList<QString> > History::GetUndeliveredMessages()
{
- QMap<QByteArray, QList<QString> > M;
- QSqlQuery query;
+ QMap<QByteArray, QList<QString> > M;
+ QSqlQuery query;
- query.setForwardOnly(true);
- query.prepare("select contact_id, message from history \
+ query.setForwardOnly(true);
+ query.prepare("select contact_id, message from history \
where account_id=:me and is_delivered=0 and is_me=1 order by id"
- );
+ );
- query.bindValue(":me", me_);
- query.exec();
+ query.bindValue(":me", me_);
+ query.exec();
- lasterr=query.lastError();
+ lasterr = query.lastError();
- if (lasterr.isValid())
- return M;
+ if (lasterr.isValid())
+ return M;
- while(query.next())
- {
- M[query.value(0).toByteArray()] << query.value(1).toString();
- }
+ while(query.next())
+ {
+ M[query.value(0).toByteArray()] << query.value(1).toString();
+ }
- return M;
+ return M;
}
bool History::isOK()
{
- return !lasterr.isValid();
+ return !lasterr.isValid();
}
QString History::GetLastError()
{
- return lasterr.text();
+ return lasterr.text();
}
diff --git a/pica-client/history.h b/pica-client/history.h
index 6fc1e08..916f80e 100644
--- a/pica-client/history.h
+++ b/pica-client/history.h
@@ -10,28 +10,28 @@
class History
{
public:
- struct HistoryRecord
- {
- QByteArray peer_id;
- bool is_me;
- bool is_delivered;
- quint32 timestamp;
- QString message;
- };
+ struct HistoryRecord
+ {
+ QByteArray peer_id;
+ bool is_me;
+ bool is_delivered;
+ quint32 timestamp;
+ QString message;
+ };
- History(QString storage, QByteArray my_id);
- void Add(QByteArray peer_id, QString message, bool is_me);//is_me - true - message from me to peer, false - from peer to me
- void SetDelivered(QByteArray peer_id); //mark first undelivered message from me to peer as delivered
- QList<HistoryRecord> GetMessages(QByteArray peer_id, quint32 start_timestamp, quint32 end_timestamp);
- QMap<QByteArray, QList<QString> > GetUndeliveredMessages();
- bool isOK();
- QString GetLastError();
+ History(QString storage, QByteArray my_id);
+ void Add(QByteArray peer_id, QString message, bool is_me);//is_me - true - message from me to peer, false - from peer to me
+ void SetDelivered(QByteArray peer_id); //mark first undelivered message from me to peer as delivered
+ QList<HistoryRecord> GetMessages(QByteArray peer_id, quint32 start_timestamp, quint32 end_timestamp);
+ QMap<QByteArray, QList<QString> > GetUndeliveredMessages();
+ bool isOK();
+ QString GetLastError();
private:
- QSqlDatabase dbconn;
- QSqlError lasterr;
+ QSqlDatabase dbconn;
+ QSqlError lasterr;
- QByteArray me_;
+ QByteArray me_;
};
#endif // HISTORY_H
diff --git a/pica-client/main.cpp b/pica-client/main.cpp
index 1441b5c..cadc6d5 100644
--- a/pica-client/main.cpp
+++ b/pica-client/main.cpp
@@ -49,27 +49,27 @@ QString snd_newmessage("share\\picapica-snd-newmessage.wav");
static bool create_database()
{
- QMessageBox msgBox;
+ QMessageBox msgBox;
- QSqlDatabase dbconn=QSqlDatabase::addDatabase("QSQLITE");
- dbconn.setDatabaseName(config_dbname);
+ QSqlDatabase dbconn = QSqlDatabase::addDatabase("QSQLITE");
+ dbconn.setDatabaseName(config_dbname);
- if (!dbconn.open())
- {
+ if (!dbconn.open())
+ {
- msgBox.setText(dbconn.lastError().text());
- msgBox.exec();
- return false;
- }
+ msgBox.setText(dbconn.lastError().text());
+ msgBox.exec();
+ return false;
+ }
- QSqlQuery query;
+ QSqlQuery query;
- query.exec("PRAGMA foreign_keys=ON;");
+ query.exec("PRAGMA foreign_keys=ON;");
- if (query.lastError().isValid())
- goto showerror;
+ if (query.lastError().isValid())
+ goto showerror;
- query.exec("create table accounts \
+ query.exec("create table accounts \
(\
id blob primary key, \
name varchar(64), \
@@ -78,10 +78,10 @@ static bool create_database()
ca_file varchar(255) default null \
);");
- if (query.lastError().isValid())
- goto showerror;
+ if (query.lastError().isValid())
+ goto showerror;
- query.exec("create table contacts \
+ query.exec("create table contacts \
(\
id blob,\
name varchar(64), \
@@ -92,11 +92,11 @@ static bool create_database()
foreign key(account_id) references accounts(id) on delete cascade\
);");
- if (query.lastError().isValid())
- goto showerror;
+ if (query.lastError().isValid())
+ goto showerror;
- query.exec(
- "create table nodes \
+ query.exec(
+ "create table nodes \
(\
address varchar(255) not null,\
port int not null,\
@@ -104,14 +104,14 @@ static bool create_database()
inactive_count int not null,\
constraint pk primary key (address,port) on conflict replace \
);");
- query.exec("insert into nodes values(\"picapica.im\", 2233, 0, 0);");
- query.exec("insert into nodes values(\"picapica.im\", 2299, 0, 0);");
- query.exec("insert into nodes values(\"picapica.ge\", 2299, 0, 0);");
+ query.exec("insert into nodes values(\"picapica.im\", 2233, 0, 0);");
+ query.exec("insert into nodes values(\"picapica.im\", 2299, 0, 0);");
+ query.exec("insert into nodes values(\"picapica.ge\", 2299, 0, 0);");
- if (query.lastError().isValid())
- goto showerror;
+ if (query.lastError().isValid())
+ goto showerror;
- query.exec("create table history \
+ query.exec("create table history \
(\
id integer primary key autoincrement, \
contact_id blob not null, \
@@ -122,77 +122,77 @@ static bool create_database()
message text(65536) not null, \
foreign key(account_id) references accounts(id) on delete cascade\
);"
- );
+ );
- if (query.lastError().isValid())
- goto showerror;
+ if (query.lastError().isValid())
+ goto showerror;
- query.exec("create table schema_version \
+ query.exec("create table schema_version \
( \
ver integer primary key, \
timestamp int not null \
);"
- );
+ );
- if (query.lastError().isValid())
- goto showerror;
+ if (query.lastError().isValid())
+ goto showerror;
- query.exec("create table settings \
+ query.exec("create table settings \
( \
name varchar(255) not null, \
value varchar(255) not null, \
constraint pk primary key (name) on conflict replace \
);"
- );
+ );
- if (query.lastError().isValid())
- goto showerror;
+ if (query.lastError().isValid())
+ goto showerror;
- query.exec("insert into schema_version values (3, strftime('%s','now'));"); //current schema version. update when needed
+ query.exec("insert into schema_version values (3, strftime('%s','now'));"); //current schema version. update when needed
- if (query.lastError().isValid())
- showerror:
- {
- msgBox.setText(query.lastError().text());
- msgBox.exec();
- return false;
- }
+ if (query.lastError().isValid())
+showerror:
+ {
+ msgBox.setText(query.lastError().text());
+ msgBox.exec();
+ return false;
+ }
- return true;
+ return true;
}
static bool update_database()
{
- QMessageBox msgBox;
- int schema_ver;
+ QMessageBox msgBox;
+ int schema_ver;
- QSqlDatabase dbconn=QSqlDatabase::addDatabase("QSQLITE");
- dbconn.setDatabaseName(config_dbname);
+ QSqlDatabase dbconn = QSqlDatabase::addDatabase("QSQLITE");
+ dbconn.setDatabaseName(config_dbname);
- if (!dbconn.open())
- {
+ if (!dbconn.open())
+ {
- msgBox.setText(dbconn.lastError().text());
- msgBox.exec();
- return false;
- }
+ msgBox.setText(dbconn.lastError().text());
+ msgBox.exec();
+ return false;
+ }
- QSqlQuery query;
+ QSqlQuery query;
- //checking if table schema_version exists. If not, then database belongs to pica-client before 0.5.3 version
- query.exec("select count(*) from sqlite_master where name=\"schema_version\"");
- query.next();
+ //checking if table schema_version exists. If not, then database belongs to pica-client before 0.5.3 version
+ query.exec("select count(*) from sqlite_master where name=\"schema_version\"");
+ query.next();
- if (query.lastError().isValid())
- goto showerror;
+ if (query.lastError().isValid())
+ goto showerror;
- if (query.value(0).toInt() == 0)
- {
- //--------updating from pre0.5.3 pica-client database
- msgBox.setText("Updating database to newer version");
- msgBox.exec();
+ if (query.value(0).toInt() == 0)
+ {
+ //--------updating from pre0.5.3 pica-client database
+ msgBox.setText("Updating database to newer version");
+ msgBox.exec();
- query.exec("create table history \
+ query.exec("create table history \
(\
id integer primary key autoincrement, \
contact_id int not null, \
@@ -203,60 +203,60 @@ static bool update_database()
message text(65536) not null, \
foreign key(account_id) references accounts(id) on delete cascade\
);"
- );
+ );
- if (query.lastError().isValid())
- goto showerror;
+ if (query.lastError().isValid())
+ goto showerror;
- query.exec("\
+ query.exec("\
create table schema_version \
( \
ver integer primary key, \
timestamp int not null \
);"
- );
+ );
- if (query.lastError().isValid())
- goto showerror;
+ if (query.lastError().isValid())
+ goto showerror;
- query.exec("insert into schema_version values (1, strftime('%s','now'));");
- //--------------------------------------------------
- schema_ver = 1;
- }
- else
- {
- query.exec("select max(ver) from schema_version");
- query.next();
+ query.exec("insert into schema_version values (1, strftime('%s','now'));");
+ //--------------------------------------------------
+ schema_ver = 1;
+ }
+ else
+ {
+ query.exec("select max(ver) from schema_version");
+ query.next();
- if (query.lastError().isValid())
- goto showerror;
+ if (query.lastError().isValid())
+ goto showerror;
- schema_ver = query.value(0).toInt();
- }
+ schema_ver = query.value(0).toInt();
+ }
- if (schema_ver == 1)
- {
- query.exec("PRAGMA foreign_keys=OFF;");
+ if (schema_ver == 1)
+ {
+ query.exec("PRAGMA foreign_keys=OFF;");
- if (query.lastError().isValid())
- goto showerror;
+ if (query.lastError().isValid())
+ goto showerror;
- query.exec("alter table accounts rename to accounts_old_schemav1;");
+ query.exec("alter table accounts rename to accounts_old_schemav1;");
- if (query.lastError().isValid())
- goto showerror;
+ if (query.lastError().isValid())
+ goto showerror;
- query.exec("alter table contacts rename to contacts_old_schemav1;");
+ query.exec("alter table contacts rename to contacts_old_schemav1;");
- if (query.lastError().isValid())
- goto showerror;
+ if (query.lastError().isValid())
+ goto showerror;
- query.exec("alter table history rename to history_old_schemav1;");
+ query.exec("alter table history rename to history_old_schemav1;");
- if (query.lastError().isValid())
- goto showerror;
+ if (query.lastError().isValid())
+ goto showerror;
- query.exec("create table accounts \
+ query.exec("create table accounts \
(\
id blob primary key, \
name varchar(64), \
@@ -264,12 +264,12 @@ static bool update_database()
pkey_file varchar(255) not null, \
ca_file varchar(255) default null \
);"
- );
+ );
- if (query.lastError().isValid())
- goto showerror;
+ if (query.lastError().isValid())
+ goto showerror;
- query.exec("create table contacts \
+ query.exec("create table contacts \
(\
id blob,\
name varchar(64), \
@@ -279,12 +279,12 @@ static bool update_database()
primary key(id, account_id),\
foreign key(account_id) references accounts(id) on delete cascade\
);"
- );
+ );
- if (query.lastError().isValid())
- goto showerror;
+ if (query.lastError().isValid())
+ goto showerror;
- query.exec("create table history \
+ query.exec("create table history \
(\
id integer primary key autoincrement, \
contact_id blob not null, \
@@ -295,96 +295,96 @@ static bool update_database()
message text(65536) not null, \
foreign key(account_id) references accounts(id) on delete cascade\
);"
- );
- if (query.lastError().isValid())
- goto showerror;
+ );
+ if (query.lastError().isValid())
+ goto showerror;
- query.exec("alter table accounts_old_schemav1 add column new_id blob;");
- query.exec("alter table contacts_old_schemav1 add column new_id blob;");
+ query.exec("alter table accounts_old_schemav1 add column new_id blob;");
+ query.exec("alter table contacts_old_schemav1 add column new_id blob;");
- if (query.lastError().isValid())
- goto showerror;
+ if (query.lastError().isValid())
+ goto showerror;
- query.exec("select id, cert_file from accounts_old_schemav1");
- if (query.lastError().isValid())
- goto showerror;
+ query.exec("select id, cert_file from accounts_old_schemav1");
+ if (query.lastError().isValid())
+ goto showerror;
- while(query.next())
- {
- quint32 old_id;
- QString cert_file;
- QSqlQuery q;
- QByteArray new_id(PICA_ID_SIZE, 0);
+ while(query.next())
+ {
+ quint32 old_id;
+ QString cert_file;
+ QSqlQuery q;
+ QByteArray new_id(PICA_ID_SIZE, 0);
- old_id = query.value(0).toUInt();
- cert_file = query.value(1).toString();
+ old_id = query.value(0).toUInt();
+ cert_file = query.value(1).toString();
- if (PICA_get_id_from_cert_file(cert_file.toUtf8().constData(), (unsigned char*)new_id.data()))
- {
- QSqlQuery q;
+ if (PICA_get_id_from_cert_file(cert_file.toUtf8().constData(), (unsigned char*)new_id.data()))
+ {
+ QSqlQuery q;
- q.prepare("update accounts_old_schemav1 set new_id = :new_id where id = :id");
- q.bindValue(":new_id", new_id);
- q.bindValue(":id", old_id);
- q.exec();
- }
- }
+ q.prepare("update accounts_old_schemav1 set new_id = :new_id where id = :id");
+ q.bindValue(":new_id", new_id);
+ q.bindValue(":id", old_id);
+ q.exec();
+ }
+ }
- query.exec("select id, cert_pem from contacts_old_schemav1");
- if (query.lastError().isValid())
- goto showerror;
+ query.exec("select id, cert_pem from contacts_old_schemav1");
+ if (query.lastError().isValid())
+ goto showerror;
- while(query.next())
- {
- quint32 old_id;
- QString cert_pem;
- QSqlQuery q;
- QByteArray new_id(PICA_ID_SIZE, 0);
+ while(query.next())
+ {
+ quint32 old_id;
+ QString cert_pem;
+ QSqlQuery q;
+ QByteArray new_id(PICA_ID_SIZE, 0);
- old_id = query.value(0).toUInt();
- cert_pem = query.value(1).toString();
+ old_id = query.value(0).toUInt();
+ cert_pem = query.value(1).toString();
- if (PICA_get_id_from_cert_string(cert_pem.toUtf8().constData(), (unsigned char *)new_id.data()))
- {
- QSqlQuery q;
+ if (PICA_get_id_from_cert_string(cert_pem.toUtf8().constData(), (unsigned char *)new_id.data()))
+ {
+ QSqlQuery q;
- q.prepare("update contacts_old_schemav1 set new_id = :new_id where id = :id");
- q.bindValue(":new_id", new_id);
- q.bindValue(":id", old_id);
- q.exec();
- }
- }
+ q.prepare("update contacts_old_schemav1 set new_id = :new_id where id = :id");
+ q.bindValue(":new_id", new_id);
+ q.bindValue(":id", old_id);
+ q.exec();
+ }
+ }
- query.exec("insert into accounts select new_id, name, cert_file, pkey_file, ca_file from accounts_old_schemav1 where new_id is not null");
+ query.exec("insert into accounts select new_id, name, cert_file, pkey_file, ca_file from accounts_old_schemav1 where new_id is not null");
- if (query.lastError().isValid())
- goto showerror;
+ if (query.lastError().isValid())
+ goto showerror;
- query.exec("insert into contacts select c.new_id, c.name, c.cert_pem, a.new_id, 1 from accounts_old_schemav1 as a, contacts_old_schemav1 as c on c.account_id = a.id where c.new_id is not null and a.new_id is not null");
+ query.exec("insert into contacts select c.new_id, c.name, c.cert_pem, a.new_id, 1 from accounts_old_schemav1 as a, contacts_old_schemav1 as c on c.account_id = a.id where c.new_id is not null and a.new_id is not null");
- if (query.lastError().isValid())
- goto showerror;
+ if (query.lastError().isValid())
+ goto showerror;
- query.exec("insert into history select h.id, c.new_id, a.new_id, h.timestamp, h.is_me, h.is_delivered, h.message \
+ query.exec("insert into history select h.id, c.new_id, a.new_id, h.timestamp, h.is_me, h.is_delivered, h.message \
from history_old_schemav1 as h, accounts_old_schemav1 as a, contacts_old_schemav1 as c on h.contact_id = c.id and h.account_id = a.id and a.id = c.account_id where c.new_id is not null and a.new_id is not null order by h.id");
- if (query.lastError().isValid())
- goto showerror;
+ if (query.lastError().isValid())
+ goto showerror;
- query.exec("insert into schema_version values (2, strftime('%s','now'));");
- schema_ver = 2;
- }
+ query.exec("insert into schema_version values (2, strftime('%s','now'));");
+ schema_ver = 2;
+ }
if (schema_ver == 2)
{
- query.exec("create table settings \
+ query.exec("create table settings \
( \
name varchar(255) not null, \
value varchar(255) not null, \
constraint pk primary key (name) on conflict replace \
);"
- );
+ );
if (query.lastError().isValid())
goto showerror;
@@ -393,106 +393,106 @@ static bool update_database()
schema_ver = 3;
}
-if (query.lastError().isValid())
+ if (query.lastError().isValid())
showerror:
- {
- msgBox.setText(query.lastError().text() + " " + query.lastQuery());
- msgBox.exec();
- return false;
- }
+ {
+ msgBox.setText(query.lastError().text() + " " + query.lastQuery());
+ msgBox.exec();
+ return false;
+ }
- return true;
+ return true;
}
static bool create_config_dir()
{
- QMessageBox msgBox;
- config_dir=QDir::homePath()+QDir::separator() +QString(PICA_CLIENT_CONFIGDIR);
-
- if (!QFile::exists(config_dir))
- {
- QDir dir;
-
- if (!dir.mkpath(config_dir))
- {
- msgBox.setText(QString(QObject::tr("Unable to create configuration directory:\n %1")).arg(config_dir));
- msgBox.exec();
- return false;
- }
- }
-
- config_dbname=config_dir+QDir::separator()+QString(PICA_CLIENT_STORAGEDB);
-
- if (!QFile::exists(config_dbname))
- {
- if (!create_database())
- return false;
- }
- else
- update_database();
-
- /*if (!QFile::exists(config_dir + QDir::separator() + PICA_CLIENT_DHPARAMFILE))
- {
- OpenSSLTool osslt;
- msgBox.setText(QString(QObject::tr("Diffie-Hellman parameters will be generated. Please wait. This process can take several minutes...")));
- msgBox.exec();
-
- if (!osslt.GenDHParam(4096, config_dir + QDir::separator() + PICA_CLIENT_DHPARAMFILE))
- {
- msgBox.setText(QString(QObject::tr("Failed to generate Diffie-Hellman parameters")));
- msgBox.exec();
- return false;
- }
- }*/
- /*
- QString dh_error_message;
-
- if (!DHParam::VerifyGenerated(NULL))
- {
- QMessageBox dhmsgBox;
- dhmsgBox.setText(QObject::tr("Do you want to generate new Diffie-Hellman parameter file?"));
- dhmsgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
- dhmsgBox.setDefaultButton(QMessageBox::No);
- dhmsgBox.setInformativeText(QObject::tr("If you press \"Yes\", new Diffie-Hellman parameter generation will be started. It is a CPU intensive process and can take undetermined amount of time (1 - 20 minutes on modern computers). Default DH parameter file will be used for starting secure communications until the new DH parameter generation is finished.\nIf you press \"No\", default DH parameter file distributed with Pica Pica Messenger will be used for every communication session."));
- switch (dhmsgBox.exec())
- {
- case QMessageBox::No:
-
- DHParam::UseDefault();
-
- break;
-
- case QMessageBox::Yes:
-
- DHParam::StartNewDHParamGeneration(&dh_error_message);
-
- break;
- }
-
- if (!DHParam::VerifyDefault(&dh_error_message))
- {
- msgBox.setText(dh_error_message);
- msgBox.setIcon(QMessageBox::Warning);
- msgBox.setStandardButtons(QMessageBox::Ok);
- msgBox.exec();
- }
- }*/
-
- return true;
+ QMessageBox msgBox;
+ config_dir = QDir::homePath() + QDir::separator() + QString(PICA_CLIENT_CONFIGDIR);
+
+ if (!QFile::exists(config_dir))
+ {
+ QDir dir;
+
+ if (!dir.mkpath(config_dir))
+ {
+ msgBox.setText(QString(QObject::tr("Unable to create configuration directory:\n %1")).arg(config_dir));
+ msgBox.exec();
+ return false;
+ }
+ }
+
+ config_dbname = config_dir + QDir::separator() + QString(PICA_CLIENT_STORAGEDB);
+
+ if (!QFile::exists(config_dbname))
+ {
+ if (!create_database())
+ return false;
+ }
+ else
+ update_database();
+
+ /*if (!QFile::exists(config_dir + QDir::separator() + PICA_CLIENT_DHPARAMFILE))
+ {
+ OpenSSLTool osslt;
+ msgBox.setText(QString(QObject::tr("Diffie-Hellman parameters will be generated. Please wait. This process can take several minutes...")));
+ msgBox.exec();
+
+ if (!osslt.GenDHParam(4096, config_dir + QDir::separator() + PICA_CLIENT_DHPARAMFILE))
+ {
+ msgBox.setText(QString(QObject::tr("Failed to generate Diffie-Hellman parameters")));
+ msgBox.exec();
+ return false;
+ }
+ }*/
+ /*
+ QString dh_error_message;
+
+ if (!DHParam::VerifyGenerated(NULL))
+ {
+ QMessageBox dhmsgBox;
+ dhmsgBox.setText(QObject::tr("Do you want to generate new Diffie-Hellman parameter file?"));
+ dhmsgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
+ dhmsgBox.setDefaultButton(QMessageBox::No);
+ dhmsgBox.setInformativeText(QObject::tr("If you press \"Yes\", new Diffie-Hellman parameter generation will be started. It is a CPU intensive process and can take undetermined amount of time (1 - 20 minutes on modern computers). Default DH parameter file will be used for starting secure communications until the new DH parameter generation is finished.\nIf you press \"No\", default DH parameter file distributed with Pica Pica Messenger will be used for every communication session."));
+ switch (dhmsgBox.exec())
+ {
+ case QMessageBox::No:
+
+ DHParam::UseDefault();
+
+ break;
+
+ case QMessageBox::Yes:
+
+ DHParam::StartNewDHParamGeneration(&dh_error_message);
+
+ break;
+ }
+
+ if (!DHParam::VerifyDefault(&dh_error_message))
+ {
+ msgBox.setText(dh_error_message);
+ msgBox.setIcon(QMessageBox::Warning);
+ msgBox.setStandardButtons(QMessageBox::Ok);
+ msgBox.exec();
+ }
+ }*/
+
+ return true;
}
int main(int argc, char *argv[])
{
- QApplication a(argc, argv);
+ QApplication a(argc, argv);
- if (!create_config_dir())
- return -1;
+ if (!create_config_dir())
+ return -1;
#ifndef WIN32
- picapica_ico_sit = QIcon(PICA_INSTALLPREFIX"/share/pica-client/picapica-icon-sit.png");
- picapica_ico_fly = QIcon(PICA_INSTALLPREFIX"/share/pica-client/picapica-icon-fly.png");
+ picapica_ico_sit = QIcon(PICA_INSTALLPREFIX"/share/pica-client/picapica-icon-sit.png");
+ picapica_ico_fly = QIcon(PICA_INSTALLPREFIX"/share/pica-client/picapica-icon-fly.png");
#else
picapica_ico_sit = QIcon("share\\picapica-icon-sit.png");
- picapica_ico_fly = QIcon("share\\picapica-icon-fly.png");
+ picapica_ico_fly = QIcon("share\\picapica-icon-fly.png");
#endif
Settings st(config_dbname);
@@ -504,30 +504,30 @@ int main(int argc, char *argv[])
sd.exec();
}
- PicaActionCenter ac;
- action_center = &ac;
+ PicaActionCenter ac;
+ action_center = &ac;
- AccountsWindow aw;
- accwindow = &aw;
+ AccountsWindow aw;
+ accwindow = &aw;
- SkyNet s;
- skynet=&s;
+ SkyNet s;
+ skynet = &s;
- PicaSysTray pst;
- systray = &pst;
+ PicaSysTray pst;
+ systray = &pst;
- AskPassword askpsw;
- askpassword=&askpsw;
+ AskPassword askpsw;
+ askpassword = &askpsw;
- MsgUIRouter muir;
- msguirouter = &muir;
+ MsgUIRouter muir;
+ msguirouter = &muir;
- FileTransferController ftc;
- ftctrl = &ftc;
+ FileTransferController ftc;
+ ftctrl = &ftc;
- aw.show();
+ aw.show();
- a.setQuitOnLastWindowClosed(false);
+ a.setQuitOnLastWindowClosed(false);
- return a.exec();
+ return a.exec();
}
diff --git a/pica-client/mainwindow.cpp b/pica-client/mainwindow.cpp
index 8f4702f..c3e8a47 100644
--- a/pica-client/mainwindow.cpp
+++ b/pica-client/mainwindow.cpp
@@ -9,142 +9,142 @@
MainWindow::MainWindow(QWidget *parent) :
- QMainWindow(parent),
- ui(new Ui::MainWindow)
+ QMainWindow(parent),
+ ui(new Ui::MainWindow)
{
- ui->setupUi(this);
+ ui->setupUi(this);
- QVBoxLayout *layout;
+ QVBoxLayout *layout;
- layout = new QVBoxLayout;
- contact_list = new ContactListWidget;
- status = new QComboBox;
- notifications = new QListWidget();
- bt_showhide_notifications = new QPushButton();
- hide_notifications();
+ layout = new QVBoxLayout;
+ contact_list = new ContactListWidget;
+ status = new QComboBox;
+ notifications = new QListWidget();
+ bt_showhide_notifications = new QPushButton();
+ hide_notifications();
- status->setMinimumHeight(36);
- notifications->setMinimumHeight(48);
+ status->setMinimumHeight(36);
+ notifications->setMinimumHeight(48);
- layout->addWidget(contact_list, 8);
- layout->addWidget(bt_showhide_notifications, 0, Qt::AlignRight);
- layout->addWidget(notifications, 1, Qt::AlignBottom);
- layout->addWidget(status,0,Qt::AlignBottom);
+ layout->addWidget(contact_list, 8);
+ layout->addWidget(bt_showhide_notifications, 0, Qt::AlignRight);
+ layout->addWidget(notifications, 1, Qt::AlignBottom);
+ layout->addWidget(status, 0, Qt::AlignBottom);
- centralWidget()->setLayout(layout);
- setWindowIcon(picapica_ico_sit);
+ centralWidget()->setLayout(layout);
+ setWindowIcon(picapica_ico_sit);
- createMenus();
+ createMenus();
- //for (int i=0;i<255;i++)
- // contact_list->addItem(QString("test %1").arg(i));
+ //for (int i=0;i<255;i++)
+ // contact_list->addItem(QString("test %1").arg(i));
- status->addItem(picapica_ico_fly, QString(tr("Connected")));
- status->addItem(picapica_ico_sit, QString(tr("Disconnected")));
+ status->addItem(picapica_ico_fly, QString(tr("Connected")));
+ status->addItem(picapica_ico_sit, QString(tr("Disconnected")));
- connect(skynet, SIGNAL(BecameSelfAware()), this, SLOT(set_online()));
- connect(skynet, SIGNAL(LostSelfAwareness()), this, SLOT(set_offline()));
- connect(status, SIGNAL(currentIndexChanged(int)), this, SLOT(status_changed(int)));
- connect(bt_showhide_notifications, SIGNAL(clicked()), this, SLOT(showhide_click()));
- connect(skynet, SIGNAL(ContactsUpdated()), contact_list, SLOT(Reload()));
+ connect(skynet, SIGNAL(BecameSelfAware()), this, SLOT(set_online()));
+ connect(skynet, SIGNAL(LostSelfAwareness()), this, SLOT(set_offline()));
+ connect(status, SIGNAL(currentIndexChanged(int)), this, SLOT(status_changed(int)));
+ connect(bt_showhide_notifications, SIGNAL(clicked()), this, SLOT(showhide_click()));
+ connect(skynet, SIGNAL(ContactsUpdated()), contact_list, SLOT(Reload()));
}
MainWindow::~MainWindow()
{
- delete ui;
+ delete ui;
}
void MainWindow::set_offline()
{
- SetStatus(false);
+ SetStatus(false);
}
void MainWindow::set_online()
{
- SetStatus(true);
+ SetStatus(true);
}
void MainWindow::status_changed(int index)
{
- if (status_change_disable_flag)
- return;
-
- if (index == 0 && !skynet->isSelfAware())
- {
- Accounts::AccountRecord curr_acc = skynet->CurrentAccount();
- skynet->Join(curr_acc);
- }
- if (1 == index && skynet->isSelfAware())
- skynet->Exit();
+ if (status_change_disable_flag)
+ return;
+
+ if (index == 0 && !skynet->isSelfAware())
+ {
+ Accounts::AccountRecord curr_acc = skynet->CurrentAccount();
+ skynet->Join(curr_acc);
+ }
+ if (1 == index && skynet->isSelfAware())
+ skynet->Exit();
}
void MainWindow::SetStatus(bool connected)
{
- status_change_disable_flag = true;
-
- if (connected)
- {
- status->setCurrentIndex(0);
- setWindowTitle(tr("Pica Pica Messenger - ") +
- Accounts::GetCurrentAccount().id.toBase64().left(8) + "...");
- }
- else
- {
- status->setCurrentIndex(1);
- setWindowTitle(tr("Pica Pica Messenger - Disconnected"));
- }
-
- status_change_disable_flag = false;
+ status_change_disable_flag = true;
+
+ if (connected)
+ {
+ status->setCurrentIndex(0);
+ setWindowTitle(tr("Pica Pica Messenger - ") +
+ Accounts::GetCurrentAccount().id.toBase64().left(8) + "...");
+ }
+ else
+ {
+ status->setCurrentIndex(1);
+ setWindowTitle(tr("Pica Pica Messenger - Disconnected"));
+ }
+
+ status_change_disable_flag = false;
}
void MainWindow::createMenus()
{
- contactsMenu=menuBar()->addMenu(tr("&Contacts"));
- contactsMenu->addAction(contact_list->addcontactAct);
- contactsMenu->addSeparator();
- contactsMenu->addAction(action_center->ExitAct());
+ contactsMenu = menuBar()->addMenu(tr("&Contacts"));
+ contactsMenu->addAction(contact_list->addcontactAct);
+ contactsMenu->addSeparator();
+ contactsMenu->addAction(action_center->ExitAct());
- accountMenu=menuBar()->addMenu(tr("&Account"));
- accountMenu->addAction(action_center->ShowMyIDAct());
+ accountMenu = menuBar()->addMenu(tr("&Account"));
+ accountMenu->addAction(action_center->ShowMyIDAct());
- nodesMenu=menuBar()->addMenu(tr("&Nodes"));
+ nodesMenu = menuBar()->addMenu(tr("&Nodes"));
settingsMenu = menuBar()->addMenu(tr("&Settings"));
settingsMenu->addAction(action_center->SettingsAct());
- helpMenu=menuBar()->addMenu(tr("&Help"));
- helpMenu->addAction(action_center->AboutAct());
+ helpMenu = menuBar()->addMenu(tr("&Help"));
+ helpMenu->addAction(action_center->AboutAct());
}
void MainWindow::show_notifications()
{
- notifications->show();
- bt_showhide_notifications->setText(tr("Hide Notifications"));
- status_notifications_hidden = false;
+ notifications->show();
+ bt_showhide_notifications->setText(tr("Hide Notifications"));
+ status_notifications_hidden = false;
}
void MainWindow::hide_notifications()
{
- notifications->hide();
- bt_showhide_notifications->setText(tr("Show Notifications"));
- status_notifications_hidden = true;
+ notifications->hide();
+ bt_showhide_notifications->setText(tr("Show Notifications"));
+ status_notifications_hidden = true;
}
void MainWindow::showhide_click()
{
- if (status_notifications_hidden)
- show_notifications();
- else
- hide_notifications();
+ if (status_notifications_hidden)
+ show_notifications();
+ else
+ hide_notifications();
}
void MainWindow::AddNotification(QString &text, bool is_critical)
{
- notifications->addItem(text);
- notifications->item(notifications->count() -1) ->setForeground(QBrush(QColor(230, 10, 10, 196)));
+ notifications->addItem(text);
+ notifications->item(notifications->count() - 1) ->setForeground(QBrush(QColor(230, 10, 10, 196)));
if (is_critical)
show_notifications();
diff --git a/pica-client/mainwindow.h b/pica-client/mainwindow.h
index b61f31a..7fec577 100644
--- a/pica-client/mainwindow.h
+++ b/pica-client/mainwindow.h
@@ -11,47 +11,48 @@
#include "contactlistwidget.h"
#include "askpassword.h"
-namespace Ui {
- class MainWindow;
+namespace Ui
+{
+class MainWindow;
}
class MainWindow : public QMainWindow
{
- Q_OBJECT
+ Q_OBJECT
public:
- explicit MainWindow(QWidget *parent = 0);
- ~MainWindow();
+ explicit MainWindow(QWidget *parent = 0);
+ ~MainWindow();
void AddNotification(QString &text, bool is_critical);
protected:
private:
- void createMenus();
-
- Ui::MainWindow *ui;
- ContactListWidget *contact_list;
- QComboBox *status;
- QListWidget *notifications;
- QPushButton *bt_showhide_notifications;
-
- QMenu *contactsMenu;
- QMenu *helpMenu;
- QMenu *nodesMenu;
- QMenu *accountMenu;
+ void createMenus();
+
+ Ui::MainWindow *ui;
+ ContactListWidget *contact_list;
+ QComboBox *status;
+ QListWidget *notifications;
+ QPushButton *bt_showhide_notifications;
+
+ QMenu *contactsMenu;
+ QMenu *helpMenu;
+ QMenu *nodesMenu;
+ QMenu *accountMenu;
QMenu *settingsMenu;
- bool status_change_disable_flag;
- void SetStatus(bool connected);
- bool status_notifications_hidden;
+ bool status_change_disable_flag;
+ void SetStatus(bool connected);
+ bool status_notifications_hidden;
private slots:
- void set_online();
- void set_offline();
- void status_changed(int index);
- void show_notifications();
- void hide_notifications();
- void showhide_click();
+ void set_online();
+ void set_offline();
+ void status_changed(int index);
+ void show_notifications();
+ void hide_notifications();
+ void showhide_click();
};
diff --git a/pica-client/msguirouter.cpp b/pica-client/msguirouter.cpp
index 84bbf56..b8c5843 100644
--- a/pica-client/msguirouter.cpp
+++ b/pica-client/msguirouter.cpp
@@ -17,125 +17,125 @@
активировать имеющиеся.
*/
MsgUIRouter::MsgUIRouter(QObject *parent) :
- QObject(parent)
+ QObject(parent)
{
- connect(skynet, SIGNAL(MessageReceived(QByteArray,QString)), this, SLOT(msg_from_peer(QByteArray,QString)));
- connect(skynet, SIGNAL(UnableToDeliver(QByteArray,QString)), this, SLOT(delivery_failed(QByteArray,QString)));
- connect(skynet, SIGNAL(Delivered(QByteArray)), this, SLOT(delivered(QByteArray)));
- connect(skynet, SIGNAL(CertificateForged(QByteArray,QString,QString)), this, SLOT(scary_cert_message(QByteArray,QString,QString)));
+ connect(skynet, SIGNAL(MessageReceived(QByteArray, QString)), this, SLOT(msg_from_peer(QByteArray, QString)));
+ connect(skynet, SIGNAL(UnableToDeliver(QByteArray, QString)), this, SLOT(delivery_failed(QByteArray, QString)));
+ connect(skynet, SIGNAL(Delivered(QByteArray)), this, SLOT(delivered(QByteArray)));
+ connect(skynet, SIGNAL(CertificateForged(QByteArray, QString, QString)), this, SLOT(scary_cert_message(QByteArray, QString, QString)));
connect(skynet, SIGNAL(StatusMsg(QString, bool)), this, SLOT(notification(QString, bool)));
- connect(systray, SIGNAL(doubleclicked()), this, SLOT(trayicon_dclick()));
+ connect(systray, SIGNAL(doubleclicked()), this, SLOT(trayicon_dclick()));
}
void MsgUIRouter::trayicon_dclick()
{
- if (mainwindow == NULL)
- {
- accwindow->showNormal();
- accwindow->activateWindow();
- accwindow->raise();
- return;
- }
-
-
- if (blinkqueue.isEmpty())
- {
- mainwindow->showNormal();
- mainwindow->activateWindow();
- mainwindow->raise();
- }
- else
- {
- QByteArray blinker_id = blinkqueue.takeFirst();
-
- if (chatwindows.contains(blinker_id))
- {
- chatwindows[blinker_id]->showNormal();
- chatwindows[blinker_id]->activateWindow();
- chatwindows[blinker_id]->raise();
- }
-
- if (blinkqueue.isEmpty())
- {
- systray->StopBlinking();
- }
- }
+ if (mainwindow == NULL)
+ {
+ accwindow->showNormal();
+ accwindow->activateWindow();
+ accwindow->raise();
+ return;
+ }
+
+
+ if (blinkqueue.isEmpty())
+ {
+ mainwindow->showNormal();
+ mainwindow->activateWindow();
+ mainwindow->raise();
+ }
+ else
+ {
+ QByteArray blinker_id = blinkqueue.takeFirst();
+
+ if (chatwindows.contains(blinker_id))
+ {
+ chatwindows[blinker_id]->showNormal();
+ chatwindows[blinker_id]->activateWindow();
+ chatwindows[blinker_id]->raise();
+ }
+
+ if (blinkqueue.isEmpty())
+ {
+ systray->StopBlinking();
+ }
+ }
}
void MsgUIRouter::create_chatwindow(QByteArray peer_id)
{
- ChatWindow *cw;
+ ChatWindow *cw;
- cw = new ChatWindow(peer_id);
+ cw = new ChatWindow(peer_id);
- chatwindows[peer_id] = cw;
+ chatwindows[peer_id] = cw;
- connect(cw, SIGNAL(msg_input(QString,ChatWindow*)), this, SLOT(msg_to_peer(QString,ChatWindow*)));
- connect(cw, SIGNAL(chatwindow_close(ChatWindow*)), this, SLOT(chatwindow_closed(ChatWindow*)));
- connect(cw, SIGNAL(contacts_update()), skynet, SIGNAL(ContactsUpdated()));
- connect(skynet, SIGNAL(ContactsUpdated()), cw, SLOT(set_peer_name()));
+ connect(cw, SIGNAL(msg_input(QString, ChatWindow*)), this, SLOT(msg_to_peer(QString, ChatWindow*)));
+ connect(cw, SIGNAL(chatwindow_close(ChatWindow*)), this, SLOT(chatwindow_closed(ChatWindow*)));
+ connect(cw, SIGNAL(contacts_update()), skynet, SIGNAL(ContactsUpdated()));
+ connect(skynet, SIGNAL(ContactsUpdated()), cw, SLOT(set_peer_name()));
- cw->show();
+ cw->show();
}
void MsgUIRouter::msg_from_peer(QByteArray from, QString msg)
{
- Sound::play(snd_newmessage);
-
- if ( ! chatwindows.contains(from))
- {
- create_chatwindow(from);
- }
-
- chatwindows[from]->msg_from_peer(msg);
-
- if (!chatwindows[from]->isActiveWindow())
- {
- if (blinkqueue.isEmpty())
- {
- systray->StartBlinking();
- blinkqueue.append(from);
- }
- else if (!blinkqueue.contains(from))
- {
- blinkqueue.append(from);
- }
-
- }
+ Sound::play(snd_newmessage);
+
+ if ( ! chatwindows.contains(from))
+ {
+ create_chatwindow(from);
+ }
+
+ chatwindows[from]->msg_from_peer(msg);
+
+ if (!chatwindows[from]->isActiveWindow())
+ {
+ if (blinkqueue.isEmpty())
+ {
+ systray->StartBlinking();
+ blinkqueue.append(from);
+ }
+ else if (!blinkqueue.contains(from))
+ {
+ blinkqueue.append(from);
+ }
+
+ }
}
void MsgUIRouter::msg_to_peer(QString msg, ChatWindow *sender_window)
{
- skynet->SendMessage(sender_window->getPeerId(), msg);
-
- if (!blinkqueue.isEmpty())
- {
- blinkqueue.removeAll(sender_window->getPeerId());
- if (blinkqueue.isEmpty())
- {
- systray->StopBlinking();
- }
- }
+ skynet->SendMessage(sender_window->getPeerId(), msg);
+
+ if (!blinkqueue.isEmpty())
+ {
+ blinkqueue.removeAll(sender_window->getPeerId());
+ if (blinkqueue.isEmpty())
+ {
+ systray->StopBlinking();
+ }
+ }
}
void MsgUIRouter::start_chat(QByteArray peer_id)
{
- if ( ! chatwindows.contains(peer_id))
- {
- create_chatwindow(peer_id);
- }
- else
- {
- chatwindows[peer_id]->showNormal();
- chatwindows[peer_id]->activateWindow();
- chatwindows[peer_id]->raise();
- }
+ if ( ! chatwindows.contains(peer_id))
+ {
+ create_chatwindow(peer_id);
+ }
+ else
+ {
+ chatwindows[peer_id]->showNormal();
+ chatwindows[peer_id]->activateWindow();
+ chatwindows[peer_id]->raise();
+ }
}
void MsgUIRouter::chatwindow_closed(ChatWindow *sender_window)
{
- chatwindows.remove(sender_window->getPeerId());
+ chatwindows.remove(sender_window->getPeerId());
}
void MsgUIRouter::delivery_failed(QByteArray to, QString msg)
@@ -148,26 +148,26 @@ void MsgUIRouter::delivery_failed(QByteArray to, QString msg)
void MsgUIRouter::delivered(QByteArray to)
{
- if (chatwindows.contains(to))
- {
- chatwindows[to]->msg_delivered();
- }
- else
- {
- History h(config_dbname, Accounts::GetCurrentAccount().id);
-
- h.SetDelivered(to);
- }
+ if (chatwindows.contains(to))
+ {
+ chatwindows[to]->msg_delivered();
+ }
+ else
+ {
+ History h(config_dbname, Accounts::GetCurrentAccount().id);
+
+ h.SetDelivered(to);
+ }
}
void MsgUIRouter::scary_cert_message(QByteArray peer_id, QString received_cert, QString stored_cert)
{
- ForgedCertDialog fcd(peer_id, received_cert, stored_cert);
- fcd.exec();
+ ForgedCertDialog fcd(peer_id, received_cert, stored_cert);
+ fcd.exec();
}
void MsgUIRouter::notification(QString text, bool is_critical)
{
- if (mainwindow)
+ if (mainwindow)
mainwindow->AddNotification(text, is_critical);
}
diff --git a/pica-client/msguirouter.h b/pica-client/msguirouter.h
index aefef2c..f931b4d 100644
--- a/pica-client/msguirouter.h
+++ b/pica-client/msguirouter.h
@@ -10,32 +10,32 @@
class MsgUIRouter : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- explicit MsgUIRouter(QObject *parent = 0);
-
+ explicit MsgUIRouter(QObject *parent = 0);
+
signals:
-
+
public slots:
- void msg_to_peer(QString msg, ChatWindow *sender_window);
- void msg_from_peer(QByteArray from, QString msg);
+ void msg_to_peer(QString msg, ChatWindow *sender_window);
+ void msg_from_peer(QByteArray from, QString msg);
- void chatwindow_closed(ChatWindow *sender_window);
- void start_chat(QByteArray peer_id);
+ void chatwindow_closed(ChatWindow *sender_window);
+ void start_chat(QByteArray peer_id);
- void delivery_failed(QByteArray to, QString msg);
- void delivered(QByteArray to);
+ void delivery_failed(QByteArray to, QString msg);
+ void delivered(QByteArray to);
- void scary_cert_message(QByteArray peer_id, QString received_cert, QString stored_cert);
+ void scary_cert_message(QByteArray peer_id, QString received_cert, QString stored_cert);
void notification(QString text, bool is_critical);
- void trayicon_dclick();
+ void trayicon_dclick();
private:
- QMap<QByteArray,ChatWindow*> chatwindows;
- QLinkedList<QByteArray> blinkqueue;
+ QMap<QByteArray, ChatWindow*> chatwindows;
+ QLinkedList<QByteArray> blinkqueue;
+
+ void create_chatwindow(QByteArray peer_id);
- void create_chatwindow(QByteArray peer_id);
-
};
#endif // MSGUIROUTER_H
diff --git a/pica-client/nodes.cpp b/pica-client/nodes.cpp
index eb8bfcc..93ae5e2 100644
--- a/pica-client/nodes.cpp
+++ b/pica-client/nodes.cpp
@@ -2,51 +2,51 @@
Nodes::Nodes(QString storage)
{
- dbconn=QSqlDatabase::addDatabase("QSQLITE");
- dbconn.setDatabaseName(storage);
-
- if (!dbconn.open())
- {
- lasterr=dbconn.lastError();
- return;
- }
+ dbconn = QSqlDatabase::addDatabase("QSQLITE");
+ dbconn.setDatabaseName(storage);
+
+ if (!dbconn.open())
+ {
+ lasterr = dbconn.lastError();
+ return;
+ }
//check if table nodes exists
}
void Nodes::Add(NodeRecord &n)
{
- QSqlQuery query;
+ QSqlQuery query;
- query.prepare("insert into nodes (address, port, last_active, inactive_count) values (:addr, :port, strftime('%s','now'), 0)");
- query.bindValue(":addr",n.address);
- query.bindValue(":port",n.port);
- query.exec();
+ query.prepare("insert into nodes (address, port, last_active, inactive_count) values (:addr, :port, strftime('%s','now'), 0)");
+ query.bindValue(":addr", n.address);
+ query.bindValue(":port", n.port);
+ query.exec();
- lasterr=query.lastError();
+ lasterr = query.lastError();
}
QList<Nodes::NodeRecord> Nodes::GetNodes()
{
- QList<NodeRecord> L;
- NodeRecord r;
- QSqlQuery query;
+ QList<NodeRecord> L;
+ NodeRecord r;
+ QSqlQuery query;
- query.setForwardOnly(true);
- query.exec("select address, port from nodes order by inactive_count asc, last_active desc");
- lasterr=query.lastError();
+ query.setForwardOnly(true);
+ query.exec("select address, port from nodes order by inactive_count asc, last_active desc");
+ lasterr = query.lastError();
- if (lasterr.isValid())
- return L;
+ if (lasterr.isValid())
+ return L;
- while(query.next())
- {
- r.address =query.value(0).toString();
- r.port =query.value(1).toUInt();
+ while(query.next())
+ {
+ r.address = query.value(0).toString();
+ r.port = query.value(1).toUInt();
- L<<r;
- }
+ L << r;
+ }
- return L;
+ return L;
}
void Nodes::MakeClean()
@@ -56,18 +56,18 @@ void Nodes::MakeClean()
void Nodes::UpdateStatus(NodeRecord &n, bool alive)
{
- QSqlQuery query;
+ QSqlQuery query;
- if (alive)
- query.prepare("update nodes set last_active = strftime('%s','now'), inactive_count = 0 where address = :addr and port = :port");
- else
- query.prepare("update nodes set inactive_count = inactive_count + 1 where address = :addr and port = :port");
+ if (alive)
+ query.prepare("update nodes set last_active = strftime('%s','now'), inactive_count = 0 where address = :addr and port = :port");
+ else
+ query.prepare("update nodes set inactive_count = inactive_count + 1 where address = :addr and port = :port");
- query.bindValue(":addr",n.address);
- query.bindValue(":port",n.port);
- query.exec();
+ query.bindValue(":addr", n.address);
+ query.bindValue(":port", n.port);
+ query.exec();
- lasterr=query.lastError();
+ lasterr = query.lastError();
}
diff --git a/pica-client/nodes.h b/pica-client/nodes.h
index a24fed2..edbf5e0 100644
--- a/pica-client/nodes.h
+++ b/pica-client/nodes.h
@@ -9,21 +9,21 @@
class Nodes
{
public:
- struct NodeRecord
- {
- QString address;
- quint16 port;
- };
+ struct NodeRecord
+ {
+ QString address;
+ quint16 port;
+ };
- Nodes(QString storage);
- void Add(NodeRecord &n);
- QList<NodeRecord> GetNodes();
- void MakeClean();//remove old inactive node records
- void UpdateStatus(NodeRecord &n, bool alive);
+ Nodes(QString storage);
+ void Add(NodeRecord &n);
+ QList<NodeRecord> GetNodes();
+ void MakeClean();//remove old inactive node records
+ void UpdateStatus(NodeRecord &n, bool alive);
private:
- QSqlDatabase dbconn;
- QSqlError lasterr;
+ QSqlDatabase dbconn;
+ QSqlError lasterr;
};
diff --git a/pica-client/nodethread.cpp b/pica-client/nodethread.cpp
index ee6504f..bf93e83 100644
--- a/pica-client/nodethread.cpp
+++ b/pica-client/nodethread.cpp
@@ -7,112 +7,112 @@
QMutex NodeThread::finished_mutex;
NodeThread::NodeThread(Nodes::NodeRecord &addr, bool *completed, PICA_acc *acc, PICA_c2n **pica_conn, QMutex *wm) :
- QThread(0)
+ QThread(0)
{
- node_addr = addr;
- finished_flag = completed;
- user_account = acc;
- connection = pica_conn;
- write_mutex = wm;
- exit = 0;
- start();
+ node_addr = addr;
+ finished_flag = completed;
+ user_account = acc;
+ connection = pica_conn;
+ write_mutex = wm;
+ exit = 0;
+ start();
}
void NodeThread::run()
{
- int ret;
- exit = 0;
-
- /*ret = PICA_new_c2n(node_addr.address.toUtf8().constData(),
- node_addr.port,
- user_account.CA_file.toUtf8().constData(),
- user_account.cert_file.toUtf8().constData(),
- user_account.pkey_file.toUtf8().constData(),
- DHParam::GetDHParamFilename().toUtf8().constData(),
- AskPassword::ask_password_cb,
- &ci);*/
- ret = PICA_new_c2n(user_account, node_addr.address.toUtf8().constData(), node_addr.port, &ci);
-
- switch(ret)
- {
- case PICA_OK:
-
- emit NodeStatusChanged(node_addr.address, node_addr.port, true);
-
- finished_mutex.lock();
- if (*finished_flag)
- {
- PICA_close_c2n(ci);
- exit = 1;
- }
- else
- {
- *finished_flag = true;
- *connection = ci;
- emit ConnectedToNode(node_addr.address, node_addr.port, this);
- }
- finished_mutex.unlock();
-
-
-
- break;
-
- case PICA_ERRSOCK:
- case PICA_ERRDNSRESOLVE:
-
- emit NodeStatusChanged(node_addr.address, node_addr.port, false);
-
- exit = 1;
- break;
-
- case PICA_ERRSSL:
- exit = 1;
- break;
-
- case PICA_ERRPROTONEW:
-
- emit ErrorMsg(QString("Node %1:%2 has newer protocol version. Please check if update for pica-client is available")
- .arg(node_addr.address)
- .arg(node_addr.port)
- );
- exit = 1;
- break;
-
- case PICA_ERRPROTOOLD:
-
- emit ErrorMsg(QString("Node %1:%2 has older protocol. Disconnected.")
- .arg(node_addr.address)
- .arg(node_addr.port)
- );
-
- exit = 1;
- break;
-
- default:
- exit = 1;
- }
-
- if (exit)
- return;
-
- do
- {
- write_mutex->lock();
- if (PICA_read(ci,10000) != PICA_OK || PICA_write(ci) != PICA_OK)
- exit=1;
- write_mutex->unlock();
- msleep(300);
- }
- while (!exit);
-
- write_mutex->lock();
- PICA_close_c2n(ci);
- *connection = NULL;
- write_mutex->unlock();
+ int ret;
+ exit = 0;
+
+ /*ret = PICA_new_c2n(node_addr.address.toUtf8().constData(),
+ node_addr.port,
+ user_account.CA_file.toUtf8().constData(),
+ user_account.cert_file.toUtf8().constData(),
+ user_account.pkey_file.toUtf8().constData(),
+ DHParam::GetDHParamFilename().toUtf8().constData(),
+ AskPassword::ask_password_cb,
+ &ci);*/
+ ret = PICA_new_c2n(user_account, node_addr.address.toUtf8().constData(), node_addr.port, &ci);
+
+ switch(ret)
+ {
+ case PICA_OK:
+
+ emit NodeStatusChanged(node_addr.address, node_addr.port, true);
+
+ finished_mutex.lock();
+ if (*finished_flag)
+ {
+ PICA_close_c2n(ci);
+ exit = 1;
+ }
+ else
+ {
+ *finished_flag = true;
+ *connection = ci;
+ emit ConnectedToNode(node_addr.address, node_addr.port, this);
+ }
+ finished_mutex.unlock();
+
+
+
+ break;
+
+ case PICA_ERRSOCK:
+ case PICA_ERRDNSRESOLVE:
+
+ emit NodeStatusChanged(node_addr.address, node_addr.port, false);
+
+ exit = 1;
+ break;
+
+ case PICA_ERRSSL:
+ exit = 1;
+ break;
+
+ case PICA_ERRPROTONEW:
+
+ emit ErrorMsg(QString("Node %1:%2 has newer protocol version. Please check if update for pica-client is available")
+ .arg(node_addr.address)
+ .arg(node_addr.port)
+ );
+ exit = 1;
+ break;
+
+ case PICA_ERRPROTOOLD:
+
+ emit ErrorMsg(QString("Node %1:%2 has older protocol. Disconnected.")
+ .arg(node_addr.address)
+ .arg(node_addr.port)
+ );
+
+ exit = 1;
+ break;
+
+ default:
+ exit = 1;
+ }
+
+ if (exit)
+ return;
+
+ do
+ {
+ write_mutex->lock();
+ if (PICA_read(ci, 10000) != PICA_OK || PICA_write(ci) != PICA_OK)
+ exit = 1;
+ write_mutex->unlock();
+ msleep(300);
+ }
+ while (!exit);
+
+ write_mutex->lock();
+ PICA_close_c2n(ci);
+ *connection = NULL;
+ write_mutex->unlock();
}
void NodeThread::CloseThread()
{
- exit = 1;
+ exit = 1;
}
diff --git a/pica-client/nodethread.h b/pica-client/nodethread.h
index 8974255..d7154a1 100644
--- a/pica-client/nodethread.h
+++ b/pica-client/nodethread.h
@@ -10,29 +10,29 @@
class NodeThread : public QThread
{
- Q_OBJECT
+ Q_OBJECT
public:
- explicit NodeThread( Nodes::NodeRecord &addr, bool *completed, PICA_acc *acc,struct PICA_c2n **pica_conn, QMutex *wm);
- void CloseThread();
+ explicit NodeThread( Nodes::NodeRecord &addr, bool *completed, PICA_acc *acc, struct PICA_c2n **pica_conn, QMutex *wm);
+ void CloseThread();
private:
- void run();
- static QMutex finished_mutex;
+ void run();
+ static QMutex finished_mutex;
- QMutex *write_mutex;
+ QMutex *write_mutex;
- bool *finished_flag;
- Nodes::NodeRecord node_addr;
- struct PICA_c2n *ci;
- struct PICA_acc *user_account;
- struct PICA_c2n **connection;
+ bool *finished_flag;
+ Nodes::NodeRecord node_addr;
+ struct PICA_c2n *ci;
+ struct PICA_acc *user_account;
+ struct PICA_c2n **connection;
- int exit;
+ int exit;
signals:
- void NodeStatusChanged(QString addr, quint16 port, bool alive);
- void ConnectedToNode(QString addr, quint16 port, NodeThread *thread);
- void ErrorMsg(QString msg);
+ void NodeStatusChanged(QString addr, quint16 port, bool alive);
+ void ConnectedToNode(QString addr, quint16 port, NodeThread *thread);
+ void ErrorMsg(QString msg);
public slots:
};
diff --git a/pica-client/openssltool.cpp b/pica-client/openssltool.cpp
index dafd0ef..39b5092 100644
--- a/pica-client/openssltool.cpp
+++ b/pica-client/openssltool.cpp
@@ -12,177 +12,178 @@ OpenSSLTool::OpenSSLTool()
QString OpenSSLTool::NameFromCertFile(QString cert_file)
{
- //
- QProcess openssl;
+ //
+ QProcess openssl;
- openssl.start("openssl",QStringList()<<"x509"<<"-in"<<cert_file<<"-subject"<<"-nameopt"<<"oneline,-esc_msb,utf8"<<"-noout");
- if (!openssl.waitForStarted())
- return QString();
+ openssl.start("openssl", QStringList() << "x509" << "-in" << cert_file << "-subject" << "-nameopt" << "oneline,-esc_msb,utf8" << "-noout");
+ if (!openssl.waitForStarted())
+ return QString();
- if (!openssl.waitForFinished())
- return QString();
+ if (!openssl.waitForFinished())
+ return QString();
- QByteArray result = openssl.readAll();
- QRegExp rxOld(REGEXOLD);
- QRegExp rx(REGEXNEW);
+ QByteArray result = openssl.readAll();
+ QRegExp rxOld(REGEXOLD);
+ QRegExp rx(REGEXNEW);
- QString name=QString::fromUtf8( result.constData());
+ QString name = QString::fromUtf8( result.constData());
- if (name.contains(rxOld))
- {
- name=rxOld.cap(1);
- }
- else if (name.contains(rx))
- {
- name=rx.cap(1);
- }
+ if (name.contains(rxOld))
+ {
+ name = rxOld.cap(1);
+ }
+ else if (name.contains(rx))
+ {
+ name = rx.cap(1);
+ }
- //
-return name;
+ //
+ return name;
}
QString OpenSSLTool::NameFromCertString(QString cert_pem)
{
- QProcess openssl;
+ QProcess openssl;
- openssl.start("openssl",QStringList()<<"x509"<<"-subject"<<"-nameopt"<<"oneline,-esc_msb,utf8"<<"-noout");
- if (!openssl.waitForStarted())
- return QString();
+ openssl.start("openssl", QStringList() << "x509" << "-subject" << "-nameopt" << "oneline,-esc_msb,utf8" << "-noout");
+ if (!openssl.waitForStarted())
+ return QString();
- openssl.write(cert_pem.toAscii());
+ openssl.write(cert_pem.toAscii());
- if (!openssl.waitForFinished())
- return QString();
+ if (!openssl.waitForFinished())
+ return QString();
- QByteArray result = openssl.readAll();
- QRegExp rxOld(REGEXOLD);
- QRegExp rx(REGEXNEW);
+ QByteArray result = openssl.readAll();
+ QRegExp rxOld(REGEXOLD);
+ QRegExp rx(REGEXNEW);
- QString name=QString::fromUtf8( result.constData());
+ QString name = QString::fromUtf8( result.constData());
- if (name.contains(rxOld))
- {
- name=rxOld.cap(1);
- }
- else if (name.contains(rx))
- {
- name=rx.cap(1);
- }
+ if (name.contains(rxOld))
+ {
+ name = rxOld.cap(1);
+ }
+ else if (name.contains(rx))
+ {
+ name = rx.cap(1);
+ }
- //
-return name;
+ //
+ return name;
}
QString OpenSSLTool::CertTextFromString(QString cert_pem)
{
- QProcess openssl;
- qint64 ret;
- char *data;
- QByteArray ba;
+ QProcess openssl;
+ qint64 ret;
+ char *data;
+ QByteArray ba;
- openssl.start("openssl", QStringList()<<"x509"<<"-noout"<<"-text"<<"-nameopt"<<"multiline,-esc_msb,utf8");
+ openssl.start("openssl", QStringList() << "x509" << "-noout" << "-text" << "-nameopt" << "multiline,-esc_msb,utf8");
- if (!openssl.waitForStarted())
- return QString();
+ if (!openssl.waitForStarted())
+ return QString();
- ba = cert_pem.toAscii();
- ret = openssl.write(data = (char*)ba.constData());
- openssl.closeWriteChannel();
+ ba = cert_pem.toAscii();
+ ret = openssl.write(data = (char*)ba.constData());
+ openssl.closeWriteChannel();
- if (!openssl.waitForFinished())
- return QString();
+ if (!openssl.waitForFinished())
+ return QString();
- return QString::fromUtf8(openssl.readAllStandardOutput().constData());
+ return QString::fromUtf8(openssl.readAllStandardOutput().constData());
}
bool OpenSSLTool::GenRSAKeySignal(quint32 numbits, QString keyfile, bool setpassword, QString password, QString rand, QObject *receiver, const char *finished_slot)
{
- QStringList args;
+ QStringList args;
- args <<"genrsa"<<"-out"<<keyfile;
+ args << "genrsa" << "-out" << keyfile;
- if (setpassword)
- args <<"-passout"<<"stdin"<<"-aes256";
+ if (setpassword)
+ args << "-passout" << "stdin" << "-aes256";
- if (!rand.isEmpty())
- args << "-rand"<<rand;
+ if (!rand.isEmpty())
+ args << "-rand" << rand;
- args <<QString::number(numbits);
+ args << QString::number(numbits);
- openssl_.start("openssl", args);
+ openssl_.start("openssl", args);
- if (!openssl_.waitForStarted())
- return false;
+ if (!openssl_.waitForStarted())
+ return false;
- if (setpassword)
- {
- openssl_.write((password + "\n").toAscii().constData());
- }
+ if (setpassword)
+ {
+ openssl_.write((password + "\n").toAscii().constData());
+ }
- openssl_.disconnect(&openssl_, SIGNAL(finished(int,QProcess::ExitStatus)), 0, 0);
- openssl_.connect(&openssl_, SIGNAL(finished(int,QProcess::ExitStatus)),receiver, finished_slot);
+ openssl_.disconnect(&openssl_, SIGNAL(finished(int, QProcess::ExitStatus)), 0, 0);
+ openssl_.connect(&openssl_, SIGNAL(finished(int, QProcess::ExitStatus)), receiver, finished_slot);
- return true;
+ return true;
}
bool OpenSSLTool::GenCertSignal(QString cert_file, QString keyfile, QString keypassword,
- QString subject, QObject *receiver, const char *finished_slot)
+ QString subject, QObject *receiver, const char *finished_slot)
{
- openssl_.start("openssl",
- QStringList()
- <<"req"
+ openssl_.start("openssl",
+ QStringList()
+ << "req"
#ifdef WIN32
- <<"-config"<<"openssl.cnf"
+ << "-config" << "openssl.cnf"
#endif
- <<"-out"<<cert_file
- <<"-key"<<keyfile
- <<"-subj"<<"/CN=" + subject
- <<"-new"
- <<"-x509"
- <<"-days"<<"3680"
- <<"-utf8"
- <<"-batch"
- <<"-passin"
- <<"stdin");
-
- if (!openssl_.waitForStarted())
- return false;
-
- openssl_.write((keypassword + "\n").toAscii().constData());
-
- openssl_.disconnect(&openssl_, SIGNAL(finished(int,QProcess::ExitStatus)), 0, 0);
- openssl_.connect(&openssl_, SIGNAL(finished(int,QProcess::ExitStatus)),receiver, finished_slot);
-
- return true;
+ << "-out" << cert_file
+ << "-key" << keyfile
+ << "-subj" << "/CN=" + subject
+ << "-new"
+ << "-x509"
+ << "-days" << "3680"
+ << "-utf8"
+ << "-batch"
+ << "-passin"
+ << "stdin");
+
+ if (!openssl_.waitForStarted())
+ return false;
+
+ openssl_.write((keypassword + "\n").toAscii().constData());
+
+ openssl_.disconnect(&openssl_, SIGNAL(finished(int, QProcess::ExitStatus)), 0, 0);
+ openssl_.connect(&openssl_, SIGNAL(finished(int, QProcess::ExitStatus)), receiver, finished_slot);
+
+ return true;
}
QString OpenSSLTool::ReadStdErr()
{
- return QString::fromUtf8(openssl_.readAllStandardError().constData());
+ return QString::fromUtf8(openssl_.readAllStandardError().constData());
}
QString OpenSSLTool::ReadStdOut()
{
- return QString::fromUtf8(openssl_.readAllStandardOutput().constData());
+ return QString::fromUtf8(openssl_.readAllStandardOutput().constData());
}
bool OpenSSLTool::GenDHParamSignal(quint32 numbits, QString output_file, QObject *receiver, const char *finished_slot)
-{//openssl dhparam -5 4096
- openssl_.start("openssl",
- QStringList()
- <<"dhparam"
- <<"-out"<<output_file
- <<"-5"
- <<QString::number(numbits));
+{
+ //openssl dhparam -5 4096
+ openssl_.start("openssl",
+ QStringList()
+ << "dhparam"
+ << "-out" << output_file
+ << "-5"
+ << QString::number(numbits));
- if (!openssl_.waitForStarted())
- return false;
+ if (!openssl_.waitForStarted())
+ return false;
- openssl_.disconnect(&openssl_, SIGNAL(finished(int,QProcess::ExitStatus)), 0, 0);
- openssl_.connect(&openssl_, SIGNAL(finished(int,QProcess::ExitStatus)), receiver, finished_slot);
+ openssl_.disconnect(&openssl_, SIGNAL(finished(int, QProcess::ExitStatus)), 0, 0);
+ openssl_.connect(&openssl_, SIGNAL(finished(int, QProcess::ExitStatus)), receiver, finished_slot);
- return true;
+ return true;
}
diff --git a/pica-client/openssltool.h b/pica-client/openssltool.h
index a5714fc..4196f12 100644
--- a/pica-client/openssltool.h
+++ b/pica-client/openssltool.h
@@ -7,23 +7,23 @@
class OpenSSLTool
{
public:
- OpenSSLTool();
+ OpenSSLTool();
- static QString NameFromCertFile(QString cert_file);
- static QString NameFromCertString(QString cert_pem);
- static QString CertTextFromString(QString cert_pem);
+ static QString NameFromCertFile(QString cert_file);
+ static QString NameFromCertString(QString cert_pem);
+ static QString CertTextFromString(QString cert_pem);
- bool GenRSAKeySignal(quint32 numbits, QString keyfile, bool setpassword,
- QString password, QString rand,QObject *receiver, const char *finished_slot);
- bool GenCertSignal(QString cert_file, QString keyfile, QString keypassword, QString subject, QObject *receiver, const char *finished_slot);
+ bool GenRSAKeySignal(quint32 numbits, QString keyfile, bool setpassword,
+ QString password, QString rand, QObject *receiver, const char *finished_slot);
+ bool GenCertSignal(QString cert_file, QString keyfile, QString keypassword, QString subject, QObject *receiver, const char *finished_slot);
- bool GenDHParamSignal(quint32 numbits, QString output_file, QObject *receiver, const char *finished_slot);
+ bool GenDHParamSignal(quint32 numbits, QString output_file, QObject *receiver, const char *finished_slot);
- QString ReadStdErr();
- QString ReadStdOut();
+ QString ReadStdErr();
+ QString ReadStdOut();
private:
- QProcess openssl_;
+ QProcess openssl_;
};
#endif // OPENSSLTOOL_H
diff --git a/pica-client/picaactioncenter.cpp b/pica-client/picaactioncenter.cpp
index 9303ca6..81c830d 100644
--- a/pica-client/picaactioncenter.cpp
+++ b/pica-client/picaactioncenter.cpp
@@ -12,22 +12,22 @@
#include <QMessageBox>
PicaActionCenter::PicaActionCenter(QObject *parent) :
- QObject(parent)
+ QObject(parent)
{
- exitAct = new QAction(tr("E&xit"),this);
- exitAct->setStatusTip(tr("Close Pica Pica messenger and exit"));
- connect(exitAct,SIGNAL(triggered()),this,SLOT(exit()));
+ exitAct = new QAction(tr("E&xit"), this);
+ exitAct->setStatusTip(tr("Close Pica Pica messenger and exit"));
+ connect(exitAct, SIGNAL(triggered()), this, SLOT(exit()));
- aboutAct = new QAction(tr("A&bout"),this);
- aboutAct->setStatusTip(tr("About Pica Pica Messenger"));
- connect(aboutAct,SIGNAL(triggered()),this,SLOT(about()));
+ aboutAct = new QAction(tr("A&bout"), this);
+ aboutAct->setStatusTip(tr("About Pica Pica Messenger"));
+ connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
- showmyidAct = new QAction(tr("Show My Pica Pica ID"), this);
- connect(showmyidAct, SIGNAL(triggered()), this, SLOT(showmyid()));
+ showmyidAct = new QAction(tr("Show My Pica Pica ID"), this);
+ connect(showmyidAct, SIGNAL(triggered()), this, SLOT(showmyid()));
- muteSoundsAct = new QAction(tr("&Mute Sounds"), this);
- muteSoundsAct->setCheckable(true);
- connect(muteSoundsAct, SIGNAL(triggered(bool)), this, SLOT(muteSounds(bool)));
+ muteSoundsAct = new QAction(tr("&Mute Sounds"), this);
+ muteSoundsAct->setCheckable(true);
+ connect(muteSoundsAct, SIGNAL(triggered(bool)), this, SLOT(muteSounds(bool)));
settingsAct = new QAction(tr("&Configure Messenger..."), this);
connect(settingsAct, SIGNAL(triggered(bool)), this, SLOT(showsettings()));
@@ -40,24 +40,24 @@ void PicaActionCenter::about()
#else
#define VERSION_STRING ""
#endif
- QMessageBox mbx;
- mbx.setWindowIcon(picapica_ico_sit);
- mbx.setIconPixmap(picapica_ico_sit.pixmap(32));
- mbx.setTextFormat(Qt::RichText);
- mbx.setText(tr("<b>Pica Pica Messenger "VERSION_STRING"<br>(c) 2012 - 2017 Anton Sviridenko</b><br>\
+ QMessageBox mbx;
+ mbx.setWindowIcon(picapica_ico_sit);
+ mbx.setIconPixmap(picapica_ico_sit.pixmap(32));
+ mbx.setTextFormat(Qt::RichText);
+ mbx.setText(tr("<b>Pica Pica Messenger "VERSION_STRING"<br>(c) 2012 - 2017 Anton Sviridenko</b><br>\
<a href=http://picapica.im>http://picapica.im</a><br><br>Contributors:<br>Daniil Ustinov - bugfixes<br>EXL - bugfixes<br><br>\
protocol version " PICA_PROTO_VER_STRING "<br>"
- "client protocol version " PICA_PROTO_CLIENT_VER_STRING));
- mbx.exec();
+ "client protocol version " PICA_PROTO_CLIENT_VER_STRING));
+ mbx.exec();
}
void PicaActionCenter::exit()
{
- if (mainwindow)
- mainwindow->close();
+ if (mainwindow)
+ mainwindow->close();
- skynet->Exit();
- QApplication::instance()->quit();
+ skynet->Exit();
+ QApplication::instance()->quit();
}
void PicaActionCenter::showsettings()
@@ -68,11 +68,11 @@ void PicaActionCenter::showsettings()
void PicaActionCenter::showmyid()
{
- ShowPicaIdDialog d(Accounts::GetCurrentAccount().name, Accounts::GetCurrentAccount().id, tr("My Current Account"));
- d.exec();
+ ShowPicaIdDialog d(Accounts::GetCurrentAccount().name, Accounts::GetCurrentAccount().id, tr("My Current Account"));
+ d.exec();
}
void PicaActionCenter::muteSounds(bool yes)
{
- Sound::mute(yes);
+ Sound::mute(yes);
}
diff --git a/pica-client/picaactioncenter.h b/pica-client/picaactioncenter.h
index 7fa98c4..721320b 100644
--- a/pica-client/picaactioncenter.h
+++ b/pica-client/picaactioncenter.h
@@ -6,31 +6,46 @@
class PicaActionCenter : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- explicit PicaActionCenter(QObject *parent = 0);
+ explicit PicaActionCenter(QObject *parent = 0);
+
+ QAction *AboutAct()
+ {
+ return aboutAct;
+ };
+ QAction *ExitAct()
+ {
+ return exitAct;
+ };
+ QAction *ShowMyIDAct()
+ {
+ return showmyidAct;
+ };
+ QAction *MuteSoundsAct()
+ {
+ return muteSoundsAct;
+ };
+ QAction *SettingsAct()
+ {
+ return settingsAct;
+ };
- QAction *AboutAct() {return aboutAct;};
- QAction *ExitAct() {return exitAct;};
- QAction *ShowMyIDAct() {return showmyidAct;};
- QAction *MuteSoundsAct() {return muteSoundsAct;};
- QAction *SettingsAct() {return settingsAct; };
-
private:
- QAction *aboutAct;
- QAction *exitAct;
- QAction *showmyidAct;
- QAction *muteSoundsAct;
+ QAction *aboutAct;
+ QAction *exitAct;
+ QAction *showmyidAct;
+ QAction *muteSoundsAct;
QAction *settingsAct;
signals:
-
+
public slots:
private slots:
- void about();
- void exit();
- void showmyid();
- void muteSounds(bool yes);
+ void about();
+ void exit();
+ void showmyid();
+ void muteSounds(bool yes);
void showsettings();
};
diff --git a/pica-client/picasystray.cpp b/pica-client/picasystray.cpp
index 8bc1e10..3c57683 100644
--- a/pica-client/picasystray.cpp
+++ b/pica-client/picasystray.cpp
@@ -10,71 +10,71 @@
#endif
PicaSysTray::PicaSysTray(QObject *parent) :
- QObject(parent), emptyicon_(32,32)
+ QObject(parent), emptyicon_(32, 32)
{
- systrayMenu_ = new QMenu();
+ systrayMenu_ = new QMenu();
- //Unity cannot into doubleclick on tray icon... :(
- QAction *activate = new QAction(tr("&Activate"), this);
- connect(activate, SIGNAL(triggered()), this, SIGNAL(doubleclicked()));
+ //Unity cannot into doubleclick on tray icon... :(
+ QAction *activate = new QAction(tr("&Activate"), this);
+ connect(activate, SIGNAL(triggered()), this, SIGNAL(doubleclicked()));
- systrayMenu_->addAction(action_center->AboutAct());
- systrayMenu_->addAction(action_center->MuteSoundsAct());
- systrayMenu_->addAction(activate);
- systrayMenu_->addSeparator();
- systrayMenu_->addAction(action_center->ExitAct());
+ systrayMenu_->addAction(action_center->AboutAct());
+ systrayMenu_->addAction(action_center->MuteSoundsAct());
+ systrayMenu_->addAction(activate);
+ systrayMenu_->addSeparator();
+ systrayMenu_->addAction(action_center->ExitAct());
- systray_ = new QSystemTrayIcon(picapica_ico_sit);
- systray_->setContextMenu(systrayMenu_);
- systray_->setToolTip("Pica Pica Messenger "VERSION_STRING);
- systray_->show();
+ systray_ = new QSystemTrayIcon(picapica_ico_sit);
+ systray_->setContextMenu(systrayMenu_);
+ systray_->setToolTip("Pica Pica Messenger "VERSION_STRING);
+ systray_->show();
- connect(systray_, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(systray_activated(QSystemTrayIcon::ActivationReason)));
- connect(skynet, SIGNAL(BecameSelfAware()), this, SLOT(skynet_became_self_aware()));
- connect(skynet, SIGNAL(LostSelfAwareness()), this, SLOT(skynet_lost_self_awareness()));
+ connect(systray_, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(systray_activated(QSystemTrayIcon::ActivationReason)));
+ connect(skynet, SIGNAL(BecameSelfAware()), this, SLOT(skynet_became_self_aware()));
+ connect(skynet, SIGNAL(LostSelfAwareness()), this, SLOT(skynet_lost_self_awareness()));
- emptyicon_.fill(Qt::transparent);
+ emptyicon_.fill(Qt::transparent);
}
void PicaSysTray::systray_activated(QSystemTrayIcon::ActivationReason r)
{
- if (r == QSystemTrayIcon::DoubleClick)
- {
- emit doubleclicked();
- }
+ if (r == QSystemTrayIcon::DoubleClick)
+ {
+ emit doubleclicked();
+ }
}
void PicaSysTray::skynet_became_self_aware()
{
- systray_->setIcon(picapica_ico_fly);
- systray_->setToolTip(Accounts::GetCurrentAccount().name + " - Pica Pica Messenger "VERSION_STRING);
+ systray_->setIcon(picapica_ico_fly);
+ systray_->setToolTip(Accounts::GetCurrentAccount().name + " - Pica Pica Messenger "VERSION_STRING);
}
void PicaSysTray::skynet_lost_self_awareness()
{
- systray_->setIcon(picapica_ico_sit);
+ systray_->setIcon(picapica_ico_sit);
}
void PicaSysTray::StartBlinking()
{
- blink_ = systray_->icon();
- timer_id_ = startTimer(300);
+ blink_ = systray_->icon();
+ timer_id_ = startTimer(300);
}
void PicaSysTray::StopBlinking()
{
- killTimer(timer_id_);
- systray_->setIcon(blink_);
+ killTimer(timer_id_);
+ systray_->setIcon(blink_);
}
void PicaSysTray::timerEvent(QTimerEvent *event)
{
-static int blinker;
+ static int blinker;
- blinker++ % 2 ? systray_->setIcon(blink_)
- :
- systray_->setIcon(QIcon(emptyicon_));
+ blinker++ % 2 ? systray_->setIcon(blink_)
+ :
+ systray_->setIcon(QIcon(emptyicon_));
}
diff --git a/pica-client/picasystray.h b/pica-client/picasystray.h
index 5743280..b6e6a24 100644
--- a/pica-client/picasystray.h
+++ b/pica-client/picasystray.h
@@ -11,29 +11,29 @@
class PicaSysTray : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- explicit PicaSysTray(QObject *parent = 0);
- void StartBlinking();
- void StopBlinking();
-
+ explicit PicaSysTray(QObject *parent = 0);
+ void StartBlinking();
+ void StopBlinking();
+
signals:
- void doubleclicked();
-
+ void doubleclicked();
+
public slots:
private:
- QSystemTrayIcon *systray_;
- QMenu *systrayMenu_;
- void timerEvent(QTimerEvent *event);
- int timer_id_;
- QIcon blink_;
- QPixmap emptyicon_;
+ QSystemTrayIcon *systray_;
+ QMenu *systrayMenu_;
+ void timerEvent(QTimerEvent *event);
+ int timer_id_;
+ QIcon blink_;
+ QPixmap emptyicon_;
private slots:
- void systray_activated(QSystemTrayIcon::ActivationReason);
- void skynet_became_self_aware();//debug
- void skynet_lost_self_awareness();//debug
+ void systray_activated(QSystemTrayIcon::ActivationReason);
+ void skynet_became_self_aware();//debug
+ void skynet_lost_self_awareness();//debug
};
#endif // PICASYSTRAY_H
diff --git a/pica-client/settings.cpp b/pica-client/settings.cpp
index 4b5485d..4651bf2 100644
--- a/pica-client/settings.cpp
+++ b/pica-client/settings.cpp
@@ -2,20 +2,20 @@
Settings::Settings(QString storage)
{
- dbconn=QSqlDatabase::addDatabase("QSQLITE");
- dbconn.setDatabaseName(storage);
+ dbconn = QSqlDatabase::addDatabase("QSQLITE");
+ dbconn.setDatabaseName(storage);
- if (!dbconn.open())
- {
- lasterr=dbconn.lastError();
- return;
- }
+ if (!dbconn.open())
+ {
+ lasterr = dbconn.lastError();
+ return;
+ }
}
QString Settings::GetLastError()
{
- return lasterr.text();
+ return lasterr.text();
}
bool Settings::isEmpty()
@@ -38,32 +38,32 @@ bool Settings::isEmpty()
QVariant Settings::loadValue(QString name, QVariant defval)
{
- QSqlQuery query;
+ QSqlQuery query;
- query.prepare("select value from settings where name = :name");
- query.bindValue(":name", name);
- query.exec();
+ query.prepare("select value from settings where name = :name");
+ query.bindValue(":name", name);
+ query.exec();
- lasterr = query.lastError();
+ lasterr = query.lastError();
- query.next();
+ query.next();
- if (!query.isValid())
- {
- return defval;
- }
+ if (!query.isValid())
+ {
+ return defval;
+ }
- return query.value(0);
+ return query.value(0);
}
void Settings::storeValue(QString name, QString val)
{
- QSqlQuery query;
+ QSqlQuery query;
- query.prepare("insert into settings (name, value) values (:name, :val)");
- query.bindValue(":addr", name);
- query.bindValue(":val", val);
- query.exec();
+ query.prepare("insert into settings (name, value) values (:name, :val)");
+ query.bindValue(":addr", name);
+ query.bindValue(":val", val);
+ query.exec();
- lasterr = query.lastError();
+ lasterr = query.lastError();
}
diff --git a/pica-client/settings.h b/pica-client/settings.h
index 9476ab5..21e3dba 100644
--- a/pica-client/settings.h
+++ b/pica-client/settings.h
@@ -8,17 +8,17 @@
class Settings
{
public:
- Settings(QString storage);
+ Settings(QString storage);
- QVariant loadValue(QString name, QVariant defval);
- void storeValue(QString name, QString val);
+ QVariant loadValue(QString name, QVariant defval);
+ void storeValue(QString name, QString val);
bool isEmpty();
- QString GetLastError();
+ QString GetLastError();
private:
- QSqlDatabase dbconn;
- QSqlError lasterr;
+ QSqlDatabase dbconn;
+ QSqlError lasterr;
};
#endif // SETTINGS_H
diff --git a/pica-client/skynet.cpp b/pica-client/skynet.cpp
index a016b48..8e22635 100644
--- a/pica-client/skynet.cpp
+++ b/pica-client/skynet.cpp
@@ -13,41 +13,42 @@
#include "settings.h"
SkyNet::SkyNet()
- : nodes(config_dbname), QObject(0)
+ : nodes(config_dbname), QObject(0)
{
- self_aware = false;
+ self_aware = false;
-PICA_client_callbacks cbs = {
- newmsg_cb,
- msgok_cb,
- c2c_established_cb,
- c2c_failed,
- accept_cb,
- notfound_cb,
- c2c_closed_cb,
- nodelist_cb,
- peer_cert_verify_cb,
- accept_file_cb,
- accepted_file_cb,
- denied_file_cb,
- file_progress,
- file_control,
- file_finished,
- c2n_established_cb,
- c2n_failed_cb,
- c2n_closed_cb,
- listener_error_cb
- };
-
-PICA_client_init(&cbs);
-
-this->active_nodelink = NULL;
-this->acc = NULL;
-this->listener = NULL;
-
-connect(this, SIGNAL(PeerCertificateReceived(QByteArray,QString,bool*)), this, SLOT(verify_peer_cert(QByteArray,QString,bool*)),Qt::DirectConnection);
-
-event_loop_timer_id = startTimer(0);
+ PICA_client_callbacks cbs =
+ {
+ newmsg_cb,
+ msgok_cb,
+ c2c_established_cb,
+ c2c_failed,
+ accept_cb,
+ notfound_cb,
+ c2c_closed_cb,
+ nodelist_cb,
+ peer_cert_verify_cb,
+ accept_file_cb,
+ accepted_file_cb,
+ denied_file_cb,
+ file_progress,
+ file_control,
+ file_finished,
+ c2n_established_cb,
+ c2n_failed_cb,
+ c2n_closed_cb,
+ listener_error_cb
+ };
+
+ PICA_client_init(&cbs);
+
+ this->active_nodelink = NULL;
+ this->acc = NULL;
+ this->listener = NULL;
+
+ connect(this, SIGNAL(PeerCertificateReceived(QByteArray, QString, bool*)), this, SLOT(verify_peer_cert(QByteArray, QString, bool*)), Qt::DirectConnection);
+
+ event_loop_timer_id = startTimer(0);
}
@@ -101,7 +102,7 @@ void SkyNet::nodelink_activated(PICA_c2n *c2n)
ret = PICA_new_c2c(active_nodelink, (const unsigned char*)c2c_peer_ids[i].constData(), NULL, &chan);
- qDebug()<<"restoring c2c to "<<c2c_peer_ids[i]<<" ret ="<<ret<<"\n";
+ qDebug() << "restoring c2c to " << c2c_peer_ids[i] << " ret =" << ret << "\n";
}
//start timer
@@ -143,17 +144,17 @@ void SkyNet::nodelink_failed(PICA_c2n *c2n, int error)
case PICA_ERRPROTONEW:
emit StatusMsg(QString("Node %1:%2 has newer protocol version. Please check if update for pica-client is available")
- .arg(connecting_nodes[i].second.address)
- .arg(connecting_nodes[i].second.port),
- true);
+ .arg(connecting_nodes[i].second.address)
+ .arg(connecting_nodes[i].second.port),
+ true);
break;
case PICA_ERRPROTOOLD:
emit StatusMsg(QString("Node %1:%2 has older protocol. Disconnected.")
- .arg(connecting_nodes[i].second.address)
- .arg(connecting_nodes[i].second.port),
- false);
+ .arg(connecting_nodes[i].second.address)
+ .arg(connecting_nodes[i].second.port),
+ false);
break;
}
@@ -170,7 +171,7 @@ void SkyNet::nodelink_failed(PICA_c2n *c2n, int error)
void SkyNet::node_status_changed(Nodes::NodeRecord nr, bool alive)
{
- nodes.UpdateStatus(nr, alive);
+ nodes.UpdateStatus(nr, alive);
}
void SkyNet::verify_peer_cert(QByteArray peer_id, QString cert_pem, bool *verified)
@@ -178,55 +179,58 @@ void SkyNet::verify_peer_cert(QByteArray peer_id, QString cert_pem, bool *verifi
// ViewCertDialog vcd;
// vcd.SetCert(cert_pem);
// vcd.exec();
- Contacts cnt(config_dbname, Accounts::GetCurrentAccount().id);
- QString stored_cert;
-
+ Contacts cnt(config_dbname, Accounts::GetCurrentAccount().id);
+ QString stored_cert;
- if (!cnt.Exists(peer_id) && cnt.isOK())
- {
- cnt.Add(peer_id, Contacts::temporary);
- }
- if ((stored_cert = cnt.GetContactCert(peer_id)).isEmpty())
- {
- cnt.SetContactCert(peer_id, cert_pem);
- QString name = OpenSSLTool::NameFromCertString(cert_pem);
+ if (!cnt.Exists(peer_id) && cnt.isOK())
+ {
+ cnt.Add(peer_id, Contacts::temporary);
+ }
+ if ((stored_cert = cnt.GetContactCert(peer_id)).isEmpty())
+ {
+ cnt.SetContactCert(peer_id, cert_pem);
- cnt.SetContactName(peer_id, name);
+ QString name = OpenSSLTool::NameFromCertString(cert_pem);
- emit ContactsUpdated();
- }
- else
- {//compare certificates
- QString strip_pem[4] = {
- "-----BEGIN CERTIFICATE-----",
- "-----END CERTIFICATE-----",
- "-----BEGIN X509 CERTIFICATE-----",
- "-----END X509 CERTIFICATE-----"
- };
- QString stripped_stored_cert = stored_cert;
- QString stripped_received_cert = cert_pem;
+ cnt.SetContactName(peer_id, name);
- for (int i = 0; i < 4; i++)
- {
- stripped_stored_cert.replace(strip_pem[i], "");
- stripped_received_cert.replace(strip_pem[i], "");
- }
+ emit ContactsUpdated();
+ }
+ else
+ {
+ //compare certificates
+ QString strip_pem[4] =
+ {
+ "-----BEGIN CERTIFICATE-----",
+ "-----END CERTIFICATE-----",
+ "-----BEGIN X509 CERTIFICATE-----",
+ "-----END X509 CERTIFICATE-----"
+ };
+ QString stripped_stored_cert = stored_cert;
+ QString stripped_received_cert = cert_pem;
+
+ for (int i = 0; i < 4; i++)
+ {
+ stripped_stored_cert.replace(strip_pem[i], "");
+ stripped_received_cert.replace(strip_pem[i], "");
+ }
- QByteArray stored_DER, received_DER;
+ QByteArray stored_DER, received_DER;
- stored_DER = QByteArray::fromBase64(stripped_stored_cert.toAscii().constData());
- received_DER = QByteArray::fromBase64(stripped_received_cert.toAscii().constData());
+ stored_DER = QByteArray::fromBase64(stripped_stored_cert.toAscii().constData());
+ received_DER = QByteArray::fromBase64(stripped_received_cert.toAscii().constData());
- if (stored_DER.size() != received_DER.size() ||
- memcmp(stored_DER.constData(), received_DER.constData(), stored_DER.size()) != 0)
- {//put scary message here
- *verified = false;
- emit CertificateForged(peer_id, cert_pem, stored_cert);
- }
+ if (stored_DER.size() != received_DER.size() ||
+ memcmp(stored_DER.constData(), received_DER.constData(), stored_DER.size()) != 0)
+ {
+ //put scary message here
+ *verified = false;
+ emit CertificateForged(peer_id, cert_pem, stored_cert);
+ }
- }
+ }
}
void SkyNet::timerEvent(QTimerEvent *e)
@@ -258,8 +262,8 @@ void SkyNet::timerEvent(QTimerEvent *e)
}
- if (self_aware)
- {
+ if (self_aware)
+ {
QMap<QByteArray, QList<QString> > queues = msgqueues;
queues.unite(sndfilequeues);
@@ -275,42 +279,43 @@ void SkyNet::timerEvent(QTimerEvent *e)
ret = PICA_new_c2c(active_nodelink, (const unsigned char*)c2c_peer_ids[i].constData(), NULL, &chan);
- qDebug()<<"restoring c2c to "<<c2c_peer_ids[i]<<" ret ="<<ret<<" in timer event\n";
+ qDebug() << "restoring c2c to " << c2c_peer_ids[i] << " ret =" << ret << " in timer event\n";
}
- }
-else
- {
- killTimer(e->timerId());
- Accounts::AccountRecord acc = this->CurrentAccount();
- Join(acc);
- }
+ }
+ else
+ {
+ killTimer(e->timerId());
+ Accounts::AccountRecord acc = this->CurrentAccount();
+ Join(acc);
+ }
}
bool SkyNet::open_account()
{
- int ret;
+ int ret;
- AskPassword::clear();
- do
- {
- ret = PICA_open_acc(skynet_account.cert_file.toUtf8().constData(),
- skynet_account.pkey_file.toUtf8().constData(),
- DHParam::GetDHParamFilename().toUtf8().constData(),
- AskPassword::ask_password_cb,
- &acc);
-
- if (ret == PICA_ERRINVPKEYPASSPHRASE)
- AskPassword::setInvalidPassword();
- } while (ret == PICA_ERRINVPKEYPASSPHRASE);
+ AskPassword::clear();
+ do
+ {
+ ret = PICA_open_acc(skynet_account.cert_file.toUtf8().constData(),
+ skynet_account.pkey_file.toUtf8().constData(),
+ DHParam::GetDHParamFilename().toUtf8().constData(),
+ AskPassword::ask_password_cb,
+ &acc);
+
+ if (ret == PICA_ERRINVPKEYPASSPHRASE)
+ AskPassword::setInvalidPassword();
+ }
+ while (ret == PICA_ERRINVPKEYPASSPHRASE);
- qDebug() << "PICA_open_acc() returned " << ret;
+ qDebug() << "PICA_open_acc() returned " << ret;
- if (ret != PICA_OK)
- return false;
+ if (ret != PICA_OK)
+ return false;
- return true;
+ return true;
}
void SkyNet::Join(Accounts::AccountRecord &accrec)
@@ -318,21 +323,21 @@ void SkyNet::Join(Accounts::AccountRecord &accrec)
PICA_directc2c_config directc2c_cfg = PICA_DIRECTC2C_CFG_DISABLED;
Settings st(config_dbname);
- skynet_account = accrec;
+ skynet_account = accrec;
QList<Nodes::NodeRecord> noderecords = nodes.GetNodes();
- if (!acc)
- {
- if (!open_account())
- return;
- }
+ if (!acc)
+ {
+ if (!open_account())
+ return;
+ }
- if (noderecords.count()==0)
- {
+ if (noderecords.count() == 0)
+ {
emit StatusMsg(QString(tr("No known Pica Pica nodes")), true);
- return;
- }
+ return;
+ }
directc2c_cfg = (PICA_directc2c_config)st.loadValue("direct_c2c.state", 1).toInt();
@@ -342,9 +347,9 @@ void SkyNet::Join(Accounts::AccountRecord &accrec)
int loc_port = st.loadValue("direct_c2c.local_port", 2298).toInt();
int ret = PICA_new_listener(acc,
- st.loadValue("direct_c2c.public_addr", "0.0.0.0").toString().toAscii().constData(),
- pub_port,
- loc_port, &listener);
+ st.loadValue("direct_c2c.public_addr", "0.0.0.0").toString().toAscii().constData(),
+ pub_port,
+ loc_port, &listener);
if (ret != PICA_OK)
{
emit StatusMsg(QString(tr("Failed to open port %1 for incoming direct connections")).arg(loc_port), true);
@@ -360,13 +365,13 @@ void SkyNet::Join(Accounts::AccountRecord &accrec)
connecting_nodes.clear();
}
- for (int i = 0; i < noderecords.size();i++)
+ for (int i = 0; i < noderecords.size(); i++)
{
int ret;
struct PICA_c2n *c2n = NULL;
ret = PICA_new_c2n(acc, noderecords[i].address.toUtf8().constData(), noderecords[i].port,
- directc2c_cfg, listener, &c2n);
+ directc2c_cfg, listener, &c2n);
if (ret == PICA_OK)
{
@@ -377,15 +382,15 @@ void SkyNet::Join(Accounts::AccountRecord &accrec)
node_status_changed(noderecords[i], false);
}
}
-/*
- for (int i=0;i<nodelist.count() && !self_aware;i++)
- {//TODO FIXME сделать запуск потоков порциями, а не все сразу
- threads.append(new NodeThread(nodelist[i],&self_aware, acc,&nodelink, &write_mutex));
- connect(threads.last(), SIGNAL(finished()),this,SLOT(nodethread_finished()));
- connect(threads.last(), SIGNAL(NodeStatusChanged(QString,quint16,bool)), this, SLOT(node_status_changed(QString,quint16,bool)));
- connect(threads.last(), SIGNAL(ConnectedToNode(QString,quint16,NodeThread*)), this, SLOT(nodethread_connected(QString,quint16,NodeThread*)));
- connect(threads.last(), SIGNAL(ErrorMsg(QString)), this, SIGNAL(ErrMsgFromNode(QString)));
- }*/
+ /*
+ for (int i=0;i<nodelist.count() && !self_aware;i++)
+ {//TODO FIXME сделать запуск потоков порциями, а не все сразу
+ threads.append(new NodeThread(nodelist[i],&self_aware, acc,&nodelink, &write_mutex));
+ connect(threads.last(), SIGNAL(finished()),this,SLOT(nodethread_finished()));
+ connect(threads.last(), SIGNAL(NodeStatusChanged(QString,quint16,bool)), this, SLOT(node_status_changed(QString,quint16,bool)));
+ connect(threads.last(), SIGNAL(ConnectedToNode(QString,quint16,NodeThread*)), this, SLOT(nodethread_connected(QString,quint16,NodeThread*)));
+ connect(threads.last(), SIGNAL(ErrorMsg(QString)), this, SIGNAL(ErrMsgFromNode(QString)));
+ }*/
}
@@ -397,7 +402,7 @@ void SkyNet::Exit()
active_nodelink = NULL;
}
- self_aware = false;
+ self_aware = false;
killTimer(retry_timer_id);
@@ -413,369 +418,369 @@ void SkyNet::Exit()
bool SkyNet::isSelfAware()
{
- return self_aware;
+ return self_aware;
}
void SkyNet::SendFile(QByteArray to, QString filepath)
{
-int ret = PICA_OK;
-struct PICA_c2c *iptr;
+ int ret = PICA_OK;
+ struct PICA_c2c *iptr;
-if ( (iptr = find_active_chan(to)) )
- {
- ret = PICA_send_file(iptr, filepath.toUtf8().data());
+ if ( (iptr = find_active_chan(to)) )
+ {
+ ret = PICA_send_file(iptr, filepath.toUtf8().data());
- if (ret != PICA_OK)
- {
- //show error somewhere somehow
- }
+ if (ret != PICA_OK)
+ {
+ //show error somewhere somehow
+ }
- return;
- }
+ return;
+ }
- if (sndfilequeues.contains(to))
- {
- //sending multiple files is not supported yet
- }
- else
- {
- struct PICA_c2c *chan = NULL;
+ if (sndfilequeues.contains(to))
+ {
+ //sending multiple files is not supported yet
+ }
+ else
+ {
+ struct PICA_c2c *chan = NULL;
- ret = PICA_new_c2c(active_nodelink, (const unsigned char*)to.constData(), NULL, &chan);
+ ret = PICA_new_c2c(active_nodelink, (const unsigned char*)to.constData(), NULL, &chan);
- QList<QString> l;
- l.append(filepath);
- sndfilequeues[to] = l;
- }
+ QList<QString> l;
+ l.append(filepath);
+ sndfilequeues[to] = l;
+ }
- if (ret!= PICA_OK)
- {
- //report error
- }
+ if (ret != PICA_OK)
+ {
+ //report error
+ }
}
void SkyNet::AcceptFile(QByteArray from, QString filepath)
{
-int ret = PICA_OK;
-struct PICA_c2c *iptr;
+ int ret = PICA_OK;
+ struct PICA_c2c *iptr;
-if ( (iptr = find_active_chan(from)) )
- {
- ret = PICA_accept_file(iptr, filepath.toUtf8().data(), filepath.toUtf8().size());
+ if ( (iptr = find_active_chan(from)) )
+ {
+ ret = PICA_accept_file(iptr, filepath.toUtf8().data(), filepath.toUtf8().size());
- qDebug() << "PICA_accept_file(" << filepath.toUtf8().data() << ", " << filepath.toUtf8().size() << ") returned " << ret << "\n";
- if (ret != PICA_OK)
- {
- //show error somewhere somehow
- }
- }
+ qDebug() << "PICA_accept_file(" << filepath.toUtf8().data() << ", " << filepath.toUtf8().size() << ") returned " << ret << "\n";
+ if (ret != PICA_OK)
+ {
+ //show error somewhere somehow
+ }
+ }
}
void SkyNet::DenyFile(QByteArray from)
{
-int ret = PICA_OK;
-struct PICA_c2c *iptr;
+ int ret = PICA_OK;
+ struct PICA_c2c *iptr;
-if ( (iptr = find_active_chan(from)) )
- {
- ret = PICA_deny_file(iptr);
+ if ( (iptr = find_active_chan(from)) )
+ {
+ ret = PICA_deny_file(iptr);
- qDebug() << "PICA_deny_file() returned " << ret << "\n";
- if (ret != PICA_OK)
- {
- //show error somewhere somehow
- }
- }
+ qDebug() << "PICA_deny_file() returned " << ret << "\n";
+ if (ret != PICA_OK)
+ {
+ //show error somewhere somehow
+ }
+ }
}
void SkyNet::PauseFile(QByteArray peer_id, bool pause_sending)
{
-int ret = PICA_OK;
-struct PICA_c2c *iptr;
+ int ret = PICA_OK;
+ struct PICA_c2c *iptr;
-if ( (iptr = find_active_chan(peer_id)) )
- {
- qDebug() << "calling PICA_pause_file(" << iptr << "," << pause_sending << ")\n";
- ret = PICA_pause_file(iptr, (int)pause_sending );
+ if ( (iptr = find_active_chan(peer_id)) )
+ {
+ qDebug() << "calling PICA_pause_file(" << iptr << "," << pause_sending << ")\n";
+ ret = PICA_pause_file(iptr, (int)pause_sending );
- if (ret != PICA_OK)
- {
- qDebug() << "PICA_pause_file() returned " << ret << "\n";
- }
- }
+ if (ret != PICA_OK)
+ {
+ qDebug() << "PICA_pause_file() returned " << ret << "\n";
+ }
+ }
}
void SkyNet::ResumeFile(QByteArray peer_id, bool resume_sending)
{
-int ret = PICA_OK;
-struct PICA_c2c *iptr;
+ int ret = PICA_OK;
+ struct PICA_c2c *iptr;
-if ( (iptr = find_active_chan(peer_id)) )
- {
- ret = PICA_resume_file(iptr, (int)resume_sending );
+ if ( (iptr = find_active_chan(peer_id)) )
+ {
+ ret = PICA_resume_file(iptr, (int)resume_sending );
- if (ret != PICA_OK)
- {
- //show error somewhere somehow
- }
- }
+ if (ret != PICA_OK)
+ {
+ //show error somewhere somehow
+ }
+ }
}
void SkyNet::CancelFile(QByteArray peer_id, bool cancel_sending)
{
-int ret = PICA_OK;
-struct PICA_c2c *iptr;
+ int ret = PICA_OK;
+ struct PICA_c2c *iptr;
-if ( (iptr = find_active_chan(peer_id)) )
- {
- ret = PICA_cancel_file(iptr, (int)cancel_sending );
+ if ( (iptr = find_active_chan(peer_id)) )
+ {
+ ret = PICA_cancel_file(iptr, (int)cancel_sending );
- if (ret != PICA_OK)
- {
- //show error somewhere somehow
- }
- }
+ if (ret != PICA_OK)
+ {
+ //show error somewhere somehow
+ }
+ }
}
void SkyNet::SendMessage(QByteArray to, QString msg)
{
-int ret = PICA_OK;
-struct PICA_c2c *iptr;
+ int ret = PICA_OK;
+ struct PICA_c2c *iptr;
-if ( (iptr = find_active_chan(to)) )
-{
- //write_mutex.lock();//<<
- ret = PICA_send_msg(iptr, msg.toUtf8().data(), msg.toUtf8().size());
- //write_mutex.unlock();//>>
+ if ( (iptr = find_active_chan(to)) )
+ {
+ //write_mutex.lock();//<<
+ ret = PICA_send_msg(iptr, msg.toUtf8().data(), msg.toUtf8().size());
+ //write_mutex.unlock();//>>
- if (ret != PICA_OK)
- emit UnableToDeliver(to, msg);
+ if (ret != PICA_OK)
+ emit UnableToDeliver(to, msg);
- return;
-}
+ return;
+ }
- if (msgqueues.contains(to))
- {
- msgqueues[to].append(msg);
- }
- else
- {
- struct PICA_c2c *chan = NULL;
+ if (msgqueues.contains(to))
+ {
+ msgqueues[to].append(msg);
+ }
+ else
+ {
+ struct PICA_c2c *chan = NULL;
ret = PICA_new_c2c(active_nodelink, (const unsigned char*)to.constData(), NULL, &chan);
- QList<QString> l;
- l.append(msg);
- msgqueues[to] = l;
- }
+ QList<QString> l;
+ l.append(msg);
+ msgqueues[to] = l;
+ }
- if (ret != PICA_OK)
- emit UnableToDeliver(to, msg);
+ if (ret != PICA_OK)
+ emit UnableToDeliver(to, msg);
}
void SkyNet::flush_queues(QByteArray to)
{
- struct PICA_c2c *chan;
- int ret;
+ struct PICA_c2c *chan;
+ int ret;
- if (self_aware && (msgqueues.contains(to) || sndfilequeues.contains(to)))
- {
- qDebug()<<"flushing "<<to<<" message queue\n";
+ if (self_aware && (msgqueues.contains(to) || sndfilequeues.contains(to)))
+ {
+ qDebug() << "flushing " << to << " message queue\n";
- if ((chan = find_active_chan(to)))
- {
- /////// messages
- while( !msgqueues[to].empty() )
- {
- ret = PICA_send_msg(chan, msgqueues[to].first().toUtf8().data(), msgqueues[to].first().toUtf8().size());
+ if ((chan = find_active_chan(to)))
+ {
+ /////// messages
+ while( !msgqueues[to].empty() )
+ {
+ ret = PICA_send_msg(chan, msgqueues[to].first().toUtf8().data(), msgqueues[to].first().toUtf8().size());
- if (ret != PICA_OK)
- {
- emit UnableToDeliver(to, msgqueues[to].first());
- break;
- }
+ if (ret != PICA_OK)
+ {
+ emit UnableToDeliver(to, msgqueues[to].first());
+ break;
+ }
- msgqueues[to].removeFirst();
+ msgqueues[to].removeFirst();
- }
+ }
- if (msgqueues[to].empty())
- msgqueues.remove(to);
+ if (msgqueues[to].empty())
+ msgqueues.remove(to);
- ///////// files
- while (!sndfilequeues[to].empty())
- {
- ret = PICA_send_file(chan, sndfilequeues[to].first().toUtf8().data());
+ ///////// files
+ while (!sndfilequeues[to].empty())
+ {
+ ret = PICA_send_file(chan, sndfilequeues[to].first().toUtf8().data());
- if (ret != PICA_OK)
- {
- //report error somehow
- break;
- }
+ if (ret != PICA_OK)
+ {
+ //report error somehow
+ break;
+ }
- sndfilequeues[to].removeFirst();
- }
+ sndfilequeues[to].removeFirst();
+ }
- if (sndfilequeues[to].empty())
- sndfilequeues.remove(to);
- }
- }
+ if (sndfilequeues[to].empty())
+ sndfilequeues.remove(to);
+ }
+ }
}
struct PICA_c2c * SkyNet::find_active_chan(QByteArray peer_id)
{
-if (!active_nodelink)
- return NULL;
+ if (!active_nodelink)
+ return NULL;
-struct PICA_c2c *iptr = active_nodelink->chan_list_head;
+ struct PICA_c2c *iptr = active_nodelink->chan_list_head;
-while(iptr)
- {
- if (iptr->state == PICA_C2C_STATE_ACTIVE && QByteArray((const char*)iptr->peer_id, PICA_ID_SIZE) == peer_id)
- break;
+ while(iptr)
+ {
+ if (iptr->state == PICA_C2C_STATE_ACTIVE && QByteArray((const char*)iptr->peer_id, PICA_ID_SIZE) == peer_id)
+ break;
- iptr = iptr->next;
- }
+ iptr = iptr->next;
+ }
-return iptr;
+ return iptr;
}
QList<QByteArray> SkyNet::filter_existing_chans(QList<QByteArray> peer_ids)
{
- QList<QByteArray> ret = peer_ids;
+ QList<QByteArray> ret = peer_ids;
if (!active_nodelink)
- return ret;
+ return ret;
struct PICA_c2c *iptr = active_nodelink->chan_list_head;
- while(iptr)
- {
- if (peer_ids.contains(QByteArray((const char*)iptr->peer_id, PICA_ID_SIZE)))
- ret.removeOne((const char*)iptr->peer_id);
+ while(iptr)
+ {
+ if (peer_ids.contains(QByteArray((const char*)iptr->peer_id, PICA_ID_SIZE)))
+ ret.removeOne((const char*)iptr->peer_id);
- iptr = iptr->next;
- }
+ iptr = iptr->next;
+ }
- return ret;
+ return ret;
}
void SkyNet::emit_Delivered(QByteArray to)
{
-emit Delivered(to);
+ emit Delivered(to);
}
void SkyNet::emit_MessageReceived(QByteArray from, QString msg)
{
-emit MessageReceived(from, msg);
+ emit MessageReceived(from, msg);
}
void SkyNet::emit_UnableToDeliver(QByteArray to, QString msg)
{
-emit UnableToDeliver(to, msg);
+ emit UnableToDeliver(to, msg);
}
void SkyNet::emit_PeerCertificateReceived(QByteArray peer_id, QString cert_pem, bool *verified)
{
- emit PeerCertificateReceived(peer_id, cert_pem, verified);
+ emit PeerCertificateReceived(peer_id, cert_pem, verified);
}
void SkyNet::emit_IncomingFileRequestReceived(QByteArray peer_id, quint64 file_size, QString filename)
{
- emit IncomingFileRequestReceived(peer_id, file_size, filename);
+ emit IncomingFileRequestReceived(peer_id, file_size, filename);
}
void SkyNet::emit_OutgoingFileRequestAccepted(QByteArray peer_id)
{
- emit OutgoingFileRequestAccepted(peer_id);
+ emit OutgoingFileRequestAccepted(peer_id);
}
void SkyNet::emit_OutgoingFileRequestDenied(QByteArray peer_id)
{
- emit OutgoingFileRequestDenied(peer_id);
+ emit OutgoingFileRequestDenied(peer_id);
}
void SkyNet::emit_FileProgress(QByteArray peer_id, quint64 bytes_sent, quint64 bytes_received)
{
- emit FileProgress(peer_id, bytes_sent, bytes_received);
+ emit FileProgress(peer_id, bytes_sent, bytes_received);
}
void SkyNet::emit_IncomingFilePaused(QByteArray peer_id)
{
- emit IncomingFilePaused(peer_id);
+ emit IncomingFilePaused(peer_id);
}
void SkyNet::emit_IncomingFileCancelled(QByteArray peer_id)
{
- emit IncomingFileCancelled(peer_id);
+ emit IncomingFileCancelled(peer_id);
}
void SkyNet::emit_IncomingFileIoError(QByteArray peer_id)
{
- emit IncomingFileIoError(peer_id);
+ emit IncomingFileIoError(peer_id);
}
void SkyNet::emit_IncomingFileResumed(QByteArray peer_id)
{
- emit IncomingFileResumed(peer_id);
+ emit IncomingFileResumed(peer_id);
}
void SkyNet::emit_OutgoingFilePaused(QByteArray peer_id)
{
- emit OutgoingFilePaused(peer_id);
+ emit OutgoingFilePaused(peer_id);
}
void SkyNet::emit_OutgoingFileCancelled(QByteArray peer_id)
{
- emit OutgoingFileCancelled(peer_id);
+ emit OutgoingFileCancelled(peer_id);
}
void SkyNet::emit_OutgoingFileIoError(QByteArray peer_id)
{
- emit OutgoingFileIoError(peer_id);
+ emit OutgoingFileIoError(peer_id);
}
void SkyNet::emit_OutgoingFileResumed(QByteArray peer_id)
{
- emit OutgoingFileResumed(peer_id);
+ emit OutgoingFileResumed(peer_id);
}
void SkyNet::emit_OutgoingFileFinished(QByteArray peer_id)
{
- emit OutgoingFileFinished(peer_id);
+ emit OutgoingFileFinished(peer_id);
}
void SkyNet::emit_IncomingFileFinished(QByteArray peer_id)
{
- emit IncomingFileFinished(peer_id);
+ emit IncomingFileFinished(peer_id);
}
void SkyNet::emit_c2cClosed(QByteArray peer_id)
{
- emit c2cClosed(peer_id);
+ emit c2cClosed(peer_id);
}
@@ -783,157 +788,157 @@ void SkyNet::emit_c2cClosed(QByteArray peer_id)
void SkyNet::newmsg_cb(const unsigned char *peer_id, const char *msgbuf, unsigned int nb, int type)
{
-QString msg = QString::fromUtf8(msgbuf, nb);
+ QString msg = QString::fromUtf8(msgbuf, nb);
-skynet->emit_MessageReceived(QByteArray((const char*)peer_id, PICA_ID_SIZE), msg);
+ skynet->emit_MessageReceived(QByteArray((const char*)peer_id, PICA_ID_SIZE), msg);
}
void SkyNet::msgok_cb(const unsigned char *peer_id)
{
-skynet->emit_Delivered(QByteArray((const char*)peer_id, PICA_ID_SIZE));
+ skynet->emit_Delivered(QByteArray((const char*)peer_id, PICA_ID_SIZE));
}
void SkyNet::c2c_established_cb(const unsigned char *peer_id)
{
-skynet->flush_queues(QByteArray((const char*)peer_id, PICA_ID_SIZE));
+ skynet->flush_queues(QByteArray((const char*)peer_id, PICA_ID_SIZE));
}
void SkyNet::c2c_failed(const unsigned char *peer_id)
{
- qDebug()<<"c2c failed ("<<QByteArray((const char*)peer_id, PICA_ID_SIZE).toBase64()<<")\n";
+ qDebug() << "c2c failed (" << QByteArray((const char*)peer_id, PICA_ID_SIZE).toBase64() << ")\n";
}
int SkyNet::accept_cb(const unsigned char *caller_id)
{
-return 1; //implement black list
+ return 1; //implement black list
}
void SkyNet::notfound_cb(const unsigned char *callee_id)
{
- qDebug()<<"not found ("<<QByteArray((const char*)callee_id, PICA_ID_SIZE).toBase64()<<")\n";
+ qDebug() << "not found (" << QByteArray((const char*)callee_id, PICA_ID_SIZE).toBase64() << ")\n";
- /*
- if (skynet->msgqueues.contains(callee_id))
- {
- while ( ! skynet->msgqueues[callee_id].empty())
- {
- skynet->emit_UnableToDeliver(callee_id, skynet->msgqueues[callee_id].last());
- skynet->msgqueues[callee_id].removeLast();
- }
- // msgqueues.remove(callee_id) was forgotten
- }
- */
+ /*
+ if (skynet->msgqueues.contains(callee_id))
+ {
+ while ( ! skynet->msgqueues[callee_id].empty())
+ {
+ skynet->emit_UnableToDeliver(callee_id, skynet->msgqueues[callee_id].last());
+ skynet->msgqueues[callee_id].removeLast();
+ }
+ // msgqueues.remove(callee_id) was forgotten
+ }
+ */
}
void SkyNet::c2c_closed_cb(const unsigned char *peer_id, int reason)
{
- qDebug()<<"c2c closed ("<<QByteArray((const char*)peer_id, PICA_ID_SIZE).toBase64()
- <<", error_code =" << reason << ")\n";
+ qDebug() << "c2c closed (" << QByteArray((const char*)peer_id, PICA_ID_SIZE).toBase64()
+ << ", error_code =" << reason << ")\n";
- skynet->emit_c2cClosed(QByteArray((const char*)peer_id, PICA_ID_SIZE));
+ skynet->emit_c2cClosed(QByteArray((const char*)peer_id, PICA_ID_SIZE));
}
void SkyNet::nodelist_cb(int type, void *addr_bin, const char *addr_str, unsigned int port)
{
- Nodes::NodeRecord nr = {addr_str, port};
- skynet->nodes.Add(nr);
+ Nodes::NodeRecord nr = {addr_str, port};
+ skynet->nodes.Add(nr);
}
int SkyNet::peer_cert_verify_cb(const unsigned char *peer_id, const char *cert_pem, unsigned int nb)
{
- bool verified = true;
+ bool verified = true;
- skynet->emit_PeerCertificateReceived(QByteArray((const char*)peer_id, PICA_ID_SIZE), QString::fromAscii(cert_pem, nb), &verified);
+ skynet->emit_PeerCertificateReceived(QByteArray((const char*)peer_id, PICA_ID_SIZE), QString::fromAscii(cert_pem, nb), &verified);
- if (!verified)
- return 0;
+ if (!verified)
+ return 0;
- return 1;
+ return 1;
}
int SkyNet::accept_file_cb(const unsigned char *peer_id, uint64_t file_size, const char *filename, unsigned int filename_size)
{
- skynet->emit_IncomingFileRequestReceived(QByteArray((const char*)peer_id, PICA_ID_SIZE),
- file_size, QString::fromUtf8(filename, filename_size));
+ skynet->emit_IncomingFileRequestReceived(QByteArray((const char*)peer_id, PICA_ID_SIZE),
+ file_size, QString::fromUtf8(filename, filename_size));
- return 2;//??? accept later code
+ return 2;//??? accept later code
}
void SkyNet::accepted_file_cb(const unsigned char *peer_id)
{
- qDebug()<<"FILE: file was accepted by remote side\n";
+ qDebug() << "FILE: file was accepted by remote side\n";
- skynet->emit_OutgoingFileRequestAccepted(QByteArray((const char *)peer_id, PICA_ID_SIZE));
+ skynet->emit_OutgoingFileRequestAccepted(QByteArray((const char *)peer_id, PICA_ID_SIZE));
}
void SkyNet::denied_file_cb(const unsigned char *peer_id)
{
- skynet->emit_OutgoingFileRequestDenied(QByteArray((const char *)peer_id, PICA_ID_SIZE));
+ skynet->emit_OutgoingFileRequestDenied(QByteArray((const char *)peer_id, PICA_ID_SIZE));
}
void SkyNet::file_progress(const unsigned char *peer_id, uint64_t sent, uint64_t received)
{
- qDebug()<<"FILE: file progress" << sent << " sent " << received << "received\n";
- skynet->emit_FileProgress(QByteArray((const char *)peer_id, PICA_ID_SIZE), sent, received);
+ qDebug() << "FILE: file progress" << sent << " sent " << received << "received\n";
+ skynet->emit_FileProgress(QByteArray((const char *)peer_id, PICA_ID_SIZE), sent, received);
}
void SkyNet::file_control(const unsigned char *peer_id, unsigned int sender_cmd, unsigned int receiver_cmd)
{
- qDebug() << "file_control callback: sender_cmd=" << sender_cmd << ", receiver_cmd=" << receiver_cmd << "\n";
-
-
- if (sender_cmd != PICA_PROTO_FILECONTROL_VOID && receiver_cmd == PICA_PROTO_FILECONTROL_VOID)
- {
- switch(sender_cmd)
- {
- case PICA_PROTO_FILECONTROL_PAUSE:
- skynet->emit_IncomingFilePaused(QByteArray((const char *)peer_id, PICA_ID_SIZE));
- break;
-
- case PICA_PROTO_FILECONTROL_RESUME:
- skynet->emit_IncomingFileResumed(QByteArray((const char *)peer_id, PICA_ID_SIZE));
- break;
-
- case PICA_PROTO_FILECONTROL_CANCEL:
- skynet->emit_IncomingFileCancelled(QByteArray((const char *)peer_id, PICA_ID_SIZE));
- break;
-
- case PICA_PROTO_FILECONTROL_IOERROR:
- skynet->emit_IncomingFileIoError(QByteArray((const char *)peer_id, PICA_ID_SIZE));
- break;
- }
- }
- else if (sender_cmd == PICA_PROTO_FILECONTROL_VOID && receiver_cmd != PICA_PROTO_FILECONTROL_VOID)
- {
- switch(receiver_cmd)
- {
- case PICA_PROTO_FILECONTROL_PAUSE:
- skynet->emit_OutgoingFilePaused(QByteArray((const char *)peer_id, PICA_ID_SIZE));
- break;
-
- case PICA_PROTO_FILECONTROL_RESUME:
- skynet->emit_OutgoingFileResumed(QByteArray((const char *)peer_id, PICA_ID_SIZE));
- break;
-
- case PICA_PROTO_FILECONTROL_CANCEL:
- skynet->emit_OutgoingFileCancelled(QByteArray((const char *)peer_id, PICA_ID_SIZE));
- break;
-
- case PICA_PROTO_FILECONTROL_IOERROR:
- skynet->emit_OutgoingFileIoError(QByteArray((const char *)peer_id, PICA_ID_SIZE));
- break;
- }
- }
+ qDebug() << "file_control callback: sender_cmd=" << sender_cmd << ", receiver_cmd=" << receiver_cmd << "\n";
+
+
+ if (sender_cmd != PICA_PROTO_FILECONTROL_VOID && receiver_cmd == PICA_PROTO_FILECONTROL_VOID)
+ {
+ switch(sender_cmd)
+ {
+ case PICA_PROTO_FILECONTROL_PAUSE:
+ skynet->emit_IncomingFilePaused(QByteArray((const char *)peer_id, PICA_ID_SIZE));
+ break;
+
+ case PICA_PROTO_FILECONTROL_RESUME:
+ skynet->emit_IncomingFileResumed(QByteArray((const char *)peer_id, PICA_ID_SIZE));
+ break;
+
+ case PICA_PROTO_FILECONTROL_CANCEL:
+ skynet->emit_IncomingFileCancelled(QByteArray((const char *)peer_id, PICA_ID_SIZE));
+ break;
+
+ case PICA_PROTO_FILECONTROL_IOERROR:
+ skynet->emit_IncomingFileIoError(QByteArray((const char *)peer_id, PICA_ID_SIZE));
+ break;
+ }
+ }
+ else if (sender_cmd == PICA_PROTO_FILECONTROL_VOID && receiver_cmd != PICA_PROTO_FILECONTROL_VOID)
+ {
+ switch(receiver_cmd)
+ {
+ case PICA_PROTO_FILECONTROL_PAUSE:
+ skynet->emit_OutgoingFilePaused(QByteArray((const char *)peer_id, PICA_ID_SIZE));
+ break;
+
+ case PICA_PROTO_FILECONTROL_RESUME:
+ skynet->emit_OutgoingFileResumed(QByteArray((const char *)peer_id, PICA_ID_SIZE));
+ break;
+
+ case PICA_PROTO_FILECONTROL_CANCEL:
+ skynet->emit_OutgoingFileCancelled(QByteArray((const char *)peer_id, PICA_ID_SIZE));
+ break;
+
+ case PICA_PROTO_FILECONTROL_IOERROR:
+ skynet->emit_OutgoingFileIoError(QByteArray((const char *)peer_id, PICA_ID_SIZE));
+ break;
+ }
+ }
}
void SkyNet::file_finished(const unsigned char *peer_id, int sending)
{
- qDebug()<< "file_finished callback\n";
+ qDebug() << "file_finished callback\n";
- if (sending)
- skynet->emit_OutgoingFileFinished(QByteArray((const char *)peer_id, PICA_ID_SIZE));
- else
- skynet->emit_IncomingFileFinished(QByteArray((const char *)peer_id, PICA_ID_SIZE));
+ if (sending)
+ skynet->emit_OutgoingFileFinished(QByteArray((const char *)peer_id, PICA_ID_SIZE));
+ else
+ skynet->emit_IncomingFileFinished(QByteArray((const char *)peer_id, PICA_ID_SIZE));
}
void SkyNet::c2n_established_cb(struct PICA_c2n *c2n)
diff --git a/pica-client/skynet.h b/pica-client/skynet.h
index bea1a21..15c4359 100644
--- a/pica-client/skynet.h
+++ b/pica-client/skynet.h
@@ -13,125 +13,128 @@
class SkyNet : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- SkyNet();
- void Join(Accounts::AccountRecord &accrec);
- bool isSelfAware();
- void Exit();
-
- void SendMessage(QByteArray to, QString msg);
- void SendFile(QByteArray to, QString filepath);
- void AcceptFile(QByteArray from, QString filepath);
- void DenyFile(QByteArray from);
- void PauseFile(QByteArray peer_id, bool pause_sending);
- void ResumeFile(QByteArray peer_id, bool resume_sending);
- void CancelFile(QByteArray peer_id, bool cancel_sending);
-
- Accounts::AccountRecord CurrentAccount() {return skynet_account;};
+ SkyNet();
+ void Join(Accounts::AccountRecord &accrec);
+ bool isSelfAware();
+ void Exit();
+
+ void SendMessage(QByteArray to, QString msg);
+ void SendFile(QByteArray to, QString filepath);
+ void AcceptFile(QByteArray from, QString filepath);
+ void DenyFile(QByteArray from);
+ void PauseFile(QByteArray peer_id, bool pause_sending);
+ void ResumeFile(QByteArray peer_id, bool resume_sending);
+ void CancelFile(QByteArray peer_id, bool cancel_sending);
+
+ Accounts::AccountRecord CurrentAccount()
+ {
+ return skynet_account;
+ };
signals:
- void MessageReceived(QByteArray from, QString msg);
- void UnableToDeliver(QByteArray to, QString msg);
- void Delivered(QByteArray to);
- void BecameSelfAware();
- void LostSelfAwareness();
- void PeerCertificateReceived(QByteArray peer_id, QString cert_pem, bool *verified);
- void CertificateForged(QByteArray peer_id, QString received_cert, QString stored_cert);
+ void MessageReceived(QByteArray from, QString msg);
+ void UnableToDeliver(QByteArray to, QString msg);
+ void Delivered(QByteArray to);
+ void BecameSelfAware();
+ void LostSelfAwareness();
+ void PeerCertificateReceived(QByteArray peer_id, QString cert_pem, bool *verified);
+ void CertificateForged(QByteArray peer_id, QString received_cert, QString stored_cert);
void StatusMsg(QString msg, bool is_critical);
- void ContactsUpdated();
- void IncomingFileRequestReceived(QByteArray peer_id, quint64 file_size, QString filename);
- void OutgoingFileRequestAccepted(QByteArray peer_id);
- void OutgoingFileRequestDenied(QByteArray peer_id);
- void FileProgress(QByteArray peer_id, quint64 bytes_sent, quint64 bytes_received);
- void IncomingFilePaused(QByteArray peer_id);
- void IncomingFileCancelled(QByteArray peer_id);
- void IncomingFileIoError(QByteArray peer_id);
- void IncomingFileResumed(QByteArray peer_id);
- void OutgoingFilePaused(QByteArray peer_id);
- void OutgoingFileCancelled(QByteArray peer_id);
- void OutgoingFileIoError(QByteArray peer_id);
- void OutgoingFileResumed(QByteArray peer_id);
- void OutgoingFileFinished(QByteArray peer_id);
- void IncomingFileFinished(QByteArray peer_id);
-
- void c2cClosed(QByteArray peer_id);
+ void ContactsUpdated();
+ void IncomingFileRequestReceived(QByteArray peer_id, quint64 file_size, QString filename);
+ void OutgoingFileRequestAccepted(QByteArray peer_id);
+ void OutgoingFileRequestDenied(QByteArray peer_id);
+ void FileProgress(QByteArray peer_id, quint64 bytes_sent, quint64 bytes_received);
+ void IncomingFilePaused(QByteArray peer_id);
+ void IncomingFileCancelled(QByteArray peer_id);
+ void IncomingFileIoError(QByteArray peer_id);
+ void IncomingFileResumed(QByteArray peer_id);
+ void OutgoingFilePaused(QByteArray peer_id);
+ void OutgoingFileCancelled(QByteArray peer_id);
+ void OutgoingFileIoError(QByteArray peer_id);
+ void OutgoingFileResumed(QByteArray peer_id);
+ void OutgoingFileFinished(QByteArray peer_id);
+ void IncomingFileFinished(QByteArray peer_id);
+
+ void c2cClosed(QByteArray peer_id);
private:
- Nodes nodes;
+ Nodes nodes;
QList<QPair<struct PICA_c2n *, Nodes::NodeRecord> > connecting_nodes;
- bool self_aware;
- QString status;
+ bool self_aware;
+ QString status;
struct PICA_c2n *active_nodelink;
- struct PICA_acc *acc;
+ struct PICA_acc *acc;
struct PICA_listener *listener;
- Accounts::AccountRecord skynet_account;
+ Accounts::AccountRecord skynet_account;
- QMap<QByteArray, QList<QString> > msgqueues;
- QMap<QByteArray, QList<QString> > sndfilequeues;
+ QMap<QByteArray, QList<QString> > msgqueues;
+ QMap<QByteArray, QList<QString> > sndfilequeues;
int retry_timer_id;
int event_loop_timer_id;
- void timerEvent(QTimerEvent * e);
+ void timerEvent(QTimerEvent * e);
- void flush_queues(QByteArray to);
- struct PICA_c2c *find_active_chan(QByteArray peer_id);
- QList<QByteArray> filter_existing_chans(QList<QByteArray> peer_ids);
- bool open_account();
+ void flush_queues(QByteArray to);
+ struct PICA_c2c *find_active_chan(QByteArray peer_id);
+ QList<QByteArray> filter_existing_chans(QList<QByteArray> peer_ids);
+ bool open_account();
- void emit_MessageReceived(QByteArray from, QString msg);
- void emit_UnableToDeliver(QByteArray to, QString msg);
- void emit_Delivered(QByteArray to);
- void emit_PeerCertificateReceived(QByteArray peer_id, QString cert_pem, bool *verified);
- void emit_IncomingFileRequestReceived(QByteArray peer_id, quint64 file_size, QString filename);
- void emit_OutgoingFileRequestAccepted(QByteArray peer_id);
- void emit_OutgoingFileRequestDenied(QByteArray peer_id);
- void emit_FileProgress(QByteArray peer_id, quint64 bytes_sent, quint64 bytes_received);
+ void emit_MessageReceived(QByteArray from, QString msg);
+ void emit_UnableToDeliver(QByteArray to, QString msg);
+ void emit_Delivered(QByteArray to);
+ void emit_PeerCertificateReceived(QByteArray peer_id, QString cert_pem, bool *verified);
+ void emit_IncomingFileRequestReceived(QByteArray peer_id, quint64 file_size, QString filename);
+ void emit_OutgoingFileRequestAccepted(QByteArray peer_id);
+ void emit_OutgoingFileRequestDenied(QByteArray peer_id);
+ void emit_FileProgress(QByteArray peer_id, quint64 bytes_sent, quint64 bytes_received);
- void emit_IncomingFilePaused(QByteArray peer_id);
- void emit_IncomingFileCancelled(QByteArray peer_id);
- void emit_IncomingFileIoError(QByteArray peer_id);
- void emit_IncomingFileResumed(QByteArray peer_id);
- void emit_OutgoingFilePaused(QByteArray peer_id);
- void emit_OutgoingFileCancelled(QByteArray peer_id);
- void emit_OutgoingFileIoError(QByteArray peer_id);
- void emit_OutgoingFileResumed(QByteArray peer_id);
+ void emit_IncomingFilePaused(QByteArray peer_id);
+ void emit_IncomingFileCancelled(QByteArray peer_id);
+ void emit_IncomingFileIoError(QByteArray peer_id);
+ void emit_IncomingFileResumed(QByteArray peer_id);
+ void emit_OutgoingFilePaused(QByteArray peer_id);
+ void emit_OutgoingFileCancelled(QByteArray peer_id);
+ void emit_OutgoingFileIoError(QByteArray peer_id);
+ void emit_OutgoingFileResumed(QByteArray peer_id);
- void emit_OutgoingFileFinished(QByteArray peer_id);
- void emit_IncomingFileFinished(QByteArray peer_id);
+ void emit_OutgoingFileFinished(QByteArray peer_id);
+ void emit_IncomingFileFinished(QByteArray peer_id);
- void emit_c2cClosed(QByteArray peer_id);
+ void emit_c2cClosed(QByteArray peer_id);
- //получение сообщения.
- static void newmsg_cb(const unsigned char *peer_id,const char* msgbuf,unsigned int nb,int type);
- //получение подтверждения о доставке сообщения
- static void msgok_cb(const unsigned char *peer_id);
- //создание канала с собеседником
- static void c2c_established_cb(const unsigned char *peer_id);
- //создать канал не удалось
- static void c2c_failed(const unsigned char *peer_id);
- //входящий запрос на создание канала от пользователя с номером caller_id
- static int accept_cb(const unsigned char *caller_id);
- //запрошенный пользователь не найден, в оффлайне или отказался от общения
- static void notfound_cb(const unsigned char *callee_id);
+ //получение сообщения.
+ static void newmsg_cb(const unsigned char *peer_id, const char* msgbuf, unsigned int nb, int type);
+ //получение подтверждения о доставке сообщения
+ static void msgok_cb(const unsigned char *peer_id);
+ //создание канала с собеседником
+ static void c2c_established_cb(const unsigned char *peer_id);
+ //создать канал не удалось
+ static void c2c_failed(const unsigned char *peer_id);
+ //входящий запрос на создание канала от пользователя с номером caller_id
+ static int accept_cb(const unsigned char *caller_id);
+ //запрошенный пользователь не найден, в оффлайне или отказался от общения
+ static void notfound_cb(const unsigned char *callee_id);
- static void c2c_closed_cb(const unsigned char *peer_id, int reason);
+ static void c2c_closed_cb(const unsigned char *peer_id, int reason);
- static void nodelist_cb(int type, void *addr_bin, const char *addr_str, unsigned int port);
+ static void nodelist_cb(int type, void *addr_bin, const char *addr_str, unsigned int port);
- static int peer_cert_verify_cb(const unsigned char *peer_id, const char *cert_pem, unsigned int nb);
+ static int peer_cert_verify_cb(const unsigned char *peer_id, const char *cert_pem, unsigned int nb);
- static int accept_file_cb(const unsigned char *peer_id, uint64_t file_size, const char *filename, unsigned int filename_size);
+ static int accept_file_cb(const unsigned char *peer_id, uint64_t file_size, const char *filename, unsigned int filename_size);
- static void accepted_file_cb(const unsigned char *peer_id);
+ static void accepted_file_cb(const unsigned char *peer_id);
- static void denied_file_cb(const unsigned char *peer_id);
+ static void denied_file_cb(const unsigned char *peer_id);
- static void file_progress(const unsigned char *peer_id, uint64_t sent, uint64_t received);
+ static void file_progress(const unsigned char *peer_id, uint64_t sent, uint64_t received);
- static void file_control(const unsigned char *peer_id, unsigned int sender_cmd, unsigned int receiver_cmd);
+ static void file_control(const unsigned char *peer_id, unsigned int sender_cmd, unsigned int receiver_cmd);
- static void file_finished(const unsigned char *peer_id, int sending);
+ static void file_finished(const unsigned char *peer_id, int sending);
static void c2n_established_cb(struct PICA_c2n *c2n);
@@ -146,8 +149,8 @@ private slots:
void nodelink_closed(PICA_c2n *c2n, int error);
void nodelink_failed(PICA_c2n *c2n, int error);
- void node_status_changed(Nodes::NodeRecord nr,bool alive);
- void verify_peer_cert(QByteArray peer_id, QString cert_pem, bool *verified);
+ void node_status_changed(Nodes::NodeRecord nr, bool alive);
+ void verify_peer_cert(QByteArray peer_id, QString cert_pem, bool *verified);
};
diff --git a/pica-client/sound.cpp b/pica-client/sound.cpp
index 3762c0e..0db4521 100644
--- a/pica-client/sound.cpp
+++ b/pica-client/sound.cpp
@@ -21,19 +21,19 @@ Sound::Sound()
void Sound::mute(bool yes)
{
- is_muted = yes;
+ is_muted = yes;
}
void Sound::play(const QString sndfile)
{
- if (is_muted)
- return;
+ if (is_muted)
+ return;
#if defined(__gnu_linux__)
- QProcess::execute("aplay -q " + sndfile);
+ QProcess::execute("aplay -q " + sndfile);
#endif
#if defined(WIN32)
- sndPlaySound(sndfile.toAscii().constData(), SND_ASYNC | SND_NODEFAULT);
+ sndPlaySound(sndfile.toAscii().constData(), SND_ASYNC | SND_NODEFAULT);
#endif
#if defined(__APPLE__)
QProcess::execute("/usr/bin/afplay " + sndfile);
diff --git a/pica-client/sound.h b/pica-client/sound.h
index 3b1357a..eee7059 100644
--- a/pica-client/sound.h
+++ b/pica-client/sound.h
@@ -5,13 +5,13 @@
class Sound
{
public:
- Sound();
+ Sound();
- static void play(const QString sndfile);
- static void mute(bool yes);
+ static void play(const QString sndfile);
+ static void mute(bool yes);
private:
- static bool is_muted;
+ static bool is_muted;
};
#endif // SOUND_H