summaryrefslogtreecommitdiffstats
path: root/NetworkDiscovery/networkdiscovery.cpp
blob: 0b21738bd6fea163eb302d7a0b17eb501c8af6dd (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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
#include "networkdiscovery.h"

#include "../common/fbgui.h"

NetworkDiscovery::NetworkDiscovery(QObject *parent) {
	_tag = "[nd:NetworkDiscovery]";
	_server = new QLocalServer(this);
}



NetworkDiscovery::~NetworkDiscovery() {

}



void NetworkDiscovery::initAndRun(QString serverIp, bool userChoice, bool autoUp, QString pathToLogFile, QString serverPath, QString pathToExe,
		QStringList* args) {

	_serverIp = serverIp;
	_userChoice = userChoice;
	_autoUp = autoUp;
	_pathToLogFile = pathToLogFile;

	_pathToDhcpcdExe = pathToExe;
	_blocked = false;
	_numberOfProcesses = 0;
	_ifUpCountdown = 10;

	if (serverPath != DEFAULT_QTSOCKETADDRESS) {
		_dhcpcdArguments.append("-q");
		_dhcpcdArguments.append(serverPath);
	}
	/* delete the file at serverPath. this is necessary since in case the application crashes, the file still
	*  exists which leads to an error.
	*/

	if(QFile::exists(serverPath)) {
		QFile::remove(serverPath);
	}

	if (!_server->listen(serverPath)) {
		// emit signal to the gui that a critial error occoured
		qDebug() << _tag << "Unable to start server: "
				<< _server->errorString();
		emit
		abortBoot("Unable to start server: " + _server->errorString());
		return;
	}

	// check if the path to the customdhcpcd file is correct
		QFileInfo fInfo(_pathToDhcpcdExe);
		if (!fInfo.exists()) {
			qDebug() << _tag
					<< "could not find customdhcpcd exe. Please check the path to this file.";
			emit abortBoot(
					"could not find customdhcpcd exe. Please check the path to this file.");
			return;
		}

	connect(_server, SIGNAL(newConnection()), this, SLOT(handleNewConnection()));
	connect(this, SIGNAL(readyForRun()), this, SLOT(slotReadyForRun()));

	if (args != NULL && !args->isEmpty()) {
		qDebug() << _tag << "added additional args";
		_dhcpcdArguments.append(*args);
	}

	// start the main work:
	if (_autoUp) {
		getListOfNetworkInterfacesWithAutoUp();
		_timer = new QTimer(this);
		connect(_timer, SIGNAL(timeout()), this, SLOT(checkForIsRunning()));
		_timer->start(1000);

	} else {
		getListOfNetworkInterfaces();
		emit readyForRun();
	}
}



void NetworkDiscovery::slotReadyForRun() {
	if (_ifUpList.size() > 0) {
		foreach(QString i, _ifUpList) {
			emit addInterface(i);
		}
		_numberOfProcesses = _ifUpList.size();
		runDHCPCD( _ifUpList);
	} else {
		qDebug() << _tag << "list is empty. Have not found usable interface.";
		emit
		abortBoot("Have not found usable interface");
		return;
	}
}



void NetworkDiscovery::checkForIsRunning() {
	bool isRunning = false;
	QList<QString> copyOfIfDownList(_ifDownList);
	foreach(QString i, _ifDownList) {
		QNetworkInterface networkInterface = QNetworkInterface::interfaceFromName(i);
		isRunning = (networkInterface.flags() & QNetworkInterface::IsRunning);
		if (isRunning) {
			_ifUpList.append(i);
			_ifDownList.removeAt(_ifDownList.indexOf(i));
		}
	}
	_ifUpCountdown--;
	if ((_ifUpCountdown <= 0 ) || _ifDownList.isEmpty()) {
		// shut down timer
		_timer->stop();
		emit readyForRun();
	}
}



int NetworkDiscovery::replaceDefaultRoute(QString &ifName, QString &gateway, int af, int mss) {
	return _networkManager.replaceDefaultRoute(ifName, gateway, mss, AF_INET);
}



int NetworkDiscovery::ip4_replaceDefaultRoute(QString ifName, QString gateway, int mss) {
	return _networkManager.replaceDefaultRoute(ifName, gateway, mss, AF_INET);
}



int NetworkDiscovery::ip4_setManualConfiguration(QVariantMap result) {
	QList<QString> dns;
	dns.append(result["dns"].toString());
	_networkManager.ip4_setManualConfiguration(result["ifname"].toString(),
			                                  result["ipaddr"].toString(),
			                                  result["netmask"].toString(),
			                                  result["broadcast"].toString(),
			                                  result["gateway"].toString(),
			                                  0,
			                                  AF_INET,
			                                  "/etc/",
			                                  dns);

	qDebug() << _tag << "set man conf. and check connectivity";

	if (!checkConnectivityViaTcp(_serverIp)) {
		qDebug() << _tag << "no connectivity. reset conf.";
		interfaceconfiguration * ifc = _ifcMap.value(result["ifname"].toString(), NULL);
		if(ifc != NULL) {
			dns.clear();
			dns = ifc->getDnsservers().trimmed().split(" ");
			_networkManager.ip4_setManualConfiguration(result["ifname"].toString(),
				                                  ifc->getIpAddress(),
				                                  ifc->getNetmask(),
				                                  ifc->getBroadcast(),
				                                  ifc->getGateway(),
				                                  0,
				                                  AF_INET,
				                                  "/etc/",
				                                  dns);
		}

		return 0;
	}
	emit continueBoot(result["ifname"].toString(), 0);
	return 0;
}



QString NetworkDiscovery::getGatewayForInterface(QString ifName) {
	interfaceconfiguration * ifConf = _ifcMap.value(ifName);
	return ifConf->getGateway();
}



QString NetworkDiscovery::readLogFile() {
	// path to log file is in _pathToLogFile. initialized in initAndRun().
	QString retval("the log file");
	QFile logFile(_pathToLogFile);
	if (logFile.exists()) {
		if (logFile.open(QIODevice::ReadOnly | QIODevice::Text))
			return retval;
	}
	while (!logFile.atEnd()) {
		retval.append(logFile.readLine());
	}
	return retval;
}



/**
 * ================================================================================
 ********************************* Private Methods ********************************
 * ================================================================================
 **/

void NetworkDiscovery::getListOfNetworkInterfacesWithAutoUp() {
	QList<QNetworkInterface> nIList = QNetworkInterface::allInterfaces();

	if (nIList.size() > 0) {
		foreach(QNetworkInterface nI, nIList)
			{
				if (((!(nI.flags() & QNetworkInterface::CanBroadcast)
						|| nI.flags() & QNetworkInterface::IsLoopBack)
						|| nI.flags() & QNetworkInterface::IsPointToPoint)
						|| checkBlackList(nI.humanReadableName())) {
					continue;
				}
				if ((nI.flags() & QNetworkInterface::IsRunning)) {
					_ifUpList.append(nI.humanReadableName());
				}
				else if (!(nI.flags() & QNetworkInterface::IsUp)) {
					_networkManager.bringInterfaceUP(nI.humanReadableName());
					qDebug() << _tag << " bring up ..";
					_ifDownList.append(nI.humanReadableName());
				}
			}
	} else {
		qDebug() << _tag << "no interfaces found!";
	}
}



void NetworkDiscovery::getListOfNetworkInterfaces() {
	QList<QNetworkInterface> nIList = QNetworkInterface::allInterfaces();

	if (nIList.size() > 0) {
		foreach(QNetworkInterface nI, nIList)
			{
				if (((!(nI.flags() & QNetworkInterface::CanBroadcast)
						|| nI.flags() & QNetworkInterface::IsLoopBack)
						|| nI.flags() & QNetworkInterface::IsPointToPoint)
						|| !(nI.flags() & QNetworkInterface::IsUp)
						|| !(nI.flags() & QNetworkInterface::IsRunning)
						|| checkBlackList(nI.humanReadableName())) {
					continue;
				}
				_ifUpList.append(nI.humanReadableName());
			}
	} else {
		qDebug() << _tag << "no interfaces found!";
	}
}



bool NetworkDiscovery::checkCarrierState(QString interface) {

	qDebug() << _tag << "check carrier state for interface " << interface;
	QByteArray ba = interface.toAscii();
	const char * iface = ba.data();

	struct sysfs_class_device *class_device = sysfs_open_class_device("net",
			iface);
	struct dlist *attrlist = sysfs_get_classdev_attributes(class_device);
	if (attrlist != NULL) {
		struct sysfs_attribute *attr = NULL;
		dlist_for_each_data(attrlist, attr, struct sysfs_attribute) {
			if (strcmp("carrier", attr->name) == 0) {
				QString value(attr->value);
				bool ok = false;
				bool * pok = &ok;
				int v = value.toInt(pok);
				if (*pok) {
					if (v == 1) {
						qDebug()
								<< "carrier is 1. Cable is plugged. return true";
						return true;
					} else {
						qDebug()
								<< "carrier is 0. Cable is unplugged. return false";
						return false;
					}
				} else {
					qDebug() << _tag << "conversion error";
				}
			}
		}
	} else {
		qDebug() << _tag << "attrlist is Null";
	}
	sysfs_close_class_device(class_device);

	return true;
}



void NetworkDiscovery::runDHCPCD(QList<QString> &interfaces) {
	foreach(QString nI, interfaces)
		{
			runDHCPCD(nI);
		}
}



void NetworkDiscovery::runDHCPCD(QString interface) {
	emit updateStatusLabel(interface, "start DHCP");
	_dhcpcdArguments.append(interface);
	QProcess * p = new QProcess(this);

	qDebug() << _tag << _dhcpcdArguments;

	_clientProcessToIfNameMap.insert(p, interface);
	p->start(_pathToDhcpcdExe, _dhcpcdArguments);
	connect(p, SIGNAL(started()), this, SLOT(handleProcessStarted()));
	connect(p, SIGNAL(finished(int, QProcess::ExitStatus)), this,
			SLOT(handleProcessFinished(int, QProcess::ExitStatus)));
	_dhcpcdArguments.removeLast();
}



bool NetworkDiscovery::checkConnectivity(QString ifName) {
	int mss = 0;

	// get gateway address
	QString pathToGatewayFile(DEFAULT_INTERFACE_CONF_LOCATION);
	pathToGatewayFile += ifName;
	interfaceconfiguration *ifConf = new interfaceconfiguration();
	ifConf->readConfigOutOfFile(pathToGatewayFile);
	_ifcMap.insert(ifName, ifConf);

	// replace default route
	qDebug() << _tag << "replace default route";
	_networkManager.replaceDefaultRoute(ifName,
			ifConf->getGateway(), mss, AF_INET);

	if (checkConnectivityViaTcp(_serverIp)) {
		qDebug() << _tag << "internet: check passed! for interface" << ifName;
		emit
		updateStatusLabel(ifName, "connection possible");
		if (!_userChoice) {
			// blockiere jeden weiteren check
			// emite continueBoot
			_blocked = true;
			emit continueBoot(ifName, 0);
		} else {
			emit connectionEstablished(ifName);
		}
		return true;
	} else {
		qDebug() << _tag << "no internet connection with interface" << ifName;
		emit
		updateStatusLabel(ifName, "connection not possible");
		return false;
	}
}



bool NetworkDiscovery::checkConnectivityViaTcp(QString server) {
	// check connectivity via tcp connection
	QTcpSocket *tcpSocket = new QTcpSocket(this);
	tcpSocket->connectToHost(server, 80);
	if (!tcpSocket->waitForConnected(500)) {
		qDebug() << _tag << tcpSocket->errorString();
		return false;
	} else {
		return true;
	}
}



/**
 *
 */
void NetworkDiscovery::handleNewConnection() {
	qDebug() << _tag << "New Connection arrived";

	/*QLocalSocket **/
	_client = _server ->nextPendingConnection();
	_clients.insert(_client, _client);
	connect(_client, SIGNAL(disconnected()), this,
			SLOT(handleClientDisconnect()));
	connect(_client, SIGNAL(readyRead()), this, SLOT(handleNewInput()));
}



/**
 *
 */
void NetworkDiscovery::handleClientDisconnect() {
	QLocalSocket* socket = qobject_cast<QLocalSocket *> (QObject::sender());

	QLocalSocket * client = _clients.value(socket);

	qDebug() << _tag << "disconnect client";
	handleNewInput(client);
	client->deleteLater();
}



/**
 *
 */
void NetworkDiscovery::handleNewInput(QLocalSocket * client) {
	qDebug() << _tag << "last read before exit";
	while (client->canReadLine()) {
		QString data(client->readLine());

		data = data.trimmed();
		qDebug() << _tag << data;
		QStringList lines = data.split("\n");

		for (int i = 0; i < lines.length(); i++) {
			handleNewInputLine(client, lines.at(i));
		}
	}
}



/**
 *
 * This method is connected to the readyRead Signal of the QLocalSocket
 * client.
 * send an ACK to the client with every received message.
 */
void NetworkDiscovery::handleNewInput() {
	QLocalSocket* socket = qobject_cast<QLocalSocket *> (QObject::sender());

	QLocalSocket * client = _clients.value(socket);
	QString data(client->read(DHCP_MESSAGE_SIZE));
	client->write("ACK", ACK_SIZE);
	client->waitForBytesWritten();
	data = data.trimmed();
	//qDebug() << _tag << data;
	QStringList lines = data.split("\n");

	for (int i = 0; i < lines.length(); i++) {
		handleNewInputLine(client, lines.at(i));
	}
}



/**
 * This Method processes the send messages.
 *
 * This Method processes the send messages. It splits the line
 * into several components. Those components are:
 *  interface: interface name ==> indicates the process who send the message
 *  s_state: is the number representation of syslog.h LOG levels
 *  s_subState: is the number representation of the dhcp.c DHCP states (1 - 8) plus
 *    the status. h states (9 - ..)
 *  msg: is a message which can contain additional informations
 *
 * According to the s_state and s_subState we emit the changeProgressBarValue() signal
 * with different values.
 *
 * @param client
 *  the client who send the message
 *
 * @param data
 *  the message. (format <interfaceName>;<state>;<subState>;<msg> )
 */
void NetworkDiscovery::handleNewInputLine(QLocalSocket * client, QString data) {

	QString logMsg(data);
	QString interface = logMsg.section(";", 0, 0);
	QString s_state = logMsg.section(";", 1, 1);
	QString s_subState = logMsg.section(";", 2, 2);
	QString msg = logMsg.section(";", 3, 3);
	int st = s_state.trimmed().toInt();
	int sst = s_subState.trimmed().toInt();
	//qDebug() << _tag << logMsg;

	if (_ifNameToClient.size() < _numberOfProcesses && !_ifNameToClient.contains(
			interface)) {
		_ifNameToClient.insert(interface, client);
	}

	switch (st) {
	case LOG_INFO:
		switch (sst) {
		case DHCP_DISCOVER:
			emit changeProgressBarValue(interface, 10);
			break;
		case DHCP_OFFER:
			emit changeProgressBarValue(interface, 20);
			break;
		case DHCP_REQUEST:
			emit changeProgressBarValue(interface, 30);
			break;
		case DHCP_ACK:
			emit changeProgressBarValue(interface, 40);
			break;
		case DHCP_NAK:
			emit changeProgressBarValue(interface, 40);
			break;
		case DHCPCD_ARP_TEST:
			emit changeProgressBarValue(interface, 50);
			break;
		case DHCP_DECLINE:
			emit changeProgressBarValue(interface, 60);
			break;
		case DHCP_RELEASE:

			break;
		case DHCP_INFORM:
			break;
		case DHCPCD_CONFIGURE:
			emit changeProgressBarValue(interface, 70);
			break;
		case DHCPCD_WRITE:
			emit changeProgressBarValue(interface, 80);
			break;
		case DHCPCD_EXIT:
			emit changeProgressBarValue(interface, 100);
			break;
		case DHCPCD_LOG:

		default:
			break;
		}
		break;
	case LOG_ERR:
		qDebug() << _tag << "received error:" << msg;
		break;
	default:
		//qDebug() << _tag << logMsg;
		break;
	}
}



/**
 * This Method is called when a process is finished.
 *
 * This Method is called when a process is finished. This slot is connected
 * with the signal finished() of the QProcess class.
 * If the process finishes, it will be checked if the process exited normal
 * or if an unexpected error occurred. For this, we determine the sender (which is a
 * QProcess), get the corresponding interface (which is stored in a map), and check
 * the exitCode. Further actions are taken according to the exitCode check.
 * Normal exit:
 * 	emit changeProgressBar() to 100%
 *  emit updateStatusLabel() to check connection
 *  checkConnectivity() @see NetworkDiscovery::checkConnectivity()
 * Unexpected exit:
 *  emit updateStatusLabel() to process exited unexpected
 *  TODO:: the reason for the unexpected exit should be presented in the logfile.
 *
 * @param exitCode
 *
 * @param exitStatus
 *
 * @return bool
 * 	returns true: if the interface name i starts with a letter in the blacklist.
 *
 * 	returns false: else
 *
 * @see NetworkDiscovery::getListOfNetworkInterfaces()
 */
void NetworkDiscovery::handleProcessFinished(int exitCode,
		QProcess::ExitStatus exitStatus) {

	QProcess* p = qobject_cast<QProcess *> (QObject::sender());
	QString ifName = _clientProcessToIfNameMap.value(p, "ifName");
	if (!_blocked) { //_blocked becomes true, if _userChoice is false and we already found a usable interface
		if (ifName.compare("ifName") == 0) {
			qDebug() << _tag << "--- \t [NetworkDiscovery::handleProcessFinished] haven't found process!";
		} else {
			qDebug() << _tag << "process for interface" << ifName << "finished"
					<< exitCode << exitStatus;
			if (exitCode > 0) {
				qDebug() << _tag << "process exited unexpected";
				emit updateStatusLabel(ifName, "process exited unexpected");
			} else {
				qDebug() << _tag << "process normal exit";
				emit changeProgressBarValue(ifName, 100);
				emit updateStatusLabel(ifName, "check connectivity");
				checkConnectivity(ifName);
			}
		}
		if (!_blocked) { //_blocked becomes true, if _userChoice is false and we found a usable interface
			QLocalSocket *client = _ifNameToClient.value(ifName, 0);
			if (client != 0) {
				handleNewInput(client);
			}
			_numberOfProcesses = _numberOfProcesses - 1;
			if (_numberOfProcesses <= 0 && _userChoice) {
				emit allProcessesFinished();
			}
		}
	} else {
		qDebug() << _tag << "already blocked";
		emit updateStatusLabel(ifName, "finished DHCP");
	}
}



/**
 * This Method is called when a process is started.
 *
 * This Method is called when a process is started.
 * It prints the message: "process started for interface: <interfaceName>".
 */
void NetworkDiscovery::handleProcessStarted() {
	QProcess* p = qobject_cast<QProcess *> (QObject::sender());
	QString ifName = _clientProcessToIfNameMap.value(p, "ifName");
	qDebug() << _tag << "process started for interface:" << ifName;
}



/**
 * This Method implements a blacklist.
 *
 * This Method implements a blacklist. We check the fist character
 * of the interface name. if this letter is in the list, we return true.
 * True means, that this interface won't be put into the result list of
 * getListOfNetworkInterfaces().
 *
 * @param i
 * 	is a interface name.
 *
 * @return bool
 * 	returns true: if the interface name i starts with a letter in the blacklist.
 *
 * 	returns false: else
 *
 * @see NetworkDiscovery::getListOfNetworkInterfaces()
 */
bool NetworkDiscovery::checkBlackList(QString i) {
	if (i.startsWith("v", Qt::CaseInsensitive)) {
		return true;
	} else if (i.startsWith("d", Qt::CaseInsensitive)) {
		return true;
	} else {
		return false;
	}
}