1
0

mainwindow.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2012-2013 ZeroTier Networks LLC
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * --
  19. *
  20. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #include "mainwindow.h"
  28. #include "aboutwindow.h"
  29. #include "networkwidget.h"
  30. #include "ui_mainwindow.h"
  31. #include "installdialog.h"
  32. #include <string>
  33. #include <map>
  34. #include <set>
  35. #include <vector>
  36. #include <stdexcept>
  37. #include <utility>
  38. #include <QClipboard>
  39. #include <QMutex>
  40. #include <QCoreApplication>
  41. #include <QDir>
  42. #include <QFile>
  43. #include <QMessageBox>
  44. #include <QDebug>
  45. #include <QProcess>
  46. #include <QStringList>
  47. #include <QVBoxLayout>
  48. #include <QScrollBar>
  49. #include <QEventLoop>
  50. QNetworkAccessManager *nam;
  51. // Globally visible
  52. ZeroTier::Node::LocalClient *zeroTierClient = (ZeroTier::Node::LocalClient *)0;
  53. // Main window instance for app
  54. static MainWindow *mainWindow = (MainWindow *)0;
  55. static void handleZTMessage(void *arg,unsigned long id,const char *line)
  56. {
  57. static std::map< unsigned long,std::vector<std::string> > ztReplies;
  58. static QMutex ztReplies_m;
  59. ztReplies_m.lock();
  60. if (*line) {
  61. ztReplies[id].push_back(std::string(line));
  62. ztReplies_m.unlock();
  63. } else { // empty lines conclude transmissions
  64. std::map< unsigned long,std::vector<std::string> >::iterator r(ztReplies.find(id));
  65. if (r != ztReplies.end()) {
  66. MainWindow::ZTMessageEvent *event = new MainWindow::ZTMessageEvent(r->second);
  67. ztReplies.erase(r);
  68. ztReplies_m.unlock();
  69. QCoreApplication::postEvent(mainWindow,event); // must post since this may be another thread
  70. } else ztReplies_m.unlock();
  71. }
  72. }
  73. MainWindow::MainWindow(QWidget *parent) :
  74. QMainWindow(parent),
  75. ui(new Ui::MainWindow),
  76. pollServiceTimerId(-1)
  77. {
  78. ui->setupUi(this);
  79. if (ui->networkListWidget->verticalScrollBar())
  80. ui->networkListWidget->verticalScrollBar()->setSingleStep(8);
  81. QWidgetList widgets = this->findChildren<QWidget*>();
  82. foreach(QWidget *widget, widgets)
  83. widget->setAttribute(Qt::WA_MacShowFocusRect,false);
  84. ui->noNetworksLabel->setText("Connecting to Service..."); // changed when result is received
  85. mainWindow = this;
  86. this->pollServiceTimerId = this->startTimer(1000);
  87. this->setEnabled(false); // gets enabled when updates are received
  88. this->cyclesSinceResponseFromService = 0;
  89. }
  90. MainWindow::~MainWindow()
  91. {
  92. delete ui;
  93. delete zeroTierClient;
  94. zeroTierClient = (ZeroTier::Node::LocalClient *)0;
  95. mainWindow = (MainWindow *)0;
  96. }
  97. void MainWindow::timerEvent(QTimerEvent *event)
  98. {
  99. event->accept();
  100. if (this->isHidden())
  101. return;
  102. if (pollServiceTimerId < 0)
  103. return;
  104. if (!zeroTierClient) {
  105. std::string authToken;
  106. if (!ZeroTier::Utils::readFile(ZeroTier::Node::LocalClient::authTokenDefaultUserPath().c_str(),authToken)) {
  107. #ifdef __APPLE__
  108. if (QFile::exists("/Library/Application Support/ZeroTier/One/zerotier-one")) {
  109. QMessageBox::information(this,"Authorization Required","You must authenticate to authorize this user to administrate ZeroTier One on this computer.\n\n(This only needs to be done once.)",QMessageBox::Ok,QMessageBox::NoButton);
  110. QString authHelperPath(QCoreApplication::applicationDirPath() + "/../Resources/helpers/mac/ZeroTier One (Authenticate).app/Contents/MacOS/applet");
  111. if (!QFile::exists(authHelperPath)) {
  112. QMessageBox::critical(this,"Unable to Locate Helper","Unable to locate authorization helper, cannot obtain authentication token.",QMessageBox::Ok,QMessageBox::NoButton);
  113. QApplication::exit(1);
  114. return;
  115. }
  116. QProcess::execute(authHelperPath,QStringList());
  117. } else {
  118. doInstallDialog();
  119. return;
  120. }
  121. #endif
  122. if (!ZeroTier::Utils::readFile(ZeroTier::Node::LocalClient::authTokenDefaultUserPath().c_str(),authToken)) {
  123. QMessageBox::critical(this,"Cannot Authorize","Unable to authorize this user to administrate ZeroTier One. (Did you enter your password correctly?)",QMessageBox::Ok,QMessageBox::NoButton);
  124. QApplication::exit(1);
  125. return;
  126. }
  127. }
  128. zeroTierClient = new ZeroTier::Node::LocalClient(authToken.c_str(),0,&handleZTMessage,this);
  129. }
  130. // TODO: do something more user-friendly here... or maybe try to restart
  131. // the service?
  132. if (++this->cyclesSinceResponseFromService == 4)
  133. QMessageBox::critical(this,"No Response from Service","The ZeroTier One service does not appear to be running.",QMessageBox::Ok,QMessageBox::NoButton);
  134. zeroTierClient->send("info");
  135. zeroTierClient->send("listnetworks");
  136. zeroTierClient->send("listpeers");
  137. }
  138. void MainWindow::customEvent(QEvent *event)
  139. {
  140. ZTMessageEvent *m = (ZTMessageEvent *)event; // only one custom event type so far
  141. if (m->ztMessage.size() == 0)
  142. return;
  143. std::vector<std::string> hdr(ZeroTier::Node::LocalClient::splitLine(m->ztMessage[0]));
  144. if (hdr.size() < 2)
  145. return;
  146. if (hdr[0] != "200")
  147. return;
  148. this->cyclesSinceResponseFromService = 0;
  149. if (hdr[1] == "info") {
  150. if (hdr.size() >= 3)
  151. this->myAddress = hdr[2].c_str();
  152. if (hdr.size() >= 4)
  153. this->myStatus = hdr[3].c_str();
  154. if (hdr.size() >= 5)
  155. this->myVersion = hdr[4].c_str();
  156. } else if (hdr[1] == "listnetworks") {
  157. std::map< std::string,std::vector<std::string> > newNetworks;
  158. for(unsigned long i=1;i<m->ztMessage.size();++i) {
  159. std::vector<std::string> l(ZeroTier::Node::LocalClient::splitLine(m->ztMessage[i]));
  160. // 200 listnetworks <nwid> <name> <status> <config age> <type> <dev> <ips>
  161. if ((l.size() == 9)&&(l[2].length() == 16))
  162. newNetworks[l[2]] = l;
  163. }
  164. if (newNetworks != networks) {
  165. networks = newNetworks;
  166. for (bool removed=true;removed;) {
  167. removed = false;
  168. for(int r=0;r<ui->networkListWidget->count();++r) {
  169. NetworkWidget *nw = (NetworkWidget *)ui->networkListWidget->itemWidget(ui->networkListWidget->item(r));
  170. if (!networks.count(nw->networkId())) {
  171. ui->networkListWidget->setVisible(false); // HACK to prevent an occasional crash here, discovered through hours of shotgun debugging... :P
  172. delete ui->networkListWidget->takeItem(r);
  173. removed = true;
  174. break;
  175. }
  176. }
  177. }
  178. ui->networkListWidget->setVisible(true);
  179. std::set<std::string> alreadyDisplayed;
  180. for(int r=0;r<ui->networkListWidget->count();++r) {
  181. NetworkWidget *nw = (NetworkWidget *)ui->networkListWidget->itemWidget(ui->networkListWidget->item(r));
  182. if (networks.count(nw->networkId()) > 0) {
  183. alreadyDisplayed.insert(nw->networkId());
  184. std::vector<std::string> &l = networks[nw->networkId()];
  185. nw->setNetworkName(l[3]);
  186. nw->setStatus(l[4],l[5]);
  187. nw->setNetworkType(l[6]);
  188. nw->setNetworkDeviceName(l[7]);
  189. nw->setIps(l[8]);
  190. }
  191. }
  192. for(std::map< std::string,std::vector<std::string> >::iterator nwdata(networks.begin());nwdata!=networks.end();++nwdata) {
  193. if (alreadyDisplayed.count(nwdata->first) == 0) {
  194. std::vector<std::string> &l = nwdata->second;
  195. NetworkWidget *nw = new NetworkWidget((QWidget *)0,nwdata->first);
  196. nw->setNetworkName(l[3]);
  197. nw->setStatus(l[4],l[5]);
  198. nw->setNetworkType(l[6]);
  199. nw->setNetworkDeviceName(l[7]);
  200. nw->setIps(l[8]);
  201. QListWidgetItem *item = new QListWidgetItem();
  202. item->setSizeHint(nw->sizeHint());
  203. ui->networkListWidget->addItem(item);
  204. ui->networkListWidget->setItemWidget(item,nw);
  205. }
  206. }
  207. }
  208. } else if (hdr[1] == "listpeers") {
  209. this->numPeers = 0;
  210. for(unsigned long i=1;i<m->ztMessage.size();++i) {
  211. std::vector<std::string> l(ZeroTier::Node::LocalClient::splitLine(m->ztMessage[i]));
  212. if ((l.size() >= 5)&&((l[3] != "-")||(l[4] != "-")))
  213. ++this->numPeers; // number of direct peers online -- check for active IPv4 and/or IPv6 address
  214. }
  215. }
  216. if (!ui->networkListWidget->count()) {
  217. ui->noNetworksLabel->setText("You Have Not Joined Any Networks");
  218. ui->noNetworksLabel->setVisible(true);
  219. } else ui->noNetworksLabel->setVisible(false);
  220. if (this->myAddress.size())
  221. ui->addressButton->setText(this->myAddress);
  222. else ui->addressButton->setText(" ");
  223. QString st(this->myStatus);
  224. st += ", v";
  225. st += this->myVersion;
  226. st += ", ";
  227. st += QString::number(this->numPeers);
  228. st += " direct links to peers";
  229. ui->statusLabel->setText(st);
  230. if (this->myStatus == "ONLINE") {
  231. if (!this->isEnabled())
  232. this->setEnabled(true);
  233. } else {
  234. if (this->isEnabled())
  235. this->setEnabled(false);
  236. }
  237. }
  238. void MainWindow::showEvent(QShowEvent *event)
  239. {
  240. #ifdef __APPLE__
  241. if (!QFile::exists("/Library/Application Support/ZeroTier/One/zerotier-one"))
  242. doInstallDialog();
  243. #endif
  244. }
  245. void MainWindow::on_joinNetworkButton_clicked()
  246. {
  247. QString toJoin(ui->networkIdLineEdit->text());
  248. ui->networkIdLineEdit->setText(QString());
  249. if (!zeroTierClient) // sanity check
  250. return;
  251. if (toJoin.size() != 16) {
  252. QMessageBox::information(this,"Invalid Network ID","The network ID you entered was not valid. Enter a 16-digit hexadecimal network ID, like '8056c2e21c000001'.",QMessageBox::Ok,QMessageBox::NoButton);
  253. return;
  254. }
  255. zeroTierClient->send((QString("join ") + toJoin).toStdString());
  256. }
  257. void MainWindow::on_actionAbout_triggered()
  258. {
  259. AboutWindow *about = new AboutWindow(this);
  260. about->show();
  261. }
  262. void MainWindow::on_networkIdLineEdit_textChanged(const QString &text)
  263. {
  264. QString newText;
  265. for(QString::const_iterator i(text.begin());i!=text.end();++i) {
  266. switch(i->toLatin1()) {
  267. case '0': newText.append('0'); break;
  268. case '1': newText.append('1'); break;
  269. case '2': newText.append('2'); break;
  270. case '3': newText.append('3'); break;
  271. case '4': newText.append('4'); break;
  272. case '5': newText.append('5'); break;
  273. case '6': newText.append('6'); break;
  274. case '7': newText.append('7'); break;
  275. case '8': newText.append('8'); break;
  276. case '9': newText.append('9'); break;
  277. case 'a': newText.append('a'); break;
  278. case 'b': newText.append('b'); break;
  279. case 'c': newText.append('c'); break;
  280. case 'd': newText.append('d'); break;
  281. case 'e': newText.append('e'); break;
  282. case 'f': newText.append('f'); break;
  283. case 'A': newText.append('a'); break;
  284. case 'B': newText.append('b'); break;
  285. case 'C': newText.append('c'); break;
  286. case 'D': newText.append('d'); break;
  287. case 'E': newText.append('e'); break;
  288. case 'F': newText.append('f'); break;
  289. default: break;
  290. }
  291. }
  292. if (newText.size() > 16)
  293. newText.truncate(16);
  294. ui->networkIdLineEdit->setText(newText);
  295. }
  296. void MainWindow::on_addressButton_clicked()
  297. {
  298. QApplication::clipboard()->setText(this->myAddress);
  299. }
  300. void MainWindow::doInstallDialog()
  301. {
  302. #ifdef __APPLE__
  303. this->setEnabled(false);
  304. if (pollServiceTimerId >= 0) {
  305. this->killTimer(pollServiceTimerId);
  306. pollServiceTimerId = -1;
  307. }
  308. InstallDialog *id = new InstallDialog(this);
  309. id->setModal(true);
  310. id->show();
  311. #endif
  312. }