mainwindow.cpp 11 KB

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