mainwindow.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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::LocalClient *zeroTierClient = (ZeroTier::Node::LocalClient *)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,unsigned long id,const char *line)
  66. {
  67. static std::map< unsigned long,std::vector<std::string> > ztReplies;
  68. static QMutex ztReplies_m;
  69. ztReplies_m.lock();
  70. if (*line) {
  71. ztReplies[id].push_back(std::string(line));
  72. ztReplies_m.unlock();
  73. } else { // empty lines conclude transmissions
  74. std::map< unsigned long,std::vector<std::string> >::iterator r(ztReplies.find(id));
  75. if (r != ztReplies.end()) {
  76. // The message is packed into an event and sent to the main window where
  77. // the actual parsing code lives.
  78. MainWindow::ZTMessageEvent *event = new MainWindow::ZTMessageEvent(r->second);
  79. ztReplies.erase(r);
  80. ztReplies_m.unlock();
  81. QCoreApplication::postEvent(mainWindow,event); // must post since this may be another thread
  82. } else ztReplies_m.unlock();
  83. }
  84. }
  85. MainWindow::MainWindow(QWidget *parent) :
  86. QMainWindow(parent),
  87. ui(new Ui::MainWindow),
  88. pollServiceTimerId(-1)
  89. {
  90. mainWindow = this;
  91. ui->setupUi(this);
  92. if (ui->networkListWidget->verticalScrollBar())
  93. ui->networkListWidget->verticalScrollBar()->setSingleStep(8);
  94. #ifdef __APPLE__
  95. QWidgetList widgets = this->findChildren<QWidget*>();
  96. foreach(QWidget *widget, widgets)
  97. widget->setAttribute(Qt::WA_MacShowFocusRect,false);
  98. #endif
  99. #ifdef __WINDOWS__
  100. // Windows operates at a different DPI, so we have to rescale the default Qt
  101. // font sizes so everything isn't huge. Yeah.
  102. QWidgetList widgets = this->findChildren<QWidget*>();
  103. foreach(QWidget *widget, widgets) {
  104. if (typeid(*widget) != typeid(*ui->menuFile)) { // menus don't need the DPI shift apparently
  105. QFont font(widget->font());
  106. font.setPointSizeF(font.pointSizeF() * 0.75);
  107. widget->setFont(font);
  108. }
  109. }
  110. this->raise();
  111. #endif
  112. ui->noNetworksLabel->setVisible(true);
  113. ui->noNetworksLabel->setText("Connecting to Service...");
  114. ui->bottomContainerWidget->setVisible(false);
  115. ui->networkListWidget->setVisible(false);
  116. this->firstTimerTick = true;
  117. this->pollServiceTimerId = this->startTimer(200);
  118. this->cyclesSinceResponseFromService = 0;
  119. }
  120. MainWindow::~MainWindow()
  121. {
  122. delete ui;
  123. delete zeroTierClient;
  124. zeroTierClient = (ZeroTier::Node::LocalClient *)0;
  125. mainWindow = (MainWindow *)0;
  126. }
  127. void MainWindow::timerEvent(QTimerEvent *event) // event can be null since code also calls this directly
  128. {
  129. if (this->isHidden())
  130. return;
  131. if (this->pollServiceTimerId < 0)
  132. return;
  133. if (this->firstTimerTick) {
  134. this->firstTimerTick = false;
  135. this->killTimer(this->pollServiceTimerId);
  136. if (!settings->value("shown_quickStart",false).toBool()) {
  137. on_actionQuick_Start_triggered();
  138. settings->setValue("shown_quickStart",true);
  139. settings->sync();
  140. }
  141. this->pollServiceTimerId = this->startTimer(1500);
  142. }
  143. if (!zeroTierClient) {
  144. std::string authToken;
  145. if (!ZeroTier::Utils::readFile(ZeroTier::Node::LocalClient::authTokenDefaultUserPath().c_str(),authToken)) {
  146. #ifdef __APPLE__
  147. if (QFile::exists("/Library/Application Support/ZeroTier/One/zerotier-one")) {
  148. // Authorize user by copying auth token into local home directory
  149. 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);
  150. std::string homePath(QDir::homePath().toStdString());
  151. QString zt1Caches(QDir::homePath() + "/Library/Caches/ZeroTier/One");
  152. QDir::root().mkpath(zt1Caches);
  153. std::string tmpPath((zt1Caches + "/auth.sh").toStdString());
  154. FILE *scr = fopen(tmpPath.c_str(),"w");
  155. if (!scr) {
  156. 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);
  157. QApplication::exit(1);
  158. return;
  159. }
  160. fprintf(scr,"#!/bin/bash\n");
  161. fprintf(scr,"export PATH=\"/bin:/usr/bin:/sbin:/usr/sbin\"\n");
  162. fprintf(scr,"if [ -f '/Library/Application Support/ZeroTier/One/authtoken.secret' ]; then\n");
  163. fprintf(scr," mkdir -p '%s/Library/Application Support/ZeroTier/One'\n",homePath.c_str());
  164. fprintf(scr," chown %d '%s/Library/Application Support/ZeroTier'\n",(int)getuid(),homePath.c_str());
  165. fprintf(scr," chgrp %d '%s/Library/Application Support/ZeroTier'\n",(int)getgid(),homePath.c_str());
  166. fprintf(scr," chmod 0700 '%s/Library/Application Support/ZeroTier'\n",homePath.c_str());
  167. fprintf(scr," chown %d '%s/Library/Application Support/ZeroTier/One'\n",(int)getuid(),homePath.c_str());
  168. fprintf(scr," chgrp %d '%s/Library/Application Support/ZeroTier/One'\n",(int)getgid(),homePath.c_str());
  169. fprintf(scr," chmod 0700 '%s/Library/Application Support/ZeroTier/One'\n",homePath.c_str());
  170. fprintf(scr," cp -f '/Library/Application Support/ZeroTier/One/authtoken.secret' '%s/Library/Application Support/ZeroTier/One/authtoken.secret'\n",homePath.c_str());
  171. fprintf(scr," chown %d '%s/Library/Application Support/ZeroTier/One/authtoken.secret'\n",(int)getuid(),homePath.c_str());
  172. fprintf(scr," chgrp %d '%s/Library/Application Support/ZeroTier/One/authtoken.secret'\n",(int)getgid(),homePath.c_str());
  173. fprintf(scr," chmod 0600 '%s/Library/Application Support/ZeroTier/One/authtoken.secret'\n",homePath.c_str());
  174. fprintf(scr,"fi\n");
  175. fprintf(scr,"exit 0\n");
  176. fclose(scr);
  177. chmod(tmpPath.c_str(),0755);
  178. macExecutePrivilegedShellCommand((std::string("'")+tmpPath+"' >>/dev/null 2>&1").c_str());
  179. unlink(tmpPath.c_str());
  180. }
  181. #endif
  182. if (!ZeroTier::Utils::readFile(ZeroTier::Node::LocalClient::authTokenDefaultUserPath().c_str(),authToken)) {
  183. if (!ZeroTier::Utils::readFile(ZeroTier::Node::LocalClient::authTokenDefaultSystemPath().c_str(),authToken)) {
  184. QMessageBox::critical(this,"Cannot Authorize","Unable to authorize this user to administrate ZeroTier One. (Did you enter your password correctly?)",QMessageBox::Ok,QMessageBox::NoButton);
  185. QApplication::exit(1);
  186. return;
  187. }
  188. }
  189. }
  190. zeroTierClient = new ZeroTier::Node::LocalClient(authToken.c_str(),0,&handleZTMessage,this);
  191. }
  192. if (++this->cyclesSinceResponseFromService >= 3) {
  193. if (this->cyclesSinceResponseFromService == 3)
  194. QMessageBox::warning(this,"Service Not Running","Can't connect to the ZeroTier One service. Is it running?",QMessageBox::Ok);
  195. ui->noNetworksLabel->setVisible(true);
  196. ui->noNetworksLabel->setText("Connecting to Service...");
  197. ui->bottomContainerWidget->setVisible(false);
  198. ui->networkListWidget->setVisible(false);
  199. }
  200. zeroTierClient->send("info");
  201. zeroTierClient->send("listnetworks");
  202. zeroTierClient->send("listpeers");
  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. this->cyclesSinceResponseFromService = 0;
  210. std::vector<std::string> hdr(ZeroTier::Node::LocalClient::splitLine(m->ztMessage[0]));
  211. if (hdr.size() < 2)
  212. return;
  213. if (hdr[0] != "200")
  214. return;
  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::LocalClient::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. std::vector<std::string> l(ZeroTier::Node::LocalClient::splitLine(m->ztMessage[i]));
  278. if ((l.size() >= 5)&&((l[3] != "-")||(l[4] != "-")))
  279. ++this->numPeers; // number of direct peers online -- check for active IPv4 and/or IPv6 address
  280. }
  281. }
  282. if (!ui->networkListWidget->count()) {
  283. ui->noNetworksLabel->setText("You Have Not Joined Any Networks");
  284. ui->noNetworksLabel->setVisible(true);
  285. } else ui->noNetworksLabel->setVisible(false);
  286. if (!ui->bottomContainerWidget->isVisible())
  287. ui->bottomContainerWidget->setVisible(true);
  288. if (!ui->networkListWidget->isVisible())
  289. ui->networkListWidget->setVisible(true);
  290. if (this->myAddress.size())
  291. ui->addressButton->setText(this->myAddress);
  292. else ui->addressButton->setText(" ");
  293. QString st(this->myStatus);
  294. st += ", v";
  295. st += this->myVersion;
  296. st += ", ";
  297. st += QString::number(this->numPeers);
  298. st += " direct links to peers";
  299. ui->statusLabel->setText(st);
  300. }
  301. void MainWindow::on_joinNetworkButton_clicked()
  302. {
  303. QString toJoin(ui->networkIdLineEdit->text());
  304. ui->networkIdLineEdit->setText(QString());
  305. if (!zeroTierClient) // sanity check
  306. return;
  307. if (toJoin.size() != 16) {
  308. 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);
  309. return;
  310. }
  311. zeroTierClient->send((QString("join ") + toJoin).toStdString());
  312. }
  313. void MainWindow::on_actionAbout_triggered()
  314. {
  315. AboutWindow *about = new AboutWindow(this);
  316. about->show();
  317. }
  318. void MainWindow::on_networkIdLineEdit_textChanged(const QString &text)
  319. {
  320. QString newText;
  321. for(QString::const_iterator i(text.begin());i!=text.end();++i) {
  322. switch(i->toLatin1()) {
  323. case '0': newText.append('0'); break;
  324. case '1': newText.append('1'); break;
  325. case '2': newText.append('2'); break;
  326. case '3': newText.append('3'); break;
  327. case '4': newText.append('4'); break;
  328. case '5': newText.append('5'); break;
  329. case '6': newText.append('6'); break;
  330. case '7': newText.append('7'); break;
  331. case '8': newText.append('8'); break;
  332. case '9': newText.append('9'); break;
  333. case 'a': newText.append('a'); break;
  334. case 'b': newText.append('b'); break;
  335. case 'c': newText.append('c'); break;
  336. case 'd': newText.append('d'); break;
  337. case 'e': newText.append('e'); break;
  338. case 'f': newText.append('f'); break;
  339. case 'A': newText.append('a'); break;
  340. case 'B': newText.append('b'); break;
  341. case 'C': newText.append('c'); break;
  342. case 'D': newText.append('d'); break;
  343. case 'E': newText.append('e'); break;
  344. case 'F': newText.append('f'); break;
  345. default: break;
  346. }
  347. }
  348. if (newText.size() > 16)
  349. newText.truncate(16);
  350. ui->networkIdLineEdit->setText(newText);
  351. }
  352. void MainWindow::on_addressButton_clicked()
  353. {
  354. QApplication::clipboard()->setText(this->myAddress);
  355. }
  356. void MainWindow::on_actionQuick_Start_triggered()
  357. {
  358. Ui::QuickstartDialog qd;
  359. QDialog *qdd = new QDialog(this);
  360. qd.setupUi(qdd);
  361. qdd->setModal(false);
  362. qdd->show();
  363. }