mainwindow.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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 "mainwindow.h"
  28. #include "aboutwindow.h"
  29. #include "networkwidget.h"
  30. #include "ui_mainwindow.h"
  31. #include "installdialog.h"
  32. #include <string>
  33. #include <map>
  34. #include <set>
  35. #include <vector>
  36. #include <stdexcept>
  37. #include <utility>
  38. #include <QClipboard>
  39. #include <QMutex>
  40. #include <QCoreApplication>
  41. #include <QDir>
  42. #include <QFile>
  43. #include <QMessageBox>
  44. #include <QDebug>
  45. #include <QProcess>
  46. #include <QStringList>
  47. #include <QVBoxLayout>
  48. #include <QScrollBar>
  49. #include <QEventLoop>
  50. QNetworkAccessManager *nam;
  51. // Globally visible
  52. ZeroTier::Node::LocalClient *zeroTierClient = (ZeroTier::Node::LocalClient *)0;
  53. // Main window instance for app
  54. static MainWindow *mainWindow = (MainWindow *)0;
  55. static void handleZTMessage(void *arg,unsigned long id,const char *line)
  56. {
  57. static std::map< unsigned long,std::vector<std::string> > ztReplies;
  58. static QMutex ztReplies_m;
  59. ztReplies_m.lock();
  60. if (*line) {
  61. ztReplies[id].push_back(std::string(line));
  62. ztReplies_m.unlock();
  63. } else { // empty lines conclude transmissions
  64. std::map< unsigned long,std::vector<std::string> >::iterator r(ztReplies.find(id));
  65. if (r != ztReplies.end()) {
  66. MainWindow::ZTMessageEvent *event = new MainWindow::ZTMessageEvent(r->second);
  67. ztReplies.erase(r);
  68. ztReplies_m.unlock();
  69. QCoreApplication::postEvent(mainWindow,event); // must post since this may be another thread
  70. } else ztReplies_m.unlock();
  71. }
  72. }
  73. MainWindow::MainWindow(QWidget *parent) :
  74. QMainWindow(parent),
  75. ui(new Ui::MainWindow),
  76. pollServiceTimerId(-1)
  77. {
  78. ui->setupUi(this);
  79. if (ui->networkListWidget->verticalScrollBar())
  80. ui->networkListWidget->verticalScrollBar()->setSingleStep(8);
  81. QWidgetList widgets = this->findChildren<QWidget*>();
  82. foreach(QWidget *widget, widgets)
  83. widget->setAttribute(Qt::WA_MacShowFocusRect,false);
  84. mainWindow = this;
  85. this->pollServiceTimerId = this->startTimer(1000);
  86. this->setEnabled(false); // gets enabled when updates are received
  87. this->cyclesSinceResponseFromService = 0;
  88. }
  89. MainWindow::~MainWindow()
  90. {
  91. delete ui;
  92. delete zeroTierClient;
  93. zeroTierClient = (ZeroTier::Node::LocalClient *)0;
  94. mainWindow = (MainWindow *)0;
  95. }
  96. void MainWindow::timerEvent(QTimerEvent *event)
  97. {
  98. event->accept();
  99. if (this->isHidden())
  100. return;
  101. if (pollServiceTimerId < 0)
  102. return;
  103. if (!zeroTierClient) {
  104. std::string authToken;
  105. if (!ZeroTier::Utils::readFile(ZeroTier::Node::LocalClient::authTokenDefaultUserPath().c_str(),authToken)) {
  106. #ifdef __APPLE__
  107. if (QFile::exists("/Library/Application Support/ZeroTier/One/zerotier-one")) {
  108. QMessageBox::information(this,"Authorization Required","You must authenticate to authorize this user to administrate ZeroTier One on this computer.\n\n(This only needs to be done once.)",QMessageBox::Ok,QMessageBox::NoButton);
  109. QString authHelperPath(QCoreApplication::applicationDirPath() + "/../Resources/helpers/mac/ZeroTier One (Authenticate).app/Contents/MacOS/applet");
  110. if (!QFile::exists(authHelperPath)) {
  111. QMessageBox::critical(this,"Unable to Locate Helper","Unable to locate authorization helper, cannot obtain authentication token.",QMessageBox::Ok,QMessageBox::NoButton);
  112. QApplication::exit(1);
  113. return;
  114. }
  115. QProcess::execute(authHelperPath,QStringList());
  116. } else {
  117. doInstallDialog();
  118. return;
  119. }
  120. #endif
  121. if (!ZeroTier::Utils::readFile(ZeroTier::Node::LocalClient::authTokenDefaultUserPath().c_str(),authToken)) {
  122. QMessageBox::critical(this,"Cannot Authorize","Unable to authorize this user to administrate ZeroTier One. (Did you enter your password correctly?)",QMessageBox::Ok,QMessageBox::NoButton);
  123. QApplication::exit(1);
  124. return;
  125. }
  126. }
  127. zeroTierClient = new ZeroTier::Node::LocalClient(authToken.c_str(),0,&handleZTMessage,this);
  128. }
  129. // TODO: do something more user-friendly here... or maybe try to restart
  130. // the service?
  131. if (++this->cyclesSinceResponseFromService == 4)
  132. QMessageBox::critical(this,"No Response from Service","The ZeroTier One service does not appear to be running.",QMessageBox::Ok,QMessageBox::NoButton);
  133. zeroTierClient->send("info");
  134. zeroTierClient->send("listnetworks");
  135. zeroTierClient->send("listpeers");
  136. }
  137. void MainWindow::customEvent(QEvent *event)
  138. {
  139. ZTMessageEvent *m = (ZTMessageEvent *)event; // only one custom event type so far
  140. if (m->ztMessage.size() == 0)
  141. return;
  142. std::vector<std::string> hdr(ZeroTier::Node::LocalClient::splitLine(m->ztMessage[0]));
  143. if (hdr.size() < 2)
  144. return;
  145. if (hdr[0] != "200")
  146. return;
  147. this->cyclesSinceResponseFromService = 0;
  148. if (hdr[1] == "info") {
  149. if (hdr.size() >= 3)
  150. this->myAddress = hdr[2].c_str();
  151. if (hdr.size() >= 4)
  152. this->myStatus = hdr[3].c_str();
  153. if (hdr.size() >= 5)
  154. this->myVersion = hdr[4].c_str();
  155. } else if (hdr[1] == "listnetworks") {
  156. std::map< std::string,std::vector<std::string> > newNetworks;
  157. for(unsigned long i=1;i<m->ztMessage.size();++i) {
  158. std::vector<std::string> l(ZeroTier::Node::LocalClient::splitLine(m->ztMessage[i]));
  159. // 200 listnetworks <nwid> <name> <status> <config age> <type> <dev> <ips>
  160. if ((l.size() == 9)&&(l[2].length() == 16))
  161. newNetworks[l[2]] = l;
  162. }
  163. if (newNetworks != networks) {
  164. networks = newNetworks;
  165. for (bool removed=true;removed;) {
  166. removed = false;
  167. for(int r=0;r<ui->networkListWidget->count();++r) {
  168. NetworkWidget *nw = (NetworkWidget *)ui->networkListWidget->itemWidget(ui->networkListWidget->item(r));
  169. if (!networks.count(nw->networkId())) {
  170. ui->networkListWidget->setVisible(false); // HACK to prevent an occasional crash here, discovered through hours of shotgun debugging... :P
  171. delete ui->networkListWidget->takeItem(r);
  172. removed = true;
  173. break;
  174. }
  175. }
  176. }
  177. ui->networkListWidget->setVisible(true);
  178. std::set<std::string> alreadyDisplayed;
  179. for(int r=0;r<ui->networkListWidget->count();++r) {
  180. NetworkWidget *nw = (NetworkWidget *)ui->networkListWidget->itemWidget(ui->networkListWidget->item(r));
  181. if (networks.count(nw->networkId()) > 0) {
  182. alreadyDisplayed.insert(nw->networkId());
  183. std::vector<std::string> &l = networks[nw->networkId()];
  184. nw->setNetworkName(l[3]);
  185. nw->setStatus(l[4],l[5]);
  186. nw->setNetworkType(l[6]);
  187. nw->setNetworkDeviceName(l[7]);
  188. nw->setIps(l[8]);
  189. }
  190. }
  191. for(std::map< std::string,std::vector<std::string> >::iterator nwdata(networks.begin());nwdata!=networks.end();++nwdata) {
  192. if (alreadyDisplayed.count(nwdata->first) == 0) {
  193. std::vector<std::string> &l = nwdata->second;
  194. NetworkWidget *nw = new NetworkWidget((QWidget *)0,nwdata->first);
  195. nw->setNetworkName(l[3]);
  196. nw->setStatus(l[4],l[5]);
  197. nw->setNetworkType(l[6]);
  198. nw->setNetworkDeviceName(l[7]);
  199. nw->setIps(l[8]);
  200. QListWidgetItem *item = new QListWidgetItem();
  201. item->setSizeHint(nw->sizeHint());
  202. ui->networkListWidget->addItem(item);
  203. ui->networkListWidget->setItemWidget(item,nw);
  204. }
  205. }
  206. }
  207. } else if (hdr[1] == "listpeers") {
  208. this->numPeers = 0;
  209. for(unsigned long i=1;i<m->ztMessage.size();++i) {
  210. std::vector<std::string> l(ZeroTier::Node::LocalClient::splitLine(m->ztMessage[i]));
  211. if ((l.size() >= 5)&&((l[3] != "-")||(l[4] != "-")))
  212. ++this->numPeers; // number of direct peers online -- check for active IPv4 and/or IPv6 address
  213. }
  214. }
  215. ui->noNetworksLabel->setVisible(ui->networkListWidget->count() == 0);
  216. if (this->myAddress.size())
  217. ui->addressButton->setText(this->myAddress);
  218. else ui->addressButton->setText(" ");
  219. QString st(this->myStatus);
  220. st += ", v";
  221. st += this->myVersion;
  222. st += ", ";
  223. st += QString::number(this->numPeers);
  224. st += " direct links to peers";
  225. ui->statusLabel->setText(st);
  226. if (this->myStatus == "ONLINE") {
  227. if (!this->isEnabled())
  228. this->setEnabled(true);
  229. } else {
  230. if (this->isEnabled())
  231. this->setEnabled(false);
  232. }
  233. }
  234. void MainWindow::showEvent(QShowEvent *event)
  235. {
  236. #ifdef __APPLE__
  237. if (!QFile::exists("/Library/Application Support/ZeroTier/One/zerotier-one"))
  238. doInstallDialog();
  239. #endif
  240. }
  241. void MainWindow::on_joinNetworkButton_clicked()
  242. {
  243. QString toJoin(ui->networkIdLineEdit->text());
  244. ui->networkIdLineEdit->setText(QString());
  245. if (!zeroTierClient) // sanity check
  246. return;
  247. if (toJoin.size() != 16) {
  248. 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);
  249. return;
  250. }
  251. zeroTierClient->send((QString("join ") + toJoin).toStdString());
  252. }
  253. void MainWindow::on_actionAbout_triggered()
  254. {
  255. AboutWindow *about = new AboutWindow(this);
  256. about->show();
  257. }
  258. void MainWindow::on_networkIdLineEdit_textChanged(const QString &text)
  259. {
  260. QString newText;
  261. for(QString::const_iterator i(text.begin());i!=text.end();++i) {
  262. switch(i->toLatin1()) {
  263. case '0': newText.append('0'); break;
  264. case '1': newText.append('1'); break;
  265. case '2': newText.append('2'); break;
  266. case '3': newText.append('3'); break;
  267. case '4': newText.append('4'); break;
  268. case '5': newText.append('5'); break;
  269. case '6': newText.append('6'); break;
  270. case '7': newText.append('7'); break;
  271. case '8': newText.append('8'); break;
  272. case '9': newText.append('9'); break;
  273. case 'a': newText.append('a'); break;
  274. case 'b': newText.append('b'); break;
  275. case 'c': newText.append('c'); break;
  276. case 'd': newText.append('d'); break;
  277. case 'e': newText.append('e'); break;
  278. case 'f': newText.append('f'); break;
  279. case 'A': newText.append('a'); break;
  280. case 'B': newText.append('b'); break;
  281. case 'C': newText.append('c'); break;
  282. case 'D': newText.append('d'); break;
  283. case 'E': newText.append('e'); break;
  284. case 'F': newText.append('f'); break;
  285. default: break;
  286. }
  287. }
  288. if (newText.size() > 16)
  289. newText.truncate(16);
  290. ui->networkIdLineEdit->setText(newText);
  291. }
  292. void MainWindow::on_addressButton_clicked()
  293. {
  294. QApplication::clipboard()->setText(this->myAddress);
  295. }
  296. void MainWindow::doInstallDialog()
  297. {
  298. #ifdef __APPLE__
  299. this->setEnabled(false);
  300. if (pollServiceTimerId >= 0) {
  301. this->killTimer(pollServiceTimerId);
  302. pollServiceTimerId = -1;
  303. }
  304. InstallDialog *id = new InstallDialog(this);
  305. id->setModal(true);
  306. id->show();
  307. #endif
  308. }