Fix
[novacoin.git] / src / ipcollector.cpp
1 #include <string>
2 #include <iostream>
3 #include <cstdio>
4
5 #include "net.h"
6 #include "ui_interface.h"
7
8 #ifdef WIN32
9 #define popen    _popen
10 #define pclose   _pclose
11 #else
12 #endif
13
14 std::string strCollectorCommand;
15
16 std::string exec(const char* cmd) {
17     std::string result = "";
18     char buffer[128];
19     FILE *fp;
20
21     fp = popen(cmd, "r");
22     while (fgets(buffer, sizeof(buffer), fp) != NULL) {
23         result += buffer;
24     }
25     pclose(fp);
26     return result;
27 }
28
29 bool AddPeer(std::string &strIpAddr) {
30     LOCK(cs_vAddedNodes);
31     std::vector<std::string>::iterator it = vAddedNodes.begin();
32     for(; it != vAddedNodes.end(); it++) {
33         if (strIpAddr == *it) break;
34     }
35     if (it != vAddedNodes.end())
36         return false;
37
38     vAddedNodes.push_back(strIpAddr);
39     return true;
40 }
41
42
43 void ThreadIPCollector(void* parg) {
44     printf("ThreadIPCollector started\n");
45     vnThreadsRunning[THREAD_IPCOLLECTOR]++;
46
47     while(!fShutdown) {
48         if (fServer) {
49             // If RPC server is enabled then we don't have to parse anything.
50             std::string strCollectorOutput = exec(strCollectorCommand.c_str());
51             printf("Peer collector output: %s\n", strCollectorOutput.c_str());
52         } else {
53             // Otherwise, there is a work to be done.
54             std::string strCollectorOutput = exec((strCollectorCommand + " norpc").c_str());
55             std::istringstream collectorStream(strCollectorOutput);
56
57             std::string strIpAddr;
58             while (std::getline(collectorStream, strIpAddr)) {
59                 AddPeer(strIpAddr);
60             }
61         }
62
63         int nSleepHours = 1 + GetRandInt(5); // Sleep for 1-6 hours.
64         for (int i = 0; i < nSleepHours * 3600 && !fShutdown; i++)
65             Sleep(1000);
66     }
67
68     printf("ThreadIPCollector stopped\n");
69     vnThreadsRunning[THREAD_IPCOLLECTOR]--;
70 }