mainwindow.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2011-2014 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 <QFont>
  46. #include "main.h"
  47. #include "mainwindow.h"
  48. #include "aboutwindow.h"
  49. #include "networkwidget.h"
  50. #include "ui_mainwindow.h"
  51. #include "ui_quickstartdialog.h"
  52. #ifdef __APPLE__
  53. #include <stdio.h>
  54. #include <string.h>
  55. #include <unistd.h>
  56. #include <sys/types.h>
  57. #include <sys/stat.h>
  58. #include "mac_doprivileged.h"
  59. #endif
  60. // Globally visible
  61. ZeroTier::Node::NodeControlClient *zeroTierClient = (ZeroTier::Node::NodeControlClient *)0;
  62. // Main window instance for app
  63. QMainWindow *mainWindow = (MainWindow *)0;
  64. // Handles message from ZeroTier One service
  65. static void handleZTMessage(void *arg,const char *line)
  66. {
  67. static std::vector<std::string> ztReplies;
  68. static QMutex ztReplies_m;
  69. ztReplies_m.lock();
  70. if (line) {
  71. if ((line[0] == '.')&&(line[1] == (char)0)) {
  72. // The message is packed into an event and sent to the main window where
  73. // the actual parsing code lives.
  74. MainWindow::ZTMessageEvent *event = new MainWindow::ZTMessageEvent(ztReplies);
  75. ztReplies.clear();
  76. QCoreApplication::postEvent(mainWindow,event); // must post since this may be another thread
  77. } else if (line[0]) {
  78. ztReplies.push_back(std::string(line));
  79. }
  80. }
  81. ztReplies_m.unlock();
  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. #ifdef __WINDOWS__
  98. // Windows operates at a different DPI, so we have to rescale the default Qt
  99. // font sizes so everything isn't huge. Yeah.
  100. QWidgetList widgets = this->findChildren<QWidget*>();
  101. foreach(QWidget *widget, widgets) {
  102. if (typeid(*widget) != typeid(*ui->menuFile)) { // menus don't need the DPI shift apparently
  103. QFont font(widget->font());
  104. font.setPointSizeF(font.pointSizeF() * 0.75);
  105. widget->setFont(font);
  106. }
  107. }
  108. this->raise();
  109. #endif
  110. ui->noNetworksLabel->setVisible(true);
  111. ui->noNetworksLabel->setText("Connecting to Service...");
  112. ui->bottomContainerWidget->setVisible(false);
  113. ui->networkListWidget->setVisible(false);
  114. this->firstTimerTick = true;
  115. this->pollServiceTimerId = this->startTimer(200);
  116. this->cyclesSinceResponseFromService = 0;
  117. }
  118. MainWindow::~MainWindow()
  119. {
  120. delete ui;
  121. delete zeroTierClient;
  122. zeroTierClient = (ZeroTier::Node::NodeControlClient *)0;
  123. mainWindow = (MainWindow *)0;
  124. }
  125. void MainWindow::timerEvent(QTimerEvent *event) // event can be null since code also calls this directly
  126. {
  127. if (this->isHidden())
  128. return;
  129. if (this->pollServiceTimerId < 0)
  130. return;
  131. // Show quick start dialog on first launch, then reset timer to normal rate
  132. if (this->firstTimerTick) {
  133. this->firstTimerTick = false;
  134. this->killTimer(this->pollServiceTimerId);
  135. if (!settings->value("shown_quickStart",false).toBool()) {
  136. on_actionQuick_Start_triggered();
  137. settings->setValue("shown_quickStart",true);
  138. settings->sync();
  139. }
  140. this->pollServiceTimerId = this->startTimer(2000);
  141. }
  142. if (!zeroTierClient) {
  143. #ifdef __APPLE__
  144. if ((!QFile::exists(ZeroTier::Node::NodeControlClient::authTokenDefaultUserPath()))&&(QFile::exists("/Library/Application Support/ZeroTier/One/zerotier-one"))) {
  145. // Authorize user by copying auth token into local home directory
  146. 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);
  147. std::string homePath(QDir::homePath().toStdString());
  148. QString zt1Caches(QDir::homePath() + "/Library/Caches/ZeroTier/One");
  149. QDir::root().mkpath(zt1Caches);
  150. std::string tmpPath((zt1Caches + "/auth.sh").toStdString());
  151. FILE *scr = fopen(tmpPath.c_str(),"w");
  152. if (!scr) {
  153. 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);
  154. QApplication::exit(1);
  155. return;
  156. }
  157. fprintf(scr,"#!/bin/bash\n");
  158. fprintf(scr,"export PATH=\"/bin:/usr/bin:/sbin:/usr/sbin\"\n");
  159. fprintf(scr,"if [ -f '/Library/Application Support/ZeroTier/One/authtoken.secret' ]; then\n");
  160. fprintf(scr," mkdir -p '%s/Library/Application Support/ZeroTier/One'\n",homePath.c_str());
  161. fprintf(scr," chown %d '%s/Library/Application Support/ZeroTier'\n",(int)getuid(),homePath.c_str());
  162. fprintf(scr," chgrp %d '%s/Library/Application Support/ZeroTier'\n",(int)getgid(),homePath.c_str());
  163. fprintf(scr," chmod 0700 '%s/Library/Application Support/ZeroTier'\n",homePath.c_str());
  164. fprintf(scr," chown %d '%s/Library/Application Support/ZeroTier/One'\n",(int)getuid(),homePath.c_str());
  165. fprintf(scr," chgrp %d '%s/Library/Application Support/ZeroTier/One'\n",(int)getgid(),homePath.c_str());
  166. fprintf(scr," chmod 0700 '%s/Library/Application Support/ZeroTier/One'\n",homePath.c_str());
  167. fprintf(scr," cp -f '/Library/Application Support/ZeroTier/One/authtoken.secret' '%s/Library/Application Support/ZeroTier/One/authtoken.secret'\n",homePath.c_str());
  168. fprintf(scr," chown %d '%s/Library/Application Support/ZeroTier/One/authtoken.secret'\n",(int)getuid(),homePath.c_str());
  169. fprintf(scr," chgrp %d '%s/Library/Application Support/ZeroTier/One/authtoken.secret'\n",(int)getgid(),homePath.c_str());
  170. fprintf(scr," chmod 0600 '%s/Library/Application Support/ZeroTier/One/authtoken.secret'\n",homePath.c_str());
  171. fprintf(scr,"fi\n");
  172. fprintf(scr,"exit 0\n");
  173. fclose(scr);
  174. chmod(tmpPath.c_str(),0755);
  175. macExecutePrivilegedShellCommand((std::string("'")+tmpPath+"' >>/dev/null 2>&1").c_str());
  176. unlink(tmpPath.c_str());
  177. }
  178. #endif // __APPLE__
  179. try {
  180. zeroTierClient = new ZeroTier::Node::NodeControlClient((const char *)0,&handleZTMessage,this);
  181. const char *err = zeroTierClient->error();
  182. if (err) {
  183. delete zeroTierClient;
  184. zeroTierClient = (ZeroTier::Node::NodeControlClient *)0;
  185. }
  186. } catch ( ... ) {
  187. zeroTierClient = (ZeroTier::Node::NodeControlClient *)0;
  188. }
  189. }
  190. if (++this->cyclesSinceResponseFromService >= 3) {
  191. if (this->cyclesSinceResponseFromService == 3)
  192. QMessageBox::warning(this,"Service Not Running","Can't connect to the ZeroTier One service. Is it running?",QMessageBox::Ok);
  193. ui->noNetworksLabel->setVisible(true);
  194. ui->noNetworksLabel->setText("Connecting to Service...");
  195. ui->bottomContainerWidget->setVisible(false);
  196. ui->networkListWidget->setVisible(false);
  197. }
  198. if (zeroTierClient) {
  199. zeroTierClient->send("info");
  200. zeroTierClient->send("listnetworks");
  201. zeroTierClient->send("listpeers");
  202. }
  203. }
  204. void MainWindow::customEvent(QEvent *event)
  205. {
  206. ZTMessageEvent *m = (ZTMessageEvent *)event; // only one custom event type so far
  207. if (m->ztMessage.size() == 0)
  208. return;
  209. std::vector<std::string> hdr(ZeroTier::Node::NodeControlClient::splitLine(m->ztMessage[0]));
  210. if (hdr.size() < 2)
  211. return;
  212. if (hdr[0] != "200")
  213. return;
  214. this->cyclesSinceResponseFromService = 0;
  215. if (hdr[1] == "info") {
  216. if (hdr.size() >= 3)
  217. this->myAddress = hdr[2].c_str();
  218. if (hdr.size() >= 4)
  219. this->myStatus = hdr[3].c_str();
  220. if (hdr.size() >= 5)
  221. this->myVersion = hdr[4].c_str();
  222. } else if (hdr[1] == "listnetworks") {
  223. std::map< std::string,std::vector<std::string> > newNetworks;
  224. for(unsigned long i=1;i<m->ztMessage.size();++i) {
  225. std::vector<std::string> l(ZeroTier::Node::NodeControlClient::splitLine(m->ztMessage[i]));
  226. // 200 listnetworks <nwid> <name> <status> <config age> <type> <dev> <ips>
  227. if ((l.size() == 9)&&(l[2].length() == 16))
  228. newNetworks[l[2]] = l;
  229. }
  230. if (newNetworks != networks) {
  231. networks = newNetworks;
  232. for (bool removed=true;removed;) {
  233. removed = false;
  234. for(int r=0;r<ui->networkListWidget->count();++r) {
  235. NetworkWidget *nw = (NetworkWidget *)ui->networkListWidget->itemWidget(ui->networkListWidget->item(r));
  236. if (!networks.count(nw->networkId())) {
  237. ui->networkListWidget->setVisible(false); // HACK to prevent an occasional crash here, discovered through hours of shotgun debugging... :P
  238. delete ui->networkListWidget->takeItem(r);
  239. removed = true;
  240. break;
  241. }
  242. }
  243. }
  244. ui->networkListWidget->setVisible(true);
  245. std::set<std::string> alreadyDisplayed;
  246. for(int r=0;r<ui->networkListWidget->count();++r) {
  247. NetworkWidget *nw = (NetworkWidget *)ui->networkListWidget->itemWidget(ui->networkListWidget->item(r));
  248. if (networks.count(nw->networkId()) > 0) {
  249. alreadyDisplayed.insert(nw->networkId());
  250. std::vector<std::string> &l = networks[nw->networkId()];
  251. nw->setNetworkName(l[3]);
  252. nw->setStatus(l[4],l[5]);
  253. nw->setNetworkType(l[6]);
  254. nw->setNetworkDeviceName(l[7]);
  255. nw->setIps(l[8]);
  256. }
  257. }
  258. for(std::map< std::string,std::vector<std::string> >::iterator nwdata(networks.begin());nwdata!=networks.end();++nwdata) {
  259. if (alreadyDisplayed.count(nwdata->first) == 0) {
  260. std::vector<std::string> &l = nwdata->second;
  261. NetworkWidget *nw = new NetworkWidget((QWidget *)0,nwdata->first);
  262. nw->setNetworkName(l[3]);
  263. nw->setStatus(l[4],l[5]);
  264. nw->setNetworkType(l[6]);
  265. nw->setNetworkDeviceName(l[7]);
  266. nw->setIps(l[8]);
  267. QListWidgetItem *item = new QListWidgetItem();
  268. item->setSizeHint(nw->sizeHint());
  269. ui->networkListWidget->addItem(item);
  270. ui->networkListWidget->setItemWidget(item,nw);
  271. }
  272. }
  273. }
  274. } else if (hdr[1] == "listpeers") {
  275. this->numPeers = 0;
  276. for(unsigned long i=1;i<m->ztMessage.size();++i)
  277. ++this->numPeers;
  278. } else
  279. return;
  280. if (!ui->networkListWidget->count()) {
  281. ui->noNetworksLabel->setText("You Have Not Joined Any Networks");
  282. ui->noNetworksLabel->setVisible(true);
  283. } else ui->noNetworksLabel->setVisible(false);
  284. if (!ui->bottomContainerWidget->isVisible())
  285. ui->bottomContainerWidget->setVisible(true);
  286. if (!ui->networkListWidget->isVisible())
  287. ui->networkListWidget->setVisible(true);
  288. if (this->myAddress.size())
  289. ui->addressButton->setText(this->myAddress);
  290. else ui->addressButton->setText(" ");
  291. QString st(this->myStatus);
  292. st += ", v";
  293. st += this->myVersion;
  294. st += ", ";
  295. st += QString::number(this->numPeers);
  296. st += " peers";
  297. ui->statusLabel->setText(st);
  298. }
  299. void MainWindow::on_joinNetworkButton_clicked()
  300. {
  301. QString toJoin(ui->networkIdLineEdit->text());
  302. ui->networkIdLineEdit->setText(QString());
  303. if (!zeroTierClient) // sanity check
  304. return;
  305. if (toJoin.size() != 16) {
  306. 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);
  307. return;
  308. }
  309. zeroTierClient->send((QString("join ") + toJoin).toStdString());
  310. }
  311. void MainWindow::on_actionAbout_triggered()
  312. {
  313. AboutWindow *about = new AboutWindow(this);
  314. about->show();
  315. }
  316. void MainWindow::on_networkIdLineEdit_textChanged(const QString &text)
  317. {
  318. QString newText;
  319. for(QString::const_iterator i(text.begin());i!=text.end();++i) {
  320. switch(i->toLatin1()) {
  321. case '0': newText.append('0'); break;
  322. case '1': newText.append('1'); break;
  323. case '2': newText.append('2'); break;
  324. case '3': newText.append('3'); break;
  325. case '4': newText.append('4'); break;
  326. case '5': newText.append('5'); break;
  327. case '6': newText.append('6'); break;
  328. case '7': newText.append('7'); break;
  329. case '8': newText.append('8'); break;
  330. case '9': newText.append('9'); break;
  331. case 'a': newText.append('a'); break;
  332. case 'b': newText.append('b'); break;
  333. case 'c': newText.append('c'); break;
  334. case 'd': newText.append('d'); break;
  335. case 'e': newText.append('e'); break;
  336. case 'f': newText.append('f'); break;
  337. case 'A': newText.append('a'); break;
  338. case 'B': newText.append('b'); break;
  339. case 'C': newText.append('c'); break;
  340. case 'D': newText.append('d'); break;
  341. case 'E': newText.append('e'); break;
  342. case 'F': newText.append('f'); break;
  343. default: break;
  344. }
  345. }
  346. if (newText.size() > 16)
  347. newText.truncate(16);
  348. ui->networkIdLineEdit->setText(newText);
  349. }
  350. void MainWindow::on_addressButton_clicked()
  351. {
  352. QApplication::clipboard()->setText(this->myAddress);
  353. }
  354. void MainWindow::on_actionQuick_Start_triggered()
  355. {
  356. Ui::QuickstartDialog qd;
  357. QDialog *qdd = new QDialog(this);
  358. qd.setupUi(qdd);
  359. qdd->setModal(false);
  360. qdd->show();
  361. }