mainwindow.cpp 13 KB

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