summaryrefslogtreecommitdiffstats
path: root/pica-client/nodethread.cpp
blob: bf93e83bf40744e6773f376f4d5e51b1c09f8a80 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#include "nodethread.h"
#include "mainwindow.h"
#include "../PICA_proto.h"
#include "globals.h"
#include "dhparam.h"

QMutex NodeThread::finished_mutex;

NodeThread::NodeThread(Nodes::NodeRecord &addr, bool *completed, PICA_acc *acc, PICA_c2n **pica_conn, QMutex *wm) :
	QThread(0)
{
	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();
}

void NodeThread::CloseThread()
{
	exit = 1;
}