main.c 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769
  1. #include "main.h"
  2. #include "client.h"
  3. #include "tox_bootstrap.h"
  4. #include "tox_bootstrap_json.h"
  5. #include "log.h"
  6. #ifdef __MACH__
  7. #include "mach.h"
  8. #endif
  9. static struct Tox_Options tox_options;
  10. Tox *tox;
  11. int client_socket = 0;
  12. TOX_CONNECTION connection_status = TOX_CONNECTION_NONE;
  13. /** CONFIGURATION OPTIONS **/
  14. /* Whether we're a client */
  15. int client_mode = 0;
  16. /* Just send a ping and exit */
  17. int ping_mode = 0;
  18. /* Open a local port and forward it */
  19. int client_local_port_mode = 0;
  20. /* Forward stdin/stdout to remote machine - SSH ProxyCommand mode */
  21. int client_pipe_mode = 0;
  22. /* Remote Tox ID in client mode */
  23. uint8_t *remote_tox_id = NULL;
  24. /* Tox TCP relay port */
  25. long int tcp_relay_port = 0;
  26. /* UDP listen ports */
  27. long int udp_start_port = 0;
  28. long int udp_end_port = 0;
  29. /* Directory with config and tox save */
  30. char config_path[500] = "/etc/tuntox/";
  31. /* Limit hostname and port in server */
  32. int nrules = 0;
  33. char rules_file[500] = "/etc/tuntox/rules";
  34. enum rules_policy_enum rules_policy = NONE;
  35. rule *rules = NULL;
  36. /* Bootstrap json file */
  37. char boot_json[500] = "/etc/tuntox/nodes.json";
  38. /* Ports and hostname for port forwarding */
  39. local_port_forward *local_port_forwards = NULL;
  40. uint32_t last_forward_id;
  41. /* Whether to daemonize/fork after startup */
  42. int daemonize = 0;
  43. /* Path to the pidfile */
  44. char *pidfile = NULL;
  45. /* Username to which we suid() in daemon mode */
  46. char *daemon_username = NULL;
  47. /* Shared secret used for authentication */
  48. int use_shared_secret = 0;
  49. char shared_secret[TOX_MAX_FRIEND_REQUEST_LENGTH];
  50. /* Only let in a whitelisted client */
  51. int server_whitelist_mode = 0;
  52. allowed_toxid *allowed_toxids = NULL;
  53. int load_saved_toxid_in_client_mode = 0;
  54. fd_set master_server_fds;
  55. /* We keep two hash tables: one indexed by sockfd and another by "connection id" */
  56. tunnel *by_id = NULL;
  57. /* Tunnels need to be delete safely, outside FD_ISSET polling */
  58. /* See: tunnel_queue_delete() */
  59. tunnel_list *tunnels_to_delete = NULL;
  60. /* Highest used fd + 1 for select() */
  61. int select_nfds = 4;
  62. /* Generate an unique tunnel ID. To be used in a server. */
  63. uint16_t get_random_tunnel_id()
  64. {
  65. while(1)
  66. {
  67. int key;
  68. uint16_t tunnel_id;
  69. tunnel *tun;
  70. tunnel_id = (uint16_t)rand();
  71. key = tunnel_id;
  72. HASH_FIND_INT(by_id, &key, tun);
  73. if(!tun)
  74. {
  75. return tunnel_id;
  76. }
  77. log_printf(L_WARNING, "[i] Found duplicated tunnel ID %d\n", key);
  78. }
  79. }
  80. /* Comparison function for allowed_toxid objects */
  81. int allowed_toxid_cmp(allowed_toxid *a, allowed_toxid *b)
  82. {
  83. return memcmp(a->toxid, b->toxid, TOX_PUBLIC_KEY_SIZE);
  84. }
  85. /* Match rule r against candidate host, port. Returns 0 for match. */
  86. int rule_match(rule *r, rule *candidate)
  87. {
  88. bool host_match = !strcmp(r->host, "*") || !strcmp(r->host, candidate->host);
  89. bool port_match = r->port == 0 || r->port == candidate->port;
  90. return port_match && host_match ? 0 : -1;
  91. }
  92. /* When a file descriptor has been added to or removed from select() fdset,
  93. * we need to update select_nfds. */
  94. void update_select_nfds(int fd)
  95. {
  96. int new_select_nfds = 0;
  97. if(fd + 1 > select_nfds)
  98. {
  99. select_nfds = fd + 1;
  100. }
  101. for(int i = 0; i < select_nfds; i++)
  102. {
  103. if(FD_ISSET(i, &master_server_fds))
  104. {
  105. if(i + 1 > new_select_nfds)
  106. {
  107. new_select_nfds = i + 1;
  108. }
  109. }
  110. }
  111. select_nfds = new_select_nfds;
  112. }
  113. /* Constructor. Returns NULL on failure. */
  114. tunnel *tunnel_create(int sockfd, int connid, uint32_t friendnumber)
  115. {
  116. tunnel *t = NULL;
  117. t = calloc(1, sizeof(tunnel));
  118. if(!t)
  119. {
  120. return NULL;
  121. }
  122. t->sockfd = sockfd;
  123. t->connid = connid;
  124. t->friendnumber = friendnumber;
  125. log_printf(L_INFO, "Created a new tunnel object connid=%d sockfd=%d\n", connid, sockfd);
  126. update_select_nfds(t->sockfd);
  127. HASH_ADD_INT( by_id, connid, t );
  128. return t;
  129. }
  130. /* Please use tunnel_queue_delete() instead */
  131. void tunnel_delete(tunnel *t)
  132. {
  133. log_printf(L_INFO, "Deleting tunnel #%d ptr %p\n", t->connid, t);
  134. if(t->sockfd)
  135. {
  136. close(t->sockfd);
  137. FD_CLR(t->sockfd, &master_server_fds);
  138. update_select_nfds(0);
  139. }
  140. HASH_DEL( by_id, t );
  141. free(t);
  142. }
  143. int tunnel_in_delete_queue(tunnel *t)
  144. {
  145. tunnel_list *element;
  146. LL_FOREACH(tunnels_to_delete, element)
  147. {
  148. if(element->tun == t)
  149. {
  150. return 1;
  151. }
  152. }
  153. return 0;
  154. }
  155. /* Delete the tunnel at the end of main loop */
  156. void tunnel_queue_delete(tunnel *t)
  157. {
  158. tunnel_list *tunnel_list_entry = NULL;
  159. if(tunnel_in_delete_queue(t))
  160. {
  161. log_printf(L_DEBUG2, "Did not queue deleting tunnel #%d ptr %p - already queued\n", t->connid, t);
  162. return;
  163. }
  164. log_printf(L_DEBUG2, "Queued deleting tunnel #%d ptr %p\n", t->connid, t);
  165. tunnel_list_entry = calloc(sizeof(tunnel_list), 1);
  166. tunnel_list_entry->tun = t;
  167. LL_APPEND(tunnels_to_delete, tunnel_list_entry);
  168. }
  169. local_port_forward *local_port_forward_create()
  170. {
  171. local_port_forward *forward = calloc(sizeof(local_port_forward), 1);
  172. if(!forward)
  173. {
  174. return NULL;
  175. }
  176. forward->forward_id = ++last_forward_id;
  177. forward->created = time(NULL);
  178. return forward;
  179. }
  180. local_port_forward *find_pending_forward_by_id(uint32_t local_forward_id)
  181. {
  182. local_port_forward *forward;
  183. LL_FOREACH(local_port_forwards, forward)
  184. {
  185. if(forward->forward_id == local_forward_id)
  186. {
  187. return forward;
  188. }
  189. }
  190. return NULL;
  191. }
  192. /* bootstrap to dht with bootstrap_nodes */
  193. /* From uTox/tox.c */
  194. static void do_bootstrap(Tox *tox)
  195. {
  196. static unsigned int j = 0;
  197. if (j == 0)
  198. j = rand();
  199. int i = 0;
  200. while(i < 8) {
  201. struct bootstrap_node *d = &bootstrap_nodes[j % countof(bootstrap_nodes)];
  202. struct bootstrap_node *r = &tcp_relays[(4*j) % countof(tcp_relays)];
  203. tox_bootstrap(tox, d->address, d->port, d->key, 0);
  204. tox_add_tcp_relay(tox, r->address, r->port, r->key, 0);
  205. i++;
  206. j++;
  207. }
  208. }
  209. /* Set username to the machine's FQDN */
  210. void set_tox_username(Tox *tox)
  211. {
  212. char hostname[1024];
  213. TOX_ERR_SET_INFO error;
  214. gethostname((char*)hostname, 1024);
  215. hostname[1023] = '\0';
  216. tox_self_set_name(tox, (uint8_t *)hostname, strlen(hostname), &error);
  217. if(error != TOX_ERR_SET_INFO_OK)
  218. {
  219. log_printf(L_DEBUG, "tox_self_set_name() failed (%u)", error);
  220. }
  221. }
  222. /* Get sockaddr, IPv4 or IPv6 */
  223. void *get_in_addr(struct sockaddr *sa)
  224. {
  225. if (sa->sa_family == AF_INET)
  226. {
  227. return &(((struct sockaddr_in*)sa)->sin_addr);
  228. }
  229. return &(((struct sockaddr_in6*)sa)->sin6_addr);
  230. }
  231. /* Connect to an endpoint, return sockfd */
  232. int get_client_socket(char *hostname, int port)
  233. {
  234. int sockfd;
  235. struct addrinfo hints, *servinfo, *p;
  236. int rv;
  237. char s[INET6_ADDRSTRLEN];
  238. char port_str[6];
  239. snprintf(port_str, 6, "%d", port);
  240. memset(&hints, 0, sizeof hints);
  241. hints.ai_family = AF_INET;
  242. hints.ai_socktype = SOCK_STREAM;
  243. if ((rv = getaddrinfo(hostname, port_str, &hints, &servinfo)) != 0)
  244. {
  245. /* Add a special case for "localhost" when name resolution is broken */
  246. if(!strncmp("localhost", hostname, 256))
  247. {
  248. const char localhostname[] = "127.0.0.1";
  249. if ((rv = getaddrinfo(localhostname, port_str, &hints, &servinfo)) != 0) {
  250. log_printf(L_WARNING, "getaddrinfo failed for 127.0.0.1: %s\n", gai_strerror(rv));
  251. return -1;
  252. }
  253. }
  254. else
  255. {
  256. log_printf(L_WARNING, "getaddrinfo: %s\n", gai_strerror(rv));
  257. return -1;
  258. }
  259. }
  260. // loop through all the results and connect to the first we can
  261. for(p = servinfo; p != NULL; p = p->ai_next)
  262. {
  263. if (p->ai_family != AF_INET && p->ai_family != AF_INET6)
  264. continue;
  265. if ((sockfd = socket(p->ai_family, p->ai_socktype,
  266. p->ai_protocol)) == -1) {
  267. perror("client: socket");
  268. continue;
  269. }
  270. if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
  271. close(sockfd);
  272. perror("client: connect");
  273. continue;
  274. }
  275. break;
  276. }
  277. if (p == NULL) {
  278. log_printf(L_WARNING, "failed to connect to %s:%d\n", hostname, port);
  279. freeaddrinfo(servinfo);
  280. return -1;
  281. }
  282. inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), s, sizeof s);
  283. log_printf(L_DEBUG, "connecting to %s\n", s);
  284. freeaddrinfo(servinfo); // all done with this structure
  285. log_printf(L_DEBUG, "Connected to %s:%d\n", hostname, port);
  286. return sockfd;
  287. }
  288. /* Proto - our protocol handling */
  289. /*
  290. * send_frame: (almost) zero-copy. Overwrites first PROTOCOL_BUFFER_OFFSET bytes of data
  291. * so actual data should start at position PROTOCOL_BUFFER_OFFSET
  292. */
  293. int send_frame(protocol_frame *frame, uint8_t *data)
  294. {
  295. int rv = -1;
  296. int try = 0;
  297. int i;
  298. TOX_ERR_FRIEND_CUSTOM_PACKET custom_packet_error;
  299. data[0] = PROTOCOL_MAGIC_HIGH;
  300. data[1] = PROTOCOL_MAGIC_LOW;
  301. data[2] = BYTE2(frame->packet_type);
  302. data[3] = BYTE1(frame->packet_type);
  303. data[4] = BYTE2(frame->connid);
  304. data[5] = BYTE1(frame->connid);
  305. data[6] = BYTE2(frame->data_length);
  306. data[7] = BYTE1(frame->data_length);
  307. for(i = 0; i < 33;) /* 2.667 seconds per packet max */
  308. {
  309. int j;
  310. try++;
  311. rv = tox_friend_send_lossless_packet(
  312. tox,
  313. frame->friendnumber,
  314. data,
  315. frame->data_length + PROTOCOL_BUFFER_OFFSET,
  316. &custom_packet_error
  317. );
  318. if(custom_packet_error == TOX_ERR_FRIEND_CUSTOM_PACKET_OK)
  319. {
  320. break;
  321. }
  322. else
  323. {
  324. /* If this branch is ran, most likely we've hit congestion control. */
  325. if(custom_packet_error == TOX_ERR_FRIEND_CUSTOM_PACKET_SENDQ)
  326. {
  327. log_printf(L_DEBUG, "[%d] Failed to send packet to friend %d (Packet queue is full)\n", i, frame->friendnumber);
  328. }
  329. else if(custom_packet_error == TOX_ERR_FRIEND_CUSTOM_PACKET_FRIEND_NOT_CONNECTED)
  330. {
  331. log_printf(L_DEBUG, "[%d] Failed to send packet to friend %d (Friend gone)\n", i, frame->friendnumber);
  332. break;
  333. }
  334. else
  335. {
  336. log_printf(L_DEBUG, "[%d] Failed to send packet to friend %d (err: %u)\n", i, frame->friendnumber, custom_packet_error);
  337. }
  338. }
  339. if(i == 0) i = 2;
  340. else i = i * 2;
  341. for(j = 0; j < i; j++)
  342. {
  343. tox_iterate(tox, NULL);
  344. usleep(j * 1000);
  345. }
  346. }
  347. if(i > 0 && rv >= 0)
  348. {
  349. log_printf(L_DEBUG, "Packet succeeded at try %d (friend %d tunnel %d)\n", try, frame->friendnumber, frame->connid);
  350. }
  351. return rv;
  352. }
  353. int send_tunnel_ack_frame(tunnel *tun, uint32_t remote_forward_id)
  354. {
  355. protocol_frame frame_st;
  356. protocol_frame *frame;
  357. uint8_t *data = NULL;
  358. frame = &frame_st;
  359. memset(frame, 0, sizeof(protocol_frame));
  360. frame->packet_type = PACKET_TYPE_ACKTUNNEL;
  361. frame->connid = tun->connid;
  362. frame->data_length = 4;
  363. frame->friendnumber = tun->friendnumber;
  364. data = calloc(PROTOCOL_BUFFER_OFFSET + frame->data_length, 1);
  365. data[PROTOCOL_BUFFER_OFFSET+3] = BYTE1(remote_forward_id);
  366. data[PROTOCOL_BUFFER_OFFSET+2] = BYTE2(remote_forward_id);
  367. data[PROTOCOL_BUFFER_OFFSET+1] = BYTE3(remote_forward_id);
  368. data[PROTOCOL_BUFFER_OFFSET] = BYTE4(remote_forward_id);
  369. return send_frame(frame, data);
  370. }
  371. int handle_ping_frame(protocol_frame *rcvd_frame)
  372. {
  373. uint8_t data[TOX_MAX_CUSTOM_PACKET_SIZE];
  374. protocol_frame frame_s;
  375. protocol_frame *frame = &frame_s;
  376. frame->data = data + PROTOCOL_BUFFER_OFFSET;
  377. memcpy(frame->data, rcvd_frame->data, rcvd_frame->data_length);
  378. frame->friendnumber = rcvd_frame->friendnumber;
  379. frame->packet_type = PACKET_TYPE_PONG;
  380. frame->data_length = rcvd_frame->data_length;
  381. send_frame(frame, data);
  382. return 0;
  383. }
  384. int handle_request_tunnel_frame(protocol_frame *rcvd_frame)
  385. {
  386. char *hostname = NULL;
  387. tunnel *tun;
  388. int port = -1;
  389. int sockfd = 0;
  390. uint16_t tunnel_id;
  391. /* Client-side ID of the tunnel */
  392. uint32_t remote_forward_id;
  393. if(client_mode)
  394. {
  395. log_printf(L_WARNING, "Got tunnel request frame from friend #%d when in client mode\n", rcvd_frame->friendnumber);
  396. return -1;
  397. }
  398. port = rcvd_frame->connid;
  399. hostname = calloc(1, rcvd_frame->data_length + 1);
  400. if(!hostname)
  401. {
  402. log_printf(L_ERROR, "Could not allocate memory for tunnel request hostname\n");
  403. return -1;
  404. }
  405. remote_forward_id = INT32_AT(rcvd_frame->data, 0);
  406. strncpy(hostname, ((char *)rcvd_frame->data) + 4, rcvd_frame->data_length - 4);
  407. hostname[rcvd_frame->data_length] = '\0';
  408. log_printf(L_INFO, "Got a request to forward data from %s:%d\n", hostname, port);
  409. // check rules
  410. if (rules_policy == VALIDATE && nrules > 0 ) {
  411. rule temp_rule, *found = NULL;
  412. temp_rule.host = hostname;
  413. temp_rule.port = port;
  414. LL_SEARCH(rules, found, &temp_rule, rule_match);
  415. if(!found)
  416. {
  417. log_printf(L_WARNING, "Rejected, request not in rules\n");
  418. if(hostname)
  419. {
  420. free(hostname);
  421. }
  422. return -1;
  423. }
  424. } else if (rules_policy != NONE) {
  425. log_printf(L_WARNING, "Filter option active but no allowed host/port. All requests will be dropped.\n");
  426. if(hostname)
  427. {
  428. free(hostname);
  429. }
  430. return -1;
  431. }
  432. tunnel_id = get_random_tunnel_id();
  433. log_printf(L_DEBUG, "Tunnel ID: %d\n", tunnel_id);
  434. sockfd = get_client_socket(hostname, port);
  435. if(sockfd >= 0)
  436. {
  437. tun = tunnel_create(sockfd, tunnel_id, rcvd_frame->friendnumber);
  438. if(tun)
  439. {
  440. FD_SET(sockfd, &master_server_fds);
  441. update_select_nfds(sockfd);
  442. log_printf(L_DEBUG, "Created tunnel, yay!\n");
  443. send_tunnel_ack_frame(tun, remote_forward_id);
  444. }
  445. else
  446. {
  447. log_printf(L_ERROR, "Couldn't allocate memory for tunnel\n");
  448. close(sockfd);
  449. }
  450. }
  451. else
  452. {
  453. log_printf(L_WARNING, "Could not connect to %s:%d\n", hostname, port);
  454. /* TODO send PACKET_TYPE_REQUESTTUNNEL */
  455. }
  456. free(hostname);
  457. return 0;
  458. }
  459. /* Handle a TCP frame received from client */
  460. int handle_client_tcp_frame(protocol_frame *rcvd_frame)
  461. {
  462. tunnel *tun=NULL;
  463. int offset = 0;
  464. int connid = rcvd_frame->connid;
  465. HASH_FIND_INT(by_id, &connid, tun);
  466. if(!tun)
  467. {
  468. log_printf(L_WARNING, "Got TCP frame with unknown tunnel ID %d\n", rcvd_frame->connid);
  469. return -1;
  470. }
  471. if(tun->friendnumber != rcvd_frame->friendnumber)
  472. {
  473. log_printf(L_WARNING, "Friend #%d tried to send packet to a tunnel which belongs to #%d\n", rcvd_frame->friendnumber, tun->friendnumber);
  474. return -1;
  475. }
  476. while(offset < rcvd_frame->data_length)
  477. {
  478. int sent_bytes;
  479. sent_bytes = send(
  480. tun->sockfd,
  481. rcvd_frame->data + offset,
  482. rcvd_frame->data_length - offset,
  483. MSG_NOSIGNAL
  484. );
  485. if(sent_bytes < 0)
  486. {
  487. log_printf(L_WARNING, "Could not write to socket %d: %s\n", tun->sockfd, strerror(errno));
  488. return -1;
  489. }
  490. offset += sent_bytes;
  491. }
  492. return 0;
  493. }
  494. /* Handle close-tunnel frame received from the client */
  495. int handle_client_tcp_fin_frame(protocol_frame *rcvd_frame)
  496. {
  497. tunnel *tun=NULL;
  498. int connid = rcvd_frame->connid;
  499. HASH_FIND_INT(by_id, &connid, tun);
  500. if(!tun)
  501. {
  502. log_printf(L_WARNING, "Got TCP FIN frame with unknown tunnel ID %d\n", rcvd_frame->connid);
  503. return -1;
  504. }
  505. if(tun->friendnumber != rcvd_frame->friendnumber)
  506. {
  507. log_printf(L_WARNING, "Friend #%d tried to close tunnel which belongs to #%d\n", rcvd_frame->friendnumber, tun->friendnumber);
  508. return -1;
  509. }
  510. log_printf(L_DEBUG2, "Deleting tunnel #%d (%p) in handle_client_tcp_fin_frame(), socket %d", rcvd_frame->connid, tun, tun->sockfd);
  511. tunnel_queue_delete(tun);
  512. return 0;
  513. }
  514. /* This is a dispatcher for our encapsulated protocol */
  515. int handle_frame(protocol_frame *frame)
  516. {
  517. switch(frame->packet_type)
  518. {
  519. case PACKET_TYPE_PING:
  520. return handle_ping_frame(frame);
  521. break;
  522. case PACKET_TYPE_PONG:
  523. return handle_pong_frame(frame);
  524. break;
  525. case PACKET_TYPE_TCP:
  526. if(client_mode)
  527. {
  528. return handle_server_tcp_frame(frame);
  529. }
  530. else
  531. {
  532. return handle_client_tcp_frame(frame);
  533. }
  534. break;
  535. case PACKET_TYPE_REQUESTTUNNEL:
  536. handle_request_tunnel_frame(frame);
  537. break;
  538. case PACKET_TYPE_ACKTUNNEL:
  539. handle_acktunnel_frame(frame);
  540. break;
  541. case PACKET_TYPE_TCP_FIN:
  542. if(client_mode)
  543. {
  544. return handle_server_tcp_fin_frame(frame);
  545. }
  546. else
  547. {
  548. return handle_client_tcp_fin_frame(frame);
  549. }
  550. break;
  551. default:
  552. log_printf(L_DEBUG, "Got unknown packet type 0x%x from friend %d\n",
  553. frame->packet_type,
  554. frame->friendnumber
  555. );
  556. }
  557. return 0;
  558. }
  559. /*
  560. * This is a callback which gets a packet from Tox core.
  561. * It checks for basic inconsistiencies and allocates the
  562. * protocol_frame structure.
  563. */
  564. void parse_lossless_packet(Tox *tox, uint32_t friendnumber, const uint8_t *data, size_t len, void *tmp)
  565. {
  566. protocol_frame *frame = NULL;
  567. if(len < PROTOCOL_BUFFER_OFFSET)
  568. {
  569. log_printf(L_WARNING, "Received too short data frame - only %d bytes, at least %d expected\n", len, PROTOCOL_BUFFER_OFFSET);
  570. return;
  571. }
  572. if(!data)
  573. {
  574. log_printf(L_ERROR, "Got NULL pointer from toxcore - WTF?\n");
  575. return;
  576. }
  577. if(data[0] != PROTOCOL_MAGIC_HIGH || data[1] != PROTOCOL_MAGIC_LOW)
  578. {
  579. log_printf(L_WARNING, "Received data frame with invalid protocol magic number 0x%x%x\n", data[0], data[1]);
  580. if(data[0] == (PROTOCOL_MAGIC_V1 >> 8) && data[1] == (PROTOCOL_MAGIC_V1 & 0xff))
  581. {
  582. log_printf(L_ERROR, "Tuntox on the other end uses old protocol version 1. Please upgrade it.");
  583. }
  584. return;
  585. }
  586. frame = calloc(1, sizeof(protocol_frame));
  587. if(!frame)
  588. {
  589. log_printf(L_ERROR, "Could not allocate memory for protocol_frame_t\n");
  590. return;
  591. }
  592. /* TODO check if friendnumber is the same in sender and connid tunnel*/
  593. frame->magic = INT16_AT(data, 0);
  594. frame->packet_type = INT16_AT(data, 2);
  595. frame->connid = INT16_AT(data, 4);
  596. frame->data_length = INT16_AT(data, 6);
  597. frame->data = (uint8_t *)(data + PROTOCOL_BUFFER_OFFSET);
  598. frame->friendnumber = friendnumber;
  599. log_printf(L_DEBUG, "Got protocol frame magic 0x%x type 0x%x from friend %d\n", frame->magic, frame->packet_type, frame->friendnumber);
  600. if(len < (size_t)frame->data_length + PROTOCOL_BUFFER_OFFSET)
  601. {
  602. log_printf(L_WARNING, "Received frame too small (attempted buffer overflow?): %d bytes, excepted at least %d bytes\n", len, frame->data_length + PROTOCOL_BUFFER_OFFSET);
  603. free(frame);
  604. return;
  605. }
  606. if(frame->data_length > (TOX_MAX_CUSTOM_PACKET_SIZE - PROTOCOL_BUFFER_OFFSET))
  607. {
  608. log_printf(L_WARNING, "Declared data length too big (attempted buffer overflow?): %d bytes, excepted at most %d bytes\n", frame->data_length, (TOX_MAX_CUSTOM_PACKET_SIZE - PROTOCOL_BUFFER_OFFSET));
  609. free(frame);
  610. return;
  611. }
  612. handle_frame(frame);
  613. free(frame);
  614. }
  615. int send_tunnel_request_packet(char *remote_host, int remote_port, uint32_t local_forward_id, int friend_number)
  616. {
  617. int packet_length = 0;
  618. protocol_frame frame_i, *frame;
  619. uint8_t *data = NULL;
  620. log_printf(L_INFO, "Sending packet to friend #%d to forward %s:%d\n", friend_number, remote_host, remote_port);
  621. packet_length = PROTOCOL_BUFFER_OFFSET + strlen(remote_host) + 4;
  622. if(packet_length > TOX_MAX_CUSTOM_PACKET_SIZE)
  623. {
  624. log_printf(L_WARNING, "Not requesting port forward - host name %s is too long", remote_host);
  625. }
  626. frame = &frame_i;
  627. data = calloc(1, packet_length);
  628. if(!data)
  629. {
  630. log_printf(L_ERROR, "Could not allocate memory for tunnel request packet\n");
  631. exit(1);
  632. }
  633. data[PROTOCOL_BUFFER_OFFSET+3] = BYTE1(local_forward_id);
  634. data[PROTOCOL_BUFFER_OFFSET+2] = BYTE2(local_forward_id);
  635. data[PROTOCOL_BUFFER_OFFSET+1] = BYTE3(local_forward_id);
  636. data[PROTOCOL_BUFFER_OFFSET] = BYTE4(local_forward_id);
  637. memcpy((char *)data+PROTOCOL_BUFFER_OFFSET+4, remote_host, strlen(remote_host));
  638. frame->friendnumber = friend_number;
  639. frame->packet_type = PACKET_TYPE_REQUESTTUNNEL;
  640. frame->connid = remote_port;
  641. frame->data_length = strlen(remote_host) + 4;
  642. send_frame(frame, data);
  643. free(data);
  644. return 0;
  645. }
  646. /* End proto */
  647. /* Save tox identity to a file */
  648. static void write_save(Tox *tox)
  649. {
  650. void *data;
  651. uint32_t size;
  652. uint8_t path_tmp[512], path_real[512], *p;
  653. FILE *file;
  654. size = tox_get_savedata_size(tox);
  655. data = malloc(size);
  656. tox_get_savedata(tox, data);
  657. strncpy((char *)path_real, config_path, sizeof(path_real));
  658. p = path_real + strlen((char *)path_real);
  659. memcpy(p, "tox_save", sizeof("tox_save"));
  660. unsigned int path_len = (p - path_real) + sizeof("tox_save");
  661. memcpy(path_tmp, path_real, path_len);
  662. memcpy(path_tmp + (path_len - 1), ".tmp", sizeof(".tmp"));
  663. file = fopen((char*)path_tmp, "wb");
  664. if(file) {
  665. fwrite(data, size, 1, file);
  666. fflush(file);
  667. fclose(file);
  668. if (rename((char*)path_tmp, (char*)path_real) != 0) {
  669. log_printf(L_WARNING, "Failed to rename file. %s to %s deleting and trying again\n", path_tmp, path_real);
  670. if(remove((const char *)path_real) < 0) {
  671. log_printf(L_WARNING, "Failed to remove old save file %s\n", path_real);
  672. }
  673. if (rename((char*)path_tmp, (char*)path_real) != 0) {
  674. log_printf(L_WARNING, "Saving Failed\n");
  675. } else {
  676. log_printf(L_DEBUG, "Saved data\n");
  677. }
  678. } else {
  679. log_printf(L_DEBUG, "Saved data\n");
  680. }
  681. }
  682. else
  683. {
  684. log_printf(L_WARNING, "Could not open save file\n");
  685. }
  686. free(data);
  687. }
  688. /* Load tox identity from a file */
  689. static size_t load_save(uint8_t **out_data)
  690. {
  691. void *data;
  692. uint32_t size;
  693. uint8_t path_real[512], *p;
  694. strncpy((char *)path_real, config_path, sizeof(path_real));
  695. p = path_real + strlen((char *)path_real);
  696. memcpy(p, "tox_save", sizeof("tox_save"));
  697. data = file_raw((char *)path_real, &size);
  698. if(data)
  699. {
  700. *out_data = data;
  701. return size;
  702. }
  703. else
  704. {
  705. log_printf(L_WARNING, "Could not open save file\n");
  706. return 0;
  707. }
  708. }
  709. /* Loads a list of allowed hostnames and ports from file. Format is hostname:port*/
  710. void load_rules()
  711. {
  712. char *ahost=NULL;
  713. int aport=0;
  714. char line[100 + 1] = "";
  715. FILE *file = NULL;
  716. rule *rule_obj = NULL;
  717. int valid_rules = 0;
  718. file = fopen(rules_file, "r");
  719. if (file == NULL) {
  720. log_printf(L_WARNING, "Could not open rules file (%s)\n", rules_file);
  721. return;
  722. }
  723. while (fgets(line, sizeof(line), file)) {
  724. /* allow comments & white lines */
  725. if (line[0]=='#'||line[0]=='\n') {
  726. continue;
  727. }
  728. if (parse_pipe_port_forward(line, &ahost, &aport) >= 0) {
  729. if (aport > 0 && aport < 65535) {
  730. rule_obj = (rule *)calloc(sizeof(rule), 1);
  731. if(!rule_obj)
  732. {
  733. log_printf(L_ERROR, "Could not allocate memory for rule");
  734. exit(1);
  735. }
  736. rule_obj->port = aport;
  737. rule_obj->host = strdup(ahost);
  738. LL_APPEND(rules, rule_obj);
  739. valid_rules++;
  740. } else {
  741. log_printf(L_WARNING, "Invalid port in line: %s\n", line);
  742. }
  743. } else {
  744. log_printf(L_WARNING, "Could not parse line: %s\n", line);
  745. }
  746. }
  747. fclose(file);
  748. /* save valid rules in global variable */
  749. nrules = valid_rules;
  750. log_printf(L_INFO, "Loaded %d rules\n", nrules);
  751. if (nrules==0 && rules_policy != NONE){
  752. log_printf(L_WARNING, "No rules loaded! NO CONNECTIONS WILL BE ALLOWED!\n");
  753. }
  754. }
  755. /* Clear rules loaded into memory */
  756. void clear_rules()
  757. {
  758. rule * elt, *tmp;
  759. /* delete each elemen using the safe iterator */
  760. LL_FOREACH_SAFE(rules,elt,tmp) {
  761. LL_DELETE(rules,elt);
  762. free(elt->host);
  763. free(elt);
  764. }
  765. }
  766. void accept_friend_request(Tox *tox, const uint8_t *public_key, const uint8_t *message, size_t length, void *userdata)
  767. {
  768. unsigned char tox_printable_id[TOX_ADDRESS_SIZE * 2 + 1];
  769. uint32_t friendnumber;
  770. TOX_ERR_FRIEND_ADD friend_add_error;
  771. log_printf(L_DEBUG, "Got friend request\n");
  772. if(use_shared_secret)
  773. {
  774. if(!message)
  775. {
  776. log_printf(L_WARNING, "Friend sent NULL message - not accepting request");
  777. return;
  778. }
  779. if(message[length - 1] != '\0')
  780. {
  781. log_printf(L_WARNING, "Message of size %u is not NULL terminated - not accepting request", length);
  782. return;
  783. }
  784. if(strncmp((char *)message, shared_secret, TOX_MAX_FRIEND_REQUEST_LENGTH-1))
  785. {
  786. log_printf(L_WARNING, "Received shared secret \"%s\" differs from our shared secret - not accepting request", message);
  787. return;
  788. }
  789. }
  790. memset(tox_printable_id, '\0', sizeof(tox_printable_id));
  791. id_to_string(tox_printable_id, public_key);
  792. if(server_whitelist_mode)
  793. {
  794. allowed_toxid etmp, *found = NULL;
  795. memcpy(etmp.toxid, public_key, TOX_PUBLIC_KEY_SIZE);
  796. LL_SEARCH(allowed_toxids, found, &etmp, allowed_toxid_cmp);
  797. if(!found)
  798. {
  799. log_printf(L_WARNING, "Rejected friend request from non-whitelisted friend %s", tox_printable_id);
  800. return;
  801. }
  802. log_printf(L_DEBUG, "Friend %s passed whitelist check", tox_printable_id);
  803. }
  804. friendnumber = tox_friend_add_norequest(tox, public_key, &friend_add_error);
  805. if(friend_add_error != TOX_ERR_FRIEND_ADD_OK)
  806. {
  807. log_printf(L_WARNING, "Could not add friend: err %u", friend_add_error);
  808. return;
  809. }
  810. log_printf(L_INFO, "Accepted friend request from %s as %d\n", tox_printable_id, friendnumber);
  811. }
  812. /* Callback for tox_callback_self_connection_status() */
  813. void handle_connection_status_change(Tox *tox, TOX_CONNECTION p_connection_status, void *user_data)
  814. {
  815. const char *status = NULL;
  816. connection_status = p_connection_status;
  817. status = readable_connection_status(connection_status);
  818. log_printf(L_INFO, "Connection status changed: %s", status);
  819. }
  820. void cleanup()
  821. {
  822. log_printf(L_DEBUG, "kthxbye\n");
  823. fflush(stdout);
  824. tox_kill(tox);
  825. if(client_socket)
  826. {
  827. close(client_socket);
  828. }
  829. log_close();
  830. }
  831. int do_server_loop()
  832. {
  833. struct timeval tv, tv_start, tv_end;
  834. unsigned long long ms_start, ms_end;
  835. fd_set fds;
  836. unsigned char tox_packet_buf[PROTOCOL_MAX_PACKET_SIZE];
  837. tunnel *tun = NULL;
  838. tunnel *tmp = NULL;
  839. TOX_CONNECTION connected = 0;
  840. int sent_data = 0;
  841. tox_callback_friend_lossless_packet(tox, parse_lossless_packet);
  842. tv.tv_sec = 0;
  843. tv.tv_usec = 20000;
  844. FD_ZERO(&master_server_fds);
  845. while(1)
  846. {
  847. TOX_CONNECTION tmp_isconnected = 0;
  848. uint32_t tox_do_interval_ms;
  849. int select_rv = 0;
  850. sent_data = 0;
  851. /* Let tox do its stuff */
  852. tox_iterate(tox, NULL);
  853. /* Get the desired sleep time, used in select() later */
  854. tox_do_interval_ms = tox_iteration_interval(tox);
  855. tv.tv_usec = (tox_do_interval_ms % 1000) * 1000;
  856. tv.tv_sec = tox_do_interval_ms / 1000;
  857. log_printf(L_DEBUG2, "Iteration interval: %dms\n", tox_do_interval_ms);
  858. gettimeofday(&tv_start, NULL);
  859. /* Check change in connection state */
  860. tmp_isconnected = connection_status;
  861. if(tmp_isconnected != connected)
  862. {
  863. connected = tmp_isconnected;
  864. if(connected)
  865. {
  866. log_printf(L_DEBUG, "Connected to Tox network\n");
  867. }
  868. else
  869. {
  870. log_printf(L_DEBUG, "Disconnected from Tox network\n");
  871. }
  872. }
  873. fds = master_server_fds;
  874. /* Poll for data from our client connection */
  875. select_rv = select(select_nfds, &fds, NULL, NULL, &tv);
  876. if(select_rv == -1 || select_rv == 0)
  877. {
  878. if(select_rv == -1)
  879. {
  880. log_printf(L_DEBUG, "Reading from local socket failed: code=%d (%s)\n",
  881. errno, strerror(errno));
  882. }
  883. else
  884. {
  885. log_printf(L_DEBUG2, "Nothing to read...");
  886. }
  887. }
  888. else
  889. {
  890. tunnel_list *tunnel_list_entry = NULL, *list_tmp = NULL;
  891. tmp = NULL;
  892. tun = NULL;
  893. log_printf(L_DEBUG, "Starting tunnel iteration...");
  894. HASH_ITER(hh, by_id, tun, tmp)
  895. {
  896. log_printf(L_DEBUG, "Current tunnel: %p", tun);
  897. if(FD_ISSET(tun->sockfd, &fds))
  898. {
  899. int nbytes = recv(tun->sockfd,
  900. tox_packet_buf+PROTOCOL_BUFFER_OFFSET,
  901. READ_BUFFER_SIZE, 0);
  902. /* Check if connection closed */
  903. if(nbytes <= 0)
  904. {
  905. uint8_t data[PROTOCOL_BUFFER_OFFSET];
  906. protocol_frame frame_st, *frame;
  907. if(nbytes == 0)
  908. {
  909. log_printf(L_WARNING, "conn closed!\n");
  910. }
  911. else
  912. {
  913. log_printf(L_WARNING, "conn closed, code=%d (%s)\n",
  914. errno, strerror(errno));
  915. }
  916. frame = &frame_st;
  917. memset(frame, 0, sizeof(protocol_frame));
  918. frame->friendnumber = tun->friendnumber;
  919. frame->packet_type = PACKET_TYPE_TCP_FIN;
  920. frame->connid = tun->connid;
  921. frame->data_length = 0;
  922. send_frame(frame, data);
  923. sent_data = 1;
  924. tunnel_queue_delete(tun);
  925. continue;
  926. }
  927. else
  928. {
  929. protocol_frame frame_st, *frame;
  930. frame = &frame_st;
  931. memset(frame, 0, sizeof(protocol_frame));
  932. frame->friendnumber = tun->friendnumber;
  933. frame->packet_type = PACKET_TYPE_TCP;
  934. frame->connid = tun->connid;
  935. frame->data_length = nbytes;
  936. send_frame(frame, tox_packet_buf);
  937. sent_data = 1;
  938. }
  939. }
  940. }
  941. log_printf(L_DEBUG, "Tunnel iteration done");
  942. LL_FOREACH_SAFE(tunnels_to_delete, tunnel_list_entry, list_tmp)
  943. {
  944. tunnel_delete(tunnel_list_entry->tun);
  945. LL_DELETE(tunnels_to_delete, tunnel_list_entry);
  946. free(tunnel_list_entry);
  947. }
  948. }
  949. gettimeofday(&tv_end, NULL);
  950. ms_start = 1000 * tv_start.tv_sec + tv_start.tv_usec/1000;
  951. ms_end = 1000 * tv_end.tv_sec + tv_end.tv_usec/1000;
  952. if(!sent_data && (ms_end - ms_start < tox_do_interval_ms))
  953. {
  954. /*log_printf(L_DEBUG, "Sleeping for %d ms extra to prevent high CPU usage\n", (tox_do_interval_ms - (ms_end - ms_start)));*/
  955. usleep((tox_do_interval_ms - (ms_end - ms_start)) * 1000);
  956. }
  957. }
  958. }
  959. /* Signal handler used when daemonizing */
  960. static void child_handler(int signum)
  961. {
  962. switch(signum) {
  963. case SIGALRM: exit(1); break;
  964. case SIGUSR1: exit(0); break;
  965. case SIGCHLD: exit(1); break;
  966. }
  967. }
  968. /*
  969. * Daemonize the process if -D is set
  970. * Optionally drop privileges and create a lock file
  971. */
  972. void do_daemonize()
  973. {
  974. pid_t pid, sid, parent;
  975. FILE *pidf = NULL;
  976. /* already a daemon */
  977. if (getppid() == 1)
  978. {
  979. return;
  980. }
  981. /* Drop user if there is one, and we were run as root */
  982. if (daemon_username && (getuid() == 0 || geteuid() == 0))
  983. {
  984. struct passwd *pw = getpwnam(daemon_username);
  985. if(pw)
  986. {
  987. log_printf(L_DEBUG, "Setuid to user %s", daemon_username);
  988. setuid(pw->pw_uid);
  989. }
  990. else
  991. {
  992. char *tmp;
  993. int uid = 0;
  994. uid = strtol(daemon_username, &tmp, 10);
  995. if(uid)
  996. {
  997. setuid(uid);
  998. log_printf(L_DEBUG, "Setuid to user ID %ld", (long)uid);
  999. }
  1000. else
  1001. {
  1002. log_printf(L_DEBUG, "Could not setuid to user %s - no pwnam (static build?) or invalid numeric UID", daemon_username);
  1003. }
  1004. }
  1005. }
  1006. /* Trap signals that we expect to recieve */
  1007. signal(SIGCHLD,child_handler);
  1008. signal(SIGUSR1,child_handler);
  1009. signal(SIGALRM,child_handler);
  1010. /* Fork off the parent process */
  1011. pid = fork();
  1012. if (pid < 0)
  1013. {
  1014. log_printf(L_ERROR, "Unable to fork daemon, code=%d (%s)",
  1015. errno, strerror(errno));
  1016. exit(1);
  1017. }
  1018. /* If we got a good PID, then we can exit the parent process. */
  1019. if (pid > 0)
  1020. {
  1021. /* Wait for confirmation from the child via SIGTERM or SIGCHLD, or
  1022. for two seconds to elapse (SIGALRM). pause() should not return. */
  1023. alarm(2);
  1024. pause();
  1025. exit(1);
  1026. }
  1027. /* At this point we are executing as the child process */
  1028. parent = getppid();
  1029. /* Cancel certain signals */
  1030. signal(SIGCHLD,SIG_DFL); /* A child process dies */
  1031. signal(SIGTSTP,SIG_IGN); /* Various TTY signals */
  1032. signal(SIGTTOU,SIG_IGN);
  1033. signal(SIGTTIN,SIG_IGN);
  1034. signal(SIGHUP, SIG_IGN); /* Ignore hangup signal */
  1035. signal(SIGTERM,SIG_DFL); /* Die on SIGTERM */
  1036. /* Change the file mode mask */
  1037. umask(S_IWGRP | S_IWOTH);
  1038. /* Reinitialize the syslog connection */
  1039. log_init();
  1040. /* Create a new SID for the child process */
  1041. sid = setsid();
  1042. if (sid < 0)
  1043. {
  1044. log_printf(L_ERROR, "unable to create a new session, code %d (%s)",
  1045. errno, strerror(errno));
  1046. exit(1);
  1047. }
  1048. /* Change the current working directory. This prevents the current
  1049. directory from being locked; hence not being able to remove it. */
  1050. if ((chdir("/")) < 0)
  1051. {
  1052. log_printf(L_ERROR, "Unable to change directory to %s, code %d (%s)",
  1053. "/", errno, strerror(errno) );
  1054. exit(1);
  1055. }
  1056. /* Redirect standard files to /dev/null */
  1057. freopen( "/dev/null", "r", stdin);
  1058. freopen( "/dev/null", "w", stdout);
  1059. freopen( "/dev/null", "w", stderr);
  1060. /* Create the pid file as the new user */
  1061. if (pidfile && pidfile[0])
  1062. {
  1063. pidf = fopen(pidfile, "w");
  1064. if (!pidf)
  1065. {
  1066. log_printf(L_ERROR, "Unable to create PID file %s, code=%d (%s)",
  1067. pidfile, errno, strerror(errno));
  1068. exit(1);
  1069. }
  1070. fprintf(pidf, "%ld", (long)getpid());
  1071. fclose(pidf);
  1072. }
  1073. /* Tell the parent process that we are A-okay */
  1074. kill( parent, SIGUSR1 );
  1075. }
  1076. /* Parse the ALL_PROXY or all_proxy environment variable */
  1077. void parse_all_proxy(struct Tox_Options *tox_options)
  1078. {
  1079. char *env;
  1080. static char all_proxy[1024];
  1081. int len_of_env = 0;
  1082. /* Remote SOCKS5 proxy host/port */
  1083. Tox_Proxy_Type proxy_type;
  1084. char *proto_name = "";
  1085. char *hostname;
  1086. int remote_port;
  1087. char *p;
  1088. unsigned int i = 0;
  1089. env = getenv("ALL_PROXY");
  1090. if(!env)
  1091. {
  1092. env = getenv("all_proxy");
  1093. }
  1094. if(!env)
  1095. {
  1096. return;
  1097. }
  1098. len_of_env = strlen(env);
  1099. if(len_of_env > 1023)
  1100. {
  1101. len_of_env = 1023;
  1102. }
  1103. for(i = 0; i < len_of_env; i++)
  1104. {
  1105. all_proxy[i] = tolower(env[i]);
  1106. }
  1107. all_proxy[len_of_env] = 0;
  1108. if(!strncmp(all_proxy, "socks5://", strlen("socks5://")))
  1109. {
  1110. proxy_type = TOX_PROXY_TYPE_SOCKS5;
  1111. proto_name = "SOCKS5";
  1112. p = all_proxy + strlen("socks5://");
  1113. }
  1114. else
  1115. {
  1116. if(!strncmp(all_proxy, "http://", strlen("http://")))
  1117. {
  1118. proxy_type = TOX_PROXY_TYPE_HTTP;
  1119. proto_name = "HTTP";
  1120. p = all_proxy + strlen("http://");
  1121. }
  1122. else
  1123. {
  1124. log_printf(L_WARNING, "%s is not a valid SOCKS5 or HTTP proxy string", all_proxy);
  1125. return;
  1126. }
  1127. }
  1128. if(parse_pipe_port_forward(p, &hostname, &remote_port))
  1129. {
  1130. log_printf(L_WARNING, "%s is not a valid %s proxy string", all_proxy, proto_name);
  1131. return;
  1132. }
  1133. log_printf(L_INFO, "Using %s proxy at %s:%d for Tox network connections", proto_name, hostname, remote_port);
  1134. if(!client_mode)
  1135. {
  1136. log_printf(L_INFO, "%s proxy is not used for outgoing tunneled connections, just for Tox network traffic", proto_name);
  1137. }
  1138. tox_options_set_proxy_type(tox_options, proxy_type);
  1139. tox_options_set_proxy_host(tox_options, hostname);
  1140. tox_options_set_proxy_port(tox_options, remote_port);
  1141. /* TODO: is this necessary? */
  1142. tox_options_set_udp_enabled(tox_options, 0);
  1143. }
  1144. void help()
  1145. {
  1146. fprintf(stdout, "tuntox - Forward ports over the Tox protocol\n\n");
  1147. fprintf(stdout, "Usage:\n");
  1148. fprintf(stdout, " tuntox ... # starts the server\n");
  1149. fprintf(stdout, " tuntox -i <servertoxid> -L <localport>:<remoteaddress>:<remoteport> ... # starts the client\n\n");
  1150. fprintf(stdout, "Options:\n");
  1151. fprintf(stdout, " Server:\n");
  1152. fprintf(stdout, " -i <toxid> - whitelisted Tox ID (can be used multiple times)\n");
  1153. fprintf(stdout, " -f <file> - only allow connections to hostname/port combinations contained\n");
  1154. fprintf(stdout, " in <file>. Rules must be entered one per line with the\n");
  1155. fprintf(stdout, " <hostname>:<port> format\n");
  1156. fprintf(stdout, " Client:\n");
  1157. fprintf(stdout, " -i <toxid> - remote point Tox ID\n");
  1158. fprintf(stdout, " -L <localport>:<remotehostname>:<remoteport>\n");
  1159. fprintf(stdout, " - forward <remotehostname>:<remoteport> to 127.0.0.1:<localport>\n");
  1160. fprintf(stdout, " -W <remotehostname>:<remoteport> - forward <remotehostname>:<remoteport> to\n");
  1161. fprintf(stdout, " stdin/stdout (SSH ProxyCommand mode)\n");
  1162. fprintf(stdout, " -p - ping the server from -i and exit\n");
  1163. fprintf(stdout, " Common:\n");
  1164. fprintf(stdout, " -C <dir> - save private key in <dir> instead of /etc/tuntox in server\n");
  1165. fprintf(stdout, " mode\n");
  1166. fprintf(stdout, " -s <secret> - shared secret used for connection authentication (max\n");
  1167. fprintf(stdout, " %u characters)\n", TOX_MAX_FRIEND_REQUEST_LENGTH-1);
  1168. fprintf(stdout, " -I <file> - save local Tox ID in <file> in clear text format\n");
  1169. fprintf(stdout, " -t <port> - set TCP relay port (0 disables TCP relaying)\n");
  1170. fprintf(stdout, " -u <port>:<port> - set Tox UDP port range\n");
  1171. fprintf(stdout, " -d - debug mode (use twice to display toxcore log too)\n");
  1172. fprintf(stdout, " -q - quiet mode\n");
  1173. fprintf(stdout, " -S - send output to syslog instead of stdout\n");
  1174. fprintf(stdout, " -D - daemonize (fork) and exit (implies -S)\n");
  1175. fprintf(stdout, " -F <path> - create a PID file named <path>\n");
  1176. fprintf(stdout, " -U <username|userid> - drop privileges to <username> before forking. Use\n");
  1177. fprintf(stdout, " numeric <userid> in static builds.\n");
  1178. fprintf(stdout, " -b <path> - bootstrap from Tox nodes in a JSON file like nodes.tox.chat/json\n");
  1179. fprintf(stdout, " -V - print version and exit\n");
  1180. fprintf(stdout, " -h - this help message\n");
  1181. fprintf(stdout, "Recognized environment variables:\n");
  1182. fprintf(stdout, " TUNTOX_SHARED_SECRET\n");
  1183. fprintf(stdout, " ALL_PROXY\n");
  1184. }
  1185. int main(int argc, char *argv[])
  1186. {
  1187. unsigned char tox_id[TOX_ADDRESS_SIZE];
  1188. unsigned char tox_printable_id[TOX_ADDRESS_SIZE * 2 + 1];
  1189. TOX_ERR_NEW tox_new_err;
  1190. int oc;
  1191. size_t save_size = 0;
  1192. uint8_t *save_data = NULL;
  1193. char *tox_id_path = NULL;
  1194. allowed_toxid *allowed_toxid_obj = NULL;
  1195. local_port_forward *port_forward = NULL;
  1196. srand(time(NULL));
  1197. tcp_relay_port = 1024 + (rand() % 64511);
  1198. udp_start_port = 1024 + (rand() % 64500);
  1199. udp_end_port = udp_start_port + 10;
  1200. last_forward_id = rand();
  1201. log_init();
  1202. while ((oc = getopt(argc, argv, "L:pi:I:C:s:f:W:dqhSF:DU:t:u:b:V")) != -1)
  1203. {
  1204. switch(oc)
  1205. {
  1206. case 'L':
  1207. port_forward = local_port_forward_create();
  1208. if(!port_forward) {
  1209. log_printf(L_ERROR, "Could not allocate memory for port forward\n");
  1210. exit(1);
  1211. }
  1212. /* Local port forwarding */
  1213. client_mode = 1;
  1214. client_local_port_mode = 1;
  1215. if(parse_local_port_forward(optarg, &(port_forward->local_port), &(port_forward->remote_host), &(port_forward->remote_port)) < 0)
  1216. {
  1217. log_printf(L_ERROR, "Invalid value for -L option - use something like -L 22:127.0.0.1:22\n");
  1218. exit(1);
  1219. }
  1220. LL_APPEND(local_port_forwards, port_forward);
  1221. if(min_log_level == L_UNSET)
  1222. {
  1223. min_log_level = L_INFO;
  1224. }
  1225. log_printf(L_DEBUG, "Forwarding remote port %d to local port %d\n", port_forward->remote_port, port_forward->local_port);
  1226. break;
  1227. case 'W':
  1228. /* Pipe forwarding */
  1229. port_forward = local_port_forward_create();
  1230. client_mode = 1;
  1231. client_pipe_mode = 1;
  1232. if(parse_pipe_port_forward(optarg, &(port_forward->remote_host), &(port_forward->remote_port)) < 0)
  1233. {
  1234. log_printf(L_ERROR, "Invalid value for -W option - use something like -W 127.0.0.1:22\n");
  1235. exit(1);
  1236. }
  1237. if(min_log_level == L_UNSET)
  1238. {
  1239. min_log_level = L_ERROR;
  1240. }
  1241. LL_APPEND(local_port_forwards, port_forward);
  1242. log_printf(L_INFO, "Forwarding remote port %d to stdin/out\n", port_forward->remote_port);
  1243. break;
  1244. case 'p':
  1245. /* Ping */
  1246. client_mode = 1;
  1247. ping_mode = 1;
  1248. if(min_log_level == L_UNSET)
  1249. {
  1250. min_log_level = L_INFO;
  1251. }
  1252. break;
  1253. case 'i':
  1254. /* Tox ID */
  1255. server_whitelist_mode = 1;
  1256. log_printf(L_DEBUG, "Server whitelist mode enabled");
  1257. allowed_toxid_obj = (allowed_toxid *)calloc(sizeof(allowed_toxid), 1);
  1258. if(!allowed_toxid_obj)
  1259. {
  1260. log_printf(L_ERROR, "Could not allocate memory for allowed_toxid");
  1261. exit(1);
  1262. }
  1263. remote_tox_id = (uint8_t *)optarg;
  1264. if(!string_to_id(allowed_toxid_obj->toxid, (uint8_t *)optarg))
  1265. {
  1266. log_printf(L_ERROR, "Invalid Tox ID");
  1267. exit(1);
  1268. }
  1269. LL_APPEND(allowed_toxids, allowed_toxid_obj);
  1270. break;
  1271. case 'I':
  1272. tox_id_path = optarg;
  1273. break;
  1274. case 'C':
  1275. /* Config directory */
  1276. strncpy(config_path, optarg, sizeof(config_path) - 1);
  1277. if(optarg[strlen(optarg) - 1] != '/')
  1278. {
  1279. int optarg_len = strlen(optarg);
  1280. config_path[optarg_len] = '/';
  1281. config_path[optarg_len + 1] = '\0';
  1282. }
  1283. load_saved_toxid_in_client_mode = 1;
  1284. break;
  1285. case 'f':
  1286. strncpy(rules_file, optarg, sizeof(rules_file) - 1);
  1287. rules_policy = VALIDATE;
  1288. log_printf(L_INFO, "Filter policy set to VALIDATE\n");
  1289. break;
  1290. case 's':
  1291. /* Shared secret */
  1292. use_shared_secret = 1;
  1293. memset(shared_secret, 0, TOX_MAX_FRIEND_REQUEST_LENGTH);
  1294. strncpy(shared_secret, optarg, TOX_MAX_FRIEND_REQUEST_LENGTH-1);
  1295. break;
  1296. case 'd':
  1297. if(min_log_level == L_DEBUG2)
  1298. {
  1299. log_tox_trace = 1;
  1300. }
  1301. if(min_log_level != L_DEBUG && min_log_level != L_DEBUG2)
  1302. {
  1303. min_log_level = L_DEBUG;
  1304. }
  1305. else
  1306. {
  1307. min_log_level = L_DEBUG2;
  1308. }
  1309. break;
  1310. case 'q':
  1311. min_log_level = L_ERROR;
  1312. break;
  1313. case 'S':
  1314. use_syslog = 1;
  1315. break;
  1316. case 'D':
  1317. daemonize = 1;
  1318. use_syslog = 1;
  1319. break;
  1320. case 'F':
  1321. pidfile = optarg;
  1322. break;
  1323. case 'U':
  1324. daemon_username = optarg;
  1325. break;
  1326. case 't':
  1327. errno = 0;
  1328. tcp_relay_port = strtol(optarg, NULL, 10);
  1329. if(errno != 0 || tcp_relay_port < 0 || tcp_relay_port > 65535)
  1330. {
  1331. tcp_relay_port = 1024 + (rand() % 64511);
  1332. log_printf(L_WARNING, "Ignored -t %s: TCP port number needs to be a number between 0 and 65535.");
  1333. }
  1334. break;
  1335. case 'u':
  1336. { /* TODO make a function in util.h */
  1337. char *sport;
  1338. char *eport;
  1339. sport = strtok(optarg, ":");
  1340. eport = strtok(NULL, ":");
  1341. if(!sport || !eport)
  1342. {
  1343. log_printf(L_WARNING, "Ignored -u %s: wrong format");
  1344. }
  1345. else
  1346. {
  1347. errno = 0;
  1348. udp_start_port = strtol(sport, NULL, 10);
  1349. udp_end_port = strtol(eport, NULL, 10);
  1350. if(errno != 0 || udp_start_port < 1 || udp_start_port > 65535 || \
  1351. udp_end_port < 1 || udp_end_port > 65535)
  1352. {
  1353. log_printf(L_WARNING, "Ignored -u %s: ports need to be integers between 1 and 65535");
  1354. udp_start_port = 1024 + (rand() % 64500);
  1355. udp_end_port = udp_start_port + 10;
  1356. }
  1357. }
  1358. }
  1359. break;
  1360. case 'b':
  1361. strncpy(boot_json, optarg, sizeof(boot_json) - 1);
  1362. break;
  1363. case 'V':
  1364. print_version_stdout();
  1365. exit(0);
  1366. case '?':
  1367. case 'h':
  1368. default:
  1369. print_version();
  1370. help();
  1371. exit(1);
  1372. }
  1373. }
  1374. if(!client_mode && min_log_level == L_UNSET)
  1375. {
  1376. min_log_level = L_INFO;
  1377. }
  1378. if(!client_mode && server_whitelist_mode)
  1379. {
  1380. log_printf(L_INFO, "Server in ToxID whitelisting mode - only clients listed with -i can connect");
  1381. }
  1382. if((!client_mode) && (rules_policy != NONE))
  1383. {
  1384. load_rules();
  1385. }
  1386. /* If shared secret has not been provided via -s, read from TUNTOX_SHARED_SECRET env variable */
  1387. if(!use_shared_secret)
  1388. {
  1389. if(getenv("TUNTOX_SHARED_SECRET") != NULL)
  1390. {
  1391. use_shared_secret = 1;
  1392. memset(shared_secret, 0, TOX_MAX_FRIEND_REQUEST_LENGTH);
  1393. strncpy(shared_secret, getenv("TUNTOX_SHARED_SECRET"), TOX_MAX_FRIEND_REQUEST_LENGTH-1);
  1394. }
  1395. }
  1396. if(daemonize)
  1397. {
  1398. do_daemonize();
  1399. }
  1400. atexit(cleanup);
  1401. print_version();
  1402. /* Bootstrap tox */
  1403. tox_options_default(&tox_options);
  1404. if(min_log_level >= L_DEBUG2)
  1405. {
  1406. tox_options.log_callback = on_tox_log;
  1407. }
  1408. tox_options.udp_enabled = 1;
  1409. tox_options.local_discovery_enabled = 1;
  1410. tox_options.tcp_port = tcp_relay_port;
  1411. tox_options.start_port = udp_start_port;
  1412. tox_options.end_port = udp_end_port;
  1413. tox_options.hole_punching_enabled = 1;
  1414. parse_all_proxy(&tox_options);
  1415. log_printf(L_INFO, "Using %d for TCP relay port and %d-%d for UDP",
  1416. tox_options.tcp_port,
  1417. tox_options.start_port,
  1418. tox_options.end_port
  1419. );
  1420. if((!client_mode) || load_saved_toxid_in_client_mode)
  1421. {
  1422. save_size = load_save(&save_data);
  1423. if(save_data && save_size)
  1424. {
  1425. tox_options.savedata_type = TOX_SAVEDATA_TYPE_TOX_SAVE;
  1426. tox_options.savedata_data = save_data;
  1427. tox_options.savedata_length = save_size;
  1428. }
  1429. }
  1430. tox = tox_new(&tox_options, &tox_new_err);
  1431. if(tox == NULL)
  1432. {
  1433. log_printf(L_DEBUG, "tox_new() failed (%u) - trying without IPv6\n", tox_new_err);
  1434. if(!tox_options.ipv6_enabled || (tox_options.ipv6_enabled = 0, (tox = tox_new(&tox_options, &tox_new_err)) == NULL))
  1435. {
  1436. log_printf(L_DEBUG, "tox_new() failed (%u) - trying with Tor\n", tox_new_err);
  1437. if((tox_options.proxy_type = TOX_PROXY_TYPE_SOCKS5, tox_options.proxy_host="127.0.0.1", tox_options.proxy_port=9050, (tox = tox_new(&tox_options, &tox_new_err)) == NULL))
  1438. {
  1439. log_printf(L_ERROR, "tox_new() failed (%u) - exiting\n", tox_new_err);
  1440. exit(1);
  1441. }
  1442. }
  1443. }
  1444. if(save_size && save_data)
  1445. {
  1446. free(save_data);
  1447. }
  1448. set_tox_username(tox);
  1449. tox_callback_self_connection_status(tox, handle_connection_status_change);
  1450. do_bootstrap(tox);
  1451. do_bootstrap_file(tox, boot_json);
  1452. if(client_mode)
  1453. {
  1454. uint8_t dht_key[TOX_PUBLIC_KEY_SIZE];
  1455. char_t readable_dht_key[2 * TOX_PUBLIC_KEY_SIZE + 1];
  1456. tox_self_get_address(tox, tox_id);
  1457. id_to_string(tox_printable_id, tox_id);
  1458. tox_printable_id[TOX_ADDRESS_SIZE * 2] = '\0';
  1459. log_printf(L_DEBUG, "Generated Tox ID: %s\n", tox_printable_id);
  1460. if(tox_id_path)
  1461. {
  1462. save_printable_tox_id(tox_printable_id, tox_id_path);
  1463. }
  1464. tox_self_get_dht_id(tox, dht_key);
  1465. to_hex(readable_dht_key, dht_key, TOX_PUBLIC_KEY_SIZE);
  1466. log_printf(L_DEBUG, "DHT key: %s\n", readable_dht_key);
  1467. if(!remote_tox_id)
  1468. {
  1469. log_printf(L_ERROR, "Tox id is required in client mode. Use -i 58435984ABCDEF475...\n");
  1470. exit(1);
  1471. }
  1472. do_client_loop(remote_tox_id);
  1473. }
  1474. else
  1475. {
  1476. uint8_t dht_key[TOX_PUBLIC_KEY_SIZE];
  1477. char_t readable_dht_key[2 * TOX_PUBLIC_KEY_SIZE + 1];
  1478. write_save(tox);
  1479. if(!use_shared_secret)
  1480. {
  1481. log_printf(L_WARNING, "Shared secret authentication is not used - skilled attackers may connect to your tuntox server");
  1482. }
  1483. tox_self_get_address(tox, tox_id);
  1484. memset(tox_printable_id, '\0', sizeof(tox_printable_id));
  1485. id_to_string(tox_printable_id, tox_id);
  1486. tox_printable_id[TOX_ADDRESS_SIZE * 2] = '\0';
  1487. log_printf(L_INFO, "Using Tox ID: %s\n", tox_printable_id);
  1488. if(tox_id_path)
  1489. {
  1490. save_printable_tox_id(tox_printable_id, tox_id_path);
  1491. }
  1492. tox_self_get_dht_id(tox, dht_key);
  1493. to_hex(readable_dht_key, dht_key, TOX_PUBLIC_KEY_SIZE);
  1494. log_printf(L_DEBUG, "DHT key: %s\n", readable_dht_key);
  1495. tox_callback_friend_request(tox, accept_friend_request);
  1496. do_server_loop();
  1497. clear_rules();
  1498. }
  1499. return 0;
  1500. }