mainwindow.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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 <string>
  28. #include <map>
  29. #include <set>
  30. #include <vector>
  31. #include <stdexcept>
  32. #include <utility>
  33. #include <QClipboard>
  34. #include <QMutex>
  35. #include <QCoreApplication>
  36. #include <QDir>
  37. #include <QFile>
  38. #include <QMessageBox>
  39. #include <QDebug>
  40. #include <QProcess>
  41. #include <QStringList>
  42. #include <QVBoxLayout>
  43. #include <QScrollBar>
  44. #include <QEventLoop>
  45. #include "main.h"
  46. #include "mainwindow.h"
  47. #include "aboutwindow.h"
  48. #include "networkwidget.h"
  49. #include "ui_mainwindow.h"
  50. #ifdef __APPLE__
  51. #include <stdio.h>
  52. #include <string.h>
  53. #include <unistd.h>
  54. #include <sys/types.h>
  55. #include <sys/stat.h>
  56. #include "mac_doprivileged.h"
  57. #endif
  58. // Globally visible
  59. ZeroTier::Node::LocalClient *zeroTierClient = (ZeroTier::Node::LocalClient *)0;
  60. // Main window instance for app
  61. static MainWindow *mainWindow = (MainWindow *)0;
  62. // Handles message from ZeroTier One service
  63. static void handleZTMessage(void *arg,unsigned long id,const char *line)
  64. {
  65. static std::map< unsigned long,std::vector<std::string> > ztReplies;
  66. static QMutex ztReplies_m;
  67. ztReplies_m.lock();
  68. if (*line) {
  69. ztReplies[id].push_back(std::string(line));
  70. ztReplies_m.unlock();
  71. } else { // empty lines conclude transmissions
  72. std::map< unsigned long,std::vector<std::string> >::iterator r(ztReplies.find(id));
  73. if (r != ztReplies.end()) {
  74. // The message is packed into an event and sent to the main window where
  75. // the actual parsing code lives.
  76. MainWindow::ZTMessageEvent *event = new MainWindow::ZTMessageEvent(r->second);
  77. ztReplies.erase(r);
  78. ztReplies_m.unlock();
  79. QCoreApplication::postEvent(mainWindow,event); // must post since this may be another thread
  80. } else ztReplies_m.unlock();
  81. }
  82. }
  83. MainWindow::MainWindow(QWidget *parent) :
  84. QMainWindow(parent),
  85. ui(new Ui::MainWindow),
  86. pollServiceTimerId(-1)
  87. {
  88. mainWindow = this;
  89. ui->setupUi(this);
  90. if (ui->networkListWidget->verticalScrollBar())
  91. ui->networkListWidget->verticalScrollBar()->setSingleStep(8);
  92. #ifdef __APPLE__
  93. QWidgetList widgets = this->findChildren<QWidget*>();
  94. foreach(QWidget *widget, widgets)
  95. widget->setAttribute(Qt::WA_MacShowFocusRect,false);
  96. #endif
  97. ui->noNetworksLabel->setVisible(true);
  98. ui->noNetworksLabel->setText("Connecting to Service...");
  99. ui->bottomContainerWidget->setVisible(false);
  100. ui->networkListWidget->setVisible(false);
  101. this->pollServiceTimerId = this->startTimer(1000);
  102. this->cyclesSinceResponseFromService = 0;
  103. }
  104. MainWindow::~MainWindow()
  105. {
  106. delete ui;
  107. delete zeroTierClient;
  108. zeroTierClient = (ZeroTier::Node::LocalClient *)0;
  109. mainWindow = (MainWindow *)0;
  110. }
  111. void MainWindow::timerEvent(QTimerEvent *event)
  112. {
  113. event->accept();
  114. if (this->isHidden())
  115. return;
  116. if (pollServiceTimerId < 0)
  117. return;
  118. if (!zeroTierClient) {
  119. std::string authToken;
  120. if (!ZeroTier::Utils::readFile(ZeroTier::Node::LocalClient::authTokenDefaultUserPath().c_str(),authToken)) {
  121. #ifdef __APPLE__
  122. if (QFile::exists("/Library/Application Support/ZeroTier/One/zerotier-one")) {
  123. // Authorize user by copying auth token into local home directory
  124. QMessageBox::information(this,"Authorization Needed","Administrator privileges are required to allow the current user to control ZeroTier One on this computer. (You only have to do this once.)",QMessageBox::Ok,QMessageBox::NoButton);
  125. std::string homePath(QDir::homePath().toStdString());
  126. QString zt1Caches(QDir::homePath() + "/Library/Caches/ZeroTier/One");
  127. QDir::root().mkpath(zt1Caches);
  128. std::string tmpPath((zt1Caches + "/auth.sh").toStdString());
  129. FILE *scr = fopen(tmpPath.c_str(),"w");
  130. if (!scr) {
  131. QMessageBox::critical(this,"Cannot Authorize","Unable to authorize this user to administrate ZeroTier One. (Cannot write to temporary Library/Caches/ZeroTier/One folder.)",QMessageBox::Ok,QMessageBox::NoButton);
  132. QApplication::exit(1);
  133. return;
  134. }
  135. fprintf(scr,"#!/bin/bash\n");
  136. fprintf(scr,"export PATH=\"/bin:/usr/bin:/sbin:/usr/sbin\"\n");
  137. fprintf(scr,"if [ -f '/Library/Application Support/ZeroTier/One/authtoken.secret' ]; then\n");
  138. fprintf(scr," mkdir -p '%s/Library/Application Support/ZeroTier/One'\n",homePath.c_str());
  139. fprintf(scr," chown %d '%s/Library/Application Support/ZeroTier'\n",(int)getuid(),homePath.c_str());
  140. fprintf(scr," chgrp %d '%s/Library/Application Support/ZeroTier'\n",(int)getgid(),homePath.c_str());
  141. fprintf(scr," chmod 0700 '%s/Library/Application Support/ZeroTier'\n",homePath.c_str());
  142. fprintf(scr," chown %d '%s/Library/Application Support/ZeroTier/One'\n",(int)getuid(),homePath.c_str());
  143. fprintf(scr," chgrp %d '%s/Library/Application Support/ZeroTier/One'\n",(int)getgid(),homePath.c_str());
  144. fprintf(scr," chmod 0700 '%s/Library/Application Support/ZeroTier/One'\n",homePath.c_str());
  145. fprintf(scr," cp -f '/Library/Application Support/ZeroTier/One/authtoken.secret' '%s/Library/Application Support/ZeroTier/One/authtoken.secret'\n",homePath.c_str());
  146. fprintf(scr," chown %d '%s/Library/Application Support/ZeroTier/One/authtoken.secret'\n",(int)getuid(),homePath.c_str());
  147. fprintf(scr," chgrp %d '%s/Library/Application Support/ZeroTier/One/authtoken.secret'\n",(int)getgid(),homePath.c_str());
  148. fprintf(scr," chmod 0600 '%s/Library/Application Support/ZeroTier/One/authtoken.secret'\n",homePath.c_str());
  149. fprintf(scr,"fi\n");
  150. fprintf(scr,"exit 0\n");
  151. fclose(scr);
  152. chmod(tmpPath.c_str(),0755);
  153. macExecutePrivilegedShellCommand((std::string("'")+tmpPath+"' >>/dev/null 2>&1").c_str());
  154. unlink(tmpPath.c_str());
  155. }
  156. #endif
  157. if (!ZeroTier::Utils::readFile(ZeroTier::Node::LocalClient::authTokenDefaultUserPath().c_str(),authToken)) {
  158. if (!ZeroTier::Utils::readFile(ZeroTier::Node::LocalClient::authTokenDefaultSystemPath().c_str(),authToken)) {
  159. QMessageBox::critical(this,"Cannot Authorize","Unable to authorize this user to administrate ZeroTier One. (Did you enter your password correctly?)",QMessageBox::Ok,QMessageBox::NoButton);
  160. QApplication::exit(1);
  161. return;
  162. }
  163. }
  164. }
  165. zeroTierClient = new ZeroTier::Node::LocalClient(authToken.c_str(),0,&handleZTMessage,this);
  166. }
  167. if (++this->cyclesSinceResponseFromService >= 3) {
  168. if (this->cyclesSinceResponseFromService == 3)
  169. QMessageBox::warning(this,"Service Not Running","Can't connect to the ZeroTier One service. Is it running?",QMessageBox::Ok);
  170. ui->noNetworksLabel->setVisible(true);
  171. ui->noNetworksLabel->setText("Connecting to Service...");
  172. ui->bottomContainerWidget->setVisible(false);
  173. ui->networkListWidget->setVisible(false);
  174. }
  175. zeroTierClient->send("info");
  176. zeroTierClient->send("listnetworks");
  177. zeroTierClient->send("listpeers");
  178. }
  179. void MainWindow::customEvent(QEvent *event)
  180. {
  181. QMessageBox::information(this,"event","event",QMessageBox::Ok);
  182. ZTMessageEvent *m = (ZTMessageEvent *)event; // only one custom event type so far
  183. if (m->ztMessage.size() == 0)
  184. return;
  185. this->cyclesSinceResponseFromService = 0;
  186. std::vector<std::string> hdr(ZeroTier::Node::LocalClient::splitLine(m->ztMessage[0]));
  187. if (hdr.size() < 2)
  188. return;
  189. if (hdr[0] != "200")
  190. return;
  191. if (hdr[1] == "info") {
  192. if (hdr.size() >= 3)
  193. this->myAddress = hdr[2].c_str();
  194. if (hdr.size() >= 4)
  195. this->myStatus = hdr[3].c_str();
  196. if (hdr.size() >= 5)
  197. this->myVersion = hdr[4].c_str();
  198. } else if (hdr[1] == "listnetworks") {
  199. std::map< std::string,std::vector<std::string> > newNetworks;
  200. for(unsigned long i=1;i<m->ztMessage.size();++i) {
  201. std::vector<std::string> l(ZeroTier::Node::LocalClient::splitLine(m->ztMessage[i]));
  202. // 200 listnetworks <nwid> <name> <status> <config age> <type> <dev> <ips>
  203. if ((l.size() == 9)&&(l[2].length() == 16))
  204. newNetworks[l[2]] = l;
  205. }
  206. if (newNetworks != networks) {
  207. networks = newNetworks;
  208. for (bool removed=true;removed;) {
  209. removed = false;
  210. for(int r=0;r<ui->networkListWidget->count();++r) {
  211. NetworkWidget *nw = (NetworkWidget *)ui->networkListWidget->itemWidget(ui->networkListWidget->item(r));
  212. if (!networks.count(nw->networkId())) {
  213. ui->networkListWidget->setVisible(false); // HACK to prevent an occasional crash here, discovered through hours of shotgun debugging... :P
  214. delete ui->networkListWidget->takeItem(r);
  215. removed = true;
  216. break;
  217. }
  218. }
  219. }
  220. ui->networkListWidget->setVisible(true);
  221. std::set<std::string> alreadyDisplayed;
  222. for(int r=0;r<ui->networkListWidget->count();++r) {
  223. NetworkWidget *nw = (NetworkWidget *)ui->networkListWidget->itemWidget(ui->networkListWidget->item(r));
  224. if (networks.count(nw->networkId()) > 0) {
  225. alreadyDisplayed.insert(nw->networkId());
  226. std::vector<std::string> &l = networks[nw->networkId()];
  227. nw->setNetworkName(l[3]);
  228. nw->setStatus(l[4],l[5]);
  229. nw->setNetworkType(l[6]);
  230. nw->setNetworkDeviceName(l[7]);
  231. nw->setIps(l[8]);
  232. }
  233. }
  234. for(std::map< std::string,std::vector<std::string> >::iterator nwdata(networks.begin());nwdata!=networks.end();++nwdata) {
  235. if (alreadyDisplayed.count(nwdata->first) == 0) {
  236. std::vector<std::string> &l = nwdata->second;
  237. NetworkWidget *nw = new NetworkWidget((QWidget *)0,nwdata->first);
  238. nw->setNetworkName(l[3]);
  239. nw->setStatus(l[4],l[5]);
  240. nw->setNetworkType(l[6]);
  241. nw->setNetworkDeviceName(l[7]);
  242. nw->setIps(l[8]);
  243. QListWidgetItem *item = new QListWidgetItem();
  244. item->setSizeHint(nw->sizeHint());
  245. ui->networkListWidget->addItem(item);
  246. ui->networkListWidget->setItemWidget(item,nw);
  247. }
  248. }
  249. }
  250. } else if (hdr[1] == "listpeers") {
  251. this->numPeers = 0;
  252. for(unsigned long i=1;i<m->ztMessage.size();++i) {
  253. std::vector<std::string> l(ZeroTier::Node::LocalClient::splitLine(m->ztMessage[i]));
  254. if ((l.size() >= 5)&&((l[3] != "-")||(l[4] != "-")))
  255. ++this->numPeers; // number of direct peers online -- check for active IPv4 and/or IPv6 address
  256. }
  257. }
  258. if (!ui->networkListWidget->count()) {
  259. ui->noNetworksLabel->setText("You Have Not Joined Any Networks");
  260. ui->noNetworksLabel->setVisible(true);
  261. } else ui->noNetworksLabel->setVisible(false);
  262. if (!ui->bottomContainerWidget->isVisible())
  263. ui->bottomContainerWidget->setVisible(true);
  264. if (!ui->networkListWidget->isVisible())
  265. ui->networkListWidget->setVisible(true);
  266. if (this->myAddress.size())
  267. ui->addressButton->setText(this->myAddress);
  268. else ui->addressButton->setText(" ");
  269. QString st(this->myStatus);
  270. st += ", v";
  271. st += this->myVersion;
  272. st += ", ";
  273. st += QString::number(this->numPeers);
  274. st += " direct links to peers";
  275. ui->statusLabel->setText(st);
  276. }
  277. void MainWindow::on_joinNetworkButton_clicked()
  278. {
  279. QString toJoin(ui->networkIdLineEdit->text());
  280. ui->networkIdLineEdit->setText(QString());
  281. if (!zeroTierClient) // sanity check
  282. return;
  283. if (toJoin.size() != 16) {
  284. 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);
  285. return;
  286. }
  287. zeroTierClient->send((QString("join ") + toJoin).toStdString());
  288. }
  289. void MainWindow::on_actionAbout_triggered()
  290. {
  291. AboutWindow *about = new AboutWindow(this);
  292. about->show();
  293. }
  294. void MainWindow::on_networkIdLineEdit_textChanged(const QString &text)
  295. {
  296. QString newText;
  297. for(QString::const_iterator i(text.begin());i!=text.end();++i) {
  298. switch(i->toLatin1()) {
  299. case '0': newText.append('0'); break;
  300. case '1': newText.append('1'); break;
  301. case '2': newText.append('2'); break;
  302. case '3': newText.append('3'); break;
  303. case '4': newText.append('4'); break;
  304. case '5': newText.append('5'); break;
  305. case '6': newText.append('6'); break;
  306. case '7': newText.append('7'); break;
  307. case '8': newText.append('8'); break;
  308. case '9': newText.append('9'); break;
  309. case 'a': newText.append('a'); break;
  310. case 'b': newText.append('b'); break;
  311. case 'c': newText.append('c'); break;
  312. case 'd': newText.append('d'); break;
  313. case 'e': newText.append('e'); break;
  314. case 'f': newText.append('f'); break;
  315. case 'A': newText.append('a'); break;
  316. case 'B': newText.append('b'); break;
  317. case 'C': newText.append('c'); break;
  318. case 'D': newText.append('d'); break;
  319. case 'E': newText.append('e'); break;
  320. case 'F': newText.append('f'); break;
  321. default: break;
  322. }
  323. }
  324. if (newText.size() > 16)
  325. newText.truncate(16);
  326. ui->networkIdLineEdit->setText(newText);
  327. }
  328. void MainWindow::on_addressButton_clicked()
  329. {
  330. QApplication::clipboard()->setText(this->myAddress);
  331. }