mainwindow.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. }
  194. ui->noNetworksLabel->setVisible(true);
  195. ui->noNetworksLabel->setText("Connecting to Service...");
  196. ui->bottomContainerWidget->setVisible(false);
  197. ui->networkListWidget->setVisible(false);
  198. }
  199. if (zeroTierClient) {
  200. zeroTierClient->send("info");
  201. zeroTierClient->send("listnetworks");
  202. zeroTierClient->send("listpeers");
  203. }
  204. }
  205. void MainWindow::customEvent(QEvent *event)
  206. {
  207. ZTMessageEvent *m = (ZTMessageEvent *)event; // only one custom event type so far
  208. if (m->ztMessage.size() == 0)
  209. return;
  210. std::vector<std::string> hdr(ZeroTier::Node::NodeControlClient::splitLine(m->ztMessage[0]));
  211. if (hdr.size() < 2)
  212. return;
  213. if (hdr[0] != "200")
  214. return;
  215. this->cyclesSinceResponseFromService = 0;
  216. if (hdr[1] == "info") {
  217. if (hdr.size() >= 3)
  218. this->myAddress = hdr[2].c_str();
  219. if (hdr.size() >= 4)
  220. this->myStatus = hdr[3].c_str();
  221. if (hdr.size() >= 5)
  222. this->myVersion = hdr[4].c_str();
  223. } else if (hdr[1] == "listnetworks") {
  224. std::map< std::string,std::vector<std::string> > newNetworks;
  225. for(unsigned long i=1;i<m->ztMessage.size();++i) {
  226. std::vector<std::string> l(ZeroTier::Node::NodeControlClient::splitLine(m->ztMessage[i]));
  227. // 200 listnetworks <nwid> <name> <mac> <status> <config age> <type> <dev> <ips>
  228. if ((l.size() == 10)&&(l[2].length() == 16))
  229. newNetworks[l[2]] = l;
  230. }
  231. if (newNetworks != networks) {
  232. networks = newNetworks;
  233. for (bool removed=true;removed;) {
  234. removed = false;
  235. for(int r=0;r<ui->networkListWidget->count();++r) {
  236. NetworkWidget *nw = (NetworkWidget *)ui->networkListWidget->itemWidget(ui->networkListWidget->item(r));
  237. if (!networks.count(nw->networkId())) {
  238. ui->networkListWidget->setVisible(false); // HACK to prevent an occasional crash here, discovered through hours of shotgun debugging... :P
  239. delete ui->networkListWidget->takeItem(r);
  240. removed = true;
  241. break;
  242. }
  243. }
  244. }
  245. ui->networkListWidget->setVisible(true);
  246. std::set<std::string> alreadyDisplayed;
  247. for(int r=0;r<ui->networkListWidget->count();++r) {
  248. NetworkWidget *nw = (NetworkWidget *)ui->networkListWidget->itemWidget(ui->networkListWidget->item(r));
  249. if (networks.count(nw->networkId()) > 0) {
  250. alreadyDisplayed.insert(nw->networkId());
  251. std::vector<std::string> &l = networks[nw->networkId()];
  252. nw->setNetworkName(l[3]);
  253. nw->setMAC(l[4]);
  254. nw->setStatus(l[5],l[6]);
  255. nw->setNetworkType(l[7]);
  256. nw->setNetworkDeviceName(l[8]);
  257. nw->setIps(l[9]);
  258. }
  259. }
  260. for(std::map< std::string,std::vector<std::string> >::iterator nwdata(networks.begin());nwdata!=networks.end();++nwdata) {
  261. if (alreadyDisplayed.count(nwdata->first) == 0) {
  262. std::vector<std::string> &l = nwdata->second;
  263. NetworkWidget *nw = new NetworkWidget((QWidget *)0,nwdata->first);
  264. nw->setNetworkName(l[3]);
  265. nw->setMAC(l[4]);
  266. nw->setStatus(l[5],l[6]);
  267. nw->setNetworkType(l[7]);
  268. nw->setNetworkDeviceName(l[8]);
  269. nw->setIps(l[9]);
  270. QListWidgetItem *item = new QListWidgetItem();
  271. item->setSizeHint(nw->sizeHint());
  272. ui->networkListWidget->addItem(item);
  273. ui->networkListWidget->setItemWidget(item,nw);
  274. }
  275. }
  276. }
  277. } else if (hdr[1] == "listpeers") {
  278. this->numPeers = 0;
  279. for(unsigned long i=1;i<m->ztMessage.size();++i)
  280. ++this->numPeers;
  281. } else
  282. return;
  283. if (!ui->networkListWidget->count()) {
  284. ui->noNetworksLabel->setText("You Have Not Joined Any Networks");
  285. ui->noNetworksLabel->setVisible(true);
  286. } else ui->noNetworksLabel->setVisible(false);
  287. if (!ui->bottomContainerWidget->isVisible())
  288. ui->bottomContainerWidget->setVisible(true);
  289. if (!ui->networkListWidget->isVisible())
  290. ui->networkListWidget->setVisible(true);
  291. if (this->myAddress.size())
  292. ui->addressButton->setText(this->myAddress);
  293. else ui->addressButton->setText(" ");
  294. QString st(this->myStatus);
  295. st += ", v";
  296. st += this->myVersion;
  297. st += ", ";
  298. st += QString::number(this->numPeers);
  299. st += " peers";
  300. ui->statusLabel->setText(st);
  301. }
  302. void MainWindow::on_joinNetworkButton_clicked()
  303. {
  304. QString toJoin(ui->networkIdLineEdit->text());
  305. ui->networkIdLineEdit->setText(QString());
  306. if (!zeroTierClient) // sanity check
  307. return;
  308. if (toJoin.size() != 16) {
  309. 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);
  310. return;
  311. }
  312. zeroTierClient->send((QString("join ") + toJoin).toStdString());
  313. }
  314. void MainWindow::on_actionAbout_triggered()
  315. {
  316. AboutWindow *about = new AboutWindow(this);
  317. about->show();
  318. }
  319. void MainWindow::on_networkIdLineEdit_textChanged(const QString &text)
  320. {
  321. QString newText;
  322. for(QString::const_iterator i(text.begin());i!=text.end();++i) {
  323. switch(i->toLatin1()) {
  324. case '0': newText.append('0'); break;
  325. case '1': newText.append('1'); break;
  326. case '2': newText.append('2'); break;
  327. case '3': newText.append('3'); break;
  328. case '4': newText.append('4'); break;
  329. case '5': newText.append('5'); break;
  330. case '6': newText.append('6'); break;
  331. case '7': newText.append('7'); break;
  332. case '8': newText.append('8'); break;
  333. case '9': newText.append('9'); break;
  334. case 'a': newText.append('a'); break;
  335. case 'b': newText.append('b'); break;
  336. case 'c': newText.append('c'); break;
  337. case 'd': newText.append('d'); break;
  338. case 'e': newText.append('e'); break;
  339. case 'f': newText.append('f'); break;
  340. case 'A': newText.append('a'); break;
  341. case 'B': newText.append('b'); break;
  342. case 'C': newText.append('c'); break;
  343. case 'D': newText.append('d'); break;
  344. case 'E': newText.append('e'); break;
  345. case 'F': newText.append('f'); break;
  346. default: break;
  347. }
  348. }
  349. if (newText.size() > 16)
  350. newText.truncate(16);
  351. ui->networkIdLineEdit->setText(newText);
  352. }
  353. void MainWindow::on_addressButton_clicked()
  354. {
  355. QApplication::clipboard()->setText(this->myAddress);
  356. }
  357. void MainWindow::on_actionQuick_Start_triggered()
  358. {
  359. Ui::QuickstartDialog qd;
  360. QDialog *qdd = new QDialog(this);
  361. qd.setupUi(qdd);
  362. qdd->setModal(false);
  363. qdd->show();
  364. }