uclient.c 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714
  1. /*
  2. * Copyright (C) 2011, 2012, 2013 Citrix Systems
  3. *
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions
  8. * are met:
  9. * 1. Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. * 2. Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. * 3. Neither the name of the project nor the names of its contributors
  15. * may be used to endorse or promote products derived from this software
  16. * without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
  19. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  20. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  21. * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
  22. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  23. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  24. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  25. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  26. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  27. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  28. * SUCH DAMAGE.
  29. */
  30. #include "apputils.h"
  31. #include "uclient.h"
  32. #include "startuclient.h"
  33. #include "ns_turn_utils.h"
  34. #include "session.h"
  35. #include <unistd.h>
  36. #include <time.h>
  37. #include <openssl/err.h>
  38. #include <openssl/rand.h>
  39. #include <sys/select.h>
  40. static int verbose_packets=0;
  41. static size_t current_clients_number = 0;
  42. static int start_full_timer=0;
  43. static u32bits tot_messages=0;
  44. static u32bits tot_send_messages=0;
  45. static u64bits tot_send_bytes = 0;
  46. static u32bits tot_recv_messages=0;
  47. static u64bits tot_recv_bytes = 0;
  48. static u64bits tot_send_dropped = 0;
  49. struct event_base* client_event_base=NULL;
  50. static int client_write(app_ur_session *elem);
  51. static int client_shutdown(app_ur_session *elem);
  52. static u64bits current_time = 0;
  53. static u64bits current_mstime = 0;
  54. static char buffer_to_send[65536]="\0";
  55. static int total_clients = 0;
  56. /* Patch for unlimited number of clients provided by [email protected] */
  57. static app_ur_session** elems = NULL;
  58. #define SLEEP_INTERVAL (234)
  59. #define MAX_LISTENING_CYCLE_NUMBER (7)
  60. int RTP_PACKET_INTERVAL = 20;
  61. static inline s64bits time_minus(u64bits t1, u64bits t2) {
  62. return ( (s64bits)t1 - (s64bits)t2 );
  63. }
  64. static u64bits total_loss = 0;
  65. static u64bits total_jitter = 0;
  66. static u64bits total_latency = 0;
  67. static u64bits min_latency = 0xFFFFFFFF;
  68. static u64bits max_latency = 0;
  69. static u64bits min_jitter = 0xFFFFFFFF;
  70. static u64bits max_jitter = 0;
  71. static int show_statistics = 0;
  72. ///////////////////////////////////////////////////////////////////////////////
  73. static void __turn_getMSTime(void) {
  74. static u64bits start_sec = 0;
  75. struct timespec tp={0,0};
  76. #if defined(CLOCK_REALTIME)
  77. clock_gettime(CLOCK_REALTIME, &tp);
  78. #else
  79. tp.tv_sec = time(NULL);
  80. #endif
  81. if(!start_sec)
  82. start_sec = tp.tv_sec;
  83. if(current_time != (u64bits)((u64bits)(tp.tv_sec)-start_sec))
  84. show_statistics = 1;
  85. current_time = (u64bits)((u64bits)(tp.tv_sec)-start_sec);
  86. current_mstime = (u64bits)((current_time * 1000) + (tp.tv_nsec/1000000));
  87. }
  88. ////////////////////////////////////////////////////////////////////
  89. static int refresh_channel(app_ur_session* elem, u16bits method, uint32_t lt);
  90. //////////////////////// SS ////////////////////////////////////////
  91. static app_ur_session* init_app_session(app_ur_session *ss) {
  92. if(ss) {
  93. ns_bzero(ss,sizeof(app_ur_session));
  94. ss->pinfo.fd=-1;
  95. }
  96. return ss;
  97. }
  98. static app_ur_session* create_new_ss(void)
  99. {
  100. ++current_clients_number;
  101. return init_app_session((app_ur_session*) turn_malloc(sizeof(app_ur_session)));
  102. }
  103. static void uc_delete_session_elem_data(app_ur_session* cdi) {
  104. if(cdi) {
  105. EVENT_DEL(cdi->input_ev);
  106. EVENT_DEL(cdi->input_tcp_data_ev);
  107. if(cdi->pinfo.tcp_conn) {
  108. int i = 0;
  109. for(i=0;i<(int)(cdi->pinfo.tcp_conn_number);++i) {
  110. if(cdi->pinfo.tcp_conn[i]) {
  111. if(cdi->pinfo.tcp_conn[i]->tcp_data_ssl && !(cdi->pinfo.broken)) {
  112. if(!(SSL_get_shutdown(cdi->pinfo.tcp_conn[i]->tcp_data_ssl) & SSL_SENT_SHUTDOWN)) {
  113. SSL_set_shutdown(cdi->pinfo.tcp_conn[i]->tcp_data_ssl, SSL_RECEIVED_SHUTDOWN);
  114. SSL_shutdown(cdi->pinfo.tcp_conn[i]->tcp_data_ssl);
  115. }
  116. if(cdi->pinfo.tcp_conn[i]->tcp_data_ssl) {
  117. SSL_FREE(cdi->pinfo.tcp_conn[i]->tcp_data_ssl);
  118. }
  119. if(cdi->pinfo.tcp_conn[i]->tcp_data_fd>=0) {
  120. socket_closesocket(cdi->pinfo.tcp_conn[i]->tcp_data_fd);
  121. cdi->pinfo.tcp_conn[i]->tcp_data_fd=-1;
  122. }
  123. turn_free(cdi->pinfo.tcp_conn[i], 111);
  124. cdi->pinfo.tcp_conn[i]=NULL;
  125. }
  126. }
  127. }
  128. cdi->pinfo.tcp_conn_number=0;
  129. if(cdi->pinfo.tcp_conn) {
  130. turn_free(cdi->pinfo.tcp_conn, 111);
  131. cdi->pinfo.tcp_conn=NULL;
  132. }
  133. }
  134. if(cdi->pinfo.ssl && !(cdi->pinfo.broken)) {
  135. if(!(SSL_get_shutdown(cdi->pinfo.ssl) & SSL_SENT_SHUTDOWN)) {
  136. SSL_set_shutdown(cdi->pinfo.ssl, SSL_RECEIVED_SHUTDOWN);
  137. SSL_shutdown(cdi->pinfo.ssl);
  138. }
  139. }
  140. if(cdi->pinfo.ssl) {
  141. SSL_FREE(cdi->pinfo.ssl);
  142. }
  143. if(cdi->pinfo.fd>=0) {
  144. socket_closesocket(cdi->pinfo.fd);
  145. }
  146. cdi->pinfo.fd=-1;
  147. }
  148. }
  149. static int remove_all_from_ss(app_ur_session* ss)
  150. {
  151. if (ss) {
  152. uc_delete_session_elem_data(ss);
  153. --current_clients_number;
  154. }
  155. return 0;
  156. }
  157. ///////////////////////////////////////////////////////////////////////////////
  158. int send_buffer(app_ur_conn_info *clnet_info, stun_buffer* message, int data_connection, app_tcp_conn_info *atc)
  159. {
  160. int rc = 0;
  161. int ret = -1;
  162. char *buffer = (char*) (message->buf);
  163. if(negative_protocol_test && (message->len>0)) {
  164. if(random()%10 == 0) {
  165. int np = (int)((unsigned long)random()%10);
  166. while(np-->0) {
  167. int pos = (int)((unsigned long)random()%(unsigned long)message->len);
  168. int val = (int)((unsigned long)random()%256);
  169. message->buf[pos]=(u08bits)val;
  170. }
  171. }
  172. }
  173. SSL *ssl = clnet_info->ssl;
  174. ioa_socket_raw fd = clnet_info->fd;
  175. if(data_connection) {
  176. if(atc) {
  177. ssl = atc->tcp_data_ssl;
  178. fd = atc->tcp_data_fd;
  179. } else if(is_TCP_relay()){
  180. TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR,
  181. "trying to send tcp data buffer over unready connection: size=%d\n",(int)(message->len));
  182. return -1;
  183. }
  184. }
  185. if (ssl) {
  186. int message_sent = 0;
  187. while (!message_sent) {
  188. if (SSL_get_shutdown(ssl)) {
  189. return -1;
  190. }
  191. int len = 0;
  192. do {
  193. len = SSL_write(ssl, buffer, (int)message->len);
  194. } while (len < 0 && ((errno == EINTR) || (errno == ENOBUFS)));
  195. if(len == (int)message->len) {
  196. if (clnet_verbose) {
  197. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,
  198. "buffer sent: size=%d\n",len);
  199. }
  200. message_sent = 1;
  201. ret = len;
  202. } else {
  203. switch (SSL_get_error(ssl, len)){
  204. case SSL_ERROR_NONE:
  205. /* Try again ? */
  206. break;
  207. case SSL_ERROR_WANT_WRITE:
  208. /* Just try again later */
  209. break;
  210. case SSL_ERROR_WANT_READ:
  211. /* continue with reading */
  212. break;
  213. case SSL_ERROR_ZERO_RETURN:
  214. /* Try again */
  215. break;
  216. case SSL_ERROR_SYSCALL:
  217. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,"Socket write error 111.666: \n");
  218. if (handle_socket_error())
  219. break;
  220. case SSL_ERROR_SSL:
  221. {
  222. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "SSL write error: \n");
  223. char buf[1024];
  224. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,
  225. "%s (%d)\n",
  226. ERR_error_string(ERR_get_error(),buf),
  227. SSL_get_error(ssl, len));
  228. }
  229. default:
  230. clnet_info->broken = 1;
  231. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,"Unexpected error while writing!\n");
  232. return -1;
  233. }
  234. }
  235. }
  236. } else if (fd >= 0) {
  237. size_t left = (size_t) (message->len);
  238. while (left > 0) {
  239. do {
  240. rc = send(fd, buffer, left, 0);
  241. } while (rc < 0 && ((errno == EINTR) || (errno == ENOBUFS)));
  242. if (rc > 0) {
  243. left -= (size_t) rc;
  244. buffer += rc;
  245. } else {
  246. tot_send_dropped+=1;
  247. break;
  248. }
  249. }
  250. if (left > 0)
  251. return -1;
  252. ret = (int) message->len;
  253. }
  254. return ret;
  255. }
  256. static int wait_fd(int fd, unsigned int cycle) {
  257. if(fd>=(int)FD_SETSIZE) {
  258. return 1;
  259. } else {
  260. fd_set fds;
  261. FD_ZERO(&fds);
  262. FD_SET(fd,&fds);
  263. if(dos && cycle==0)
  264. return 0;
  265. struct timeval start_time;
  266. struct timeval ctime;
  267. gettimeofday(&start_time,NULL);
  268. ctime.tv_sec = start_time.tv_sec;
  269. ctime.tv_usec = start_time.tv_usec;
  270. int rc = 0;
  271. do {
  272. struct timeval timeout = {0,0};
  273. if(cycle == 0) {
  274. timeout.tv_usec = 500000;
  275. } else {
  276. timeout.tv_sec = 1;
  277. while(--cycle) timeout.tv_sec = timeout.tv_sec + timeout.tv_sec;
  278. if(ctime.tv_sec > start_time.tv_sec) {
  279. if(ctime.tv_sec >= start_time.tv_sec + timeout.tv_sec) {
  280. break;
  281. } else {
  282. timeout.tv_sec -= (ctime.tv_sec - start_time.tv_sec);
  283. }
  284. }
  285. }
  286. rc = select(fd+1,&fds,NULL,NULL,&timeout);
  287. if((rc<0) && (errno == EINTR)) {
  288. gettimeofday(&ctime,NULL);
  289. } else {
  290. break;
  291. }
  292. } while(1);
  293. return rc;
  294. }
  295. }
  296. int recv_buffer(app_ur_conn_info *clnet_info, stun_buffer* message, int sync, int data_connection, app_tcp_conn_info *atc, stun_buffer* request_message) {
  297. int rc = 0;
  298. stun_tid tid;
  299. u16bits method = 0;
  300. if(request_message) {
  301. stun_tid_from_message(request_message, &tid);
  302. method = stun_get_method(request_message);
  303. }
  304. ioa_socket_raw fd = clnet_info->fd;
  305. if (atc)
  306. fd = atc->tcp_data_fd;
  307. SSL* ssl = clnet_info->ssl;
  308. if (atc)
  309. ssl = atc->tcp_data_ssl;
  310. recv_again:
  311. if(!use_tcp && sync && request_message && (fd>=0)) {
  312. unsigned int cycle = 0;
  313. while(cycle < MAX_LISTENING_CYCLE_NUMBER) {
  314. int serc = wait_fd(fd,cycle);
  315. if(serc>0)
  316. break;
  317. if(serc<0) {
  318. return -1;
  319. }
  320. if(send_buffer(clnet_info, request_message, data_connection, atc)<=0)
  321. return -1;
  322. ++cycle;
  323. }
  324. }
  325. if (!use_secure && !use_tcp && fd >= 0) {
  326. /* Plain UDP */
  327. do {
  328. rc = recv(fd, message->buf, sizeof(message->buf) - 1, 0);
  329. if (rc < 0 && errno == EAGAIN && sync)
  330. errno = EINTR;
  331. } while (rc < 0 && (errno == EINTR));
  332. if (rc < 0) {
  333. return -1;
  334. }
  335. message->len = rc;
  336. } else if (use_secure && !use_tcp && ssl && !(clnet_info->broken)) {
  337. /* DTLS */
  338. int message_received = 0;
  339. int cycle = 0;
  340. while (!message_received && cycle++ < 100) {
  341. if (SSL_get_shutdown(ssl))
  342. return -1;
  343. rc = 0;
  344. do {
  345. rc = SSL_read(ssl, message->buf, sizeof(message->buf) - 1);
  346. if (rc < 0 && errno == EAGAIN && sync)
  347. continue;
  348. } while (rc < 0 && (errno == EINTR));
  349. if (rc > 0) {
  350. if (clnet_verbose) {
  351. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,
  352. "response received: size=%d\n", rc);
  353. }
  354. message->len = rc;
  355. message_received = 1;
  356. } else {
  357. int sslerr = SSL_get_error(ssl, rc);
  358. switch (sslerr) {
  359. case SSL_ERROR_NONE:
  360. /* Try again ? */
  361. break;
  362. case SSL_ERROR_WANT_WRITE:
  363. /* Just try again later */
  364. break;
  365. case SSL_ERROR_WANT_READ:
  366. /* continue with reading */
  367. break;
  368. case SSL_ERROR_ZERO_RETURN:
  369. /* Try again */
  370. break;
  371. case SSL_ERROR_SYSCALL:
  372. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,
  373. "Socket read error 111.999: \n");
  374. if (handle_socket_error())
  375. break;
  376. case SSL_ERROR_SSL: {
  377. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "SSL write error: \n");
  378. char buf[1024];
  379. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s (%d)\n",
  380. ERR_error_string(ERR_get_error(), buf),
  381. SSL_get_error(ssl, rc));
  382. }
  383. default:
  384. clnet_info->broken = 1;
  385. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,
  386. "Unexpected error while reading: rc=%d, sslerr=%d\n",
  387. rc, sslerr);
  388. return -1;
  389. }
  390. if (!sync)
  391. break;
  392. }
  393. }
  394. } else if (use_secure && use_tcp && ssl && !(clnet_info->broken)) {
  395. /* TLS*/
  396. int message_received = 0;
  397. int cycle = 0;
  398. while (!message_received && cycle++ < 100) {
  399. if (SSL_get_shutdown(ssl))
  400. return -1;
  401. rc = 0;
  402. do {
  403. rc = SSL_read(ssl, message->buf, sizeof(message->buf) - 1);
  404. if (rc < 0 && errno == EAGAIN && sync)
  405. continue;
  406. } while (rc < 0 && (errno == EINTR));
  407. if (rc > 0) {
  408. if (clnet_verbose) {
  409. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,
  410. "response received: size=%d\n", rc);
  411. }
  412. message->len = rc;
  413. message_received = 1;
  414. } else {
  415. int sslerr = SSL_get_error(ssl, rc);
  416. switch (sslerr) {
  417. case SSL_ERROR_NONE:
  418. /* Try again ? */
  419. break;
  420. case SSL_ERROR_WANT_WRITE:
  421. /* Just try again later */
  422. break;
  423. case SSL_ERROR_WANT_READ:
  424. /* continue with reading */
  425. break;
  426. case SSL_ERROR_ZERO_RETURN:
  427. /* Try again */
  428. break;
  429. case SSL_ERROR_SYSCALL:
  430. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,
  431. "Socket read error 111.999: \n");
  432. if (handle_socket_error())
  433. break;
  434. case SSL_ERROR_SSL: {
  435. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "SSL write error: \n");
  436. char buf[1024];
  437. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s (%d)\n",
  438. ERR_error_string(ERR_get_error(), buf),
  439. SSL_get_error(ssl, rc));
  440. }
  441. default:
  442. clnet_info->broken = 1;
  443. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,
  444. "Unexpected error while reading: rc=%d, sslerr=%d\n",
  445. rc, sslerr);
  446. return -1;
  447. }
  448. if (!sync)
  449. break;
  450. }
  451. }
  452. } else if (!use_secure && use_tcp && fd >= 0) {
  453. /* Plain TCP */
  454. do {
  455. rc = recv(fd, message->buf, sizeof(message->buf) - 1, MSG_PEEK);
  456. if ((rc < 0) && (errno == EAGAIN) && sync) {
  457. errno = EINTR;
  458. }
  459. } while (rc < 0 && (errno == EINTR));
  460. if (rc > 0) {
  461. int mlen = rc;
  462. size_t app_msg_len = (size_t) rc;
  463. if (!atc) {
  464. mlen = stun_get_message_len_str(message->buf, rc, 1,
  465. &app_msg_len);
  466. } else {
  467. if (!sync)
  468. mlen = clmessage_length;
  469. if (mlen > clmessage_length)
  470. mlen = clmessage_length;
  471. app_msg_len = (size_t) mlen;
  472. }
  473. if (mlen > 0) {
  474. int rcr = 0;
  475. int rsf = 0;
  476. int cycle = 0;
  477. while (rsf < mlen && cycle++ < 128) {
  478. do {
  479. rcr = recv(fd, message->buf + rsf,
  480. (size_t) mlen - (size_t) rsf, 0);
  481. if (rcr < 0 && errno == EAGAIN && sync)
  482. errno = EINTR;
  483. } while (rcr < 0 && (errno == EINTR));
  484. if (rcr > 0)
  485. rsf += rcr;
  486. }
  487. if (rsf < 1)
  488. return -1;
  489. if (rsf < (int) app_msg_len) {
  490. if ((size_t) (app_msg_len / (size_t) rsf) * ((size_t) (rsf))
  491. != app_msg_len) {
  492. return -1;
  493. }
  494. }
  495. message->len = app_msg_len;
  496. rc = app_msg_len;
  497. } else {
  498. rc = 0;
  499. }
  500. }
  501. }
  502. if(rc>0) {
  503. if(request_message) {
  504. stun_tid recv_tid;
  505. u16bits recv_method = 0;
  506. stun_tid_from_message(message, &recv_tid);
  507. recv_method = stun_get_method(message);
  508. if(method != recv_method) {
  509. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Received wrong response method: 0x%x, expected 0x%x; trying again...\n",(unsigned int)recv_method,(unsigned int)method);
  510. goto recv_again;
  511. }
  512. if(memcmp(tid.tsx_id,recv_tid.tsx_id,STUN_TID_SIZE)) {
  513. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Received wrong response tid; trying again...\n");
  514. goto recv_again;
  515. }
  516. }
  517. }
  518. return rc;
  519. }
  520. static int client_read(app_ur_session *elem, int is_tcp_data, app_tcp_conn_info *atc) {
  521. if (!elem)
  522. return -1;
  523. if (elem->state != UR_STATE_READY)
  524. return -1;
  525. elem->ctime = current_time;
  526. app_ur_conn_info *clnet_info = &(elem->pinfo);
  527. int err_code = 0;
  528. u08bits err_msg[129];
  529. int rc = 0;
  530. int applen = 0;
  531. if (clnet_verbose && verbose_packets) {
  532. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "before read ...\n");
  533. }
  534. rc = recv_buffer(clnet_info, &(elem->in_buffer), 0, is_tcp_data, atc, NULL);
  535. if (clnet_verbose && verbose_packets) {
  536. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "read %d bytes\n", (int) rc);
  537. }
  538. if (rc > 0) {
  539. elem->in_buffer.len = rc;
  540. uint16_t chnumber = 0;
  541. const message_info *mi = NULL;
  542. size_t buffers = 1;
  543. if(is_tcp_data) {
  544. if ((int)elem->in_buffer.len == clmessage_length) {
  545. mi = (message_info*)(elem->in_buffer.buf);
  546. }
  547. } else if (stun_is_indication(&(elem->in_buffer))) {
  548. uint16_t method = stun_get_method(&elem->in_buffer);
  549. if((method == STUN_METHOD_CONNECTION_ATTEMPT)&& is_TCP_relay()) {
  550. stun_attr_ref sar = stun_attr_get_first(&(elem->in_buffer));
  551. u32bits cid = 0;
  552. while(sar) {
  553. int attr_type = stun_attr_get_type(sar);
  554. if(attr_type == STUN_ATTRIBUTE_CONNECTION_ID) {
  555. cid = *((const u32bits*)stun_attr_get_value(sar));
  556. break;
  557. }
  558. sar = stun_attr_get_next_str(elem->in_buffer.buf,elem->in_buffer.len,sar);
  559. }
  560. if(negative_test) {
  561. tcp_data_connect(elem,(u64bits)random());
  562. } else {
  563. /* positive test */
  564. tcp_data_connect(elem,cid);
  565. }
  566. return rc;
  567. } else if (method != STUN_METHOD_DATA) {
  568. TURN_LOG_FUNC(
  569. TURN_LOG_LEVEL_INFO,
  570. "ERROR: received indication message has wrong method: 0x%x\n",
  571. (int) method);
  572. return rc;
  573. } else {
  574. stun_attr_ref sar = stun_attr_get_first_by_type(&(elem->in_buffer), STUN_ATTRIBUTE_DATA);
  575. if (!sar) {
  576. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "ERROR: received DATA message has no data, size=%d\n", rc);
  577. return rc;
  578. }
  579. int rlen = stun_attr_get_len(sar);
  580. applen = rlen;
  581. if (rlen != clmessage_length) {
  582. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "ERROR: received DATA message has wrong len: %d, must be %d\n", rlen, clmessage_length);
  583. tot_recv_bytes += applen;
  584. return rc;
  585. }
  586. const u08bits* data = stun_attr_get_value(sar);
  587. mi = (const message_info*) data;
  588. }
  589. } else if (stun_is_success_response(&(elem->in_buffer))) {
  590. if(elem->pinfo.nonce[0]) {
  591. if(check_integrity(&(elem->pinfo), &(elem->in_buffer))<0)
  592. return -1;
  593. }
  594. if(is_TCP_relay() && (stun_get_method(&(elem->in_buffer)) == STUN_METHOD_CONNECT)) {
  595. stun_attr_ref sar = stun_attr_get_first(&(elem->in_buffer));
  596. u32bits cid = 0;
  597. while(sar) {
  598. int attr_type = stun_attr_get_type(sar);
  599. if(attr_type == STUN_ATTRIBUTE_CONNECTION_ID) {
  600. cid = *((const u32bits*)stun_attr_get_value(sar));
  601. break;
  602. }
  603. sar = stun_attr_get_next_str(elem->in_buffer.buf,elem->in_buffer.len,sar);
  604. }
  605. tcp_data_connect(elem,cid);
  606. }
  607. return rc;
  608. } else if (stun_is_challenge_response_str(elem->in_buffer.buf, (size_t)elem->in_buffer.len,
  609. &err_code,err_msg,sizeof(err_msg),
  610. clnet_info->realm,clnet_info->nonce,
  611. clnet_info->server_name, &(clnet_info->oauth))) {
  612. if(is_TCP_relay() && (stun_get_method(&(elem->in_buffer)) == STUN_METHOD_CONNECT)) {
  613. turn_tcp_connect(clnet_verbose, &(elem->pinfo), &(elem->pinfo.peer_addr));
  614. } else if(stun_get_method(&(elem->in_buffer)) == STUN_METHOD_REFRESH) {
  615. refresh_channel(elem, stun_get_method(&elem->in_buffer),600);
  616. }
  617. return rc;
  618. } else if (stun_is_error_response(&(elem->in_buffer), NULL,NULL,0)) {
  619. return rc;
  620. } else if (stun_is_channel_message(&(elem->in_buffer), &chnumber, use_tcp)) {
  621. if (elem->chnum != chnumber) {
  622. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,
  623. "ERROR: received message has wrong channel: %d\n",
  624. (int) chnumber);
  625. return rc;
  626. }
  627. if (elem->in_buffer.len >= 4) {
  628. if (((int)(elem->in_buffer.len-4) < clmessage_length) ||
  629. ((int)(elem->in_buffer.len-4) > clmessage_length + 3)) {
  630. TURN_LOG_FUNC(
  631. TURN_LOG_LEVEL_INFO,
  632. "ERROR: received buffer have wrong length: %d, must be %d, len=%d\n",
  633. rc, clmessage_length + 4,(int)elem->in_buffer.len);
  634. return rc;
  635. }
  636. mi = (message_info*)(elem->in_buffer.buf + 4);
  637. applen = elem->in_buffer.len -4;
  638. }
  639. } else {
  640. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,
  641. "ERROR: Unknown message received of size: %d\n",(int)(elem->in_buffer.len));
  642. return rc;
  643. }
  644. if(mi) {
  645. /*
  646. printf("%s: 111.111: msgnum=%d, rmsgnum=%d, sent=%lu, recv=%lu\n",__FUNCTION__,
  647. mi->msgnum,elem->recvmsgnum,(unsigned long)mi->mstime,(unsigned long)current_mstime);
  648. */
  649. if(mi->msgnum != elem->recvmsgnum+1)
  650. ++(elem->loss);
  651. else {
  652. u64bits clatency = (u64bits)time_minus(current_mstime,mi->mstime);
  653. if(clatency>max_latency)
  654. max_latency = clatency;
  655. if(clatency<min_latency)
  656. min_latency = clatency;
  657. elem->latency += clatency;
  658. if(elem->rmsgnum>0) {
  659. u64bits cjitter = abs((int)(current_mstime-elem->recvtimems)-RTP_PACKET_INTERVAL);
  660. if(cjitter>max_jitter)
  661. max_jitter = cjitter;
  662. if(cjitter<min_jitter)
  663. min_jitter = cjitter;
  664. elem->jitter += cjitter;
  665. }
  666. }
  667. elem->recvmsgnum = mi->msgnum;
  668. }
  669. elem->rmsgnum+=buffers;
  670. tot_recv_messages+=buffers;
  671. if(applen > 0)
  672. tot_recv_bytes += applen;
  673. else
  674. tot_recv_bytes += elem->in_buffer.len;
  675. elem->recvtimems=current_mstime;
  676. elem->wait_cycles = 0;
  677. } else if(rc == 0) {
  678. return 0;
  679. } else {
  680. return -1;
  681. }
  682. return rc;
  683. }
  684. static int client_shutdown(app_ur_session *elem) {
  685. if(!elem) return -1;
  686. elem->state=UR_STATE_DONE;
  687. elem->ctime=current_time;
  688. remove_all_from_ss(elem);
  689. if (clnet_verbose)
  690. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,"done, connection 0x%lx closed.\n",(long)elem);
  691. return 0;
  692. }
  693. static int client_write(app_ur_session *elem) {
  694. if(!elem) return -1;
  695. if(elem->state!=UR_STATE_READY) return -1;
  696. elem->ctime=current_time;
  697. message_info *mi = (message_info*)buffer_to_send;
  698. mi->msgnum=elem->wmsgnum;
  699. mi->mstime=current_mstime;
  700. app_tcp_conn_info *atc=NULL;
  701. if (is_TCP_relay()) {
  702. memcpy(elem->out_buffer.buf, buffer_to_send, clmessage_length);
  703. elem->out_buffer.len = clmessage_length;
  704. if(elem->pinfo.is_peer) {
  705. if(send(elem->pinfo.fd, elem->out_buffer.buf, clmessage_length, 0)>=0) {
  706. ++elem->wmsgnum;
  707. elem->to_send_timems += RTP_PACKET_INTERVAL;
  708. tot_send_messages++;
  709. tot_send_bytes += clmessage_length;
  710. }
  711. return 0;
  712. }
  713. if (!(elem->pinfo.tcp_conn) || !(elem->pinfo.tcp_conn_number)) {
  714. return -1;
  715. }
  716. int i = (unsigned int)(random()) % elem->pinfo.tcp_conn_number;
  717. atc = elem->pinfo.tcp_conn[i];
  718. if(!atc->tcp_data_bound) {
  719. printf("%s: Uninitialized atc: i=%d, atc=0x%lx\n",__FUNCTION__,i,(long)atc);
  720. return -1;
  721. }
  722. } else if(!do_not_use_channel) {
  723. /* Let's always do padding: */
  724. stun_init_channel_message(elem->chnum, &(elem->out_buffer), clmessage_length, mandatory_channel_padding || use_tcp);
  725. memcpy(elem->out_buffer.buf+4,buffer_to_send,clmessage_length);
  726. } else {
  727. stun_init_indication(STUN_METHOD_SEND, &(elem->out_buffer));
  728. stun_attr_add(&(elem->out_buffer), STUN_ATTRIBUTE_DATA, buffer_to_send, clmessage_length);
  729. stun_attr_add_addr(&(elem->out_buffer),STUN_ATTRIBUTE_XOR_PEER_ADDRESS, &(elem->pinfo.peer_addr));
  730. if(dont_fragment)
  731. stun_attr_add(&(elem->out_buffer), STUN_ATTRIBUTE_DONT_FRAGMENT, NULL, 0);
  732. if(use_fingerprints)
  733. stun_attr_add_fingerprint_str(elem->out_buffer.buf,(size_t*)&(elem->out_buffer.len));
  734. }
  735. if (elem->out_buffer.len > 0) {
  736. if (clnet_verbose && verbose_packets) {
  737. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "before write ...\n");
  738. }
  739. int rc=send_buffer(&(elem->pinfo),&(elem->out_buffer),1,atc);
  740. ++elem->wmsgnum;
  741. elem->to_send_timems += RTP_PACKET_INTERVAL;
  742. if(rc >= 0) {
  743. if (clnet_verbose && verbose_packets) {
  744. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "wrote %d bytes\n", (int) rc);
  745. }
  746. tot_send_messages++;
  747. tot_send_bytes += clmessage_length;
  748. } else {
  749. return -1;
  750. }
  751. }
  752. return 0;
  753. }
  754. void client_input_handler(evutil_socket_t fd, short what, void* arg) {
  755. if(!(what&EV_READ)||!arg) return;
  756. UNUSED_ARG(fd);
  757. app_ur_session* elem = (app_ur_session*)arg;
  758. if(!elem) {
  759. return;
  760. }
  761. switch(elem->state) {
  762. case UR_STATE_READY:
  763. do {
  764. app_tcp_conn_info *atc = NULL;
  765. int is_tcp_data = 0;
  766. if(elem->pinfo.tcp_conn) {
  767. int i = 0;
  768. for(i=0;i<(int)(elem->pinfo.tcp_conn_number);++i) {
  769. if(elem->pinfo.tcp_conn[i]) {
  770. if((fd==elem->pinfo.tcp_conn[i]->tcp_data_fd) && (elem->pinfo.tcp_conn[i]->tcp_data_bound)) {
  771. is_tcp_data = 1;
  772. atc = elem->pinfo.tcp_conn[i];
  773. break;
  774. }
  775. }
  776. }
  777. }
  778. int rc = client_read(elem, is_tcp_data, atc);
  779. if(rc<=0) break;
  780. } while(1);
  781. break;
  782. default:
  783. ;
  784. }
  785. }
  786. static void run_events(int short_burst)
  787. {
  788. struct timeval timeout;
  789. if(!short_burst) {
  790. timeout.tv_sec = 1;
  791. timeout.tv_usec = 0;
  792. } else {
  793. timeout.tv_sec = 0;
  794. timeout.tv_usec = 100000;
  795. }
  796. event_base_loopexit(client_event_base, &timeout);
  797. event_base_dispatch(client_event_base);
  798. }
  799. ////////////////////// main method /////////////////
  800. static int start_client(const char *remote_address, int port,
  801. const unsigned char* ifname, const char *local_address,
  802. int messagenumber,
  803. int i) {
  804. app_ur_session* ss=create_new_ss();
  805. app_ur_session* ss_rtcp=NULL;
  806. if(!no_rtcp)
  807. ss_rtcp = create_new_ss();
  808. app_ur_conn_info clnet_info_probe; /* for load balancing probe */
  809. ns_bzero(&clnet_info_probe,sizeof(clnet_info_probe));
  810. clnet_info_probe.fd = -1;
  811. app_ur_conn_info *clnet_info=&(ss->pinfo);
  812. app_ur_conn_info *clnet_info_rtcp=NULL;
  813. if(!no_rtcp)
  814. clnet_info_rtcp = &(ss_rtcp->pinfo);
  815. uint16_t chnum=0;
  816. uint16_t chnum_rtcp=0;
  817. start_connection(port, remote_address,
  818. ifname, local_address,
  819. clnet_verbose,
  820. &clnet_info_probe,
  821. clnet_info, &chnum,
  822. clnet_info_rtcp, &chnum_rtcp);
  823. if(clnet_info_probe.ssl) {
  824. SSL_FREE(clnet_info_probe.ssl);
  825. clnet_info_probe.fd = -1;
  826. } else if(clnet_info_probe.fd != -1) {
  827. socket_closesocket(clnet_info_probe.fd);
  828. clnet_info_probe.fd = -1;
  829. }
  830. socket_set_nonblocking(clnet_info->fd);
  831. if(!no_rtcp)
  832. socket_set_nonblocking(clnet_info_rtcp->fd);
  833. struct event* ev = event_new(client_event_base,clnet_info->fd,
  834. EV_READ|EV_PERSIST,client_input_handler,
  835. ss);
  836. event_add(ev,NULL);
  837. struct event* ev_rtcp = NULL;
  838. if(!no_rtcp) {
  839. ev_rtcp = event_new(client_event_base,clnet_info_rtcp->fd,
  840. EV_READ|EV_PERSIST,client_input_handler,
  841. ss_rtcp);
  842. event_add(ev_rtcp,NULL);
  843. }
  844. ss->state=UR_STATE_READY;
  845. ss->input_ev=ev;
  846. ss->tot_msgnum=messagenumber;
  847. ss->recvmsgnum=-1;
  848. ss->chnum=chnum;
  849. if(!no_rtcp) {
  850. ss_rtcp->state=UR_STATE_READY;
  851. ss_rtcp->input_ev=ev_rtcp;
  852. ss_rtcp->tot_msgnum=ss->tot_msgnum;
  853. if(ss_rtcp->tot_msgnum<1) ss_rtcp->tot_msgnum=1;
  854. ss_rtcp->recvmsgnum=-1;
  855. ss_rtcp->chnum=chnum_rtcp;
  856. }
  857. elems[i]=ss;
  858. refresh_channel(ss, 0, 600);
  859. if(!no_rtcp)
  860. elems[i+1]=ss_rtcp;
  861. return 0;
  862. }
  863. static int start_c2c(const char *remote_address, int port,
  864. const unsigned char* ifname, const char *local_address,
  865. int messagenumber,
  866. int i) {
  867. app_ur_session* ss1=create_new_ss();
  868. app_ur_session* ss1_rtcp=NULL;
  869. if(!no_rtcp)
  870. ss1_rtcp = create_new_ss();
  871. app_ur_session* ss2=create_new_ss();
  872. app_ur_session* ss2_rtcp=NULL;
  873. if(!no_rtcp)
  874. ss2_rtcp = create_new_ss();
  875. app_ur_conn_info clnet_info_probe; /* for load balancing probe */
  876. ns_bzero(&clnet_info_probe,sizeof(clnet_info_probe));
  877. clnet_info_probe.fd = -1;
  878. app_ur_conn_info *clnet_info1=&(ss1->pinfo);
  879. app_ur_conn_info *clnet_info1_rtcp=NULL;
  880. if(!no_rtcp)
  881. clnet_info1_rtcp = &(ss1_rtcp->pinfo);
  882. app_ur_conn_info *clnet_info2=&(ss2->pinfo);
  883. app_ur_conn_info *clnet_info2_rtcp=NULL;
  884. if(!no_rtcp)
  885. clnet_info2_rtcp = &(ss2_rtcp->pinfo);
  886. uint16_t chnum1=0;
  887. uint16_t chnum1_rtcp=0;
  888. uint16_t chnum2=0;
  889. uint16_t chnum2_rtcp=0;
  890. start_c2c_connection(port, remote_address,
  891. ifname, local_address,
  892. clnet_verbose,
  893. &clnet_info_probe,
  894. clnet_info1, &chnum1,
  895. clnet_info1_rtcp, &chnum1_rtcp,
  896. clnet_info2, &chnum2,
  897. clnet_info2_rtcp, &chnum2_rtcp);
  898. if(clnet_info_probe.ssl) {
  899. SSL_FREE(clnet_info_probe.ssl);
  900. clnet_info_probe.fd = -1;
  901. } else if(clnet_info_probe.fd != -1) {
  902. socket_closesocket(clnet_info_probe.fd);
  903. clnet_info_probe.fd = -1;
  904. }
  905. socket_set_nonblocking(clnet_info1->fd);
  906. if(!no_rtcp)
  907. socket_set_nonblocking(clnet_info1_rtcp->fd);
  908. socket_set_nonblocking(clnet_info2->fd);
  909. if(!no_rtcp)
  910. socket_set_nonblocking(clnet_info2_rtcp->fd);
  911. struct event* ev1 = event_new(client_event_base,clnet_info1->fd,
  912. EV_READ|EV_PERSIST,client_input_handler,
  913. ss1);
  914. event_add(ev1,NULL);
  915. struct event* ev1_rtcp = NULL;
  916. if(!no_rtcp) {
  917. ev1_rtcp = event_new(client_event_base,clnet_info1_rtcp->fd,
  918. EV_READ|EV_PERSIST,client_input_handler,
  919. ss1_rtcp);
  920. event_add(ev1_rtcp,NULL);
  921. }
  922. struct event* ev2 = event_new(client_event_base,clnet_info2->fd,
  923. EV_READ|EV_PERSIST,client_input_handler,
  924. ss2);
  925. event_add(ev2,NULL);
  926. struct event* ev2_rtcp = NULL;
  927. if(!no_rtcp) {
  928. ev2_rtcp = event_new(client_event_base,clnet_info2_rtcp->fd,
  929. EV_READ|EV_PERSIST,client_input_handler,
  930. ss2_rtcp);
  931. event_add(ev2_rtcp,NULL);
  932. }
  933. ss1->state=UR_STATE_READY;
  934. ss1->input_ev=ev1;
  935. ss1->tot_msgnum=messagenumber;
  936. ss1->recvmsgnum=-1;
  937. ss1->chnum=chnum1;
  938. if(!no_rtcp) {
  939. ss1_rtcp->state=UR_STATE_READY;
  940. ss1_rtcp->input_ev=ev1_rtcp;
  941. ss1_rtcp->tot_msgnum=ss1->tot_msgnum;
  942. if(ss1_rtcp->tot_msgnum<1) ss1_rtcp->tot_msgnum=1;
  943. ss1_rtcp->recvmsgnum=-1;
  944. ss1_rtcp->chnum=chnum1_rtcp;
  945. }
  946. ss2->state=UR_STATE_READY;
  947. ss2->input_ev=ev2;
  948. ss2->tot_msgnum=ss1->tot_msgnum;
  949. ss2->recvmsgnum=-1;
  950. ss2->chnum=chnum2;
  951. if(!no_rtcp) {
  952. ss2_rtcp->state=UR_STATE_READY;
  953. ss2_rtcp->input_ev=ev2_rtcp;
  954. ss2_rtcp->tot_msgnum=ss1_rtcp->tot_msgnum;
  955. ss2_rtcp->recvmsgnum=-1;
  956. ss2_rtcp->chnum=chnum2_rtcp;
  957. }
  958. elems[i++]=ss1;
  959. if(!no_rtcp)
  960. elems[i++]=ss1_rtcp;
  961. elems[i++]=ss2;
  962. if(!no_rtcp)
  963. elems[i++]=ss2_rtcp;
  964. return 0;
  965. }
  966. static int refresh_channel(app_ur_session* elem, u16bits method, uint32_t lt)
  967. {
  968. stun_buffer message;
  969. app_ur_conn_info *clnet_info = &(elem->pinfo);
  970. if(clnet_info->is_peer)
  971. return 0;
  972. if (!method || (method == STUN_METHOD_REFRESH)) {
  973. stun_init_request(STUN_METHOD_REFRESH, &message);
  974. lt = htonl(lt);
  975. stun_attr_add(&message, STUN_ATTRIBUTE_LIFETIME, (const char*) &lt, 4);
  976. if(dual_allocation && !mobility) {
  977. int t = ((u08bits)random())%3;
  978. if(t) {
  979. u08bits field[4];
  980. field[0] = (t==1) ? (u08bits)STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV4 : (u08bits)STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV6;
  981. field[1]=0;
  982. field[2]=0;
  983. field[3]=0;
  984. stun_attr_add(&message, STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY, (const char*) field, 4);
  985. }
  986. }
  987. add_origin(&message);
  988. if(add_integrity(clnet_info, &message)<0) return -1;
  989. if(use_fingerprints)
  990. stun_attr_add_fingerprint_str(message.buf, (size_t*) &(message.len));
  991. send_buffer(clnet_info, &message, 0,0);
  992. }
  993. if (lt && !addr_any(&(elem->pinfo.peer_addr))) {
  994. if(!no_permissions) {
  995. if (!method || (method == STUN_METHOD_CREATE_PERMISSION)) {
  996. stun_init_request(STUN_METHOD_CREATE_PERMISSION, &message);
  997. stun_attr_add_addr(&message, STUN_ATTRIBUTE_XOR_PEER_ADDRESS, &(elem->pinfo.peer_addr));
  998. add_origin(&message);
  999. if(add_integrity(clnet_info, &message)<0) return -1;
  1000. if(use_fingerprints)
  1001. stun_attr_add_fingerprint_str(message.buf, (size_t*) &(message.len));
  1002. send_buffer(&(elem->pinfo), &message, 0,0);
  1003. }
  1004. }
  1005. if (!method || (method == STUN_METHOD_CHANNEL_BIND)) {
  1006. if (STUN_VALID_CHANNEL(elem->chnum)) {
  1007. stun_set_channel_bind_request(&message, &(elem->pinfo.peer_addr), elem->chnum);
  1008. add_origin(&message);
  1009. if(add_integrity(clnet_info, &message)<0) return -1;
  1010. if(use_fingerprints)
  1011. stun_attr_add_fingerprint_str(message.buf, (size_t*) &(message.len));
  1012. send_buffer(&(elem->pinfo), &message,1,0);
  1013. }
  1014. }
  1015. }
  1016. elem->refresh_time = current_mstime + 30*1000;
  1017. return 0;
  1018. }
  1019. static inline int client_timer_handler(app_ur_session* elem, int *done)
  1020. {
  1021. if (elem) {
  1022. if (!turn_time_before(current_mstime, elem->refresh_time)) {
  1023. refresh_channel(elem, 0, 600);
  1024. }
  1025. if(hang_on && elem->completed)
  1026. return 0;
  1027. int max_num = 50;
  1028. int cur_num = 0;
  1029. while (!turn_time_before(current_mstime, elem->to_send_timems)) {
  1030. if(cur_num++>=max_num)
  1031. break;
  1032. if (elem->wmsgnum >= elem->tot_msgnum) {
  1033. if (!turn_time_before(current_mstime, elem->finished_time) ||
  1034. (tot_recv_messages>=tot_messages)) {
  1035. /*
  1036. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,"%s: elem=0x%x: 111.111: c=%d, t=%d, r=%d, w=%d\n",__FUNCTION__,(int)elem,elem->wait_cycles,elem->tot_msgnum,elem->rmsgnum,elem->wmsgnum);
  1037. */
  1038. /*
  1039. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,"%s: 111.222: ly=%llu, ls=%llu, j=%llu\n",__FUNCTION__,
  1040. (unsigned long long)elem->latency,
  1041. (unsigned long long)elem->loss,
  1042. (unsigned long long)elem->jitter);
  1043. */
  1044. total_loss += elem->loss;
  1045. elem->loss=0;
  1046. total_latency += elem->latency;
  1047. elem->latency=0;
  1048. total_jitter += elem->jitter;
  1049. elem->jitter=0;
  1050. elem->completed = 1;
  1051. if (!hang_on) {
  1052. refresh_channel(elem,0,0);
  1053. client_shutdown(elem);
  1054. return 1;
  1055. } else {
  1056. return 0;
  1057. }
  1058. }
  1059. } else {
  1060. *done += 1;
  1061. client_write(elem);
  1062. elem->finished_time = current_mstime + STOPPING_TIME*1000;
  1063. }
  1064. }
  1065. }
  1066. return 0;
  1067. }
  1068. static void timer_handler(evutil_socket_t fd, short event, void *arg)
  1069. {
  1070. UNUSED_ARG(fd);
  1071. UNUSED_ARG(event);
  1072. UNUSED_ARG(arg);
  1073. __turn_getMSTime();
  1074. if(start_full_timer) {
  1075. int i = 0;
  1076. int done = 0;
  1077. for (i = 0; i < total_clients; ++i) {
  1078. if (elems[i]) {
  1079. int finished = client_timer_handler(elems[i], &done);
  1080. if (finished) {
  1081. elems[i] = NULL;
  1082. }
  1083. }
  1084. }
  1085. if(done>5 && (dos || random_disconnect)) {
  1086. for (i = 0; i < total_clients; ++i) {
  1087. if (elems[i]) {
  1088. close(elems[i]->pinfo.fd);
  1089. elems[i]->pinfo.fd = -1;
  1090. }
  1091. }
  1092. }
  1093. }
  1094. }
  1095. void start_mclient(const char *remote_address, int port,
  1096. const unsigned char* ifname, const char *local_address,
  1097. int messagenumber, int mclient) {
  1098. if (mclient < 1)
  1099. mclient = 1;
  1100. total_clients = mclient;
  1101. if(c2c) {
  1102. //mclient must be a multiple of 4:
  1103. if(!no_rtcp)
  1104. mclient += ((4 - (mclient & 0x00000003)) & 0x00000003);
  1105. else if(mclient & 0x1)
  1106. ++mclient;
  1107. } else {
  1108. if(!no_rtcp)
  1109. if(mclient & 0x1)
  1110. ++mclient;
  1111. }
  1112. elems = (app_ur_session**)turn_malloc(sizeof(app_ur_session)*((mclient*2)+1)+sizeof(void*));
  1113. __turn_getMSTime();
  1114. u32bits stime = current_time;
  1115. memset(buffer_to_send, 7, clmessage_length);
  1116. client_event_base = turn_event_base_new();
  1117. int i = 0;
  1118. int tot_clients = 0;
  1119. if(c2c) {
  1120. if(!no_rtcp)
  1121. for (i = 0; i < (mclient >> 2); i++) {
  1122. if(!dos) usleep(SLEEP_INTERVAL);
  1123. if (start_c2c(remote_address, port, ifname, local_address,
  1124. messagenumber, i << 2) < 0) {
  1125. exit(-1);
  1126. }
  1127. tot_clients+=4;
  1128. }
  1129. else
  1130. for (i = 0; i < (mclient >> 1); i++) {
  1131. if(!dos) usleep(SLEEP_INTERVAL);
  1132. if (start_c2c(remote_address, port, ifname, local_address,
  1133. messagenumber, i << 1) < 0) {
  1134. exit(-1);
  1135. }
  1136. tot_clients+=2;
  1137. }
  1138. } else {
  1139. if(!no_rtcp)
  1140. for (i = 0; i < (mclient >> 1); i++) {
  1141. if(!dos) usleep(SLEEP_INTERVAL);
  1142. if (start_client(remote_address, port, ifname, local_address,
  1143. messagenumber, i << 1) < 0) {
  1144. exit(-1);
  1145. }
  1146. tot_clients+=2;
  1147. }
  1148. else
  1149. for (i = 0; i < mclient; i++) {
  1150. if(!dos) usleep(SLEEP_INTERVAL);
  1151. if (start_client(remote_address, port, ifname, local_address,
  1152. messagenumber, i) < 0) {
  1153. exit(-1);
  1154. }
  1155. tot_clients++;
  1156. }
  1157. }
  1158. if(dos)
  1159. _exit(0);
  1160. total_clients = tot_clients;
  1161. __turn_getMSTime();
  1162. struct event *ev = event_new(client_event_base, -1, EV_TIMEOUT|EV_PERSIST, timer_handler, NULL);
  1163. struct timeval tv;
  1164. tv.tv_sec = 0;
  1165. tv.tv_usec = 1000;
  1166. evtimer_add(ev,&tv);
  1167. for(i=0;i<total_clients;i++) {
  1168. if(is_TCP_relay()) {
  1169. if(passive_tcp) {
  1170. if(elems[i]->pinfo.is_peer) {
  1171. int connect_err = 0;
  1172. socket_connect(elems[i]->pinfo.fd, &(elems[i]->pinfo.remote_addr), &connect_err);
  1173. }
  1174. } else {
  1175. int j = 0;
  1176. for(j=i+1;j<total_clients;j++) {
  1177. if (turn_tcp_connect(clnet_verbose, &(elems[i]->pinfo), &(elems[j]->pinfo.relay_addr)) < 0) {
  1178. exit(-1);
  1179. }
  1180. }
  1181. }
  1182. }
  1183. run_events(1);
  1184. }
  1185. __turn_getMSTime();
  1186. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Total connect time is %u\n",
  1187. ((unsigned int) (current_time - stime)));
  1188. stime = current_time;
  1189. if(is_TCP_relay()) {
  1190. u64bits connect_wait_start_time = current_time;
  1191. while(1) {
  1192. int i = 0;
  1193. int completed = 0;
  1194. if(passive_tcp) {
  1195. for(i=0;i<total_clients;++i) {
  1196. if(elems[i]->pinfo.is_peer) {
  1197. completed+=1;
  1198. } else if(elems[i]->pinfo.tcp_conn_number>0 &&
  1199. elems[i]->pinfo.tcp_conn[0]->tcp_data_bound) {
  1200. completed += elems[i]->pinfo.tcp_conn_number;
  1201. }
  1202. }
  1203. if(completed >= total_clients)
  1204. break;
  1205. } else {
  1206. for(i=0;i<total_clients;++i) {
  1207. int j = 0;
  1208. for(j=0;j<(int)elems[i]->pinfo.tcp_conn_number;j++) {
  1209. if(elems[i]->pinfo.tcp_conn[j]->tcp_data_bound) {
  1210. completed++;
  1211. }
  1212. }
  1213. }
  1214. if(completed >= total_clients*(total_clients-1)) {
  1215. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%d connections are completed\n",(int)(completed));
  1216. break;
  1217. }
  1218. }
  1219. run_events(0);
  1220. if(current_time > connect_wait_start_time + STARTING_TCP_RELAY_TIME + total_clients) {
  1221. TURN_LOG_FUNC(TURN_LOG_LEVEL_WARNING, "WARNING: %d connections are completed, not enough\n",
  1222. (int)(completed));
  1223. break;
  1224. }
  1225. }
  1226. }
  1227. __turn_getMSTime();
  1228. stime = current_time;
  1229. for(i=0;i<total_clients;i++) {
  1230. elems[i]->to_send_timems = current_mstime + 1000 + ((u32bits)random())%5000;
  1231. }
  1232. tot_messages = elems[0]->tot_msgnum * total_clients;
  1233. start_full_timer = 1;
  1234. while (1) {
  1235. run_events(1);
  1236. int msz = (int)current_clients_number;
  1237. if (msz < 1) {
  1238. break;
  1239. }
  1240. if(show_statistics) {
  1241. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,
  1242. "%s: msz=%d, tot_send_msgs=%lu, tot_recv_msgs=%lu, tot_send_bytes ~ %llu, tot_recv_bytes ~ %llu\n",
  1243. __FUNCTION__, msz, (unsigned long) tot_send_messages,
  1244. (unsigned long) tot_recv_messages,
  1245. (unsigned long long) tot_send_bytes,
  1246. (unsigned long long) tot_recv_bytes);
  1247. show_statistics=0;
  1248. }
  1249. }
  1250. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,
  1251. "%s: tot_send_msgs=%lu, tot_recv_msgs=%lu\n",
  1252. __FUNCTION__,
  1253. (unsigned long) tot_send_messages,
  1254. (unsigned long) tot_recv_messages);
  1255. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,
  1256. "%s: tot_send_bytes ~ %lu, tot_recv_bytes ~ %lu\n",
  1257. __FUNCTION__,
  1258. (unsigned long) tot_send_bytes,
  1259. (unsigned long) tot_recv_bytes);
  1260. if (client_event_base)
  1261. event_base_free(client_event_base);
  1262. if(tot_send_messages<tot_recv_messages)
  1263. tot_recv_messages=tot_send_messages;
  1264. total_loss = tot_send_messages-tot_recv_messages;
  1265. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Total transmit time is %u\n",
  1266. ((unsigned int)(current_time - stime)));
  1267. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Total lost packets %llu (%f%c), total send dropped %llu (%f%c)\n",
  1268. (unsigned long long)total_loss, (((double)total_loss/(double)tot_send_messages)*100.00),'%',
  1269. (unsigned long long)tot_send_dropped, (((double)tot_send_dropped/(double)(tot_send_messages+tot_send_dropped))*100.00),'%');
  1270. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Average round trip delay %f ms; min = %lu ms, max = %lu ms\n",
  1271. ((double)total_latency/(double)((tot_recv_messages<1) ? 1 : tot_recv_messages)),
  1272. (unsigned long)min_latency,
  1273. (unsigned long)max_latency);
  1274. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Average jitter %f ms; min = %lu ms, max = %lu ms\n",
  1275. ((double)total_jitter/(double)tot_recv_messages),
  1276. (unsigned long)min_jitter,
  1277. (unsigned long)max_jitter);
  1278. turn_free(elems,0);
  1279. }
  1280. ///////////////////////////////////////////
  1281. turn_credential_type get_turn_credentials_type(void)
  1282. {
  1283. return TURN_CREDENTIALS_LONG_TERM;
  1284. }
  1285. int add_integrity(app_ur_conn_info *clnet_info, stun_buffer *message)
  1286. {
  1287. if(clnet_info->nonce[0]) {
  1288. if(oauth && clnet_info->oauth) {
  1289. u16bits method = stun_get_method_str(message->buf, message->len);
  1290. int cok = clnet_info->cok;
  1291. if(((method == STUN_METHOD_ALLOCATE) || (method == STUN_METHOD_REFRESH)) || !(clnet_info->key_set))
  1292. {
  1293. cok=((unsigned short)random())%3;
  1294. clnet_info->cok = cok;
  1295. oauth_token otoken;
  1296. encoded_oauth_token etoken;
  1297. u08bits nonce[12];
  1298. RAND_bytes((unsigned char*)nonce,12);
  1299. long halflifetime = OAUTH_SESSION_LIFETIME/2;
  1300. long random_lifetime = 0;
  1301. while(!random_lifetime) {
  1302. random_lifetime = random();
  1303. }
  1304. if(random_lifetime<0) random_lifetime=-random_lifetime;
  1305. random_lifetime = random_lifetime % halflifetime;
  1306. otoken.enc_block.lifetime = (uint32_t)(halflifetime + random_lifetime);
  1307. otoken.enc_block.timestamp = ((uint64_t)turn_time()) << 16;
  1308. if(shatype == SHATYPE_SHA256) {
  1309. otoken.enc_block.key_length = 32;
  1310. } else if(shatype == SHATYPE_SHA384) {
  1311. otoken.enc_block.key_length = 48;
  1312. } else if(shatype == SHATYPE_SHA512) {
  1313. otoken.enc_block.key_length = 64;
  1314. } else {
  1315. otoken.enc_block.key_length = 20;
  1316. }
  1317. RAND_bytes((unsigned char *)(otoken.enc_block.mac_key), otoken.enc_block.key_length);
  1318. if(encode_oauth_token(clnet_info->server_name, &etoken, &(okey_array[cok]), &otoken, nonce)<0) {
  1319. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO," Cannot encode token\n");
  1320. return -1;
  1321. }
  1322. stun_attr_add_str(message->buf, (size_t*)&(message->len), STUN_ATTRIBUTE_OAUTH_ACCESS_TOKEN,
  1323. (const u08bits*)etoken.token, (int)etoken.size);
  1324. ns_bcopy(otoken.enc_block.mac_key,clnet_info->key,otoken.enc_block.key_length);
  1325. clnet_info->key_set = 1;
  1326. }
  1327. if(stun_attr_add_integrity_by_key_str(message->buf, (size_t*)&(message->len), (u08bits*)okey_array[cok].kid,
  1328. clnet_info->realm, clnet_info->key, clnet_info->nonce, shatype)<0) {
  1329. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO," Cannot add integrity to the message\n");
  1330. return -1;
  1331. }
  1332. //self-test:
  1333. {
  1334. password_t pwd;
  1335. if(stun_check_message_integrity_by_key_str(get_turn_credentials_type(),
  1336. message->buf, (size_t)(message->len), clnet_info->key, pwd, shatype)<1) {
  1337. TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR," Self-test of integrity does not comple correctly !\n");
  1338. return -1;
  1339. }
  1340. }
  1341. } else {
  1342. if(stun_attr_add_integrity_by_user_str(message->buf, (size_t*)&(message->len), g_uname,
  1343. clnet_info->realm, g_upwd, clnet_info->nonce, shatype)<0) {
  1344. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO," Cannot add integrity to the message\n");
  1345. return -1;
  1346. }
  1347. }
  1348. }
  1349. return 0;
  1350. }
  1351. int check_integrity(app_ur_conn_info *clnet_info, stun_buffer *message)
  1352. {
  1353. SHATYPE sht = shatype;
  1354. if(oauth && clnet_info->oauth) {
  1355. password_t pwd;
  1356. return stun_check_message_integrity_by_key_str(get_turn_credentials_type(),
  1357. message->buf, (size_t)(message->len), clnet_info->key, pwd, sht);
  1358. } else {
  1359. if(stun_check_message_integrity_str(get_turn_credentials_type(),
  1360. message->buf, (size_t)(message->len), g_uname,
  1361. clnet_info->realm, g_upwd, sht)<1) {
  1362. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,"Wrong integrity in a message received from server\n");
  1363. return -1;
  1364. }
  1365. }
  1366. return 0;
  1367. }
  1368. SOCKET_TYPE get_socket_type()
  1369. {
  1370. if(use_sctp) {
  1371. if(use_secure) {
  1372. return TLS_SCTP_SOCKET;
  1373. } else {
  1374. return SCTP_SOCKET;
  1375. }
  1376. } else if(use_tcp) {
  1377. if(use_secure) {
  1378. return TLS_SOCKET;
  1379. } else {
  1380. return TCP_SOCKET;
  1381. }
  1382. } else {
  1383. if(use_secure) {
  1384. return DTLS_SOCKET;
  1385. } else {
  1386. return UDP_SOCKET;
  1387. }
  1388. }
  1389. }
  1390. ///////////////////////////////////////////