mainwindow.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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. QWidgetList widgets = this->findChildren<QWidget*>();
  93. foreach(QWidget *widget, widgets)
  94. widget->setAttribute(Qt::WA_MacShowFocusRect,false);
  95. ui->noNetworksLabel->setText("Connecting to Service..."); // changed when result is received
  96. this->pollServiceTimerId = this->startTimer(1000);
  97. this->setEnabled(false); // gets enabled when updates are received
  98. this->cyclesSinceResponseFromService = 0;
  99. }
  100. MainWindow::~MainWindow()
  101. {
  102. delete ui;
  103. delete zeroTierClient;
  104. zeroTierClient = (ZeroTier::Node::LocalClient *)0;
  105. mainWindow = (MainWindow *)0;
  106. }
  107. void MainWindow::timerEvent(QTimerEvent *event)
  108. {
  109. event->accept();
  110. if (this->isHidden())
  111. return;
  112. if (pollServiceTimerId < 0)
  113. return;
  114. if (!zeroTierClient) {
  115. std::string authToken;
  116. if (!ZeroTier::Utils::readFile(ZeroTier::Node::LocalClient::authTokenDefaultUserPath().c_str(),authToken)) {
  117. #ifdef __APPLE__
  118. if (QFile::exists("/Library/Application Support/ZeroTier/One/zerotier-one")) {
  119. // Authorize user by copying auth token into local home directory
  120. 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);
  121. std::string homePath(QDir::homePath().toStdString());
  122. QString zt1Caches(QDir::homePath() + "/Library/Caches/ZeroTier/One");
  123. QDir::root().mkpath(zt1Caches);
  124. std::string tmpPath((zt1Caches + "/auth.sh").toStdString());
  125. FILE *scr = fopen(tmpPath.c_str(),"w");
  126. if (!scr) {
  127. 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);
  128. QApplication::exit(1);
  129. return;
  130. }
  131. fprintf(scr,"#!/bin/bash\n");
  132. fprintf(scr,"export PATH=\"/bin:/usr/bin:/sbin:/usr/sbin\"\n");
  133. fprintf(scr,"if [ -f '/Library/Application Support/ZeroTier/One/authtoken.secret' ]; then\n");
  134. fprintf(scr," mkdir -p '%s/Library/Application Support/ZeroTier/One'\n",homePath.c_str());
  135. fprintf(scr," chown %d '%s/Library/Application Support/ZeroTier'\n",(int)getuid(),homePath.c_str());
  136. fprintf(scr," chgrp %d '%s/Library/Application Support/ZeroTier'\n",(int)getgid(),homePath.c_str());
  137. fprintf(scr," chmod 0700 '%s/Library/Application Support/ZeroTier'\n",homePath.c_str());
  138. fprintf(scr," chown %d '%s/Library/Application Support/ZeroTier/One'\n",(int)getuid(),homePath.c_str());
  139. fprintf(scr," chgrp %d '%s/Library/Application Support/ZeroTier/One'\n",(int)getgid(),homePath.c_str());
  140. fprintf(scr," chmod 0700 '%s/Library/Application Support/ZeroTier/One'\n",homePath.c_str());
  141. fprintf(scr," cp -f '/Library/Application Support/ZeroTier/One/authtoken.secret' '%s/Library/Application Support/ZeroTier/One/authtoken.secret'\n",homePath.c_str());
  142. fprintf(scr," chown %d '%s/Library/Application Support/ZeroTier/One/authtoken.secret'\n",(int)getuid(),homePath.c_str());
  143. fprintf(scr," chgrp %d '%s/Library/Application Support/ZeroTier/One/authtoken.secret'\n",(int)getgid(),homePath.c_str());
  144. fprintf(scr," chmod 0600 '%s/Library/Application Support/ZeroTier/One/authtoken.secret'\n",homePath.c_str());
  145. fprintf(scr,"fi\n");
  146. fprintf(scr,"exit 0\n");
  147. fclose(scr);
  148. chmod(tmpPath.c_str(),0755);
  149. macExecutePrivilegedShellCommand((std::string("'")+tmpPath+"' >>/dev/null 2>&1").c_str());
  150. unlink(tmpPath.c_str());
  151. }
  152. #endif
  153. if (!ZeroTier::Utils::readFile(ZeroTier::Node::LocalClient::authTokenDefaultUserPath().c_str(),authToken)) {
  154. QMessageBox::critical(this,"Cannot Authorize","Unable to authorize this user to administrate ZeroTier One. (Did you enter your password correctly?)",QMessageBox::Ok,QMessageBox::NoButton);
  155. QApplication::exit(1);
  156. return;
  157. }
  158. }
  159. zeroTierClient = new ZeroTier::Node::LocalClient(authToken.c_str(),0,&handleZTMessage,this);
  160. }
  161. // TODO: do something more user-friendly here... or maybe try to restart
  162. // the service?
  163. if (++this->cyclesSinceResponseFromService == 4)
  164. QMessageBox::critical(this,"No Response from Service","The ZeroTier One service does not appear to be running.",QMessageBox::Ok,QMessageBox::NoButton);
  165. zeroTierClient->send("info");
  166. zeroTierClient->send("listnetworks");
  167. zeroTierClient->send("listpeers");
  168. }
  169. void MainWindow::customEvent(QEvent *event)
  170. {
  171. ZTMessageEvent *m = (ZTMessageEvent *)event; // only one custom event type so far
  172. if (m->ztMessage.size() == 0)
  173. return;
  174. std::vector<std::string> hdr(ZeroTier::Node::LocalClient::splitLine(m->ztMessage[0]));
  175. if (hdr.size() < 2)
  176. return;
  177. if (hdr[0] != "200")
  178. return;
  179. this->cyclesSinceResponseFromService = 0;
  180. if (hdr[1] == "info") {
  181. if (hdr.size() >= 3)
  182. this->myAddress = hdr[2].c_str();
  183. if (hdr.size() >= 4)
  184. this->myStatus = hdr[3].c_str();
  185. if (hdr.size() >= 5)
  186. this->myVersion = hdr[4].c_str();
  187. } else if (hdr[1] == "listnetworks") {
  188. std::map< std::string,std::vector<std::string> > newNetworks;
  189. for(unsigned long i=1;i<m->ztMessage.size();++i) {
  190. std::vector<std::string> l(ZeroTier::Node::LocalClient::splitLine(m->ztMessage[i]));
  191. // 200 listnetworks <nwid> <name> <status> <config age> <type> <dev> <ips>
  192. if ((l.size() == 9)&&(l[2].length() == 16))
  193. newNetworks[l[2]] = l;
  194. }
  195. if (newNetworks != networks) {
  196. networks = newNetworks;
  197. for (bool removed=true;removed;) {
  198. removed = false;
  199. for(int r=0;r<ui->networkListWidget->count();++r) {
  200. NetworkWidget *nw = (NetworkWidget *)ui->networkListWidget->itemWidget(ui->networkListWidget->item(r));
  201. if (!networks.count(nw->networkId())) {
  202. ui->networkListWidget->setVisible(false); // HACK to prevent an occasional crash here, discovered through hours of shotgun debugging... :P
  203. delete ui->networkListWidget->takeItem(r);
  204. removed = true;
  205. break;
  206. }
  207. }
  208. }
  209. ui->networkListWidget->setVisible(true);
  210. std::set<std::string> alreadyDisplayed;
  211. for(int r=0;r<ui->networkListWidget->count();++r) {
  212. NetworkWidget *nw = (NetworkWidget *)ui->networkListWidget->itemWidget(ui->networkListWidget->item(r));
  213. if (networks.count(nw->networkId()) > 0) {
  214. alreadyDisplayed.insert(nw->networkId());
  215. std::vector<std::string> &l = networks[nw->networkId()];
  216. nw->setNetworkName(l[3]);
  217. nw->setStatus(l[4],l[5]);
  218. nw->setNetworkType(l[6]);
  219. nw->setNetworkDeviceName(l[7]);
  220. nw->setIps(l[8]);
  221. }
  222. }
  223. for(std::map< std::string,std::vector<std::string> >::iterator nwdata(networks.begin());nwdata!=networks.end();++nwdata) {
  224. if (alreadyDisplayed.count(nwdata->first) == 0) {
  225. std::vector<std::string> &l = nwdata->second;
  226. NetworkWidget *nw = new NetworkWidget((QWidget *)0,nwdata->first);
  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. QListWidgetItem *item = new QListWidgetItem();
  233. item->setSizeHint(nw->sizeHint());
  234. ui->networkListWidget->addItem(item);
  235. ui->networkListWidget->setItemWidget(item,nw);
  236. }
  237. }
  238. }
  239. } else if (hdr[1] == "listpeers") {
  240. this->numPeers = 0;
  241. for(unsigned long i=1;i<m->ztMessage.size();++i) {
  242. std::vector<std::string> l(ZeroTier::Node::LocalClient::splitLine(m->ztMessage[i]));
  243. if ((l.size() >= 5)&&((l[3] != "-")||(l[4] != "-")))
  244. ++this->numPeers; // number of direct peers online -- check for active IPv4 and/or IPv6 address
  245. }
  246. }
  247. if (!ui->networkListWidget->count()) {
  248. ui->noNetworksLabel->setText("You Have Not Joined Any Networks");
  249. ui->noNetworksLabel->setVisible(true);
  250. } else ui->noNetworksLabel->setVisible(false);
  251. if (this->myAddress.size())
  252. ui->addressButton->setText(this->myAddress);
  253. else ui->addressButton->setText(" ");
  254. QString st(this->myStatus);
  255. st += ", v";
  256. st += this->myVersion;
  257. st += ", ";
  258. st += QString::number(this->numPeers);
  259. st += " direct links to peers";
  260. ui->statusLabel->setText(st);
  261. if (this->myStatus == "ONLINE") {
  262. if (!this->isEnabled())
  263. this->setEnabled(true);
  264. } else {
  265. if (this->isEnabled())
  266. this->setEnabled(false);
  267. }
  268. }
  269. void MainWindow::on_joinNetworkButton_clicked()
  270. {
  271. QString toJoin(ui->networkIdLineEdit->text());
  272. ui->networkIdLineEdit->setText(QString());
  273. if (!zeroTierClient) // sanity check
  274. return;
  275. if (toJoin.size() != 16) {
  276. 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);
  277. return;
  278. }
  279. zeroTierClient->send((QString("join ") + toJoin).toStdString());
  280. }
  281. void MainWindow::on_actionAbout_triggered()
  282. {
  283. AboutWindow *about = new AboutWindow(this);
  284. about->show();
  285. }
  286. void MainWindow::on_networkIdLineEdit_textChanged(const QString &text)
  287. {
  288. QString newText;
  289. for(QString::const_iterator i(text.begin());i!=text.end();++i) {
  290. switch(i->toLatin1()) {
  291. case '0': newText.append('0'); break;
  292. case '1': newText.append('1'); break;
  293. case '2': newText.append('2'); break;
  294. case '3': newText.append('3'); break;
  295. case '4': newText.append('4'); break;
  296. case '5': newText.append('5'); break;
  297. case '6': newText.append('6'); break;
  298. case '7': newText.append('7'); break;
  299. case '8': newText.append('8'); break;
  300. case '9': newText.append('9'); break;
  301. case 'a': newText.append('a'); break;
  302. case 'b': newText.append('b'); break;
  303. case 'c': newText.append('c'); break;
  304. case 'd': newText.append('d'); break;
  305. case 'e': newText.append('e'); break;
  306. case 'f': newText.append('f'); break;
  307. case 'A': newText.append('a'); break;
  308. case 'B': newText.append('b'); break;
  309. case 'C': newText.append('c'); break;
  310. case 'D': newText.append('d'); break;
  311. case 'E': newText.append('e'); break;
  312. case 'F': newText.append('f'); break;
  313. default: break;
  314. }
  315. }
  316. if (newText.size() > 16)
  317. newText.truncate(16);
  318. ui->networkIdLineEdit->setText(newText);
  319. }
  320. void MainWindow::on_addressButton_clicked()
  321. {
  322. QApplication::clipboard()->setText(this->myAddress);
  323. }