mainwindow.cpp 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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. // Globally visible
  24. ZeroTier::Node::LocalClient *zeroTierClient = (ZeroTier::Node::LocalClient *)0;
  25. // Main window instance for app
  26. static MainWindow *mainWindow = (MainWindow *)0;
  27. static void handleZTMessage(void *arg,unsigned long id,const char *line)
  28. {
  29. static std::map< unsigned long,std::vector<std::string> > ztReplies;
  30. static QMutex ztReplies_m;
  31. ztReplies_m.lock();
  32. if (*line) {
  33. ztReplies[id].push_back(std::string(line));
  34. ztReplies_m.unlock();
  35. } else { // empty lines conclude transmissions
  36. std::map< unsigned long,std::vector<std::string> >::iterator r(ztReplies.find(id));
  37. if (r != ztReplies.end()) {
  38. MainWindow::ZTMessageEvent *event = new MainWindow::ZTMessageEvent(r->second);
  39. ztReplies.erase(r);
  40. ztReplies_m.unlock();
  41. QCoreApplication::postEvent(mainWindow,event); // must post since this may be another thread
  42. } else ztReplies_m.unlock();
  43. }
  44. }
  45. MainWindow::MainWindow(QWidget *parent) :
  46. QMainWindow(parent),
  47. ui(new Ui::MainWindow)
  48. {
  49. ui->setupUi(this);
  50. this->startTimer(1000); // poll service every second
  51. this->setEnabled(false); // gets enabled when updates are received
  52. mainWindow = this;
  53. this->cyclesSinceResponseFromService = 0;
  54. if (ui->networkListWidget->verticalScrollBar())
  55. ui->networkListWidget->verticalScrollBar()->setSingleStep(8);
  56. QWidgetList widgets = this->findChildren<QWidget*>();
  57. foreach(QWidget* widget, widgets)
  58. widget->setAttribute(Qt::WA_MacShowFocusRect,false);
  59. }
  60. MainWindow::~MainWindow()
  61. {
  62. delete ui;
  63. delete zeroTierClient;
  64. zeroTierClient = (ZeroTier::Node::LocalClient *)0;
  65. mainWindow = (MainWindow *)0;
  66. }
  67. void MainWindow::timerEvent(QTimerEvent *event)
  68. {
  69. event->accept();
  70. #ifdef __APPLE__
  71. #else
  72. #endif
  73. if (!zeroTierClient) {
  74. std::string dotAuthFile((QDir::homePath() + QDir::separator() + ".zeroTierOneAuthToken").toStdString());
  75. std::string authToken;
  76. if (!ZeroTier::Utils::readFile(dotAuthFile.c_str(),authToken)) {
  77. #ifdef __APPLE__
  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. #endif
  94. if (!ZeroTier::Utils::readFile(dotAuthFile.c_str(),authToken)) {
  95. 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);
  96. QApplication::exit(1);
  97. return;
  98. }
  99. }
  100. zeroTierClient = new ZeroTier::Node::LocalClient(authToken.c_str(),0,&handleZTMessage,this);
  101. }
  102. // TODO: do something more user-friendly here... or maybe try to restart
  103. // the service?
  104. if (++this->cyclesSinceResponseFromService == 3)
  105. QMessageBox::critical(this,"No Response from Service","The ZeroTier One service does not appear to be running.",QMessageBox::Ok,QMessageBox::NoButton);
  106. zeroTierClient->send("info");
  107. zeroTierClient->send("listnetworks");
  108. zeroTierClient->send("listpeers");
  109. }
  110. void MainWindow::customEvent(QEvent *event)
  111. {
  112. ZTMessageEvent *m = (ZTMessageEvent *)event; // only one custom event type so far
  113. if (m->ztMessage.size() == 0)
  114. return;
  115. std::vector<std::string> hdr(ZeroTier::Node::LocalClient::splitLine(m->ztMessage[0]));
  116. if (hdr.size() < 2)
  117. return;
  118. if (hdr[0] != "200")
  119. return;
  120. this->cyclesSinceResponseFromService = 0;
  121. if (hdr[1] == "info") {
  122. if (hdr.size() >= 3)
  123. this->myAddress = hdr[2].c_str();
  124. if (hdr.size() >= 4)
  125. this->myStatus = hdr[3].c_str();
  126. if (hdr.size() >= 5)
  127. this->myVersion = hdr[4].c_str();
  128. } else if (hdr[1] == "listnetworks") {
  129. std::map< std::string,std::vector<std::string> > newNetworks;
  130. for(unsigned long i=1;i<m->ztMessage.size();++i) {
  131. std::vector<std::string> l(ZeroTier::Node::LocalClient::splitLine(m->ztMessage[i]));
  132. // 200 listnetworks <nwid> <name> <status> <config age> <type> <dev> <ips>
  133. if ((l.size() == 9)&&(l[2].length() == 16))
  134. newNetworks[l[2]] = l;
  135. }
  136. if (newNetworks != networks) {
  137. networks = newNetworks;
  138. for (bool removed=true;removed;) {
  139. removed = false;
  140. for(int r=0;r<ui->networkListWidget->count();++r) {
  141. NetworkWidget *nw = (NetworkWidget *)ui->networkListWidget->itemWidget(ui->networkListWidget->item(r));
  142. if (!networks.count(nw->networkId())) {
  143. ui->networkListWidget->setVisible(false); // HACK to prevent an occasional crash here, discovered through hours of shotgun debugging... :P
  144. delete ui->networkListWidget->takeItem(r);
  145. removed = true;
  146. break;
  147. }
  148. }
  149. }
  150. ui->networkListWidget->setVisible(true);
  151. std::set<std::string> alreadyDisplayed;
  152. for(int r=0;r<ui->networkListWidget->count();++r) {
  153. NetworkWidget *nw = (NetworkWidget *)ui->networkListWidget->itemWidget(ui->networkListWidget->item(r));
  154. if (networks.count(nw->networkId()) > 0) {
  155. alreadyDisplayed.insert(nw->networkId());
  156. std::vector<std::string> &l = networks[nw->networkId()];
  157. nw->setNetworkName(l[3]);
  158. nw->setStatus(l[4],l[5]);
  159. nw->setNetworkType(l[6]);
  160. nw->setNetworkDeviceName(l[7]);
  161. nw->setIps(l[8]);
  162. }
  163. }
  164. for(std::map< std::string,std::vector<std::string> >::iterator nwdata(networks.begin());nwdata!=networks.end();++nwdata) {
  165. if (alreadyDisplayed.count(nwdata->first) == 0) {
  166. std::vector<std::string> &l = nwdata->second;
  167. NetworkWidget *nw = new NetworkWidget((QWidget *)0,nwdata->first);
  168. nw->setNetworkName(l[3]);
  169. nw->setStatus(l[4],l[5]);
  170. nw->setNetworkType(l[6]);
  171. nw->setNetworkDeviceName(l[7]);
  172. nw->setIps(l[8]);
  173. QListWidgetItem *item = new QListWidgetItem();
  174. item->setSizeHint(nw->sizeHint());
  175. ui->networkListWidget->addItem(item);
  176. ui->networkListWidget->setItemWidget(item,nw);
  177. }
  178. }
  179. }
  180. } else if (hdr[1] == "listpeers") {
  181. this->numPeers = 0;
  182. for(unsigned long i=1;i<m->ztMessage.size();++i) {
  183. std::vector<std::string> l(ZeroTier::Node::LocalClient::splitLine(m->ztMessage[i]));
  184. if ((l.size() >= 5)&&((l[3] != "-")||(l[4] != "-")))
  185. ++this->numPeers; // number of direct peers online -- check for active IPv4 and/or IPv6 address
  186. }
  187. }
  188. if (this->myAddress.size())
  189. ui->addressButton->setText(this->myAddress);
  190. else ui->addressButton->setText(" ");
  191. QString st(this->myStatus);
  192. st += ", v";
  193. st += this->myVersion;
  194. st += ", ";
  195. st += QString::number(this->numPeers);
  196. st += " direct links to peers";
  197. ui->statusLabel->setText(st);
  198. if (this->myStatus == "ONLINE") {
  199. if (!this->isEnabled())
  200. this->setEnabled(true);
  201. } else {
  202. if (this->isEnabled())
  203. this->setEnabled(false);
  204. }
  205. }
  206. void MainWindow::on_joinNetworkButton_clicked()
  207. {
  208. QString toJoin(ui->networkIdLineEdit->text());
  209. ui->networkIdLineEdit->setText(QString());
  210. if (!zeroTierClient) // sanity check
  211. return;
  212. if (toJoin.size() != 16) {
  213. 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);
  214. return;
  215. }
  216. zeroTierClient->send((QString("join ") + toJoin).toStdString());
  217. }
  218. void MainWindow::on_actionAbout_triggered()
  219. {
  220. AboutWindow *about = new AboutWindow(this);
  221. about->show();
  222. }
  223. void MainWindow::on_networkIdLineEdit_textChanged(const QString &text)
  224. {
  225. QString newText;
  226. for(QString::const_iterator i(text.begin());i!=text.end();++i) {
  227. switch(i->toLatin1()) {
  228. case '0': newText.append('0'); break;
  229. case '1': newText.append('1'); break;
  230. case '2': newText.append('2'); break;
  231. case '3': newText.append('3'); break;
  232. case '4': newText.append('4'); break;
  233. case '5': newText.append('5'); break;
  234. case '6': newText.append('6'); break;
  235. case '7': newText.append('7'); break;
  236. case '8': newText.append('8'); break;
  237. case '9': newText.append('9'); break;
  238. case 'a': newText.append('a'); break;
  239. case 'b': newText.append('b'); break;
  240. case 'c': newText.append('c'); break;
  241. case 'd': newText.append('d'); break;
  242. case 'e': newText.append('e'); break;
  243. case 'f': newText.append('f'); break;
  244. case 'A': newText.append('a'); break;
  245. case 'B': newText.append('b'); break;
  246. case 'C': newText.append('c'); break;
  247. case 'D': newText.append('d'); break;
  248. case 'E': newText.append('e'); break;
  249. case 'F': newText.append('f'); break;
  250. default: break;
  251. }
  252. }
  253. if (newText.size() > 16)
  254. newText.truncate(16);
  255. ui->networkIdLineEdit->setText(newText);
  256. }
  257. void MainWindow::on_addressButton_clicked()
  258. {
  259. QApplication::clipboard()->setText(this->myAddress);
  260. }