main.c 44 KB

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