tcp_main.c 112 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869
  1. /*
  2. * $Id$
  3. *
  4. * Copyright (C) 2001-2003 FhG Fokus
  5. *
  6. * This file is part of ser, a free SIP server.
  7. *
  8. * ser is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 2 of the License, or
  11. * (at your option) any later version
  12. *
  13. * For a license to use the ser software under conditions
  14. * other than those described here, or to purchase support for this
  15. * software, please contact iptel.org by e-mail at the following addresses:
  16. * [email protected]
  17. *
  18. * ser is distributed in the hope that it will be useful,
  19. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. * GNU General Public License for more details.
  22. *
  23. * You should have received a copy of the GNU General Public License
  24. * along with this program; if not, write to the Free Software
  25. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  26. */
  27. /*
  28. * History:
  29. * --------
  30. * 2002-11-29 created by andrei
  31. * 2002-12-11 added tcp_send (andrei)
  32. * 2003-01-20 locking fixes, hashtables (andrei)
  33. * 2003-02-20 s/lock_t/gen_lock_t/ to avoid a conflict on solaris (andrei)
  34. * 2003-02-25 Nagle is disabled if -DDISABLE_NAGLE (andrei)
  35. * 2003-03-29 SO_REUSEADDR before calling bind to allow
  36. * server restart, Nagle set on the (hopefuly)
  37. * correct socket (jiri)
  38. * 2003-03-31 always try to find the corresponding tcp listen socket for
  39. * a temp. socket and store in in *->bind_address: added
  40. * find_tcp_si, modified tcpconn_connect (andrei)
  41. * 2003-04-14 set sockopts to TOS low delay (andrei)
  42. * 2003-06-30 moved tcp new connect checking & handling to
  43. * handle_new_connect (andrei)
  44. * 2003-07-09 tls_close called before closing the tcp connection (andrei)
  45. * 2003-10-24 converted to the new socket_info lists (andrei)
  46. * 2003-10-27 tcp port aliases support added (andrei)
  47. * 2003-11-04 always lock before manipulating refcnt; sendchild
  48. * does not inc refcnt by itself anymore (andrei)
  49. * 2003-11-07 different unix sockets are used for fd passing
  50. * to/from readers/writers (andrei)
  51. * 2003-11-17 handle_new_connect & tcp_connect will close the
  52. * new socket if tcpconn_new return 0 (e.g. out of mem) (andrei)
  53. * 2003-11-28 tcp_blocking_write & tcp_blocking_connect added (andrei)
  54. * 2004-11-08 dropped find_tcp_si and replaced with find_si (andrei)
  55. * 2005-06-07 new tcp optimized code, supports epoll (LT), sigio + real time
  56. * signals, poll & select (andrei)
  57. * 2005-06-26 *bsd kqueue support (andrei)
  58. * 2005-07-04 solaris /dev/poll support (andrei)
  59. * 2005-07-08 tcp_max_connections, tcp_connection_lifetime, don't accept
  60. * more connections if tcp_max_connections is exceeded (andrei)
  61. * 2005-10-21 cleanup all the open connections on exit
  62. * decrement the no. of open connections on timeout too (andrei) * 2006-01-30 queue send_fd request and execute them at the end of the
  63. * poll loop (#ifdef) (andrei)
  64. * process all children requests, before attempting to send
  65. * them new stuff (fixes some deadlocks) (andrei)
  66. * 2006-02-03 timers are run only once per s (andrei)
  67. * tcp children fds can be non-blocking; send fds are queued on
  68. * EAGAIN; lots of bug fixes (andrei)
  69. * 2006-02-06 better tcp_max_connections checks, tcp_connections_no moved to
  70. * shm (andrei)
  71. * 2006-04-12 tcp_send() changed to use struct dest_info (andrei)
  72. * 2006-11-02 switched to atomic ops for refcnt, locking improvements
  73. * (andrei)
  74. * 2006-11-04 switched to raw ticks (to fix conversion errors which could
  75. * result in inf. lifetime) (andrei)
  76. * 2007-07-25 tcpconn_connect can now bind the socket on a specified
  77. * source addr/port (andrei)
  78. * 2007-07-26 tcp_send() and tcpconn_get() can now use a specified source
  79. * addr./port (andrei)
  80. * 2007-08-23 getsockname() for INADDR_ANY(SI_IS_ANY) sockets (andrei)
  81. * 2007-08-27 split init_sock_opt into a lightweight init_sock_opt_accept()
  82. * used when accepting connections and init_sock_opt used for
  83. * connect/ new sockets (andrei)
  84. * 2007-11-22 always add the connection & clear the coresponding flags before
  85. * io_watch_add-ing its fd - it's safer this way (andrei)
  86. * 2007-11-26 improved tcp timers: switched to local_timer (andrei)
  87. * 2007-11-27 added send fd cache and reader fd reuse (andrei)
  88. * 2007-11-28 added support for TCP_DEFER_ACCEPT, KEEPALIVE, KEEPINTVL,
  89. * KEEPCNT, QUICKACK, SYNCNT, LINGER2 (andrei)
  90. * 2007-12-04 support for queueing write requests (andrei)
  91. * 2007-12-12 destroy connection asap on wbuf. timeout (andrei)
  92. * 2007-12-13 changed the refcnt and destroy scheme, now refcnt is 1 if
  93. * linked into the hash tables (was 0) (andrei)
  94. * 2007-12-21 support for pending connects (connections are added to the
  95. * hash immediately and writes on them are buffered) (andrei)
  96. * 2008-02-05 handle POLLRDHUP (if supported), POLLERR and
  97. * POLLHUP (andrei)
  98. * on write error check if there's still data in the socket
  99. * read buffer and process it first (andrei)
  100. */
  101. #ifdef USE_TCP
  102. #ifndef SHM_MEM
  103. #error "shared memory support needed (add -DSHM_MEM to Makefile.defs)"
  104. #endif
  105. #define HANDLE_IO_INLINE
  106. #include "io_wait.h" /* include first to make sure the needed features are
  107. turned on (e.g. _GNU_SOURCE for POLLRDHUP) */
  108. #include <sys/time.h>
  109. #include <sys/types.h>
  110. #include <sys/select.h>
  111. #include <sys/socket.h>
  112. #include <sys/ioctl.h> /* ioctl() used on write error */
  113. #include <netinet/in.h>
  114. #include <netinet/in_systm.h>
  115. #include <netinet/ip.h>
  116. #include <netinet/tcp.h>
  117. #include <sys/uio.h> /* writev*/
  118. #include <netdb.h>
  119. #include <stdlib.h> /*exit() */
  120. #include <unistd.h>
  121. #include <errno.h>
  122. #include <string.h>
  123. #ifdef HAVE_SELECT
  124. #include <sys/select.h>
  125. #endif
  126. #include <sys/poll.h>
  127. #include "ip_addr.h"
  128. #include "pass_fd.h"
  129. #include "tcp_conn.h"
  130. #include "globals.h"
  131. #include "pt.h"
  132. #include "locking.h"
  133. #include "mem/mem.h"
  134. #include "mem/shm_mem.h"
  135. #include "timer.h"
  136. #include "sr_module.h"
  137. #include "tcp_server.h"
  138. #include "tcp_init.h"
  139. #include "tsend.h"
  140. #include "timer_ticks.h"
  141. #include "local_timer.h"
  142. #ifdef CORE_TLS
  143. #include "tls/tls_server.h"
  144. #define tls_loaded() 1
  145. #else
  146. #include "tls_hooks_init.h"
  147. #include "tls_hooks.h"
  148. #endif
  149. #include "tcp_info.h"
  150. #include "tcp_options.h"
  151. #include "ut.h"
  152. #include "cfg/cfg_struct.h"
  153. #define local_malloc pkg_malloc
  154. #define local_free pkg_free
  155. #include <fcntl.h> /* must be included after io_wait.h if SIGIO_RT is used */
  156. #ifdef NO_MSG_DONTWAIT
  157. #ifndef MSG_DONTWAIT
  158. /* should work inside tcp_main */
  159. #define MSG_DONTWAIT 0
  160. #endif
  161. #endif /*NO_MSG_DONTWAIT */
  162. #define TCP_PASS_NEW_CONNECTION_ON_DATA /* don't pass a new connection
  163. immediately to a child, wait for
  164. some data on it first */
  165. #define TCP_LISTEN_BACKLOG 1024
  166. #define SEND_FD_QUEUE /* queue send fd requests on EAGAIN, instead of sending
  167. them immediately */
  168. #define TCP_CHILD_NON_BLOCKING
  169. #ifdef SEND_FD_QUEUE
  170. #ifndef TCP_CHILD_NON_BLOCKING
  171. #define TCP_CHILD_NON_BLOCKING
  172. #endif
  173. #define MAX_SEND_FD_QUEUE_SIZE tcp_main_max_fd_no
  174. #define SEND_FD_QUEUE_SIZE 128 /* initial size */
  175. #define MAX_SEND_FD_RETRIES 96 /* FIXME: not used for now */
  176. #define SEND_FD_QUEUE_TIMEOUT MS_TO_TICKS(2000) /* 2 s */
  177. #endif
  178. /* maximum accepted lifetime (maximum possible is ~ MAXINT/2) */
  179. #define MAX_TCP_CON_LIFETIME ((1U<<(sizeof(ticks_t)*8-1))-1)
  180. /* minimum interval local_timer_run() is allowed to run, in ticks */
  181. #define TCPCONN_TIMEOUT_MIN_RUN 1 /* once per tick */
  182. #define TCPCONN_WAIT_TIMEOUT 1 /* 1 tick */
  183. #ifdef TCP_BUF_WRITE
  184. #define TCP_WBUF_SIZE 1024 /* FIXME: after debugging switch to 16-32k */
  185. static unsigned int* tcp_total_wq=0;
  186. #endif
  187. enum fd_types { F_NONE, F_SOCKINFO /* a tcp_listen fd */,
  188. F_TCPCONN, F_TCPCHILD, F_PROC };
  189. #ifdef TCP_FD_CACHE
  190. #define TCP_FD_CACHE_SIZE 8
  191. struct fd_cache_entry{
  192. struct tcp_connection* con;
  193. int id;
  194. int fd;
  195. };
  196. static struct fd_cache_entry fd_cache[TCP_FD_CACHE_SIZE];
  197. #endif /* TCP_FD_CACHE */
  198. static int is_tcp_main=0;
  199. int tcp_accept_aliases=0; /* by default don't accept aliases */
  200. /* flags used for adding new aliases */
  201. int tcp_alias_flags=TCP_ALIAS_FORCE_ADD;
  202. /* flags used for adding the default aliases of a new tcp connection */
  203. int tcp_new_conn_alias_flags=TCP_ALIAS_REPLACE;
  204. int tcp_connect_timeout=DEFAULT_TCP_CONNECT_TIMEOUT;
  205. int tcp_send_timeout=DEFAULT_TCP_SEND_TIMEOUT;
  206. int tcp_con_lifetime=DEFAULT_TCP_CONNECTION_LIFETIME;
  207. enum poll_types tcp_poll_method=0; /* by default choose the best method */
  208. int tcp_max_connections=DEFAULT_TCP_MAX_CONNECTIONS;
  209. int tcp_main_max_fd_no=0;
  210. static union sockaddr_union tcp_source_ipv4_addr; /* saved bind/srv v4 addr. */
  211. static union sockaddr_union* tcp_source_ipv4=0;
  212. #ifdef USE_IPV6
  213. static union sockaddr_union tcp_source_ipv6_addr; /* saved bind/src v6 addr. */
  214. static union sockaddr_union* tcp_source_ipv6=0;
  215. #endif
  216. static int* tcp_connections_no=0; /* current open connections */
  217. /* connection hash table (after ip&port) , includes also aliases */
  218. struct tcp_conn_alias** tcpconn_aliases_hash=0;
  219. /* connection hash table (after connection id) */
  220. struct tcp_connection** tcpconn_id_hash=0;
  221. gen_lock_t* tcpconn_lock=0;
  222. struct tcp_child* tcp_children;
  223. static int* connection_id=0; /* unique for each connection, used for
  224. quickly finding the corresponding connection
  225. for a reply */
  226. int unix_tcp_sock;
  227. static int tcp_proto_no=-1; /* tcp protocol number as returned by
  228. getprotobyname */
  229. static io_wait_h io_h;
  230. static struct local_timer tcp_main_ltimer;
  231. static ticks_t tcp_main_prev_ticks;
  232. static ticks_t tcpconn_main_timeout(ticks_t , struct timer_ln* , void* );
  233. inline static int _tcpconn_add_alias_unsafe(struct tcp_connection* c, int port,
  234. struct ip_addr* l_ip, int l_port,
  235. int flags);
  236. /* sets source address used when opening new sockets and no source is specified
  237. * (by default the address is choosen by the kernel)
  238. * Should be used only on init.
  239. * returns -1 on error */
  240. int tcp_set_src_addr(struct ip_addr* ip)
  241. {
  242. switch (ip->af){
  243. case AF_INET:
  244. ip_addr2su(&tcp_source_ipv4_addr, ip, 0);
  245. tcp_source_ipv4=&tcp_source_ipv4_addr;
  246. break;
  247. #ifdef USE_IPV6
  248. case AF_INET6:
  249. ip_addr2su(&tcp_source_ipv6_addr, ip, 0);
  250. tcp_source_ipv6=&tcp_source_ipv6_addr;
  251. break;
  252. #endif
  253. default:
  254. return -1;
  255. }
  256. return 0;
  257. }
  258. static inline int init_sock_keepalive(int s)
  259. {
  260. int optval;
  261. #ifdef HAVE_SO_KEEPALIVE
  262. if (tcp_options.keepalive){
  263. optval=1;
  264. if (setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, &optval,
  265. sizeof(optval))<0){
  266. LOG(L_WARN, "WARNING: init_sock_keepalive: failed to enable"
  267. " SO_KEEPALIVE: %s\n", strerror(errno));
  268. return -1;
  269. }
  270. }
  271. #endif
  272. #ifdef HAVE_TCP_KEEPINTVL
  273. if (tcp_options.keepintvl){
  274. optval=tcp_options.keepintvl;
  275. if (setsockopt(s, IPPROTO_TCP, TCP_KEEPINTVL, &optval,
  276. sizeof(optval))<0){
  277. LOG(L_WARN, "WARNING: init_sock_keepalive: failed to set"
  278. " keepalive probes interval: %s\n", strerror(errno));
  279. }
  280. }
  281. #endif
  282. #ifdef HAVE_TCP_KEEPIDLE
  283. if (tcp_options.keepidle){
  284. optval=tcp_options.keepidle;
  285. if (setsockopt(s, IPPROTO_TCP, TCP_KEEPIDLE, &optval,
  286. sizeof(optval))<0){
  287. LOG(L_WARN, "WARNING: init_sock_keepalive: failed to set"
  288. " keepalive idle interval: %s\n", strerror(errno));
  289. }
  290. }
  291. #endif
  292. #ifdef HAVE_TCP_KEEPCNT
  293. if (tcp_options.keepcnt){
  294. optval=tcp_options.keepcnt;
  295. if (setsockopt(s, IPPROTO_TCP, TCP_KEEPCNT, &optval,
  296. sizeof(optval))<0){
  297. LOG(L_WARN, "WARNING: init_sock_keepalive: failed to set"
  298. " maximum keepalive count: %s\n", strerror(errno));
  299. }
  300. }
  301. #endif
  302. return 0;
  303. }
  304. /* set all socket/fd options for new sockets (e.g. before connect):
  305. * disable nagle, tos lowdelay, reuseaddr, non-blocking
  306. *
  307. * return -1 on error */
  308. static int init_sock_opt(int s)
  309. {
  310. int flags;
  311. int optval;
  312. #ifdef DISABLE_NAGLE
  313. flags=1;
  314. if ( (tcp_proto_no!=-1) && (setsockopt(s, tcp_proto_no , TCP_NODELAY,
  315. &flags, sizeof(flags))<0) ){
  316. LOG(L_WARN, "WARNING: init_sock_opt: could not disable Nagle: %s\n",
  317. strerror(errno));
  318. }
  319. #endif
  320. /* tos*/
  321. optval = tos;
  322. if (setsockopt(s, IPPROTO_IP, IP_TOS, (void*)&optval,sizeof(optval)) ==-1){
  323. LOG(L_WARN, "WARNING: init_sock_opt: setsockopt tos: %s\n",
  324. strerror(errno));
  325. /* continue since this is not critical */
  326. }
  327. #if !defined(TCP_DONT_REUSEADDR)
  328. optval=1;
  329. if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
  330. (void*)&optval, sizeof(optval))==-1){
  331. LOG(L_ERR, "ERROR: setsockopt SO_REUSEADDR %s\n",
  332. strerror(errno));
  333. /* continue, not critical */
  334. }
  335. #endif /* !TCP_DONT_REUSEADDR */
  336. #ifdef HAVE_TCP_SYNCNT
  337. if (tcp_options.syncnt){
  338. optval=tcp_options.syncnt;
  339. if (setsockopt(s, IPPROTO_TCP, TCP_SYNCNT, &optval,
  340. sizeof(optval))<0){
  341. LOG(L_WARN, "WARNING: init_sock_opt: failed to set"
  342. " maximum SYN retr. count: %s\n", strerror(errno));
  343. }
  344. }
  345. #endif
  346. #ifdef HAVE_TCP_LINGER2
  347. if (tcp_options.linger2){
  348. optval=tcp_options.linger2;
  349. if (setsockopt(s, IPPROTO_TCP, TCP_LINGER2, &optval,
  350. sizeof(optval))<0){
  351. LOG(L_WARN, "WARNING: init_sock_opt: failed to set"
  352. " maximum LINGER2 timeout: %s\n", strerror(errno));
  353. }
  354. }
  355. #endif
  356. #ifdef HAVE_TCP_QUICKACK
  357. if (tcp_options.delayed_ack){
  358. optval=0; /* reset quick ack => delayed ack */
  359. if (setsockopt(s, IPPROTO_TCP, TCP_QUICKACK, &optval,
  360. sizeof(optval))<0){
  361. LOG(L_WARN, "WARNING: init_sock_opt: failed to reset"
  362. " TCP_QUICKACK: %s\n", strerror(errno));
  363. }
  364. }
  365. #endif /* HAVE_TCP_QUICKACK */
  366. init_sock_keepalive(s);
  367. /* non-blocking */
  368. flags=fcntl(s, F_GETFL);
  369. if (flags==-1){
  370. LOG(L_ERR, "ERROR: init_sock_opt: fnctl failed: (%d) %s\n",
  371. errno, strerror(errno));
  372. goto error;
  373. }
  374. if (fcntl(s, F_SETFL, flags|O_NONBLOCK)==-1){
  375. LOG(L_ERR, "ERROR: init_sock_opt: fcntl: set non-blocking failed:"
  376. " (%d) %s\n", errno, strerror(errno));
  377. goto error;
  378. }
  379. return 0;
  380. error:
  381. return -1;
  382. }
  383. /* set all socket/fd options for "accepted" sockets
  384. * only nonblocking is set since the rest is inherited from the
  385. * "parent" (listening) socket
  386. * Note: setting O_NONBLOCK is required on linux but it's not needed on
  387. * BSD and possibly solaris (where the flag is inherited from the
  388. * parent socket). However since there is no standard document
  389. * requiring a specific behaviour in this case it's safer to always set
  390. * it (at least for now) --andrei
  391. * TODO: check on which OSes O_NONBLOCK is inherited and make this
  392. * function a nop.
  393. *
  394. * return -1 on error */
  395. static int init_sock_opt_accept(int s)
  396. {
  397. int flags;
  398. /* non-blocking */
  399. flags=fcntl(s, F_GETFL);
  400. if (flags==-1){
  401. LOG(L_ERR, "ERROR: init_sock_opt_accept: fnctl failed: (%d) %s\n",
  402. errno, strerror(errno));
  403. goto error;
  404. }
  405. if (fcntl(s, F_SETFL, flags|O_NONBLOCK)==-1){
  406. LOG(L_ERR, "ERROR: init_sock_opt_accept: "
  407. "fcntl: set non-blocking failed: (%d) %s\n",
  408. errno, strerror(errno));
  409. goto error;
  410. }
  411. return 0;
  412. error:
  413. return -1;
  414. }
  415. /* blocking connect on a non-blocking fd; it will timeout after
  416. * tcp_connect_timeout
  417. * if BLOCKING_USE_SELECT and HAVE_SELECT are defined it will internally
  418. * use select() instead of poll (bad if fd > FD_SET_SIZE, poll is preferred)
  419. */
  420. static int tcp_blocking_connect(int fd, const struct sockaddr *servaddr,
  421. socklen_t addrlen)
  422. {
  423. int n;
  424. #if defined(HAVE_SELECT) && defined(BLOCKING_USE_SELECT)
  425. fd_set sel_set;
  426. fd_set orig_set;
  427. struct timeval timeout;
  428. #else
  429. struct pollfd pf;
  430. #endif
  431. int elapsed;
  432. int to;
  433. int ticks;
  434. int err;
  435. unsigned int err_len;
  436. int poll_err;
  437. poll_err=0;
  438. to=tcp_connect_timeout;
  439. ticks=get_ticks();
  440. again:
  441. n=connect(fd, servaddr, addrlen);
  442. if (n==-1){
  443. if (errno==EINTR){
  444. elapsed=(get_ticks()-ticks)*TIMER_TICK;
  445. if (elapsed<to) goto again;
  446. else goto error_timeout;
  447. }
  448. if (errno!=EINPROGRESS && errno!=EALREADY){
  449. LOG(L_ERR, "ERROR: tcp_blocking_connect %s: (%d) %s\n",
  450. su2a((union sockaddr_union*)servaddr, addrlen),
  451. errno, strerror(errno));
  452. goto error;
  453. }
  454. }else goto end;
  455. /* poll/select loop */
  456. #if defined(HAVE_SELECT) && defined(BLOCKING_USE_SELECT)
  457. FD_ZERO(&orig_set);
  458. FD_SET(fd, &orig_set);
  459. #else
  460. pf.fd=fd;
  461. pf.events=POLLOUT;
  462. #endif
  463. while(1){
  464. elapsed=(get_ticks()-ticks)*TIMER_TICK;
  465. if (elapsed<to)
  466. to-=elapsed;
  467. else
  468. goto error_timeout;
  469. #if defined(HAVE_SELECT) && defined(BLOCKING_USE_SELECT)
  470. sel_set=orig_set;
  471. timeout.tv_sec=to;
  472. timeout.tv_usec=0;
  473. n=select(fd+1, 0, &sel_set, 0, &timeout);
  474. #else
  475. n=poll(&pf, 1, to*1000);
  476. #endif
  477. if (n<0){
  478. if (errno==EINTR) continue;
  479. LOG(L_ERR, "ERROR: tcp_blocking_connect %s: poll/select failed:"
  480. " (%d) %s\n",
  481. su2a((union sockaddr_union*)servaddr, addrlen),
  482. errno, strerror(errno));
  483. goto error;
  484. }else if (n==0) /* timeout */ continue;
  485. #if defined(HAVE_SELECT) && defined(BLOCKING_USE_SELECT)
  486. if (FD_ISSET(fd, &sel_set))
  487. #else
  488. if (pf.revents&(POLLERR|POLLHUP|POLLNVAL)){
  489. LOG(L_ERR, "ERROR: tcp_blocking_connect %s: poll error: "
  490. "flags %x\n",
  491. su2a((union sockaddr_union*)servaddr, addrlen),
  492. pf.revents);
  493. poll_err=1;
  494. }
  495. #endif
  496. {
  497. err_len=sizeof(err);
  498. getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &err_len);
  499. if ((err==0) && (poll_err==0)) goto end;
  500. if (err!=EINPROGRESS && err!=EALREADY){
  501. LOG(L_ERR, "ERROR: tcp_blocking_connect %s: SO_ERROR (%d) "
  502. "%s\n",
  503. su2a((union sockaddr_union*)servaddr, addrlen),
  504. err, strerror(err));
  505. goto error;
  506. }
  507. }
  508. }
  509. error_timeout:
  510. /* timeout */
  511. LOG(L_ERR, "ERROR: tcp_blocking_connect %s: timeout %d s elapsed "
  512. "from %d s\n", su2a((union sockaddr_union*)servaddr, addrlen),
  513. elapsed, tcp_connect_timeout);
  514. error:
  515. return -1;
  516. end:
  517. return 0;
  518. }
  519. inline static int _tcpconn_write_nb(int fd, struct tcp_connection* c,
  520. char* buf, int len);
  521. #ifdef TCP_BUF_WRITE
  522. /* unsafe version */
  523. #define _wbufq_empty(con) ((con)->wbuf_q.first==0)
  524. /* unsafe version */
  525. #define _wbufq_non_empty(con) ((con)->wbuf_q.first!=0)
  526. /* unsafe version, call while holding the connection write lock */
  527. inline static int _wbufq_add(struct tcp_connection* c, char* data,
  528. unsigned int size)
  529. {
  530. struct tcp_wbuffer_queue* q;
  531. struct tcp_wbuffer* wb;
  532. unsigned int last_free;
  533. unsigned int wb_size;
  534. unsigned int crt_size;
  535. ticks_t t;
  536. q=&c->wbuf_q;
  537. t=get_ticks_raw();
  538. if (unlikely( ((q->queued+size)>tcp_options.tcpconn_wq_max) ||
  539. ((*tcp_total_wq+size)>tcp_options.tcp_wq_max) ||
  540. (q->first &&
  541. TICKS_LT(q->wr_timeout, t)) )){
  542. LOG(L_ERR, "ERROR: wbufq_add(%d bytes): write queue full or timeout "
  543. " (%d, total %d, last write %d s ago)\n",
  544. size, q->queued, *tcp_total_wq,
  545. TICKS_TO_S(t-q->wr_timeout-tcp_options.tcp_wq_timeout));
  546. goto error;
  547. }
  548. if (unlikely(q->last==0)){
  549. wb_size=MAX_unsigned(TCP_WBUF_SIZE, size);
  550. wb=shm_malloc(sizeof(*wb)+wb_size-1);
  551. if (unlikely(wb==0))
  552. goto error;
  553. wb->b_size=wb_size;
  554. wb->next=0;
  555. q->last=wb;
  556. q->first=wb;
  557. q->last_used=0;
  558. q->offset=0;
  559. q->wr_timeout=get_ticks_raw()+tcp_options.tcp_wq_timeout;
  560. }else{
  561. wb=q->last;
  562. }
  563. while(size){
  564. last_free=wb->b_size-q->last_used;
  565. if (last_free==0){
  566. wb_size=MAX_unsigned(TCP_WBUF_SIZE, size);
  567. wb=shm_malloc(sizeof(*wb)+wb_size-1);
  568. if (unlikely(wb==0))
  569. goto error;
  570. wb->b_size=wb_size;
  571. wb->next=0;
  572. q->last->next=wb;
  573. q->last=wb;
  574. q->last_used=0;
  575. last_free=wb->b_size;
  576. }
  577. crt_size=MIN_unsigned(last_free, size);
  578. memcpy(wb->buf+q->last_used, data, crt_size);
  579. q->last_used+=crt_size;
  580. size-=crt_size;
  581. data+=crt_size;
  582. q->queued+=crt_size;
  583. atomic_add_int((int*)tcp_total_wq, crt_size);
  584. }
  585. return 0;
  586. error:
  587. return -1;
  588. }
  589. /* unsafe version, call while holding the connection write lock
  590. * inserts data at the beginning, it ignores the max queue size checks and
  591. * the timeout (use sparingly)
  592. * Note: it should never be called on a write buffer after wbufq_run() */
  593. inline static int _wbufq_insert(struct tcp_connection* c, char* data,
  594. unsigned int size)
  595. {
  596. struct tcp_wbuffer_queue* q;
  597. struct tcp_wbuffer* wb;
  598. q=&c->wbuf_q;
  599. if (likely(q->first==0)) /* if empty, use wbufq_add */
  600. return _wbufq_add(c, data, size);
  601. if (unlikely((*tcp_total_wq+size)>tcp_options.tcp_wq_max)){
  602. LOG(L_ERR, "ERROR: wbufq_insert(%d bytes): write queue full or timeout"
  603. " (%d, total %d, last write %d s ago)\n",
  604. size, q->queued, *tcp_total_wq,
  605. TICKS_TO_S(get_ticks_raw()-q->wr_timeout-
  606. tcp_options.tcp_wq_timeout));
  607. goto error;
  608. }
  609. if (unlikely(q->offset)){
  610. LOG(L_CRIT, "BUG: wbufq_insert: non-null offset %d (bad call, should"
  611. "never be called after the wbufq_run())\n", q->offset);
  612. goto error;
  613. }
  614. if ((q->first==q->last) && ((q->last->b_size-q->last_used)>=size)){
  615. /* one block with enough space in it for size bytes */
  616. memmove(q->first->buf+size, q->first->buf, size);
  617. memcpy(q->first->buf, data, size);
  618. q->last_used+=size;
  619. }else{
  620. /* create a size bytes block directly */
  621. wb=shm_malloc(sizeof(*wb)+size-1);
  622. if (unlikely(wb==0))
  623. goto error;
  624. wb->b_size=size;
  625. /* insert it */
  626. wb->next=q->first;
  627. q->first=wb;
  628. memcpy(wb->buf, data, size);
  629. }
  630. q->queued+=size;
  631. atomic_add_int((int*)tcp_total_wq, size);
  632. return 0;
  633. error:
  634. return -1;
  635. }
  636. /* unsafe version, call while holding the connection write lock */
  637. inline static void _wbufq_destroy( struct tcp_wbuffer_queue* q)
  638. {
  639. struct tcp_wbuffer* wb;
  640. struct tcp_wbuffer* next_wb;
  641. int unqueued;
  642. unqueued=0;
  643. if (likely(q->first)){
  644. wb=q->first;
  645. do{
  646. next_wb=wb->next;
  647. unqueued+=(wb==q->last)?q->last_used:wb->b_size;
  648. if (wb==q->first)
  649. unqueued-=q->offset;
  650. shm_free(wb);
  651. wb=next_wb;
  652. }while(wb);
  653. }
  654. memset(q, 0, sizeof(*q));
  655. atomic_add_int((int*)tcp_total_wq, -unqueued);
  656. }
  657. /* tries to empty the queue (safe version, c->write_lock must not be hold)
  658. * returns -1 on error, bytes written on success (>=0)
  659. * if the whole queue is emptied => sets *empty*/
  660. inline static int wbufq_run(int fd, struct tcp_connection* c, int* empty)
  661. {
  662. struct tcp_wbuffer_queue* q;
  663. struct tcp_wbuffer* wb;
  664. int n;
  665. int ret;
  666. int block_size;
  667. ticks_t t;
  668. char* buf;
  669. *empty=0;
  670. ret=0;
  671. t=get_ticks_raw();
  672. lock_get(&c->write_lock);
  673. q=&c->wbuf_q;
  674. while(q->first){
  675. block_size=((q->first==q->last)?q->last_used:q->first->b_size)-
  676. q->offset;
  677. buf=q->first->buf+q->offset;
  678. n=_tcpconn_write_nb(fd, c, buf, block_size);
  679. if (likely(n>0)){
  680. ret+=n;
  681. if (likely(n==block_size)){
  682. wb=q->first;
  683. q->first=q->first->next;
  684. shm_free(wb);
  685. q->offset=0;
  686. q->queued-=block_size;
  687. atomic_add_int((int*)tcp_total_wq, -block_size);
  688. }else{
  689. q->offset+=n;
  690. q->queued-=n;
  691. atomic_add_int((int*)tcp_total_wq, -n);
  692. break;
  693. }
  694. q->wr_timeout=t+tcp_options.tcp_wq_timeout;
  695. c->state=S_CONN_OK;
  696. }else{
  697. if (n<0){
  698. /* EINTR is handled inside _tcpconn_write_nb */
  699. if (!(errno==EAGAIN || errno==EWOULDBLOCK)){
  700. ret=-1;
  701. LOG(L_ERR, "ERROR: wbuf_runq: %s [%d]\n",
  702. strerror(errno), errno);
  703. }
  704. }
  705. break;
  706. }
  707. }
  708. if (likely(q->first==0)){
  709. q->last=0;
  710. q->last_used=0;
  711. q->offset=0;
  712. *empty=1;
  713. }
  714. if (unlikely(c->state==S_CONN_CONNECT && (ret>0)))
  715. c->state=S_CONN_OK;
  716. lock_release(&c->write_lock);
  717. return ret;
  718. }
  719. #endif /* TCP_BUF_WRITE */
  720. #if 0
  721. /* blocking write even on non-blocking sockets
  722. * if TCP_TIMEOUT will return with error */
  723. static int tcp_blocking_write(struct tcp_connection* c, int fd, char* buf,
  724. unsigned int len)
  725. {
  726. int n;
  727. fd_set sel_set;
  728. struct timeval timeout;
  729. int ticks;
  730. int initial_len;
  731. initial_len=len;
  732. again:
  733. n=send(fd, buf, len,
  734. #ifdef HAVE_MSG_NOSIGNAL
  735. MSG_NOSIGNAL
  736. #else
  737. 0
  738. #endif
  739. );
  740. if (n<0){
  741. if (errno==EINTR) goto again;
  742. else if (errno!=EAGAIN && errno!=EWOULDBLOCK){
  743. LOG(L_ERR, "tcp_blocking_write: failed to send: (%d) %s\n",
  744. errno, strerror(errno));
  745. goto error;
  746. }
  747. }else if (n<len){
  748. /* partial write */
  749. buf+=n;
  750. len-=n;
  751. }else{
  752. /* success: full write */
  753. goto end;
  754. }
  755. while(1){
  756. FD_ZERO(&sel_set);
  757. FD_SET(fd, &sel_set);
  758. timeout.tv_sec=tcp_send_timeout;
  759. timeout.tv_usec=0;
  760. ticks=get_ticks();
  761. n=select(fd+1, 0, &sel_set, 0, &timeout);
  762. if (n<0){
  763. if (errno==EINTR) continue; /* signal, ignore */
  764. LOG(L_ERR, "ERROR: tcp_blocking_write: select failed: "
  765. " (%d) %s\n", errno, strerror(errno));
  766. goto error;
  767. }else if (n==0){
  768. /* timeout */
  769. if (get_ticks()-ticks>=tcp_send_timeout){
  770. LOG(L_ERR, "ERROR: tcp_blocking_write: send timeout (%d)\n",
  771. tcp_send_timeout);
  772. goto error;
  773. }
  774. continue;
  775. }
  776. if (FD_ISSET(fd, &sel_set)){
  777. /* we can write again */
  778. goto again;
  779. }
  780. }
  781. error:
  782. return -1;
  783. end:
  784. return initial_len;
  785. }
  786. #endif
  787. struct tcp_connection* tcpconn_new(int sock, union sockaddr_union* su,
  788. union sockaddr_union* local_addr,
  789. struct socket_info* ba, int type,
  790. int state)
  791. {
  792. struct tcp_connection *c;
  793. c=(struct tcp_connection*)shm_malloc(sizeof(struct tcp_connection));
  794. if (c==0){
  795. LOG(L_ERR, "ERROR: tcpconn_new: mem. allocation failure\n");
  796. goto error;
  797. }
  798. memset(c, 0, sizeof(struct tcp_connection)); /* zero init */
  799. c->s=sock;
  800. c->fd=-1; /* not initialized */
  801. if (lock_init(&c->write_lock)==0){
  802. LOG(L_ERR, "ERROR: tcpconn_new: init lock failed\n");
  803. goto error;
  804. }
  805. c->rcv.src_su=*su;
  806. atomic_set(&c->refcnt, 0);
  807. local_timer_init(&c->timer, tcpconn_main_timeout, c, 0);
  808. su2ip_addr(&c->rcv.src_ip, su);
  809. c->rcv.src_port=su_getport(su);
  810. c->rcv.bind_address=ba;
  811. if (likely(local_addr)){
  812. su2ip_addr(&c->rcv.dst_ip, local_addr);
  813. c->rcv.dst_port=su_getport(local_addr);
  814. }else if (ba){
  815. c->rcv.dst_ip=ba->address;
  816. c->rcv.dst_port=ba->port_no;
  817. }
  818. print_ip("tcpconn_new: new tcp connection: ", &c->rcv.src_ip, "\n");
  819. DBG( "tcpconn_new: on port %d, type %d\n", c->rcv.src_port, type);
  820. init_tcp_req(&c->req);
  821. c->id=(*connection_id)++;
  822. c->rcv.proto_reserved1=0; /* this will be filled before receive_message*/
  823. c->rcv.proto_reserved2=0;
  824. c->state=state;
  825. c->extra_data=0;
  826. #ifdef USE_TLS
  827. if (type==PROTO_TLS){
  828. if (tls_tcpconn_init(c, sock)==-1) goto error;
  829. }else
  830. #endif /* USE_TLS*/
  831. {
  832. c->type=PROTO_TCP;
  833. c->rcv.proto=PROTO_TCP;
  834. c->timeout=get_ticks_raw()+tcp_con_lifetime;
  835. }
  836. return c;
  837. error:
  838. if (c) shm_free(c);
  839. return 0;
  840. }
  841. /* do the actual connect, set sock. options a.s.o
  842. * returns socket on success, -1 on error
  843. * sets also *res_local_addr, res_si and state (S_CONN_CONNECT for an
  844. * unfinished connect and S_CONN_OK for a finished one)*/
  845. inline static int tcp_do_connect( union sockaddr_union* server,
  846. union sockaddr_union* from,
  847. int type,
  848. union sockaddr_union* res_local_addr,
  849. struct socket_info** res_si,
  850. enum tcp_conn_states *state
  851. )
  852. {
  853. int s;
  854. union sockaddr_union my_name;
  855. socklen_t my_name_len;
  856. struct ip_addr ip;
  857. #ifdef TCP_BUF_WRITE
  858. int n;
  859. #endif /* TCP_BUF_WRITE */
  860. s=socket(AF2PF(server->s.sa_family), SOCK_STREAM, 0);
  861. if (unlikely(s==-1)){
  862. LOG(L_ERR, "ERROR: tcp_do_connect %s: socket: (%d) %s\n",
  863. su2a(server, sizeof(*server)), errno, strerror(errno));
  864. goto error;
  865. }
  866. if (init_sock_opt(s)<0){
  867. LOG(L_ERR, "ERROR: tcp_do_connect %s: init_sock_opt failed\n",
  868. su2a(server, sizeof(*server)));
  869. goto error;
  870. }
  871. if (unlikely(from && bind(s, &from->s, sockaddru_len(*from)) != 0)){
  872. LOG(L_WARN, "WARNING: tcp_do_connect: binding to source address"
  873. " %s failed: %s [%d]\n", su2a(from, sizeof(*from)),
  874. strerror(errno), errno);
  875. }
  876. *state=S_CONN_OK;
  877. #ifdef TCP_BUF_WRITE
  878. if (likely(tcp_options.tcp_buf_write)){
  879. again:
  880. n=connect(s, &server->s, sockaddru_len(*server));
  881. if (unlikely(n==-1)){
  882. if (errno==EINTR) goto again;
  883. if (likely(errno==EINPROGRESS))
  884. *state=S_CONN_CONNECT;
  885. else if (errno!=EALREADY){
  886. LOG(L_ERR, "ERROR: tcp_do_connect: connect %s: (%d) %s\n",
  887. su2a(server, sizeof(*server)),
  888. errno, strerror(errno));
  889. goto error;
  890. }
  891. }
  892. }else{
  893. #endif /* TCP_BUF_WRITE */
  894. if (tcp_blocking_connect(s, &server->s, sockaddru_len(*server))<0){
  895. LOG(L_ERR, "ERROR: tcp_do_connect: tcp_blocking_connect %s"
  896. " failed\n", su2a(server, sizeof(*server)));
  897. goto error;
  898. }
  899. #ifdef TCP_BUF_WRITE
  900. }
  901. #endif /* TCP_BUF_WRITE */
  902. if (from){
  903. su2ip_addr(&ip, from);
  904. if (!ip_addr_any(&ip))
  905. /* we already know the source ip, skip the sys. call */
  906. goto find_socket;
  907. }
  908. my_name_len=sizeof(my_name);
  909. if (unlikely(getsockname(s, &my_name.s, &my_name_len)!=0)){
  910. LOG(L_ERR, "ERROR: tcp_do_connect: getsockname failed: %s(%d)\n",
  911. strerror(errno), errno);
  912. *res_si=0;
  913. goto error;
  914. }
  915. from=&my_name; /* update from with the real "from" address */
  916. su2ip_addr(&ip, &my_name);
  917. find_socket:
  918. #ifdef USE_TLS
  919. if (unlikely(type==PROTO_TLS))
  920. *res_si=find_si(&ip, 0, PROTO_TLS);
  921. else
  922. #endif
  923. *res_si=find_si(&ip, 0, PROTO_TCP);
  924. if (unlikely(*res_si==0)){
  925. LOG(L_WARN, "WARNING: tcp_do_connect %s: could not find corresponding"
  926. " listening socket for %s, using default...\n",
  927. su2a(server, sizeof(*server)), ip_addr2a(&ip));
  928. if (server->s.sa_family==AF_INET) *res_si=sendipv4_tcp;
  929. #ifdef USE_IPV6
  930. else *res_si=sendipv6_tcp;
  931. #endif
  932. }
  933. *res_local_addr=*from;
  934. return s;
  935. error:
  936. if (s!=-1) close(s);
  937. return -1;
  938. }
  939. struct tcp_connection* tcpconn_connect( union sockaddr_union* server,
  940. union sockaddr_union* from,
  941. int type)
  942. {
  943. int s;
  944. struct socket_info* si;
  945. union sockaddr_union my_name;
  946. struct tcp_connection* con;
  947. enum tcp_conn_states state;
  948. s=-1;
  949. if (*tcp_connections_no >= tcp_max_connections){
  950. LOG(L_ERR, "ERROR: tcpconn_connect: maximum number of connections"
  951. " exceeded (%d/%d)\n",
  952. *tcp_connections_no, tcp_max_connections);
  953. goto error;
  954. }
  955. s=tcp_do_connect(server, from, type, &my_name, &si, &state);
  956. if (s==-1){
  957. LOG(L_ERR, "ERROR: tcp_do_connect %s: failed (%d) %s\n",
  958. su2a(server, sizeof(*server)), errno, strerror(errno));
  959. goto error;
  960. }
  961. con=tcpconn_new(s, server, &my_name, si, type, state);
  962. if (con==0){
  963. LOG(L_ERR, "ERROR: tcp_connect %s: tcpconn_new failed, closing the "
  964. " socket\n", su2a(server, sizeof(*server)));
  965. goto error;
  966. }
  967. return con;
  968. /*FIXME: set sock idx! */
  969. error:
  970. if (s!=-1) close(s); /* close the opened socket */
  971. return 0;
  972. }
  973. #ifdef TCP_CONNECT_WAIT
  974. int tcpconn_finish_connect( struct tcp_connection* c,
  975. union sockaddr_union* from)
  976. {
  977. int s;
  978. int r;
  979. union sockaddr_union local_addr;
  980. struct socket_info* si;
  981. enum tcp_conn_states state;
  982. struct tcp_conn_alias* a;
  983. s=tcp_do_connect(&c->rcv.src_su, from, c->type, &local_addr, &si, &state);
  984. if (unlikely(s==-1)){
  985. LOG(L_ERR, "ERROR: tcpconn_finish_connect %s: tcp_do_connect for %p"
  986. " failed\n", su2a(&c->rcv.src_su, sizeof(c->rcv.src_su)),
  987. c);
  988. return -1;
  989. }
  990. c->rcv.bind_address=si;
  991. su2ip_addr(&c->rcv.dst_ip, &local_addr);
  992. c->rcv.dst_port=su_getport(&local_addr);
  993. /* update aliases if needed */
  994. if (likely(from==0)){
  995. /* add aliases */
  996. TCPCONN_LOCK;
  997. _tcpconn_add_alias_unsafe(c, c->rcv.src_port, &c->rcv.dst_ip, 0,
  998. tcp_new_conn_alias_flags);
  999. _tcpconn_add_alias_unsafe(c, c->rcv.src_port, &c->rcv.dst_ip,
  1000. c->rcv.dst_port, tcp_new_conn_alias_flags);
  1001. TCPCONN_UNLOCK;
  1002. }else if (su_cmp(from, &local_addr)!=1){
  1003. TCPCONN_LOCK;
  1004. /* remove all the aliases except the first one and re-add them
  1005. * (there shouldn't be more then the 3 default aliases at this
  1006. * stage) */
  1007. for (r=1; r<c->aliases; r++){
  1008. a=&c->con_aliases[r];
  1009. tcpconn_listrm(tcpconn_aliases_hash[a->hash], a, next, prev);
  1010. }
  1011. c->aliases=1;
  1012. /* add the local_ip:0 and local_ip:local_port aliases */
  1013. _tcpconn_add_alias_unsafe(c, c->rcv.src_port, &c->rcv.dst_ip,
  1014. 0, tcp_new_conn_alias_flags);
  1015. _tcpconn_add_alias_unsafe(c, c->rcv.src_port, &c->rcv.dst_ip,
  1016. c->rcv.dst_port, tcp_new_conn_alias_flags);
  1017. TCPCONN_UNLOCK;
  1018. }
  1019. return s;
  1020. }
  1021. #endif /* TCP_CONNECT_WAIT */
  1022. /* adds a tcp connection to the tcpconn hashes
  1023. * Note: it's called _only_ from the tcp_main process */
  1024. inline static struct tcp_connection* tcpconn_add(struct tcp_connection *c)
  1025. {
  1026. struct ip_addr zero_ip;
  1027. if (likely(c)){
  1028. ip_addr_mk_any(c->rcv.src_ip.af, &zero_ip);
  1029. c->id_hash=tcp_id_hash(c->id);
  1030. c->aliases=0;
  1031. TCPCONN_LOCK;
  1032. c->flags|=F_CONN_HASHED;
  1033. /* add it at the begining of the list*/
  1034. tcpconn_listadd(tcpconn_id_hash[c->id_hash], c, id_next, id_prev);
  1035. /* set the aliases */
  1036. /* first alias is for (peer_ip, peer_port, 0 ,0) -- for finding
  1037. * any connection to peer_ip, peer_port
  1038. * the second alias is for (peer_ip, peer_port, local_addr, 0) -- for
  1039. * finding any conenction to peer_ip, peer_port from local_addr
  1040. * the third alias is for (peer_ip, peer_port, local_addr, local_port)
  1041. * -- for finding if a fully specified connection exists */
  1042. _tcpconn_add_alias_unsafe(c, c->rcv.src_port, &zero_ip, 0,
  1043. tcp_new_conn_alias_flags);
  1044. if (likely(c->rcv.dst_ip.af && ! ip_addr_any(&c->rcv.dst_ip))){
  1045. _tcpconn_add_alias_unsafe(c, c->rcv.src_port, &c->rcv.dst_ip, 0,
  1046. tcp_new_conn_alias_flags);
  1047. _tcpconn_add_alias_unsafe(c, c->rcv.src_port, &c->rcv.dst_ip,
  1048. c->rcv.dst_port, tcp_new_conn_alias_flags);
  1049. }
  1050. /* ignore add_alias errors, there are some valid cases when one
  1051. * of the add_alias would fail (e.g. first add_alias for 2 connections
  1052. * with the same destination but different src. ip*/
  1053. TCPCONN_UNLOCK;
  1054. DBG("tcpconn_add: hashes: %d:%d:%d, %d\n",
  1055. c->con_aliases[0].hash,
  1056. c->con_aliases[1].hash,
  1057. c->con_aliases[2].hash,
  1058. c->id_hash);
  1059. return c;
  1060. }else{
  1061. LOG(L_CRIT, "tcpconn_add: BUG: null connection pointer\n");
  1062. return 0;
  1063. }
  1064. }
  1065. static inline void _tcpconn_detach(struct tcp_connection *c)
  1066. {
  1067. int r;
  1068. tcpconn_listrm(tcpconn_id_hash[c->id_hash], c, id_next, id_prev);
  1069. /* remove all the aliases */
  1070. for (r=0; r<c->aliases; r++)
  1071. tcpconn_listrm(tcpconn_aliases_hash[c->con_aliases[r].hash],
  1072. &c->con_aliases[r], next, prev);
  1073. }
  1074. static inline void _tcpconn_free(struct tcp_connection* c)
  1075. {
  1076. #ifdef TCP_BUF_WRITE
  1077. if (unlikely(_wbufq_non_empty(c)))
  1078. _wbufq_destroy(&c->wbuf_q);
  1079. #endif
  1080. lock_destroy(&c->write_lock);
  1081. #ifdef USE_TLS
  1082. if (unlikely(c->type==PROTO_TLS)) tls_tcpconn_clean(c);
  1083. #endif
  1084. shm_free(c);
  1085. }
  1086. /* unsafe tcpconn_rm version (nolocks) */
  1087. void _tcpconn_rm(struct tcp_connection* c)
  1088. {
  1089. _tcpconn_detach(c);
  1090. _tcpconn_free(c);
  1091. }
  1092. void tcpconn_rm(struct tcp_connection* c)
  1093. {
  1094. int r;
  1095. TCPCONN_LOCK;
  1096. tcpconn_listrm(tcpconn_id_hash[c->id_hash], c, id_next, id_prev);
  1097. /* remove all the aliases */
  1098. for (r=0; r<c->aliases; r++)
  1099. tcpconn_listrm(tcpconn_aliases_hash[c->con_aliases[r].hash],
  1100. &c->con_aliases[r], next, prev);
  1101. TCPCONN_UNLOCK;
  1102. lock_destroy(&c->write_lock);
  1103. #ifdef USE_TLS
  1104. if ((c->type==PROTO_TLS)&&(c->extra_data)) tls_tcpconn_clean(c);
  1105. #endif
  1106. shm_free(c);
  1107. }
  1108. /* finds a connection, if id=0 uses the ip addr, port, local_ip and local port
  1109. * (host byte order) and tries to find the connection that matches all of
  1110. * them. Wild cards can be used for local_ip and local_port (a 0 filled
  1111. * ip address and/or a 0 local port).
  1112. * WARNING: unprotected (locks) use tcpconn_get unless you really
  1113. * know what you are doing */
  1114. struct tcp_connection* _tcpconn_find(int id, struct ip_addr* ip, int port,
  1115. struct ip_addr* l_ip, int l_port)
  1116. {
  1117. struct tcp_connection *c;
  1118. struct tcp_conn_alias* a;
  1119. unsigned hash;
  1120. int is_local_ip_any;
  1121. #ifdef EXTRA_DEBUG
  1122. DBG("tcpconn_find: %d port %d\n",id, port);
  1123. if (ip) print_ip("tcpconn_find: ip ", ip, "\n");
  1124. #endif
  1125. if (likely(id)){
  1126. hash=tcp_id_hash(id);
  1127. for (c=tcpconn_id_hash[hash]; c; c=c->id_next){
  1128. #ifdef EXTRA_DEBUG
  1129. DBG("c=%p, c->id=%d, port=%d\n",c, c->id, c->rcv.src_port);
  1130. print_ip("ip=", &c->rcv.src_ip, "\n");
  1131. #endif
  1132. if ((id==c->id)&&(c->state!=S_CONN_BAD)) return c;
  1133. }
  1134. }else if (likely(ip)){
  1135. hash=tcp_addr_hash(ip, port, l_ip, l_port);
  1136. is_local_ip_any=ip_addr_any(l_ip);
  1137. for (a=tcpconn_aliases_hash[hash]; a; a=a->next){
  1138. #ifdef EXTRA_DEBUG
  1139. DBG("a=%p, c=%p, c->id=%d, alias port= %d port=%d\n", a, a->parent,
  1140. a->parent->id, a->port, a->parent->rcv.src_port);
  1141. print_ip("ip=",&a->parent->rcv.src_ip,"\n");
  1142. #endif
  1143. if ( (a->parent->state!=S_CONN_BAD) && (port==a->port) &&
  1144. ((l_port==0) || (l_port==a->parent->rcv.dst_port)) &&
  1145. (ip_addr_cmp(ip, &a->parent->rcv.src_ip)) &&
  1146. (is_local_ip_any ||
  1147. ip_addr_cmp(l_ip, &a->parent->rcv.dst_ip))
  1148. )
  1149. return a->parent;
  1150. }
  1151. }
  1152. return 0;
  1153. }
  1154. /* _tcpconn_find with locks and timeout
  1155. * local_addr contains the desired local ip:port. If null any local address
  1156. * will be used. IN*ADDR_ANY or 0 port are wild cards.
  1157. */
  1158. struct tcp_connection* tcpconn_get(int id, struct ip_addr* ip, int port,
  1159. union sockaddr_union* local_addr,
  1160. ticks_t timeout)
  1161. {
  1162. struct tcp_connection* c;
  1163. struct ip_addr local_ip;
  1164. int local_port;
  1165. local_port=0;
  1166. if (likely(ip)){
  1167. if (unlikely(local_addr)){
  1168. su2ip_addr(&local_ip, local_addr);
  1169. local_port=su_getport(local_addr);
  1170. }else{
  1171. ip_addr_mk_any(ip->af, &local_ip);
  1172. local_port=0;
  1173. }
  1174. }
  1175. TCPCONN_LOCK;
  1176. c=_tcpconn_find(id, ip, port, &local_ip, local_port);
  1177. if (likely(c)){
  1178. atomic_inc(&c->refcnt);
  1179. /* update the timeout only if the connection is not handled
  1180. * by a tcp reader (the tcp reader process uses c->timeout for
  1181. * its own internal timeout and c->timeout will be overwritten
  1182. * anyway on return to tcp_main) */
  1183. if (likely(c->reader_pid==0))
  1184. c->timeout=get_ticks_raw()+timeout;
  1185. }
  1186. TCPCONN_UNLOCK;
  1187. return c;
  1188. }
  1189. /* add c->dst:port, local_addr as an alias for the "id" connection,
  1190. * flags: TCP_ALIAS_FORCE_ADD - add an alias even if a previous one exists
  1191. * TCP_ALIAS_REPLACE - if a prev. alias exists, replace it with the
  1192. * new one
  1193. * returns 0 on success, <0 on failure ( -1 - null c, -2 too many aliases,
  1194. * -3 alias already present and pointing to another connection)
  1195. * WARNING: must be called with TCPCONN_LOCK held */
  1196. inline static int _tcpconn_add_alias_unsafe(struct tcp_connection* c, int port,
  1197. struct ip_addr* l_ip, int l_port,
  1198. int flags)
  1199. {
  1200. unsigned hash;
  1201. struct tcp_conn_alias* a;
  1202. struct tcp_conn_alias* nxt;
  1203. struct tcp_connection* p;
  1204. int is_local_ip_any;
  1205. int i;
  1206. int r;
  1207. a=0;
  1208. is_local_ip_any=ip_addr_any(l_ip);
  1209. if (likely(c)){
  1210. hash=tcp_addr_hash(&c->rcv.src_ip, port, l_ip, l_port);
  1211. /* search the aliases for an already existing one */
  1212. for (a=tcpconn_aliases_hash[hash], nxt=0; a; a=nxt){
  1213. nxt=a->next;
  1214. if ( (a->parent->state!=S_CONN_BAD) && (port==a->port) &&
  1215. ( (l_port==0) || (l_port==a->parent->rcv.dst_port)) &&
  1216. (ip_addr_cmp(&c->rcv.src_ip, &a->parent->rcv.src_ip)) &&
  1217. ( is_local_ip_any ||
  1218. ip_addr_cmp(&a->parent->rcv.dst_ip, l_ip))
  1219. ){
  1220. /* found */
  1221. if (unlikely(a->parent!=c)){
  1222. if (flags & TCP_ALIAS_FORCE_ADD)
  1223. /* still have to walk the whole list to check if
  1224. * the alias was not already added */
  1225. continue;
  1226. else if (flags & TCP_ALIAS_REPLACE){
  1227. /* remove the alias =>
  1228. * remove the current alias and all the following
  1229. * ones from the corresponding connection, shift the
  1230. * connection aliases array and re-add the other
  1231. * aliases (!= current one) */
  1232. p=a->parent;
  1233. for (i=0; (i<p->aliases) && (&(p->con_aliases[i])!=a);
  1234. i++);
  1235. if (unlikely(i==p->aliases)){
  1236. LOG(L_CRIT, "BUG: _tcpconn_add_alias_unsafe: "
  1237. " alias %p not found in con %p (id %d)\n",
  1238. a, p, p->id);
  1239. goto error_not_found;
  1240. }
  1241. for (r=i; r<p->aliases; r++){
  1242. tcpconn_listrm(
  1243. tcpconn_aliases_hash[p->con_aliases[r].hash],
  1244. &p->con_aliases[r], next, prev);
  1245. }
  1246. if (likely((i+1)<p->aliases)){
  1247. memmove(&p->con_aliases[i], &p->con_aliases[i+1],
  1248. (p->aliases-i-1)*
  1249. sizeof(p->con_aliases[0]));
  1250. }
  1251. p->aliases--;
  1252. /* re-add the remaining aliases */
  1253. for (r=i; r<p->aliases; r++){
  1254. tcpconn_listadd(
  1255. tcpconn_aliases_hash[p->con_aliases[r].hash],
  1256. &p->con_aliases[r], next, prev);
  1257. }
  1258. }else
  1259. goto error_sec;
  1260. }else goto ok;
  1261. }
  1262. }
  1263. if (unlikely(c->aliases>=TCP_CON_MAX_ALIASES)) goto error_aliases;
  1264. c->con_aliases[c->aliases].parent=c;
  1265. c->con_aliases[c->aliases].port=port;
  1266. c->con_aliases[c->aliases].hash=hash;
  1267. tcpconn_listadd(tcpconn_aliases_hash[hash],
  1268. &c->con_aliases[c->aliases], next, prev);
  1269. c->aliases++;
  1270. }else goto error_not_found;
  1271. ok:
  1272. #ifdef EXTRA_DEBUG
  1273. if (a) DBG("_tcpconn_add_alias_unsafe: alias already present\n");
  1274. else DBG("_tcpconn_add_alias_unsafe: alias port %d for hash %d, id %d\n",
  1275. port, hash, c->id);
  1276. #endif
  1277. return 0;
  1278. error_aliases:
  1279. /* too many aliases */
  1280. return -2;
  1281. error_not_found:
  1282. /* null connection */
  1283. return -1;
  1284. error_sec:
  1285. /* alias already present and pointing to a different connection
  1286. * (hijack attempt?) */
  1287. return -3;
  1288. }
  1289. /* add port as an alias for the "id" connection,
  1290. * returns 0 on success,-1 on failure */
  1291. int tcpconn_add_alias(int id, int port, int proto)
  1292. {
  1293. struct tcp_connection* c;
  1294. int ret;
  1295. struct ip_addr zero_ip;
  1296. int r;
  1297. /* fix the port */
  1298. port=port?port:((proto==PROTO_TLS)?SIPS_PORT:SIP_PORT);
  1299. TCPCONN_LOCK;
  1300. /* check if alias already exists */
  1301. c=_tcpconn_find(id, 0, 0, 0, 0);
  1302. if (likely(c)){
  1303. ip_addr_mk_any(c->rcv.src_ip.af, &zero_ip);
  1304. /* alias src_ip:port, 0, 0 */
  1305. ret=_tcpconn_add_alias_unsafe(c, port, &zero_ip, 0,
  1306. tcp_alias_flags);
  1307. if (ret<0 && ret!=-3) goto error;
  1308. /* alias src_ip:port, local_ip, 0 */
  1309. ret=_tcpconn_add_alias_unsafe(c, port, &c->rcv.dst_ip, 0,
  1310. tcp_alias_flags);
  1311. if (ret<0 && ret!=-3) goto error;
  1312. /* alias src_ip:port, local_ip, local_port */
  1313. ret=_tcpconn_add_alias_unsafe(c, port, &c->rcv.dst_ip, c->rcv.dst_port,
  1314. tcp_alias_flags);
  1315. if (unlikely(ret<0)) goto error;
  1316. }else goto error_not_found;
  1317. TCPCONN_UNLOCK;
  1318. return 0;
  1319. error_not_found:
  1320. TCPCONN_UNLOCK;
  1321. LOG(L_ERR, "ERROR: tcpconn_add_alias: no connection found for id %d\n",id);
  1322. return -1;
  1323. error:
  1324. TCPCONN_UNLOCK;
  1325. switch(ret){
  1326. case -2:
  1327. LOG(L_ERR, "ERROR: tcpconn_add_alias: too many aliases (%d)"
  1328. " for connection %p (id %d) %s:%d <- %d\n",
  1329. c->aliases, c, c->id, ip_addr2a(&c->rcv.src_ip),
  1330. c->rcv.src_port, port);
  1331. for (r=0; r<c->aliases; r++){
  1332. LOG(L_ERR, "ERROR: tcpconn_add_alias: alias %d: for %p (%d)"
  1333. " %s:%d <-%d hash %x\n", r, c, c->id,
  1334. ip_addr2a(&c->rcv.src_ip), c->rcv.src_port,
  1335. c->con_aliases[r].port, c->con_aliases[r].hash);
  1336. }
  1337. break;
  1338. case -3:
  1339. LOG(L_ERR, "ERROR: tcpconn_add_alias: possible port"
  1340. " hijack attempt\n");
  1341. LOG(L_ERR, "ERROR: tcpconn_add_alias: alias for %d port %d already"
  1342. " present and points to another connection \n",
  1343. c->id, port);
  1344. break;
  1345. default:
  1346. LOG(L_ERR, "ERROR: tcpconn_add_alias: unkown error %d\n", ret);
  1347. }
  1348. return -1;
  1349. }
  1350. #ifdef TCP_FD_CACHE
  1351. static void tcp_fd_cache_init()
  1352. {
  1353. int r;
  1354. for (r=0; r<TCP_FD_CACHE_SIZE; r++)
  1355. fd_cache[r].fd=-1;
  1356. }
  1357. inline static struct fd_cache_entry* tcp_fd_cache_get(struct tcp_connection *c)
  1358. {
  1359. int h;
  1360. h=c->id%TCP_FD_CACHE_SIZE;
  1361. if ((fd_cache[h].fd>0) && (fd_cache[h].id==c->id) && (fd_cache[h].con==c))
  1362. return &fd_cache[h];
  1363. return 0;
  1364. }
  1365. inline static void tcp_fd_cache_rm(struct fd_cache_entry* e)
  1366. {
  1367. e->fd=-1;
  1368. }
  1369. inline static void tcp_fd_cache_add(struct tcp_connection *c, int fd)
  1370. {
  1371. int h;
  1372. h=c->id%TCP_FD_CACHE_SIZE;
  1373. if (likely(fd_cache[h].fd>0))
  1374. close(fd_cache[h].fd);
  1375. fd_cache[h].fd=fd;
  1376. fd_cache[h].id=c->id;
  1377. fd_cache[h].con=c;
  1378. }
  1379. #endif /* TCP_FD_CACHE */
  1380. inline static int tcpconn_chld_put(struct tcp_connection* tcpconn);
  1381. /* finds a tcpconn & sends on it
  1382. * uses the dst members to, proto (TCP|TLS) and id and tries to send
  1383. * from the "from" address (if non null and id==0)
  1384. * returns: number of bytes written (>=0) on success
  1385. * <0 on error */
  1386. int tcp_send(struct dest_info* dst, union sockaddr_union* from,
  1387. char* buf, unsigned len)
  1388. {
  1389. struct tcp_connection *c;
  1390. struct tcp_connection *tmp;
  1391. struct ip_addr ip;
  1392. int port;
  1393. int fd;
  1394. long response[2];
  1395. int n;
  1396. int do_close_fd;
  1397. #ifdef TCP_BUF_WRITE
  1398. int enable_write_watch;
  1399. #endif /* TCP_BUF_WRITE */
  1400. #ifdef TCP_FD_CACHE
  1401. struct fd_cache_entry* fd_cache_e;
  1402. int use_fd_cache;
  1403. use_fd_cache=tcp_options.fd_cache;
  1404. fd_cache_e=0;
  1405. #endif /* TCP_FD_CACHE */
  1406. do_close_fd=1; /* close the fd on exit */
  1407. port=su_getport(&dst->to);
  1408. if (likely(port)){
  1409. su2ip_addr(&ip, &dst->to);
  1410. c=tcpconn_get(dst->id, &ip, port, from, tcp_con_lifetime);
  1411. }else if (likely(dst->id)){
  1412. c=tcpconn_get(dst->id, 0, 0, 0, tcp_con_lifetime);
  1413. }else{
  1414. LOG(L_CRIT, "BUG: tcp_send called with null id & to\n");
  1415. return -1;
  1416. }
  1417. if (likely(dst->id)){
  1418. if (unlikely(c==0)) {
  1419. if (likely(port)){
  1420. /* try again w/o id */
  1421. c=tcpconn_get(0, &ip, port, from, tcp_con_lifetime);
  1422. goto no_id;
  1423. }else{
  1424. LOG(L_ERR, "ERROR: tcp_send: id %d not found, dropping\n",
  1425. dst->id);
  1426. return -1;
  1427. }
  1428. }else goto get_fd;
  1429. }
  1430. no_id:
  1431. if (unlikely(c==0)){
  1432. DBG("tcp_send: no open tcp connection found, opening new one\n");
  1433. /* create tcp connection */
  1434. if (likely(from==0)){
  1435. /* check to see if we have to use a specific source addr. */
  1436. switch (dst->to.s.sa_family) {
  1437. case AF_INET:
  1438. from = tcp_source_ipv4;
  1439. break;
  1440. #ifdef USE_IPV6
  1441. case AF_INET6:
  1442. from = tcp_source_ipv6;
  1443. break;
  1444. #endif
  1445. default:
  1446. /* error, bad af, ignore ... */
  1447. break;
  1448. }
  1449. }
  1450. #if defined(TCP_CONNECT_WAIT) && defined(TCP_BUF_WRITE)
  1451. if (likely(tcp_options.tcp_connect_wait &&
  1452. tcp_options.tcp_buf_write )){
  1453. if (unlikely(*tcp_connections_no >= tcp_max_connections)){
  1454. LOG(L_ERR, "ERROR: tcp_send %s: maximum number of"
  1455. " connections exceeded (%d/%d)\n",
  1456. su2a(&dst->to, sizeof(dst->to)),
  1457. *tcp_connections_no, tcp_max_connections);
  1458. return -1;
  1459. }
  1460. c=tcpconn_new(-1, &dst->to, from, 0, dst->proto,
  1461. S_CONN_PENDING);
  1462. if (unlikely(c==0)){
  1463. LOG(L_ERR, "ERROR: tcp_send %s: could not create new"
  1464. " connection\n",
  1465. su2a(&dst->to, sizeof(dst->to)));
  1466. return -1;
  1467. }
  1468. c->flags|=F_CONN_PENDING|F_CONN_FD_CLOSED;
  1469. atomic_set(&c->refcnt, 2); /* ref from here and from main hash
  1470. table */
  1471. /* add it to id hash and aliases */
  1472. if (unlikely(tcpconn_add(c)==0)){
  1473. LOG(L_ERR, "ERROR: tcp_send %s: could not add "
  1474. "connection %p\n",
  1475. su2a(&dst->to, sizeof(dst->to)),
  1476. c);
  1477. _tcpconn_free(c);
  1478. n=-1;
  1479. goto end_no_conn;
  1480. }
  1481. /* do connect and if src ip or port changed, update the
  1482. * aliases */
  1483. if (unlikely((fd=tcpconn_finish_connect(c, from))<0)){
  1484. LOG(L_ERR, "ERROR: tcp_send %s: tcpconn_finish_connect(%p)"
  1485. " failed\n", su2a(&dst->to, sizeof(dst->to)),
  1486. c);
  1487. goto conn_wait_error;
  1488. }
  1489. /* ? TODO: it might be faster just to queue the write directly
  1490. * and send to main CONN_NEW_PENDING_WRITE */
  1491. /* delay sending the fd to main after the send */
  1492. /* NOTE: no lock here, because the connection is marked as
  1493. * pending and nobody else will try to write on it. However
  1494. * this might produce out-of-order writes. If this is not
  1495. * desired either lock before the write or use
  1496. * _wbufq_insert(...) */
  1497. n=_tcpconn_write_nb(fd, c, buf, len);
  1498. if (unlikely(n<(int)len)){
  1499. if ((n>=0) || errno==EAGAIN || errno==EWOULDBLOCK){
  1500. DBG("tcp_send: pending write on new connection %p "
  1501. " (%d/%d bytes written)\n", c, n, len);
  1502. if (n<0) n=0;
  1503. /* add to the write queue */
  1504. lock_get(&c->write_lock);
  1505. if (unlikely(_wbufq_insert(c, buf+n, len-n)<0)){
  1506. lock_release(&c->write_lock);
  1507. n=-1;
  1508. LOG(L_ERR, "ERROR: tcp_send %s: EAGAIN and"
  1509. " write queue full or failed for %p\n",
  1510. su2a(&dst->to, sizeof(dst->to)),
  1511. c);
  1512. goto conn_wait_error;
  1513. }
  1514. lock_release(&c->write_lock);
  1515. /* send to tcp_main */
  1516. response[0]=(long)c;
  1517. response[1]=CONN_NEW_PENDING_WRITE;
  1518. if (unlikely(send_fd(unix_tcp_sock, response,
  1519. sizeof(response), fd) <= 0)){
  1520. LOG(L_ERR, "BUG: tcp_send %s: "
  1521. "CONN_NEW_PENDING_WRITE for %p"
  1522. " failed:" " %s (%d)\n",
  1523. su2a(&dst->to, sizeof(dst->to)),
  1524. c, strerror(errno), errno);
  1525. goto conn_wait_error;
  1526. }
  1527. n=len;
  1528. goto end;
  1529. }
  1530. /* error: destroy it directly */
  1531. LOG(L_ERR, "ERROR: tcp_send %s: connect & send "
  1532. " for %p failed:" " %s (%d)\n",
  1533. su2a(&dst->to, sizeof(dst->to)),
  1534. c, strerror(errno), errno);
  1535. goto conn_wait_error;
  1536. }
  1537. LOG(L_INFO, "tcp_send: quick connect for %p\n", c);
  1538. /* send to tcp_main */
  1539. response[0]=(long)c;
  1540. response[1]=CONN_NEW_COMPLETE;
  1541. if (unlikely(send_fd(unix_tcp_sock, response,
  1542. sizeof(response), fd) <= 0)){
  1543. LOG(L_ERR, "BUG: tcp_send %s: CONN_NEW_COMPLETE for %p"
  1544. " failed:" " %s (%d)\n",
  1545. su2a(&dst->to, sizeof(dst->to)),
  1546. c, strerror(errno), errno);
  1547. goto conn_wait_error;
  1548. }
  1549. goto end;
  1550. }
  1551. #endif /* TCP_CONNECT_WAIT && TCP_BUF_WRITE */
  1552. if (unlikely((c=tcpconn_connect(&dst->to, from, dst->proto))==0)){
  1553. LOG(L_ERR, "ERROR: tcp_send %s: connect failed\n",
  1554. su2a(&dst->to, sizeof(dst->to)));
  1555. return -1;
  1556. }
  1557. atomic_set(&c->refcnt, 2); /* ref. from here and it will also
  1558. be added in the tcp_main hash */
  1559. fd=c->s;
  1560. c->flags|=F_CONN_FD_CLOSED; /* not yet opened in main */
  1561. /* ? TODO: it might be faster just to queue the write and
  1562. * send to main a CONN_NEW_PENDING_WRITE */
  1563. /* send the new tcpconn to "tcp main" */
  1564. response[0]=(long)c;
  1565. response[1]=CONN_NEW;
  1566. n=send_fd(unix_tcp_sock, response, sizeof(response), c->s);
  1567. if (unlikely(n<=0)){
  1568. LOG(L_ERR, "BUG: tcp_send %s: failed send_fd: %s (%d)\n",
  1569. su2a(&dst->to, sizeof(dst->to)),
  1570. strerror(errno), errno);
  1571. /* we can safely delete it, it's not referenced by anybody */
  1572. _tcpconn_free(c);
  1573. n=-1;
  1574. goto end_no_conn;
  1575. }
  1576. goto send_it;
  1577. }
  1578. get_fd:
  1579. #ifdef TCP_BUF_WRITE
  1580. /* if data is already queued, we don't need the fd any more */
  1581. if (unlikely(tcp_options.tcp_buf_write && (_wbufq_non_empty(c)
  1582. #ifdef TCP_CONNECT_WAIT
  1583. || (c->state==S_CONN_PENDING)
  1584. #endif /* TCP_CONNECT_WAIT */
  1585. ) )){
  1586. lock_get(&c->write_lock);
  1587. if (likely(_wbufq_non_empty(c)
  1588. #ifdef TCP_CONNECT_WAIT
  1589. || (c->state==S_CONN_PENDING)
  1590. #endif /* TCP_CONNECT_WAIT */
  1591. )){
  1592. do_close_fd=0;
  1593. if (unlikely(_wbufq_add(c, buf, len)<0)){
  1594. lock_release(&c->write_lock);
  1595. n=-1;
  1596. goto error;
  1597. }
  1598. n=len;
  1599. lock_release(&c->write_lock);
  1600. goto release_c;
  1601. }
  1602. lock_release(&c->write_lock);
  1603. }
  1604. #endif /* TCP_BUF_WRITE */
  1605. /* check if this is not the same reader process holding
  1606. * c and if so send directly on c->fd */
  1607. if (c->reader_pid==my_pid()){
  1608. DBG("tcp_send: send from reader (%d (%d)), reusing fd\n",
  1609. my_pid(), process_no);
  1610. fd=c->fd;
  1611. do_close_fd=0; /* don't close the fd on exit, it's in use */
  1612. #ifdef TCP_FD_CACHE
  1613. use_fd_cache=0; /* don't cache: problems would arise due to the
  1614. close() on cache eviction (if the fd is still
  1615. used). If it has to be cached then dup() _must_
  1616. be used */
  1617. }else if (likely(use_fd_cache &&
  1618. ((fd_cache_e=tcp_fd_cache_get(c))!=0))){
  1619. fd=fd_cache_e->fd;
  1620. do_close_fd=0;
  1621. DBG("tcp_send: found fd in cache ( %d, %p, %d)\n",
  1622. fd, c, fd_cache_e->id);
  1623. #endif /* TCP_FD_CACHE */
  1624. }else{
  1625. DBG("tcp_send: tcp connection found (%p), acquiring fd\n", c);
  1626. /* get the fd */
  1627. response[0]=(long)c;
  1628. response[1]=CONN_GET_FD;
  1629. n=send_all(unix_tcp_sock, response, sizeof(response));
  1630. if (unlikely(n<=0)){
  1631. LOG(L_ERR, "BUG: tcp_send: failed to get fd(write):%s (%d)\n",
  1632. strerror(errno), errno);
  1633. n=-1;
  1634. goto release_c;
  1635. }
  1636. DBG("tcp_send, c= %p, n=%d\n", c, n);
  1637. n=receive_fd(unix_tcp_sock, &tmp, sizeof(tmp), &fd, MSG_WAITALL);
  1638. if (unlikely(n<=0)){
  1639. LOG(L_ERR, "BUG: tcp_send: failed to get fd(receive_fd):"
  1640. " %s (%d)\n", strerror(errno), errno);
  1641. n=-1;
  1642. do_close_fd=0;
  1643. goto release_c;
  1644. }
  1645. if (unlikely(c!=tmp)){
  1646. LOG(L_CRIT, "BUG: tcp_send: get_fd: got different connection:"
  1647. " %p (id= %d, refcnt=%d state=%d) != "
  1648. " %p (n=%d)\n",
  1649. c, c->id, atomic_get(&c->refcnt), c->state,
  1650. tmp, n
  1651. );
  1652. n=-1; /* fail */
  1653. goto end;
  1654. }
  1655. DBG("tcp_send: after receive_fd: c= %p n=%d fd=%d\n",c, n, fd);
  1656. }
  1657. send_it:
  1658. DBG("tcp_send: sending...\n");
  1659. lock_get(&c->write_lock);
  1660. #ifdef TCP_BUF_WRITE
  1661. if (likely(tcp_options.tcp_buf_write)){
  1662. if (_wbufq_non_empty(c)
  1663. #ifdef TCP_CONNECT_WAIT
  1664. || (c->state==S_CONN_PENDING)
  1665. #endif /* TCP_CONNECT_WAIT */
  1666. ){
  1667. if (unlikely(_wbufq_add(c, buf, len)<0)){
  1668. lock_release(&c->write_lock);
  1669. n=-1;
  1670. goto error;
  1671. }
  1672. lock_release(&c->write_lock);
  1673. n=len;
  1674. goto end;
  1675. }
  1676. n=_tcpconn_write_nb(fd, c, buf, len);
  1677. }else{
  1678. #endif /* TCP_BUF_WRITE */
  1679. #ifdef USE_TLS
  1680. if (c->type==PROTO_TLS)
  1681. n=tls_blocking_write(c, fd, buf, len);
  1682. else
  1683. #endif
  1684. /* n=tcp_blocking_write(c, fd, buf, len); */
  1685. n=tsend_stream(fd, buf, len, tcp_send_timeout*1000);
  1686. #ifdef TCP_BUF_WRITE
  1687. }
  1688. #else /* ! TCP_BUF_WRITE */
  1689. lock_release(&c->write_lock);
  1690. #endif /* TCP_BUF_WRITE */
  1691. DBG("tcp_send: after real write: c= %p n=%d fd=%d\n",c, n, fd);
  1692. DBG("tcp_send: buf=\n%.*s\n", (int)len, buf);
  1693. if (unlikely(n<(int)len)){
  1694. #ifdef TCP_BUF_WRITE
  1695. if (tcp_options.tcp_buf_write &&
  1696. ((n>=0) || errno==EAGAIN || errno==EWOULDBLOCK)){
  1697. enable_write_watch=_wbufq_empty(c);
  1698. if (n<0) n=0;
  1699. if (unlikely(_wbufq_add(c, buf+n, len-n)<0)){
  1700. lock_release(&c->write_lock);
  1701. n=-1;
  1702. goto error;
  1703. }
  1704. lock_release(&c->write_lock);
  1705. n=len;
  1706. if (likely(enable_write_watch)){
  1707. response[0]=(long)c;
  1708. response[1]=CONN_QUEUED_WRITE;
  1709. if (send_all(unix_tcp_sock, response, sizeof(response)) <= 0){
  1710. LOG(L_ERR, "BUG: tcp_send: error return failed "
  1711. "(write):%s (%d)\n", strerror(errno), errno);
  1712. n=-1;
  1713. goto error;
  1714. }
  1715. }
  1716. goto end;
  1717. }else{
  1718. lock_release(&c->write_lock);
  1719. }
  1720. #endif /* TCP_BUF_WRITE */
  1721. LOG(L_ERR, "ERROR: tcp_send: failed to send on %p (%s:%d->%s): %s (%d)"
  1722. "\n", c, ip_addr2a(&c->rcv.dst_ip), c->rcv.dst_port,
  1723. su2a(&c->rcv.src_su, sizeof(c->rcv.src_su)),
  1724. strerror(errno), errno);
  1725. #ifdef TCP_BUF_WRITE
  1726. error:
  1727. #endif /* TCP_BUF_WRITE */
  1728. /* error on the connection , mark it as bad and set 0 timeout */
  1729. c->state=S_CONN_BAD;
  1730. c->timeout=get_ticks_raw();
  1731. /* tell "main" it should drop this (optional it will t/o anyway?)*/
  1732. response[0]=(long)c;
  1733. response[1]=CONN_ERROR;
  1734. if (send_all(unix_tcp_sock, response, sizeof(response))<=0){
  1735. LOG(L_CRIT, "BUG: tcp_send: error return failed (write):%s (%d)\n",
  1736. strerror(errno), errno);
  1737. tcpconn_chld_put(c); /* deref. it manually */
  1738. n=-1;
  1739. }
  1740. /* CONN_ERROR will auto-dec refcnt => we must not call tcpconn_put
  1741. * if it succeeds */
  1742. #ifdef TCP_FD_CACHE
  1743. if (unlikely(fd_cache_e)){
  1744. LOG(L_ERR, "ERROR: tcp_send %s: error on cached fd, removing from"
  1745. " the cache (%d, %p, %d)\n",
  1746. su2a(&c->rcv.src_su, sizeof(c->rcv.src_su)),
  1747. fd, fd_cache_e->con, fd_cache_e->id);
  1748. tcp_fd_cache_rm(fd_cache_e);
  1749. close(fd);
  1750. }else
  1751. #endif /* TCP_FD_CACHE */
  1752. if (do_close_fd) close(fd);
  1753. return n; /* error return, no tcpconn_put */
  1754. }
  1755. #ifdef TCP_BUF_WRITE
  1756. lock_release(&c->write_lock);
  1757. if (likely(tcp_options.tcp_buf_write)){
  1758. if (unlikely(c->state==S_CONN_CONNECT))
  1759. c->state=S_CONN_OK;
  1760. }
  1761. #endif /* TCP_BUF_WRITE */
  1762. end:
  1763. #ifdef TCP_FD_CACHE
  1764. if (unlikely((fd_cache_e==0) && use_fd_cache)){
  1765. tcp_fd_cache_add(c, fd);
  1766. }else
  1767. #endif /* TCP_FD_CACHE */
  1768. if (do_close_fd) close(fd);
  1769. release_c:
  1770. tcpconn_chld_put(c); /* release c (dec refcnt & free on 0) */
  1771. end_no_conn:
  1772. return n;
  1773. #ifdef TCP_CONNECT_WAIT
  1774. conn_wait_error:
  1775. /* connect or send failed on newly created connection which was not
  1776. * yet sent to tcp_main (but was already hashed) => don't send to main,
  1777. * unhash and destroy directly (if refcnt>2 it will be destroyed when the
  1778. * last sender releases the connection (tcpconn_chld_put(c))) or when
  1779. * tcp_main receives a CONN_ERROR it*/
  1780. c->state=S_CONN_BAD;
  1781. TCPCONN_LOCK;
  1782. if (c->flags & F_CONN_HASHED){
  1783. /* if some other parallel tcp_send did send CONN_ERROR to
  1784. * tcp_main, the connection might be already detached */
  1785. _tcpconn_detach(c);
  1786. c->flags&=~F_CONN_HASHED;
  1787. TCPCONN_UNLOCK;
  1788. tcpconn_put(c);
  1789. }else
  1790. TCPCONN_UNLOCK;
  1791. /* dec refcnt -> mark it for destruction */
  1792. tcpconn_chld_put(c);
  1793. return -1;
  1794. #endif /* TCP_CONNET_WAIT */
  1795. }
  1796. int tcp_init(struct socket_info* sock_info)
  1797. {
  1798. union sockaddr_union* addr;
  1799. int optval;
  1800. #ifdef HAVE_TCP_ACCEPT_FILTER
  1801. struct accept_filter_arg afa;
  1802. #endif /* HAVE_TCP_ACCEPT_FILTER */
  1803. #ifdef DISABLE_NAGLE
  1804. int flag;
  1805. struct protoent* pe;
  1806. if (tcp_proto_no==-1){ /* if not already set */
  1807. pe=getprotobyname("tcp");
  1808. if (pe==0){
  1809. LOG(L_ERR, "ERROR: tcp_init: could not get TCP protocol number\n");
  1810. tcp_proto_no=-1;
  1811. }else{
  1812. tcp_proto_no=pe->p_proto;
  1813. }
  1814. }
  1815. #endif
  1816. addr=&sock_info->su;
  1817. /* sock_info->proto=PROTO_TCP; */
  1818. if (init_su(addr, &sock_info->address, sock_info->port_no)<0){
  1819. LOG(L_ERR, "ERROR: tcp_init: could no init sockaddr_union\n");
  1820. goto error;
  1821. }
  1822. DBG("tcp_init: added %s\n", su2a(addr, sizeof(*addr)));
  1823. sock_info->socket=socket(AF2PF(addr->s.sa_family), SOCK_STREAM, 0);
  1824. if (sock_info->socket==-1){
  1825. LOG(L_ERR, "ERROR: tcp_init: socket: %s\n", strerror(errno));
  1826. goto error;
  1827. }
  1828. #ifdef DISABLE_NAGLE
  1829. flag=1;
  1830. if ( (tcp_proto_no!=-1) &&
  1831. (setsockopt(sock_info->socket, tcp_proto_no , TCP_NODELAY,
  1832. &flag, sizeof(flag))<0) ){
  1833. LOG(L_ERR, "ERROR: tcp_init: could not disable Nagle: %s\n",
  1834. strerror(errno));
  1835. }
  1836. #endif
  1837. #if !defined(TCP_DONT_REUSEADDR)
  1838. /* Stevens, "Network Programming", Section 7.5, "Generic Socket
  1839. * Options": "...server started,..a child continues..on existing
  1840. * connection..listening server is restarted...call to bind fails
  1841. * ... ALL TCP servers should specify the SO_REUSEADDRE option
  1842. * to allow the server to be restarted in this situation
  1843. *
  1844. * Indeed, without this option, the server can't restart.
  1845. * -jiri
  1846. */
  1847. optval=1;
  1848. if (setsockopt(sock_info->socket, SOL_SOCKET, SO_REUSEADDR,
  1849. (void*)&optval, sizeof(optval))==-1) {
  1850. LOG(L_ERR, "ERROR: tcp_init: setsockopt %s\n",
  1851. strerror(errno));
  1852. goto error;
  1853. }
  1854. #endif
  1855. /* tos */
  1856. optval = tos;
  1857. if (setsockopt(sock_info->socket, IPPROTO_IP, IP_TOS, (void*)&optval,
  1858. sizeof(optval)) ==-1){
  1859. LOG(L_WARN, "WARNING: tcp_init: setsockopt tos: %s\n", strerror(errno));
  1860. /* continue since this is not critical */
  1861. }
  1862. #ifdef HAVE_TCP_DEFER_ACCEPT
  1863. /* linux only */
  1864. if (tcp_options.defer_accept){
  1865. optval=tcp_options.defer_accept;
  1866. if (setsockopt(sock_info->socket, IPPROTO_TCP, TCP_DEFER_ACCEPT,
  1867. (void*)&optval, sizeof(optval)) ==-1){
  1868. LOG(L_WARN, "WARNING: tcp_init: setsockopt TCP_DEFER_ACCEPT %s\n",
  1869. strerror(errno));
  1870. /* continue since this is not critical */
  1871. }
  1872. }
  1873. #endif /* HAVE_TCP_DEFFER_ACCEPT */
  1874. #ifdef HAVE_TCP_SYNCNT
  1875. if (tcp_options.syncnt){
  1876. optval=tcp_options.syncnt;
  1877. if (setsockopt(sock_info->socket, IPPROTO_TCP, TCP_SYNCNT, &optval,
  1878. sizeof(optval))<0){
  1879. LOG(L_WARN, "WARNING: tcp_init: failed to set"
  1880. " maximum SYN retr. count: %s\n", strerror(errno));
  1881. }
  1882. }
  1883. #endif
  1884. #ifdef HAVE_TCP_LINGER2
  1885. if (tcp_options.linger2){
  1886. optval=tcp_options.linger2;
  1887. if (setsockopt(sock_info->socket, IPPROTO_TCP, TCP_LINGER2, &optval,
  1888. sizeof(optval))<0){
  1889. LOG(L_WARN, "WARNING: tcp_init: failed to set"
  1890. " maximum LINGER2 timeout: %s\n", strerror(errno));
  1891. }
  1892. }
  1893. #endif
  1894. init_sock_keepalive(sock_info->socket);
  1895. if (bind(sock_info->socket, &addr->s, sockaddru_len(*addr))==-1){
  1896. LOG(L_ERR, "ERROR: tcp_init: bind(%x, %p, %d) on %s:%d : %s\n",
  1897. sock_info->socket, &addr->s,
  1898. (unsigned)sockaddru_len(*addr),
  1899. sock_info->address_str.s,
  1900. sock_info->port_no,
  1901. strerror(errno));
  1902. goto error;
  1903. }
  1904. if (listen(sock_info->socket, TCP_LISTEN_BACKLOG)==-1){
  1905. LOG(L_ERR, "ERROR: tcp_init: listen(%x, %p, %d) on %s: %s\n",
  1906. sock_info->socket, &addr->s,
  1907. (unsigned)sockaddru_len(*addr),
  1908. sock_info->address_str.s,
  1909. strerror(errno));
  1910. goto error;
  1911. }
  1912. #ifdef HAVE_TCP_ACCEPT_FILTER
  1913. /* freebsd */
  1914. if (tcp_options.defer_accept){
  1915. memset(&afa, 0, sizeof(afa));
  1916. strcpy(afa.af_name, "dataready");
  1917. if (setsockopt(sock_info->socket, SOL_SOCKET, SO_ACCEPTFILTER,
  1918. (void*)&afa, sizeof(afa)) ==-1){
  1919. LOG(L_WARN, "WARNING: tcp_init: setsockopt SO_ACCEPTFILTER %s\n",
  1920. strerror(errno));
  1921. /* continue since this is not critical */
  1922. }
  1923. }
  1924. #endif /* HAVE_TCP_ACCEPT_FILTER */
  1925. return 0;
  1926. error:
  1927. if (sock_info->socket!=-1){
  1928. close(sock_info->socket);
  1929. sock_info->socket=-1;
  1930. }
  1931. return -1;
  1932. }
  1933. /* close tcp_main's fd from a tcpconn
  1934. * WARNING: call only in tcp_main context */
  1935. inline static void tcpconn_close_main_fd(struct tcp_connection* tcpconn)
  1936. {
  1937. int fd;
  1938. fd=tcpconn->s;
  1939. #ifdef USE_TLS
  1940. /*FIXME: lock ->writelock ? */
  1941. if (tcpconn->type==PROTO_TLS)
  1942. tls_close(tcpconn, fd);
  1943. #endif
  1944. #ifdef TCP_FD_CACHE
  1945. if (likely(tcp_options.fd_cache)) shutdown(fd, SHUT_RDWR);
  1946. #endif /* TCP_FD_CACHE */
  1947. close_again:
  1948. if (unlikely(close(fd)<0)){
  1949. if (errno==EINTR)
  1950. goto close_again;
  1951. LOG(L_ERR, "ERROR: tcpconn_put_destroy; close() failed: %s (%d)\n",
  1952. strerror(errno), errno);
  1953. }
  1954. }
  1955. /* dec refcnt & frees the connection if refcnt==0
  1956. * returns 1 if the connection is freed, 0 otherwise
  1957. *
  1958. * WARNING: use only from child processes */
  1959. inline static int tcpconn_chld_put(struct tcp_connection* tcpconn)
  1960. {
  1961. if (unlikely(atomic_dec_and_test(&tcpconn->refcnt))){
  1962. DBG("tcpconn_chld_put: destroying connection %p (%d, %d) "
  1963. "flags %04x\n", tcpconn, tcpconn->id,
  1964. tcpconn->s, tcpconn->flags);
  1965. /* sanity checks */
  1966. membar_read_atomic_op(); /* make sure we see the current flags */
  1967. if (unlikely(!(tcpconn->flags & F_CONN_FD_CLOSED) ||
  1968. (tcpconn->flags &
  1969. (F_CONN_HASHED|F_CONN_MAIN_TIMER|F_CONN_READ_W|F_CONN_WRITE_W)) )){
  1970. LOG(L_CRIT, "BUG: tcpconn_chld_put: %p bad flags = %0x\n",
  1971. tcpconn, tcpconn->flags);
  1972. abort();
  1973. }
  1974. _tcpconn_free(tcpconn); /* destroys also the wbuf_q if still present*/
  1975. return 1;
  1976. }
  1977. return 0;
  1978. }
  1979. /* simple destroy function (the connection should be already removed
  1980. * from the hashes and the fds should not be watched anymore for IO)
  1981. */
  1982. inline static void tcpconn_destroy(struct tcp_connection* tcpconn)
  1983. {
  1984. DBG("tcpconn_destroy: destroying connection %p (%d, %d) "
  1985. "flags %04x\n", tcpconn, tcpconn->id,
  1986. tcpconn->s, tcpconn->flags);
  1987. if (unlikely(tcpconn->flags & F_CONN_HASHED)){
  1988. LOG(L_CRIT, "BUG: tcpconn_destroy: called with hashed"
  1989. " connection (%p)\n", tcpconn);
  1990. /* try to continue */
  1991. if (likely(tcpconn->flags & F_CONN_MAIN_TIMER))
  1992. local_timer_del(&tcp_main_ltimer, &tcpconn->timer);
  1993. TCPCONN_LOCK;
  1994. _tcpconn_detach(tcpconn);
  1995. TCPCONN_UNLOCK;
  1996. }
  1997. if (likely(!(tcpconn->flags & F_CONN_FD_CLOSED))){
  1998. tcpconn_close_main_fd(tcpconn);
  1999. (*tcp_connections_no)--;
  2000. }
  2001. _tcpconn_free(tcpconn); /* destroys also the wbuf_q if still present*/
  2002. }
  2003. /* tries to destroy the connection: dec. refcnt and if 0 destroys the
  2004. * connection, else it will mark it as BAD and close the main fds
  2005. *
  2006. * returns 1 if the connection was destroyed, 0 otherwise
  2007. *
  2008. * WARNING: - the connection _has_ to be removed from the hash and timer
  2009. * first (use tcpconn_try_unhash() for this )
  2010. * - the fd should not be watched anymore (io_watch_del()...)
  2011. * - must be called _only_ from the tcp_main process context
  2012. * (or else the fd will remain open)
  2013. */
  2014. inline static int tcpconn_put_destroy(struct tcp_connection* tcpconn)
  2015. {
  2016. if (unlikely((tcpconn->flags &
  2017. (F_CONN_WRITE_W|F_CONN_HASHED|F_CONN_MAIN_TIMER|F_CONN_READ_W)) )){
  2018. /* sanity check */
  2019. if (unlikely(tcpconn->flags & F_CONN_HASHED)){
  2020. LOG(L_CRIT, "BUG: tcpconn_destroy: called with hashed and/or"
  2021. "on timer connection (%p), flags = %0x\n",
  2022. tcpconn, tcpconn->flags);
  2023. /* try to continue */
  2024. if (likely(tcpconn->flags & F_CONN_MAIN_TIMER))
  2025. local_timer_del(&tcp_main_ltimer, &tcpconn->timer);
  2026. TCPCONN_LOCK;
  2027. _tcpconn_detach(tcpconn);
  2028. TCPCONN_UNLOCK;
  2029. }else{
  2030. LOG(L_CRIT, "BUG: tcpconn_put_destroy: %p flags = %0x\n",
  2031. tcpconn, tcpconn->flags);
  2032. }
  2033. }
  2034. tcpconn->state=S_CONN_BAD;
  2035. /* in case it's still in a reader timer */
  2036. tcpconn->timeout=get_ticks_raw();
  2037. /* fast close: close fds now */
  2038. if (likely(!(tcpconn->flags & F_CONN_FD_CLOSED))){
  2039. tcpconn_close_main_fd(tcpconn);
  2040. tcpconn->flags|=F_CONN_FD_CLOSED;
  2041. (*tcp_connections_no)--;
  2042. }
  2043. /* all the flags / ops on the tcpconn must be done prior to decrementing
  2044. * the refcnt. and at least a membar_write_atomic_op() mem. barrier or
  2045. * a mb_atomic_* op must * be used to make sure all the changed flags are
  2046. * written into memory prior to the new refcnt value */
  2047. if (unlikely(mb_atomic_dec_and_test(&tcpconn->refcnt))){
  2048. _tcpconn_free(tcpconn);
  2049. return 1;
  2050. }
  2051. return 0;
  2052. }
  2053. /* try to remove a connection from the hashes and timer.
  2054. * returns 1 if the connection was removed, 0 if not (connection not in
  2055. * hash)
  2056. *
  2057. * WARNING: call it only in the tcp_main process context or else the
  2058. * timer removal won't work.
  2059. */
  2060. inline static int tcpconn_try_unhash(struct tcp_connection* tcpconn)
  2061. {
  2062. if (likely(tcpconn->flags & F_CONN_HASHED)){
  2063. tcpconn->state=S_CONN_BAD;
  2064. if (likely(tcpconn->flags & F_CONN_MAIN_TIMER)){
  2065. local_timer_del(&tcp_main_ltimer, &tcpconn->timer);
  2066. tcpconn->flags&=~F_CONN_MAIN_TIMER;
  2067. }else
  2068. /* in case it's still in a reader timer */
  2069. tcpconn->timeout=get_ticks_raw();
  2070. TCPCONN_LOCK;
  2071. if (tcpconn->flags & F_CONN_HASHED){
  2072. tcpconn->flags&=~F_CONN_HASHED;
  2073. _tcpconn_detach(tcpconn);
  2074. TCPCONN_UNLOCK;
  2075. }else{
  2076. /* tcp_send was faster and did unhash it itself */
  2077. TCPCONN_UNLOCK;
  2078. return 0;
  2079. }
  2080. #ifdef TCP_BUF_WRITE
  2081. /* empty possible write buffers (optional) */
  2082. if (unlikely(_wbufq_non_empty(tcpconn))){
  2083. lock_get(&tcpconn->write_lock);
  2084. /* check again, while holding the lock */
  2085. if (likely(_wbufq_non_empty(tcpconn)))
  2086. _wbufq_destroy(&tcpconn->wbuf_q);
  2087. lock_release(&tcpconn->write_lock);
  2088. }
  2089. #endif /* TCP_BUF_WRITE */
  2090. return 1;
  2091. }
  2092. return 0;
  2093. }
  2094. #ifdef SEND_FD_QUEUE
  2095. struct send_fd_info{
  2096. struct tcp_connection* tcp_conn;
  2097. ticks_t expire;
  2098. int unix_sock;
  2099. unsigned int retries; /* debugging */
  2100. };
  2101. struct tcp_send_fd_q{
  2102. struct send_fd_info* data; /* buffer */
  2103. struct send_fd_info* crt; /* pointer inside the buffer */
  2104. struct send_fd_info* end; /* points after the last valid position */
  2105. };
  2106. static struct tcp_send_fd_q send2child_q;
  2107. static int send_fd_queue_init(struct tcp_send_fd_q *q, unsigned int size)
  2108. {
  2109. q->data=pkg_malloc(size*sizeof(struct send_fd_info));
  2110. if (q->data==0){
  2111. LOG(L_ERR, "ERROR: send_fd_queue_init: out of memory\n");
  2112. return -1;
  2113. }
  2114. q->crt=&q->data[0];
  2115. q->end=&q->data[size];
  2116. return 0;
  2117. }
  2118. static void send_fd_queue_destroy(struct tcp_send_fd_q *q)
  2119. {
  2120. if (q->data){
  2121. pkg_free(q->data);
  2122. q->data=0;
  2123. q->crt=q->end=0;
  2124. }
  2125. }
  2126. static int init_send_fd_queues()
  2127. {
  2128. if (send_fd_queue_init(&send2child_q, SEND_FD_QUEUE_SIZE)!=0)
  2129. goto error;
  2130. return 0;
  2131. error:
  2132. LOG(L_ERR, "ERROR: init_send_fd_queues: init failed\n");
  2133. return -1;
  2134. }
  2135. static void destroy_send_fd_queues()
  2136. {
  2137. send_fd_queue_destroy(&send2child_q);
  2138. }
  2139. inline static int send_fd_queue_add( struct tcp_send_fd_q* q,
  2140. int unix_sock,
  2141. struct tcp_connection *t)
  2142. {
  2143. struct send_fd_info* tmp;
  2144. unsigned long new_size;
  2145. if (q->crt>=q->end){
  2146. new_size=q->end-&q->data[0];
  2147. if (new_size< MAX_SEND_FD_QUEUE_SIZE/2){
  2148. new_size*=2;
  2149. }else new_size=MAX_SEND_FD_QUEUE_SIZE;
  2150. if (unlikely(q->crt>=&q->data[new_size])){
  2151. LOG(L_ERR, "ERROR: send_fd_queue_add: queue full: %ld/%ld\n",
  2152. (long)(q->crt-&q->data[0]-1), new_size);
  2153. goto error;
  2154. }
  2155. LOG(L_CRIT, "INFO: send_fd_queue: queue full: %ld, extending to %ld\n",
  2156. (long)(q->end-&q->data[0]), new_size);
  2157. tmp=pkg_realloc(q->data, new_size*sizeof(struct send_fd_info));
  2158. if (unlikely(tmp==0)){
  2159. LOG(L_ERR, "ERROR: send_fd_queue_add: out of memory\n");
  2160. goto error;
  2161. }
  2162. q->crt=(q->crt-&q->data[0])+tmp;
  2163. q->data=tmp;
  2164. q->end=&q->data[new_size];
  2165. }
  2166. q->crt->tcp_conn=t;
  2167. q->crt->unix_sock=unix_sock;
  2168. q->crt->expire=get_ticks_raw()+SEND_FD_QUEUE_TIMEOUT;
  2169. q->crt->retries=0;
  2170. q->crt++;
  2171. return 0;
  2172. error:
  2173. return -1;
  2174. }
  2175. inline static void send_fd_queue_run(struct tcp_send_fd_q* q)
  2176. {
  2177. struct send_fd_info* p;
  2178. struct send_fd_info* t;
  2179. for (p=t=&q->data[0]; p<q->crt; p++){
  2180. if (unlikely(send_fd(p->unix_sock, &(p->tcp_conn),
  2181. sizeof(struct tcp_connection*), p->tcp_conn->s)<=0)){
  2182. if ( ((errno==EAGAIN)||(errno==EWOULDBLOCK)) &&
  2183. ((s_ticks_t)(p->expire-get_ticks_raw())>0)){
  2184. /* leave in queue for a future try */
  2185. *t=*p;
  2186. t->retries++;
  2187. t++;
  2188. }else{
  2189. LOG(L_ERR, "ERROR: run_send_fd_queue: send_fd failed"
  2190. " on socket %d , queue entry %ld, retries %d,"
  2191. " connection %p, tcp socket %d, errno=%d (%s) \n",
  2192. p->unix_sock, (long)(p-&q->data[0]), p->retries,
  2193. p->tcp_conn, p->tcp_conn->s, errno,
  2194. strerror(errno));
  2195. #ifdef TCP_BUF_WRITE
  2196. if (p->tcp_conn->flags & F_CONN_WRITE_W){
  2197. io_watch_del(&io_h, p->tcp_conn->s, -1, IO_FD_CLOSING);
  2198. p->tcp_conn->flags &=~F_CONN_WRITE_W;
  2199. }
  2200. #endif
  2201. p->tcp_conn->flags &= ~F_CONN_READER;
  2202. if (likely(tcpconn_try_unhash(p->tcp_conn)))
  2203. tcpconn_put(p->tcp_conn);
  2204. tcpconn_put_destroy(p->tcp_conn); /* dec refcnt & destroy */
  2205. }
  2206. }
  2207. }
  2208. q->crt=t;
  2209. }
  2210. #else
  2211. #define send_fd_queue_run(q)
  2212. #endif
  2213. /* non blocking write() on a tcpconnection, unsafe version (should be called
  2214. * while holding c->write_lock). The fd should be non-blocking.
  2215. * returns number of bytes written on success, -1 on error (and sets errno)
  2216. */
  2217. inline static int _tcpconn_write_nb(int fd, struct tcp_connection* c,
  2218. char* buf, int len)
  2219. {
  2220. int n;
  2221. again:
  2222. #ifdef USE_TLS
  2223. if (unlikely(c->type==PROTO_TLS))
  2224. /* FIXME: tls_nonblocking_write !! */
  2225. n=tls_blocking_write(c, fd, buf, len);
  2226. else
  2227. #endif /* USE_TLS */
  2228. n=send(fd, buf, len,
  2229. #ifdef HAVE_MSG_NOSIGNAL
  2230. MSG_NOSIGNAL
  2231. #else
  2232. 0
  2233. #endif /* HAVE_MSG_NOSIGNAL */
  2234. );
  2235. if (unlikely(n<0)){
  2236. if (errno==EINTR) goto again;
  2237. }
  2238. return n;
  2239. }
  2240. /* handles io from a tcp child process
  2241. * params: tcp_c - pointer in the tcp_children array, to the entry for
  2242. * which an io event was detected
  2243. * fd_i - fd index in the fd_array (usefull for optimizing
  2244. * io_watch_deletes)
  2245. * returns: handle_* return convention: -1 on error, 0 on EAGAIN (no more
  2246. * io events queued), >0 on success. success/error refer only to
  2247. * the reads from the fd.
  2248. */
  2249. inline static int handle_tcp_child(struct tcp_child* tcp_c, int fd_i)
  2250. {
  2251. struct tcp_connection* tcpconn;
  2252. long response[2];
  2253. int cmd;
  2254. int bytes;
  2255. int n;
  2256. ticks_t t;
  2257. ticks_t crt_timeout;
  2258. if (unlikely(tcp_c->unix_sock<=0)){
  2259. /* (we can't have a fd==0, 0 is never closed )*/
  2260. LOG(L_CRIT, "BUG: handle_tcp_child: fd %d for %d "
  2261. "(pid %d, ser no %d)\n", tcp_c->unix_sock,
  2262. (int)(tcp_c-&tcp_children[0]), tcp_c->pid, tcp_c->proc_no);
  2263. goto error;
  2264. }
  2265. /* read until sizeof(response)
  2266. * (this is a SOCK_STREAM so read is not atomic) */
  2267. bytes=recv_all(tcp_c->unix_sock, response, sizeof(response), MSG_DONTWAIT);
  2268. if (unlikely(bytes<(int)sizeof(response))){
  2269. if (bytes==0){
  2270. /* EOF -> bad, child has died */
  2271. DBG("DBG: handle_tcp_child: dead tcp child %d (pid %d, no %d)"
  2272. " (shutting down?)\n", (int)(tcp_c-&tcp_children[0]),
  2273. tcp_c->pid, tcp_c->proc_no );
  2274. /* don't listen on it any more */
  2275. io_watch_del(&io_h, tcp_c->unix_sock, fd_i, 0);
  2276. goto error; /* eof. so no more io here, it's ok to return error */
  2277. }else if (bytes<0){
  2278. /* EAGAIN is ok if we try to empty the buffer
  2279. * e.g.: SIGIO_RT overflow mode or EPOLL ET */
  2280. if ((errno!=EAGAIN) && (errno!=EWOULDBLOCK)){
  2281. LOG(L_CRIT, "ERROR: handle_tcp_child: read from tcp child %ld "
  2282. " (pid %d, no %d) %s [%d]\n",
  2283. (long)(tcp_c-&tcp_children[0]), tcp_c->pid,
  2284. tcp_c->proc_no, strerror(errno), errno );
  2285. }else{
  2286. bytes=0;
  2287. }
  2288. /* try to ignore ? */
  2289. goto end;
  2290. }else{
  2291. /* should never happen */
  2292. LOG(L_CRIT, "BUG: handle_tcp_child: too few bytes received (%d)\n",
  2293. bytes );
  2294. bytes=0; /* something was read so there is no error; otoh if
  2295. receive_fd returned less then requested => the receive
  2296. buffer is empty => no more io queued on this fd */
  2297. goto end;
  2298. }
  2299. }
  2300. DBG("handle_tcp_child: reader response= %lx, %ld from %d \n",
  2301. response[0], response[1], (int)(tcp_c-&tcp_children[0]));
  2302. cmd=response[1];
  2303. tcpconn=(struct tcp_connection*)response[0];
  2304. if (unlikely(tcpconn==0)){
  2305. /* should never happen */
  2306. LOG(L_CRIT, "BUG: handle_tcp_child: null tcpconn pointer received"
  2307. " from tcp child %d (pid %d): %lx, %lx\n",
  2308. (int)(tcp_c-&tcp_children[0]), tcp_c->pid,
  2309. response[0], response[1]) ;
  2310. goto end;
  2311. }
  2312. switch(cmd){
  2313. case CONN_RELEASE:
  2314. tcp_c->busy--;
  2315. if (unlikely(tcpconn_put(tcpconn))){
  2316. tcpconn_destroy(tcpconn);
  2317. break;
  2318. }
  2319. if (unlikely(tcpconn->state==S_CONN_BAD)){
  2320. #ifdef TCP_BUF_WRITE
  2321. if (unlikely(tcpconn->flags & F_CONN_WRITE_W)){
  2322. io_watch_del(&io_h, tcpconn->s, -1, IO_FD_CLOSING);
  2323. tcpconn->flags &= ~F_CONN_WRITE_W;
  2324. }
  2325. #endif /* TCP_BUF_WRITE */
  2326. if (tcpconn_try_unhash(tcpconn))
  2327. tcpconn_put_destroy(tcpconn);
  2328. break;
  2329. }
  2330. /* update the timeout*/
  2331. t=get_ticks_raw();
  2332. tcpconn->timeout=t+tcp_con_lifetime;
  2333. crt_timeout=tcp_con_lifetime;
  2334. #ifdef TCP_BUF_WRITE
  2335. if (unlikely(tcp_options.tcp_buf_write &&
  2336. _wbufq_non_empty(tcpconn) )){
  2337. if (unlikely(TICKS_LE(t, tcpconn->wbuf_q.wr_timeout))){
  2338. DBG("handle_tcp_child: wr. timeout on CONN_RELEASE for %p "
  2339. "refcnt= %d\n", tcpconn,
  2340. atomic_get(&tcpconn->refcnt));
  2341. /* timeout */
  2342. if (unlikely(tcpconn->flags & F_CONN_WRITE_W)){
  2343. io_watch_del(&io_h, tcpconn->s, -1, IO_FD_CLOSING);
  2344. tcpconn->flags&=~F_CONN_WRITE_W;
  2345. }
  2346. if (tcpconn_try_unhash(tcpconn))
  2347. tcpconn_put_destroy(tcpconn);
  2348. break;
  2349. }else{
  2350. crt_timeout=MIN_unsigned(tcp_con_lifetime,
  2351. tcpconn->wbuf_q.wr_timeout-t);
  2352. }
  2353. }
  2354. #endif /* TCP_BUF_WRITE */
  2355. /* re-activate the timer */
  2356. tcpconn->timer.f=tcpconn_main_timeout;
  2357. local_timer_reinit(&tcpconn->timer);
  2358. local_timer_add(&tcp_main_ltimer, &tcpconn->timer, crt_timeout, t);
  2359. /* must be after the de-ref*/
  2360. tcpconn->flags|=(F_CONN_MAIN_TIMER|F_CONN_READ_W|F_CONN_WANTS_RD);
  2361. tcpconn->flags&=~(F_CONN_READER|F_CONN_OOB_DATA);
  2362. #ifdef TCP_BUF_WRITE
  2363. if (unlikely(tcpconn->flags & F_CONN_WRITE_W))
  2364. n=io_watch_chg(&io_h, tcpconn->s, POLLIN| POLLOUT, -1);
  2365. else
  2366. #endif /* TCP_BUF_WRITE */
  2367. n=io_watch_add(&io_h, tcpconn->s, POLLIN, F_TCPCONN, tcpconn);
  2368. if (unlikely(n<0)){
  2369. LOG(L_CRIT, "ERROR: tcp_main: handle_tcp_child: failed to add"
  2370. " new socket to the fd list\n");
  2371. tcpconn->flags&=~F_CONN_READ_W;
  2372. #ifdef TCP_BUF_WRITE
  2373. if (unlikely(tcpconn->flags & F_CONN_WRITE_W)){
  2374. io_watch_del(&io_h, tcpconn->s, -1, IO_FD_CLOSING);
  2375. tcpconn->flags&=~F_CONN_WRITE_W;
  2376. }
  2377. #endif /* TCP_BUF_WRITE */
  2378. if (tcpconn_try_unhash(tcpconn));
  2379. tcpconn_put_destroy(tcpconn);
  2380. break;
  2381. }
  2382. DBG("handle_tcp_child: CONN_RELEASE %p refcnt= %d\n",
  2383. tcpconn, atomic_get(&tcpconn->refcnt));
  2384. break;
  2385. case CONN_ERROR:
  2386. case CONN_DESTROY:
  2387. case CONN_EOF:
  2388. /* WARNING: this will auto-dec. refcnt! */
  2389. tcp_c->busy--;
  2390. /* main doesn't listen on it => we don't have to delete it
  2391. if (tcpconn->s!=-1)
  2392. io_watch_del(&io_h, tcpconn->s, -1, IO_FD_CLOSING);
  2393. */
  2394. #ifdef TCP_BUF_WRITE
  2395. if ((tcpconn->flags & F_CONN_WRITE_W) && (tcpconn->s!=-1)){
  2396. io_watch_del(&io_h, tcpconn->s, -1, IO_FD_CLOSING);
  2397. tcpconn->flags&=~F_CONN_WRITE_W;
  2398. }
  2399. #endif /* TCP_BUF_WRITE */
  2400. if (tcpconn_try_unhash(tcpconn))
  2401. tcpconn_put(tcpconn);
  2402. tcpconn_put_destroy(tcpconn); /* deref & delete if refcnt==0 */
  2403. break;
  2404. default:
  2405. LOG(L_CRIT, "BUG: handle_tcp_child: unknown cmd %d"
  2406. " from tcp reader %d\n",
  2407. cmd, (int)(tcp_c-&tcp_children[0]));
  2408. }
  2409. end:
  2410. return bytes;
  2411. error:
  2412. return -1;
  2413. }
  2414. /* handles io from a "generic" ser process (get fd or new_fd from a tcp_send)
  2415. *
  2416. * params: p - pointer in the ser processes array (pt[]), to the entry for
  2417. * which an io event was detected
  2418. * fd_i - fd index in the fd_array (usefull for optimizing
  2419. * io_watch_deletes)
  2420. * returns: handle_* return convention:
  2421. * -1 on error reading from the fd,
  2422. * 0 on EAGAIN or when no more io events are queued
  2423. * (receive buffer empty),
  2424. * >0 on successfull reads from the fd (the receive buffer might
  2425. * be non-empty).
  2426. */
  2427. inline static int handle_ser_child(struct process_table* p, int fd_i)
  2428. {
  2429. struct tcp_connection* tcpconn;
  2430. long response[2];
  2431. int cmd;
  2432. int bytes;
  2433. int ret;
  2434. int fd;
  2435. int flags;
  2436. ticks_t t;
  2437. ret=-1;
  2438. if (unlikely(p->unix_sock<=0)){
  2439. /* (we can't have a fd==0, 0 is never closed )*/
  2440. LOG(L_CRIT, "BUG: handle_ser_child: fd %d for %d "
  2441. "(pid %d)\n", p->unix_sock, (int)(p-&pt[0]), p->pid);
  2442. goto error;
  2443. }
  2444. /* get all bytes and the fd (if transmitted)
  2445. * (this is a SOCK_STREAM so read is not atomic) */
  2446. bytes=receive_fd(p->unix_sock, response, sizeof(response), &fd,
  2447. MSG_DONTWAIT);
  2448. if (unlikely(bytes<(int)sizeof(response))){
  2449. /* too few bytes read */
  2450. if (bytes==0){
  2451. /* EOF -> bad, child has died */
  2452. DBG("DBG: handle_ser_child: dead child %d, pid %d"
  2453. " (shutting down?)\n", (int)(p-&pt[0]), p->pid);
  2454. /* don't listen on it any more */
  2455. io_watch_del(&io_h, p->unix_sock, fd_i, 0);
  2456. goto error; /* child dead => no further io events from it */
  2457. }else if (bytes<0){
  2458. /* EAGAIN is ok if we try to empty the buffer
  2459. * e.g: SIGIO_RT overflow mode or EPOLL ET */
  2460. if ((errno!=EAGAIN) && (errno!=EWOULDBLOCK)){
  2461. LOG(L_CRIT, "ERROR: handle_ser_child: read from child %d "
  2462. "(pid %d): %s [%d]\n", (int)(p-&pt[0]), p->pid,
  2463. strerror(errno), errno);
  2464. ret=-1;
  2465. }else{
  2466. ret=0;
  2467. }
  2468. /* try to ignore ? */
  2469. goto end;
  2470. }else{
  2471. /* should never happen */
  2472. LOG(L_CRIT, "BUG: handle_ser_child: too few bytes received (%d)\n",
  2473. bytes );
  2474. ret=0; /* something was read so there is no error; otoh if
  2475. receive_fd returned less then requested => the receive
  2476. buffer is empty => no more io queued on this fd */
  2477. goto end;
  2478. }
  2479. }
  2480. ret=1; /* something was received, there might be more queued */
  2481. DBG("handle_ser_child: read response= %lx, %ld, fd %d from %d (%d)\n",
  2482. response[0], response[1], fd, (int)(p-&pt[0]), p->pid);
  2483. cmd=response[1];
  2484. tcpconn=(struct tcp_connection*)response[0];
  2485. if (unlikely(tcpconn==0)){
  2486. LOG(L_CRIT, "BUG: handle_ser_child: null tcpconn pointer received"
  2487. " from child %d (pid %d): %lx, %lx\n",
  2488. (int)(p-&pt[0]), p->pid, response[0], response[1]) ;
  2489. goto end;
  2490. }
  2491. switch(cmd){
  2492. case CONN_ERROR:
  2493. LOG(L_ERR, "handle_ser_child: ERROR: received CON_ERROR for %p"
  2494. " (id %d), refcnt %d\n",
  2495. tcpconn, tcpconn->id, atomic_get(&tcpconn->refcnt));
  2496. #ifdef TCP_CONNECT_WAIT
  2497. /* if the connection is pending => it might be on the way of
  2498. * reaching tcp_main (e.g. CONN_NEW_COMPLETE or
  2499. * CONN_NEW_PENDING_WRITE) => it cannot be destroyed here */
  2500. if ( !(tcpconn->flags & F_CONN_PENDING) &&
  2501. tcpconn_try_unhash(tcpconn) )
  2502. tcpconn_put(tcpconn);
  2503. #else /* ! TCP_CONNECT_WAIT */
  2504. if ( tcpconn_try_unhash(tcpconn) )
  2505. tcpconn_put(tcpconn);
  2506. #endif /* TCP_CONNECT_WAIT */
  2507. if ( ((tcpconn->flags & (F_CONN_WRITE_W|F_CONN_READ_W)) ) &&
  2508. (tcpconn->s!=-1)){
  2509. io_watch_del(&io_h, tcpconn->s, -1, IO_FD_CLOSING);
  2510. tcpconn->flags&=~(F_CONN_WRITE_W|F_CONN_READ_W);
  2511. }
  2512. tcpconn_put_destroy(tcpconn); /* dec refcnt & destroy on 0 */
  2513. break;
  2514. case CONN_GET_FD:
  2515. /* send the requested FD */
  2516. /* WARNING: take care of setting refcnt properly to
  2517. * avoid race conditions */
  2518. if (unlikely(send_fd(p->unix_sock, &tcpconn, sizeof(tcpconn),
  2519. tcpconn->s)<=0)){
  2520. LOG(L_ERR, "ERROR: handle_ser_child: send_fd failed\n");
  2521. }
  2522. break;
  2523. case CONN_NEW:
  2524. /* update the fd in the requested tcpconn*/
  2525. /* WARNING: take care of setting refcnt properly to
  2526. * avoid race conditions */
  2527. if (unlikely(fd==-1)){
  2528. LOG(L_CRIT, "BUG: handle_ser_child: CONN_NEW:"
  2529. " no fd received\n");
  2530. tcpconn->flags|=F_CONN_FD_CLOSED;
  2531. tcpconn_put_destroy(tcpconn);
  2532. break;
  2533. }
  2534. (*tcp_connections_no)++;
  2535. tcpconn->s=fd;
  2536. /* add tcpconn to the list*/
  2537. tcpconn_add(tcpconn);
  2538. /* update the timeout*/
  2539. t=get_ticks_raw();
  2540. tcpconn->timeout=t+tcp_con_lifetime;
  2541. /* activate the timer (already properly init. in tcpconn_new())
  2542. * no need for reinit */
  2543. local_timer_add(&tcp_main_ltimer, &tcpconn->timer,
  2544. tcp_con_lifetime, t);
  2545. tcpconn->flags|=(F_CONN_MAIN_TIMER|F_CONN_READ_W|F_CONN_WANTS_RD)
  2546. #ifdef TCP_BUF_WRITE
  2547. /* not used for now, the connection is sent to tcp_main
  2548. * before knowing whether we can write on it or we should
  2549. * wait */
  2550. | (((int)!(tcpconn->flags & F_CONN_WANTS_WR)-1)&
  2551. F_CONN_WRITE_W)
  2552. #endif /* TCP_BUF_WRITE */
  2553. ;
  2554. tcpconn->flags&=~F_CONN_FD_CLOSED;
  2555. flags=POLLIN
  2556. #ifdef TCP_BUF_WRITE
  2557. /* not used for now, the connection is sent to tcp_main
  2558. * before knowing if we can write on it or we should
  2559. * wait */
  2560. | (((int)!(tcpconn->flags & F_CONN_WANTS_WR)-1) & POLLOUT)
  2561. #endif /* TCP_BUF_WRITE */
  2562. ;
  2563. if (unlikely(
  2564. io_watch_add(&io_h, tcpconn->s, flags,
  2565. F_TCPCONN, tcpconn)<0)){
  2566. LOG(L_CRIT, "ERROR: tcp_main: handle_ser_child: failed to add"
  2567. " new socket to the fd list\n");
  2568. tcpconn->flags&=~(F_CONN_WRITE_W|F_CONN_READ_W);
  2569. tcpconn_try_unhash(tcpconn); /* unhash & dec refcnt */
  2570. tcpconn_put_destroy(tcpconn);
  2571. }
  2572. break;
  2573. #ifdef TCP_BUF_WRITE
  2574. case CONN_QUEUED_WRITE:
  2575. /* received only if the wr. queue is empty and a write finishes
  2576. * with EAGAIN (common after connect())
  2577. * it should only enable write watching on the fd. The connection
  2578. * should be already in the hash. The refcnt is not changed.
  2579. */
  2580. if (unlikely((tcpconn->state==S_CONN_BAD) ||
  2581. !(tcpconn->flags & F_CONN_HASHED) ))
  2582. break;
  2583. if (!(tcpconn->flags & F_CONN_WANTS_WR)){
  2584. tcpconn->flags|=F_CONN_WANTS_WR;
  2585. t=get_ticks_raw();
  2586. if (likely((tcpconn->flags & F_CONN_MAIN_TIMER) &&
  2587. (TICKS_LT(tcpconn->wbuf_q.wr_timeout, tcpconn->timeout)) &&
  2588. TICKS_LT(t, tcpconn->wbuf_q.wr_timeout) )){
  2589. /* _wbufq_nonempty() is guaranteed here */
  2590. /* update the timer */
  2591. local_timer_del(&tcp_main_ltimer, &tcpconn->timer);
  2592. local_timer_reinit(&tcpconn->timer);
  2593. local_timer_add(&tcp_main_ltimer, &tcpconn->timer,
  2594. tcpconn->wbuf_q.wr_timeout-t, t);
  2595. DBG("tcp_main: handle_ser_child: CONN_QUEUED_WRITE; %p "
  2596. "timeout adjusted to %d s\n", tcpconn,
  2597. TICKS_TO_S(tcpconn->wbuf_q.wr_timeout-t));
  2598. }
  2599. if (!(tcpconn->flags & F_CONN_WRITE_W)){
  2600. tcpconn->flags|=F_CONN_WRITE_W;
  2601. if (!(tcpconn->flags & F_CONN_READ_W)){
  2602. if (unlikely(io_watch_add(&io_h, tcpconn->s, POLLOUT,
  2603. F_TCPCONN, tcpconn)<0)){
  2604. LOG(L_CRIT, "ERROR: tcp_main: handle_ser_child:"
  2605. " failed to enable write watch on"
  2606. " socket\n");
  2607. if (tcpconn_try_unhash(tcpconn))
  2608. tcpconn_put_destroy(tcpconn);
  2609. break;
  2610. }
  2611. }else{
  2612. if (unlikely(io_watch_chg(&io_h, tcpconn->s,
  2613. POLLIN|POLLOUT, -1)<0)){
  2614. LOG(L_CRIT, "ERROR: tcp_main: handle_ser_child:"
  2615. " failed to change socket watch events\n");
  2616. io_watch_del(&io_h, tcpconn->s, -1, IO_FD_CLOSING);
  2617. tcpconn->flags&=~F_CONN_READ_W;
  2618. if (tcpconn_try_unhash(tcpconn))
  2619. tcpconn_put_destroy(tcpconn);
  2620. break;
  2621. }
  2622. }
  2623. }
  2624. }else{
  2625. LOG(L_WARN, "tcp_main: hanlder_ser_child: connection %p"
  2626. " already watched for write\n", tcpconn);
  2627. }
  2628. break;
  2629. #ifdef TCP_CONNECT_WAIT
  2630. case CONN_NEW_COMPLETE:
  2631. case CONN_NEW_PENDING_WRITE:
  2632. /* received when a pending connect completes in the same
  2633. * tcp_send() that initiated it
  2634. * the connection is already in the hash with S_CONN_PENDING
  2635. * state (added by tcp_send()) and refcnt at least 1 (for the
  2636. * hash)*/
  2637. tcpconn->flags&=~(F_CONN_PENDING|F_CONN_FD_CLOSED);
  2638. if (unlikely((tcpconn->state==S_CONN_BAD) || (fd==-1))){
  2639. if (unlikely(fd==-1))
  2640. LOG(L_CRIT, "BUG: handle_ser_child: CONN_NEW_COMPLETE:"
  2641. " no fd received\n");
  2642. else
  2643. LOG(L_WARN, "WARNING: handle_ser_child: CONN_NEW_COMPLETE:"
  2644. " received connection with error\n");
  2645. tcpconn->flags|=F_CONN_FD_CLOSED;
  2646. tcpconn->state=S_CONN_BAD;
  2647. tcpconn_try_unhash(tcpconn);
  2648. tcpconn_put_destroy(tcpconn);
  2649. break;
  2650. }
  2651. tcpconn->state=S_CONN_OK;
  2652. (*tcp_connections_no)++;
  2653. tcpconn->s=fd;
  2654. /* update the timeout*/
  2655. t=get_ticks_raw();
  2656. tcpconn->timeout=t+tcp_con_lifetime;
  2657. /* activate the timer (already properly init. in tcpconn_new())
  2658. * no need for reinit */
  2659. local_timer_add(&tcp_main_ltimer, &tcpconn->timer,
  2660. tcp_con_lifetime, t);
  2661. tcpconn->flags|=F_CONN_MAIN_TIMER|F_CONN_READ_W|F_CONN_WANTS_RD;
  2662. if (unlikely(cmd==CONN_NEW_COMPLETE)){
  2663. /* check if needs to be watched for write */
  2664. lock_get(&tcpconn->write_lock);
  2665. /* if queue non empty watch it for write */
  2666. flags=(_wbufq_empty(tcpconn)-1)&POLLOUT;
  2667. lock_release(&tcpconn->write_lock);
  2668. tcpconn->flags|=(!(flags&POLLOUT)-1)&
  2669. (F_CONN_WRITE_W|F_CONN_WANTS_WR);
  2670. }else{
  2671. /* CONN_NEW_PENDING_WRITE */
  2672. /* no need to check, we have something queued for write */
  2673. flags=POLLOUT;
  2674. tcpconn->flags|=(F_CONN_WRITE_W|F_CONN_WANTS_WR);
  2675. }
  2676. flags|=POLLIN;
  2677. if (unlikely(
  2678. io_watch_add(&io_h, tcpconn->s, flags,
  2679. F_TCPCONN, tcpconn)<0)){
  2680. LOG(L_CRIT, "ERROR: tcp_main: handle_ser_child: failed to add"
  2681. " new socket to the fd list\n");
  2682. tcpconn->flags&=~(F_CONN_WRITE_W|F_CONN_READ_W);
  2683. tcpconn_try_unhash(tcpconn); /* unhash & dec refcnt */
  2684. tcpconn_put_destroy(tcpconn);
  2685. }
  2686. break;
  2687. #endif /* TCP_CONNECT_WAIT */
  2688. #endif /* TCP_BUF_WRITE */
  2689. default:
  2690. LOG(L_CRIT, "BUG: handle_ser_child: unknown cmd %d\n", cmd);
  2691. }
  2692. end:
  2693. return ret;
  2694. error:
  2695. return -1;
  2696. }
  2697. /* sends a tcpconn + fd to a choosen child */
  2698. inline static int send2child(struct tcp_connection* tcpconn)
  2699. {
  2700. int i;
  2701. int min_busy;
  2702. int idx;
  2703. static int crt=0; /* current child */
  2704. int last;
  2705. min_busy=tcp_children[0].busy;
  2706. idx=0;
  2707. last=crt+tcp_children_no;
  2708. for (; crt<last; crt++){
  2709. i=crt%tcp_children_no;
  2710. if (!tcp_children[i].busy){
  2711. idx=i;
  2712. min_busy=0;
  2713. break;
  2714. }else if (min_busy>tcp_children[i].busy){
  2715. min_busy=tcp_children[i].busy;
  2716. idx=i;
  2717. }
  2718. }
  2719. crt=idx+1; /* next time we start with crt%tcp_children_no */
  2720. tcp_children[idx].busy++;
  2721. tcp_children[idx].n_reqs++;
  2722. if (unlikely(min_busy)){
  2723. DBG("WARNING: send2child: no free tcp receiver, "
  2724. " connection passed to the least busy one (%d)\n",
  2725. min_busy);
  2726. }
  2727. DBG("send2child: to tcp child %d %d(%d), %p\n", idx,
  2728. tcp_children[idx].proc_no,
  2729. tcp_children[idx].pid, tcpconn);
  2730. /* first make sure this child doesn't have pending request for
  2731. * tcp_main (to avoid a possible deadlock: e.g. child wants to
  2732. * send a release command, but the master fills its socket buffer
  2733. * with new connection commands => deadlock) */
  2734. /* answer tcp_send requests first */
  2735. while(handle_ser_child(&pt[tcp_children[idx].proc_no], -1)>0);
  2736. /* process tcp readers requests */
  2737. while(handle_tcp_child(&tcp_children[idx], -1)>0);
  2738. #ifdef SEND_FD_QUEUE
  2739. /* if queue full, try to queue the io */
  2740. if (unlikely(send_fd(tcp_children[idx].unix_sock, &tcpconn,
  2741. sizeof(tcpconn), tcpconn->s)<=0)){
  2742. if ((errno==EAGAIN)||(errno==EWOULDBLOCK)){
  2743. /* FIXME: remove after debugging */
  2744. LOG(L_CRIT, "INFO: tcp child %d, socket %d: queue full,"
  2745. " %d requests queued (total handled %d)\n",
  2746. idx, tcp_children[idx].unix_sock, min_busy,
  2747. tcp_children[idx].n_reqs-1);
  2748. if (send_fd_queue_add(&send2child_q, tcp_children[idx].unix_sock,
  2749. tcpconn)!=0){
  2750. LOG(L_ERR, "ERROR: send2child: queue send op. failed\n");
  2751. return -1;
  2752. }
  2753. }else{
  2754. LOG(L_ERR, "ERROR: send2child: send_fd failed\n");
  2755. return -1;
  2756. }
  2757. }
  2758. #else
  2759. if (unlikely(send_fd(tcp_children[idx].unix_sock, &tcpconn,
  2760. sizeof(tcpconn), tcpconn->s)<=0)){
  2761. LOG(L_ERR, "ERROR: send2child: send_fd failed\n");
  2762. return -1;
  2763. }
  2764. #endif
  2765. return 0;
  2766. }
  2767. /* handles a new connection, called internally by tcp_main_loop/handle_io.
  2768. * params: si - pointer to one of the tcp socket_info structures on which
  2769. * an io event was detected (connection attempt)
  2770. * returns: handle_* return convention: -1 on error, 0 on EAGAIN (no more
  2771. * io events queued), >0 on success. success/error refer only to
  2772. * the accept.
  2773. */
  2774. static inline int handle_new_connect(struct socket_info* si)
  2775. {
  2776. union sockaddr_union su;
  2777. union sockaddr_union sock_name;
  2778. unsigned sock_name_len;
  2779. union sockaddr_union* dst_su;
  2780. struct tcp_connection* tcpconn;
  2781. socklen_t su_len;
  2782. int new_sock;
  2783. /* got a connection on r */
  2784. su_len=sizeof(su);
  2785. new_sock=accept(si->socket, &(su.s), &su_len);
  2786. if (unlikely(new_sock==-1)){
  2787. if ((errno==EAGAIN)||(errno==EWOULDBLOCK))
  2788. return 0;
  2789. LOG(L_ERR, "WARNING: handle_new_connect: error while accepting"
  2790. " connection(%d): %s\n", errno, strerror(errno));
  2791. return -1;
  2792. }
  2793. if (unlikely(*tcp_connections_no>=tcp_max_connections)){
  2794. LOG(L_ERR, "ERROR: maximum number of connections exceeded: %d/%d\n",
  2795. *tcp_connections_no, tcp_max_connections);
  2796. close(new_sock);
  2797. return 1; /* success, because the accept was succesfull */
  2798. }
  2799. if (unlikely(init_sock_opt_accept(new_sock)<0)){
  2800. LOG(L_ERR, "ERROR: handle_new_connect: init_sock_opt failed\n");
  2801. close(new_sock);
  2802. return 1; /* success, because the accept was succesfull */
  2803. }
  2804. (*tcp_connections_no)++;
  2805. dst_su=&si->su;
  2806. if (unlikely(si->flags & SI_IS_ANY)){
  2807. /* INADDR_ANY => get local dst */
  2808. sock_name_len=sizeof(sock_name);
  2809. if (getsockname(new_sock, &sock_name.s, &sock_name_len)!=0){
  2810. LOG(L_ERR, "ERROR: handle_new_connect:"
  2811. " getsockname failed: %s(%d)\n",
  2812. strerror(errno), errno);
  2813. /* go on with the 0.0.0.0 dst from the sock_info */
  2814. }else{
  2815. dst_su=&sock_name;
  2816. }
  2817. }
  2818. /* add socket to list */
  2819. tcpconn=tcpconn_new(new_sock, &su, dst_su, si, si->proto, S_CONN_ACCEPT);
  2820. if (likely(tcpconn)){
  2821. #ifdef TCP_PASS_NEW_CONNECTION_ON_DATA
  2822. atomic_set(&tcpconn->refcnt, 1); /* safe, not yet available to the
  2823. outside world */
  2824. tcpconn_add(tcpconn);
  2825. /* activate the timer */
  2826. local_timer_add(&tcp_main_ltimer, &tcpconn->timer,
  2827. tcp_con_lifetime, get_ticks_raw());
  2828. tcpconn->flags|=(F_CONN_MAIN_TIMER|F_CONN_READ_W|F_CONN_WANTS_RD);
  2829. if (unlikely(io_watch_add(&io_h, tcpconn->s, POLLIN,
  2830. F_TCPCONN, tcpconn)<0)){
  2831. LOG(L_CRIT, "ERROR: tcp_main: handle_new_connect: failed to add"
  2832. " new socket to the fd list\n");
  2833. tcpconn->flags&=~F_CONN_READ_W;
  2834. if (tcpconn_try_unhash(tcpconn))
  2835. tcpconn_put_destroy(tcpconn);
  2836. }
  2837. #else
  2838. atomic_set(&tcpconn->refcnt, 2); /* safe, not yet available to the
  2839. outside world */
  2840. /* prepare it for passing to a child */
  2841. tcpconn->flags|=F_CONN_READER;
  2842. tcpconn_add(tcpconn);
  2843. DBG("handle_new_connect: new connection from %s: %p %d flags: %04x\n",
  2844. su2a(&su, sizeof(su)), tcpconn, tcpconn->s, tcpconn->flags);
  2845. if(unlikely(send2child(tcpconn)<0)){
  2846. LOG(L_ERR,"ERROR: handle_new_connect: no children "
  2847. "available\n");
  2848. tcpconn->flags&=~F_CONN_READER;
  2849. tcpconn_put(tcpconn);
  2850. tcpconn_try_unhash(tcpconn);
  2851. tcpconn_put_destroy(tcpconn);
  2852. }
  2853. #endif
  2854. }else{ /*tcpconn==0 */
  2855. LOG(L_ERR, "ERROR: handle_new_connect: tcpconn_new failed, "
  2856. "closing socket\n");
  2857. close(new_sock);
  2858. (*tcp_connections_no)--;
  2859. }
  2860. return 1; /* accept() was succesfull */
  2861. }
  2862. /* handles an io event on one of the watched tcp connections
  2863. *
  2864. * params: tcpconn - pointer to the tcp_connection for which we have an io ev.
  2865. * fd_i - index in the fd_array table (needed for delete)
  2866. * returns: handle_* return convention, but on success it always returns 0
  2867. * (because it's one-shot, after a succesful execution the fd is
  2868. * removed from tcp_main's watch fd list and passed to a child =>
  2869. * tcp_main is not interested in further io events that might be
  2870. * queued for this fd)
  2871. */
  2872. inline static int handle_tcpconn_ev(struct tcp_connection* tcpconn, short ev,
  2873. int fd_i)
  2874. {
  2875. #ifdef TCP_BUF_WRITE
  2876. int empty_q;
  2877. int bytes;
  2878. #endif /* TCP_BUF_WRITE */
  2879. /* is refcnt!=0 really necessary?
  2880. * No, in fact it's a bug: I can have the following situation: a send only
  2881. * tcp connection used by n processes simultaneously => refcnt = n. In
  2882. * the same time I can have a read event and this situation is perfectly
  2883. * valid. -- andrei
  2884. */
  2885. #if 0
  2886. if ((tcpconn->refcnt!=0)){
  2887. /* FIXME: might be valid for sigio_rt iff fd flags are not cleared
  2888. * (there is a short window in which it could generate a sig
  2889. * that would be catched by tcp_main) */
  2890. LOG(L_CRIT, "BUG: handle_tcpconn_ev: io event on referenced"
  2891. " tcpconn (%p), refcnt=%d, fd=%d\n",
  2892. tcpconn, tcpconn->refcnt, tcpconn->s);
  2893. return -1;
  2894. }
  2895. #endif
  2896. /* pass it to child, so remove it from the io watch list and the local
  2897. * timer */
  2898. #ifdef TCP_BUF_WRITE
  2899. empty_q=0; /* warning fix */
  2900. if (unlikely((ev & (POLLOUT|POLLERR|POLLHUP)) &&
  2901. (tcpconn->flags & F_CONN_WRITE_W))){
  2902. if (unlikely((ev & (POLLERR|POLLHUP)) ||
  2903. (wbufq_run(tcpconn->s, tcpconn, &empty_q)<0))){
  2904. if (unlikely(io_watch_del(&io_h, tcpconn->s, fd_i, 0)<0)){
  2905. LOG(L_ERR, "ERROR: handle_tcpconn_ev: io_watch_del(1) failed:"
  2906. " for %p, fd %d\n", tcpconn, tcpconn->s);
  2907. }
  2908. if ((tcpconn->flags & F_CONN_READ_W) && (ev & POLLIN)){
  2909. /* connection is watched for read and there is a read event
  2910. * (unfortunately if we have POLLIN here we don't know if
  2911. * there's really any data in the read buffer or the POLLIN
  2912. * was generated by the error or EOF => to avoid loosing
  2913. * data it's safer to either directly check the read buffer
  2914. * or try a read)*/
  2915. /* in most cases the read buffer will be empty, so in general
  2916. * is cheaper to check it here and then send the
  2917. * conn. to a a child only if needed (another syscall + at
  2918. * least 2 * syscalls in the reader + ...) */
  2919. if ((ioctl(tcpconn->s, FIONREAD, &bytes)>=0) && (bytes>0)){
  2920. tcpconn->flags&=~(F_CONN_WRITE_W|F_CONN_READ_W|
  2921. F_CONN_WANTS_RD|F_CONN_WANTS_WR);
  2922. tcpconn->flags|=F_CONN_FORCE_EOF|F_CONN_WR_ERROR;
  2923. goto send_to_child;
  2924. }
  2925. /* if bytes==0 or ioctl failed, destroy the connection now */
  2926. }
  2927. tcpconn->flags&=~(F_CONN_WRITE_W|F_CONN_READ_W|
  2928. F_CONN_WANTS_RD|F_CONN_WANTS_WR);
  2929. if (unlikely(!tcpconn_try_unhash(tcpconn))){
  2930. LOG(L_CRIT, "BUG: tcpconn_ev: unhashed connection %p\n",
  2931. tcpconn);
  2932. }
  2933. tcpconn_put_destroy(tcpconn);
  2934. goto error;
  2935. }
  2936. if (empty_q){
  2937. tcpconn->flags&=~F_CONN_WANTS_WR;
  2938. if (!(tcpconn->flags & F_CONN_READ_W)){
  2939. if (unlikely(io_watch_del(&io_h, tcpconn->s, fd_i, 0)==-1)){
  2940. LOG(L_ERR, "ERROR: handle_tcpconn_ev: io_watch_del(2)"
  2941. " failed:" " for %p, fd %d\n",
  2942. tcpconn, tcpconn->s);
  2943. goto error;
  2944. }
  2945. }else{
  2946. if (unlikely(io_watch_chg(&io_h, tcpconn->s,
  2947. POLLIN, fd_i)==-1)){
  2948. LOG(L_ERR, "ERROR: handle_tcpconn_ev: io_watch_chg(1)"
  2949. " failed:" " for %p, fd %d\n",
  2950. tcpconn, tcpconn->s);
  2951. goto error;
  2952. }
  2953. }
  2954. tcpconn->flags&=~F_CONN_WRITE_W;
  2955. }
  2956. ev&=~POLLOUT; /* clear POLLOUT */
  2957. }
  2958. if (likely(ev && (tcpconn->flags & F_CONN_READ_W))){
  2959. /* if still some other IO event (POLLIN|POLLHUP|POLLERR) and
  2960. * connection is still watched in tcp_main for reads, send it to a
  2961. * child and stop watching it for input (but continue watching for
  2962. * writes if needed): */
  2963. if (unlikely(tcpconn->flags & F_CONN_WRITE_W)){
  2964. if (unlikely(io_watch_chg(&io_h, tcpconn->s, POLLOUT, fd_i)==-1)){
  2965. LOG(L_ERR, "ERROR: handle_tcpconn_ev: io_watch_chg(2)"
  2966. " failed:" " for %p, fd %d\n",
  2967. tcpconn, tcpconn->s);
  2968. goto error;
  2969. }
  2970. }else
  2971. #else
  2972. {
  2973. #endif /* TCP_BUF_WRITE */
  2974. if (unlikely(io_watch_del(&io_h, tcpconn->s, fd_i, 0)==-1)){
  2975. LOG(L_ERR, "ERROR: handle_tcpconn_ev: io_watch_del(3)"
  2976. " failed:" " for %p, fd %d\n",
  2977. tcpconn, tcpconn->s);
  2978. goto error;
  2979. }
  2980. #ifdef TCP_BUF_WRITE
  2981. send_to_child:
  2982. #endif
  2983. DBG("tcp: DBG: sendig to child, events %x\n", ev);
  2984. #ifdef POLLRDHUP
  2985. tcpconn->flags|=((int)!(ev & (POLLRDHUP|POLLHUP|POLLERR)) -1) &
  2986. F_CONN_EOF_SEEN;
  2987. #else /* POLLRDHUP */
  2988. tcpconn->flags|=((int)!(ev & (POLLHUP|POLLERR)) -1) & F_CONN_EOF_SEEN;
  2989. #endif /* POLLRDHUP */
  2990. tcpconn->flags|= ((int)!(ev & POLLPRI) -1) & F_CONN_OOB_DATA;
  2991. tcpconn->flags|=F_CONN_READER;
  2992. local_timer_del(&tcp_main_ltimer, &tcpconn->timer);
  2993. tcpconn->flags&=~(F_CONN_MAIN_TIMER|F_CONN_READ_W|F_CONN_WANTS_RD);
  2994. tcpconn_ref(tcpconn); /* refcnt ++ */
  2995. if (unlikely(send2child(tcpconn)<0)){
  2996. LOG(L_ERR,"ERROR: handle_tcpconn_ev: no children available\n");
  2997. tcpconn->flags&=~F_CONN_READER;
  2998. #ifdef TCP_BUF_WRITE
  2999. if (tcpconn->flags & F_CONN_WRITE_W){
  3000. if (unlikely(io_watch_del(&io_h, tcpconn->s, fd_i, 0)<0)){
  3001. LOG(L_ERR, "ERROR: handle_tcpconn_ev: io_watch_del(4)"
  3002. " failed:" " for %p, fd %d\n",
  3003. tcpconn, tcpconn->s);
  3004. }
  3005. tcpconn->flags&=~F_CONN_WRITE_W;
  3006. }
  3007. #endif /* TCP_BUF_WRITE */
  3008. tcpconn_put(tcpconn);
  3009. tcpconn_try_unhash(tcpconn);
  3010. tcpconn_put_destroy(tcpconn); /* because of the tcpconn_ref() */
  3011. }
  3012. }
  3013. return 0; /* we are not interested in possibly queued io events,
  3014. the fd was either passed to a child, closed, or for writes,
  3015. everything possible was already written */
  3016. error:
  3017. return -1;
  3018. }
  3019. /* generic handle io routine, it will call the appropiate
  3020. * handle_xxx() based on the fd_map type
  3021. *
  3022. * params: fm - pointer to a fd hash entry
  3023. * idx - index in the fd_array (or -1 if not known)
  3024. * return: -1 on error
  3025. * 0 on EAGAIN or when by some other way it is known that no more
  3026. * io events are queued on the fd (the receive buffer is empty).
  3027. * Usefull to detect when there are no more io events queued for
  3028. * sigio_rt, epoll_et, kqueue.
  3029. * >0 on successfull read from the fd (when there might be more io
  3030. * queued -- the receive buffer might still be non-empty)
  3031. */
  3032. inline static int handle_io(struct fd_map* fm, short ev, int idx)
  3033. {
  3034. int ret;
  3035. /* update the local config */
  3036. cfg_update();
  3037. switch(fm->type){
  3038. case F_SOCKINFO:
  3039. ret=handle_new_connect((struct socket_info*)fm->data);
  3040. break;
  3041. case F_TCPCONN:
  3042. ret=handle_tcpconn_ev((struct tcp_connection*)fm->data, ev, idx);
  3043. break;
  3044. case F_TCPCHILD:
  3045. ret=handle_tcp_child((struct tcp_child*)fm->data, idx);
  3046. break;
  3047. case F_PROC:
  3048. ret=handle_ser_child((struct process_table*)fm->data, idx);
  3049. break;
  3050. case F_NONE:
  3051. LOG(L_CRIT, "BUG: handle_io: empty fd map: %p {%d, %d, %p},"
  3052. " idx %d\n", fm, fm->fd, fm->type, fm->data, idx);
  3053. goto error;
  3054. default:
  3055. LOG(L_CRIT, "BUG: handle_io: uknown fd type %d\n", fm->type);
  3056. goto error;
  3057. }
  3058. return ret;
  3059. error:
  3060. return -1;
  3061. }
  3062. /* timer handler for tcpconnection handled by tcp_main */
  3063. static ticks_t tcpconn_main_timeout(ticks_t t, struct timer_ln* tl, void* data)
  3064. {
  3065. struct tcp_connection *c;
  3066. int fd;
  3067. c=(struct tcp_connection*)data;
  3068. /* or (struct tcp...*)(tl-offset(c->timer)) */
  3069. #ifdef TCP_BUF_WRITE
  3070. DBG( "tcp_main: entering timer for %p (ticks=%d, timeout=%d (%d s), "
  3071. "wr_timeout=%d (%d s)), write queue: %d bytes\n",
  3072. c, t, c->timeout, TICKS_TO_S(c->timeout-t),
  3073. c->wbuf_q.wr_timeout, TICKS_TO_S(c->wbuf_q.wr_timeout-t),
  3074. c->wbuf_q.queued);
  3075. if (TICKS_LT(t, c->timeout) &&
  3076. (!tcp_options.tcp_buf_write | _wbufq_empty(c) |
  3077. TICKS_LT(t, c->wbuf_q.wr_timeout)) ){
  3078. if (unlikely(tcp_options.tcp_buf_write && _wbufq_non_empty(c)))
  3079. return (ticks_t)MIN_unsigned(c->timeout-t, c->wbuf_q.wr_timeout-t);
  3080. else
  3081. return (ticks_t)(c->timeout - t);
  3082. }
  3083. #else /* ! TCP_BUF_WRITE */
  3084. if (TICKS_LT(t, c->timeout)){
  3085. /* timeout extended, exit */
  3086. return (ticks_t)(c->timeout - t);
  3087. }
  3088. #endif /* TCP_BUF_WRITE */
  3089. DBG("tcp_main: timeout for %p\n", c);
  3090. if (likely(c->flags & F_CONN_HASHED)){
  3091. c->flags&=~(F_CONN_HASHED|F_CONN_MAIN_TIMER);
  3092. c->state=S_CONN_BAD;
  3093. TCPCONN_LOCK;
  3094. _tcpconn_detach(c);
  3095. TCPCONN_UNLOCK;
  3096. }else{
  3097. c->flags&=~F_CONN_MAIN_TIMER;
  3098. LOG(L_CRIT, "BUG: tcp_main: timer: called with unhashed connection %p"
  3099. "\n", c);
  3100. tcpconn_ref(c); /* ugly hack to try to go on */
  3101. }
  3102. fd=c->s;
  3103. if (likely(fd>0)){
  3104. if (likely(c->flags & (F_CONN_READ_W|F_CONN_WRITE_W))){
  3105. io_watch_del(&io_h, fd, -1, IO_FD_CLOSING);
  3106. c->flags&=~(F_CONN_READ_W|F_CONN_WRITE_W);
  3107. }
  3108. }
  3109. tcpconn_put_destroy(c);
  3110. return 0;
  3111. }
  3112. static inline void tcp_timer_run()
  3113. {
  3114. ticks_t ticks;
  3115. ticks=get_ticks_raw();
  3116. if (unlikely((ticks-tcp_main_prev_ticks)<TCPCONN_TIMEOUT_MIN_RUN)) return;
  3117. tcp_main_prev_ticks=ticks;
  3118. local_timer_run(&tcp_main_ltimer, ticks);
  3119. }
  3120. /* keep in sync with tcpconn_destroy, the "delete" part should be
  3121. * the same except for io_watch_del..
  3122. * Note: this function is called only on shutdown by the main ser process via
  3123. * cleanup(). However it's also safe to call it from the tcp_main process.
  3124. * => with the ser shutdown exception, it cannot execute in parallel
  3125. * with tcpconn_add() or tcpconn_destroy()*/
  3126. static inline void tcpconn_destroy_all()
  3127. {
  3128. struct tcp_connection *c, *next;
  3129. unsigned h;
  3130. int fd;
  3131. TCPCONN_LOCK;
  3132. for(h=0; h<TCP_ID_HASH_SIZE; h++){
  3133. c=tcpconn_id_hash[h];
  3134. while(c){
  3135. next=c->id_next;
  3136. if (is_tcp_main){
  3137. /* we cannot close or remove the fd if we are not in the
  3138. * tcp main proc.*/
  3139. if ((c->flags & F_CONN_MAIN_TIMER)){
  3140. local_timer_del(&tcp_main_ltimer, &c->timer);
  3141. c->flags&=~F_CONN_MAIN_TIMER;
  3142. } /* else still in some reader */
  3143. fd=c->s;
  3144. if (fd>0 && (c->flags & (F_CONN_READ_W|F_CONN_WRITE_W))){
  3145. io_watch_del(&io_h, fd, -1, IO_FD_CLOSING);
  3146. c->flags&=~(F_CONN_READ_W|F_CONN_WRITE_W);
  3147. }
  3148. }else{
  3149. fd=-1;
  3150. }
  3151. #ifdef USE_TLS
  3152. if (fd>0 && c->type==PROTO_TLS)
  3153. tls_close(c, fd);
  3154. #endif
  3155. _tcpconn_rm(c);
  3156. if (fd>0) {
  3157. #ifdef TCP_FD_CACHE
  3158. if (likely(tcp_options.fd_cache)) shutdown(fd, SHUT_RDWR);
  3159. #endif /* TCP_FD_CACHE */
  3160. close(fd);
  3161. }
  3162. (*tcp_connections_no)--;
  3163. c=next;
  3164. }
  3165. }
  3166. TCPCONN_UNLOCK;
  3167. }
  3168. /* tcp main loop */
  3169. void tcp_main_loop()
  3170. {
  3171. struct socket_info* si;
  3172. int r;
  3173. is_tcp_main=1; /* mark this process as tcp main */
  3174. tcp_main_max_fd_no=get_max_open_fds();
  3175. /* init send fd queues (here because we want mem. alloc only in the tcp
  3176. * process */
  3177. #ifdef SEND_FD_QUEUE
  3178. if (init_send_fd_queues()<0){
  3179. LOG(L_CRIT, "ERROR: init_tcp: could not init send fd queues\n");
  3180. goto error;
  3181. }
  3182. #endif
  3183. /* init io_wait (here because we want the memory allocated only in
  3184. * the tcp_main process) */
  3185. if (init_io_wait(&io_h, tcp_main_max_fd_no, tcp_poll_method)<0)
  3186. goto error;
  3187. /* init: start watching all the fds*/
  3188. /* init local timer */
  3189. tcp_main_prev_ticks=get_ticks_raw();
  3190. if (init_local_timer(&tcp_main_ltimer, get_ticks_raw())!=0){
  3191. LOG(L_ERR, "ERROR: init_tcp: failed to init local timer\n");
  3192. goto error;
  3193. }
  3194. #ifdef TCP_FD_CACHE
  3195. if (tcp_options.fd_cache) tcp_fd_cache_init();
  3196. #endif /* TCP_FD_CACHE */
  3197. /* add all the sockets we listen on for connections */
  3198. for (si=tcp_listen; si; si=si->next){
  3199. if ((si->proto==PROTO_TCP) &&(si->socket!=-1)){
  3200. if (io_watch_add(&io_h, si->socket, POLLIN, F_SOCKINFO, si)<0){
  3201. LOG(L_CRIT, "ERROR: tcp_main_loop: init: failed to add "
  3202. "listen socket to the fd list\n");
  3203. goto error;
  3204. }
  3205. }else{
  3206. LOG(L_CRIT, "BUG: tcp_main_loop: non tcp address in tcp_listen\n");
  3207. }
  3208. }
  3209. #ifdef USE_TLS
  3210. if (!tls_disable && tls_loaded()){
  3211. for (si=tls_listen; si; si=si->next){
  3212. if ((si->proto==PROTO_TLS) && (si->socket!=-1)){
  3213. if (io_watch_add(&io_h, si->socket, POLLIN, F_SOCKINFO, si)<0){
  3214. LOG(L_CRIT, "ERROR: tcp_main_loop: init: failed to add "
  3215. "tls listen socket to the fd list\n");
  3216. goto error;
  3217. }
  3218. }else{
  3219. LOG(L_CRIT, "BUG: tcp_main_loop: non tls address"
  3220. " in tls_listen\n");
  3221. }
  3222. }
  3223. }
  3224. #endif
  3225. /* add all the unix sockets used for communcation with other ser processes
  3226. * (get fd, new connection a.s.o) */
  3227. for (r=1; r<process_no; r++){
  3228. if (pt[r].unix_sock>0) /* we can't have 0, we never close it!*/
  3229. if (io_watch_add(&io_h, pt[r].unix_sock, POLLIN,F_PROC, &pt[r])<0){
  3230. LOG(L_CRIT, "ERROR: tcp_main_loop: init: failed to add "
  3231. "process %d unix socket to the fd list\n", r);
  3232. goto error;
  3233. }
  3234. }
  3235. /* add all the unix sokets used for communication with the tcp childs */
  3236. for (r=0; r<tcp_children_no; r++){
  3237. if (tcp_children[r].unix_sock>0)/*we can't have 0, we never close it!*/
  3238. if (io_watch_add(&io_h, tcp_children[r].unix_sock, POLLIN,
  3239. F_TCPCHILD, &tcp_children[r]) <0){
  3240. LOG(L_CRIT, "ERROR: tcp_main_loop: init: failed to add "
  3241. "tcp child %d unix socket to the fd list\n", r);
  3242. goto error;
  3243. }
  3244. }
  3245. /* initialize the cfg framework */
  3246. if (cfg_child_init()) goto error;
  3247. /* main loop */
  3248. switch(io_h.poll_method){
  3249. case POLL_POLL:
  3250. while(1){
  3251. /* wait and process IO */
  3252. io_wait_loop_poll(&io_h, TCP_MAIN_SELECT_TIMEOUT, 0);
  3253. send_fd_queue_run(&send2child_q); /* then new io */
  3254. /* remove old connections */
  3255. tcp_timer_run();
  3256. }
  3257. break;
  3258. #ifdef HAVE_SELECT
  3259. case POLL_SELECT:
  3260. while(1){
  3261. io_wait_loop_select(&io_h, TCP_MAIN_SELECT_TIMEOUT, 0);
  3262. send_fd_queue_run(&send2child_q); /* then new io */
  3263. tcp_timer_run();
  3264. }
  3265. break;
  3266. #endif
  3267. #ifdef HAVE_SIGIO_RT
  3268. case POLL_SIGIO_RT:
  3269. while(1){
  3270. io_wait_loop_sigio_rt(&io_h, TCP_MAIN_SELECT_TIMEOUT);
  3271. send_fd_queue_run(&send2child_q); /* then new io */
  3272. tcp_timer_run();
  3273. }
  3274. break;
  3275. #endif
  3276. #ifdef HAVE_EPOLL
  3277. case POLL_EPOLL_LT:
  3278. while(1){
  3279. io_wait_loop_epoll(&io_h, TCP_MAIN_SELECT_TIMEOUT, 0);
  3280. send_fd_queue_run(&send2child_q); /* then new io */
  3281. tcp_timer_run();
  3282. }
  3283. break;
  3284. case POLL_EPOLL_ET:
  3285. while(1){
  3286. io_wait_loop_epoll(&io_h, TCP_MAIN_SELECT_TIMEOUT, 1);
  3287. send_fd_queue_run(&send2child_q); /* then new io */
  3288. tcp_timer_run();
  3289. }
  3290. break;
  3291. #endif
  3292. #ifdef HAVE_KQUEUE
  3293. case POLL_KQUEUE:
  3294. while(1){
  3295. io_wait_loop_kqueue(&io_h, TCP_MAIN_SELECT_TIMEOUT, 0);
  3296. send_fd_queue_run(&send2child_q); /* then new io */
  3297. tcp_timer_run();
  3298. }
  3299. break;
  3300. #endif
  3301. #ifdef HAVE_DEVPOLL
  3302. case POLL_DEVPOLL:
  3303. while(1){
  3304. io_wait_loop_devpoll(&io_h, TCP_MAIN_SELECT_TIMEOUT, 0);
  3305. send_fd_queue_run(&send2child_q); /* then new io */
  3306. tcp_timer_run();
  3307. }
  3308. break;
  3309. #endif
  3310. default:
  3311. LOG(L_CRIT, "BUG: tcp_main_loop: no support for poll method "
  3312. " %s (%d)\n",
  3313. poll_method_name(io_h.poll_method), io_h.poll_method);
  3314. goto error;
  3315. }
  3316. error:
  3317. #ifdef SEND_FD_QUEUE
  3318. destroy_send_fd_queues();
  3319. #endif
  3320. destroy_io_wait(&io_h);
  3321. LOG(L_CRIT, "ERROR: tcp_main_loop: exiting...");
  3322. exit(-1);
  3323. }
  3324. /* cleanup before exit */
  3325. void destroy_tcp()
  3326. {
  3327. if (tcpconn_id_hash){
  3328. if (tcpconn_lock)
  3329. TCPCONN_UNLOCK; /* hack: force-unlock the tcp lock in case
  3330. some process was terminated while holding
  3331. it; this will allow an almost gracious
  3332. shutdown */
  3333. tcpconn_destroy_all();
  3334. shm_free(tcpconn_id_hash);
  3335. tcpconn_id_hash=0;
  3336. }
  3337. if (tcp_connections_no){
  3338. shm_free(tcp_connections_no);
  3339. tcp_connections_no=0;
  3340. }
  3341. #ifdef TCP_BUF_WRITE
  3342. if (tcp_total_wq){
  3343. shm_free(tcp_total_wq);
  3344. tcp_total_wq=0;
  3345. }
  3346. #endif /* TCP_BUF_WRITE */
  3347. if (connection_id){
  3348. shm_free(connection_id);
  3349. connection_id=0;
  3350. }
  3351. if (tcpconn_aliases_hash){
  3352. shm_free(tcpconn_aliases_hash);
  3353. tcpconn_aliases_hash=0;
  3354. }
  3355. if (tcpconn_lock){
  3356. lock_destroy(tcpconn_lock);
  3357. lock_dealloc((void*)tcpconn_lock);
  3358. tcpconn_lock=0;
  3359. }
  3360. if (tcp_children){
  3361. pkg_free(tcp_children);
  3362. tcp_children=0;
  3363. }
  3364. destroy_local_timer(&tcp_main_ltimer);
  3365. }
  3366. int init_tcp()
  3367. {
  3368. char* poll_err;
  3369. tcp_options_check();
  3370. /* init lock */
  3371. tcpconn_lock=lock_alloc();
  3372. if (tcpconn_lock==0){
  3373. LOG(L_CRIT, "ERROR: init_tcp: could not alloc lock\n");
  3374. goto error;
  3375. }
  3376. if (lock_init(tcpconn_lock)==0){
  3377. LOG(L_CRIT, "ERROR: init_tcp: could not init lock\n");
  3378. lock_dealloc((void*)tcpconn_lock);
  3379. tcpconn_lock=0;
  3380. goto error;
  3381. }
  3382. /* init globals */
  3383. tcp_connections_no=shm_malloc(sizeof(int));
  3384. if (tcp_connections_no==0){
  3385. LOG(L_CRIT, "ERROR: init_tcp: could not alloc globals\n");
  3386. goto error;
  3387. }
  3388. *tcp_connections_no=0;
  3389. connection_id=shm_malloc(sizeof(int));
  3390. if (connection_id==0){
  3391. LOG(L_CRIT, "ERROR: init_tcp: could not alloc globals\n");
  3392. goto error;
  3393. }
  3394. *connection_id=1;
  3395. #ifdef TCP_BUF_WRITE
  3396. tcp_total_wq=shm_malloc(sizeof(*tcp_total_wq));
  3397. if (tcp_total_wq==0){
  3398. LOG(L_CRIT, "ERROR: init_tcp: could not alloc globals\n");
  3399. goto error;
  3400. }
  3401. #endif /* TCP_BUF_WRITE */
  3402. /* alloc hashtables*/
  3403. tcpconn_aliases_hash=(struct tcp_conn_alias**)
  3404. shm_malloc(TCP_ALIAS_HASH_SIZE* sizeof(struct tcp_conn_alias*));
  3405. if (tcpconn_aliases_hash==0){
  3406. LOG(L_CRIT, "ERROR: init_tcp: could not alloc address hashtable\n");
  3407. goto error;
  3408. }
  3409. tcpconn_id_hash=(struct tcp_connection**)shm_malloc(TCP_ID_HASH_SIZE*
  3410. sizeof(struct tcp_connection*));
  3411. if (tcpconn_id_hash==0){
  3412. LOG(L_CRIT, "ERROR: init_tcp: could not alloc id hashtable\n");
  3413. goto error;
  3414. }
  3415. /* init hashtables*/
  3416. memset((void*)tcpconn_aliases_hash, 0,
  3417. TCP_ALIAS_HASH_SIZE * sizeof(struct tcp_conn_alias*));
  3418. memset((void*)tcpconn_id_hash, 0,
  3419. TCP_ID_HASH_SIZE * sizeof(struct tcp_connection*));
  3420. /* fix config variables */
  3421. if (tcp_connect_timeout<0)
  3422. tcp_connect_timeout=DEFAULT_TCP_CONNECT_TIMEOUT;
  3423. if (tcp_send_timeout<0)
  3424. tcp_send_timeout=DEFAULT_TCP_SEND_TIMEOUT;
  3425. if (tcp_con_lifetime<0){
  3426. /* set to max value (~ 1/2 MAX_INT) */
  3427. tcp_con_lifetime=MAX_TCP_CON_LIFETIME;
  3428. }else{
  3429. if ((unsigned)tcp_con_lifetime >
  3430. (unsigned)TICKS_TO_S(MAX_TCP_CON_LIFETIME)){
  3431. LOG(L_WARN, "init_tcp: tcp_con_lifetime too big (%u s), "
  3432. " the maximum value is %u\n", tcp_con_lifetime,
  3433. TICKS_TO_S(MAX_TCP_CON_LIFETIME));
  3434. tcp_con_lifetime=MAX_TCP_CON_LIFETIME;
  3435. }else{
  3436. tcp_con_lifetime=S_TO_TICKS(tcp_con_lifetime);
  3437. }
  3438. }
  3439. poll_err=check_poll_method(tcp_poll_method);
  3440. /* set an appropriate poll method */
  3441. if (poll_err || (tcp_poll_method==0)){
  3442. tcp_poll_method=choose_poll_method();
  3443. if (poll_err){
  3444. LOG(L_ERR, "ERROR: init_tcp: %s, using %s instead\n",
  3445. poll_err, poll_method_name(tcp_poll_method));
  3446. }else{
  3447. LOG(L_INFO, "init_tcp: using %s as the io watch method"
  3448. " (auto detected)\n", poll_method_name(tcp_poll_method));
  3449. }
  3450. }else{
  3451. LOG(L_INFO, "init_tcp: using %s io watch method (config)\n",
  3452. poll_method_name(tcp_poll_method));
  3453. }
  3454. return 0;
  3455. error:
  3456. /* clean-up */
  3457. destroy_tcp();
  3458. return -1;
  3459. }
  3460. #ifdef TCP_CHILD_NON_BLOCKING
  3461. /* returns -1 on error */
  3462. static int set_non_blocking(int s)
  3463. {
  3464. int flags;
  3465. /* non-blocking */
  3466. flags=fcntl(s, F_GETFL);
  3467. if (flags==-1){
  3468. LOG(L_ERR, "ERROR: set_non_blocking: fnctl failed: (%d) %s\n",
  3469. errno, strerror(errno));
  3470. goto error;
  3471. }
  3472. if (fcntl(s, F_SETFL, flags|O_NONBLOCK)==-1){
  3473. LOG(L_ERR, "ERROR: set_non_blocking: fcntl: set non-blocking failed:"
  3474. " (%d) %s\n", errno, strerror(errno));
  3475. goto error;
  3476. }
  3477. return 0;
  3478. error:
  3479. return -1;
  3480. }
  3481. #endif
  3482. /* returns -1 on error, 0 on success */
  3483. int tcp_fix_child_sockets(int* fd)
  3484. {
  3485. #ifdef TCP_CHILD_NON_BLOCKING
  3486. if ((set_non_blocking(fd[0])<0) ||
  3487. (set_non_blocking(fd[1])<0)){
  3488. return -1;
  3489. }
  3490. #endif
  3491. return 0;
  3492. }
  3493. /* starts the tcp processes */
  3494. int tcp_init_children()
  3495. {
  3496. int r;
  3497. int reader_fd_1; /* for comm. with the tcp children read */
  3498. pid_t pid;
  3499. struct socket_info *si;
  3500. /* estimate max fd. no:
  3501. * 1 tcp send unix socket/all_proc,
  3502. * + 1 udp sock/udp proc + 1 tcp_child sock/tcp child*
  3503. * + no_listen_tcp */
  3504. for(r=0, si=tcp_listen; si; si=si->next, r++);
  3505. #ifdef USE_TLS
  3506. if (! tls_disable)
  3507. for (si=tls_listen; si; si=si->next, r++);
  3508. #endif
  3509. register_fds(r+tcp_max_connections+get_max_procs()-1 /* tcp main */);
  3510. #if 0
  3511. tcp_max_fd_no=get_max_procs()*2 +r-1 /* timer */ +3; /* stdin/out/err*/
  3512. /* max connections can be temporarily exceeded with estimated_process_count
  3513. * - tcp_main (tcpconn_connect called simultaneously in all all the
  3514. * processes) */
  3515. tcp_max_fd_no+=tcp_max_connections+get_max_procs()-1 /* tcp main */;
  3516. #endif
  3517. /* alloc the children array */
  3518. tcp_children=pkg_malloc(sizeof(struct tcp_child)*tcp_children_no);
  3519. if (tcp_children==0){
  3520. LOG(L_ERR, "ERROR: tcp_init_children: out of memory\n");
  3521. goto error;
  3522. }
  3523. /* create the tcp sock_info structures */
  3524. /* copy the sockets --moved to main_loop*/
  3525. /* fork children & create the socket pairs*/
  3526. for(r=0; r<tcp_children_no; r++){
  3527. child_rank++;
  3528. pid=fork_tcp_process(child_rank, "tcp receiver", r, &reader_fd_1);
  3529. if (pid<0){
  3530. LOG(L_ERR, "ERROR: tcp_main: fork failed: %s\n",
  3531. strerror(errno));
  3532. goto error;
  3533. }else if (pid>0){
  3534. /* parent */
  3535. }else{
  3536. /* child */
  3537. bind_address=0; /* force a SEGFAULT if someone uses a non-init.
  3538. bind address on tcp */
  3539. tcp_receive_loop(reader_fd_1);
  3540. }
  3541. }
  3542. return 0;
  3543. error:
  3544. return -1;
  3545. }
  3546. void tcp_get_info(struct tcp_gen_info *ti)
  3547. {
  3548. ti->tcp_readers=tcp_children_no;
  3549. ti->tcp_max_connections=tcp_max_connections;
  3550. ti->tcp_connections_no=*tcp_connections_no;
  3551. #ifdef TCP_BUF_WRITE
  3552. ti->tcp_write_queued=*tcp_total_wq;
  3553. #else
  3554. ti->tcp_write_queued=0;
  3555. #endif /* TCP_BUF_WRITE */
  3556. }
  3557. #endif