2
0

mainwindow.cpp 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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. if (!zeroTierClient) {
  71. std::string dotAuthFile((QDir::homePath() + QDir::separator() + ".zeroTierOneAuthToken").toStdString());
  72. std::string authToken;
  73. if (!ZeroTier::Utils::readFile(dotAuthFile.c_str(),authToken)) {
  74. #ifdef __APPLE__
  75. // Run the little AppleScript hack that asks for admin credentials and
  76. // then installs the auth token file in the current user's home.
  77. QString authHelperPath(QCoreApplication::applicationDirPath() + "/../Resources/helpers/mac/ZeroTier One (Authenticate).app/Contents/MacOS/applet");
  78. if (!QFile::exists(authHelperPath)) {
  79. // Allow this to also work from the source tree if it's run from there.
  80. // This is for debugging purposes and shouldn't harm the live release
  81. // in any way.
  82. authHelperPath = QCoreApplication::applicationDirPath() + "/../../../../ZeroTierUI/helpers/mac/ZeroTier One (Authenticate).app/Contents/MacOS/applet";
  83. if (!QFile::exists(authHelperPath)) {
  84. QMessageBox::critical(this,"Unable to Locate Helper","Unable to locate authorization helper, cannot obtain authentication token.",QMessageBox::Ok,QMessageBox::NoButton);
  85. QApplication::exit(1);
  86. return;
  87. }
  88. }
  89. QProcess::execute(authHelperPath,QStringList());
  90. #endif
  91. if (!ZeroTier::Utils::readFile(dotAuthFile.c_str(),authToken)) {
  92. 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);
  93. QApplication::exit(1);
  94. return;
  95. }
  96. }
  97. zeroTierClient = new ZeroTier::Node::LocalClient(authToken.c_str(),0,&handleZTMessage,this);
  98. }
  99. // TODO: do something more user-friendly here... or maybe try to restart
  100. // the service?
  101. if (++this->cyclesSinceResponseFromService == 3)
  102. QMessageBox::critical(this,"No Response from Service","The ZeroTier One service does not appear to be running.",QMessageBox::Ok,QMessageBox::NoButton);
  103. zeroTierClient->send("info");
  104. zeroTierClient->send("listnetworks");
  105. zeroTierClient->send("listpeers");
  106. }
  107. void MainWindow::customEvent(QEvent *event)
  108. {
  109. ZTMessageEvent *m = (ZTMessageEvent *)event; // only one custom event type so far
  110. if (m->ztMessage.size() == 0)
  111. return;
  112. std::vector<std::string> hdr(ZeroTier::Node::LocalClient::splitLine(m->ztMessage[0]));
  113. if (hdr.size() < 2)
  114. return;
  115. if (hdr[0] != "200")
  116. return;
  117. this->cyclesSinceResponseFromService = 0;
  118. if (hdr[1] == "info") {
  119. if (hdr.size() >= 3)
  120. this->myAddress = hdr[2].c_str();
  121. if (hdr.size() >= 4)
  122. this->myStatus = hdr[3].c_str();
  123. if (hdr.size() >= 5)
  124. this->myVersion = hdr[4].c_str();
  125. } else if (hdr[1] == "listnetworks") {
  126. std::map< std::string,std::vector<std::string> > newNetworks;
  127. for(unsigned long i=1;i<m->ztMessage.size();++i) {
  128. std::vector<std::string> l(ZeroTier::Node::LocalClient::splitLine(m->ztMessage[i]));
  129. // 200 listnetworks <nwid> <name> <status> <config age> <type> <dev> <ips>
  130. if ((l.size() == 9)&&(l[2].length() == 16))
  131. newNetworks[l[2]] = l;
  132. }
  133. if (newNetworks != networks) {
  134. networks = newNetworks;
  135. for (bool removed=true;removed;) {
  136. removed = false;
  137. for(int r=0;r<ui->networkListWidget->count();++r) {
  138. NetworkWidget *nw = (NetworkWidget *)ui->networkListWidget->itemWidget(ui->networkListWidget->item(r));
  139. if (!networks.count(nw->networkId())) {
  140. ui->networkListWidget->setVisible(false); // HACK to prevent an occasional crash here, discovered through hours of shotgun debugging... :P
  141. delete ui->networkListWidget->takeItem(r);
  142. removed = true;
  143. break;
  144. }
  145. }
  146. }
  147. ui->networkListWidget->setVisible(true);
  148. std::set<std::string> alreadyDisplayed;
  149. for(int r=0;r<ui->networkListWidget->count();++r) {
  150. NetworkWidget *nw = (NetworkWidget *)ui->networkListWidget->itemWidget(ui->networkListWidget->item(r));
  151. if (networks.count(nw->networkId()) > 0) {
  152. alreadyDisplayed.insert(nw->networkId());
  153. std::vector<std::string> &l = networks[nw->networkId()];
  154. nw->setNetworkName(l[3]);
  155. nw->setStatus(l[4],l[5]);
  156. nw->setNetworkType(l[6]);
  157. nw->setNetworkDeviceName(l[7]);
  158. nw->setIps(l[8]);
  159. }
  160. }
  161. for(std::map< std::string,std::vector<std::string> >::iterator nwdata(networks.begin());nwdata!=networks.end();++nwdata) {
  162. if (alreadyDisplayed.count(nwdata->first) == 0) {
  163. std::vector<std::string> &l = nwdata->second;
  164. NetworkWidget *nw = new NetworkWidget((QWidget *)0,nwdata->first);
  165. nw->setNetworkName(l[3]);
  166. nw->setStatus(l[4],l[5]);
  167. nw->setNetworkType(l[6]);
  168. nw->setNetworkDeviceName(l[7]);
  169. nw->setIps(l[8]);
  170. QListWidgetItem *item = new QListWidgetItem();
  171. item->setSizeHint(nw->sizeHint());
  172. ui->networkListWidget->addItem(item);
  173. ui->networkListWidget->setItemWidget(item,nw);
  174. }
  175. }
  176. }
  177. } else if (hdr[1] == "listpeers") {
  178. this->numPeers = 0;
  179. for(unsigned long i=1;i<m->ztMessage.size();++i) {
  180. std::vector<std::string> l(ZeroTier::Node::LocalClient::splitLine(m->ztMessage[i]));
  181. if ((l.size() >= 5)&&((l[3] != "-")||(l[4] != "-")))
  182. ++this->numPeers; // number of direct peers online -- check for active IPv4 and/or IPv6 address
  183. }
  184. }
  185. if (this->myAddress.size())
  186. ui->addressButton->setText(this->myAddress);
  187. else ui->addressButton->setText(" ");
  188. QString st(this->myStatus);
  189. st += ", v";
  190. st += this->myVersion;
  191. st += ", ";
  192. st += QString::number(this->numPeers);
  193. st += " direct links to peers";
  194. ui->statusLabel->setText(st);
  195. if (this->myStatus == "ONLINE") {
  196. if (!this->isEnabled())
  197. this->setEnabled(true);
  198. } else {
  199. if (this->isEnabled())
  200. this->setEnabled(false);
  201. }
  202. }
  203. void MainWindow::on_joinNetworkButton_clicked()
  204. {
  205. QString toJoin(ui->networkIdLineEdit->text());
  206. ui->networkIdLineEdit->setText(QString());
  207. if (!zeroTierClient) // sanity check
  208. return;
  209. if (toJoin.size() != 16) {
  210. 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);
  211. return;
  212. }
  213. zeroTierClient->send((QString("join ") + toJoin).toStdString());
  214. }
  215. void MainWindow::on_actionAbout_triggered()
  216. {
  217. AboutWindow *about = new AboutWindow(this);
  218. about->show();
  219. }
  220. void MainWindow::on_networkIdLineEdit_textChanged(const QString &text)
  221. {
  222. QString newText;
  223. for(QString::const_iterator i(text.begin());i!=text.end();++i) {
  224. switch(i->toLatin1()) {
  225. case '0': newText.append('0'); break;
  226. case '1': newText.append('1'); break;
  227. case '2': newText.append('2'); break;
  228. case '3': newText.append('3'); break;
  229. case '4': newText.append('4'); break;
  230. case '5': newText.append('5'); break;
  231. case '6': newText.append('6'); break;
  232. case '7': newText.append('7'); break;
  233. case '8': newText.append('8'); break;
  234. case '9': newText.append('9'); break;
  235. case 'a': newText.append('a'); break;
  236. case 'b': newText.append('b'); break;
  237. case 'c': newText.append('c'); break;
  238. case 'd': newText.append('d'); break;
  239. case 'e': newText.append('e'); break;
  240. case 'f': newText.append('f'); break;
  241. case 'A': newText.append('a'); break;
  242. case 'B': newText.append('b'); break;
  243. case 'C': newText.append('c'); break;
  244. case 'D': newText.append('d'); break;
  245. case 'E': newText.append('e'); break;
  246. case 'F': newText.append('f'); break;
  247. default: break;
  248. }
  249. }
  250. if (newText.size() > 16)
  251. newText.truncate(16);
  252. ui->networkIdLineEdit->setText(newText);
  253. }
  254. void MainWindow::on_addressButton_clicked()
  255. {
  256. QApplication::clipboard()->setText(this->myAddress);
  257. }