mainwindow.cpp 11 KB

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