ns_ioalib_engine_impl.c 94 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816
  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 "ns_turn_utils.h"
  31. #include "ns_turn_session.h"
  32. #include "ns_turn_server.h"
  33. #include "ns_turn_khash.h"
  34. #include "stun_buffer.h"
  35. #include "apputils.h"
  36. #include "ns_ioalib_impl.h"
  37. #if TLS_SUPPORTED
  38. #include <event2/bufferevent_ssl.h>
  39. #endif
  40. #include <event2/listener.h>
  41. #include <openssl/err.h>
  42. #if !defined(TURN_NO_HIREDIS)
  43. #include "hiredis_libevent2.h"
  44. #endif
  45. #if !defined(TURN_NO_SCTP) && defined(TURN_SCTP_INCLUDE)
  46. #include TURN_SCTP_INCLUDE
  47. #endif
  48. /* Compilation test:
  49. #if defined(IP_RECVTTL)
  50. #undef IP_RECVTTL
  51. #endif
  52. #if defined(IPV6_RECVHOPLIMIT)
  53. #undef IPV6_RECVHOPLIMIT
  54. #endif
  55. #if defined(IP_RECVTOS)
  56. #undef IP_RECVTOS
  57. #endif
  58. #if defined(IPV6_RECVTCLASS)
  59. #undef IPV6_RECVTCLASS
  60. #endif
  61. */
  62. #define MAX_ERRORS_IN_UDP_BATCH (1024)
  63. struct turn_sock_extended_err {
  64. uint32_t ee_errno; /* error number */
  65. uint8_t ee_origin; /* where the error originated */
  66. uint8_t ee_type; /* type */
  67. uint8_t ee_code; /* code */
  68. uint8_t ee_pad; /* padding */
  69. uint32_t ee_info; /* additional information */
  70. uint32_t ee_data; /* other data */
  71. /* More data may follow */
  72. };
  73. #define TRIAL_EFFORTS_TO_SEND (2)
  74. #define SSL_MAX_RENEG_NUMBER (3)
  75. const int predef_timer_intervals[PREDEF_TIMERS_NUM] = {30,60,90,120,240,300,360,540,600,700,800,900,1800,3600};
  76. /************** Forward function declarations ******/
  77. static int socket_readerr(evutil_socket_t fd, ioa_addr *orig_addr);
  78. static void socket_input_handler(evutil_socket_t fd, short what, void* arg);
  79. static void socket_output_handler_bev(struct bufferevent *bev, void* arg);
  80. static void socket_input_handler_bev(struct bufferevent *bev, void* arg);
  81. static void eventcb_bev(struct bufferevent *bev, short events, void *arg);
  82. static int send_ssl_backlog_buffers(ioa_socket_handle s);
  83. static int set_accept_cb(ioa_socket_handle s, accept_cb acb, void *arg);
  84. static void close_socket_net_data(ioa_socket_handle s);
  85. /************** Utils **************************/
  86. static const int tcp_congestion_control = 1;
  87. static int bufferevent_enabled(struct bufferevent *bufev, short flags)
  88. {
  89. return (bufferevent_get_enabled(bufev) & flags);
  90. }
  91. static int is_socket_writeable(ioa_socket_handle s, size_t sz, const char *msg, int option)
  92. {
  93. UNUSED_ARG(sz);
  94. UNUSED_ARG(msg);
  95. UNUSED_ARG(option);
  96. if (!s)
  97. return 0;
  98. if (!(s->done) && !(s->broken) && !(s->tobeclosed)) {
  99. switch (s->st){
  100. case SCTP_SOCKET:
  101. case TLS_SCTP_SOCKET:
  102. case TCP_SOCKET:
  103. case TLS_SOCKET:
  104. if (s->bev) {
  105. struct evbuffer *evb = bufferevent_get_output(s->bev);
  106. if (evb) {
  107. size_t bufsz = evbuffer_get_length(evb);
  108. size_t newsz = bufsz + sz;
  109. switch (s->sat){
  110. case TCP_CLIENT_DATA_SOCKET:
  111. case TCP_RELAY_DATA_SOCKET:
  112. switch (option){
  113. case 0:
  114. case 1:
  115. if (newsz >= BUFFEREVENT_MAX_TCP_TO_TCP_WRITE) {
  116. return 0;
  117. }
  118. break;
  119. case 3:
  120. case 4:
  121. if (newsz >= BUFFEREVENT_MAX_TCP_TO_TCP_WRITE) {
  122. return 0;
  123. }
  124. break;
  125. default:
  126. return 1;
  127. }
  128. ;
  129. break;
  130. default:
  131. if (option == 2) {
  132. if (newsz >= BUFFEREVENT_MAX_UDP_TO_TCP_WRITE) {
  133. return 0;
  134. }
  135. }
  136. };
  137. }
  138. }
  139. break;
  140. default:
  141. ;
  142. };
  143. }
  144. return 1;
  145. }
  146. static void log_socket_event(ioa_socket_handle s, const char *msg, int error) {
  147. if(s && (error || (s->e && s->e->verbose))) {
  148. if(!msg)
  149. msg = "General socket event";
  150. turnsession_id id = 0;
  151. {
  152. ts_ur_super_session *ss = s->session;
  153. if (ss) {
  154. id = ss->id;
  155. } else{
  156. return;
  157. }
  158. }
  159. TURN_LOG_LEVEL ll = TURN_LOG_LEVEL_INFO;
  160. if(error)
  161. ll = TURN_LOG_LEVEL_ERROR;
  162. UNUSED_ARG(ll);
  163. {
  164. char sraddr[129]="\0";
  165. char sladdr[129]="\0";
  166. addr_to_string(&(s->remote_addr),(u08bits*)sraddr);
  167. addr_to_string(&(s->local_addr),(u08bits*)sladdr);
  168. if(EVUTIL_SOCKET_ERROR()) {
  169. TURN_LOG_FUNC(ll,"session %018llu: %s: %s (local %s, remote %s)\n",(unsigned long long)id,
  170. msg, evutil_socket_error_to_string(EVUTIL_SOCKET_ERROR()),
  171. sladdr,sraddr);
  172. } else {
  173. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,"session %018llu: %s (local %s, remote %s)\n",
  174. (unsigned long long)id,msg,sladdr,sraddr);
  175. }
  176. }
  177. }
  178. }
  179. int set_df_on_ioa_socket(ioa_socket_handle s, int value)
  180. {
  181. if(!s)
  182. return 0;
  183. if(s->parent_s)
  184. return 0;
  185. if (s->do_not_use_df)
  186. value = 0;
  187. if (s->current_df_relay_flag != value) {
  188. s->current_df_relay_flag = value;
  189. return set_socket_df(s->fd, s->family, value);
  190. }
  191. return 0;
  192. }
  193. void set_do_not_use_df(ioa_socket_handle s)
  194. {
  195. if(s->parent_s)
  196. return;
  197. s->do_not_use_df = 1;
  198. s->current_df_relay_flag = 1;
  199. set_socket_df(s->fd, s->family, 0);
  200. }
  201. /************** Buffer List ********************/
  202. static int buffer_list_empty(stun_buffer_list *bufs)
  203. {
  204. if(bufs && bufs->head && bufs->tsz)
  205. return 0;
  206. return 1;
  207. }
  208. static stun_buffer_list_elem *get_elem_from_buffer_list(stun_buffer_list *bufs)
  209. {
  210. stun_buffer_list_elem *ret = NULL;
  211. if(bufs && bufs->head && bufs->tsz) {
  212. ret=bufs->head;
  213. bufs->head=ret->next;
  214. --bufs->tsz;
  215. ret->next=NULL;
  216. ret->buf.len = 0;
  217. ret->buf.offset = 0;
  218. ret->buf.coffset = 0;
  219. }
  220. return ret;
  221. }
  222. static void pop_elem_from_buffer_list(stun_buffer_list *bufs)
  223. {
  224. if(bufs && bufs->head && bufs->tsz) {
  225. stun_buffer_list_elem *ret = bufs->head;
  226. bufs->head=ret->next;
  227. --bufs->tsz;
  228. turn_free(ret,sizeof(stun_buffer_list_elem));
  229. }
  230. }
  231. static stun_buffer_list_elem *new_blist_elem(ioa_engine_handle e)
  232. {
  233. stun_buffer_list_elem *ret = get_elem_from_buffer_list(&(e->bufs));
  234. if(!ret) {
  235. ret = (stun_buffer_list_elem *)turn_malloc(sizeof(stun_buffer_list_elem));
  236. ret->buf.len = 0;
  237. ret->buf.offset = 0;
  238. ret->buf.coffset = 0;
  239. ret->next = NULL;
  240. }
  241. return ret;
  242. }
  243. static inline void add_elem_to_buffer_list(stun_buffer_list *bufs, stun_buffer_list_elem *buf_elem)
  244. {
  245. buf_elem->next = bufs->head;
  246. bufs->head = buf_elem;
  247. bufs->tsz += 1;
  248. }
  249. static void add_buffer_to_buffer_list(stun_buffer_list *bufs, s08bits *buf, size_t len)
  250. {
  251. if(bufs && buf && (bufs->tsz<MAX_SOCKET_BUFFER_BACKLOG)) {
  252. stun_buffer_list_elem *buf_elem = (stun_buffer_list_elem *)turn_malloc(sizeof(stun_buffer_list_elem));
  253. ns_bcopy(buf,buf_elem->buf.buf,len);
  254. buf_elem->buf.len = len;
  255. buf_elem->buf.offset = 0;
  256. buf_elem->buf.coffset = 0;
  257. add_elem_to_buffer_list(bufs,buf_elem);
  258. }
  259. }
  260. static void free_blist_elem(ioa_engine_handle e, stun_buffer_list_elem *buf_elem)
  261. {
  262. if(buf_elem) {
  263. if(e && (e->bufs.tsz<MAX_BUFFER_QUEUE_SIZE_PER_ENGINE)) {
  264. add_elem_to_buffer_list(&(e->bufs), buf_elem);
  265. } else {
  266. turn_free(buf_elem,sizeof(stun_buffer_list_elem));
  267. }
  268. }
  269. }
  270. /************** ENGINE *************************/
  271. static void timer_handler(ioa_engine_handle e, void* arg) {
  272. UNUSED_ARG(arg);
  273. _log_time_value = turn_time();
  274. _log_time_value_set = 1;
  275. e->jiffie = _log_time_value;
  276. }
  277. ioa_engine_handle create_ioa_engine(super_memory_t *sm,
  278. struct event_base *eb, turnipports *tp, const s08bits* relay_ifname,
  279. size_t relays_number, s08bits **relay_addrs, int default_relays,
  280. int verbose
  281. #if !defined(TURN_NO_HIREDIS)
  282. ,const char* redis_report_connection_string
  283. #endif
  284. )
  285. {
  286. static int capabilities_checked = 0;
  287. if(!capabilities_checked) {
  288. capabilities_checked = 1;
  289. #if !defined(CMSG_SPACE)
  290. TURN_LOG_FUNC(TURN_LOG_LEVEL_WARNING, "On this platform, I am using alternative behavior of TTL/TOS according to RFC 5766.\n");
  291. #endif
  292. #if !defined(IP_RECVTTL) || !defined(IP_TTL)
  293. TURN_LOG_FUNC(TURN_LOG_LEVEL_WARNING, "IPv4: On this platform, I am using alternative behavior of TTL according to RFC 5766.\n");
  294. #endif
  295. #if !defined(IPV6_RECVHOPLIMIT) || !defined(IPV6_HOPLIMIT)
  296. TURN_LOG_FUNC(TURN_LOG_LEVEL_WARNING, "IPv6: On this platform, I am using alternative behavior of TTL (HOPLIMIT) according to RFC 6156.\n");
  297. #endif
  298. #if !defined(IP_RECVTOS) || !defined(IP_TOS)
  299. TURN_LOG_FUNC(TURN_LOG_LEVEL_WARNING, "IPv4: On this platform, I am using alternative behavior of TOS according to RFC 5766.\n");
  300. #endif
  301. #if !defined(IPV6_RECVTCLASS) || !defined(IPV6_TCLASS)
  302. TURN_LOG_FUNC(TURN_LOG_LEVEL_WARNING, "IPv6: On this platform, I am using alternative behavior of TRAFFIC CLASS according to RFC 6156.\n");
  303. #endif
  304. }
  305. if (!relays_number || !relay_addrs || !tp) {
  306. TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: Cannot create TURN engine\n", __FUNCTION__);
  307. return NULL;
  308. } else {
  309. ioa_engine_handle e = (ioa_engine_handle)allocate_super_memory_region(sm, sizeof(ioa_engine));
  310. e->sm = sm;
  311. e->default_relays = default_relays;
  312. e->verbose = verbose;
  313. e->tp = tp;
  314. if (eb) {
  315. e->event_base = eb;
  316. e->deallocate_eb = 0;
  317. } else {
  318. e->event_base = turn_event_base_new();
  319. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,"IO method (engine own thread): %s\n",event_base_get_method(e->event_base));
  320. e->deallocate_eb = 1;
  321. }
  322. #if !defined(TURN_NO_HIREDIS)
  323. if(redis_report_connection_string && *redis_report_connection_string) {
  324. e->rch = get_redis_async_connection(e->event_base, redis_report_connection_string, 0);
  325. }
  326. #endif
  327. {
  328. int t;
  329. for(t=0;t<PREDEF_TIMERS_NUM;++t) {
  330. struct timeval duration;
  331. duration.tv_sec = predef_timer_intervals[t];
  332. duration.tv_usec = 0;
  333. const struct timeval *ptv = event_base_init_common_timeout(e->event_base, &duration);
  334. if(!ptv) {
  335. TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR,"FATAL: cannot create preferable timeval for %d secs (%d number)\n",predef_timer_intervals[t],t);
  336. exit(-1);
  337. } else {
  338. ns_bcopy(ptv,&(e->predef_timers[t]),sizeof(struct timeval));
  339. e->predef_timer_intervals[t] = predef_timer_intervals[t];
  340. }
  341. }
  342. }
  343. if (relay_ifname)
  344. STRCPY(e->relay_ifname, relay_ifname);
  345. {
  346. size_t i = 0;
  347. e->relay_addrs = (ioa_addr*)allocate_super_memory_region(sm, relays_number * sizeof(ioa_addr)+8);
  348. for (i = 0; i < relays_number; i++) {
  349. if(make_ioa_addr((u08bits*) relay_addrs[i], 0, &(e->relay_addrs[i]))<0) {
  350. TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR,"Cannot add a relay address: %s\n",relay_addrs[i]);
  351. }
  352. }
  353. e->relays_number = relays_number;
  354. }
  355. e->relay_addr_counter = (unsigned short) turn_random();
  356. timer_handler(e,e);
  357. e->timer_ev = set_ioa_timer(e, 1, 0, timer_handler, e, 1, "timer_handler");
  358. return e;
  359. }
  360. }
  361. void set_ssl_ctx(ioa_engine_handle e,
  362. SSL_CTX *tls_ctx_ssl23,
  363. SSL_CTX *tls_ctx_v1_0
  364. #if TLSv1_1_SUPPORTED
  365. ,SSL_CTX *tls_ctx_v1_1
  366. #if TLSv1_2_SUPPORTED
  367. ,SSL_CTX *tls_ctx_v1_2
  368. #endif
  369. #endif
  370. #if DTLS_SUPPORTED
  371. ,SSL_CTX *dtls_ctx
  372. #endif
  373. #if DTLSv1_2_SUPPORTED
  374. ,SSL_CTX *dtls_ctx_v1_2
  375. #endif
  376. )
  377. {
  378. e->tls_ctx_ssl23 = tls_ctx_ssl23;
  379. e->tls_ctx_v1_0 = tls_ctx_v1_0;
  380. #if TLSv1_1_SUPPORTED
  381. e->tls_ctx_v1_1 = tls_ctx_v1_1;
  382. #if TLSv1_2_SUPPORTED
  383. e->tls_ctx_v1_2 = tls_ctx_v1_2;
  384. #endif
  385. #endif
  386. #if DTLS_SUPPORTED
  387. e->dtls_ctx = dtls_ctx;
  388. #endif
  389. #if DTLSv1_2_SUPPORTED
  390. e->dtls_ctx_v1_2 = dtls_ctx_v1_2;
  391. #endif
  392. }
  393. void ioa_engine_set_rtcp_map(ioa_engine_handle e, rtcp_map *rtcpmap)
  394. {
  395. if(e)
  396. e->map_rtcp = rtcpmap;
  397. }
  398. static const ioa_addr* ioa_engine_get_relay_addr(ioa_engine_handle e, ioa_socket_handle client_s,
  399. int address_family, int *err_code)
  400. {
  401. if(e) {
  402. int family = AF_INET;
  403. if(address_family == STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV6)
  404. family = AF_INET6;
  405. if(e->default_relays) {
  406. //No relay addrs defined - just return the client address if appropriate:
  407. ioa_addr *client_addr = get_local_addr_from_ioa_socket(client_s);
  408. if(client_addr) {
  409. switch(address_family) {
  410. case STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV4:
  411. if (client_addr->ss.sa_family == AF_INET)
  412. return client_addr;
  413. break;
  414. case STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV6:
  415. if (client_addr->ss.sa_family == AF_INET6)
  416. return client_addr;
  417. break;
  418. default:
  419. return client_addr;
  420. };
  421. }
  422. }
  423. if (e->relays_number>0) {
  424. size_t i = 0;
  425. //Default recommended behavior:
  426. for(i=0; i<e->relays_number; i++) {
  427. if(e->relay_addr_counter >= e->relays_number)
  428. e->relay_addr_counter = 0;
  429. ioa_addr *relay_addr = &(e->relay_addrs[e->relay_addr_counter++]);
  430. if(addr_any_no_port(relay_addr))
  431. get_a_local_relay(family, relay_addr);
  432. switch (address_family){
  433. case STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_DEFAULT:
  434. case STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV4:
  435. if (relay_addr->ss.sa_family == AF_INET)
  436. return relay_addr;
  437. break;
  438. case STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_IPV6:
  439. if (relay_addr->ss.sa_family == AF_INET6)
  440. return relay_addr;
  441. break;
  442. default:
  443. ;
  444. };
  445. }
  446. if(address_family == STUN_ATTRIBUTE_REQUESTED_ADDRESS_FAMILY_VALUE_DEFAULT) {
  447. //Fallback to "find whatever is available":
  448. if(e->relay_addr_counter >= e->relays_number)
  449. e->relay_addr_counter = 0;
  450. const ioa_addr *relay_addr = &(e->relay_addrs[e->relay_addr_counter++]);
  451. return relay_addr;
  452. }
  453. *err_code = 440;
  454. }
  455. }
  456. return NULL;
  457. }
  458. /******************** Timers ****************************/
  459. static void timer_event_handler(evutil_socket_t fd, short what, void* arg)
  460. {
  461. timer_event* te = (timer_event*)arg;
  462. if(!te)
  463. return;
  464. UNUSED_ARG(fd);
  465. if (!(what & EV_TIMEOUT))
  466. return;
  467. if(te->e && eve(te->e->verbose))
  468. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: timeout 0x%lx: %s\n", __FUNCTION__,(long)te, te->txt);
  469. ioa_timer_event_handler cb = te->cb;
  470. ioa_engine_handle e = te->e;
  471. void *ctx = te->ctx;
  472. cb(e, ctx);
  473. }
  474. ioa_timer_handle set_ioa_timer(ioa_engine_handle e, int secs, int ms, ioa_timer_event_handler cb, void* ctx, int persist, const s08bits *txt)
  475. {
  476. ioa_timer_handle ret = NULL;
  477. if (e && cb && secs > 0) {
  478. timer_event * te = (timer_event*) turn_malloc(sizeof(timer_event));
  479. int flags = EV_TIMEOUT;
  480. if (persist)
  481. flags |= EV_PERSIST;
  482. struct event *ev = event_new(e->event_base, -1, flags, timer_event_handler, te);
  483. struct timeval tv;
  484. tv.tv_sec = secs;
  485. te->ctx = ctx;
  486. te->e = e;
  487. te->ev = ev;
  488. te->cb = cb;
  489. te->txt = turn_strdup(txt);
  490. if(!ms) {
  491. tv.tv_usec = 0;
  492. int found = 0;
  493. int t;
  494. for(t=0;t<PREDEF_TIMERS_NUM;++t) {
  495. if(e->predef_timer_intervals[t] == secs) {
  496. evtimer_add(ev,&(e->predef_timers[t]));
  497. found = 1;
  498. break;
  499. }
  500. }
  501. if(!found) {
  502. evtimer_add(ev,&tv);
  503. }
  504. } else {
  505. tv.tv_usec = ms * 1000;
  506. evtimer_add(ev,&tv);
  507. }
  508. ret = te;
  509. }
  510. return ret;
  511. }
  512. void stop_ioa_timer(ioa_timer_handle th)
  513. {
  514. if (th) {
  515. timer_event *te = (timer_event *)th;
  516. EVENT_DEL(te->ev);
  517. }
  518. }
  519. void delete_ioa_timer(ioa_timer_handle th)
  520. {
  521. if (th) {
  522. stop_ioa_timer(th);
  523. timer_event *te = (timer_event *)th;
  524. if(te->txt) {
  525. turn_free(te->txt,strlen(te->txt)+1);
  526. te->txt = NULL;
  527. }
  528. turn_free(th,sizeof(timer_event));
  529. }
  530. }
  531. /************** SOCKETS HELPERS ***********************/
  532. int ioa_socket_check_bandwidth(ioa_socket_handle s, ioa_network_buffer_handle nbh, int read)
  533. {
  534. if(s && (s->e) && nbh &&
  535. ((s->sat == CLIENT_SOCKET) || (s->sat == RELAY_SOCKET) || (s->sat == RELAY_RTCP_SOCKET)) &&
  536. (s->session)) {
  537. size_t sz = ioa_network_buffer_get_size(nbh);
  538. band_limit_t max_bps = s->session->bps;
  539. if(max_bps<1)
  540. return 1;
  541. struct traffic_bytes *traffic = &(s->data_traffic);
  542. if(s->sat == CLIENT_SOCKET) {
  543. u08bits *buf = ioa_network_buffer_data(nbh);
  544. if(stun_is_command_message_str(buf,sz)) {
  545. u16bits method = stun_get_method_str(buf,sz);
  546. if((method != STUN_METHOD_SEND) && (method != STUN_METHOD_DATA)) {
  547. traffic = &(s->control_traffic);
  548. }
  549. }
  550. }
  551. band_limit_t bsz = (band_limit_t)sz;
  552. if(s->jiffie != s->e->jiffie) {
  553. s->jiffie = s->e->jiffie;
  554. traffic->jiffie_bytes_read = 0;
  555. traffic->jiffie_bytes_write = 0;
  556. if(bsz > max_bps) {
  557. return 0;
  558. } else {
  559. if(read)
  560. traffic->jiffie_bytes_read = bsz;
  561. else
  562. traffic->jiffie_bytes_write = bsz;
  563. return 1;
  564. }
  565. } else {
  566. band_limit_t nsz;
  567. if(read)
  568. nsz = traffic->jiffie_bytes_read + bsz;
  569. else
  570. nsz = traffic->jiffie_bytes_write + bsz;
  571. if(nsz > max_bps) {
  572. return 0;
  573. } else {
  574. if(read)
  575. traffic->jiffie_bytes_read = nsz;
  576. else
  577. traffic->jiffie_bytes_write = nsz;
  578. return 1;
  579. }
  580. }
  581. }
  582. return 1;
  583. }
  584. int get_ioa_socket_from_reservation(ioa_engine_handle e, u64bits in_reservation_token, ioa_socket_handle *s)
  585. {
  586. if (e && in_reservation_token && s) {
  587. *s = rtcp_map_get(e->map_rtcp, in_reservation_token);
  588. if (*s) {
  589. return 0;
  590. }
  591. }
  592. return -1;
  593. }
  594. /* Socket options helpers ==>> */
  595. static int set_socket_ttl(ioa_socket_handle s, int ttl)
  596. {
  597. if(s->default_ttl < 0) //Unsupported
  598. return -1;
  599. if(ttl < 0)
  600. ttl = s->default_ttl;
  601. CORRECT_RAW_TTL(ttl);
  602. if(ttl > s->default_ttl)
  603. ttl=s->default_ttl;
  604. if(s->current_ttl != ttl) {
  605. int ret = set_raw_socket_ttl(s->fd, s->family, ttl);
  606. s->current_ttl = ttl;
  607. return ret;
  608. }
  609. return 0;
  610. }
  611. static int set_socket_tos(ioa_socket_handle s, int tos)
  612. {
  613. if(s->default_tos < 0) //Unsupported
  614. return -1;
  615. if(tos < 0)
  616. tos = s->default_tos;
  617. CORRECT_RAW_TOS(tos);
  618. if(s->current_tos != tos) {
  619. int ret = set_raw_socket_tos(s->fd, s->family, tos);
  620. s->current_tos = tos;
  621. return ret;
  622. }
  623. return 0;
  624. }
  625. int set_raw_socket_ttl_options(evutil_socket_t fd, int family)
  626. {
  627. if (family == AF_INET6) {
  628. #if !defined(IPV6_RECVHOPLIMIT)
  629. UNUSED_ARG(fd);
  630. #else
  631. int recv_ttl_on = 1;
  632. if (setsockopt(fd, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &recv_ttl_on,
  633. sizeof(recv_ttl_on)) < 0) {
  634. perror("cannot set recvhoplimit\n");
  635. }
  636. #endif
  637. } else {
  638. #if !defined(IP_RECVTTL)
  639. UNUSED_ARG(fd);
  640. #else
  641. int recv_ttl_on = 1;
  642. if (setsockopt(fd, IPPROTO_IP, IP_RECVTTL, &recv_ttl_on,
  643. sizeof(recv_ttl_on)) < 0) {
  644. perror("cannot set recvttl\n");
  645. }
  646. #endif
  647. }
  648. return 0;
  649. }
  650. int set_raw_socket_tos_options(evutil_socket_t fd, int family)
  651. {
  652. if (family == AF_INET6) {
  653. #if !defined(IPV6_RECVTCLASS)
  654. UNUSED_ARG(fd);
  655. #else
  656. int recv_tos_on = 1;
  657. if (setsockopt(fd, IPPROTO_IPV6, IPV6_RECVTCLASS, &recv_tos_on,
  658. sizeof(recv_tos_on)) < 0) {
  659. perror("cannot set recvtclass\n");
  660. }
  661. #endif
  662. } else {
  663. #if !defined(IP_RECVTOS)
  664. UNUSED_ARG(fd);
  665. #else
  666. int recv_tos_on = 1;
  667. if (setsockopt(fd, IPPROTO_IP, IP_RECVTOS, &recv_tos_on,
  668. sizeof(recv_tos_on)) < 0) {
  669. perror("cannot set recvtos\n");
  670. }
  671. #endif
  672. }
  673. return 0;
  674. }
  675. int set_socket_options_fd(evutil_socket_t fd, SOCKET_TYPE st, int family)
  676. {
  677. if(fd<0)
  678. return 0;
  679. set_sock_buf_size(fd,UR_CLIENT_SOCK_BUF_SIZE);
  680. if(is_tcp_socket(st)) { /* <<== FREEBSD fix */
  681. struct linger so_linger;
  682. so_linger.l_onoff = 1;
  683. so_linger.l_linger = 0;
  684. if(setsockopt(fd,
  685. SOL_SOCKET,
  686. SO_LINGER,
  687. &so_linger,
  688. sizeof(so_linger))<1) {
  689. //perror("setsolinger")
  690. ;
  691. }
  692. }
  693. socket_set_nonblocking(fd);
  694. if (!is_stream_socket(st)) {
  695. set_raw_socket_ttl_options(fd, family);
  696. set_raw_socket_tos_options(fd, family);
  697. #ifdef IP_RECVERR
  698. if (family != AF_INET6) {
  699. int on = 0;
  700. #ifdef TURN_IP_RECVERR
  701. on = 1;
  702. #endif
  703. if(setsockopt(fd, IPPROTO_IP, IP_RECVERR, (void *)&on, sizeof(on))<0)
  704. perror("IP_RECVERR");
  705. }
  706. #endif
  707. #ifdef IPV6_RECVERR
  708. if (family == AF_INET6) {
  709. int on = 0;
  710. #ifdef TURN_IP_RECVERR
  711. on = 1;
  712. #endif
  713. if(setsockopt(fd, IPPROTO_IPV6, IPV6_RECVERR, (void *)&on, sizeof(on))<0)
  714. perror("IPV6_RECVERR");
  715. }
  716. #endif
  717. } else {
  718. int flag = 1;
  719. if(is_tcp_socket(st)) {
  720. setsockopt(fd, /* socket affected */
  721. IPPROTO_TCP, /* set option at TCP level */
  722. TCP_NODELAY, /* name of option */
  723. (char*)&flag, /* value */
  724. sizeof(int)); /* length of option value */
  725. } else {
  726. #if defined(SCTP_NODELAY)
  727. setsockopt(fd, /* socket affected */
  728. IPPROTO_SCTP, /* set option at SCTP level */
  729. SCTP_NODELAY, /* name of option */
  730. (char*)&flag, /* value */
  731. sizeof(int)); /* length of option value */
  732. #endif
  733. }
  734. socket_tcp_set_keepalive(fd,st);
  735. }
  736. return 0;
  737. }
  738. int set_socket_options(ioa_socket_handle s)
  739. {
  740. if(!s || (s->parent_s))
  741. return 0;
  742. set_socket_options_fd(s->fd,s->st,s->family);
  743. s->default_ttl = get_raw_socket_ttl(s->fd, s->family);
  744. s->current_ttl = s->default_ttl;
  745. s->default_tos = get_raw_socket_tos(s->fd, s->family);
  746. s->current_tos = s->default_tos;
  747. return 0;
  748. }
  749. /* <<== Socket options helpers */
  750. ioa_socket_handle create_unbound_relay_ioa_socket(ioa_engine_handle e, int family, SOCKET_TYPE st, SOCKET_APP_TYPE sat)
  751. {
  752. evutil_socket_t fd = -1;
  753. ioa_socket_handle ret = NULL;
  754. switch (st){
  755. case UDP_SOCKET:
  756. fd = socket(family, RELAY_DGRAM_SOCKET_TYPE, RELAY_DGRAM_SOCKET_PROTOCOL);
  757. if (fd < 0) {
  758. perror("UDP socket");
  759. return NULL;
  760. }
  761. set_sock_buf_size(fd, UR_CLIENT_SOCK_BUF_SIZE);
  762. break;
  763. case TCP_SOCKET:
  764. fd = socket(family, RELAY_STREAM_SOCKET_TYPE, RELAY_STREAM_SOCKET_PROTOCOL);
  765. if (fd < 0) {
  766. perror("TCP socket");
  767. return NULL;
  768. }
  769. set_sock_buf_size(fd, UR_CLIENT_SOCK_BUF_SIZE);
  770. break;
  771. default:
  772. /* we do not support other sockets in the relay position */
  773. return NULL;
  774. }
  775. ret = (ioa_socket*)turn_malloc(sizeof(ioa_socket));
  776. ns_bzero(ret,sizeof(ioa_socket));
  777. ret->magic = SOCKET_MAGIC;
  778. ret->fd = fd;
  779. ret->family = family;
  780. ret->st = st;
  781. ret->sat = sat;
  782. ret->e = e;
  783. set_socket_options(ret);
  784. return ret;
  785. }
  786. static int bind_ioa_socket(ioa_socket_handle s, const ioa_addr* local_addr, int reusable)
  787. {
  788. if(!s || (s->parent_s))
  789. return 0;
  790. if (s && s->fd >= 0 && s->e && local_addr) {
  791. int res = addr_bind(s->fd, local_addr, reusable,1,s->st);
  792. if (res >= 0) {
  793. s->bound = 1;
  794. addr_cpy(&(s->local_addr), local_addr);
  795. if(addr_get_port(local_addr)<1) {
  796. ioa_addr tmpaddr;
  797. addr_get_from_sock(s->fd, &tmpaddr);
  798. if(addr_any(&(s->local_addr))) {
  799. addr_cpy(&(s->local_addr),&tmpaddr);
  800. } else {
  801. addr_set_port(&(s->local_addr),addr_get_port(&tmpaddr));
  802. }
  803. }
  804. s->local_addr_known = 1;
  805. return 0;
  806. }
  807. }
  808. return -1;
  809. }
  810. int create_relay_ioa_sockets(ioa_engine_handle e,
  811. ioa_socket_handle client_s,
  812. int address_family, u08bits transport,
  813. int even_port, ioa_socket_handle *rtp_s,
  814. ioa_socket_handle *rtcp_s, uint64_t *out_reservation_token,
  815. int *err_code, const u08bits **reason,
  816. accept_cb acb, void *acbarg)
  817. {
  818. *rtp_s = NULL;
  819. if (rtcp_s)
  820. *rtcp_s = NULL;
  821. turnipports* tp = e->tp;
  822. size_t iip = 0;
  823. for (iip = 0; iip < e->relays_number; ++iip) {
  824. ioa_addr relay_addr;
  825. const ioa_addr *ra = ioa_engine_get_relay_addr(e, client_s, address_family, err_code);
  826. if(ra)
  827. addr_cpy(&relay_addr, ra);
  828. if(*err_code) {
  829. if(*err_code == 440)
  830. *reason = (const u08bits *) "Unsupported address family";
  831. return -1;
  832. }
  833. int rtcp_port = -1;
  834. IOA_CLOSE_SOCKET(*rtp_s);
  835. if(rtcp_s)
  836. IOA_CLOSE_SOCKET(*rtcp_s);
  837. ioa_addr rtcp_local_addr;
  838. addr_cpy(&rtcp_local_addr, &relay_addr);
  839. int i = 0;
  840. int port = 0;
  841. ioa_addr local_addr;
  842. addr_cpy(&local_addr, &relay_addr);
  843. for (i = 0; i < 0xFFFF; i++) {
  844. port = 0;
  845. rtcp_port = -1;
  846. if (even_port < 0) {
  847. port = turnipports_allocate(tp, transport, &relay_addr);
  848. } else {
  849. port = turnipports_allocate_even(tp, &relay_addr, even_port, out_reservation_token);
  850. if (port >= 0 && even_port > 0) {
  851. IOA_CLOSE_SOCKET(*rtcp_s);
  852. *rtcp_s = create_unbound_relay_ioa_socket(e, relay_addr.ss.sa_family, UDP_SOCKET, RELAY_RTCP_SOCKET);
  853. if (*rtcp_s == NULL) {
  854. perror("socket");
  855. IOA_CLOSE_SOCKET(*rtp_s);
  856. addr_set_port(&local_addr, port);
  857. turnipports_release(tp, transport, &local_addr);
  858. rtcp_port = port + 1;
  859. addr_set_port(&rtcp_local_addr, rtcp_port);
  860. turnipports_release(tp, transport, &rtcp_local_addr);
  861. return -1;
  862. }
  863. sock_bind_to_device((*rtcp_s)->fd, (unsigned char*)e->relay_ifname);
  864. rtcp_port = port + 1;
  865. addr_set_port(&rtcp_local_addr, rtcp_port);
  866. if (bind_ioa_socket(*rtcp_s, &rtcp_local_addr,
  867. (transport == STUN_ATTRIBUTE_TRANSPORT_TCP_VALUE)) < 0) {
  868. addr_set_port(&local_addr, port);
  869. turnipports_release(tp, transport, &local_addr);
  870. turnipports_release(tp, transport, &rtcp_local_addr);
  871. rtcp_port = -1;
  872. IOA_CLOSE_SOCKET(*rtcp_s);
  873. continue;
  874. }
  875. }
  876. }
  877. if (port < 0) {
  878. IOA_CLOSE_SOCKET(*rtp_s);
  879. if (rtcp_s)
  880. IOA_CLOSE_SOCKET(*rtcp_s);
  881. rtcp_port = -1;
  882. break;
  883. } else {
  884. IOA_CLOSE_SOCKET(*rtp_s);
  885. *rtp_s = create_unbound_relay_ioa_socket(e, relay_addr.ss.sa_family,
  886. (transport == STUN_ATTRIBUTE_TRANSPORT_TCP_VALUE) ? TCP_SOCKET : UDP_SOCKET,
  887. RELAY_SOCKET);
  888. if (*rtp_s == NULL) {
  889. int rtcp_bound = 0;
  890. if (rtcp_s && *rtcp_s) {
  891. rtcp_bound = (*rtcp_s)->bound;
  892. IOA_CLOSE_SOCKET(*rtcp_s);
  893. }
  894. addr_set_port(&local_addr, port);
  895. turnipports_release(tp, transport, &local_addr);
  896. if (rtcp_port >= 0 && !rtcp_bound) {
  897. addr_set_port(&rtcp_local_addr, rtcp_port);
  898. turnipports_release(tp, transport, &rtcp_local_addr);
  899. }
  900. perror("socket");
  901. return -1;
  902. }
  903. sock_bind_to_device((*rtp_s)->fd, (unsigned char*)e->relay_ifname);
  904. addr_set_port(&local_addr, port);
  905. if (bind_ioa_socket(*rtp_s, &local_addr,
  906. (transport == STUN_ATTRIBUTE_TRANSPORT_TCP_VALUE)) >= 0) {
  907. break;
  908. } else {
  909. IOA_CLOSE_SOCKET(*rtp_s);
  910. int rtcp_bound = 0;
  911. if (rtcp_s && *rtcp_s) {
  912. rtcp_bound = (*rtcp_s)->bound;
  913. IOA_CLOSE_SOCKET(*rtcp_s);
  914. }
  915. addr_set_port(&local_addr, port);
  916. turnipports_release(tp, transport, &local_addr);
  917. if (rtcp_port >= 0 && !rtcp_bound) {
  918. addr_set_port(&rtcp_local_addr, rtcp_port);
  919. turnipports_release(tp, transport, &rtcp_local_addr);
  920. }
  921. rtcp_port = -1;
  922. }
  923. }
  924. }
  925. if(i>=0xFFFF) {
  926. IOA_CLOSE_SOCKET(*rtp_s);
  927. if (rtcp_s)
  928. IOA_CLOSE_SOCKET(*rtcp_s);
  929. }
  930. if (*rtp_s) {
  931. addr_set_port(&local_addr, port);
  932. addr_debug_print(e->verbose, &local_addr, "Local relay addr");
  933. if (rtcp_s && *rtcp_s) {
  934. addr_set_port(&local_addr, port+1);
  935. addr_debug_print(e->verbose, &local_addr, "Local reserved relay addr");
  936. }
  937. break;
  938. }
  939. }
  940. if (!(*rtp_s)) {
  941. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: no available ports 3\n", __FUNCTION__);
  942. IOA_CLOSE_SOCKET(*rtp_s);
  943. if (rtcp_s)
  944. IOA_CLOSE_SOCKET(*rtcp_s);
  945. return -1;
  946. }
  947. set_accept_cb(*rtp_s, acb, acbarg);
  948. if (rtcp_s && *rtcp_s && out_reservation_token && *out_reservation_token) {
  949. if (rtcp_map_put(e->map_rtcp, *out_reservation_token, *rtcp_s) < 0) {
  950. TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: cannot update RTCP map\n", __FUNCTION__);
  951. IOA_CLOSE_SOCKET(*rtp_s);
  952. if (rtcp_s)
  953. IOA_CLOSE_SOCKET(*rtcp_s);
  954. return -1;
  955. }
  956. }
  957. return 0;
  958. }
  959. /* RFC 6062 ==>> */
  960. static void tcp_listener_input_handler(struct evconnlistener *l, evutil_socket_t fd,
  961. struct sockaddr *sa, int socklen, void *arg)
  962. {
  963. UNUSED_ARG(l);
  964. ioa_socket_handle list_s = (ioa_socket_handle) arg;
  965. ioa_addr client_addr;
  966. ns_bcopy(sa,&client_addr,socklen);
  967. addr_debug_print(((list_s->e) && list_s->e->verbose), &client_addr,"tcp accepted from");
  968. ioa_socket_handle s =
  969. create_ioa_socket_from_fd(
  970. list_s->e,
  971. fd,
  972. NULL,
  973. TCP_SOCKET,
  974. TCP_RELAY_DATA_SOCKET,
  975. &client_addr,
  976. &(list_s->local_addr));
  977. if (s) {
  978. if(list_s->acb) {
  979. list_s->acb(s,list_s->acbarg);
  980. } else {
  981. TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR,
  982. "Do not know what to do with accepted TCP socket\n");
  983. close_ioa_socket(s);
  984. }
  985. } else {
  986. TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR,
  987. "Cannot create ioa_socket from FD\n");
  988. socket_closesocket(fd);
  989. }
  990. }
  991. static int set_accept_cb(ioa_socket_handle s, accept_cb acb, void *arg)
  992. {
  993. if(!s || s->parent_s)
  994. return -1;
  995. if(s->st == TCP_SOCKET) {
  996. s->list_ev = evconnlistener_new(s->e->event_base,
  997. tcp_listener_input_handler, s,
  998. LEV_OPT_REUSEABLE,
  999. 1024, s->fd);
  1000. if(!(s->list_ev)) {
  1001. TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: cannot start TCP listener\n", __FUNCTION__);
  1002. return -1;
  1003. }
  1004. s->acb = acb;
  1005. s->acbarg = arg;
  1006. }
  1007. return 0;
  1008. }
  1009. static void connect_eventcb(struct bufferevent *bev, short events, void *ptr)
  1010. {
  1011. UNUSED_ARG(bev);
  1012. ioa_socket_handle ret = (ioa_socket_handle) ptr;
  1013. if (ret) {
  1014. connect_cb cb = ret->conn_cb;
  1015. void *arg = ret->conn_arg;
  1016. if (events & BEV_EVENT_CONNECTED) {
  1017. ret->conn_cb = NULL;
  1018. ret->conn_arg = NULL;
  1019. BUFFEREVENT_FREE(ret->conn_bev);
  1020. ret->connected = 1;
  1021. if(cb) {
  1022. cb(1,arg);
  1023. }
  1024. } else if (events & BEV_EVENT_ERROR) {
  1025. /* An error occured while connecting. */
  1026. ret->conn_cb = NULL;
  1027. ret->conn_arg = NULL;
  1028. BUFFEREVENT_FREE(ret->conn_bev);
  1029. if(cb) {
  1030. cb(0,arg);
  1031. }
  1032. }
  1033. }
  1034. }
  1035. ioa_socket_handle ioa_create_connecting_tcp_relay_socket(ioa_socket_handle s, ioa_addr *peer_addr, connect_cb cb, void *arg)
  1036. {
  1037. ioa_socket_handle ret = create_unbound_relay_ioa_socket(s->e, s->family, s->st, TCP_RELAY_DATA_SOCKET);
  1038. if(!ret) {
  1039. return NULL;
  1040. }
  1041. ioa_addr new_local_addr;
  1042. addr_cpy(&new_local_addr, &(s->local_addr));
  1043. #if !defined(SO_REUSEPORT)
  1044. /*
  1045. * trick for OSes which do not support SO_REUSEPORT.
  1046. * Section 5.2 of RFC 6062 will not work correctly
  1047. * for those OSes (for example, Linux pre-3.9 kernel).
  1048. */
  1049. #if !defined(__CYGWIN__) && !defined(__CYGWIN32__) && !defined(__CYGWIN64__)
  1050. close_socket_net_data(s);
  1051. #else
  1052. addr_set_port(&new_local_addr,0);
  1053. #endif
  1054. #endif
  1055. if(bind_ioa_socket(ret, &new_local_addr,1)<0) {
  1056. IOA_CLOSE_SOCKET(ret);
  1057. ret = NULL;
  1058. goto ccs_end;
  1059. }
  1060. addr_cpy(&(ret->remote_addr), peer_addr);
  1061. set_ioa_socket_session(ret, s->session);
  1062. BUFFEREVENT_FREE(ret->conn_bev);
  1063. ret->conn_bev = bufferevent_socket_new(ret->e->event_base,
  1064. ret->fd,
  1065. TURN_BUFFEREVENTS_OPTIONS);
  1066. debug_ptr_add(ret->conn_bev);
  1067. bufferevent_setcb(ret->conn_bev, NULL, NULL, connect_eventcb, ret);
  1068. ret->conn_arg = arg;
  1069. ret->conn_cb = cb;
  1070. if (bufferevent_socket_connect(ret->conn_bev, (struct sockaddr *) peer_addr, get_ioa_addr_len(peer_addr)) < 0) {
  1071. /* Error starting connection */
  1072. set_ioa_socket_session(ret, NULL);
  1073. IOA_CLOSE_SOCKET(ret);
  1074. ret = NULL;
  1075. goto ccs_end;
  1076. }
  1077. ccs_end:
  1078. #if !defined(SO_REUSEPORT)
  1079. #if !defined(__CYGWIN__) && !defined(__CYGWIN32__) && !defined(__CYGWIN64__)
  1080. /*
  1081. * trick for OSes which do not support SO_REUSEPORT.
  1082. * Section 5.2 of RFC 6062 will not work correctly
  1083. * for those OSes (for example, Linux pre-3.9 kernel).
  1084. */
  1085. s->fd = socket(s->family, RELAY_STREAM_SOCKET_TYPE, RELAY_STREAM_SOCKET_PROTOCOL);
  1086. if (s->fd < 0) {
  1087. perror("TCP socket");
  1088. if(ret) {
  1089. set_ioa_socket_session(ret, NULL);
  1090. IOA_CLOSE_SOCKET(ret);
  1091. ret = NULL;
  1092. }
  1093. } else {
  1094. set_socket_options(s);
  1095. sock_bind_to_device(s->fd, (unsigned char*)s->e->relay_ifname);
  1096. if(bind_ioa_socket(s, &new_local_addr, 1)<0) {
  1097. if(ret) {
  1098. set_ioa_socket_session(ret, NULL);
  1099. IOA_CLOSE_SOCKET(ret);
  1100. ret = NULL;
  1101. }
  1102. } else {
  1103. set_accept_cb(s, s->acb, s->acbarg);
  1104. }
  1105. }
  1106. #endif
  1107. #endif
  1108. return ret;
  1109. }
  1110. /* <<== RFC 6062 */
  1111. void add_socket_to_parent(ioa_socket_handle parent_s, ioa_socket_handle s)
  1112. {
  1113. if(parent_s && s) {
  1114. delete_socket_from_parent(s);
  1115. s->parent_s = parent_s;
  1116. s->fd = parent_s->fd;
  1117. }
  1118. }
  1119. void delete_socket_from_parent(ioa_socket_handle s)
  1120. {
  1121. if(s && s->parent_s) {
  1122. s->parent_s = NULL;
  1123. s->fd = -1;
  1124. }
  1125. }
  1126. void add_socket_to_map(ioa_socket_handle s, ur_addr_map *amap)
  1127. {
  1128. if(amap && s && (s->sockets_container != amap)) {
  1129. delete_socket_from_map(s);
  1130. ur_addr_map_del(amap, &(s->remote_addr),NULL);
  1131. ur_addr_map_put(amap,
  1132. &(s->remote_addr),
  1133. (ur_addr_map_value_type)s);
  1134. s->sockets_container = amap;
  1135. }
  1136. }
  1137. void delete_socket_from_map(ioa_socket_handle s)
  1138. {
  1139. if(s && s->sockets_container) {
  1140. ur_addr_map_del(s->sockets_container,
  1141. &(s->remote_addr),
  1142. NULL);
  1143. s->sockets_container = NULL;
  1144. }
  1145. }
  1146. ioa_socket_handle create_ioa_socket_from_fd(ioa_engine_handle e,
  1147. ioa_socket_raw fd, ioa_socket_handle parent_s,
  1148. SOCKET_TYPE st, SOCKET_APP_TYPE sat,
  1149. const ioa_addr *remote_addr, const ioa_addr *local_addr)
  1150. {
  1151. ioa_socket_handle ret = NULL;
  1152. if ((fd < 0) && !parent_s) {
  1153. return NULL;
  1154. }
  1155. ret = (ioa_socket*)turn_malloc(sizeof(ioa_socket));
  1156. ns_bzero(ret,sizeof(ioa_socket));
  1157. ret->magic = SOCKET_MAGIC;
  1158. ret->fd = fd;
  1159. ret->st = st;
  1160. ret->sat = sat;
  1161. ret->e = e;
  1162. if (local_addr) {
  1163. ret->family = local_addr->ss.sa_family;
  1164. ret->bound = 1;
  1165. addr_cpy(&(ret->local_addr), local_addr);
  1166. }
  1167. if (remote_addr) {
  1168. ret->connected = 1;
  1169. if(!(ret->family))
  1170. ret->family = remote_addr->ss.sa_family;
  1171. addr_cpy(&(ret->remote_addr), remote_addr);
  1172. }
  1173. if(parent_s) {
  1174. add_socket_to_parent(parent_s, ret);
  1175. } else {
  1176. set_socket_options(ret);
  1177. }
  1178. return ret;
  1179. }
  1180. static void ssl_info_callback(SSL *ssl, int where, int ret) {
  1181. UNUSED_ARG(ret);
  1182. if (0 != (where & SSL_CB_HANDSHAKE_START)) {
  1183. ioa_socket_handle s = (ioa_socket_handle)SSL_get_app_data(ssl);
  1184. if(s) {
  1185. ++(s->ssl_renegs);
  1186. }
  1187. } else if (0 != (where & SSL_CB_HANDSHAKE_DONE)) {
  1188. if(ssl->s3) {
  1189. ioa_socket_handle s = (ioa_socket_handle)SSL_get_app_data(ssl);
  1190. if(s) {
  1191. if(s->ssl_renegs>SSL_MAX_RENEG_NUMBER) {
  1192. ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
  1193. }
  1194. }
  1195. }
  1196. }
  1197. }
  1198. typedef void (*ssl_info_callback_t)(const SSL *ssl,int type,int val);
  1199. static void set_socket_ssl(ioa_socket_handle s, SSL *ssl)
  1200. {
  1201. if(s && (s->ssl != ssl)) {
  1202. if(s->ssl) {
  1203. SSL_set_app_data(s->ssl,NULL);
  1204. SSL_set_info_callback(s->ssl, (ssl_info_callback_t)NULL);
  1205. }
  1206. s->ssl = ssl;
  1207. if(ssl) {
  1208. SSL_set_app_data(ssl,s);
  1209. SSL_set_info_callback(ssl, (ssl_info_callback_t)ssl_info_callback);
  1210. }
  1211. }
  1212. }
  1213. /* Only must be called for DTLS_SOCKET */
  1214. ioa_socket_handle create_ioa_socket_from_ssl(ioa_engine_handle e, ioa_socket_handle parent_s, SSL* ssl, SOCKET_TYPE st, SOCKET_APP_TYPE sat, const ioa_addr *remote_addr, const ioa_addr *local_addr)
  1215. {
  1216. if(!parent_s)
  1217. return NULL;
  1218. ioa_socket_handle ret = create_ioa_socket_from_fd(e, parent_s->fd, parent_s, st, sat, remote_addr, local_addr);
  1219. if(ret) {
  1220. set_socket_ssl(ret,ssl);
  1221. }
  1222. return ret;
  1223. }
  1224. static void close_socket_net_data(ioa_socket_handle s)
  1225. {
  1226. if(s) {
  1227. EVENT_DEL(s->read_event);
  1228. if(s->list_ev) {
  1229. evconnlistener_free(s->list_ev);
  1230. s->list_ev = NULL;
  1231. }
  1232. BUFFEREVENT_FREE(s->conn_bev);
  1233. BUFFEREVENT_FREE(s->bev);
  1234. if (s->ssl) {
  1235. if (!s->broken) {
  1236. if(!(SSL_get_shutdown(s->ssl) & SSL_SENT_SHUTDOWN)) {
  1237. /*
  1238. * SSL_RECEIVED_SHUTDOWN tells SSL_shutdown to act as if we had already
  1239. * received a close notify from the other end. SSL_shutdown will then
  1240. * send the final close notify in reply. The other end will receive the
  1241. * close notify and send theirs. By this time, we will have already
  1242. * closed the socket and the other end's real close notify will never be
  1243. * received. In effect, both sides will think that they have completed a
  1244. * clean shutdown and keep their sessions valid. This strategy will fail
  1245. * if the socket is not ready for writing, in which case this hack will
  1246. * lead to an unclean shutdown and lost session on the other end.
  1247. */
  1248. SSL_set_shutdown(s->ssl, SSL_RECEIVED_SHUTDOWN);
  1249. SSL_shutdown(s->ssl);
  1250. log_socket_event(s, "SSL shutdown received, socket to be closed",0);
  1251. }
  1252. }
  1253. SSL_FREE(s->ssl);
  1254. }
  1255. if (s->fd >= 0) {
  1256. socket_closesocket(s->fd);
  1257. s->fd = -1;
  1258. }
  1259. }
  1260. }
  1261. void detach_socket_net_data(ioa_socket_handle s)
  1262. {
  1263. if(s) {
  1264. EVENT_DEL(s->read_event);
  1265. s->read_cb = NULL;
  1266. s->read_ctx = NULL;
  1267. if(s->list_ev) {
  1268. evconnlistener_free(s->list_ev);
  1269. s->list_ev = NULL;
  1270. }
  1271. s->acb = NULL;
  1272. s->acbarg = NULL;
  1273. BUFFEREVENT_FREE(s->conn_bev);
  1274. s->conn_arg=NULL;
  1275. s->conn_cb=NULL;
  1276. BUFFEREVENT_FREE(s->bev);
  1277. }
  1278. }
  1279. void close_ioa_socket(ioa_socket_handle s)
  1280. {
  1281. if (s) {
  1282. if(s->magic != SOCKET_MAGIC) {
  1283. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "!!! %s wrong magic on socket: 0x%lx, st=%d, sat=%d\n", __FUNCTION__,(long)s, s->st, s->sat);
  1284. return;
  1285. }
  1286. if(s->done) {
  1287. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "!!! %s double free on socket: 0x%lx, st=%d, sat=%d\n", __FUNCTION__,(long)s, s->st, s->sat);
  1288. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "!!! %s socket: 0x%lx was closed\n", __FUNCTION__,(long)s);
  1289. return;
  1290. }
  1291. s->done = 1;
  1292. while(!buffer_list_empty(&(s->bufs)))
  1293. pop_elem_from_buffer_list(&(s->bufs));
  1294. ioa_network_buffer_delete(s->e, s->defer_nbh);
  1295. if(s->bound && s->e && s->e->tp &&
  1296. ((s->sat == RELAY_SOCKET)||(s->sat == RELAY_RTCP_SOCKET))) {
  1297. turnipports_release(s->e->tp,
  1298. ((s->st == TCP_SOCKET) ? STUN_ATTRIBUTE_TRANSPORT_TCP_VALUE : STUN_ATTRIBUTE_TRANSPORT_UDP_VALUE),
  1299. &(s->local_addr));
  1300. }
  1301. if(s->special_session) {
  1302. turn_free(s->special_session,s->special_session_size);
  1303. s->special_session = NULL;
  1304. }
  1305. s->special_session_size = 0;
  1306. delete_socket_from_map(s);
  1307. delete_socket_from_parent(s);
  1308. close_socket_net_data(s);
  1309. s->session = NULL;
  1310. s->sub_session = NULL;
  1311. s->magic = 0;
  1312. turn_free(s,sizeof(ioa_socket));
  1313. }
  1314. }
  1315. ioa_socket_handle detach_ioa_socket(ioa_socket_handle s)
  1316. {
  1317. ioa_socket_handle ret = NULL;
  1318. if (!s) {
  1319. TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR,"Detaching NULL socket\n");
  1320. } else {
  1321. if((s->magic != SOCKET_MAGIC)||(s->done)) {
  1322. TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "!!! %s detach on bad socket: 0x%lx, st=%d, sat=%d\n", __FUNCTION__,(long)s, s->st, s->sat);
  1323. TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "!!! %s socket: 0x%lx was closed\n", __FUNCTION__,(long)s);
  1324. return ret;
  1325. }
  1326. if(s->tobeclosed) {
  1327. TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "!!! %s detach on tobeclosed socket: 0x%lx, st=%d, sat=%d\n", __FUNCTION__,(long)s, s->st, s->sat);
  1328. return ret;
  1329. }
  1330. if(!(s->e)) {
  1331. TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "!!! %s detach on socket without engine: 0x%lx, st=%d, sat=%d\n", __FUNCTION__,(long)s, s->st, s->sat);
  1332. return ret;
  1333. }
  1334. s->tobeclosed = 1;
  1335. if(s->parent_s) {
  1336. if((s->st != UDP_SOCKET) && (s->st != DTLS_SOCKET)) {
  1337. TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "!!! %s detach on non-UDP child socket: 0x%lx, st=%d, sat=%d\n", __FUNCTION__,(long)s, s->st, s->sat);
  1338. return ret;
  1339. }
  1340. }
  1341. evutil_socket_t udp_fd = -1;
  1342. if(s->parent_s) {
  1343. udp_fd = socket(s->local_addr.ss.sa_family, CLIENT_DGRAM_SOCKET_TYPE, CLIENT_DGRAM_SOCKET_PROTOCOL);
  1344. if (udp_fd < 0) {
  1345. perror("socket");
  1346. TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR,"%s: Cannot allocate new socket\n",__FUNCTION__);
  1347. return ret;
  1348. }
  1349. if(sock_bind_to_device(udp_fd, (unsigned char*)(s->e->relay_ifname))<0) {
  1350. TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR,"Cannot bind udp server socket to device %s\n",(char*)(s->e->relay_ifname));
  1351. }
  1352. if(addr_bind(udp_fd,&(s->local_addr),1,1,UDP_SOCKET)<0) {
  1353. TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR,"Cannot bind new detached udp server socket to local addr\n");
  1354. close(udp_fd);
  1355. return ret;
  1356. }
  1357. int connect_err=0;
  1358. if(addr_connect(udp_fd, &(s->remote_addr), &connect_err)<0) {
  1359. TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR,"Cannot connect new detached udp server socket to remote addr\n");
  1360. close(udp_fd);
  1361. return ret;
  1362. }
  1363. set_raw_socket_ttl_options(udp_fd, s->local_addr.ss.sa_family);
  1364. set_raw_socket_tos_options(udp_fd, s->local_addr.ss.sa_family);
  1365. }
  1366. detach_socket_net_data(s);
  1367. while(!buffer_list_empty(&(s->bufs)))
  1368. pop_elem_from_buffer_list(&(s->bufs));
  1369. ioa_network_buffer_delete(s->e, s->defer_nbh);
  1370. ret = (ioa_socket*)turn_malloc(sizeof(ioa_socket));
  1371. if(!ret) {
  1372. TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR,"%s: Cannot allocate new socket structure\n",__FUNCTION__);
  1373. if(udp_fd>=0)
  1374. close(udp_fd);
  1375. return ret;
  1376. }
  1377. ns_bzero(ret,sizeof(ioa_socket));
  1378. ret->magic = SOCKET_MAGIC;
  1379. ret->realm_hash = s->realm_hash;
  1380. SSL* ssl = s->ssl;
  1381. set_socket_ssl(s,NULL);
  1382. set_socket_ssl(ret,ssl);
  1383. ret->fd = s->fd;
  1384. ret->family = get_ioa_socket_address_family(s);
  1385. ret->st = s->st;
  1386. ret->sat = s->sat;
  1387. ret->bound = s->bound;
  1388. ret->local_addr_known = s->local_addr_known;
  1389. addr_cpy(&(ret->local_addr),&(s->local_addr));
  1390. ret->connected = s->connected;
  1391. addr_cpy(&(ret->remote_addr),&(s->remote_addr));
  1392. delete_socket_from_map(s);
  1393. delete_socket_from_parent(s);
  1394. if(udp_fd>=0) {
  1395. ret->fd = udp_fd;
  1396. set_socket_options(ret);
  1397. }
  1398. ret->current_ttl = s->current_ttl;
  1399. ret->default_ttl = s->default_ttl;
  1400. ret->current_tos = s->current_tos;
  1401. ret->default_tos = s->default_tos;
  1402. s->fd = -1;
  1403. }
  1404. return ret;
  1405. }
  1406. ts_ur_super_session *get_ioa_socket_session(ioa_socket_handle s)
  1407. {
  1408. if(s)
  1409. return s->session;
  1410. return NULL;
  1411. }
  1412. void set_ioa_socket_session(ioa_socket_handle s, ts_ur_super_session *ss)
  1413. {
  1414. if(s)
  1415. s->session = ss;
  1416. }
  1417. void clear_ioa_socket_session_if(ioa_socket_handle s, void *ss)
  1418. {
  1419. if(s && ((void*)(s->session)==ss)) {
  1420. s->session=NULL;
  1421. }
  1422. }
  1423. tcp_connection *get_ioa_socket_sub_session(ioa_socket_handle s)
  1424. {
  1425. if(s)
  1426. return s->sub_session;
  1427. return NULL;
  1428. }
  1429. void set_ioa_socket_sub_session(ioa_socket_handle s, tcp_connection *tc)
  1430. {
  1431. if(s)
  1432. s->sub_session = tc;
  1433. }
  1434. int get_ioa_socket_address_family(ioa_socket_handle s) {
  1435. int first_time = 1;
  1436. beg:
  1437. if (!(s && (s->magic == SOCKET_MAGIC) && !(s->done))) {
  1438. return AF_INET;
  1439. } else if(first_time && s->parent_s && (s != s->parent_s)) {
  1440. first_time = 0;
  1441. s = s->parent_s;
  1442. goto beg;
  1443. } else {
  1444. return s->family;
  1445. }
  1446. }
  1447. SOCKET_TYPE get_ioa_socket_type(ioa_socket_handle s)
  1448. {
  1449. if(s)
  1450. return s->st;
  1451. return UNKNOWN_SOCKET;
  1452. }
  1453. SOCKET_APP_TYPE get_ioa_socket_app_type(ioa_socket_handle s)
  1454. {
  1455. if(s)
  1456. return s->sat;
  1457. return UNKNOWN_APP_SOCKET;
  1458. }
  1459. void set_ioa_socket_app_type(ioa_socket_handle s, SOCKET_APP_TYPE sat) {
  1460. if(s)
  1461. s->sat = sat;
  1462. }
  1463. ioa_addr* get_local_addr_from_ioa_socket(ioa_socket_handle s)
  1464. {
  1465. if (s && (s->magic == SOCKET_MAGIC) && !(s->done)) {
  1466. if(s->parent_s) {
  1467. s = s->parent_s;
  1468. }
  1469. if (s->local_addr_known) {
  1470. return &(s->local_addr);
  1471. } else if (s->bound && (addr_get_port(&(s->local_addr)) > 0)) {
  1472. s->local_addr_known = 1;
  1473. return &(s->local_addr);
  1474. } else {
  1475. ioa_addr tmpaddr;
  1476. if (addr_get_from_sock(s->fd, &tmpaddr) == 0) {
  1477. if(addr_get_port(&tmpaddr)>0) {
  1478. s->local_addr_known = 1;
  1479. s->bound = 1;
  1480. if(addr_any(&(s->local_addr))) {
  1481. addr_cpy(&(s->local_addr),&tmpaddr);
  1482. } else {
  1483. addr_set_port(&(s->local_addr),addr_get_port(&tmpaddr));
  1484. }
  1485. return &(s->local_addr);
  1486. }
  1487. if(addr_any(&(s->local_addr))) {
  1488. addr_cpy(&(s->local_addr),&tmpaddr);
  1489. }
  1490. return &(s->local_addr);
  1491. }
  1492. }
  1493. }
  1494. return NULL;
  1495. }
  1496. ioa_addr* get_remote_addr_from_ioa_socket(ioa_socket_handle s)
  1497. {
  1498. if (s && (s->magic == SOCKET_MAGIC) && !(s->done)) {
  1499. if (s->connected) {
  1500. return &(s->remote_addr);
  1501. }
  1502. }
  1503. return NULL;
  1504. }
  1505. int get_local_mtu_ioa_socket(ioa_socket_handle s)
  1506. {
  1507. if(s) {
  1508. if(s->parent_s)
  1509. s = s->parent_s;
  1510. return get_socket_mtu(s->fd, s->family, (s->e && eve(s->e->verbose)));
  1511. }
  1512. return -1;
  1513. }
  1514. /*
  1515. * Return: -1 - error, 0 or >0 - OK
  1516. * *read_len -1 - no data, >=0 - data available
  1517. */
  1518. int ssl_read(evutil_socket_t fd, SSL* ssl, ioa_network_buffer_handle nbh, int verbose)
  1519. {
  1520. int ret = 0;
  1521. if (!ssl || !nbh)
  1522. return -1;
  1523. s08bits* buffer = (s08bits*)ioa_network_buffer_data(nbh);
  1524. int buf_size = (int)ioa_network_buffer_get_capacity_udp();
  1525. int read_len = (int)ioa_network_buffer_get_size(nbh);
  1526. if(read_len < 1)
  1527. return -1;
  1528. s08bits *new_buffer = buffer + buf_size;
  1529. int old_buffer_len = read_len;
  1530. int len = 0;
  1531. if (eve(verbose)) {
  1532. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: before read...\n", __FUNCTION__);
  1533. }
  1534. BIO *wbio = SSL_get_wbio(ssl);
  1535. if(wbio) {
  1536. BIO_set_fd(wbio,fd,BIO_NOCLOSE);
  1537. }
  1538. BIO* rbio = BIO_new_mem_buf(buffer, old_buffer_len);
  1539. BIO_set_mem_eof_return(rbio, -1);
  1540. ssl->rbio = rbio;
  1541. int if1 = SSL_is_init_finished(ssl);
  1542. do {
  1543. len = SSL_read(ssl, new_buffer, buf_size);
  1544. } while (len < 0 && (errno == EINTR));
  1545. int if2 = SSL_is_init_finished(ssl);
  1546. if (eve(verbose)) {
  1547. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: after read: %d\n", __FUNCTION__, len);
  1548. }
  1549. if(SSL_get_shutdown(ssl)) {
  1550. ret = -1;
  1551. } else if (!if1 && if2) {
  1552. if(verbose && SSL_get_peer_certificate(ssl)) {
  1553. printf("\n------------------------------------------------------------\n");
  1554. X509_NAME_print_ex_fp(stdout, X509_get_subject_name(SSL_get_peer_certificate(ssl)), 1,
  1555. XN_FLAG_MULTILINE);
  1556. printf("\n\n Cipher: %s\n", SSL_CIPHER_get_name(SSL_get_current_cipher(ssl)));
  1557. printf("\n------------------------------------------------------------\n\n");
  1558. }
  1559. ret = 0;
  1560. } else if (len < 0 && ((errno == ENOBUFS) || (errno == EAGAIN))) {
  1561. if (eve(verbose)) {
  1562. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: ENOBUFS/EAGAIN\n", __FUNCTION__);
  1563. }
  1564. ret = 0;
  1565. } else {
  1566. if (eve(verbose)) {
  1567. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: read %d bytes\n", __FUNCTION__, (int) len);
  1568. }
  1569. if (len >= 0) {
  1570. ret = len;
  1571. } else {
  1572. switch (SSL_get_error(ssl, len)){
  1573. case SSL_ERROR_NONE:
  1574. //???
  1575. ret = 0;
  1576. break;
  1577. case SSL_ERROR_WANT_READ:
  1578. ret = 0;
  1579. break;
  1580. case SSL_ERROR_WANT_WRITE:
  1581. ret = 0;
  1582. break;
  1583. case SSL_ERROR_ZERO_RETURN:
  1584. ret = 0;
  1585. break;
  1586. case SSL_ERROR_SYSCALL:
  1587. {
  1588. int err = errno;
  1589. if (handle_socket_error()) {
  1590. ret = 0;
  1591. } else {
  1592. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "TLS Socket read error: %d\n", err);
  1593. ret = -1;
  1594. }
  1595. break;
  1596. }
  1597. case SSL_ERROR_SSL:
  1598. if (verbose) {
  1599. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "SSL read error: ");
  1600. s08bits buf[65536];
  1601. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s (%d)\n", ERR_error_string(ERR_get_error(), buf), SSL_get_error(ssl, len));
  1602. }
  1603. if (verbose)
  1604. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "SSL connection closed.\n");
  1605. ret = -1;
  1606. break;
  1607. default:
  1608. if (verbose) {
  1609. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Unexpected error while reading!\n");
  1610. }
  1611. ret = -1;
  1612. }
  1613. }
  1614. }
  1615. if(ret>0) {
  1616. ioa_network_buffer_add_offset_size(nbh, (u16bits)buf_size, 0, (size_t)ret);
  1617. }
  1618. BIO_free(rbio);
  1619. ssl->rbio = NULL;
  1620. return ret;
  1621. }
  1622. static int socket_readerr(evutil_socket_t fd, ioa_addr *orig_addr)
  1623. {
  1624. if ((fd < 0) || !orig_addr)
  1625. return -1;
  1626. #if defined(CMSG_SPACE) && defined(MSG_ERRQUEUE) && defined(IP_RECVERR)
  1627. u08bits ecmsg[TURN_CMSG_SZ+1];
  1628. int flags = MSG_ERRQUEUE;
  1629. int len = 0;
  1630. struct msghdr msg;
  1631. struct iovec iov;
  1632. char buffer[65536];
  1633. char *cmsg = (char*)ecmsg;
  1634. msg.msg_control = cmsg;
  1635. msg.msg_controllen = TURN_CMSG_SZ;
  1636. /* CMSG_SPACE(sizeof(recv_ttl)+sizeof(recv_tos)) */
  1637. msg.msg_name = orig_addr;
  1638. msg.msg_namelen = (socklen_t)get_ioa_addr_len(orig_addr);
  1639. msg.msg_iov = &iov;
  1640. msg.msg_iovlen = 1;
  1641. msg.msg_iov->iov_base = buffer;
  1642. msg.msg_iov->iov_len = sizeof(buffer);
  1643. msg.msg_flags = 0;
  1644. int try_cycle = 0;
  1645. do {
  1646. do {
  1647. len = recvmsg(fd,&msg,flags);
  1648. } while (len < 0 && (errno == EINTR));
  1649. } while((len>0)&&(try_cycle++<MAX_ERRORS_IN_UDP_BATCH));
  1650. #endif
  1651. return 0;
  1652. }
  1653. typedef unsigned char recv_ttl_t;
  1654. typedef unsigned char recv_tos_t;
  1655. int udp_recvfrom(evutil_socket_t fd, ioa_addr* orig_addr, const ioa_addr *like_addr, s08bits* buffer, int buf_size, int *ttl, int *tos, s08bits *ecmsg, int flags, u32bits *errcode)
  1656. {
  1657. int len = 0;
  1658. if (fd < 0 || !orig_addr || !like_addr || !buffer)
  1659. return -1;
  1660. if(errcode)
  1661. *errcode = 0;
  1662. int slen = get_ioa_addr_len(like_addr);
  1663. recv_ttl_t recv_ttl = TTL_DEFAULT;
  1664. recv_tos_t recv_tos = TOS_DEFAULT;
  1665. #if !defined(CMSG_SPACE)
  1666. do {
  1667. len = recvfrom(fd, buffer, buf_size, flags, (struct sockaddr*) orig_addr, (socklen_t*) &slen);
  1668. } while (len < 0 && (errno == EINTR));
  1669. if(len<0 && errcode)
  1670. *errcode = (u32bits)errno;
  1671. #else
  1672. struct msghdr msg;
  1673. struct iovec iov;
  1674. char *cmsg = (char*)ecmsg;
  1675. msg.msg_control = cmsg;
  1676. msg.msg_controllen = TURN_CMSG_SZ;
  1677. /* CMSG_SPACE(sizeof(recv_ttl)+sizeof(recv_tos)) */
  1678. msg.msg_name = orig_addr;
  1679. msg.msg_namelen = (socklen_t)slen;
  1680. msg.msg_iov = &iov;
  1681. msg.msg_iovlen = 1;
  1682. msg.msg_iov->iov_base = buffer;
  1683. msg.msg_iov->iov_len = (size_t)buf_size;
  1684. msg.msg_flags = 0;
  1685. #if defined(MSG_ERRQUEUE)
  1686. int try_cycle = 0;
  1687. try_again:
  1688. #endif
  1689. do {
  1690. len = recvmsg(fd,&msg,flags);
  1691. } while (len < 0 && (errno == EINTR));
  1692. #if defined(MSG_ERRQUEUE)
  1693. if(flags & MSG_ERRQUEUE) {
  1694. if((len>0)&&(try_cycle++<MAX_ERRORS_IN_UDP_BATCH)) goto try_again;
  1695. }
  1696. if((len<0) && (!(flags & MSG_ERRQUEUE))) {
  1697. //Linux
  1698. int eflags = MSG_ERRQUEUE | MSG_DONTWAIT;
  1699. u32bits errcode1 = 0;
  1700. udp_recvfrom(fd, orig_addr, like_addr, buffer, buf_size, ttl, tos, ecmsg, eflags, &errcode1);
  1701. //try again...
  1702. do {
  1703. len = recvmsg(fd,&msg,flags);
  1704. } while (len < 0 && (errno == EINTR));
  1705. }
  1706. #endif
  1707. if (len >= 0) {
  1708. struct cmsghdr *cmsgh;
  1709. // Receive auxiliary data in msg
  1710. for (cmsgh = CMSG_FIRSTHDR(&msg); cmsgh != NULL; cmsgh
  1711. = CMSG_NXTHDR(&msg,cmsgh)) {
  1712. int l = cmsgh->cmsg_level;
  1713. int t = cmsgh->cmsg_type;
  1714. switch(l) {
  1715. case IPPROTO_IP:
  1716. switch(t) {
  1717. #if defined(IP_RECVTTL)
  1718. case IP_RECVTTL:
  1719. case IP_TTL:
  1720. recv_ttl = *((recv_ttl_t *) CMSG_DATA(cmsgh));
  1721. break;
  1722. #endif
  1723. #if defined(IP_RECVTOS)
  1724. case IP_RECVTOS:
  1725. case IP_TOS:
  1726. recv_tos = *((recv_tos_t *) CMSG_DATA(cmsgh));
  1727. break;
  1728. #endif
  1729. #if defined(IP_RECVERR)
  1730. case IP_RECVERR:
  1731. {
  1732. struct turn_sock_extended_err *e=(struct turn_sock_extended_err*) CMSG_DATA(cmsgh);
  1733. if(errcode)
  1734. *errcode = e->ee_errno;
  1735. }
  1736. break;
  1737. #endif
  1738. default:
  1739. ;
  1740. /* no break */
  1741. };
  1742. break;
  1743. case IPPROTO_IPV6:
  1744. switch(t) {
  1745. #if defined(IPV6_RECVHOPLIMIT)
  1746. case IPV6_RECVHOPLIMIT:
  1747. case IPV6_HOPLIMIT:
  1748. recv_ttl = *((recv_ttl_t *) CMSG_DATA(cmsgh));
  1749. break;
  1750. #endif
  1751. #if defined(IPV6_RECVTCLASS)
  1752. case IPV6_RECVTCLASS:
  1753. case IPV6_TCLASS:
  1754. recv_tos = *((recv_tos_t *) CMSG_DATA(cmsgh));
  1755. break;
  1756. #endif
  1757. #if defined(IPV6_RECVERR)
  1758. case IPV6_RECVERR:
  1759. {
  1760. struct turn_sock_extended_err *e=(struct turn_sock_extended_err*) CMSG_DATA(cmsgh);
  1761. if(errcode)
  1762. *errcode = e->ee_errno;
  1763. }
  1764. break;
  1765. #endif
  1766. default:
  1767. ;
  1768. /* no break */
  1769. };
  1770. break;
  1771. default:
  1772. ;
  1773. /* no break */
  1774. };
  1775. }
  1776. }
  1777. #endif
  1778. *ttl = recv_ttl;
  1779. CORRECT_RAW_TTL(*ttl);
  1780. *tos = recv_tos;
  1781. CORRECT_RAW_TOS(*tos);
  1782. return len;
  1783. }
  1784. #if TLS_SUPPORTED
  1785. static TURN_TLS_TYPE check_tentative_tls(ioa_socket_raw fd)
  1786. {
  1787. TURN_TLS_TYPE ret = TURN_TLS_NO;
  1788. char s[12];
  1789. int len = 0;
  1790. do {
  1791. len = (int)recv(fd, s, sizeof(s), MSG_PEEK);
  1792. } while (len < 0 && (errno == EINTR));
  1793. if(len>0 && ((size_t)len == sizeof(s))) {
  1794. if((s[0]==22)&&(s[1]==3)&&(s[5]==1)&&(s[9]==3)) {
  1795. char max_supported = (char)(TURN_TLS_TOTAL-2);
  1796. if(s[10] >= max_supported)
  1797. ret = TURN_TLS_SSL23; /* compatibility mode */
  1798. else
  1799. ret = (TURN_TLS_TYPE)(s[10]+1);
  1800. } else if((s[2]==1)&&(s[3]==3)) {
  1801. ret = TURN_TLS_SSL23; /* compatibility mode */
  1802. }
  1803. }
  1804. return ret;
  1805. }
  1806. #endif
  1807. static int socket_input_worker(ioa_socket_handle s)
  1808. {
  1809. int len = 0;
  1810. int ret = 0;
  1811. size_t app_msg_len = 0;
  1812. int ttl = TTL_IGNORE;
  1813. int tos = TOS_IGNORE;
  1814. ioa_addr remote_addr;
  1815. int try_again = 0;
  1816. int try_ok = 0;
  1817. int try_cycle = 0;
  1818. const int MAX_TRIES = 16;
  1819. if(!s)
  1820. return 0;
  1821. if((s->magic != SOCKET_MAGIC)||(s->done)) {
  1822. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "!!!%s on socket: 0x%lx, st=%d, sat=%d\n", __FUNCTION__,(long)s, s->st, s->sat);
  1823. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "!!! %s socket: 0x%lx was closed\n", __FUNCTION__,(long)s);
  1824. return -1;
  1825. }
  1826. if(!(s->e))
  1827. return 0;
  1828. if(s->tobeclosed)
  1829. return 0;
  1830. if(s->connected)
  1831. addr_cpy(&remote_addr,&(s->remote_addr));
  1832. if(tcp_congestion_control && s->sub_session && s->bev) {
  1833. if(s == s->sub_session->client_s && (s->sub_session->peer_s)) {
  1834. if(!is_socket_writeable(s->sub_session->peer_s, STUN_BUFFER_SIZE,__FUNCTION__,0)) {
  1835. if(bufferevent_enabled(s->bev,EV_READ)) {
  1836. bufferevent_disable(s->bev,EV_READ);
  1837. }
  1838. }
  1839. } else if(s == s->sub_session->peer_s && (s->sub_session->client_s)) {
  1840. if(!is_socket_writeable(s->sub_session->client_s, STUN_BUFFER_SIZE,__FUNCTION__,1)) {
  1841. if(bufferevent_enabled(s->bev,EV_READ)) {
  1842. bufferevent_disable(s->bev,EV_READ);
  1843. }
  1844. }
  1845. }
  1846. }
  1847. if((s->st == TLS_SOCKET)||(s->st == TLS_SCTP_SOCKET)) {
  1848. #if TLS_SUPPORTED
  1849. SSL *ctx = bufferevent_openssl_get_ssl(s->bev);
  1850. if(!ctx || SSL_get_shutdown(ctx)) {
  1851. s->tobeclosed = 1;
  1852. return 0;
  1853. }
  1854. #endif
  1855. } else if(s->st == DTLS_SOCKET) {
  1856. if(!(s->ssl) || SSL_get_shutdown(s->ssl)) {
  1857. s->tobeclosed = 1;
  1858. return 0;
  1859. }
  1860. }
  1861. if(!(s->e))
  1862. return 0;
  1863. if(s->st == TENTATIVE_TCP_SOCKET) {
  1864. EVENT_DEL(s->read_event);
  1865. #if TLS_SUPPORTED
  1866. TURN_TLS_TYPE tls_type = check_tentative_tls(s->fd);
  1867. if(tls_type) {
  1868. s->st = TLS_SOCKET;
  1869. if(s->ssl) {
  1870. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "!!!%s on socket: 0x%lx, st=%d, sat=%d: ssl already exist\n", __FUNCTION__,(long)s, s->st, s->sat);
  1871. }
  1872. if(s->bev) {
  1873. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "!!!%s on socket: 0x%lx, st=%d, sat=%d: bev already exist\n", __FUNCTION__,(long)s, s->st, s->sat);
  1874. }
  1875. switch(tls_type) {
  1876. #if TLSv1_2_SUPPORTED
  1877. case TURN_TLS_v1_2:
  1878. if(s->e->tls_ctx_v1_2) {
  1879. set_socket_ssl(s,SSL_NEW(s->e->tls_ctx_v1_2));
  1880. }
  1881. break;
  1882. #endif
  1883. #if TLSv1_1_SUPPORTED
  1884. case TURN_TLS_v1_1:
  1885. if(s->e->tls_ctx_v1_1) {
  1886. set_socket_ssl(s,SSL_NEW(s->e->tls_ctx_v1_1));
  1887. }
  1888. break;
  1889. #endif
  1890. case TURN_TLS_v1_0:
  1891. if(s->e->tls_ctx_v1_0) {
  1892. set_socket_ssl(s,SSL_NEW(s->e->tls_ctx_v1_0));
  1893. }
  1894. break;
  1895. default:
  1896. if(s->e->tls_ctx_ssl23) {
  1897. set_socket_ssl(s,SSL_NEW(s->e->tls_ctx_ssl23));
  1898. } else {
  1899. s->tobeclosed = 1;
  1900. return 0;
  1901. }
  1902. };
  1903. if(s->ssl) {
  1904. s->bev = bufferevent_openssl_socket_new(s->e->event_base,
  1905. s->fd,
  1906. s->ssl,
  1907. BUFFEREVENT_SSL_ACCEPTING,
  1908. TURN_BUFFEREVENTS_OPTIONS);
  1909. debug_ptr_add(s->bev);
  1910. bufferevent_setcb(s->bev, socket_input_handler_bev, socket_output_handler_bev,
  1911. eventcb_bev, s);
  1912. bufferevent_setwatermark(s->bev, EV_READ|EV_WRITE, 0, BUFFEREVENT_HIGH_WATERMARK);
  1913. bufferevent_enable(s->bev, EV_READ|EV_WRITE); /* Start reading. */
  1914. }
  1915. } else
  1916. #endif //TLS_SUPPORTED
  1917. {
  1918. s->st = TCP_SOCKET;
  1919. if(s->bev) {
  1920. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "!!!%s on socket: 0x%lx, st=%d, sat=%d: bev already exist\n", __FUNCTION__,(long)s, s->st, s->sat);
  1921. }
  1922. s->bev = bufferevent_socket_new(s->e->event_base,
  1923. s->fd,
  1924. TURN_BUFFEREVENTS_OPTIONS);
  1925. debug_ptr_add(s->bev);
  1926. bufferevent_setcb(s->bev, socket_input_handler_bev, socket_output_handler_bev,
  1927. eventcb_bev, s);
  1928. bufferevent_setwatermark(s->bev, EV_READ|EV_WRITE, 0, BUFFEREVENT_HIGH_WATERMARK);
  1929. bufferevent_enable(s->bev, EV_READ|EV_WRITE); /* Start reading. */
  1930. }
  1931. } else if(s->st == TENTATIVE_SCTP_SOCKET) {
  1932. EVENT_DEL(s->read_event);
  1933. #if TLS_SUPPORTED
  1934. TURN_TLS_TYPE tls_type = check_tentative_tls(s->fd);
  1935. if(tls_type) {
  1936. s->st = TLS_SCTP_SOCKET;
  1937. if(s->ssl) {
  1938. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "!!!%s on socket: 0x%lx, st=%d, sat=%d: ssl already exist\n", __FUNCTION__,(long)s, s->st, s->sat);
  1939. }
  1940. if(s->bev) {
  1941. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "!!!%s on socket: 0x%lx, st=%d, sat=%d: bev already exist\n", __FUNCTION__,(long)s, s->st, s->sat);
  1942. }
  1943. switch(tls_type) {
  1944. #if TLSv1_2_SUPPORTED
  1945. case TURN_TLS_v1_2:
  1946. if(s->e->tls_ctx_v1_2) {
  1947. set_socket_ssl(s,SSL_NEW(s->e->tls_ctx_v1_2));
  1948. }
  1949. break;
  1950. #endif
  1951. #if TLSv1_1_SUPPORTED
  1952. case TURN_TLS_v1_1:
  1953. if(s->e->tls_ctx_v1_1) {
  1954. set_socket_ssl(s,SSL_NEW(s->e->tls_ctx_v1_1));
  1955. }
  1956. break;
  1957. #endif
  1958. case TURN_TLS_v1_0:
  1959. if(s->e->tls_ctx_v1_0) {
  1960. set_socket_ssl(s,SSL_NEW(s->e->tls_ctx_v1_0));
  1961. }
  1962. break;
  1963. default:
  1964. if(s->e->tls_ctx_ssl23) {
  1965. set_socket_ssl(s,SSL_NEW(s->e->tls_ctx_ssl23));
  1966. } else {
  1967. s->tobeclosed = 1;
  1968. return 0;
  1969. }
  1970. };
  1971. if(s->ssl) {
  1972. s->bev = bufferevent_openssl_socket_new(s->e->event_base,
  1973. s->fd,
  1974. s->ssl,
  1975. BUFFEREVENT_SSL_ACCEPTING,
  1976. TURN_BUFFEREVENTS_OPTIONS);
  1977. debug_ptr_add(s->bev);
  1978. bufferevent_setcb(s->bev, socket_input_handler_bev, socket_output_handler_bev,
  1979. eventcb_bev, s);
  1980. bufferevent_setwatermark(s->bev, EV_READ|EV_WRITE, 0, BUFFEREVENT_HIGH_WATERMARK);
  1981. bufferevent_enable(s->bev, EV_READ|EV_WRITE); /* Start reading. */
  1982. }
  1983. } else
  1984. #endif //TLS_SUPPORTED
  1985. {
  1986. s->st = SCTP_SOCKET;
  1987. if(s->bev) {
  1988. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "!!!%s on socket: 0x%lx, st=%d, sat=%d: bev already exist\n", __FUNCTION__,(long)s, s->st, s->sat);
  1989. }
  1990. s->bev = bufferevent_socket_new(s->e->event_base,
  1991. s->fd,
  1992. TURN_BUFFEREVENTS_OPTIONS);
  1993. debug_ptr_add(s->bev);
  1994. bufferevent_setcb(s->bev, socket_input_handler_bev, socket_output_handler_bev,
  1995. eventcb_bev, s);
  1996. bufferevent_setwatermark(s->bev, EV_READ|EV_WRITE, 0, BUFFEREVENT_HIGH_WATERMARK);
  1997. bufferevent_enable(s->bev, EV_READ|EV_WRITE); /* Start reading. */
  1998. }
  1999. }
  2000. try_start:
  2001. if(!(s->e))
  2002. return 0;
  2003. try_again=0;
  2004. try_ok=0;
  2005. stun_buffer_list_elem *buf_elem = new_blist_elem(s->e);
  2006. len = -1;
  2007. if(s->bev) { /* TCP & TLS & SCTP & SCTP/TLS */
  2008. struct evbuffer *inbuf = bufferevent_get_input(s->bev);
  2009. if(inbuf) {
  2010. ev_ssize_t blen = evbuffer_copyout(inbuf, buf_elem->buf.buf, STUN_BUFFER_SIZE);
  2011. if(blen>0) {
  2012. int mlen = 0;
  2013. if(blen>(ev_ssize_t)STUN_BUFFER_SIZE)
  2014. blen=(ev_ssize_t)STUN_BUFFER_SIZE;
  2015. if(is_stream_socket(s->st) && ((s->sat == TCP_CLIENT_DATA_SOCKET)||(s->sat==TCP_RELAY_DATA_SOCKET))) {
  2016. mlen = blen;
  2017. } else {
  2018. mlen = stun_get_message_len_str(buf_elem->buf.buf, blen, 1, &app_msg_len);
  2019. }
  2020. if(mlen>0 && mlen<=(int)blen) {
  2021. len = (int)bufferevent_read(s->bev, buf_elem->buf.buf, mlen);
  2022. if(len < 0) {
  2023. ret = -1;
  2024. s->tobeclosed = 1;
  2025. s->broken = 1;
  2026. log_socket_event(s, "socket read failed, to be closed",1);
  2027. } else if((s->st == TLS_SOCKET)||(s->st == TLS_SCTP_SOCKET)) {
  2028. #if TLS_SUPPORTED
  2029. SSL *ctx = bufferevent_openssl_get_ssl(s->bev);
  2030. if(!ctx || SSL_get_shutdown(ctx)) {
  2031. ret = -1;
  2032. s->tobeclosed = 1;
  2033. }
  2034. #endif
  2035. }
  2036. if(ret != -1) {
  2037. ret = len;
  2038. }
  2039. }
  2040. } else if(blen<0) {
  2041. s->tobeclosed = 1;
  2042. s->broken = 1;
  2043. ret = -1;
  2044. log_socket_event(s, "socket buffer copy failed, to be closed",1);
  2045. }
  2046. } else {
  2047. s->tobeclosed = 1;
  2048. s->broken = 1;
  2049. ret = -1;
  2050. log_socket_event(s, "socket input failed, socket to be closed",1);
  2051. }
  2052. if(len == 0)
  2053. len = -1;
  2054. } else if(s->fd>=0){ /* UDP and DTLS */
  2055. ret = udp_recvfrom(s->fd, &remote_addr, &(s->local_addr), (s08bits*)(buf_elem->buf.buf), UDP_STUN_BUFFER_SIZE, &ttl, &tos, s->e->cmsg, 0, NULL);
  2056. len = ret;
  2057. if(s->ssl && (len>0)) { /* DTLS */
  2058. send_ssl_backlog_buffers(s);
  2059. buf_elem->buf.len = (size_t)len;
  2060. ret = ssl_read(s->fd, s->ssl, (ioa_network_buffer_handle)buf_elem, ((s->e) && s->e->verbose));
  2061. addr_cpy(&remote_addr,&(s->remote_addr));
  2062. if(ret < 0) {
  2063. len = -1;
  2064. s->tobeclosed = 1;
  2065. s->broken = 1;
  2066. log_socket_event(s, "SSL read failed, to be closed",0);
  2067. } else {
  2068. len = (int)ioa_network_buffer_get_size((ioa_network_buffer_handle)buf_elem);
  2069. }
  2070. if((ret!=-1)&&(len>0))
  2071. try_again = 1;
  2072. } else { /* UDP */
  2073. if(ret>=0)
  2074. try_again = 1;
  2075. }
  2076. } else {
  2077. s->tobeclosed = 1;
  2078. s->broken = 1;
  2079. ret = -1;
  2080. log_socket_event(s, "socket unknown error, to be closed",1);
  2081. }
  2082. if ((ret!=-1) && (len >= 0)) {
  2083. if(app_msg_len)
  2084. buf_elem->buf.len = app_msg_len;
  2085. else
  2086. buf_elem->buf.len = len;
  2087. if(ioa_socket_check_bandwidth(s,buf_elem,1)) {
  2088. if(s->read_cb) {
  2089. ioa_net_data nd;
  2090. ns_bzero(&nd,sizeof(ioa_net_data));
  2091. addr_cpy(&(nd.src_addr),&remote_addr);
  2092. nd.nbh = buf_elem;
  2093. nd.recv_ttl = ttl;
  2094. nd.recv_tos = tos;
  2095. s->read_cb(s, IOA_EV_READ, &nd, s->read_ctx, 1);
  2096. if(nd.nbh)
  2097. free_blist_elem(s->e,buf_elem);
  2098. buf_elem = NULL;
  2099. try_ok = 1;
  2100. } else {
  2101. ioa_network_buffer_delete(s->e, s->defer_nbh);
  2102. s->defer_nbh = buf_elem;
  2103. buf_elem = NULL;
  2104. }
  2105. }
  2106. }
  2107. if(buf_elem) {
  2108. free_blist_elem(s->e,buf_elem);
  2109. buf_elem = NULL;
  2110. }
  2111. if(try_again && try_ok && !(s->done) &&
  2112. !(s->tobeclosed) && ((++try_cycle)<MAX_TRIES) &&
  2113. !(s->parent_s)) {
  2114. goto try_start;
  2115. }
  2116. return len;
  2117. }
  2118. static void socket_input_handler(evutil_socket_t fd, short what, void* arg)
  2119. {
  2120. if (!(what & EV_READ))
  2121. return;
  2122. if(!arg) {
  2123. read_spare_buffer(fd);
  2124. return;
  2125. }
  2126. ioa_socket_handle s = (ioa_socket_handle)arg;
  2127. if(!s) {
  2128. read_spare_buffer(fd);
  2129. return;
  2130. }
  2131. if((s->magic != SOCKET_MAGIC)||(s->done)) {
  2132. read_spare_buffer(fd);
  2133. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "!!!%s on bad socket, ev=%d: 0x%lx, st=%d, sat=%d\n", __FUNCTION__,(int)what,(long)s, s->st, s->sat);
  2134. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "!!! %s socket: 0x%lx was closed\n", __FUNCTION__,(long)s);
  2135. return;
  2136. }
  2137. if(fd != s->fd) {
  2138. read_spare_buffer(fd);
  2139. return;
  2140. }
  2141. if (!ioa_socket_tobeclosed(s))
  2142. socket_input_worker(s);
  2143. else
  2144. read_spare_buffer(fd);
  2145. if((s->magic != SOCKET_MAGIC)||(s->done)) {
  2146. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "!!!%s (1) on socket, ev=%d: 0x%lx, st=%d, sat=%d\n", __FUNCTION__,(int)what,(long)s, s->st, s->sat);
  2147. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "!!! %s socket: 0x%lx was closed\n", __FUNCTION__,(long)s);
  2148. return;
  2149. }
  2150. close_ioa_socket_after_processing_if_necessary(s);
  2151. }
  2152. void close_ioa_socket_after_processing_if_necessary(ioa_socket_handle s)
  2153. {
  2154. if (s && ioa_socket_tobeclosed(s)) {
  2155. if(s->special_session) {
  2156. turn_free(s->special_session,s->special_session_size);
  2157. s->special_session = NULL;
  2158. }
  2159. s->special_session_size = 0;
  2160. if(!(s->session) && !(s->sub_session)) {
  2161. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s https server socket closed: 0x%lx, st=%d, sat=%d\n", __FUNCTION__,(long)s, get_ioa_socket_type(s), get_ioa_socket_app_type(s));
  2162. IOA_CLOSE_SOCKET(s);
  2163. return;
  2164. }
  2165. switch (s->sat){
  2166. case TCP_CLIENT_DATA_SOCKET:
  2167. case TCP_RELAY_DATA_SOCKET:
  2168. {
  2169. tcp_connection *tc = s->sub_session;
  2170. if (tc) {
  2171. delete_tcp_connection(tc);
  2172. s->sub_session = NULL;
  2173. }
  2174. }
  2175. break;
  2176. default:
  2177. {
  2178. ts_ur_super_session *ss = s->session;
  2179. if (ss) {
  2180. turn_turnserver *server = (turn_turnserver *) ss->server;
  2181. if (server) {
  2182. shutdown_client_connection(server, ss, 0, "general");
  2183. }
  2184. }
  2185. }
  2186. }
  2187. }
  2188. }
  2189. static void socket_output_handler_bev(struct bufferevent *bev, void* arg)
  2190. {
  2191. UNUSED_ARG(bev);
  2192. UNUSED_ARG(arg);
  2193. if (tcp_congestion_control) {
  2194. if (bev && arg) {
  2195. ioa_socket_handle s = (ioa_socket_handle) arg;
  2196. if(s->in_write)
  2197. return;
  2198. if ((s->magic != SOCKET_MAGIC)||(s->done)||(bev != s->bev)) {
  2199. return;
  2200. }
  2201. if (s->tobeclosed) {
  2202. if (bufferevent_enabled(bev,EV_READ)) {
  2203. bufferevent_disable(bev,EV_READ);
  2204. }
  2205. return;
  2206. }
  2207. if (s->sub_session) {
  2208. if (s == s->sub_session->client_s) {
  2209. if (s->sub_session->peer_s && s->sub_session->peer_s->bev) {
  2210. if (!bufferevent_enabled(s->sub_session->peer_s->bev,
  2211. EV_READ)) {
  2212. if (is_socket_writeable(s->sub_session->peer_s,
  2213. STUN_BUFFER_SIZE, __FUNCTION__, 3)) {
  2214. bufferevent_enable(s->sub_session->peer_s->bev,EV_READ);
  2215. socket_input_handler_bev(
  2216. s->sub_session->peer_s->bev,
  2217. s->sub_session->peer_s);
  2218. }
  2219. }
  2220. }
  2221. } else if (s == s->sub_session->peer_s) {
  2222. if (s->sub_session->client_s
  2223. && s->sub_session->client_s->bev) {
  2224. if (!bufferevent_enabled(s->sub_session->client_s->bev,
  2225. EV_READ)) {
  2226. if (is_socket_writeable(s->sub_session->client_s,
  2227. STUN_BUFFER_SIZE, __FUNCTION__, 4)) {
  2228. bufferevent_enable(s->sub_session->client_s->bev, EV_READ);
  2229. socket_input_handler_bev(
  2230. s->sub_session->client_s->bev,
  2231. s->sub_session->client_s);
  2232. }
  2233. }
  2234. }
  2235. }
  2236. }
  2237. }
  2238. }
  2239. }
  2240. static int read_spare_buffer_bev(struct bufferevent *bev)
  2241. {
  2242. if(bev) {
  2243. char some_buffer[8192];
  2244. bufferevent_read(bev, some_buffer, sizeof(some_buffer));
  2245. }
  2246. return 0;
  2247. }
  2248. static void socket_input_handler_bev(struct bufferevent *bev, void* arg)
  2249. {
  2250. if (bev) {
  2251. if(!arg) {
  2252. read_spare_buffer_bev(bev);
  2253. return;
  2254. }
  2255. ioa_socket_handle s = (ioa_socket_handle) arg;
  2256. if(bev != s->bev) {
  2257. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "!!! %s socket: 0x%lx: wrong bev\n", __FUNCTION__,(long)s);
  2258. read_spare_buffer_bev(bev);
  2259. return;
  2260. }
  2261. if((s->magic != SOCKET_MAGIC)||(s->done)) {
  2262. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "!!!%s on socket: 0x%lx, st=%d, sat=%d\n", __FUNCTION__, (long) s, s->st, s->sat);
  2263. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "!!! %s socket: 0x%lx was closed\n", __FUNCTION__,(long)s);
  2264. read_spare_buffer_bev(bev);
  2265. return;
  2266. }
  2267. {
  2268. size_t cycle = 0;
  2269. do {
  2270. if(ioa_socket_tobeclosed(s)) {
  2271. read_spare_buffer_bev(s->bev);
  2272. break;
  2273. }
  2274. if (socket_input_worker(s) <= 0)
  2275. break;
  2276. } while((cycle++<128) && (s->bev));
  2277. }
  2278. if((s->magic != SOCKET_MAGIC)||(s->done)) {
  2279. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "!!!%s (1) on socket: 0x%lx, st=%d, sat=%d\n", __FUNCTION__, (long) s, s->st, s->sat);
  2280. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "!!! %s socket: 0x%lx was closed\n", __FUNCTION__,(long)s);
  2281. return;
  2282. }
  2283. close_ioa_socket_after_processing_if_necessary(s);
  2284. }
  2285. }
  2286. static void eventcb_bev(struct bufferevent *bev, short events, void *arg)
  2287. {
  2288. UNUSED_ARG(bev);
  2289. if (events & BEV_EVENT_CONNECTED) {
  2290. // Connect okay
  2291. } else if (events & (BEV_EVENT_ERROR | BEV_EVENT_EOF)) {
  2292. if (arg) {
  2293. ioa_socket_handle s = (ioa_socket_handle) arg;
  2294. if(!is_stream_socket(s->st)) {
  2295. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "!!! %s: socket type is wrong on the socket: 0x%lx, st=%d, sat=%d\n",__FUNCTION__,(long)s,s->st,s->sat);
  2296. return;
  2297. }
  2298. if(s->magic != SOCKET_MAGIC) {
  2299. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "!!! %s: magic is wrong on the socket: 0x%lx, st=%d, sat=%d\n",__FUNCTION__,(long)s,s->st,s->sat);
  2300. return;
  2301. }
  2302. if (s->done) {
  2303. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "!!! %s: closed socket: 0x%lx (1): done=%d, fd=%d, br=%d, st=%d, sat=%d, tbc=%d\n", __FUNCTION__, (long) s, (int) s->done,
  2304. (int) s->fd, s->broken, s->st, s->sat, s->tobeclosed);
  2305. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "!!! %s socket: 0x%lx was closed\n", __FUNCTION__,(long)s);
  2306. return;
  2307. }
  2308. if (events & BEV_EVENT_ERROR)
  2309. s->broken = 1;
  2310. s->tobeclosed = 1;
  2311. if(s->special_session) {
  2312. turn_free(s->special_session,s->special_session_size);
  2313. s->special_session = NULL;
  2314. }
  2315. s->special_session_size = 0;
  2316. if(!(s->session) && !(s->sub_session)) {
  2317. char sraddr[129]="\0";
  2318. addr_to_string(&(s->remote_addr),(u08bits*)sraddr);
  2319. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s https server socket closed: 0x%lx, st=%d, sat=%d, remote addr=%s\n", __FUNCTION__,(long)s, get_ioa_socket_type(s), get_ioa_socket_app_type(s),sraddr);
  2320. IOA_CLOSE_SOCKET(s);
  2321. return;
  2322. }
  2323. switch (s->sat){
  2324. case TCP_CLIENT_DATA_SOCKET:
  2325. case TCP_RELAY_DATA_SOCKET:
  2326. {
  2327. tcp_connection *tc = s->sub_session;
  2328. if (tc) {
  2329. delete_tcp_connection(tc);
  2330. s->sub_session = NULL;
  2331. }
  2332. }
  2333. break;
  2334. default:
  2335. {
  2336. ts_ur_super_session *ss = s->session;
  2337. if (ss) {
  2338. turn_turnserver *server = (turn_turnserver *) ss->server;
  2339. if (server) {
  2340. {
  2341. char sraddr[129]="\0";
  2342. addr_to_string(&(s->remote_addr),(u08bits*)sraddr);
  2343. if (events & BEV_EVENT_EOF) {
  2344. if(server->verbose)
  2345. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,"session %018llu: %s socket closed remotely %s\n",
  2346. (unsigned long long)(ss->id),socket_type_name(s->st),sraddr);
  2347. if(s == ss->client_socket) {
  2348. char msg[256];
  2349. snprintf(msg,sizeof(msg)-1,"%s connection closed by client (callback)",socket_type_name(s->st));
  2350. shutdown_client_connection(server, ss, 0, msg);
  2351. } else if(s == ss->alloc.relay_sessions[ALLOC_IPV4_INDEX].s) {
  2352. char msg[256];
  2353. snprintf(msg,sizeof(msg)-1,"%s connection closed by peer (ipv4 callback)",socket_type_name(s->st));
  2354. shutdown_client_connection(server, ss, 0, msg);
  2355. } else if(s == ss->alloc.relay_sessions[ALLOC_IPV6_INDEX].s) {
  2356. char msg[256];
  2357. snprintf(msg,sizeof(msg)-1,"%s connection closed by peer (ipv6 callback)",socket_type_name(s->st));
  2358. shutdown_client_connection(server, ss, 0, msg);
  2359. } else {
  2360. char msg[256];
  2361. snprintf(msg,sizeof(msg)-1,"%s connection closed by remote party (callback)",socket_type_name(s->st));
  2362. shutdown_client_connection(server, ss, 0, msg);
  2363. }
  2364. } else if (events & BEV_EVENT_ERROR) {
  2365. if(EVUTIL_SOCKET_ERROR()) {
  2366. TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR,"session %018llu: %s socket error: %s %s\n",(unsigned long long)(ss->id),
  2367. socket_type_name(s->st),evutil_socket_error_to_string(EVUTIL_SOCKET_ERROR()), sraddr);
  2368. } else if(server->verbose) {
  2369. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,"session %018llu: %s socket disconnected: %s\n",
  2370. (unsigned long long)(ss->id),socket_type_name(s->st),sraddr);
  2371. }
  2372. char msg[256];
  2373. snprintf(msg,sizeof(msg)-1,"%s socket buffer operation error (callback)",socket_type_name(s->st));
  2374. shutdown_client_connection(server, ss, 0, msg);
  2375. }
  2376. }
  2377. }
  2378. }
  2379. }
  2380. };
  2381. }
  2382. }
  2383. }
  2384. static int ssl_send(ioa_socket_handle s, const s08bits* buffer, int len, int verbose)
  2385. {
  2386. if (!s || !(s->ssl) || !buffer || (s->fd<0))
  2387. return -1;
  2388. SSL *ssl = s->ssl;
  2389. if (eve(verbose)) {
  2390. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: before write: buffer=0x%lx, len=%d\n", __FUNCTION__,(long)buffer,len);
  2391. }
  2392. if(s->parent_s) {
  2393. /* Trick only for "children" sockets: */
  2394. BIO *wbio = SSL_get_wbio(ssl);
  2395. if(!wbio)
  2396. return -1;
  2397. int fd = BIO_get_fd(wbio,0);
  2398. int sfd = s->parent_s->fd;
  2399. if(sfd >= 0) {
  2400. if(fd != sfd) {
  2401. BIO_set_fd(wbio,sfd,BIO_NOCLOSE);
  2402. }
  2403. }
  2404. } else {
  2405. BIO *wbio = SSL_get_wbio(ssl);
  2406. if(!wbio)
  2407. return -1;
  2408. int fd = BIO_get_fd(wbio,0);
  2409. if(fd != s->fd) {
  2410. BIO_set_fd(wbio,s->fd,BIO_NOCLOSE);
  2411. }
  2412. }
  2413. int rc = 0;
  2414. int try_again = 1;
  2415. #if !defined(TURN_IP_RECVERR)
  2416. try_again = 0;
  2417. #endif
  2418. try_start:
  2419. do {
  2420. rc = SSL_write(ssl, buffer, len);
  2421. } while (rc < 0 && errno == EINTR);
  2422. if (eve(verbose)) {
  2423. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: after write: %d\n", __FUNCTION__,rc);
  2424. }
  2425. if (rc < 0 && ((errno == ENOBUFS) || (errno == EAGAIN))) {
  2426. if (eve(verbose)) {
  2427. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: ENOBUFS/EAGAIN\n", __FUNCTION__);
  2428. }
  2429. return 0;
  2430. }
  2431. if (rc >= 0) {
  2432. if (eve(verbose)) {
  2433. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: wrote %d bytes\n", __FUNCTION__, (int) rc);
  2434. }
  2435. return rc;
  2436. } else {
  2437. if (eve(verbose)) {
  2438. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s: failure: rc=%d, err=%d\n", __FUNCTION__, (int)rc,(int)SSL_get_error(ssl, rc));
  2439. }
  2440. switch (SSL_get_error(ssl, rc)){
  2441. case SSL_ERROR_NONE:
  2442. //???
  2443. if (eve(verbose)) {
  2444. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "wrote %d bytes\n", (int) rc);
  2445. }
  2446. return 0;
  2447. case SSL_ERROR_WANT_WRITE:
  2448. return 0;
  2449. case SSL_ERROR_WANT_READ:
  2450. return 0;
  2451. case SSL_ERROR_SYSCALL:
  2452. {
  2453. int err = errno;
  2454. if (!handle_socket_error()) {
  2455. if(s->st == DTLS_SOCKET) {
  2456. if(is_connreset()) {
  2457. if(try_again) {
  2458. BIO *wbio = SSL_get_wbio(ssl);
  2459. if(wbio) {
  2460. int fd = BIO_get_fd(wbio,0);
  2461. if(fd>=0) {
  2462. try_again = 0;
  2463. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "DTLS Socket, tring to recover write operation...\n");
  2464. socket_readerr(fd, &(s->local_addr));
  2465. goto try_start;
  2466. }
  2467. }
  2468. }
  2469. }
  2470. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "DTLS Socket lost packet... fine\n");
  2471. return 0;
  2472. }
  2473. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "DTLS Socket write error unrecoverable: %d; buffer=0x%lx, len=%d, ssl=0x%lx\n", err, (long)buffer, (int)len, (long)ssl);
  2474. return -1;
  2475. } else {
  2476. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "DTLS Socket write error recoverable: %d\n", err);
  2477. return 0;
  2478. }
  2479. }
  2480. case SSL_ERROR_SSL:
  2481. if (verbose) {
  2482. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "SSL write error: ");
  2483. s08bits buf[65536];
  2484. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "%s (%d)\n", ERR_error_string(ERR_get_error(), buf),
  2485. SSL_get_error(ssl, rc));
  2486. }
  2487. return -1;
  2488. default:
  2489. if (verbose) {
  2490. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "Unexpected error while writing!\n");
  2491. }
  2492. return -1;
  2493. }
  2494. }
  2495. }
  2496. static int send_ssl_backlog_buffers(ioa_socket_handle s)
  2497. {
  2498. int ret = 0;
  2499. if(s) {
  2500. stun_buffer_list_elem *buf_elem = s->bufs.head;
  2501. while(buf_elem) {
  2502. int rc = ssl_send(s, (s08bits*)buf_elem->buf.buf + buf_elem->buf.offset - buf_elem->buf.coffset, (size_t)buf_elem->buf.len, ((s->e) && s->e->verbose));
  2503. if(rc<1)
  2504. break;
  2505. ++ret;
  2506. pop_elem_from_buffer_list(&(s->bufs));
  2507. buf_elem = s->bufs.head;
  2508. }
  2509. }
  2510. return ret;
  2511. }
  2512. int is_connreset(void) {
  2513. switch (errno) {
  2514. case ECONNRESET:
  2515. case ECONNREFUSED:
  2516. return 1;
  2517. default:
  2518. ;
  2519. }
  2520. return 0;
  2521. }
  2522. int would_block(void) {
  2523. #if defined(EWOULDBLOCK)
  2524. if(errno == EWOULDBLOCK)
  2525. return 1;
  2526. #endif
  2527. return (errno == EAGAIN);
  2528. }
  2529. int udp_send(ioa_socket_handle s, const ioa_addr* dest_addr, const s08bits* buffer, int len)
  2530. {
  2531. int rc = 0;
  2532. evutil_socket_t fd = -1;
  2533. if(!s)
  2534. return -1;
  2535. if(s->parent_s)
  2536. fd = s->parent_s->fd;
  2537. else
  2538. fd = s->fd;
  2539. if(fd>=0) {
  2540. int try_again = 1;
  2541. int cycle;
  2542. #if !defined(TURN_IP_RECVERR)
  2543. try_again = 0;
  2544. #endif
  2545. try_start:
  2546. cycle = 0;
  2547. if (dest_addr) {
  2548. int slen = get_ioa_addr_len(dest_addr);
  2549. do {
  2550. rc = sendto(fd, buffer, len, 0, (const struct sockaddr*) dest_addr, (socklen_t) slen);
  2551. } while (
  2552. ((rc < 0) && (errno == EINTR)) ||
  2553. ((rc<0) && is_connreset() && (++cycle<TRIAL_EFFORTS_TO_SEND))
  2554. );
  2555. } else {
  2556. do {
  2557. rc = send(fd, buffer, len, 0);
  2558. } while (
  2559. ((rc < 0) && (errno == EINTR)) ||
  2560. ((rc<0) && is_connreset() && (++cycle<TRIAL_EFFORTS_TO_SEND))
  2561. );
  2562. }
  2563. if(rc<0) {
  2564. if((errno == ENOBUFS) || (errno == EAGAIN)) {
  2565. //Lost packet due to overload ... fine.
  2566. rc = len;
  2567. } else if(is_connreset()) {
  2568. if(try_again) {
  2569. try_again = 0;
  2570. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "UDP Socket, tring to recover write operation...\n");
  2571. socket_readerr(fd, &(s->local_addr));
  2572. goto try_start;
  2573. }
  2574. //Lost packet - sent to nowhere... fine.
  2575. rc = len;
  2576. }
  2577. }
  2578. }
  2579. return rc;
  2580. }
  2581. int send_data_from_ioa_socket_nbh(ioa_socket_handle s, ioa_addr* dest_addr,
  2582. ioa_network_buffer_handle nbh,
  2583. int ttl, int tos, int *skip)
  2584. {
  2585. int ret = -1;
  2586. if(!s) {
  2587. ioa_network_buffer_delete(NULL, nbh);
  2588. return -1;
  2589. }
  2590. if (s->done || (s->fd == -1)) {
  2591. TURN_LOG_FUNC(
  2592. TURN_LOG_LEVEL_INFO,
  2593. "!!! %s: (1) Trying to send data from closed socket: 0x%lx (1): done=%d, fd=%d, st=%d, sat=%d\n",
  2594. __FUNCTION__, (long) s, (int) s->done,
  2595. (int) s->fd, s->st, s->sat);
  2596. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "!!! %s socket: 0x%lx was closed\n", __FUNCTION__,(long)s);
  2597. } else if (nbh) {
  2598. if(!ioa_socket_check_bandwidth(s,nbh,0)) {
  2599. /* Bandwidth exhausted, we pretend everything is fine: */
  2600. ret = (int)(ioa_network_buffer_get_size(nbh));
  2601. if(skip) *skip = 1;
  2602. } else {
  2603. if (!ioa_socket_tobeclosed(s) && s->e) {
  2604. if (!(s->done || (s->fd == -1))) {
  2605. set_socket_ttl(s, ttl);
  2606. set_socket_tos(s, tos);
  2607. if (s->connected && s->bev) {
  2608. if ((s->st == TLS_SOCKET)||(s->st == TLS_SCTP_SOCKET)) {
  2609. #if TLS_SUPPORTED
  2610. SSL *ctx = bufferevent_openssl_get_ssl(s->bev);
  2611. if (!ctx || SSL_get_shutdown(ctx)) {
  2612. s->tobeclosed = 1;
  2613. ret = 0;
  2614. }
  2615. #endif
  2616. }
  2617. if (!(s->tobeclosed)) {
  2618. ret = (int) ioa_network_buffer_get_size(nbh);
  2619. if (!tcp_congestion_control || is_socket_writeable(
  2620. s, (size_t) ret, __FUNCTION__, 2)) {
  2621. s->in_write = 1;
  2622. if (bufferevent_write(s->bev,
  2623. ioa_network_buffer_data(nbh),
  2624. ioa_network_buffer_get_size(nbh)) < 0) {
  2625. ret = -1;
  2626. perror("bufev send");
  2627. log_socket_event(
  2628. s,
  2629. "socket write failed, to be closed",
  2630. 1);
  2631. s->tobeclosed = 1;
  2632. s->broken = 1;
  2633. }
  2634. /*
  2635. bufferevent_flush(s->bev,
  2636. EV_READ|EV_WRITE,
  2637. BEV_FLUSH);
  2638. */
  2639. s->in_write = 0;
  2640. } else {
  2641. //drop the packet
  2642. ;
  2643. }
  2644. }
  2645. } else if (s->ssl) {
  2646. send_ssl_backlog_buffers(s);
  2647. ret = ssl_send(
  2648. s,
  2649. (s08bits*) ioa_network_buffer_data(nbh),
  2650. ioa_network_buffer_get_size(nbh),
  2651. ((s->e) && s->e->verbose));
  2652. if (ret < 0)
  2653. s->tobeclosed = 1;
  2654. else if (ret == 0)
  2655. add_buffer_to_buffer_list(
  2656. &(s->bufs),
  2657. (s08bits*) ioa_network_buffer_data(nbh),
  2658. ioa_network_buffer_get_size(nbh));
  2659. } else if (s->fd >= 0) {
  2660. if (s->connected && !(s->parent_s)) {
  2661. dest_addr = NULL; /* ignore dest_addr */
  2662. } else if (!dest_addr) {
  2663. dest_addr = &(s->remote_addr);
  2664. }
  2665. ret = udp_send(s,
  2666. dest_addr,
  2667. (s08bits*) ioa_network_buffer_data(nbh),ioa_network_buffer_get_size(nbh));
  2668. if (ret < 0) {
  2669. s->tobeclosed = 1;
  2670. #if defined(EADDRNOTAVAIL)
  2671. int perr=errno;
  2672. #endif
  2673. perror("udp send");
  2674. #if defined(EADDRNOTAVAIL)
  2675. if(dest_addr && (perr==EADDRNOTAVAIL)) {
  2676. char sfrom[129];
  2677. addr_to_string(&(s->local_addr), (u08bits*)sfrom);
  2678. char sto[129];
  2679. addr_to_string(dest_addr, (u08bits*)sto);
  2680. TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR,
  2681. "%s: network error: address unreachable from %s to %s\n",
  2682. __FUNCTION__,sfrom,sto);
  2683. }
  2684. #endif
  2685. }
  2686. }
  2687. }
  2688. }
  2689. }
  2690. }
  2691. ioa_network_buffer_delete(s->e, nbh);
  2692. return ret;
  2693. }
  2694. int send_data_from_ioa_socket_tcp(ioa_socket_handle s, const void *data, size_t sz)
  2695. {
  2696. int ret = -1;
  2697. if(s && data) {
  2698. if (s->done || (s->fd == -1) || ioa_socket_tobeclosed(s) || !(s->e)) {
  2699. TURN_LOG_FUNC(
  2700. TURN_LOG_LEVEL_INFO,
  2701. "!!! %s: (1) Trying to send data from bad socket: 0x%lx (1): done=%d, fd=%d, st=%d, sat=%d\n",
  2702. __FUNCTION__, (long) s, (int) s->done,
  2703. (int) s->fd, s->st, s->sat);
  2704. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "!!! %s socket: 0x%lx was closed\n", __FUNCTION__,(long)s);
  2705. } else if (s->connected && s->bev) {
  2706. if ((s->st == TLS_SOCKET)||(s->st == TLS_SCTP_SOCKET)) {
  2707. #if TLS_SUPPORTED
  2708. SSL *ctx = bufferevent_openssl_get_ssl(s->bev);
  2709. if (!ctx || SSL_get_shutdown(ctx)) {
  2710. s->tobeclosed = 1;
  2711. ret = 0;
  2712. }
  2713. #endif
  2714. }
  2715. if (!(s->tobeclosed)) {
  2716. ret = (int)sz;
  2717. s->in_write = 1;
  2718. if (bufferevent_write(s->bev, data, sz) < 0) {
  2719. ret = -1;
  2720. perror("bufev send");
  2721. log_socket_event(s, "socket write failed, to be closed", 1);
  2722. s->tobeclosed = 1;
  2723. s->broken = 1;
  2724. }
  2725. s->in_write = 0;
  2726. }
  2727. }
  2728. }
  2729. return ret;
  2730. }
  2731. int send_str_from_ioa_socket_tcp(ioa_socket_handle s, const void *data)
  2732. {
  2733. if(data) {
  2734. return send_data_from_ioa_socket_tcp(s, data, strlen((const char*)data));
  2735. } else {
  2736. return 0;
  2737. }
  2738. }
  2739. int send_ulong_from_ioa_socket_tcp(ioa_socket_handle s, size_t data)
  2740. {
  2741. char str[129];
  2742. snprintf(str,sizeof(str)-1,"%lu",(unsigned long)data);
  2743. return send_str_from_ioa_socket_tcp(s,str);
  2744. }
  2745. int register_callback_on_ioa_socket(ioa_engine_handle e, ioa_socket_handle s, int event_type, ioa_net_event_handler cb, void* ctx, int clean_preexisting)
  2746. {
  2747. if(s) {
  2748. if (event_type & IOA_EV_READ) {
  2749. if(e)
  2750. s->e = e;
  2751. if(s->e && !(s->parent_s)) {
  2752. switch(s->st) {
  2753. case DTLS_SOCKET:
  2754. case UDP_SOCKET:
  2755. if(s->read_event) {
  2756. if(!clean_preexisting) {
  2757. TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR,
  2758. "%s: software error: buffer preset 1\n", __FUNCTION__);
  2759. return -1;
  2760. }
  2761. } else {
  2762. s->read_event = event_new(s->e->event_base,s->fd, EV_READ|EV_PERSIST, socket_input_handler, s);
  2763. event_add(s->read_event,NULL);
  2764. }
  2765. break;
  2766. case TENTATIVE_TCP_SOCKET:
  2767. case TENTATIVE_SCTP_SOCKET:
  2768. if(s->bev) {
  2769. if(!clean_preexisting) {
  2770. TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR,
  2771. "%s: software error: buffer preset 2\n", __FUNCTION__);
  2772. return -1;
  2773. }
  2774. } else if(s->read_event) {
  2775. if(!clean_preexisting) {
  2776. TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR,
  2777. "%s: software error: buffer preset 3\n", __FUNCTION__);
  2778. return -1;
  2779. }
  2780. } else {
  2781. s->read_event = event_new(s->e->event_base,s->fd, EV_READ|EV_PERSIST, socket_input_handler, s);
  2782. event_add(s->read_event,NULL);
  2783. }
  2784. break;
  2785. case SCTP_SOCKET:
  2786. case TCP_SOCKET:
  2787. if(s->bev) {
  2788. if(!clean_preexisting) {
  2789. TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR,
  2790. "%s: software error: buffer preset 4\n", __FUNCTION__);
  2791. return -1;
  2792. }
  2793. } else {
  2794. if(check_tentative_tls(s->fd)) {
  2795. s->tobeclosed = 1;
  2796. return -1;
  2797. } else {
  2798. s->bev = bufferevent_socket_new(s->e->event_base,
  2799. s->fd,
  2800. TURN_BUFFEREVENTS_OPTIONS);
  2801. debug_ptr_add(s->bev);
  2802. bufferevent_setcb(s->bev, socket_input_handler_bev, socket_output_handler_bev,
  2803. eventcb_bev, s);
  2804. bufferevent_setwatermark(s->bev, EV_READ|EV_WRITE, 0, BUFFEREVENT_HIGH_WATERMARK);
  2805. bufferevent_enable(s->bev, EV_READ|EV_WRITE); /* Start reading. */
  2806. }
  2807. }
  2808. break;
  2809. case TLS_SCTP_SOCKET:
  2810. case TLS_SOCKET:
  2811. if(s->bev) {
  2812. if(!clean_preexisting) {
  2813. TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR,
  2814. "%s: software error: buffer preset 5\n", __FUNCTION__);
  2815. return -1;
  2816. }
  2817. } else {
  2818. #if TLS_SUPPORTED
  2819. if(!(s->ssl)) {
  2820. //??? how we can get to this point ???
  2821. set_socket_ssl(s,SSL_NEW(e->tls_ctx_ssl23));
  2822. s->bev = bufferevent_openssl_socket_new(s->e->event_base,
  2823. s->fd,
  2824. s->ssl,
  2825. BUFFEREVENT_SSL_ACCEPTING,
  2826. TURN_BUFFEREVENTS_OPTIONS);
  2827. debug_ptr_add(s->bev);
  2828. } else {
  2829. s->bev = bufferevent_openssl_socket_new(s->e->event_base,
  2830. s->fd,
  2831. s->ssl,
  2832. BUFFEREVENT_SSL_OPEN,
  2833. TURN_BUFFEREVENTS_OPTIONS);
  2834. debug_ptr_add(s->bev);
  2835. }
  2836. bufferevent_setcb(s->bev, socket_input_handler_bev, socket_output_handler_bev,
  2837. eventcb_bev, s);
  2838. bufferevent_setwatermark(s->bev, EV_READ|EV_WRITE, 0, BUFFEREVENT_HIGH_WATERMARK);
  2839. bufferevent_enable(s->bev, EV_READ|EV_WRITE); /* Start reading. */
  2840. #endif
  2841. }
  2842. break;
  2843. default:
  2844. TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR,
  2845. "%s: software error: unknown socket type: %d\n", __FUNCTION__,(int)(s->st));
  2846. return -1;
  2847. }
  2848. }
  2849. s->read_cb = cb;
  2850. s->read_ctx = ctx;
  2851. return 0;
  2852. }
  2853. }
  2854. /* unsupported event or else */
  2855. return -1;
  2856. }
  2857. int ioa_socket_tobeclosed(ioa_socket_handle s)
  2858. {
  2859. if(s) {
  2860. if(s->magic != SOCKET_MAGIC) {
  2861. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "!!! %s: magic is wrong on the socket: 0x%lx, st=%d, sat=%d\n",__FUNCTION__,(long)s,s->st,s->sat);
  2862. return 1;
  2863. }
  2864. if(s->done) {
  2865. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "!!! %s: check on already closed socket: 0x%lx, st=%d, sat=%d\n",__FUNCTION__,(long)s,s->st,s->sat);
  2866. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO, "!!! %s socket: 0x%lx was closed\n", __FUNCTION__,(long)s);
  2867. return 1;
  2868. }
  2869. if(s->tobeclosed) {
  2870. return 1;
  2871. } else if(s->broken) {
  2872. s->tobeclosed = 1;
  2873. log_socket_event(s, "socket broken", 0);
  2874. return 1;
  2875. } else if(s->fd < 0) {
  2876. s->tobeclosed = 1;
  2877. log_socket_event(s, "socket fd<0", 0);
  2878. return 1;
  2879. } else if(s->ssl) {
  2880. if(SSL_get_shutdown(s->ssl)) {
  2881. s->tobeclosed = 1;
  2882. log_socket_event(s, "socket SSL shutdown", 0);
  2883. return 1;
  2884. }
  2885. }
  2886. }
  2887. return 0;
  2888. }
  2889. void set_ioa_socket_tobeclosed(ioa_socket_handle s)
  2890. {
  2891. if(s)
  2892. s->tobeclosed = 1;
  2893. }
  2894. static u32bits string_hash(const u08bits *str) {
  2895. u32bits hash = 0;
  2896. int c = 0;
  2897. while ((c = *str++))
  2898. hash = c + (hash << 6) + (hash << 16) - hash;
  2899. return hash;
  2900. }
  2901. int check_realm_hash(ioa_socket_handle s, u08bits *realm)
  2902. {
  2903. if(s) {
  2904. if(realm && realm[0]) {
  2905. if(s->realm_hash != string_hash(realm)) {
  2906. return 0;
  2907. }
  2908. }
  2909. }
  2910. return 1;
  2911. }
  2912. void set_realm_hash(ioa_socket_handle s, u08bits *realm)
  2913. {
  2914. if(s) {
  2915. if(realm && realm[0]) {
  2916. s->realm_hash = string_hash(realm);
  2917. }
  2918. }
  2919. }
  2920. /*
  2921. * Network buffer functions
  2922. */
  2923. ioa_network_buffer_handle ioa_network_buffer_allocate(ioa_engine_handle e)
  2924. {
  2925. stun_buffer_list_elem *buf_elem = new_blist_elem(e);
  2926. buf_elem->buf.len = 0;
  2927. buf_elem->buf.offset = 0;
  2928. buf_elem->buf.coffset = 0;
  2929. return buf_elem;
  2930. }
  2931. /* We do not use special header in this simple implementation */
  2932. void ioa_network_buffer_header_init(ioa_network_buffer_handle nbh)
  2933. {
  2934. UNUSED_ARG(nbh);
  2935. }
  2936. u08bits *ioa_network_buffer_data(ioa_network_buffer_handle nbh)
  2937. {
  2938. stun_buffer_list_elem *buf_elem = (stun_buffer_list_elem *)nbh;
  2939. return buf_elem->buf.buf + buf_elem->buf.offset - buf_elem->buf.coffset;
  2940. }
  2941. size_t ioa_network_buffer_get_size(ioa_network_buffer_handle nbh)
  2942. {
  2943. if(!nbh)
  2944. return 0;
  2945. else {
  2946. stun_buffer_list_elem *buf_elem = (stun_buffer_list_elem *)nbh;
  2947. return (size_t)(buf_elem->buf.len);
  2948. }
  2949. }
  2950. size_t ioa_network_buffer_get_capacity(ioa_network_buffer_handle nbh)
  2951. {
  2952. if(!nbh)
  2953. return 0;
  2954. else {
  2955. stun_buffer_list_elem *buf_elem = (stun_buffer_list_elem *)nbh;
  2956. if(buf_elem->buf.offset < STUN_BUFFER_SIZE) {
  2957. return (STUN_BUFFER_SIZE - buf_elem->buf.offset);
  2958. }
  2959. return 0;
  2960. }
  2961. }
  2962. size_t ioa_network_buffer_get_capacity_udp(void)
  2963. {
  2964. return UDP_STUN_BUFFER_SIZE;
  2965. }
  2966. void ioa_network_buffer_set_size(ioa_network_buffer_handle nbh, size_t len)
  2967. {
  2968. stun_buffer_list_elem *buf_elem = (stun_buffer_list_elem *)nbh;
  2969. buf_elem->buf.len=(size_t)len;
  2970. }
  2971. void ioa_network_buffer_add_offset_size(ioa_network_buffer_handle nbh, u16bits offset, u08bits coffset, size_t len)
  2972. {
  2973. stun_buffer_list_elem *buf_elem = (stun_buffer_list_elem *)nbh;
  2974. buf_elem->buf.len=(size_t)len;
  2975. buf_elem->buf.offset += offset;
  2976. buf_elem->buf.coffset += coffset;
  2977. if((buf_elem->buf.offset + buf_elem->buf.len - buf_elem->buf.coffset)>=sizeof(buf_elem->buf.buf) ||
  2978. (buf_elem->buf.offset + sizeof(buf_elem->buf.channel) < buf_elem->buf.coffset)
  2979. ) {
  2980. buf_elem->buf.coffset = 0;
  2981. buf_elem->buf.len = 0;
  2982. buf_elem->buf.offset = 0;
  2983. }
  2984. }
  2985. u16bits ioa_network_buffer_get_offset(ioa_network_buffer_handle nbh)
  2986. {
  2987. stun_buffer_list_elem *buf_elem = (stun_buffer_list_elem *)nbh;
  2988. return buf_elem->buf.offset;
  2989. }
  2990. u08bits ioa_network_buffer_get_coffset(ioa_network_buffer_handle nbh)
  2991. {
  2992. stun_buffer_list_elem *buf_elem = (stun_buffer_list_elem *)nbh;
  2993. return buf_elem->buf.coffset;
  2994. }
  2995. void ioa_network_buffer_delete(ioa_engine_handle e, ioa_network_buffer_handle nbh) {
  2996. stun_buffer_list_elem *buf_elem = (stun_buffer_list_elem *)nbh;
  2997. free_blist_elem(e,buf_elem);
  2998. }
  2999. /////////// REPORTING STATUS /////////////////////
  3000. const char* get_ioa_socket_cipher(ioa_socket_handle s)
  3001. {
  3002. if(s && s->ssl) {
  3003. return SSL_get_cipher(s->ssl);
  3004. }
  3005. return "no SSL";
  3006. }
  3007. const char* get_ioa_socket_ssl_method(ioa_socket_handle s)
  3008. {
  3009. if(s && s->ssl) {
  3010. return turn_get_ssl_method(s->ssl, "UNKNOWN");
  3011. }
  3012. return "no SSL";
  3013. }
  3014. void turn_report_allocation_set(void *a, turn_time_t lifetime, int refresh)
  3015. {
  3016. if(a) {
  3017. ts_ur_super_session *ss = (ts_ur_super_session*)(((allocation*)a)->owner);
  3018. if(ss) {
  3019. const char* status="new";
  3020. if(refresh)
  3021. status="refreshed";
  3022. turn_turnserver *server = (turn_turnserver*)ss->server;
  3023. if(server) {
  3024. ioa_engine_handle e = turn_server_get_engine(server);
  3025. if(e && e->verbose && ss->client_socket) {
  3026. if(ss->client_socket->ssl) {
  3027. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,"session %018llu: %s, realm=<%s>, username=<%s>, lifetime=%lu, cipher=%s, method=%s\n", (unsigned long long)ss->id, status, (char*)ss->realm_options.name, (char*)ss->username, (unsigned long)lifetime, SSL_get_cipher(ss->client_socket->ssl),
  3028. turn_get_ssl_method(ss->client_socket->ssl, "UNKNOWN"));
  3029. } else {
  3030. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,"session %018llu: %s, realm=<%s>, username=<%s>, lifetime=%lu\n", (unsigned long long)ss->id, status, (char*)ss->realm_options.name, (char*)ss->username, (unsigned long)lifetime);
  3031. }
  3032. }
  3033. #if !defined(TURN_NO_HIREDIS)
  3034. {
  3035. char key[1024];
  3036. if(ss->realm_options.name[0]) {
  3037. snprintf(key,sizeof(key),"turn/realm/%s/user/%s/allocation/%018llu/status",ss->realm_options.name,(char*)ss->username, (unsigned long long)ss->id);
  3038. } else {
  3039. snprintf(key,sizeof(key),"turn/user/%s/allocation/%018llu/status",(char*)ss->username, (unsigned long long)ss->id);
  3040. }
  3041. send_message_to_redis(e->rch, "set", key, "%s lifetime=%lu", status, (unsigned long)lifetime);
  3042. send_message_to_redis(e->rch, "publish", key, "%s lifetime=%lu", status, (unsigned long)lifetime);
  3043. }
  3044. #endif
  3045. }
  3046. }
  3047. }
  3048. }
  3049. void turn_report_allocation_delete(void *a)
  3050. {
  3051. if(a) {
  3052. ts_ur_super_session *ss = (ts_ur_super_session*)(((allocation*)a)->owner);
  3053. if(ss) {
  3054. turn_turnserver *server = (turn_turnserver*)ss->server;
  3055. if(server) {
  3056. ioa_engine_handle e = turn_server_get_engine(server);
  3057. if(e && e->verbose) {
  3058. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,"session %018llu: delete: realm=<%s>, username=<%s>\n", (unsigned long long)ss->id, (char*)ss->realm_options.name, (char*)ss->username);
  3059. }
  3060. #if !defined(TURN_NO_HIREDIS)
  3061. {
  3062. char key[1024];
  3063. if(ss->realm_options.name[0]) {
  3064. snprintf(key,sizeof(key),"turn/realm/%s/user/%s/allocation/%018llu/status",ss->realm_options.name,(char*)ss->username, (unsigned long long)ss->id);
  3065. } else {
  3066. snprintf(key,sizeof(key),"turn/user/%s/allocation/%018llu/status",(char*)ss->username, (unsigned long long)ss->id);
  3067. }
  3068. send_message_to_redis(e->rch, "del", key, "");
  3069. send_message_to_redis(e->rch, "publish", key, "deleted");
  3070. }
  3071. #endif
  3072. }
  3073. }
  3074. }
  3075. }
  3076. void turn_report_session_usage(void *session)
  3077. {
  3078. if(session) {
  3079. ts_ur_super_session *ss = (ts_ur_super_session *)session;
  3080. turn_turnserver *server = (turn_turnserver*)ss->server;
  3081. if(server && (ss->received_packets || ss->sent_packets)) {
  3082. ioa_engine_handle e = turn_server_get_engine(server);
  3083. if(((ss->received_packets+ss->sent_packets)&2047)==0) {
  3084. if(e && e->verbose) {
  3085. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,"session %018llu: usage: realm=<%s>, username=<%s>, rp=%lu, rb=%lu, sp=%lu, sb=%lu\n", (unsigned long long)(ss->id), (char*)ss->realm_options.name, (char*)ss->username, (unsigned long)(ss->received_packets), (unsigned long)(ss->received_bytes),(unsigned long)(ss->sent_packets),(unsigned long)(ss->sent_bytes));
  3086. }
  3087. #if !defined(TURN_NO_HIREDIS)
  3088. {
  3089. char key[1024];
  3090. if(ss->realm_options.name[0]) {
  3091. snprintf(key,sizeof(key),"turn/realm/%s/user/%s/allocation/%018llu/traffic",ss->realm_options.name,(char*)ss->username, (unsigned long long)(ss->id));
  3092. } else {
  3093. snprintf(key,sizeof(key),"turn/user/%s/allocation/%018llu/traffic",(char*)ss->username, (unsigned long long)(ss->id));
  3094. }
  3095. send_message_to_redis(e->rch, "publish", key, "rcvp=%lu, rcvb=%lu, sentp=%lu, sentb=%lu",(unsigned long)(ss->received_packets), (unsigned long)(ss->received_bytes),(unsigned long)(ss->sent_packets),(unsigned long)(ss->sent_bytes));
  3096. }
  3097. #endif
  3098. ss->t_received_packets += ss->received_packets;
  3099. ss->t_received_bytes += ss->received_bytes;
  3100. ss->t_sent_packets += ss->sent_packets;
  3101. ss->t_sent_bytes += ss->sent_bytes;
  3102. {
  3103. turn_time_t ct = get_turn_server_time(server);
  3104. if(ct != ss->start_time) {
  3105. ct = ct - ss->start_time;
  3106. ss->received_rate = (u32bits)(ss->t_received_bytes / ct);
  3107. ss->sent_rate = (u32bits)(ss->t_sent_bytes / ct);
  3108. ss->total_rate = ss->received_rate + ss->sent_rate;
  3109. }
  3110. }
  3111. report_turn_session_info(server,ss,0);
  3112. ss->received_packets=0;
  3113. ss->received_bytes=0;
  3114. ss->sent_packets=0;
  3115. ss->sent_bytes=0;
  3116. }
  3117. }
  3118. }
  3119. }
  3120. /////////////// SSL ///////////////////
  3121. const char* get_ioa_socket_tls_cipher(ioa_socket_handle s)
  3122. {
  3123. if(s && (s->ssl))
  3124. return SSL_get_cipher(s->ssl);
  3125. return "";
  3126. }
  3127. const char* get_ioa_socket_tls_method(ioa_socket_handle s)
  3128. {
  3129. if(s && (s->ssl))
  3130. return turn_get_ssl_method(s->ssl,"UNKNOWN");
  3131. return "";
  3132. }
  3133. ///////////// Super Memory Region //////////////
  3134. #define TURN_SM_SIZE (1024<<11)
  3135. struct _super_memory {
  3136. pthread_mutex_t mutex_sm;
  3137. char **super_memory;
  3138. size_t *sm_allocated;
  3139. size_t sm_total_sz;
  3140. size_t sm_chunk;
  3141. u32bits id;
  3142. };
  3143. static void init_super_memory_region(super_memory_t *r)
  3144. {
  3145. if(r) {
  3146. ns_bzero(r,sizeof(super_memory_t));
  3147. r->super_memory = (char**)turn_malloc(sizeof(char*));
  3148. r->super_memory[0] = (char*)turn_malloc(TURN_SM_SIZE);
  3149. ns_bzero(r->super_memory[0],TURN_SM_SIZE);
  3150. r->sm_allocated = (size_t*)turn_malloc(sizeof(size_t*));
  3151. r->sm_allocated[0] = 0;
  3152. r->sm_total_sz = TURN_SM_SIZE;
  3153. r->sm_chunk = 0;
  3154. while(r->id == 0)
  3155. r->id = (u32bits)random();
  3156. pthread_mutex_init(&r->mutex_sm, NULL);
  3157. }
  3158. }
  3159. void init_super_memory(void)
  3160. {
  3161. ;
  3162. }
  3163. super_memory_t* new_super_memory_region(void)
  3164. {
  3165. super_memory_t* r = (super_memory_t*)turn_malloc(sizeof(super_memory_t));
  3166. init_super_memory_region(r);
  3167. return r;
  3168. }
  3169. void* allocate_super_memory_region_func(super_memory_t *r, size_t size, const char* file, const char* func, int line)
  3170. {
  3171. UNUSED_ARG(file);
  3172. UNUSED_ARG(func);
  3173. UNUSED_ARG(line);
  3174. void *ret = NULL;
  3175. if(!r) {
  3176. ret = turn_malloc(size);
  3177. ns_bzero(ret, size);
  3178. return ret;
  3179. }
  3180. pthread_mutex_lock(&r->mutex_sm);
  3181. size = ((size_t)((size+sizeof(void*))/(sizeof(void*)))) * sizeof(void*);
  3182. if(size>=TURN_SM_SIZE) {
  3183. TURN_LOG_FUNC(TURN_LOG_LEVEL_INFO,"(%s:%s:%d): Size too large for super memory: region id = %u, chunk=%lu, total=%lu, allocated=%lu, want=%lu\n",file,func,line,(unsigned int)r->id, (unsigned long)r->sm_chunk, (unsigned long)r->sm_total_sz, (unsigned long)r->sm_allocated[r->sm_chunk],(unsigned long)size);
  3184. } else {
  3185. size_t i = 0;
  3186. char *region = NULL;
  3187. size_t *rsz = NULL;
  3188. for(i=0;i<=r->sm_chunk;++i) {
  3189. size_t left = (size_t)r->sm_total_sz - r->sm_allocated[i];
  3190. if(left<size+sizeof(void*)) {
  3191. continue;
  3192. } else {
  3193. region = r->super_memory[i];
  3194. rsz = r->sm_allocated + i;
  3195. break;
  3196. }
  3197. }
  3198. if(!region) {
  3199. r->sm_chunk += 1;
  3200. r->super_memory = (char**)turn_realloc(r->super_memory,0, (r->sm_chunk+1) * sizeof(char*));
  3201. r->super_memory[r->sm_chunk] = (char*)turn_malloc(TURN_SM_SIZE);
  3202. ns_bzero(r->super_memory[r->sm_chunk],TURN_SM_SIZE);
  3203. r->sm_allocated = (size_t*)turn_realloc(r->sm_allocated,0,(r->sm_chunk+1) * sizeof(size_t*));
  3204. r->sm_allocated[r->sm_chunk] = 0;
  3205. region = r->super_memory[r->sm_chunk];
  3206. rsz = r->sm_allocated + r->sm_chunk;
  3207. }
  3208. {
  3209. char* ptr = region + *rsz;
  3210. ns_bzero(ptr, size);
  3211. *rsz += size;
  3212. ret = ptr;
  3213. }
  3214. }
  3215. pthread_mutex_unlock(&r->mutex_sm);
  3216. if(!ret) {
  3217. ret = turn_malloc(size);
  3218. ns_bzero(ret, size);
  3219. }
  3220. return ret;
  3221. }
  3222. void* allocate_super_memory_engine_func(ioa_engine_handle e, size_t size, const char* file, const char* func, int line)
  3223. {
  3224. if(e)
  3225. return allocate_super_memory_region_func(e->sm,size,file,func,line);
  3226. return allocate_super_memory_region_func(NULL,size,file,func,line);
  3227. }
  3228. //////////////////////////////////////////////////