tcp_main.c 146 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900
  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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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. * 2009-02-26 direct blacklist support (andrei)
  101. * 2009-03-20 s/wq_timeout/send_timeout ; send_timeout is now in ticks
  102. * (andrei)
  103. * 2009-04-09 tcp ev and tcp stats macros added (andrei)
  104. * 2009-09-15 support for force connection reuse and close after send
  105. * send flags (andrei)
  106. * 2010-03-23 tcp_send() split in 3 smaller functions (andrei)
  107. */
  108. /** tcp main/dispatcher and tcp send functions.
  109. * @file tcp_main.c
  110. * @ingroup core
  111. * Module: @ref core
  112. */
  113. #ifdef USE_TCP
  114. #ifndef SHM_MEM
  115. #error "shared memory support needed (add -DSHM_MEM to Makefile.defs)"
  116. #endif
  117. #define HANDLE_IO_INLINE
  118. #include "io_wait.h" /* include first to make sure the needed features are
  119. turned on (e.g. _GNU_SOURCE for POLLRDHUP) */
  120. #include <sys/time.h>
  121. #include <sys/types.h>
  122. #include <sys/select.h>
  123. #include <sys/socket.h>
  124. #ifdef HAVE_FILIO_H
  125. #include <sys/filio.h> /* needed on solaris 2.x for FIONREAD */
  126. #elif defined __OS_solaris
  127. #define BSD_COMP /* needed on older solaris for FIONREAD */
  128. #endif /* HAVE_FILIO_H / __OS_solaris */
  129. #include <sys/ioctl.h> /* ioctl() used on write error */
  130. #include <netinet/in.h>
  131. #include <netinet/in_systm.h>
  132. #include <netinet/ip.h>
  133. #include <netinet/tcp.h>
  134. #include <sys/uio.h> /* writev*/
  135. #include <netdb.h>
  136. #include <stdlib.h> /*exit() */
  137. #include <unistd.h>
  138. #include <errno.h>
  139. #include <string.h>
  140. #ifdef HAVE_SELECT
  141. #include <sys/select.h>
  142. #endif
  143. #include <poll.h>
  144. #include "ip_addr.h"
  145. #include "pass_fd.h"
  146. #include "tcp_conn.h"
  147. #include "globals.h"
  148. #include "pt.h"
  149. #include "locking.h"
  150. #include "mem/mem.h"
  151. #include "mem/shm_mem.h"
  152. #include "timer.h"
  153. #include "sr_module.h"
  154. #include "tcp_server.h"
  155. #include "tcp_init.h"
  156. #include "tcp_int_send.h"
  157. #include "tcp_stats.h"
  158. #include "tcp_ev.h"
  159. #include "tsend.h"
  160. #include "timer_ticks.h"
  161. #include "local_timer.h"
  162. #ifdef CORE_TLS
  163. #include "tls/tls_server.h"
  164. #define tls_loaded() 1
  165. #else
  166. #include "tls_hooks_init.h"
  167. #include "tls_hooks.h"
  168. #endif /* CORE_TLS*/
  169. #ifdef USE_DST_BLACKLIST
  170. #include "dst_blacklist.h"
  171. #endif /* USE_DST_BLACKLIST */
  172. #include "tcp_info.h"
  173. #include "tcp_options.h"
  174. #include "ut.h"
  175. #include "cfg/cfg_struct.h"
  176. #define local_malloc pkg_malloc
  177. #define local_free pkg_free
  178. #include <fcntl.h> /* must be included after io_wait.h if SIGIO_RT is used */
  179. #ifdef NO_MSG_DONTWAIT
  180. #ifndef MSG_DONTWAIT
  181. /* should work inside tcp_main */
  182. #define MSG_DONTWAIT 0
  183. #endif
  184. #endif /*NO_MSG_DONTWAIT */
  185. #define TCP_PASS_NEW_CONNECTION_ON_DATA /* don't pass a new connection
  186. immediately to a child, wait for
  187. some data on it first */
  188. #define TCP_LISTEN_BACKLOG 1024
  189. #define SEND_FD_QUEUE /* queue send fd requests on EAGAIN, instead of sending
  190. them immediately */
  191. #define TCP_CHILD_NON_BLOCKING
  192. #ifdef SEND_FD_QUEUE
  193. #ifndef TCP_CHILD_NON_BLOCKING
  194. #define TCP_CHILD_NON_BLOCKING
  195. #endif
  196. #define MAX_SEND_FD_QUEUE_SIZE tcp_main_max_fd_no
  197. #define SEND_FD_QUEUE_SIZE 128 /* initial size */
  198. #define SEND_FD_QUEUE_TIMEOUT MS_TO_TICKS(2000) /* 2 s */
  199. #endif
  200. /* minimum interval local_timer_run() is allowed to run, in ticks */
  201. #define TCPCONN_TIMEOUT_MIN_RUN 1 /* once per tick */
  202. #define TCPCONN_WAIT_TIMEOUT 1 /* 1 tick */
  203. #ifdef TCP_ASYNC
  204. static unsigned int* tcp_total_wq=0;
  205. #endif
  206. enum fd_types { F_NONE, F_SOCKINFO /* a tcp_listen fd */,
  207. F_TCPCONN, F_TCPCHILD, F_PROC };
  208. #ifdef TCP_FD_CACHE
  209. #define TCP_FD_CACHE_SIZE 8
  210. struct fd_cache_entry{
  211. struct tcp_connection* con;
  212. int id;
  213. int fd;
  214. };
  215. static struct fd_cache_entry fd_cache[TCP_FD_CACHE_SIZE];
  216. #endif /* TCP_FD_CACHE */
  217. static int is_tcp_main=0;
  218. enum poll_types tcp_poll_method=0; /* by default choose the best method */
  219. int tcp_main_max_fd_no=0;
  220. int tcp_max_connections=DEFAULT_TCP_MAX_CONNECTIONS;
  221. int tls_max_connections=DEFAULT_TLS_MAX_CONNECTIONS;
  222. static union sockaddr_union tcp_source_ipv4_addr; /* saved bind/srv v4 addr. */
  223. static union sockaddr_union* tcp_source_ipv4=0;
  224. static union sockaddr_union tcp_source_ipv6_addr; /* saved bind/src v6 addr. */
  225. static union sockaddr_union* tcp_source_ipv6=0;
  226. static int* tcp_connections_no=0; /* current tcp (+tls) open connections */
  227. static int* tls_connections_no=0; /* current tls open connections */
  228. /* connection hash table (after ip&port) , includes also aliases */
  229. struct tcp_conn_alias** tcpconn_aliases_hash=0;
  230. /* connection hash table (after connection id) */
  231. struct tcp_connection** tcpconn_id_hash=0;
  232. gen_lock_t* tcpconn_lock=0;
  233. struct tcp_child* tcp_children=0;
  234. static int* connection_id=0; /* unique for each connection, used for
  235. quickly finding the corresponding connection
  236. for a reply */
  237. int unix_tcp_sock;
  238. static int tcp_proto_no=-1; /* tcp protocol number as returned by
  239. getprotobyname */
  240. static io_wait_h io_h;
  241. static struct local_timer tcp_main_ltimer;
  242. static ticks_t tcp_main_prev_ticks;
  243. /* tell if there are tcp workers that should handle only specific socket
  244. * - used to optimize the search of least loaded worker for a tcp socket
  245. * - 0 - no workers per tcp sockets have been set
  246. * - 1 + generic_workers - when there are workers per tcp sockets
  247. */
  248. static int tcp_sockets_gworkers = 0;
  249. static ticks_t tcpconn_main_timeout(ticks_t , struct timer_ln* , void* );
  250. inline static int _tcpconn_add_alias_unsafe(struct tcp_connection* c, int port,
  251. struct ip_addr* l_ip, int l_port,
  252. int flags);
  253. /* sets source address used when opening new sockets and no source is specified
  254. * (by default the address is choosen by the kernel)
  255. * Should be used only on init.
  256. * returns -1 on error */
  257. int tcp_set_src_addr(struct ip_addr* ip)
  258. {
  259. switch (ip->af){
  260. case AF_INET:
  261. ip_addr2su(&tcp_source_ipv4_addr, ip, 0);
  262. tcp_source_ipv4=&tcp_source_ipv4_addr;
  263. break;
  264. case AF_INET6:
  265. ip_addr2su(&tcp_source_ipv6_addr, ip, 0);
  266. tcp_source_ipv6=&tcp_source_ipv6_addr;
  267. break;
  268. default:
  269. return -1;
  270. }
  271. return 0;
  272. }
  273. static inline int init_sock_keepalive(int s)
  274. {
  275. int optval;
  276. #ifdef HAVE_SO_KEEPALIVE
  277. if (cfg_get(tcp, tcp_cfg, keepalive)){
  278. optval=1;
  279. if (setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, &optval,
  280. sizeof(optval))<0){
  281. LM_WARN("failed to enable SO_KEEPALIVE: %s\n", strerror(errno));
  282. return -1;
  283. }
  284. }
  285. #endif
  286. #ifdef HAVE_TCP_KEEPINTVL
  287. if ((optval=cfg_get(tcp, tcp_cfg, keepintvl))){
  288. if (setsockopt(s, IPPROTO_TCP, TCP_KEEPINTVL, &optval,
  289. sizeof(optval))<0){
  290. LM_WARN("failed to set keepalive probes interval: %s\n", strerror(errno));
  291. }
  292. }
  293. #endif
  294. #ifdef HAVE_TCP_KEEPIDLE
  295. if ((optval=cfg_get(tcp, tcp_cfg, keepidle))){
  296. if (setsockopt(s, IPPROTO_TCP, TCP_KEEPIDLE, &optval,
  297. sizeof(optval))<0){
  298. LM_WARN("failed to set keepalive idle interval: %s\n", strerror(errno));
  299. }
  300. }
  301. #endif
  302. #ifdef HAVE_TCP_KEEPCNT
  303. if ((optval=cfg_get(tcp, tcp_cfg, keepcnt))){
  304. if (setsockopt(s, IPPROTO_TCP, TCP_KEEPCNT, &optval,
  305. sizeof(optval))<0){
  306. LM_WARN("failed to set maximum keepalive count: %s\n", strerror(errno));
  307. }
  308. }
  309. #endif
  310. return 0;
  311. }
  312. /* set all socket/fd options for new sockets (e.g. before connect):
  313. * disable nagle, tos lowdelay, reuseaddr, non-blocking
  314. *
  315. * return -1 on error */
  316. static int init_sock_opt(int s, int af)
  317. {
  318. int flags;
  319. int optval;
  320. #ifdef DISABLE_NAGLE
  321. flags=1;
  322. if ( (tcp_proto_no!=-1) && (setsockopt(s, tcp_proto_no , TCP_NODELAY,
  323. &flags, sizeof(flags))<0) ){
  324. LM_WARN("could not disable Nagle: %s\n", strerror(errno));
  325. }
  326. #endif
  327. /* tos*/
  328. optval = tos;
  329. if(af==AF_INET){
  330. if (setsockopt(s, IPPROTO_IP, IP_TOS, (void*)&optval,
  331. sizeof(optval)) ==-1){
  332. LM_WARN("setsockopt tos: %s\n", strerror(errno));
  333. /* continue since this is not critical */
  334. }
  335. } else if(af==AF_INET6){
  336. if (setsockopt(s, IPPROTO_IPV6, IPV6_TCLASS,
  337. (void*)&optval, sizeof(optval)) ==-1) {
  338. LM_WARN("setsockopt v6 tos: %s\n", strerror(errno));
  339. /* continue since this is not critical */
  340. }
  341. }
  342. #if !defined(TCP_DONT_REUSEADDR)
  343. optval=1;
  344. if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR,
  345. (void*)&optval, sizeof(optval))==-1){
  346. LM_ERR("setsockopt SO_REUSEADDR %s\n", strerror(errno));
  347. /* continue, not critical */
  348. }
  349. #endif /* !TCP_DONT_REUSEADDR */
  350. #ifdef HAVE_TCP_SYNCNT
  351. if ((optval=cfg_get(tcp, tcp_cfg, syncnt))){
  352. if (setsockopt(s, IPPROTO_TCP, TCP_SYNCNT, &optval,
  353. sizeof(optval))<0){
  354. LM_WARN("failed to set maximum SYN retr. count: %s\n", strerror(errno));
  355. }
  356. }
  357. #endif
  358. #ifdef HAVE_TCP_LINGER2
  359. if ((optval=cfg_get(tcp, tcp_cfg, linger2))){
  360. if (setsockopt(s, IPPROTO_TCP, TCP_LINGER2, &optval,
  361. sizeof(optval))<0){
  362. LM_WARN("failed to set maximum LINGER2 timeout: %s\n", strerror(errno));
  363. }
  364. }
  365. #endif
  366. #ifdef HAVE_TCP_QUICKACK
  367. if (cfg_get(tcp, tcp_cfg, delayed_ack)){
  368. optval=0; /* reset quick ack => delayed ack */
  369. if (setsockopt(s, IPPROTO_TCP, TCP_QUICKACK, &optval,
  370. sizeof(optval))<0){
  371. LM_WARN("failed to reset TCP_QUICKACK: %s\n", strerror(errno));
  372. }
  373. }
  374. #endif /* HAVE_TCP_QUICKACK */
  375. init_sock_keepalive(s);
  376. /* non-blocking */
  377. flags=fcntl(s, F_GETFL);
  378. if (flags==-1){
  379. LM_ERR("fnctl failed: (%d) %s\n", errno, strerror(errno));
  380. goto error;
  381. }
  382. if (fcntl(s, F_SETFL, flags|O_NONBLOCK)==-1){
  383. LM_ERR("fcntl: set non-blocking failed: (%d) %s\n", errno, strerror(errno));
  384. goto error;
  385. }
  386. return 0;
  387. error:
  388. return -1;
  389. }
  390. /* set all socket/fd options for "accepted" sockets
  391. * only nonblocking is set since the rest is inherited from the
  392. * "parent" (listening) socket
  393. * Note: setting O_NONBLOCK is required on linux but it's not needed on
  394. * BSD and possibly solaris (where the flag is inherited from the
  395. * parent socket). However since there is no standard document
  396. * requiring a specific behaviour in this case it's safer to always set
  397. * it (at least for now) --andrei
  398. * TODO: check on which OSes O_NONBLOCK is inherited and make this
  399. * function a nop.
  400. *
  401. * return -1 on error */
  402. static int init_sock_opt_accept(int s)
  403. {
  404. int flags;
  405. /* non-blocking */
  406. flags=fcntl(s, F_GETFL);
  407. if (flags==-1){
  408. LM_ERR("fnctl failed: (%d) %s\n", errno, strerror(errno));
  409. goto error;
  410. }
  411. if (fcntl(s, F_SETFL, flags|O_NONBLOCK)==-1){
  412. LM_ERR("fcntl: set non-blocking failed: (%d) %s\n", errno, strerror(errno));
  413. goto error;
  414. }
  415. return 0;
  416. error:
  417. return -1;
  418. }
  419. /** close a socket, handling errno.
  420. * On EINTR, repeat the close().
  421. * Filter expected errors (return success if close() failed because
  422. * EPIPE, ECONNRST a.s.o). Note that this happens on *BSDs (on linux close()
  423. * does not fail for socket level errors).
  424. * @param s - open valid socket.
  425. * @return - 0 on success, < 0 on error (whatever close() returns). On error
  426. * errno is set.
  427. */
  428. static int tcp_safe_close(int s)
  429. {
  430. int ret;
  431. retry:
  432. if (unlikely((ret = close(s)) < 0 )) {
  433. switch(errno) {
  434. case EINTR:
  435. goto retry;
  436. case EPIPE:
  437. case ENOTCONN:
  438. case ECONNRESET:
  439. case ECONNREFUSED:
  440. case ENETUNREACH:
  441. case EHOSTUNREACH:
  442. /* on *BSD we really get these errors at close() time
  443. => ignore them */
  444. ret = 0;
  445. break;
  446. default:
  447. break;
  448. }
  449. }
  450. return ret;
  451. }
  452. /* blocking connect on a non-blocking fd; it will timeout after
  453. * tcp_connect_timeout
  454. * if BLOCKING_USE_SELECT and HAVE_SELECT are defined it will internally
  455. * use select() instead of poll (bad if fd > FD_SET_SIZE, poll is preferred)
  456. */
  457. static int tcp_blocking_connect(int fd, int type, snd_flags_t* send_flags,
  458. const struct sockaddr *servaddr,
  459. socklen_t addrlen)
  460. {
  461. int n;
  462. #if defined(HAVE_SELECT) && defined(BLOCKING_USE_SELECT)
  463. fd_set sel_set;
  464. fd_set orig_set;
  465. struct timeval timeout;
  466. #else
  467. struct pollfd pf;
  468. #endif
  469. int elapsed;
  470. int to;
  471. int ticks;
  472. int err;
  473. unsigned int err_len;
  474. int poll_err;
  475. poll_err=0;
  476. to=cfg_get(tcp, tcp_cfg, connect_timeout_s);
  477. ticks=get_ticks();
  478. again:
  479. n=connect(fd, servaddr, addrlen);
  480. if (n==-1){
  481. if (errno==EINTR){
  482. elapsed=(get_ticks()-ticks)*TIMER_TICK;
  483. if (elapsed<to) goto again;
  484. else goto error_timeout;
  485. }
  486. if (errno!=EINPROGRESS && errno!=EALREADY){
  487. goto error_errno;
  488. }
  489. }else goto end;
  490. /* poll/select loop */
  491. #if defined(HAVE_SELECT) && defined(BLOCKING_USE_SELECT)
  492. FD_ZERO(&orig_set);
  493. FD_SET(fd, &orig_set);
  494. #else
  495. pf.fd=fd;
  496. pf.events=POLLOUT;
  497. #endif
  498. while(1){
  499. elapsed=(get_ticks()-ticks)*TIMER_TICK;
  500. if (elapsed>=to)
  501. goto error_timeout;
  502. #if defined(HAVE_SELECT) && defined(BLOCKING_USE_SELECT)
  503. sel_set=orig_set;
  504. timeout.tv_sec=to-elapsed;
  505. timeout.tv_usec=0;
  506. n=select(fd+1, 0, &sel_set, 0, &timeout);
  507. #else
  508. n=poll(&pf, 1, (to-elapsed)*1000);
  509. #endif
  510. if (n<0){
  511. if (errno==EINTR) continue;
  512. LM_ERR("%s: poll/select failed: (%d) %s\n",
  513. su2a((union sockaddr_union*)servaddr, addrlen),
  514. errno, strerror(errno));
  515. goto error;
  516. }else if (n==0) /* timeout */ continue;
  517. #if defined(HAVE_SELECT) && defined(BLOCKING_USE_SELECT)
  518. if (FD_ISSET(fd, &sel_set))
  519. #else
  520. if (pf.revents&(POLLERR|POLLHUP|POLLNVAL)){
  521. LM_ERR("%s: poll error: flags %x\n",
  522. su2a((union sockaddr_union*)servaddr, addrlen),
  523. pf.revents);
  524. poll_err=1;
  525. }
  526. #endif
  527. {
  528. err_len=sizeof(err);
  529. getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &err_len);
  530. if ((err==0) && (poll_err==0)) goto end;
  531. if (err!=EINPROGRESS && err!=EALREADY){
  532. LM_ERR("%s: SO_ERROR (%d) %s\n",
  533. su2a((union sockaddr_union*)servaddr, addrlen),
  534. err, strerror(err));
  535. errno=err;
  536. goto error_errno;
  537. }
  538. }
  539. }
  540. error_errno:
  541. switch(errno){
  542. case ENETUNREACH:
  543. case EHOSTUNREACH:
  544. #ifdef USE_DST_BLACKLIST
  545. dst_blacklist_su(BLST_ERR_CONNECT, type,
  546. (union sockaddr_union*)servaddr, send_flags, 0);
  547. #endif /* USE_DST_BLACKLIST */
  548. TCP_EV_CONNECT_UNREACHABLE(errno, 0, 0,
  549. (union sockaddr_union*)servaddr, type);
  550. break;
  551. case ETIMEDOUT:
  552. #ifdef USE_DST_BLACKLIST
  553. dst_blacklist_su(BLST_ERR_CONNECT, type,
  554. (union sockaddr_union*)servaddr, send_flags, 0);
  555. #endif /* USE_DST_BLACKLIST */
  556. TCP_EV_CONNECT_TIMEOUT(errno, 0, 0,
  557. (union sockaddr_union*)servaddr, type);
  558. break;
  559. case ECONNREFUSED:
  560. case ECONNRESET:
  561. #ifdef USE_DST_BLACKLIST
  562. dst_blacklist_su(BLST_ERR_CONNECT, type,
  563. (union sockaddr_union*)servaddr, send_flags, 0);
  564. #endif /* USE_DST_BLACKLIST */
  565. TCP_EV_CONNECT_RST(errno, 0, 0,
  566. (union sockaddr_union*)servaddr, type);
  567. break;
  568. case EAGAIN: /* not posix, but supported on linux and bsd */
  569. TCP_EV_CONNECT_NO_MORE_PORTS(errno, 0, 0,
  570. (union sockaddr_union*)servaddr, type);
  571. break;
  572. default:
  573. TCP_EV_CONNECT_ERR(errno, 0, 0,
  574. (union sockaddr_union*)servaddr, type);
  575. }
  576. LM_ERR("%s: (%d) %s\n",
  577. su2a((union sockaddr_union*)servaddr, addrlen),
  578. errno, strerror(errno));
  579. goto error;
  580. error_timeout:
  581. /* timeout */
  582. #ifdef USE_DST_BLACKLIST
  583. dst_blacklist_su(BLST_ERR_CONNECT, type,
  584. (union sockaddr_union*)servaddr, send_flags, 0);
  585. #endif /* USE_DST_BLACKLIST */
  586. TCP_EV_CONNECT_TIMEOUT(0, 0, 0, (union sockaddr_union*)servaddr, type);
  587. LM_ERR("%s: timeout %d s elapsed from %d s\n",
  588. su2a((union sockaddr_union*)servaddr, addrlen),
  589. elapsed, cfg_get(tcp, tcp_cfg, connect_timeout_s));
  590. error:
  591. TCP_STATS_CONNECT_FAILED();
  592. return -1;
  593. end:
  594. return 0;
  595. }
  596. #ifdef TCP_ASYNC
  597. /* unsafe version */
  598. #define _wbufq_empty(con) ((con)->wbuf_q.first==0)
  599. /* unsafe version */
  600. #define _wbufq_non_empty(con) ((con)->wbuf_q.first!=0)
  601. /* unsafe version, call while holding the connection write lock */
  602. inline static int _wbufq_add(struct tcp_connection* c, const char* data,
  603. unsigned int size)
  604. {
  605. struct tcp_wbuffer_queue* q;
  606. struct tcp_wbuffer* wb;
  607. unsigned int last_free;
  608. unsigned int wb_size;
  609. unsigned int crt_size;
  610. ticks_t t;
  611. q=&c->wbuf_q;
  612. t=get_ticks_raw();
  613. if (unlikely( ((q->queued+size)>cfg_get(tcp, tcp_cfg, tcpconn_wq_max)) ||
  614. ((*tcp_total_wq+size)>cfg_get(tcp, tcp_cfg, tcp_wq_max)) ||
  615. (q->first &&
  616. TICKS_LT(q->wr_timeout, t)) )){
  617. LM_ERR("(%d bytes): write queue full or timeout "
  618. " (%d, total %d, last write %d s ago)\n",
  619. size, q->queued, *tcp_total_wq,
  620. TICKS_TO_S(t-(q->wr_timeout-
  621. cfg_get(tcp, tcp_cfg, send_timeout))));
  622. if (q->first && TICKS_LT(q->wr_timeout, t)){
  623. if (unlikely(c->state==S_CONN_CONNECT)){
  624. #ifdef USE_DST_BLACKLIST
  625. (void)dst_blacklist_su( BLST_ERR_CONNECT, c->rcv.proto,
  626. &c->rcv.src_su, &c->send_flags, 0);
  627. #endif /* USE_DST_BLACKLIST */
  628. TCP_EV_CONNECT_TIMEOUT(0, TCP_LADDR(c), TCP_LPORT(c),
  629. TCP_PSU(c), TCP_PROTO(c));
  630. TCP_STATS_CONNECT_FAILED();
  631. }else{
  632. #ifdef USE_DST_BLACKLIST
  633. (void)dst_blacklist_su( BLST_ERR_SEND, c->rcv.proto,
  634. &c->rcv.src_su, &c->send_flags, 0);
  635. #endif /* USE_DST_BLACKLIST */
  636. TCP_EV_SEND_TIMEOUT(0, &c->rcv);
  637. TCP_STATS_SEND_TIMEOUT();
  638. }
  639. }else{
  640. /* if it's not a timeout => queue full */
  641. TCP_EV_SENDQ_FULL(0, &c->rcv);
  642. TCP_STATS_SENDQ_FULL();
  643. }
  644. goto error;
  645. }
  646. if (unlikely(q->last==0)){
  647. wb_size=MAX_unsigned(cfg_get(tcp, tcp_cfg, wq_blk_size), size);
  648. wb=shm_malloc(sizeof(*wb)+wb_size-1);
  649. if (unlikely(wb==0))
  650. goto error;
  651. wb->b_size=wb_size;
  652. wb->next=0;
  653. q->last=wb;
  654. q->first=wb;
  655. q->last_used=0;
  656. q->offset=0;
  657. q->wr_timeout=get_ticks_raw()+
  658. ((c->state==S_CONN_CONNECT)?
  659. S_TO_TICKS(cfg_get(tcp, tcp_cfg, connect_timeout_s)):
  660. cfg_get(tcp, tcp_cfg, send_timeout));
  661. }else{
  662. wb=q->last;
  663. }
  664. while(size){
  665. last_free=wb->b_size-q->last_used;
  666. if (last_free==0){
  667. wb_size=MAX_unsigned(cfg_get(tcp, tcp_cfg, wq_blk_size), size);
  668. wb=shm_malloc(sizeof(*wb)+wb_size-1);
  669. if (unlikely(wb==0))
  670. goto error;
  671. wb->b_size=wb_size;
  672. wb->next=0;
  673. q->last->next=wb;
  674. q->last=wb;
  675. q->last_used=0;
  676. last_free=wb->b_size;
  677. }
  678. crt_size=MIN_unsigned(last_free, size);
  679. memcpy(wb->buf+q->last_used, data, crt_size);
  680. q->last_used+=crt_size;
  681. size-=crt_size;
  682. data+=crt_size;
  683. q->queued+=crt_size;
  684. atomic_add_int((int*)tcp_total_wq, crt_size);
  685. }
  686. return 0;
  687. error:
  688. return -1;
  689. }
  690. /* unsafe version, call while holding the connection write lock
  691. * inserts data at the beginning, it ignores the max queue size checks and
  692. * the timeout (use sparingly)
  693. * Note: it should never be called on a write buffer after wbufq_run() */
  694. inline static int _wbufq_insert(struct tcp_connection* c, const char* data,
  695. unsigned int size)
  696. {
  697. struct tcp_wbuffer_queue* q;
  698. struct tcp_wbuffer* wb;
  699. q=&c->wbuf_q;
  700. if (likely(q->first==0)) /* if empty, use wbufq_add */
  701. return _wbufq_add(c, data, size);
  702. if (unlikely((*tcp_total_wq+size)>cfg_get(tcp, tcp_cfg, tcp_wq_max))){
  703. LM_ERR("(%d bytes): write queue full"
  704. " (%d, total %d, last write %d s ago)\n",
  705. size, q->queued, *tcp_total_wq,
  706. TICKS_TO_S(get_ticks_raw()-q->wr_timeout-
  707. cfg_get(tcp, tcp_cfg, send_timeout)));
  708. goto error;
  709. }
  710. if (unlikely(q->offset)){
  711. LM_CRIT("non-null offset %d (bad call, should"
  712. "never be called after the wbufq_run())\n", q->offset);
  713. goto error;
  714. }
  715. if ((q->first==q->last) && ((q->last->b_size-q->last_used)>=size)){
  716. /* one block with enough space in it for size bytes */
  717. memmove(q->first->buf+size, q->first->buf, q->last_used);
  718. memcpy(q->first->buf, data, size);
  719. q->last_used+=size;
  720. }else{
  721. /* create a size bytes block directly */
  722. wb=shm_malloc(sizeof(*wb)+size-1);
  723. if (unlikely(wb==0))
  724. goto error;
  725. wb->b_size=size;
  726. /* insert it */
  727. wb->next=q->first;
  728. q->first=wb;
  729. memcpy(wb->buf, data, size);
  730. }
  731. q->queued+=size;
  732. atomic_add_int((int*)tcp_total_wq, size);
  733. return 0;
  734. error:
  735. return -1;
  736. }
  737. /* unsafe version, call while holding the connection write lock */
  738. inline static void _wbufq_destroy( struct tcp_wbuffer_queue* q)
  739. {
  740. struct tcp_wbuffer* wb;
  741. struct tcp_wbuffer* next_wb;
  742. int unqueued;
  743. unqueued=0;
  744. if (likely(q->first)){
  745. wb=q->first;
  746. do{
  747. next_wb=wb->next;
  748. unqueued+=(wb==q->last)?q->last_used:wb->b_size;
  749. if (wb==q->first)
  750. unqueued-=q->offset;
  751. shm_free(wb);
  752. wb=next_wb;
  753. }while(wb);
  754. }
  755. memset(q, 0, sizeof(*q));
  756. atomic_add_int((int*)tcp_total_wq, -unqueued);
  757. }
  758. /* tries to empty the queue (safe version, c->write_lock must not be hold)
  759. * returns -1 on error, bytes written on success (>=0)
  760. * if the whole queue is emptied => sets *empty*/
  761. inline static int wbufq_run(int fd, struct tcp_connection* c, int* empty)
  762. {
  763. struct tcp_wbuffer_queue* q;
  764. struct tcp_wbuffer* wb;
  765. int n;
  766. int ret;
  767. int block_size;
  768. char* buf;
  769. *empty=0;
  770. ret=0;
  771. lock_get(&c->write_lock);
  772. q=&c->wbuf_q;
  773. while(q->first){
  774. block_size=((q->first==q->last)?q->last_used:q->first->b_size)-
  775. q->offset;
  776. buf=q->first->buf+q->offset;
  777. n=_tcpconn_write_nb(fd, c, buf, block_size);
  778. if (likely(n>0)){
  779. ret+=n;
  780. if (likely(n==block_size)){
  781. wb=q->first;
  782. q->first=q->first->next;
  783. shm_free(wb);
  784. q->offset=0;
  785. q->queued-=block_size;
  786. atomic_add_int((int*)tcp_total_wq, -block_size);
  787. }else{
  788. q->offset+=n;
  789. q->queued-=n;
  790. atomic_add_int((int*)tcp_total_wq, -n);
  791. break;
  792. }
  793. }else{
  794. if (n<0){
  795. /* EINTR is handled inside _tcpconn_write_nb */
  796. if (!(errno==EAGAIN || errno==EWOULDBLOCK)){
  797. if (unlikely(c->state==S_CONN_CONNECT)){
  798. switch(errno){
  799. case ENETUNREACH:
  800. case EHOSTUNREACH: /* not posix for send() */
  801. #ifdef USE_DST_BLACKLIST
  802. dst_blacklist_su(BLST_ERR_CONNECT,
  803. c->rcv.proto,
  804. &c->rcv.src_su,
  805. &c->send_flags, 0);
  806. #endif /* USE_DST_BLACKLIST */
  807. TCP_EV_CONNECT_UNREACHABLE(errno, TCP_LADDR(c),
  808. TCP_LPORT(c), TCP_PSU(c),
  809. TCP_PROTO(c));
  810. break;
  811. case ECONNREFUSED:
  812. case ECONNRESET:
  813. #ifdef USE_DST_BLACKLIST
  814. dst_blacklist_su(BLST_ERR_CONNECT,
  815. c->rcv.proto,
  816. &c->rcv.src_su,
  817. &c->send_flags, 0);
  818. #endif /* USE_DST_BLACKLIST */
  819. TCP_EV_CONNECT_RST(0, TCP_LADDR(c),
  820. TCP_LPORT(c), TCP_PSU(c),
  821. TCP_PROTO(c));
  822. break;
  823. default:
  824. TCP_EV_CONNECT_ERR(errno, TCP_LADDR(c),
  825. TCP_LPORT(c), TCP_PSU(c),
  826. TCP_PROTO(c));
  827. }
  828. TCP_STATS_CONNECT_FAILED();
  829. }else{
  830. switch(errno){
  831. case ECONNREFUSED:
  832. case ECONNRESET:
  833. TCP_STATS_CON_RESET();
  834. /* no break */
  835. case ENETUNREACH:
  836. case EHOSTUNREACH: /* not posix for send() */
  837. #ifdef USE_DST_BLACKLIST
  838. dst_blacklist_su(BLST_ERR_SEND,
  839. c->rcv.proto,
  840. &c->rcv.src_su,
  841. &c->send_flags, 0);
  842. #endif /* USE_DST_BLACKLIST */
  843. break;
  844. }
  845. }
  846. ret=-1;
  847. LM_ERR("%s [%d]\n", strerror(errno), errno);
  848. }
  849. }
  850. break;
  851. }
  852. }
  853. if (likely(q->first==0)){
  854. q->last=0;
  855. q->last_used=0;
  856. q->offset=0;
  857. *empty=1;
  858. }
  859. lock_release(&c->write_lock);
  860. if (likely(ret>0)){
  861. q->wr_timeout=get_ticks_raw()+cfg_get(tcp, tcp_cfg, send_timeout);
  862. if (unlikely(c->state==S_CONN_CONNECT || c->state==S_CONN_ACCEPT)){
  863. TCP_STATS_ESTABLISHED(c->state);
  864. c->state=S_CONN_OK;
  865. }
  866. }
  867. return ret;
  868. }
  869. #endif /* TCP_ASYNC */
  870. #if 0
  871. /* blocking write even on non-blocking sockets
  872. * if TCP_TIMEOUT will return with error */
  873. static int tcp_blocking_write(struct tcp_connection* c, int fd, char* buf,
  874. unsigned int len)
  875. {
  876. int n;
  877. fd_set sel_set;
  878. struct timeval timeout;
  879. int ticks;
  880. int initial_len;
  881. initial_len=len;
  882. again:
  883. n=send(fd, buf, len,
  884. #ifdef HAVE_MSG_NOSIGNAL
  885. MSG_NOSIGNAL
  886. #else
  887. 0
  888. #endif
  889. );
  890. if (n<0){
  891. if (errno==EINTR) goto again;
  892. else if (errno!=EAGAIN && errno!=EWOULDBLOCK){
  893. LM_ERR("failed to send: (%d) %s\n", errno, strerror(errno));
  894. TCP_EV_SEND_TIMEOUT(errno, &c->rcv);
  895. TCP_STATS_SEND_TIMEOUT();
  896. goto error;
  897. }
  898. }else if (n<len){
  899. /* partial write */
  900. buf+=n;
  901. len-=n;
  902. }else{
  903. /* success: full write */
  904. goto end;
  905. }
  906. while(1){
  907. FD_ZERO(&sel_set);
  908. FD_SET(fd, &sel_set);
  909. timeout.tv_sec=tcp_send_timeout;
  910. timeout.tv_usec=0;
  911. ticks=get_ticks();
  912. n=select(fd+1, 0, &sel_set, 0, &timeout);
  913. if (n<0){
  914. if (errno==EINTR) continue; /* signal, ignore */
  915. LM_ERR("select failed: (%d) %s\n", errno, strerror(errno));
  916. goto error;
  917. }else if (n==0){
  918. /* timeout */
  919. if (get_ticks()-ticks>=tcp_send_timeout){
  920. LM_ERR("send timeout (%d)\n", tcp_send_timeout);
  921. goto error;
  922. }
  923. continue;
  924. }
  925. if (FD_ISSET(fd, &sel_set)){
  926. /* we can write again */
  927. goto again;
  928. }
  929. }
  930. error:
  931. return -1;
  932. end:
  933. return initial_len;
  934. }
  935. #endif
  936. struct tcp_connection* tcpconn_new(int sock, union sockaddr_union* su,
  937. union sockaddr_union* local_addr,
  938. struct socket_info* ba, int type,
  939. int state)
  940. {
  941. struct tcp_connection *c;
  942. int rd_b_size;
  943. rd_b_size=cfg_get(tcp, tcp_cfg, rd_buf_size);
  944. c=shm_malloc(sizeof(struct tcp_connection) + rd_b_size);
  945. if (c==0){
  946. LM_ERR("mem. allocation failure\n");
  947. goto error;
  948. }
  949. memset(c, 0, sizeof(struct tcp_connection)); /* zero init (skip rd buf)*/
  950. c->s=sock;
  951. c->fd=-1; /* not initialized */
  952. if (lock_init(&c->write_lock)==0){
  953. LM_ERR("init lock failed\n");
  954. goto error;
  955. }
  956. c->rcv.src_su=*su;
  957. atomic_set(&c->refcnt, 0);
  958. local_timer_init(&c->timer, tcpconn_main_timeout, c, 0);
  959. su2ip_addr(&c->rcv.src_ip, su);
  960. c->rcv.src_port=su_getport(su);
  961. c->rcv.bind_address=ba;
  962. if (likely(local_addr)){
  963. su2ip_addr(&c->rcv.dst_ip, local_addr);
  964. c->rcv.dst_port=su_getport(local_addr);
  965. }else if (ba){
  966. c->rcv.dst_ip=ba->address;
  967. c->rcv.dst_port=ba->port_no;
  968. }
  969. print_ip("tcpconn_new: new tcp connection: ", &c->rcv.src_ip, "\n");
  970. DBG( "tcpconn_new: on port %d, type %d\n", c->rcv.src_port, type);
  971. init_tcp_req(&c->req, (char*)c+sizeof(struct tcp_connection), rd_b_size);
  972. c->id=(*connection_id)++;
  973. c->rcv.proto_reserved1=0; /* this will be filled before receive_message*/
  974. c->rcv.proto_reserved2=0;
  975. c->state=state;
  976. c->extra_data=0;
  977. #ifdef USE_TLS
  978. if (type==PROTO_TLS){
  979. if (tls_tcpconn_init(c, sock)==-1) goto error;
  980. }else
  981. #endif /* USE_TLS*/
  982. {
  983. c->type=PROTO_TCP;
  984. c->rcv.proto=PROTO_TCP;
  985. c->timeout=get_ticks_raw()+cfg_get(tcp, tcp_cfg, con_lifetime);
  986. }
  987. return c;
  988. error:
  989. if (c) shm_free(c);
  990. return 0;
  991. }
  992. /* do the actual connect, set sock. options a.s.o
  993. * returns socket on success, -1 on error
  994. * sets also *res_local_addr, res_si and state (S_CONN_CONNECT for an
  995. * unfinished connect and S_CONN_OK for a finished one)*/
  996. inline static int tcp_do_connect( union sockaddr_union* server,
  997. union sockaddr_union* from,
  998. int type,
  999. snd_flags_t* send_flags,
  1000. union sockaddr_union* res_local_addr,
  1001. struct socket_info** res_si,
  1002. enum tcp_conn_states *state
  1003. )
  1004. {
  1005. int s;
  1006. union sockaddr_union my_name;
  1007. socklen_t my_name_len;
  1008. struct ip_addr ip;
  1009. #ifdef TCP_ASYNC
  1010. int n;
  1011. #endif /* TCP_ASYNC */
  1012. s=socket(AF2PF(server->s.sa_family), SOCK_STREAM, 0);
  1013. if (unlikely(s==-1)){
  1014. LM_ERR("%s: socket: (%d) %s\n",
  1015. su2a(server, sizeof(*server)), errno, strerror(errno));
  1016. goto error;
  1017. }
  1018. if (init_sock_opt(s, server->s.sa_family)<0){
  1019. LM_ERR("%s: init_sock_opt failed\n",
  1020. su2a(server, sizeof(*server)));
  1021. goto error;
  1022. }
  1023. if (unlikely(from && bind(s, &from->s, sockaddru_len(*from)) != 0)){
  1024. LM_WARN("binding to source address %s failed: %s [%d]\n",
  1025. su2a(from, sizeof(*from)),
  1026. strerror(errno), errno);
  1027. }
  1028. *state=S_CONN_OK;
  1029. #ifdef TCP_ASYNC
  1030. if (likely(cfg_get(tcp, tcp_cfg, async))){
  1031. again:
  1032. n=connect(s, &server->s, sockaddru_len(*server));
  1033. if (likely(n==-1)){ /*non-blocking => most probable EINPROGRESS*/
  1034. if (likely(errno==EINPROGRESS))
  1035. *state=S_CONN_CONNECT;
  1036. else if (errno==EINTR) goto again;
  1037. else if (errno!=EALREADY){
  1038. switch(errno){
  1039. case ENETUNREACH:
  1040. case EHOSTUNREACH:
  1041. #ifdef USE_DST_BLACKLIST
  1042. dst_blacklist_su(BLST_ERR_CONNECT, type, server,
  1043. send_flags, 0);
  1044. #endif /* USE_DST_BLACKLIST */
  1045. TCP_EV_CONNECT_UNREACHABLE(errno, 0, 0, server, type);
  1046. break;
  1047. case ETIMEDOUT:
  1048. #ifdef USE_DST_BLACKLIST
  1049. dst_blacklist_su(BLST_ERR_CONNECT, type, server,
  1050. send_flags, 0);
  1051. #endif /* USE_DST_BLACKLIST */
  1052. TCP_EV_CONNECT_TIMEOUT(errno, 0, 0, server, type);
  1053. break;
  1054. case ECONNREFUSED:
  1055. case ECONNRESET:
  1056. #ifdef USE_DST_BLACKLIST
  1057. dst_blacklist_su(BLST_ERR_CONNECT, type, server,
  1058. send_flags, 0);
  1059. #endif /* USE_DST_BLACKLIST */
  1060. TCP_EV_CONNECT_RST(errno, 0, 0, server, type);
  1061. break;
  1062. case EAGAIN:/* not posix, but supported on linux and bsd */
  1063. TCP_EV_CONNECT_NO_MORE_PORTS(errno, 0, 0, server,type);
  1064. break;
  1065. default:
  1066. TCP_EV_CONNECT_ERR(errno, 0, 0, server, type);
  1067. }
  1068. TCP_STATS_CONNECT_FAILED();
  1069. LM_ERR("connect %s: (%d) %s\n",
  1070. su2a(server, sizeof(*server)),
  1071. errno, strerror(errno));
  1072. goto error;
  1073. }
  1074. }
  1075. }else{
  1076. #endif /* TCP_ASYNC */
  1077. if (tcp_blocking_connect(s, type, send_flags, &server->s,
  1078. sockaddru_len(*server))<0){
  1079. LM_ERR("tcp_blocking_connect %s failed\n",
  1080. su2a(server, sizeof(*server)));
  1081. goto error;
  1082. }
  1083. #ifdef TCP_ASYNC
  1084. }
  1085. #endif /* TCP_ASYNC */
  1086. if (from){
  1087. su2ip_addr(&ip, from);
  1088. if (!ip_addr_any(&ip))
  1089. /* we already know the source ip, skip the sys. call */
  1090. goto find_socket;
  1091. }
  1092. my_name_len=sizeof(my_name);
  1093. if (unlikely(getsockname(s, &my_name.s, &my_name_len)!=0)){
  1094. LM_ERR("getsockname failed: %s(%d)\n", strerror(errno), errno);
  1095. *res_si=0;
  1096. goto error;
  1097. }
  1098. from=&my_name; /* update from with the real "from" address */
  1099. su2ip_addr(&ip, &my_name);
  1100. find_socket:
  1101. #ifdef USE_TLS
  1102. if (unlikely(type==PROTO_TLS))
  1103. *res_si=find_si(&ip, 0, PROTO_TLS);
  1104. else
  1105. #endif
  1106. *res_si=find_si(&ip, 0, PROTO_TCP);
  1107. if (unlikely(*res_si==0)){
  1108. LM_WARN("%s: could not find corresponding"
  1109. " listening socket for %s, using default...\n",
  1110. su2a(server, sizeof(*server)), ip_addr2a(&ip));
  1111. if (server->s.sa_family==AF_INET) *res_si=sendipv4_tcp;
  1112. else *res_si=sendipv6_tcp;
  1113. }
  1114. *res_local_addr=*from;
  1115. return s;
  1116. error:
  1117. if (s!=-1) tcp_safe_close(s);
  1118. return -1;
  1119. }
  1120. struct tcp_connection* tcpconn_connect( union sockaddr_union* server,
  1121. union sockaddr_union* from,
  1122. int type, snd_flags_t* send_flags)
  1123. {
  1124. int s;
  1125. struct socket_info* si;
  1126. union sockaddr_union my_name;
  1127. struct tcp_connection* con;
  1128. enum tcp_conn_states state;
  1129. s=-1;
  1130. if (*tcp_connections_no >= cfg_get(tcp, tcp_cfg, max_connections)){
  1131. LM_ERR("maximum number of connections exceeded (%d/%d)\n",
  1132. *tcp_connections_no,
  1133. cfg_get(tcp, tcp_cfg, max_connections));
  1134. goto error;
  1135. }
  1136. if (unlikely(type==PROTO_TLS)) {
  1137. if (*tls_connections_no >= cfg_get(tcp, tcp_cfg, max_tls_connections)){
  1138. LM_ERR("maximum number of tls connections"
  1139. " exceeded (%d/%d)\n",
  1140. *tls_connections_no,
  1141. cfg_get(tcp, tcp_cfg, max_tls_connections));
  1142. goto error;
  1143. }
  1144. }
  1145. s=tcp_do_connect(server, from, type, send_flags, &my_name, &si, &state);
  1146. if (s==-1){
  1147. LM_ERR("tcp_do_connect %s: failed (%d) %s\n",
  1148. su2a(server, sizeof(*server)), errno, strerror(errno));
  1149. goto error;
  1150. }
  1151. con=tcpconn_new(s, server, &my_name, si, type, state);
  1152. if (con==0){
  1153. LM_ERR("%s: tcpconn_new failed, closing the "
  1154. " socket\n", su2a(server, sizeof(*server)));
  1155. goto error;
  1156. }
  1157. tcpconn_set_send_flags(con, *send_flags);
  1158. return con;
  1159. error:
  1160. if (s!=-1) tcp_safe_close(s); /* close the opened socket */
  1161. return 0;
  1162. }
  1163. #ifdef TCP_CONNECT_WAIT
  1164. int tcpconn_finish_connect( struct tcp_connection* c,
  1165. union sockaddr_union* from)
  1166. {
  1167. int s;
  1168. int r;
  1169. union sockaddr_union local_addr;
  1170. struct socket_info* si;
  1171. enum tcp_conn_states state;
  1172. struct tcp_conn_alias* a;
  1173. int new_conn_alias_flags;
  1174. s=tcp_do_connect(&c->rcv.src_su, from, c->type, &c->send_flags,
  1175. &local_addr, &si, &state);
  1176. if (unlikely(s==-1)){
  1177. LM_ERR("%s: tcp_do_connect for %p failed\n",
  1178. su2a(&c->rcv.src_su, sizeof(c->rcv.src_su)), c);
  1179. return -1;
  1180. }
  1181. c->rcv.bind_address=si;
  1182. su2ip_addr(&c->rcv.dst_ip, &local_addr);
  1183. c->rcv.dst_port=su_getport(&local_addr);
  1184. /* update aliases if needed */
  1185. if (likely(from==0)){
  1186. new_conn_alias_flags=cfg_get(tcp, tcp_cfg, new_conn_alias_flags);
  1187. /* add aliases */
  1188. TCPCONN_LOCK;
  1189. _tcpconn_add_alias_unsafe(c, c->rcv.src_port, &c->rcv.dst_ip, 0,
  1190. new_conn_alias_flags);
  1191. _tcpconn_add_alias_unsafe(c, c->rcv.src_port, &c->rcv.dst_ip,
  1192. c->rcv.dst_port, new_conn_alias_flags);
  1193. TCPCONN_UNLOCK;
  1194. }else if (su_cmp(from, &local_addr)!=1){
  1195. new_conn_alias_flags=cfg_get(tcp, tcp_cfg, new_conn_alias_flags);
  1196. TCPCONN_LOCK;
  1197. /* remove all the aliases except the first one and re-add them
  1198. * (there shouldn't be more then the 3 default aliases at this
  1199. * stage) */
  1200. if (c->aliases > 1) {
  1201. for (r=1; r<c->aliases; r++){
  1202. a=&c->con_aliases[r];
  1203. tcpconn_listrm(tcpconn_aliases_hash[a->hash],
  1204. a, next, prev);
  1205. }
  1206. c->aliases=1;
  1207. }
  1208. /* add the local_ip:0 and local_ip:local_port aliases */
  1209. _tcpconn_add_alias_unsafe(c, c->rcv.src_port, &c->rcv.dst_ip,
  1210. 0, new_conn_alias_flags);
  1211. _tcpconn_add_alias_unsafe(c, c->rcv.src_port, &c->rcv.dst_ip,
  1212. c->rcv.dst_port, new_conn_alias_flags);
  1213. TCPCONN_UNLOCK;
  1214. }
  1215. return s;
  1216. }
  1217. #endif /* TCP_CONNECT_WAIT */
  1218. /* adds a tcp connection to the tcpconn hashes
  1219. * Note: it's called _only_ from the tcp_main process */
  1220. inline static struct tcp_connection* tcpconn_add(struct tcp_connection *c)
  1221. {
  1222. struct ip_addr zero_ip;
  1223. int new_conn_alias_flags;
  1224. if (likely(c)){
  1225. ip_addr_mk_any(c->rcv.src_ip.af, &zero_ip);
  1226. c->id_hash=tcp_id_hash(c->id);
  1227. c->aliases=0;
  1228. new_conn_alias_flags=cfg_get(tcp, tcp_cfg, new_conn_alias_flags);
  1229. TCPCONN_LOCK;
  1230. c->flags|=F_CONN_HASHED;
  1231. /* add it at the begining of the list*/
  1232. tcpconn_listadd(tcpconn_id_hash[c->id_hash], c, id_next, id_prev);
  1233. /* set the aliases */
  1234. /* first alias is for (peer_ip, peer_port, 0 ,0) -- for finding
  1235. * any connection to peer_ip, peer_port
  1236. * the second alias is for (peer_ip, peer_port, local_addr, 0) -- for
  1237. * finding any conenction to peer_ip, peer_port from local_addr
  1238. * the third alias is for (peer_ip, peer_port, local_addr, local_port)
  1239. * -- for finding if a fully specified connection exists */
  1240. _tcpconn_add_alias_unsafe(c, c->rcv.src_port, &zero_ip, 0,
  1241. new_conn_alias_flags);
  1242. if (likely(c->rcv.dst_ip.af && ! ip_addr_any(&c->rcv.dst_ip))){
  1243. _tcpconn_add_alias_unsafe(c, c->rcv.src_port, &c->rcv.dst_ip, 0,
  1244. new_conn_alias_flags);
  1245. _tcpconn_add_alias_unsafe(c, c->rcv.src_port, &c->rcv.dst_ip,
  1246. c->rcv.dst_port, new_conn_alias_flags);
  1247. }
  1248. /* ignore add_alias errors, there are some valid cases when one
  1249. * of the add_alias would fail (e.g. first add_alias for 2 connections
  1250. * with the same destination but different src. ip*/
  1251. TCPCONN_UNLOCK;
  1252. DBG("tcpconn_add: hashes: %d:%d:%d, %d\n",
  1253. c->con_aliases[0].hash,
  1254. c->con_aliases[1].hash,
  1255. c->con_aliases[2].hash,
  1256. c->id_hash);
  1257. return c;
  1258. }else{
  1259. LM_CRIT("null connection pointer\n");
  1260. return 0;
  1261. }
  1262. }
  1263. static inline void _tcpconn_detach(struct tcp_connection *c)
  1264. {
  1265. int r;
  1266. tcpconn_listrm(tcpconn_id_hash[c->id_hash], c, id_next, id_prev);
  1267. /* remove all the aliases */
  1268. for (r=0; r<c->aliases; r++)
  1269. tcpconn_listrm(tcpconn_aliases_hash[c->con_aliases[r].hash],
  1270. &c->con_aliases[r], next, prev);
  1271. c->aliases = 0;
  1272. }
  1273. static inline void _tcpconn_free(struct tcp_connection* c)
  1274. {
  1275. #ifdef TCP_ASYNC
  1276. if (unlikely(_wbufq_non_empty(c)))
  1277. _wbufq_destroy(&c->wbuf_q);
  1278. #endif
  1279. lock_destroy(&c->write_lock);
  1280. #ifdef USE_TLS
  1281. if (unlikely(c->type==PROTO_TLS || c->type==PROTO_WSS)) tls_tcpconn_clean(c);
  1282. #endif
  1283. shm_free(c);
  1284. }
  1285. /* unsafe tcpconn_rm version (nolocks) */
  1286. void _tcpconn_rm(struct tcp_connection* c)
  1287. {
  1288. _tcpconn_detach(c);
  1289. _tcpconn_free(c);
  1290. }
  1291. void tcpconn_rm(struct tcp_connection* c)
  1292. {
  1293. int r;
  1294. TCPCONN_LOCK;
  1295. tcpconn_listrm(tcpconn_id_hash[c->id_hash], c, id_next, id_prev);
  1296. /* remove all the aliases */
  1297. for (r=0; r<c->aliases; r++)
  1298. tcpconn_listrm(tcpconn_aliases_hash[c->con_aliases[r].hash],
  1299. &c->con_aliases[r], next, prev);
  1300. c->aliases = 0;
  1301. TCPCONN_UNLOCK;
  1302. lock_destroy(&c->write_lock);
  1303. #ifdef USE_TLS
  1304. if ((c->type==PROTO_TLS || c->type==PROTO_WSS)&&(c->extra_data)) tls_tcpconn_clean(c);
  1305. #endif
  1306. shm_free(c);
  1307. }
  1308. /* finds a connection, if id=0 uses the ip addr, port, local_ip and local port
  1309. * (host byte order) and tries to find the connection that matches all of
  1310. * them. Wild cards can be used for local_ip and local_port (a 0 filled
  1311. * ip address and/or a 0 local port).
  1312. * WARNING: unprotected (locks) use tcpconn_get unless you really
  1313. * know what you are doing */
  1314. struct tcp_connection* _tcpconn_find(int id, struct ip_addr* ip, int port,
  1315. struct ip_addr* l_ip, int l_port)
  1316. {
  1317. struct tcp_connection *c;
  1318. struct tcp_conn_alias* a;
  1319. unsigned hash;
  1320. int is_local_ip_any;
  1321. #ifdef EXTRA_DEBUG
  1322. DBG("tcpconn_find: %d port %d\n",id, port);
  1323. if (ip) print_ip("tcpconn_find: ip ", ip, "\n");
  1324. #endif
  1325. if (likely(id)){
  1326. hash=tcp_id_hash(id);
  1327. for (c=tcpconn_id_hash[hash]; c; c=c->id_next){
  1328. #ifdef EXTRA_DEBUG
  1329. DBG("c=%p, c->id=%d, port=%d\n",c, c->id, c->rcv.src_port);
  1330. print_ip("ip=", &c->rcv.src_ip, "\n");
  1331. #endif
  1332. if ((id==c->id)&&(c->state!=S_CONN_BAD)) return c;
  1333. }
  1334. }else if (likely(ip)){
  1335. hash=tcp_addr_hash(ip, port, l_ip, l_port);
  1336. is_local_ip_any=ip_addr_any(l_ip);
  1337. for (a=tcpconn_aliases_hash[hash]; a; a=a->next){
  1338. #ifdef EXTRA_DEBUG
  1339. DBG("a=%p, c=%p, c->id=%d, alias port= %d port=%d\n", a, a->parent,
  1340. a->parent->id, a->port, a->parent->rcv.src_port);
  1341. print_ip("ip=",&a->parent->rcv.src_ip,"\n");
  1342. #endif
  1343. if ( (a->parent->state!=S_CONN_BAD) && (port==a->port) &&
  1344. ((l_port==0) || (l_port==a->parent->rcv.dst_port)) &&
  1345. (ip_addr_cmp(ip, &a->parent->rcv.src_ip)) &&
  1346. (is_local_ip_any ||
  1347. ip_addr_cmp(l_ip, &a->parent->rcv.dst_ip))
  1348. )
  1349. return a->parent;
  1350. }
  1351. }
  1352. return 0;
  1353. }
  1354. /* _tcpconn_find with locks and timeout
  1355. * local_addr contains the desired local ip:port. If null any local address
  1356. * will be used. IN*ADDR_ANY or 0 port are wild cards.
  1357. */
  1358. struct tcp_connection* tcpconn_get(int id, struct ip_addr* ip, int port,
  1359. union sockaddr_union* local_addr,
  1360. ticks_t timeout)
  1361. {
  1362. struct tcp_connection* c;
  1363. struct ip_addr local_ip;
  1364. int local_port;
  1365. local_port=0;
  1366. if (likely(ip)){
  1367. if (unlikely(local_addr)){
  1368. su2ip_addr(&local_ip, local_addr);
  1369. local_port=su_getport(local_addr);
  1370. }else{
  1371. ip_addr_mk_any(ip->af, &local_ip);
  1372. local_port=0;
  1373. }
  1374. }
  1375. TCPCONN_LOCK;
  1376. c=_tcpconn_find(id, ip, port, &local_ip, local_port);
  1377. if (likely(c)){
  1378. atomic_inc(&c->refcnt);
  1379. /* update the timeout only if the connection is not handled
  1380. * by a tcp reader _and_the timeout is non-zero (the tcp
  1381. * reader process uses c->timeout for its own internal
  1382. * timeout and c->timeout will be overwritten * anyway on
  1383. * return to tcp_main) */
  1384. if (likely(c->reader_pid==0 && timeout != 0))
  1385. c->timeout=get_ticks_raw()+timeout;
  1386. }
  1387. TCPCONN_UNLOCK;
  1388. return c;
  1389. }
  1390. /* add c->dst:port, local_addr as an alias for the "id" connection,
  1391. * flags: TCP_ALIAS_FORCE_ADD - add an alias even if a previous one exists
  1392. * TCP_ALIAS_REPLACE - if a prev. alias exists, replace it with the
  1393. * new one
  1394. * returns 0 on success, <0 on failure ( -1 - null c, -2 too many aliases,
  1395. * -3 alias already present and pointing to another connection)
  1396. * WARNING: must be called with TCPCONN_LOCK held */
  1397. inline static int _tcpconn_add_alias_unsafe(struct tcp_connection* c, int port,
  1398. struct ip_addr* l_ip, int l_port,
  1399. int flags)
  1400. {
  1401. unsigned hash;
  1402. struct tcp_conn_alias* a;
  1403. struct tcp_conn_alias* nxt;
  1404. struct tcp_connection* p;
  1405. int is_local_ip_any;
  1406. int i;
  1407. int r;
  1408. a=0;
  1409. is_local_ip_any=ip_addr_any(l_ip);
  1410. if (likely(c)){
  1411. hash=tcp_addr_hash(&c->rcv.src_ip, port, l_ip, l_port);
  1412. /* search the aliases for an already existing one */
  1413. for (a=tcpconn_aliases_hash[hash], nxt=0; a; a=nxt){
  1414. nxt=a->next;
  1415. if ( (a->parent->state!=S_CONN_BAD) && (port==a->port) &&
  1416. ( (l_port==0) || (l_port==a->parent->rcv.dst_port)) &&
  1417. (ip_addr_cmp(&c->rcv.src_ip, &a->parent->rcv.src_ip)) &&
  1418. ( is_local_ip_any ||
  1419. ip_addr_cmp(&a->parent->rcv.dst_ip, l_ip))
  1420. ){
  1421. /* found */
  1422. if (unlikely(a->parent!=c)){
  1423. if (flags & TCP_ALIAS_FORCE_ADD)
  1424. /* still have to walk the whole list to check if
  1425. * the alias was not already added */
  1426. continue;
  1427. else if (flags & TCP_ALIAS_REPLACE){
  1428. /* remove the alias =>
  1429. * remove the current alias and all the following
  1430. * ones from the corresponding connection, shift the
  1431. * connection aliases array and re-add the other
  1432. * aliases (!= current one) */
  1433. p=a->parent;
  1434. for (i=0; (i<p->aliases) && (&(p->con_aliases[i])!=a);
  1435. i++);
  1436. if (unlikely(i==p->aliases)){
  1437. LM_CRIT("alias %p not found in con %p (id %d)\n",
  1438. a, p, p->id);
  1439. goto error_not_found;
  1440. }
  1441. for (r=i; r<p->aliases; r++){
  1442. tcpconn_listrm(
  1443. tcpconn_aliases_hash[p->con_aliases[r].hash],
  1444. &p->con_aliases[r], next, prev);
  1445. }
  1446. if (likely((i+1)<p->aliases)){
  1447. memmove(&p->con_aliases[i], &p->con_aliases[i+1],
  1448. (p->aliases-i-1)*
  1449. sizeof(p->con_aliases[0]));
  1450. }
  1451. p->aliases--;
  1452. /* re-add the remaining aliases */
  1453. for (r=i; r<p->aliases; r++){
  1454. tcpconn_listadd(
  1455. tcpconn_aliases_hash[p->con_aliases[r].hash],
  1456. &p->con_aliases[r], next, prev);
  1457. }
  1458. }else
  1459. goto error_sec;
  1460. }else goto ok;
  1461. }
  1462. }
  1463. if (unlikely(c->aliases>=TCP_CON_MAX_ALIASES)) goto error_aliases;
  1464. c->con_aliases[c->aliases].parent=c;
  1465. c->con_aliases[c->aliases].port=port;
  1466. c->con_aliases[c->aliases].hash=hash;
  1467. tcpconn_listadd(tcpconn_aliases_hash[hash],
  1468. &c->con_aliases[c->aliases], next, prev);
  1469. c->aliases++;
  1470. }else goto error_not_found;
  1471. ok:
  1472. #ifdef EXTRA_DEBUG
  1473. if (a) DBG("_tcpconn_add_alias_unsafe: alias already present\n");
  1474. else DBG("_tcpconn_add_alias_unsafe: alias port %d for hash %d, id %d\n",
  1475. port, hash, c->id);
  1476. #endif
  1477. return 0;
  1478. error_aliases:
  1479. /* too many aliases */
  1480. return -2;
  1481. error_not_found:
  1482. /* null connection */
  1483. return -1;
  1484. error_sec:
  1485. /* alias already present and pointing to a different connection
  1486. * (hijack attempt?) */
  1487. return -3;
  1488. }
  1489. /* add port as an alias for the "id" connection,
  1490. * returns 0 on success,-1 on failure */
  1491. int tcpconn_add_alias(int id, int port, int proto)
  1492. {
  1493. struct tcp_connection* c;
  1494. int ret;
  1495. struct ip_addr zero_ip;
  1496. int r;
  1497. int alias_flags;
  1498. /* fix the port */
  1499. port=port?port:((proto==PROTO_TLS)?SIPS_PORT:SIP_PORT);
  1500. TCPCONN_LOCK;
  1501. /* check if alias already exists */
  1502. c=_tcpconn_find(id, 0, 0, 0, 0);
  1503. if (likely(c)){
  1504. ip_addr_mk_any(c->rcv.src_ip.af, &zero_ip);
  1505. alias_flags=cfg_get(tcp, tcp_cfg, alias_flags);
  1506. /* alias src_ip:port, 0, 0 */
  1507. ret=_tcpconn_add_alias_unsafe(c, port, &zero_ip, 0,
  1508. alias_flags);
  1509. if (ret<0 && ret!=-3) goto error;
  1510. /* alias src_ip:port, local_ip, 0 */
  1511. ret=_tcpconn_add_alias_unsafe(c, port, &c->rcv.dst_ip, 0,
  1512. alias_flags);
  1513. if (ret<0 && ret!=-3) goto error;
  1514. /* alias src_ip:port, local_ip, local_port */
  1515. ret=_tcpconn_add_alias_unsafe(c, port, &c->rcv.dst_ip, c->rcv.dst_port,
  1516. alias_flags);
  1517. if (unlikely(ret<0)) goto error;
  1518. }else goto error_not_found;
  1519. TCPCONN_UNLOCK;
  1520. return 0;
  1521. error_not_found:
  1522. TCPCONN_UNLOCK;
  1523. LM_ERR("no connection found for id %d\n",id);
  1524. return -1;
  1525. error:
  1526. TCPCONN_UNLOCK;
  1527. switch(ret){
  1528. case -2:
  1529. LM_ERR("too many aliases (%d) for connection %p (id %d) %s:%d <- %d\n",
  1530. c->aliases, c, c->id, ip_addr2a(&c->rcv.src_ip),
  1531. c->rcv.src_port, port);
  1532. for (r=0; r<c->aliases; r++){
  1533. LM_ERR("alias %d: for %p (%d) %s:%d <-%d hash %x\n", r, c, c->id,
  1534. ip_addr2a(&c->rcv.src_ip), c->rcv.src_port,
  1535. c->con_aliases[r].port, c->con_aliases[r].hash);
  1536. }
  1537. break;
  1538. case -3:
  1539. LM_ERR("possible port hijack attempt\n");
  1540. LM_ERR("alias for %d port %d already"
  1541. " present and points to another connection \n",
  1542. c->id, port);
  1543. break;
  1544. default:
  1545. LM_ERR("unknown error %d\n", ret);
  1546. }
  1547. return -1;
  1548. }
  1549. #ifdef TCP_FD_CACHE
  1550. static void tcp_fd_cache_init(void)
  1551. {
  1552. int r;
  1553. for (r=0; r<TCP_FD_CACHE_SIZE; r++)
  1554. fd_cache[r].fd=-1;
  1555. }
  1556. inline static struct fd_cache_entry* tcp_fd_cache_get(struct tcp_connection *c)
  1557. {
  1558. int h;
  1559. h=c->id%TCP_FD_CACHE_SIZE;
  1560. if ((fd_cache[h].fd>0) && (fd_cache[h].id==c->id) && (fd_cache[h].con==c))
  1561. return &fd_cache[h];
  1562. return 0;
  1563. }
  1564. inline static void tcp_fd_cache_rm(struct fd_cache_entry* e)
  1565. {
  1566. e->fd=-1;
  1567. }
  1568. inline static void tcp_fd_cache_add(struct tcp_connection *c, int fd)
  1569. {
  1570. int h;
  1571. h=c->id%TCP_FD_CACHE_SIZE;
  1572. if (likely(fd_cache[h].fd>0))
  1573. tcp_safe_close(fd_cache[h].fd);
  1574. fd_cache[h].fd=fd;
  1575. fd_cache[h].id=c->id;
  1576. fd_cache[h].con=c;
  1577. }
  1578. #endif /* TCP_FD_CACHE */
  1579. inline static int tcpconn_chld_put(struct tcp_connection* tcpconn);
  1580. static int tcpconn_send_put(struct tcp_connection* c, const char* buf,
  1581. unsigned len, snd_flags_t send_flags);
  1582. static int tcpconn_do_send(int fd, struct tcp_connection* c,
  1583. const char* buf, unsigned len,
  1584. snd_flags_t send_flags, long* resp, int locked);
  1585. static int tcpconn_1st_send(int fd, struct tcp_connection* c,
  1586. const char* buf, unsigned len,
  1587. snd_flags_t send_flags, long* resp, int locked);
  1588. /* finds a tcpconn & sends on it
  1589. * uses the dst members to, proto (TCP|TLS) and id and tries to send
  1590. * from the "from" address (if non null and id==0)
  1591. * returns: number of bytes written (>=0) on success
  1592. * <0 on error */
  1593. int tcp_send(struct dest_info* dst, union sockaddr_union* from,
  1594. const char* buf, unsigned len)
  1595. {
  1596. struct tcp_connection *c;
  1597. struct ip_addr ip;
  1598. int port;
  1599. int fd;
  1600. long response[2];
  1601. int n;
  1602. ticks_t con_lifetime;
  1603. #ifdef USE_TLS
  1604. const char* rest_buf;
  1605. const char* t_buf;
  1606. unsigned rest_len, t_len;
  1607. long resp;
  1608. snd_flags_t t_send_flags;
  1609. #endif /* USE_TLS */
  1610. port=su_getport(&dst->to);
  1611. con_lifetime=cfg_get(tcp, tcp_cfg, con_lifetime);
  1612. if (likely(port)){
  1613. su2ip_addr(&ip, &dst->to);
  1614. c=tcpconn_get(dst->id, &ip, port, from, con_lifetime);
  1615. }else if (likely(dst->id)){
  1616. c=tcpconn_get(dst->id, 0, 0, 0, con_lifetime);
  1617. }else{
  1618. LM_CRIT("null id & to\n");
  1619. return -1;
  1620. }
  1621. if (likely(dst->id)){
  1622. if (unlikely(c==0)) {
  1623. if (likely(port)){
  1624. /* try again w/o id */
  1625. c=tcpconn_get(0, &ip, port, from, con_lifetime);
  1626. }else{
  1627. LM_ERR("id %d not found, dropping\n", dst->id);
  1628. return -1;
  1629. }
  1630. }
  1631. }
  1632. /* connection not found or unusable => open a new one and send on it */
  1633. if (unlikely((c==0) || tcpconn_close_after_send(c))){
  1634. if (unlikely(c)){
  1635. /* can't use c if it's marked as close-after-send =>
  1636. release it and try opening new one */
  1637. tcpconn_chld_put(c); /* release c (dec refcnt & free on 0) */
  1638. c=0;
  1639. }
  1640. /* check if connect() is disabled */
  1641. if (unlikely((dst->send_flags.f & SND_F_FORCE_CON_REUSE) ||
  1642. cfg_get(tcp, tcp_cfg, no_connect)))
  1643. return -1;
  1644. DBG("tcp_send: no open tcp connection found, opening new one\n");
  1645. /* create tcp connection */
  1646. if (likely(from==0)){
  1647. /* check to see if we have to use a specific source addr. */
  1648. switch (dst->to.s.sa_family) {
  1649. case AF_INET:
  1650. from = tcp_source_ipv4;
  1651. break;
  1652. case AF_INET6:
  1653. from = tcp_source_ipv6;
  1654. break;
  1655. default:
  1656. /* error, bad af, ignore ... */
  1657. break;
  1658. }
  1659. }
  1660. #if defined(TCP_CONNECT_WAIT) && defined(TCP_ASYNC)
  1661. if (likely(cfg_get(tcp, tcp_cfg, tcp_connect_wait) &&
  1662. cfg_get(tcp, tcp_cfg, async) )){
  1663. if (unlikely(*tcp_connections_no >=
  1664. cfg_get(tcp, tcp_cfg, max_connections))){
  1665. LM_ERR("%s: maximum number of connections exceeded (%d/%d)\n",
  1666. su2a(&dst->to, sizeof(dst->to)),
  1667. *tcp_connections_no,
  1668. cfg_get(tcp, tcp_cfg, max_connections));
  1669. return -1;
  1670. }
  1671. if (unlikely(dst->proto==PROTO_TLS)) {
  1672. if (unlikely(*tls_connections_no >=
  1673. cfg_get(tcp, tcp_cfg, max_tls_connections))){
  1674. LM_ERR("%s: maximum number of tls connections exceeded (%d/%d)\n",
  1675. su2a(&dst->to, sizeof(dst->to)),
  1676. *tls_connections_no,
  1677. cfg_get(tcp, tcp_cfg, max_tls_connections));
  1678. return -1;
  1679. }
  1680. }
  1681. c=tcpconn_new(-1, &dst->to, from, 0, dst->proto,
  1682. S_CONN_CONNECT);
  1683. if (unlikely(c==0)){
  1684. LM_ERR("%s: could not create new connection\n",
  1685. su2a(&dst->to, sizeof(dst->to)));
  1686. return -1;
  1687. }
  1688. c->flags|=F_CONN_PENDING|F_CONN_FD_CLOSED;
  1689. tcpconn_set_send_flags(c, dst->send_flags);
  1690. atomic_set(&c->refcnt, 2); /* ref from here and from main hash
  1691. table */
  1692. /* add it to id hash and aliases */
  1693. if (unlikely(tcpconn_add(c)==0)){
  1694. LM_ERR("%s: could not add connection %p\n",
  1695. su2a(&dst->to, sizeof(dst->to)), c);
  1696. _tcpconn_free(c);
  1697. n=-1;
  1698. goto end_no_conn;
  1699. }
  1700. /* do connect and if src ip or port changed, update the
  1701. * aliases */
  1702. if (unlikely((fd=tcpconn_finish_connect(c, from))<0)){
  1703. /* tcpconn_finish_connect will automatically blacklist
  1704. on error => no need to do it here */
  1705. LM_ERR("%s: tcpconn_finish_connect(%p) failed\n",
  1706. su2a(&dst->to, sizeof(dst->to)), c);
  1707. goto conn_wait_error;
  1708. }
  1709. /* ? TODO: it might be faster just to queue the write directly
  1710. * and send to main CONN_NEW_PENDING_WRITE */
  1711. /* delay sending the fd to main after the send */
  1712. /* NOTE: no lock here, because the connection is marked as
  1713. * pending and nobody else will try to write on it. However
  1714. * this might produce out-of-order writes. If this is not
  1715. * desired either lock before the write or use
  1716. * _wbufq_insert(...)
  1717. * NOTE2: _wbufq_insert() is used now (no out-of-order).
  1718. */
  1719. #ifdef USE_TLS
  1720. if (unlikely(c->type==PROTO_TLS)) {
  1721. /* for TLS the TLS processing and the send must happen
  1722. atomically w/ respect to other sends on the same connection
  1723. (otherwise reordering might occur which would break TLS) =>
  1724. lock. However in this case this send will always be the first.
  1725. We can have the send() outside the lock only if this is the
  1726. first and only send (tls_encode is not called again), or
  1727. this is the last send for a tls_encode() loop and all the
  1728. previous ones did return CONN_NEW_COMPLETE or CONN_EOF.
  1729. */
  1730. response[1] = CONN_NOP;
  1731. t_buf = buf;
  1732. t_len = len;
  1733. lock_get(&c->write_lock);
  1734. redo_tls_encode:
  1735. t_send_flags = dst->send_flags;
  1736. n = tls_encode(c, &t_buf, &t_len, &rest_buf, &rest_len,
  1737. &t_send_flags);
  1738. /* There are 4 cases:
  1739. 1. entire buffer consumed from the first try
  1740. (rest_len == rest_buf == 0)
  1741. 2. rest_buf & first call
  1742. 3. rest_buf & not first call
  1743. 3a. CONN_NEW_COMPLETE or CONN_EOF
  1744. 3b. CONN_NEW_PENDING_WRITE
  1745. 4. entire buffer consumed, but not first call
  1746. 4a. CONN_NEW_COMPLETE or CONN_EOF
  1747. 4b. CONN_NEW_PENDING_WRITE
  1748. We misuse response[1] == CONN_NOP to test for the
  1749. first call.
  1750. */
  1751. if (unlikely(n < 0)) {
  1752. lock_release(&c->write_lock);
  1753. goto conn_wait_error;
  1754. }
  1755. if (likely(rest_len == 0)) {
  1756. /* 1 or 4*: CONN_NEW_COMPLETE, CONN_EOF, CONN_NOP
  1757. or CONN_NEW_PENDING_WRITE (*rest_len == 0) */
  1758. if (likely(response[1] != CONN_NEW_PENDING_WRITE)) {
  1759. /* 1 or 4a => it's safe to do the send outside the
  1760. lock (it will either send directly or
  1761. wbufq_insert())
  1762. */
  1763. lock_release(&c->write_lock);
  1764. if (likely(t_len != 0)) {
  1765. n=tcpconn_1st_send(fd, c, t_buf, t_len,
  1766. t_send_flags,
  1767. &response[1], 0);
  1768. } else { /* t_len == 0 */
  1769. if (response[1] == CONN_NOP) {
  1770. /* nothing to send (e.g parallel send
  1771. tls_encode queues some data and then
  1772. WANT_READ => this tls_encode will queue
  1773. the cleartext too and will have nothing
  1774. to send right now) and initial send =>
  1775. behave as if the send was successful
  1776. (but never return EOF here) */
  1777. response[1] = CONN_NEW_COMPLETE;
  1778. }
  1779. }
  1780. /* exit */
  1781. } else {
  1782. /* CONN_NEW_PENDING_WRITE: 4b: it was a
  1783. repeated tls_encode() (or otherwise we would
  1784. have here CONN_NOP) => add to the queue */
  1785. if (unlikely(t_len &&
  1786. _wbufq_add(c, t_buf, t_len) < 0)) {
  1787. response[1] = CONN_ERROR;
  1788. n = -1;
  1789. }
  1790. lock_release(&c->write_lock);
  1791. /* exit (no send) */
  1792. }
  1793. } else { /* rest_len != 0 */
  1794. /* 2 or 3*: if tls_encode hasn't finished, we have to
  1795. call tcpconn_1st_send() under lock (otherwise if it
  1796. returns CONN_NEW_PENDING_WRITE, there is no way
  1797. to find the right place to add the new queued
  1798. data from the 2nd tls_encode()) */
  1799. if (likely((response[1] == CONN_NOP /*2*/ ||
  1800. response[1] == CONN_NEW_COMPLETE /*3a*/ ||
  1801. response[1] == CONN_EOF /*3a*/) && t_len))
  1802. n = tcpconn_1st_send(fd, c, t_buf, t_len,
  1803. t_send_flags,
  1804. &response[1], 1);
  1805. else if (unlikely(t_len &&
  1806. _wbufq_add(c, t_buf, t_len) < 0)) {
  1807. /*3b: CONN_NEW_PENDING_WRITE*/
  1808. response[1] = CONN_ERROR;
  1809. n = -1;
  1810. }
  1811. if (likely(n >= 0)) {
  1812. /* if t_len == 0 => nothing was sent => previous
  1813. response will be kept */
  1814. t_buf = rest_buf;
  1815. t_len = rest_len;
  1816. goto redo_tls_encode;
  1817. } else {
  1818. lock_release(&c->write_lock);
  1819. /* error exit */
  1820. }
  1821. }
  1822. } else
  1823. #endif /* USE_TLS */
  1824. n=tcpconn_1st_send(fd, c, buf, len, dst->send_flags,
  1825. &response[1], 0);
  1826. if (unlikely(n<0)) /* this will catch CONN_ERROR too */
  1827. goto conn_wait_error;
  1828. if (unlikely(response[1]==CONN_EOF)){
  1829. /* if close-after-send requested, don't bother
  1830. sending the fd back to tcp_main, try closing it
  1831. immediately (no other tcp_send should use it,
  1832. because it is marked as close-after-send before
  1833. being added to the hash) */
  1834. goto conn_wait_close;
  1835. }
  1836. /* send to tcp_main */
  1837. response[0]=(long)c;
  1838. if (unlikely(send_fd(unix_tcp_sock, response,
  1839. sizeof(response), fd) <= 0)){
  1840. LM_ERR("%s: %ld for %p failed:" " %s (%d)\n",
  1841. su2a(&dst->to, sizeof(dst->to)),
  1842. response[1], c, strerror(errno), errno);
  1843. goto conn_wait_error;
  1844. }
  1845. goto conn_wait_success;
  1846. }
  1847. #endif /* TCP_CONNECT_WAIT && TCP_ASYNC */
  1848. if (unlikely((c=tcpconn_connect(&dst->to, from, dst->proto,
  1849. &dst->send_flags))==0)){
  1850. LM_ERR("%s: connect failed\n", su2a(&dst->to, sizeof(dst->to)));
  1851. return -1;
  1852. }
  1853. tcpconn_set_send_flags(c, dst->send_flags);
  1854. if (likely(c->state==S_CONN_OK))
  1855. TCP_STATS_ESTABLISHED(S_CONN_CONNECT);
  1856. atomic_set(&c->refcnt, 2); /* ref. from here and it will also
  1857. be added in the tcp_main hash */
  1858. fd=c->s;
  1859. c->flags|=F_CONN_FD_CLOSED; /* not yet opened in main */
  1860. /* ? TODO: it might be faster just to queue the write and
  1861. * send to main a CONN_NEW_PENDING_WRITE */
  1862. /* send the new tcpconn to "tcp main" */
  1863. response[0]=(long)c;
  1864. response[1]=CONN_NEW;
  1865. n=send_fd(unix_tcp_sock, response, sizeof(response), c->s);
  1866. if (unlikely(n<=0)){
  1867. LM_ERR("%s: failed send_fd: %s (%d)\n",
  1868. su2a(&dst->to, sizeof(dst->to)),
  1869. strerror(errno), errno);
  1870. /* we can safely delete it, it's not referenced by anybody */
  1871. _tcpconn_free(c);
  1872. n=-1;
  1873. goto end_no_conn;
  1874. }
  1875. /* new connection => send on it directly */
  1876. #ifdef USE_TLS
  1877. if (unlikely(c->type==PROTO_TLS)) {
  1878. /* for TLS the TLS processing and the send must happen
  1879. atomically w/ respect to other sends on the same connection
  1880. (otherwise reordering might occur which would break TLS) =>
  1881. lock.
  1882. */
  1883. response[1] = CONN_NOP;
  1884. t_buf = buf;
  1885. t_len = len;
  1886. lock_get(&c->write_lock);
  1887. do {
  1888. t_send_flags = dst->send_flags;
  1889. n = tls_encode(c, &t_buf, &t_len, &rest_buf, &rest_len,
  1890. &t_send_flags);
  1891. if (likely(n > 0)) {
  1892. n = tcpconn_do_send(fd, c, t_buf, t_len, t_send_flags,
  1893. &resp, 1);
  1894. if (likely(response[1] != CONN_QUEUED_WRITE ||
  1895. resp == CONN_ERROR))
  1896. /* don't overwrite a previous CONN_QUEUED_WRITE
  1897. unless error */
  1898. response[1] = resp;
  1899. } else if (unlikely(n < 0)) {
  1900. response[1] = CONN_ERROR;
  1901. break;
  1902. }
  1903. /* else do nothing for n (t_len) == 0, keep
  1904. the last reponse */
  1905. t_buf = rest_buf;
  1906. t_len = rest_len;
  1907. } while(unlikely(rest_len && n > 0));
  1908. lock_release(&c->write_lock);
  1909. } else
  1910. #endif /* USE_TLS */
  1911. n = tcpconn_do_send(fd, c, buf, len, dst->send_flags,
  1912. &response[1], 0);
  1913. if (unlikely(response[1] != CONN_NOP)) {
  1914. response[0]=(long)c;
  1915. if (send_all(unix_tcp_sock, response, sizeof(response)) <= 0) {
  1916. BUG("tcp_main command %ld sending failed (write):"
  1917. "%s (%d)\n", response[1], strerror(errno), errno);
  1918. /* all commands != CONN_NOP returned by tcpconn_do_send()
  1919. (CONN_EOF, CONN_ERROR, CONN_QUEUED_WRITE) will auto-dec
  1920. refcnt => if sending the command fails we have to
  1921. dec. refcnt by hand */
  1922. tcpconn_chld_put(c); /* deref. it manually */
  1923. n=-1;
  1924. }
  1925. /* here refcnt for c is already decremented => c contents can
  1926. no longer be used and refcnt _must_ _not_ be decremented
  1927. again on exit */
  1928. if (unlikely(n < 0 || response[1] == CONN_EOF)) {
  1929. /* on error or eof, close fd */
  1930. tcp_safe_close(fd);
  1931. } else if (response[1] == CONN_QUEUED_WRITE) {
  1932. #ifdef TCP_FD_CACHE
  1933. if (cfg_get(tcp, tcp_cfg, fd_cache)) {
  1934. tcp_fd_cache_add(c, fd);
  1935. } else
  1936. #endif /* TCP_FD_CACHE */
  1937. tcp_safe_close(fd);
  1938. } else {
  1939. BUG("unexpected tcpconn_do_send() return & response:"
  1940. " %d, %ld\n", n, response[1]);
  1941. }
  1942. goto end_no_deref;
  1943. }
  1944. #ifdef TCP_FD_CACHE
  1945. if (cfg_get(tcp, tcp_cfg, fd_cache)) {
  1946. tcp_fd_cache_add(c, fd);
  1947. }else
  1948. #endif /* TCP_FD_CACHE */
  1949. tcp_safe_close(fd);
  1950. /* here we can have only commands that _do_ _not_ dec refcnt.
  1951. (CONN_EOF, CON_ERROR, CON_QUEUED_WRITE are all treated above) */
  1952. goto release_c;
  1953. } /* if (c==0 or unusable) new connection */
  1954. /* existing connection, send on it */
  1955. n = tcpconn_send_put(c, buf, len, dst->send_flags);
  1956. /* no deref needed (automatically done inside tcpconn_send_put() */
  1957. return n;
  1958. #ifdef TCP_CONNECT_WAIT
  1959. conn_wait_success:
  1960. #ifdef TCP_FD_CACHE
  1961. if (cfg_get(tcp, tcp_cfg, fd_cache)) {
  1962. tcp_fd_cache_add(c, fd);
  1963. } else
  1964. #endif /* TCP_FD_CACHE */
  1965. if (unlikely (tcp_safe_close(fd) < 0))
  1966. LM_ERR("closing temporary send fd for %p: %s: "
  1967. "close(%d) failed (flags 0x%x): %s (%d)\n", c,
  1968. su2a(&c->rcv.src_su, sizeof(c->rcv.src_su)),
  1969. fd, c->flags, strerror(errno), errno);
  1970. tcpconn_chld_put(c); /* release c (dec refcnt & free on 0) */
  1971. return n;
  1972. conn_wait_error:
  1973. n=-1;
  1974. conn_wait_close:
  1975. /* connect or send failed or immediate close-after-send was requested on
  1976. * newly created connection which was not yet sent to tcp_main (but was
  1977. * already hashed) => don't send to main, unhash and destroy directly
  1978. * (if refcnt>2 it will be destroyed when the last sender releases the
  1979. * connection (tcpconn_chld_put(c))) or when tcp_main receives a
  1980. * CONN_ERROR it*/
  1981. c->state=S_CONN_BAD;
  1982. /* we are here only if we opened a new fd (and not reused a cached or
  1983. a reader one) => if the connect was successful close the fd */
  1984. if (fd>=0) {
  1985. if (unlikely(tcp_safe_close(fd) < 0 ))
  1986. LM_ERR("closing temporary send fd for %p: %s: "
  1987. "close(%d) failed (flags 0x%x): %s (%d)\n", c,
  1988. su2a(&c->rcv.src_su, sizeof(c->rcv.src_su)),
  1989. fd, c->flags, strerror(errno), errno);
  1990. }
  1991. /* here the connection is for sure in the hash (tcp_main will not
  1992. remove it because it's marked as PENDing) and the refcnt is at least
  1993. 2
  1994. */
  1995. TCPCONN_LOCK;
  1996. _tcpconn_detach(c);
  1997. c->flags&=~F_CONN_HASHED;
  1998. tcpconn_put(c);
  1999. TCPCONN_UNLOCK;
  2000. /* dec refcnt -> mark it for destruction */
  2001. tcpconn_chld_put(c);
  2002. return n;
  2003. #endif /* TCP_CONNECT_WAIT */
  2004. release_c:
  2005. tcpconn_chld_put(c); /* release c (dec refcnt & free on 0) */
  2006. end_no_deref:
  2007. end_no_conn:
  2008. return n;
  2009. }
  2010. /** sends on an existing tcpconn and auto-dec. con. ref counter.
  2011. * As opposed to tcp_send(), this function requires an existing
  2012. * tcp connection.
  2013. * WARNING: the tcp_connection will be de-referenced.
  2014. * @param c - existing tcp connection pointer.
  2015. * @param buf - data to be sent.
  2016. * @param len - data length,
  2017. * @return >=0 on success, -1 on error.
  2018. */
  2019. static int tcpconn_send_put(struct tcp_connection* c, const char* buf,
  2020. unsigned len, snd_flags_t send_flags)
  2021. {
  2022. struct tcp_connection *tmp;
  2023. int fd;
  2024. long response[2];
  2025. int n;
  2026. int do_close_fd;
  2027. #ifdef USE_TLS
  2028. const char* rest_buf;
  2029. const char* t_buf;
  2030. unsigned rest_len, t_len;
  2031. long resp;
  2032. snd_flags_t t_send_flags;
  2033. #endif /* USE_TLS */
  2034. #ifdef TCP_FD_CACHE
  2035. struct fd_cache_entry* fd_cache_e;
  2036. int use_fd_cache;
  2037. use_fd_cache=cfg_get(tcp, tcp_cfg, fd_cache);
  2038. fd_cache_e=0;
  2039. #endif /* TCP_FD_CACHE */
  2040. do_close_fd=1; /* close the fd on exit */
  2041. response[1] = CONN_NOP;
  2042. #ifdef TCP_ASYNC
  2043. /* if data is already queued, we don't need the fd */
  2044. #ifdef TCP_CONNECT_WAIT
  2045. if (unlikely(cfg_get(tcp, tcp_cfg, async) &&
  2046. (_wbufq_non_empty(c) || (c->flags&F_CONN_PENDING)) ))
  2047. #else /* ! TCP_CONNECT_WAIT */
  2048. if (unlikely(cfg_get(tcp, tcp_cfg, async) && (_wbufq_non_empty(c)) ))
  2049. #endif /* TCP_CONNECT_WAIT */
  2050. {
  2051. lock_get(&c->write_lock);
  2052. #ifdef TCP_CONNECT_WAIT
  2053. if (likely(_wbufq_non_empty(c) || (c->flags&F_CONN_PENDING)))
  2054. #else /* ! TCP_CONNECT_WAIT */
  2055. if (likely(_wbufq_non_empty(c)))
  2056. #endif /* TCP_CONNECT_WAIT */
  2057. {
  2058. do_close_fd=0;
  2059. #ifdef USE_TLS
  2060. if (unlikely(c->type==PROTO_TLS || c->type==PROTO_WSS)) {
  2061. t_buf = buf;
  2062. t_len = len;
  2063. do {
  2064. t_send_flags = send_flags;
  2065. n = tls_encode(c, &t_buf, &t_len,
  2066. &rest_buf, &rest_len,
  2067. &t_send_flags);
  2068. if (unlikely((n < 0) || (t_len &&
  2069. (_wbufq_add(c, t_buf, t_len) < 0)))) {
  2070. lock_release(&c->write_lock);
  2071. n=-1;
  2072. response[1] = CONN_ERROR;
  2073. c->state=S_CONN_BAD;
  2074. c->timeout=get_ticks_raw(); /* force timeout */
  2075. goto error;
  2076. }
  2077. t_buf = rest_buf;
  2078. t_len = rest_len;
  2079. } while(unlikely(rest_len && n > 0));
  2080. } else
  2081. #endif /* USE_TLS */
  2082. if (unlikely(len && (_wbufq_add(c, buf, len)<0))){
  2083. lock_release(&c->write_lock);
  2084. n=-1;
  2085. response[1] = CONN_ERROR;
  2086. c->state=S_CONN_BAD;
  2087. c->timeout=get_ticks_raw(); /* force timeout */
  2088. goto error;
  2089. }
  2090. n=len;
  2091. lock_release(&c->write_lock);
  2092. goto release_c;
  2093. }
  2094. lock_release(&c->write_lock);
  2095. }
  2096. #endif /* TCP_ASYNC */
  2097. /* check if this is not the same reader process holding
  2098. * c and if so send directly on c->fd */
  2099. if (c->reader_pid==my_pid()){
  2100. DBG("tcp_send: send from reader (%d (%d)), reusing fd\n",
  2101. my_pid(), process_no);
  2102. fd=c->fd;
  2103. do_close_fd=0; /* don't close the fd on exit, it's in use */
  2104. #ifdef TCP_FD_CACHE
  2105. use_fd_cache=0; /* don't cache: problems would arise due to the
  2106. close() on cache eviction (if the fd is still
  2107. used). If it has to be cached then dup() _must_
  2108. be used */
  2109. }else if (likely(use_fd_cache &&
  2110. ((fd_cache_e=tcp_fd_cache_get(c))!=0))){
  2111. fd=fd_cache_e->fd;
  2112. do_close_fd=0;
  2113. DBG("tcp_send: found fd in cache ( %d, %p, %d)\n",
  2114. fd, c, fd_cache_e->id);
  2115. #endif /* TCP_FD_CACHE */
  2116. }else{
  2117. DBG("tcp_send: tcp connection found (%p), acquiring fd\n", c);
  2118. /* get the fd */
  2119. response[0]=(long)c;
  2120. response[1]=CONN_GET_FD;
  2121. n=send_all(unix_tcp_sock, response, sizeof(response));
  2122. if (unlikely(n<=0)){
  2123. LM_ERR("failed to get fd(write):%s (%d)\n", strerror(errno), errno);
  2124. n=-1;
  2125. goto release_c;
  2126. }
  2127. DBG("tcp_send, c= %p, n=%d\n", c, n);
  2128. n=receive_fd(unix_tcp_sock, &tmp, sizeof(tmp), &fd, MSG_WAITALL);
  2129. if (unlikely(n<=0)){
  2130. LM_ERR("failed to get fd(receive_fd): %s (%d)\n",
  2131. strerror(errno), errno);
  2132. n=-1;
  2133. do_close_fd=0;
  2134. goto release_c;
  2135. }
  2136. /* handle fd closed or bad connection/error
  2137. (it's possible that this happened in the time between
  2138. we found the intial connection and the time when we get
  2139. the fd)
  2140. */
  2141. if (unlikely(c!=tmp || fd==-1 || c->state==S_CONN_BAD)){
  2142. if (unlikely(c!=tmp && tmp!=0))
  2143. BUG("tcp_send: get_fd: got different connection:"
  2144. " %p (id= %d, refcnt=%d state=%d) != "
  2145. " %p (n=%d)\n",
  2146. c, c->id, atomic_get(&c->refcnt), c->state,
  2147. tmp, n
  2148. );
  2149. n=-1; /* fail */
  2150. /* don't cache fd & close it */
  2151. do_close_fd = (fd==-1)?0:1;
  2152. #ifdef TCP_FD_CACHE
  2153. use_fd_cache = 0;
  2154. #endif /* TCP_FD_CACHE */
  2155. goto end;
  2156. }
  2157. DBG("tcp_send: after receive_fd: c= %p n=%d fd=%d\n",c, n, fd);
  2158. }
  2159. #ifdef USE_TLS
  2160. if (unlikely(c->type==PROTO_TLS || c->type==PROTO_WSS)) {
  2161. /* for TLS the TLS processing and the send must happen
  2162. atomically w/ respect to other sends on the same connection
  2163. (otherwise reordering might occur which would break TLS) =>
  2164. lock.
  2165. */
  2166. response[1] = CONN_NOP;
  2167. t_buf = buf;
  2168. t_len = len;
  2169. lock_get(&c->write_lock);
  2170. do {
  2171. t_send_flags = send_flags;
  2172. n = tls_encode(c, &t_buf, &t_len, &rest_buf, &rest_len,
  2173. &t_send_flags);
  2174. if (likely(n > 0)) {
  2175. n = tcpconn_do_send(fd, c, t_buf, t_len, t_send_flags,
  2176. &resp, 1);
  2177. if (likely(response[1] != CONN_QUEUED_WRITE ||
  2178. resp == CONN_ERROR))
  2179. /* don't overwrite a previous CONN_QUEUED_WRITE
  2180. unless error */
  2181. response[1] = resp;
  2182. } else if (unlikely(n < 0)) {
  2183. response[1] = CONN_ERROR;
  2184. break;
  2185. }
  2186. /* else do nothing for n (t_len) == 0, keep
  2187. the last reponse */
  2188. t_buf = rest_buf;
  2189. t_len = rest_len;
  2190. } while(unlikely(rest_len && n > 0));
  2191. lock_release(&c->write_lock);
  2192. } else
  2193. #endif
  2194. n = tcpconn_do_send(fd, c, buf, len, send_flags, &response[1], 0);
  2195. if (unlikely(response[1] != CONN_NOP)) {
  2196. error:
  2197. response[0]=(long)c;
  2198. if (send_all(unix_tcp_sock, response, sizeof(response)) <= 0) {
  2199. BUG("tcp_main command %ld sending failed (write):%s (%d)\n",
  2200. response[1], strerror(errno), errno);
  2201. /* all commands != CONN_NOP returned by tcpconn_do_send()
  2202. (CONN_EOF, CONN_ERROR, CONN_QUEUED_WRITE) will auto-dec refcnt
  2203. => if sending the command fails we have to dec. refcnt by hand
  2204. */
  2205. tcpconn_chld_put(c); /* deref. it manually */
  2206. n=-1;
  2207. }
  2208. /* here refcnt for c is already decremented => c contents can no
  2209. longer be used and refcnt _must_ _not_ be decremented again
  2210. on exit */
  2211. if (unlikely(n < 0 || response[1] == CONN_EOF)) {
  2212. /* on error or eof, remove from cache or close fd */
  2213. #ifdef TCP_FD_CACHE
  2214. if (unlikely(fd_cache_e)){
  2215. tcp_fd_cache_rm(fd_cache_e);
  2216. fd_cache_e = 0;
  2217. tcp_safe_close(fd);
  2218. }else
  2219. #endif /* TCP_FD_CACHE */
  2220. if (do_close_fd) tcp_safe_close(fd);
  2221. } else if (response[1] == CONN_QUEUED_WRITE) {
  2222. #ifdef TCP_FD_CACHE
  2223. if (unlikely((fd_cache_e==0) && use_fd_cache)){
  2224. tcp_fd_cache_add(c, fd);
  2225. }else
  2226. #endif /* TCP_FD_CACHE */
  2227. if (do_close_fd) tcp_safe_close(fd);
  2228. } else {
  2229. BUG("unexpected tcpconn_do_send() return & response: %d, %ld\n",
  2230. n, response[1]);
  2231. }
  2232. return n; /* no tcpconn_put */
  2233. }
  2234. end:
  2235. #ifdef TCP_FD_CACHE
  2236. if (unlikely((fd_cache_e==0) && use_fd_cache)){
  2237. tcp_fd_cache_add(c, fd);
  2238. }else
  2239. #endif /* TCP_FD_CACHE */
  2240. if (do_close_fd) {
  2241. if (unlikely(tcp_safe_close(fd) < 0))
  2242. LM_ERR("closing temporary send fd for %p: %s: "
  2243. "close(%d) failed (flags 0x%x): %s (%d)\n", c,
  2244. su2a(&c->rcv.src_su, sizeof(c->rcv.src_su)),
  2245. fd, c->flags, strerror(errno), errno);
  2246. }
  2247. /* here we can have only commands that _do_ _not_ dec refcnt.
  2248. (CONN_EOF, CON_ERROR, CON_QUEUED_WRITE are all treated above) */
  2249. release_c:
  2250. tcpconn_chld_put(c); /* release c (dec refcnt & free on 0) */
  2251. return n;
  2252. }
  2253. /* unsafe send on a known tcp connection.
  2254. * Directly send on a known tcp connection with a given fd.
  2255. * It is assumed that the connection locks are already held.
  2256. * Side effects: if needed it will send state update commands to
  2257. * tcp_main (e.g. CON_EOF, CON_ERROR, CON_QUEUED_WRITE).
  2258. * @param fd - fd used for sending.
  2259. * @param c - existing tcp connection pointer (state and flags might be
  2260. * changed).
  2261. * @param buf - data to be sent.
  2262. * @param len - data length.
  2263. * @param send_flags
  2264. * @return <0 on error, number of bytes sent on success.
  2265. */
  2266. int tcpconn_send_unsafe(int fd, struct tcp_connection *c,
  2267. const char* buf, unsigned len, snd_flags_t send_flags)
  2268. {
  2269. int n;
  2270. long response[2];
  2271. n = tcpconn_do_send(fd, c, buf, len, send_flags, &response[1], 1);
  2272. if (unlikely(response[1] != CONN_NOP)) {
  2273. /* all commands != CONN_NOP returned by tcpconn_do_send()
  2274. (CONN_EOF, CONN_ERROR, CONN_QUEUED_WRITE) will auto-dec refcnt
  2275. => increment it (we don't want the connection to be destroyed
  2276. from under us)
  2277. */
  2278. atomic_inc(&c->refcnt);
  2279. response[0]=(long)c;
  2280. if (send_all(unix_tcp_sock, response, sizeof(response)) <= 0) {
  2281. BUG("connection %p command %ld sending failed (write):%s (%d)\n",
  2282. c, response[1], strerror(errno), errno);
  2283. /* send failed => deref. it back by hand */
  2284. tcpconn_chld_put(c);
  2285. n=-1;
  2286. }
  2287. /* here refcnt for c is already decremented => c contents can no
  2288. longer be used and refcnt _must_ _not_ be decremented again
  2289. on exit */
  2290. return n;
  2291. }
  2292. return n;
  2293. }
  2294. /** lower level send (connection and fd should be known).
  2295. * It takes care of possible write-queueing, blacklisting a.s.o.
  2296. * It expects a valid tcp connection. It doesn't touch the ref. cnts.
  2297. * It will also set the connection flags from send_flags (it's better
  2298. * to do it here, because it's guaranteed to be under lock).
  2299. * @param fd - fd used for sending.
  2300. * @param c - existing tcp connection pointer (state and flags might be
  2301. * changed).
  2302. * @param buf - data to be sent.
  2303. * @param len - data length.
  2304. * @param send_flags
  2305. * @param resp - filled with a cmd. for tcp_main:
  2306. * CONN_NOP - nothing needs to be done (do not send
  2307. * anything to tcp_main).
  2308. * CONN_ERROR - error, connection should be closed.
  2309. * CONN_EOF - no error, but connection should be closed.
  2310. * CONN_QUEUED_WRITE - new write queue (connection
  2311. * should be watched for write and the wr.
  2312. * queue flushed).
  2313. * @param locked - if set assume the connection is already locked (call from
  2314. * tls) and do not lock/unlock the connection.
  2315. * @return >=0 on success, < 0 on error && *resp == CON_ERROR.
  2316. *
  2317. */
  2318. static int tcpconn_do_send(int fd, struct tcp_connection* c,
  2319. const char* buf, unsigned len,
  2320. snd_flags_t send_flags, long* resp,
  2321. int locked)
  2322. {
  2323. int n;
  2324. #ifdef TCP_ASYNC
  2325. int enable_write_watch;
  2326. #endif /* TCP_ASYNC */
  2327. DBG("tcp_send: sending...\n");
  2328. *resp = CONN_NOP;
  2329. if (likely(!locked)) lock_get(&c->write_lock);
  2330. /* update connection send flags with the current ones */
  2331. tcpconn_set_send_flags(c, send_flags);
  2332. #ifdef TCP_ASYNC
  2333. if (likely(cfg_get(tcp, tcp_cfg, async))){
  2334. if (_wbufq_non_empty(c)
  2335. #ifdef TCP_CONNECT_WAIT
  2336. || (c->flags&F_CONN_PENDING)
  2337. #endif /* TCP_CONNECT_WAIT */
  2338. ){
  2339. if (unlikely(_wbufq_add(c, buf, len)<0)){
  2340. if (likely(!locked)) lock_release(&c->write_lock);
  2341. n=-1;
  2342. goto error;
  2343. }
  2344. if (likely(!locked)) lock_release(&c->write_lock);
  2345. n=len;
  2346. goto end;
  2347. }
  2348. n=_tcpconn_write_nb(fd, c, buf, len);
  2349. }else{
  2350. #endif /* TCP_ASYNC */
  2351. /* n=tcp_blocking_write(c, fd, buf, len); */
  2352. n=tsend_stream(fd, buf, len,
  2353. TICKS_TO_S(cfg_get(tcp, tcp_cfg, send_timeout)) *
  2354. 1000);
  2355. #ifdef TCP_ASYNC
  2356. }
  2357. #else /* ! TCP_ASYNC */
  2358. if (likely(!locked)) lock_release(&c->write_lock);
  2359. #endif /* TCP_ASYNC */
  2360. DBG("tcp_send: after real write: c= %p n=%d fd=%d\n",c, n, fd);
  2361. DBG("tcp_send: buf=\n%.*s\n", (int)len, buf);
  2362. if (unlikely(n<(int)len)){
  2363. #ifdef TCP_ASYNC
  2364. if (cfg_get(tcp, tcp_cfg, async) &&
  2365. ((n>=0) || errno==EAGAIN || errno==EWOULDBLOCK)){
  2366. enable_write_watch=_wbufq_empty(c);
  2367. if (n<0) n=0;
  2368. else if (unlikely(c->state==S_CONN_CONNECT ||
  2369. c->state==S_CONN_ACCEPT)){
  2370. TCP_STATS_ESTABLISHED(c->state);
  2371. c->state=S_CONN_OK; /* something was written */
  2372. }
  2373. if (unlikely(_wbufq_add(c, buf+n, len-n)<0)){
  2374. if (likely(!locked)) lock_release(&c->write_lock);
  2375. n=-1;
  2376. goto error;
  2377. }
  2378. if (likely(!locked)) lock_release(&c->write_lock);
  2379. n=len;
  2380. if (likely(enable_write_watch))
  2381. *resp=CONN_QUEUED_WRITE;
  2382. goto end;
  2383. }else{
  2384. if (likely(!locked)) lock_release(&c->write_lock);
  2385. }
  2386. #endif /* TCP_ASYNC */
  2387. if (unlikely(c->state==S_CONN_CONNECT)){
  2388. switch(errno){
  2389. case ENETUNREACH:
  2390. case EHOSTUNREACH: /* not posix for send() */
  2391. #ifdef USE_DST_BLACKLIST
  2392. dst_blacklist_su(BLST_ERR_CONNECT, c->rcv.proto,
  2393. &c->rcv.src_su, &c->send_flags, 0);
  2394. #endif /* USE_DST_BLACKLIST */
  2395. TCP_EV_CONNECT_UNREACHABLE(errno, TCP_LADDR(c),
  2396. TCP_LPORT(c), TCP_PSU(c), TCP_PROTO(c));
  2397. break;
  2398. case ECONNREFUSED:
  2399. case ECONNRESET:
  2400. #ifdef USE_DST_BLACKLIST
  2401. dst_blacklist_su(BLST_ERR_CONNECT, c->rcv.proto,
  2402. &c->rcv.src_su, &c->send_flags, 0);
  2403. #endif /* USE_DST_BLACKLIST */
  2404. TCP_EV_CONNECT_RST(errno, TCP_LADDR(c), TCP_LPORT(c),
  2405. TCP_PSU(c), TCP_PROTO(c));
  2406. break;
  2407. default:
  2408. TCP_EV_CONNECT_ERR(errno, TCP_LADDR(c), TCP_LPORT(c),
  2409. TCP_PSU(c), TCP_PROTO(c));
  2410. }
  2411. TCP_STATS_CONNECT_FAILED();
  2412. }else{
  2413. switch(errno){
  2414. case ECONNREFUSED:
  2415. case ECONNRESET:
  2416. TCP_STATS_CON_RESET();
  2417. /* no break */
  2418. case ENETUNREACH:
  2419. /*case EHOSTUNREACH: -- not posix */
  2420. #ifdef USE_DST_BLACKLIST
  2421. dst_blacklist_su(BLST_ERR_SEND, c->rcv.proto,
  2422. &c->rcv.src_su, &c->send_flags, 0);
  2423. #endif /* USE_DST_BLACKLIST */
  2424. break;
  2425. }
  2426. }
  2427. LM_ERR("failed to send on %p (%s:%d->%s): %s (%d)\n",
  2428. c, ip_addr2a(&c->rcv.dst_ip), c->rcv.dst_port,
  2429. su2a(&c->rcv.src_su, sizeof(c->rcv.src_su)),
  2430. strerror(errno), errno);
  2431. n = -1;
  2432. #ifdef TCP_ASYNC
  2433. error:
  2434. #endif /* TCP_ASYNC */
  2435. /* error on the connection , mark it as bad and set 0 timeout */
  2436. c->state=S_CONN_BAD;
  2437. c->timeout=get_ticks_raw();
  2438. /* tell "main" it should drop this (optional it will t/o anyway?)*/
  2439. *resp=CONN_ERROR;
  2440. return n; /* error return, no tcpconn_put */
  2441. }
  2442. #ifdef TCP_ASYNC
  2443. if (likely(!locked)) lock_release(&c->write_lock);
  2444. #endif /* TCP_ASYNC */
  2445. /* in non-async mode here we're either in S_CONN_OK or S_CONN_ACCEPT*/
  2446. if (unlikely(c->state==S_CONN_CONNECT || c->state==S_CONN_ACCEPT)){
  2447. TCP_STATS_ESTABLISHED(c->state);
  2448. c->state=S_CONN_OK;
  2449. }
  2450. if (unlikely(send_flags.f & SND_F_CON_CLOSE)){
  2451. /* close after write => send EOF request to tcp_main */
  2452. c->state=S_CONN_BAD;
  2453. c->timeout=get_ticks_raw();
  2454. /* tell "main" it should drop this*/
  2455. *resp=CONN_EOF;
  2456. return n;
  2457. }
  2458. end:
  2459. return n;
  2460. }
  2461. /** low level 1st send on a new connection.
  2462. * It takes care of possible write-queueing, blacklisting a.s.o.
  2463. * It expects a valid just-opened tcp connection. It doesn't touch the
  2464. * ref. counters. It's used only in the async first send case.
  2465. * @param fd - fd used for sending.
  2466. * @param c - existing tcp connection pointer (state and flags might be
  2467. * changed). The connection must be new (no previous send on it).
  2468. * @param buf - data to be sent.
  2469. * @param len - data length.
  2470. * @param send_flags
  2471. * @param resp - filled with a fd sending cmd. for tcp_main on success. It
  2472. * _must_ be one of the commands listed below:
  2473. * CONN_NEW_PENDING_WRITE - new connection, first write
  2474. * was partially successful (or EAGAIN) and
  2475. * was queued (connection should be watched
  2476. * for write and the write queue flushed).
  2477. * The fd should be sent to tcp_main.
  2478. * CONN_NEW_COMPLETE - new connection, first write
  2479. * completed successfully and no data is
  2480. * queued. The fd should be sent to tcp_main.
  2481. * CONN_EOF - no error, but the connection should be
  2482. * closed (e.g. SND_F_CON_CLOSE send flag).
  2483. * CONN_ERROR - error, _must_ return < 0.
  2484. * @param locked - if set assume the connection is already locked (call from
  2485. * tls) and do not lock/unlock the connection.
  2486. * @return >=0 on success, < 0 on error (on error *resp is undefined).
  2487. *
  2488. */
  2489. static int tcpconn_1st_send(int fd, struct tcp_connection* c,
  2490. const char* buf, unsigned len,
  2491. snd_flags_t send_flags, long* resp,
  2492. int locked)
  2493. {
  2494. int n;
  2495. n=_tcpconn_write_nb(fd, c, buf, len);
  2496. if (unlikely(n<(int)len)){
  2497. /* on EAGAIN or ENOTCONN return success.
  2498. ENOTCONN appears on newer FreeBSD versions (non-blocking socket,
  2499. connect() & send immediately) */
  2500. if ((n>=0) || errno==EAGAIN || errno==EWOULDBLOCK || errno==ENOTCONN){
  2501. DBG("pending write on new connection %p "
  2502. " (%d/%d bytes written)\n", c, n, len);
  2503. if (unlikely(n<0)) n=0;
  2504. else{
  2505. if (likely(c->state == S_CONN_CONNECT))
  2506. TCP_STATS_ESTABLISHED(S_CONN_CONNECT);
  2507. c->state=S_CONN_OK; /* partial write => connect()
  2508. ended */
  2509. }
  2510. /* add to the write queue */
  2511. if (likely(!locked)) lock_get(&c->write_lock);
  2512. if (unlikely(_wbufq_insert(c, buf+n, len-n)<0)){
  2513. if (likely(!locked)) lock_release(&c->write_lock);
  2514. n=-1;
  2515. LM_ERR("%s: EAGAIN and write queue full or failed for %p\n",
  2516. su2a(&c->rcv.src_su, sizeof(c->rcv.src_su)), c);
  2517. goto error;
  2518. }
  2519. if (likely(!locked)) lock_release(&c->write_lock);
  2520. /* send to tcp_main */
  2521. *resp=CONN_NEW_PENDING_WRITE;
  2522. n=len;
  2523. goto end;
  2524. }
  2525. /* n < 0 and not EAGAIN => write error */
  2526. /* if first write failed it's most likely a
  2527. connect error */
  2528. switch(errno){
  2529. case ENETUNREACH:
  2530. case EHOSTUNREACH: /* not posix for send() */
  2531. #ifdef USE_DST_BLACKLIST
  2532. dst_blacklist_su( BLST_ERR_CONNECT, c->rcv.proto,
  2533. &c->rcv.src_su, &c->send_flags, 0);
  2534. #endif /* USE_DST_BLACKLIST */
  2535. TCP_EV_CONNECT_UNREACHABLE(errno, TCP_LADDR(c),
  2536. TCP_LPORT(c), TCP_PSU(c), TCP_PROTO(c));
  2537. break;
  2538. case ECONNREFUSED:
  2539. case ECONNRESET:
  2540. #ifdef USE_DST_BLACKLIST
  2541. dst_blacklist_su( BLST_ERR_CONNECT, c->rcv.proto,
  2542. &c->rcv.src_su, &c->send_flags, 0);
  2543. #endif /* USE_DST_BLACKLIST */
  2544. TCP_EV_CONNECT_RST(errno, TCP_LADDR(c),
  2545. TCP_LPORT(c), TCP_PSU(c), TCP_PROTO(c));
  2546. break;
  2547. default:
  2548. TCP_EV_CONNECT_ERR(errno, TCP_LADDR(c),
  2549. TCP_LPORT(c), TCP_PSU(c), TCP_PROTO(c));
  2550. }
  2551. /* error: destroy it directly */
  2552. TCP_STATS_CONNECT_FAILED();
  2553. LM_ERR("%s: connect & send for %p failed:" " %s (%d)\n",
  2554. su2a(&c->rcv.src_su, sizeof(c->rcv.src_su)),
  2555. c, strerror(errno), errno);
  2556. goto error;
  2557. }
  2558. LM_INFO("quick connect for %p\n", c);
  2559. if (likely(c->state == S_CONN_CONNECT))
  2560. TCP_STATS_ESTABLISHED(S_CONN_CONNECT);
  2561. if (unlikely(send_flags.f & SND_F_CON_CLOSE)){
  2562. /* close after write => EOF => close immediately */
  2563. c->state=S_CONN_BAD;
  2564. /* tell our caller that it should drop this*/
  2565. *resp=CONN_EOF;
  2566. }else{
  2567. c->state=S_CONN_OK;
  2568. /* send to tcp_main */
  2569. *resp=CONN_NEW_COMPLETE;
  2570. }
  2571. end:
  2572. return n; /* >= 0 */
  2573. error:
  2574. *resp=CONN_ERROR;
  2575. return -1;
  2576. }
  2577. int tcp_init(struct socket_info* sock_info)
  2578. {
  2579. union sockaddr_union* addr;
  2580. int optval;
  2581. #ifdef HAVE_TCP_ACCEPT_FILTER
  2582. struct accept_filter_arg afa;
  2583. #endif /* HAVE_TCP_ACCEPT_FILTER */
  2584. #ifdef DISABLE_NAGLE
  2585. int flag;
  2586. struct protoent* pe;
  2587. if (tcp_proto_no==-1){ /* if not already set */
  2588. pe=getprotobyname("tcp");
  2589. if (pe==0){
  2590. LM_ERR("could not get TCP protocol number\n");
  2591. tcp_proto_no=-1;
  2592. }else{
  2593. tcp_proto_no=pe->p_proto;
  2594. }
  2595. }
  2596. #endif
  2597. addr=&sock_info->su;
  2598. /* sock_info->proto=PROTO_TCP; */
  2599. if (init_su(addr, &sock_info->address, sock_info->port_no)<0){
  2600. LM_ERR("could no init sockaddr_union\n");
  2601. goto error;
  2602. }
  2603. DBG("tcp_init: added %s\n", su2a(addr, sizeof(*addr)));
  2604. sock_info->socket=socket(AF2PF(addr->s.sa_family), SOCK_STREAM, 0);
  2605. if (sock_info->socket==-1){
  2606. LM_ERR("tcp_init: socket: %s\n", strerror(errno));
  2607. goto error;
  2608. }
  2609. #ifdef DISABLE_NAGLE
  2610. flag=1;
  2611. if ( (tcp_proto_no!=-1) &&
  2612. (setsockopt(sock_info->socket, tcp_proto_no , TCP_NODELAY,
  2613. &flag, sizeof(flag))<0) ){
  2614. LM_ERR("could not disable Nagle: %s\n", strerror(errno));
  2615. }
  2616. #endif
  2617. #if !defined(TCP_DONT_REUSEADDR)
  2618. /* Stevens, "Network Programming", Section 7.5, "Generic Socket
  2619. * Options": "...server started,..a child continues..on existing
  2620. * connection..listening server is restarted...call to bind fails
  2621. * ... ALL TCP servers should specify the SO_REUSEADDRE option
  2622. * to allow the server to be restarted in this situation
  2623. *
  2624. * Indeed, without this option, the server can't restart.
  2625. * -jiri
  2626. */
  2627. optval=1;
  2628. if (setsockopt(sock_info->socket, SOL_SOCKET, SO_REUSEADDR,
  2629. (void*)&optval, sizeof(optval))==-1) {
  2630. LM_ERR("setsockopt %s\n", strerror(errno));
  2631. goto error;
  2632. }
  2633. #endif
  2634. /* tos */
  2635. optval = tos;
  2636. if (setsockopt(sock_info->socket, IPPROTO_IP, IP_TOS, (void*)&optval,
  2637. sizeof(optval)) ==-1){
  2638. LM_WARN("setsockopt tos: %s\n", strerror(errno));
  2639. /* continue since this is not critical */
  2640. }
  2641. #ifdef HAVE_TCP_DEFER_ACCEPT
  2642. /* linux only */
  2643. if ((optval=cfg_get(tcp, tcp_cfg, defer_accept))){
  2644. if (setsockopt(sock_info->socket, IPPROTO_TCP, TCP_DEFER_ACCEPT,
  2645. (void*)&optval, sizeof(optval)) ==-1){
  2646. LM_WARN("setsockopt TCP_DEFER_ACCEPT %s\n", strerror(errno));
  2647. /* continue since this is not critical */
  2648. }
  2649. }
  2650. #endif /* HAVE_TCP_DEFFER_ACCEPT */
  2651. #ifdef HAVE_TCP_SYNCNT
  2652. if ((optval=cfg_get(tcp, tcp_cfg, syncnt))){
  2653. if (setsockopt(sock_info->socket, IPPROTO_TCP, TCP_SYNCNT, &optval,
  2654. sizeof(optval))<0){
  2655. LM_WARN("failed to set maximum SYN retr. count: %s\n", strerror(errno));
  2656. }
  2657. }
  2658. #endif
  2659. #ifdef HAVE_TCP_LINGER2
  2660. if ((optval=cfg_get(tcp, tcp_cfg, linger2))){
  2661. if (setsockopt(sock_info->socket, IPPROTO_TCP, TCP_LINGER2, &optval,
  2662. sizeof(optval))<0){
  2663. LM_WARN("failed to set maximum LINGER2 timeout: %s\n", strerror(errno));
  2664. }
  2665. }
  2666. #endif
  2667. init_sock_keepalive(sock_info->socket);
  2668. if (bind(sock_info->socket, &addr->s, sockaddru_len(*addr))==-1){
  2669. LM_ERR("bind(%x, %p, %d) on %s:%d : %s\n",
  2670. sock_info->socket, &addr->s,
  2671. (unsigned)sockaddru_len(*addr),
  2672. sock_info->address_str.s,
  2673. sock_info->port_no,
  2674. strerror(errno));
  2675. goto error;
  2676. }
  2677. if (listen(sock_info->socket, TCP_LISTEN_BACKLOG)==-1){
  2678. LM_ERR("listen(%x, %p, %d) on %s: %s\n",
  2679. sock_info->socket, &addr->s,
  2680. (unsigned)sockaddru_len(*addr),
  2681. sock_info->address_str.s,
  2682. strerror(errno));
  2683. goto error;
  2684. }
  2685. #ifdef HAVE_TCP_ACCEPT_FILTER
  2686. /* freebsd */
  2687. if (cfg_get(tcp, tcp_cfg, defer_accept)){
  2688. memset(&afa, 0, sizeof(afa));
  2689. strcpy(afa.af_name, "dataready");
  2690. if (setsockopt(sock_info->socket, SOL_SOCKET, SO_ACCEPTFILTER,
  2691. (void*)&afa, sizeof(afa)) ==-1){
  2692. LM_WARN("setsockopt SO_ACCEPTFILTER %s\n",
  2693. strerror(errno));
  2694. /* continue since this is not critical */
  2695. }
  2696. }
  2697. #endif /* HAVE_TCP_ACCEPT_FILTER */
  2698. return 0;
  2699. error:
  2700. if (sock_info->socket!=-1){
  2701. tcp_safe_close(sock_info->socket);
  2702. sock_info->socket=-1;
  2703. }
  2704. return -1;
  2705. }
  2706. /* close tcp_main's fd from a tcpconn
  2707. * WARNING: call only in tcp_main context */
  2708. inline static void tcpconn_close_main_fd(struct tcp_connection* tcpconn)
  2709. {
  2710. int fd;
  2711. fd=tcpconn->s;
  2712. #ifdef USE_TLS
  2713. if (tcpconn->type==PROTO_TLS || tcpconn->type==PROTO_WSS)
  2714. tls_close(tcpconn, fd);
  2715. #endif
  2716. #ifdef TCP_FD_CACHE
  2717. if (likely(cfg_get(tcp, tcp_cfg, fd_cache))) shutdown(fd, SHUT_RDWR);
  2718. #endif /* TCP_FD_CACHE */
  2719. if (unlikely(tcp_safe_close(fd)<0))
  2720. LM_ERR("(%p): %s close(%d) failed (flags 0x%x): %s (%d)\n", tcpconn,
  2721. su2a(&tcpconn->rcv.src_su, sizeof(tcpconn->rcv.src_su)),
  2722. fd, tcpconn->flags, strerror(errno), errno);
  2723. tcpconn->s=-1;
  2724. }
  2725. /* dec refcnt & frees the connection if refcnt==0
  2726. * returns 1 if the connection is freed, 0 otherwise
  2727. *
  2728. * WARNING: use only from child processes */
  2729. inline static int tcpconn_chld_put(struct tcp_connection* tcpconn)
  2730. {
  2731. if (unlikely(atomic_dec_and_test(&tcpconn->refcnt))){
  2732. DBG("tcpconn_chld_put: destroying connection %p (%d, %d) "
  2733. "flags %04x\n", tcpconn, tcpconn->id,
  2734. tcpconn->s, tcpconn->flags);
  2735. /* sanity checks */
  2736. membar_read_atomic_op(); /* make sure we see the current flags */
  2737. if (unlikely(!(tcpconn->flags & F_CONN_FD_CLOSED) ||
  2738. (tcpconn->flags &
  2739. (F_CONN_HASHED|F_CONN_MAIN_TIMER|
  2740. F_CONN_READ_W|F_CONN_WRITE_W)) )){
  2741. LM_CRIT("%p bad flags = %0x\n", tcpconn, tcpconn->flags);
  2742. abort();
  2743. }
  2744. _tcpconn_free(tcpconn); /* destroys also the wbuf_q if still present*/
  2745. return 1;
  2746. }
  2747. return 0;
  2748. }
  2749. /* simple destroy function (the connection should be already removed
  2750. * from the hashes. refcnt 0 and the fds should not be watched anymore for IO)
  2751. */
  2752. inline static void tcpconn_destroy(struct tcp_connection* tcpconn)
  2753. {
  2754. DBG("tcpconn_destroy: destroying connection %p (%d, %d) "
  2755. "flags %04x\n", tcpconn, tcpconn->id,
  2756. tcpconn->s, tcpconn->flags);
  2757. if (unlikely(tcpconn->flags & F_CONN_HASHED)){
  2758. LM_CRIT("called with hashed connection (%p)\n", tcpconn);
  2759. /* try to continue */
  2760. if (likely(tcpconn->flags & F_CONN_MAIN_TIMER))
  2761. local_timer_del(&tcp_main_ltimer, &tcpconn->timer);
  2762. TCPCONN_LOCK;
  2763. _tcpconn_detach(tcpconn);
  2764. tcpconn->flags &= ~(F_CONN_HASHED|F_CONN_MAIN_TIMER);
  2765. TCPCONN_UNLOCK;
  2766. }
  2767. if (likely(!(tcpconn->flags & F_CONN_FD_CLOSED))){
  2768. tcpconn_close_main_fd(tcpconn);
  2769. tcpconn->flags|=F_CONN_FD_CLOSED;
  2770. (*tcp_connections_no)--;
  2771. if (unlikely(tcpconn->type==PROTO_TLS || tcpconn->type==PROTO_WSS))
  2772. (*tls_connections_no)--;
  2773. }
  2774. _tcpconn_free(tcpconn); /* destroys also the wbuf_q if still present*/
  2775. }
  2776. /* tries to destroy the connection: dec. refcnt and if 0 destroys the
  2777. * connection, else it will mark it as BAD and close the main fds
  2778. *
  2779. * returns 1 if the connection was destroyed, 0 otherwise
  2780. *
  2781. * WARNING: - the connection _has_ to be removed from the hash and timer
  2782. * first (use tcpconn_try_unhash() for this )
  2783. * - the fd should not be watched anymore (io_watch_del()...)
  2784. * - must be called _only_ from the tcp_main process context
  2785. * (or else the fd will remain open)
  2786. */
  2787. inline static int tcpconn_put_destroy(struct tcp_connection* tcpconn)
  2788. {
  2789. if (unlikely((tcpconn->flags &
  2790. (F_CONN_WRITE_W|F_CONN_HASHED|F_CONN_MAIN_TIMER|F_CONN_READ_W)) )){
  2791. /* sanity check */
  2792. if (unlikely(tcpconn->flags & F_CONN_HASHED)){
  2793. LM_CRIT("called with hashed and/or"
  2794. "on timer connection (%p), flags = %0x\n",
  2795. tcpconn, tcpconn->flags);
  2796. /* try to continue */
  2797. if (likely(tcpconn->flags & F_CONN_MAIN_TIMER))
  2798. local_timer_del(&tcp_main_ltimer, &tcpconn->timer);
  2799. TCPCONN_LOCK;
  2800. _tcpconn_detach(tcpconn);
  2801. tcpconn->flags &= ~(F_CONN_HASHED|F_CONN_MAIN_TIMER);
  2802. TCPCONN_UNLOCK;
  2803. }else{
  2804. LM_CRIT("%p flags = %0x\n", tcpconn, tcpconn->flags);
  2805. }
  2806. }
  2807. tcpconn->state=S_CONN_BAD;
  2808. /* in case it's still in a reader timer */
  2809. tcpconn->timeout=get_ticks_raw();
  2810. /* fast close: close fds now */
  2811. if (likely(!(tcpconn->flags & F_CONN_FD_CLOSED))){
  2812. tcpconn_close_main_fd(tcpconn);
  2813. tcpconn->flags|=F_CONN_FD_CLOSED;
  2814. (*tcp_connections_no)--;
  2815. if (unlikely(tcpconn->type==PROTO_TLS || tcpconn->type==PROTO_WSS))
  2816. (*tls_connections_no)--;
  2817. }
  2818. /* all the flags / ops on the tcpconn must be done prior to decrementing
  2819. * the refcnt. and at least a membar_write_atomic_op() mem. barrier or
  2820. * a mb_atomic_* op must * be used to make sure all the changed flags are
  2821. * written into memory prior to the new refcnt value */
  2822. if (unlikely(mb_atomic_dec_and_test(&tcpconn->refcnt))){
  2823. _tcpconn_free(tcpconn);
  2824. return 1;
  2825. }
  2826. return 0;
  2827. }
  2828. /* try to remove a connection from the hashes and timer.
  2829. * returns 1 if the connection was removed, 0 if not (connection not in
  2830. * hash)
  2831. *
  2832. * WARNING: call it only in the tcp_main process context or else the
  2833. * timer removal won't work.
  2834. */
  2835. inline static int tcpconn_try_unhash(struct tcp_connection* tcpconn)
  2836. {
  2837. if (likely(tcpconn->flags & F_CONN_HASHED)){
  2838. tcpconn->state=S_CONN_BAD;
  2839. if (likely(tcpconn->flags & F_CONN_MAIN_TIMER)){
  2840. local_timer_del(&tcp_main_ltimer, &tcpconn->timer);
  2841. tcpconn->flags&=~F_CONN_MAIN_TIMER;
  2842. }else
  2843. /* in case it's still in a reader timer */
  2844. tcpconn->timeout=get_ticks_raw();
  2845. TCPCONN_LOCK;
  2846. if (tcpconn->flags & F_CONN_HASHED){
  2847. tcpconn->flags&=~F_CONN_HASHED;
  2848. _tcpconn_detach(tcpconn);
  2849. TCPCONN_UNLOCK;
  2850. }else{
  2851. /* tcp_send was faster and did unhash it itself */
  2852. TCPCONN_UNLOCK;
  2853. return 0;
  2854. }
  2855. #ifdef TCP_ASYNC
  2856. /* empty possible write buffers (optional) */
  2857. if (unlikely(_wbufq_non_empty(tcpconn))){
  2858. lock_get(&tcpconn->write_lock);
  2859. /* check again, while holding the lock */
  2860. if (likely(_wbufq_non_empty(tcpconn)))
  2861. _wbufq_destroy(&tcpconn->wbuf_q);
  2862. lock_release(&tcpconn->write_lock);
  2863. }
  2864. #endif /* TCP_ASYNC */
  2865. return 1;
  2866. }
  2867. return 0;
  2868. }
  2869. #ifdef SEND_FD_QUEUE
  2870. struct send_fd_info{
  2871. struct tcp_connection* tcp_conn;
  2872. ticks_t expire;
  2873. int unix_sock;
  2874. unsigned int retries; /* debugging */
  2875. };
  2876. struct tcp_send_fd_q{
  2877. struct send_fd_info* data; /* buffer */
  2878. struct send_fd_info* crt; /* pointer inside the buffer */
  2879. struct send_fd_info* end; /* points after the last valid position */
  2880. };
  2881. static struct tcp_send_fd_q send2child_q;
  2882. static int send_fd_queue_init(struct tcp_send_fd_q *q, unsigned int size)
  2883. {
  2884. q->data=pkg_malloc(size*sizeof(struct send_fd_info));
  2885. if (q->data==0){
  2886. LM_ERR("out of memory\n");
  2887. return -1;
  2888. }
  2889. q->crt=&q->data[0];
  2890. q->end=&q->data[size];
  2891. return 0;
  2892. }
  2893. static void send_fd_queue_destroy(struct tcp_send_fd_q *q)
  2894. {
  2895. if (q->data){
  2896. pkg_free(q->data);
  2897. q->data=0;
  2898. q->crt=q->end=0;
  2899. }
  2900. }
  2901. static int init_send_fd_queues(void)
  2902. {
  2903. if (send_fd_queue_init(&send2child_q, SEND_FD_QUEUE_SIZE)!=0)
  2904. goto error;
  2905. return 0;
  2906. error:
  2907. LM_ERR("init failed\n");
  2908. return -1;
  2909. }
  2910. static void destroy_send_fd_queues(void)
  2911. {
  2912. send_fd_queue_destroy(&send2child_q);
  2913. }
  2914. inline static int send_fd_queue_add( struct tcp_send_fd_q* q,
  2915. int unix_sock,
  2916. struct tcp_connection *t)
  2917. {
  2918. struct send_fd_info* tmp;
  2919. unsigned long new_size;
  2920. if (q->crt>=q->end){
  2921. new_size=q->end-&q->data[0];
  2922. if (new_size< MAX_SEND_FD_QUEUE_SIZE/2){
  2923. new_size*=2;
  2924. }else new_size=MAX_SEND_FD_QUEUE_SIZE;
  2925. if (unlikely(q->crt>=&q->data[new_size])){
  2926. LM_ERR("queue full: %ld/%ld\n",
  2927. (long)(q->crt-&q->data[0]-1), new_size);
  2928. goto error;
  2929. }
  2930. LM_CRIT("queue full: %ld, extending to %ld\n",
  2931. (long)(q->end-&q->data[0]), new_size);
  2932. tmp=pkg_realloc(q->data, new_size*sizeof(struct send_fd_info));
  2933. if (unlikely(tmp==0)){
  2934. LM_ERR("out of memory\n");
  2935. goto error;
  2936. }
  2937. q->crt=(q->crt-&q->data[0])+tmp;
  2938. q->data=tmp;
  2939. q->end=&q->data[new_size];
  2940. }
  2941. q->crt->tcp_conn=t;
  2942. q->crt->unix_sock=unix_sock;
  2943. q->crt->expire=get_ticks_raw()+SEND_FD_QUEUE_TIMEOUT;
  2944. q->crt->retries=0;
  2945. q->crt++;
  2946. return 0;
  2947. error:
  2948. return -1;
  2949. }
  2950. inline static void send_fd_queue_run(struct tcp_send_fd_q* q)
  2951. {
  2952. struct send_fd_info* p;
  2953. struct send_fd_info* t;
  2954. for (p=t=&q->data[0]; p<q->crt; p++){
  2955. if (unlikely(p->tcp_conn->state == S_CONN_BAD ||
  2956. p->tcp_conn->flags & F_CONN_FD_CLOSED ||
  2957. p->tcp_conn->s ==-1)) {
  2958. /* bad and/or already closed connection => remove */
  2959. goto rm_con;
  2960. }
  2961. if (unlikely(send_fd(p->unix_sock, &(p->tcp_conn),
  2962. sizeof(struct tcp_connection*), p->tcp_conn->s)<=0)){
  2963. if ( ((errno==EAGAIN)||(errno==EWOULDBLOCK)) &&
  2964. ((s_ticks_t)(p->expire-get_ticks_raw())>0)){
  2965. /* leave in queue for a future try */
  2966. *t=*p;
  2967. t->retries++;
  2968. t++;
  2969. }else{
  2970. LM_ERR("send_fd failed on socket %d , queue entry %ld, retries %d,"
  2971. " connection %p, tcp socket %d, errno=%d (%s) \n",
  2972. p->unix_sock, (long)(p-&q->data[0]), p->retries,
  2973. p->tcp_conn, p->tcp_conn->s, errno,
  2974. strerror(errno));
  2975. rm_con:
  2976. #ifdef TCP_ASYNC
  2977. /* if a connection is on the send_fd queue it means it's
  2978. not watched for read anymore => could be watched only for
  2979. write */
  2980. if (p->tcp_conn->flags & F_CONN_WRITE_W){
  2981. io_watch_del(&io_h, p->tcp_conn->s, -1, IO_FD_CLOSING);
  2982. p->tcp_conn->flags &=~F_CONN_WRITE_W;
  2983. }
  2984. #endif
  2985. p->tcp_conn->flags &= ~F_CONN_READER;
  2986. if (likely(tcpconn_try_unhash(p->tcp_conn)))
  2987. tcpconn_put(p->tcp_conn);
  2988. tcpconn_put_destroy(p->tcp_conn); /* dec refcnt & destroy */
  2989. }
  2990. }
  2991. }
  2992. q->crt=t;
  2993. }
  2994. #else
  2995. #define send_fd_queue_run(q)
  2996. #endif
  2997. /* non blocking write() on a tcpconnection, unsafe version (should be called
  2998. * while holding c->write_lock). The fd should be non-blocking.
  2999. * returns number of bytes written on success, -1 on error (and sets errno)
  3000. */
  3001. int _tcpconn_write_nb(int fd, struct tcp_connection* c,
  3002. const char* buf, int len)
  3003. {
  3004. int n;
  3005. again:
  3006. n=send(fd, buf, len,
  3007. #ifdef HAVE_MSG_NOSIGNAL
  3008. MSG_NOSIGNAL
  3009. #else
  3010. 0
  3011. #endif /* HAVE_MSG_NOSIGNAL */
  3012. );
  3013. if (unlikely(n<0)){
  3014. if (errno==EINTR) goto again;
  3015. }
  3016. return n;
  3017. }
  3018. /* handles io from a tcp child process
  3019. * params: tcp_c - pointer in the tcp_children array, to the entry for
  3020. * which an io event was detected
  3021. * fd_i - fd index in the fd_array (usefull for optimizing
  3022. * io_watch_deletes)
  3023. * returns: handle_* return convention: -1 on error, 0 on EAGAIN (no more
  3024. * io events queued), >0 on success. success/error refer only to
  3025. * the reads from the fd.
  3026. */
  3027. inline static int handle_tcp_child(struct tcp_child* tcp_c, int fd_i)
  3028. {
  3029. struct tcp_connection* tcpconn;
  3030. long response[2];
  3031. int cmd;
  3032. int bytes;
  3033. int n;
  3034. ticks_t t;
  3035. ticks_t crt_timeout;
  3036. ticks_t con_lifetime;
  3037. if (unlikely(tcp_c->unix_sock<=0)){
  3038. /* (we can't have a fd==0, 0 is never closed )*/
  3039. LM_CRIT("fd %d for %d (pid %ld, ser no %d)\n", tcp_c->unix_sock,
  3040. (int)(tcp_c-&tcp_children[0]), (long)tcp_c->pid,
  3041. tcp_c->proc_no);
  3042. goto error;
  3043. }
  3044. /* read until sizeof(response)
  3045. * (this is a SOCK_STREAM so read is not atomic) */
  3046. bytes=recv_all(tcp_c->unix_sock, response, sizeof(response), MSG_DONTWAIT);
  3047. if (unlikely(bytes<(int)sizeof(response))){
  3048. if (bytes==0){
  3049. /* EOF -> bad, child has died */
  3050. DBG("DBG: handle_tcp_child: dead tcp child %d (pid %ld, no %d)"
  3051. " (shutting down?)\n", (int)(tcp_c-&tcp_children[0]),
  3052. (long)tcp_c->pid, tcp_c->proc_no );
  3053. /* don't listen on it any more */
  3054. io_watch_del(&io_h, tcp_c->unix_sock, fd_i, 0);
  3055. goto error; /* eof. so no more io here, it's ok to return error */
  3056. }else if (bytes<0){
  3057. /* EAGAIN is ok if we try to empty the buffer
  3058. * e.g.: SIGIO_RT overflow mode or EPOLL ET */
  3059. if ((errno!=EAGAIN) && (errno!=EWOULDBLOCK)){
  3060. LM_CRIT("read from tcp child %ld (pid %ld, no %d) %s [%d]\n",
  3061. (long)(tcp_c-&tcp_children[0]), (long)tcp_c->pid,
  3062. tcp_c->proc_no, strerror(errno), errno );
  3063. }else{
  3064. bytes=0;
  3065. }
  3066. /* try to ignore ? */
  3067. goto end;
  3068. }else{
  3069. /* should never happen */
  3070. LM_CRIT("too few bytes received (%d)\n", bytes );
  3071. bytes=0; /* something was read so there is no error; otoh if
  3072. receive_fd returned less then requested => the receive
  3073. buffer is empty => no more io queued on this fd */
  3074. goto end;
  3075. }
  3076. }
  3077. DBG("handle_tcp_child: reader response= %lx, %ld from %d \n",
  3078. response[0], response[1], (int)(tcp_c-&tcp_children[0]));
  3079. cmd=response[1];
  3080. tcpconn=(struct tcp_connection*)response[0];
  3081. if (unlikely(tcpconn==0)){
  3082. /* should never happen */
  3083. LM_CRIT("null tcpconn pointer received from tcp child %d (pid %ld): %lx, %lx\n",
  3084. (int)(tcp_c-&tcp_children[0]), (long)tcp_c->pid,
  3085. response[0], response[1]) ;
  3086. goto end;
  3087. }
  3088. switch(cmd){
  3089. case CONN_RELEASE:
  3090. tcp_c->busy--;
  3091. if (unlikely(tcpconn_put(tcpconn))){
  3092. /* if refcnt was 1 => it was used only in the
  3093. tcp reader => it's not hashed or watched for IO
  3094. anymore => no need to io_watch_del() */
  3095. tcpconn_destroy(tcpconn);
  3096. break;
  3097. }
  3098. if (unlikely(tcpconn->state==S_CONN_BAD)){
  3099. if (tcpconn_try_unhash(tcpconn)) {
  3100. #ifdef TCP_ASYNC
  3101. if (unlikely(tcpconn->flags & F_CONN_WRITE_W)){
  3102. io_watch_del(&io_h, tcpconn->s, -1, IO_FD_CLOSING);
  3103. tcpconn->flags &= ~F_CONN_WRITE_W;
  3104. }
  3105. #endif /* TCP_ASYNC */
  3106. tcpconn_put_destroy(tcpconn);
  3107. }
  3108. #ifdef TCP_ASYNC
  3109. else if (unlikely(tcpconn->flags & F_CONN_WRITE_W)){
  3110. /* should never happen: if it's already unhashed, it
  3111. should not be watched for IO */
  3112. BUG("unhashed connection watched for write\n");
  3113. io_watch_del(&io_h, tcpconn->s, -1, 0);
  3114. tcpconn->flags &= ~F_CONN_WRITE_W;
  3115. }
  3116. #endif /* TCP_ASYNC */
  3117. break;
  3118. }
  3119. /* update the timeout*/
  3120. t=get_ticks_raw();
  3121. con_lifetime=cfg_get(tcp, tcp_cfg, con_lifetime);
  3122. tcpconn->timeout=t+con_lifetime;
  3123. crt_timeout=con_lifetime;
  3124. #ifdef TCP_ASYNC
  3125. if (unlikely(cfg_get(tcp, tcp_cfg, async) &&
  3126. _wbufq_non_empty(tcpconn) )){
  3127. if (unlikely(TICKS_GE(t, tcpconn->wbuf_q.wr_timeout))){
  3128. DBG("handle_tcp_child: wr. timeout on CONN_RELEASE for %p "
  3129. "refcnt= %d\n", tcpconn,
  3130. atomic_get(&tcpconn->refcnt));
  3131. /* timeout */
  3132. if (unlikely(tcpconn->state==S_CONN_CONNECT)){
  3133. #ifdef USE_DST_BLACKLIST
  3134. (void)dst_blacklist_su( BLST_ERR_CONNECT,
  3135. tcpconn->rcv.proto,
  3136. &tcpconn->rcv.src_su,
  3137. &tcpconn->send_flags, 0);
  3138. #endif /* USE_DST_BLACKLIST */
  3139. TCP_EV_CONNECT_TIMEOUT(0, TCP_LADDR(tcpconn),
  3140. TCP_LPORT(tcpconn), TCP_PSU(tcpconn),
  3141. TCP_PROTO(tcpconn));
  3142. TCP_STATS_CONNECT_FAILED();
  3143. }else{
  3144. #ifdef USE_DST_BLACKLIST
  3145. (void)dst_blacklist_su( BLST_ERR_SEND,
  3146. tcpconn->rcv.proto,
  3147. &tcpconn->rcv.src_su,
  3148. &tcpconn->send_flags, 0);
  3149. #endif /* USE_DST_BLACKLIST */
  3150. TCP_EV_SEND_TIMEOUT(0, &tcpconn->rcv);
  3151. TCP_STATS_SEND_TIMEOUT();
  3152. }
  3153. if (tcpconn_try_unhash(tcpconn)) {
  3154. if (unlikely(tcpconn->flags & F_CONN_WRITE_W)){
  3155. io_watch_del(&io_h, tcpconn->s, -1, IO_FD_CLOSING);
  3156. tcpconn->flags&=~F_CONN_WRITE_W;
  3157. }
  3158. tcpconn_put_destroy(tcpconn);
  3159. } else if (unlikely(tcpconn->flags & F_CONN_WRITE_W)){
  3160. BUG("unhashed connection watched for write\n");
  3161. io_watch_del(&io_h, tcpconn->s, -1, 0);
  3162. tcpconn->flags&=~F_CONN_WRITE_W;
  3163. }
  3164. break;
  3165. }else{
  3166. crt_timeout=MIN_unsigned(con_lifetime,
  3167. tcpconn->wbuf_q.wr_timeout-t);
  3168. }
  3169. }
  3170. #endif /* TCP_ASYNC */
  3171. /* re-activate the timer */
  3172. tcpconn->timer.f=tcpconn_main_timeout;
  3173. local_timer_reinit(&tcpconn->timer);
  3174. local_timer_add(&tcp_main_ltimer, &tcpconn->timer, crt_timeout, t);
  3175. /* must be after the de-ref*/
  3176. tcpconn->flags|=(F_CONN_MAIN_TIMER|F_CONN_READ_W|F_CONN_WANTS_RD);
  3177. tcpconn->flags&=~(F_CONN_READER|F_CONN_OOB_DATA);
  3178. #ifdef TCP_ASYNC
  3179. if (unlikely(tcpconn->flags & F_CONN_WRITE_W))
  3180. n=io_watch_chg(&io_h, tcpconn->s, POLLIN| POLLOUT, -1);
  3181. else
  3182. #endif /* TCP_ASYNC */
  3183. n=io_watch_add(&io_h, tcpconn->s, POLLIN, F_TCPCONN, tcpconn);
  3184. if (unlikely(n<0)){
  3185. LM_CRIT("failed to add new socket to the fd list\n");
  3186. tcpconn->flags&=~F_CONN_READ_W;
  3187. if (tcpconn_try_unhash(tcpconn)) {
  3188. #ifdef TCP_ASYNC
  3189. if (unlikely(tcpconn->flags & F_CONN_WRITE_W)){
  3190. io_watch_del(&io_h, tcpconn->s, -1, IO_FD_CLOSING);
  3191. tcpconn->flags&=~F_CONN_WRITE_W;
  3192. }
  3193. #endif /* TCP_ASYNC */
  3194. tcpconn_put_destroy(tcpconn);
  3195. }
  3196. #ifdef TCP_ASYNC
  3197. else if (unlikely(tcpconn->flags & F_CONN_WRITE_W)) {
  3198. BUG("unhashed connection watched for write\n");
  3199. io_watch_del(&io_h, tcpconn->s, -1, 0);
  3200. tcpconn->flags&=~F_CONN_WRITE_W;
  3201. }
  3202. #endif /* TCP_ASYNC */
  3203. break;
  3204. }
  3205. DBG("handle_tcp_child: CONN_RELEASE %p refcnt= %d\n",
  3206. tcpconn, atomic_get(&tcpconn->refcnt));
  3207. break;
  3208. case CONN_ERROR:
  3209. case CONN_DESTROY:
  3210. case CONN_EOF:
  3211. /* WARNING: this will auto-dec. refcnt! */
  3212. tcp_c->busy--;
  3213. /* main doesn't listen on it => we don't have to delete it
  3214. if (tcpconn->s!=-1)
  3215. io_watch_del(&io_h, tcpconn->s, -1, IO_FD_CLOSING);
  3216. */
  3217. #ifdef TCP_ASYNC
  3218. if ((tcpconn->flags & F_CONN_WRITE_W) && (tcpconn->s!=-1)){
  3219. io_watch_del(&io_h, tcpconn->s, -1, IO_FD_CLOSING);
  3220. tcpconn->flags&=~F_CONN_WRITE_W;
  3221. }
  3222. #endif /* TCP_ASYNC */
  3223. if (tcpconn_try_unhash(tcpconn))
  3224. tcpconn_put(tcpconn);
  3225. tcpconn_put_destroy(tcpconn); /* deref & delete if refcnt==0 */
  3226. break;
  3227. default:
  3228. LM_CRIT("unknown cmd %d from tcp reader %d\n",
  3229. cmd, (int)(tcp_c-&tcp_children[0]));
  3230. }
  3231. end:
  3232. return bytes;
  3233. error:
  3234. return -1;
  3235. }
  3236. /* handles io from a "generic" ser process (get fd or new_fd from a tcp_send)
  3237. *
  3238. * params: p - pointer in the ser processes array (pt[]), to the entry for
  3239. * which an io event was detected
  3240. * fd_i - fd index in the fd_array (usefull for optimizing
  3241. * io_watch_deletes)
  3242. * returns: handle_* return convention:
  3243. * -1 on error reading from the fd,
  3244. * 0 on EAGAIN or when no more io events are queued
  3245. * (receive buffer empty),
  3246. * >0 on successfull reads from the fd (the receive buffer might
  3247. * be non-empty).
  3248. */
  3249. inline static int handle_ser_child(struct process_table* p, int fd_i)
  3250. {
  3251. struct tcp_connection* tcpconn;
  3252. struct tcp_connection* tmp;
  3253. long response[2];
  3254. int cmd;
  3255. int bytes;
  3256. int ret;
  3257. int fd;
  3258. int flags;
  3259. ticks_t t;
  3260. ticks_t con_lifetime;
  3261. #ifdef TCP_ASYNC
  3262. ticks_t nxt_timeout;
  3263. #endif /* TCP_ASYNC */
  3264. ret=-1;
  3265. if (unlikely(p->unix_sock<=0)){
  3266. /* (we can't have a fd==0, 0 is never closed )*/
  3267. LM_CRIT("fd %d for %d (pid %d)\n", p->unix_sock, (int)(p-&pt[0]), p->pid);
  3268. goto error;
  3269. }
  3270. /* get all bytes and the fd (if transmitted)
  3271. * (this is a SOCK_STREAM so read is not atomic) */
  3272. bytes=receive_fd(p->unix_sock, response, sizeof(response), &fd,
  3273. MSG_DONTWAIT);
  3274. if (unlikely(bytes<(int)sizeof(response))){
  3275. /* too few bytes read */
  3276. if (bytes==0){
  3277. /* EOF -> bad, child has died */
  3278. DBG("DBG: handle_ser_child: dead child %d, pid %d"
  3279. " (shutting down?)\n", (int)(p-&pt[0]), p->pid);
  3280. /* don't listen on it any more */
  3281. io_watch_del(&io_h, p->unix_sock, fd_i, 0);
  3282. goto error; /* child dead => no further io events from it */
  3283. }else if (bytes<0){
  3284. /* EAGAIN is ok if we try to empty the buffer
  3285. * e.g: SIGIO_RT overflow mode or EPOLL ET */
  3286. if ((errno!=EAGAIN) && (errno!=EWOULDBLOCK)){
  3287. LM_CRIT("read from child %d (pid %d): %s [%d]\n",
  3288. (int)(p-&pt[0]), p->pid,
  3289. strerror(errno), errno);
  3290. ret=-1;
  3291. }else{
  3292. ret=0;
  3293. }
  3294. /* try to ignore ? */
  3295. goto end;
  3296. }else{
  3297. /* should never happen */
  3298. LM_CRIT("too few bytes received (%d)\n", bytes );
  3299. ret=0; /* something was read so there is no error; otoh if
  3300. receive_fd returned less then requested => the receive
  3301. buffer is empty => no more io queued on this fd */
  3302. goto end;
  3303. }
  3304. }
  3305. ret=1; /* something was received, there might be more queued */
  3306. DBG("handle_ser_child: read response= %lx, %ld, fd %d from %d (%d)\n",
  3307. response[0], response[1], fd, (int)(p-&pt[0]), p->pid);
  3308. cmd=response[1];
  3309. tcpconn=(struct tcp_connection*)response[0];
  3310. if (unlikely(tcpconn==0)){
  3311. LM_CRIT("null tcpconn pointer received from child %d (pid %d): %lx, %lx\n",
  3312. (int)(p-&pt[0]), p->pid, response[0], response[1]) ;
  3313. goto end;
  3314. }
  3315. switch(cmd){
  3316. case CONN_ERROR:
  3317. LM_ERR("received CON_ERROR for %p (id %d), refcnt %d, flags 0x%0x\n",
  3318. tcpconn, tcpconn->id, atomic_get(&tcpconn->refcnt),
  3319. tcpconn->flags);
  3320. case CONN_EOF: /* forced EOF after full send, due to send flags */
  3321. #ifdef TCP_CONNECT_WAIT
  3322. /* if the connection is marked as pending => it might be on
  3323. * the way of reaching tcp_main (e.g. CONN_NEW_COMPLETE or
  3324. * CONN_NEW_PENDING_WRITE) => it cannot be destroyed here,
  3325. * it will be destroyed on CONN_NEW_COMPLETE /
  3326. * CONN_NEW_PENDING_WRITE or in the send error case by the
  3327. * sender process */
  3328. if (unlikely(tcpconn->flags & F_CONN_PENDING)) {
  3329. if (tcpconn_put(tcpconn))
  3330. tcpconn_destroy(tcpconn);
  3331. /* no need for io_watch_del(), if PENDING it should not
  3332. be watched for anything in tcp_main */
  3333. break;
  3334. }
  3335. #endif /* TCP_CONNECT_WAIT */
  3336. if ( tcpconn_try_unhash(tcpconn) )
  3337. tcpconn_put(tcpconn);
  3338. if ( ((tcpconn->flags & (F_CONN_WRITE_W|F_CONN_READ_W)) ) &&
  3339. (tcpconn->s!=-1)){
  3340. io_watch_del(&io_h, tcpconn->s, -1, IO_FD_CLOSING);
  3341. tcpconn->flags&=~(F_CONN_WRITE_W|F_CONN_READ_W);
  3342. }
  3343. tcpconn_put_destroy(tcpconn); /* dec refcnt & destroy on 0 */
  3344. break;
  3345. case CONN_GET_FD:
  3346. /* send the requested FD */
  3347. /* WARNING: take care of setting refcnt properly to
  3348. * avoid race conditions */
  3349. if (unlikely(tcpconn->state == S_CONN_BAD ||
  3350. (tcpconn->flags & F_CONN_FD_CLOSED) ||
  3351. tcpconn->s ==-1)) {
  3352. /* connection is already marked as bad and/or has no
  3353. fd => don't try to send the fd (trying to send a
  3354. closed fd _will_ fail) */
  3355. tmp = 0;
  3356. if (unlikely(send_all(p->unix_sock, &tmp, sizeof(tmp)) <= 0))
  3357. BUG("handle_ser_child: CONN_GET_FD: send_all failed\n");
  3358. /* no need to attempt to destroy the connection, it should
  3359. be already in the process of being destroyed */
  3360. } else if (unlikely(send_fd(p->unix_sock, &tcpconn,
  3361. sizeof(tcpconn), tcpconn->s)<=0)){
  3362. LM_ERR("CONN_GET_FD: send_fd failed\n");
  3363. /* try sending error (better then not sending anything) */
  3364. tmp = 0;
  3365. if (unlikely(send_all(p->unix_sock, &tmp, sizeof(tmp)) <= 0))
  3366. BUG("handle_ser_child: CONN_GET_FD:"
  3367. " send_fd send_all fallback failed\n");
  3368. }
  3369. break;
  3370. case CONN_NEW:
  3371. /* update the fd in the requested tcpconn*/
  3372. /* WARNING: take care of setting refcnt properly to
  3373. * avoid race conditions */
  3374. if (unlikely(fd==-1)){
  3375. LM_CRIT("CONN_NEW: no fd received\n");
  3376. tcpconn->flags|=F_CONN_FD_CLOSED;
  3377. tcpconn_put_destroy(tcpconn);
  3378. break;
  3379. }
  3380. (*tcp_connections_no)++;
  3381. if (unlikely(tcpconn->type==PROTO_TLS))
  3382. (*tls_connections_no)++;
  3383. tcpconn->s=fd;
  3384. /* add tcpconn to the list*/
  3385. tcpconn_add(tcpconn);
  3386. /* update the timeout*/
  3387. t=get_ticks_raw();
  3388. con_lifetime=cfg_get(tcp, tcp_cfg, con_lifetime);
  3389. tcpconn->timeout=t+con_lifetime;
  3390. /* activate the timer (already properly init. in tcpconn_new())
  3391. * no need for reinit */
  3392. local_timer_add(&tcp_main_ltimer, &tcpconn->timer,
  3393. con_lifetime, t);
  3394. tcpconn->flags|=(F_CONN_MAIN_TIMER|F_CONN_READ_W|F_CONN_WANTS_RD)
  3395. #ifdef TCP_ASYNC
  3396. /* not used for now, the connection is sent to tcp_main
  3397. * before knowing whether we can write on it or we should
  3398. * wait */
  3399. | (((int)!(tcpconn->flags & F_CONN_WANTS_WR)-1)&
  3400. F_CONN_WRITE_W)
  3401. #endif /* TCP_ASYNC */
  3402. ;
  3403. tcpconn->flags&=~F_CONN_FD_CLOSED;
  3404. flags=POLLIN
  3405. #ifdef TCP_ASYNC
  3406. /* not used for now, the connection is sent to tcp_main
  3407. * before knowing if we can write on it or we should
  3408. * wait */
  3409. | (((int)!(tcpconn->flags & F_CONN_WANTS_WR)-1) & POLLOUT)
  3410. #endif /* TCP_ASYNC */
  3411. ;
  3412. if (unlikely(
  3413. io_watch_add(&io_h, tcpconn->s, flags,
  3414. F_TCPCONN, tcpconn)<0)){
  3415. LM_CRIT("failed to add new socket to the fd list\n");
  3416. tcpconn->flags&=~(F_CONN_WRITE_W|F_CONN_READ_W);
  3417. tcpconn_try_unhash(tcpconn); /* unhash & dec refcnt */
  3418. tcpconn_put_destroy(tcpconn);
  3419. }
  3420. break;
  3421. #ifdef TCP_ASYNC
  3422. case CONN_QUEUED_WRITE:
  3423. /* received only if the wr. queue is empty and a write finishes
  3424. * with EAGAIN (common after connect())
  3425. * it should only enable write watching on the fd. The connection
  3426. * should be already in the hash. The refcnt is automatically
  3427. * decremented.
  3428. */
  3429. /* auto-dec refcnt */
  3430. if (unlikely(tcpconn_put(tcpconn))){
  3431. tcpconn_destroy(tcpconn);
  3432. break;
  3433. }
  3434. if (unlikely((tcpconn->state==S_CONN_BAD) ||
  3435. !(tcpconn->flags & F_CONN_HASHED) ))
  3436. /* in the process of being destroyed => do nothing */
  3437. break;
  3438. if (!(tcpconn->flags & F_CONN_WANTS_WR)){
  3439. tcpconn->flags|=F_CONN_WANTS_WR;
  3440. t=get_ticks_raw();
  3441. if (likely((tcpconn->flags & F_CONN_MAIN_TIMER) &&
  3442. (TICKS_LT(tcpconn->wbuf_q.wr_timeout, tcpconn->timeout)) &&
  3443. TICKS_LT(t, tcpconn->wbuf_q.wr_timeout) )){
  3444. /* _wbufq_nonempty() is guaranteed here */
  3445. /* update the timer */
  3446. local_timer_del(&tcp_main_ltimer, &tcpconn->timer);
  3447. local_timer_reinit(&tcpconn->timer);
  3448. local_timer_add(&tcp_main_ltimer, &tcpconn->timer,
  3449. tcpconn->wbuf_q.wr_timeout-t, t);
  3450. DBG("tcp_main: handle_ser_child: CONN_QUEUED_WRITE; %p "
  3451. "timeout adjusted to %d s\n", tcpconn,
  3452. TICKS_TO_S(tcpconn->wbuf_q.wr_timeout-t));
  3453. }
  3454. if (!(tcpconn->flags & F_CONN_WRITE_W)){
  3455. tcpconn->flags|=F_CONN_WRITE_W;
  3456. if (!(tcpconn->flags & F_CONN_READ_W)){
  3457. if (unlikely(io_watch_add(&io_h, tcpconn->s, POLLOUT,
  3458. F_TCPCONN, tcpconn)<0)){
  3459. LM_CRIT("failed to enable write watch on socket\n");
  3460. if (tcpconn_try_unhash(tcpconn))
  3461. tcpconn_put_destroy(tcpconn);
  3462. break;
  3463. }
  3464. }else{
  3465. if (unlikely(io_watch_chg(&io_h, tcpconn->s,
  3466. POLLIN|POLLOUT, -1)<0)){
  3467. LM_CRIT("failed to change socket watch events\n");
  3468. if (tcpconn_try_unhash(tcpconn)) {
  3469. io_watch_del(&io_h, tcpconn->s, -1,
  3470. IO_FD_CLOSING);
  3471. tcpconn->flags&=~F_CONN_READ_W;
  3472. tcpconn_put_destroy(tcpconn);
  3473. } else {
  3474. BUG("unhashed connection watched for IO\n");
  3475. io_watch_del(&io_h, tcpconn->s, -1, 0);
  3476. tcpconn->flags&=~F_CONN_READ_W;
  3477. }
  3478. break;
  3479. }
  3480. }
  3481. }
  3482. }else{
  3483. LM_WARN("connection %p already watched for write\n", tcpconn);
  3484. }
  3485. break;
  3486. #ifdef TCP_CONNECT_WAIT
  3487. case CONN_NEW_COMPLETE:
  3488. case CONN_NEW_PENDING_WRITE:
  3489. /* received when a pending connect completes in the same
  3490. * tcp_send() that initiated it
  3491. * the connection is already in the hash with F_CONN_PENDING
  3492. * flag (added by tcp_send()) and refcnt at least 1 (for the
  3493. * hash)*/
  3494. tcpconn->flags&=~(F_CONN_PENDING|F_CONN_FD_CLOSED);
  3495. if (unlikely((tcpconn->state==S_CONN_BAD) || (fd==-1))){
  3496. if (unlikely(fd==-1))
  3497. LM_CRIT("CONN_NEW_COMPLETE: no fd received\n");
  3498. else
  3499. LM_WARN("CONN_NEW_COMPLETE: received connection with error\n");
  3500. tcpconn->flags|=F_CONN_FD_CLOSED;
  3501. tcpconn->state=S_CONN_BAD;
  3502. tcpconn_try_unhash(tcpconn);
  3503. tcpconn_put_destroy(tcpconn);
  3504. break;
  3505. }
  3506. (*tcp_connections_no)++;
  3507. if (unlikely(tcpconn->type==PROTO_TLS))
  3508. (*tls_connections_no)++;
  3509. tcpconn->s=fd;
  3510. /* update the timeout*/
  3511. t=get_ticks_raw();
  3512. con_lifetime=cfg_get(tcp, tcp_cfg, con_lifetime);
  3513. tcpconn->timeout=t+con_lifetime;
  3514. nxt_timeout=con_lifetime;
  3515. if (unlikely(cmd==CONN_NEW_COMPLETE)){
  3516. /* check if needs to be watched for write */
  3517. lock_get(&tcpconn->write_lock);
  3518. /* if queue non empty watch it for write */
  3519. flags=(_wbufq_empty(tcpconn)-1)&POLLOUT;
  3520. lock_release(&tcpconn->write_lock);
  3521. if (flags){
  3522. if (TICKS_LT(tcpconn->wbuf_q.wr_timeout, tcpconn->timeout)
  3523. && TICKS_LT(t, tcpconn->wbuf_q.wr_timeout))
  3524. nxt_timeout=tcpconn->wbuf_q.wr_timeout-t;
  3525. tcpconn->flags|=F_CONN_WRITE_W|F_CONN_WANTS_WR;
  3526. }
  3527. /* activate the timer (already properly init. in
  3528. tcpconn_new()) no need for reinit */
  3529. local_timer_add(&tcp_main_ltimer, &tcpconn->timer, nxt_timeout,
  3530. t);
  3531. tcpconn->flags|=F_CONN_MAIN_TIMER|F_CONN_READ_W|
  3532. F_CONN_WANTS_RD;
  3533. }else{
  3534. /* CONN_NEW_PENDING_WRITE */
  3535. /* no need to check, we have something queued for write */
  3536. flags=POLLOUT;
  3537. if (TICKS_LT(tcpconn->wbuf_q.wr_timeout, tcpconn->timeout)
  3538. && TICKS_LT(t, tcpconn->wbuf_q.wr_timeout))
  3539. nxt_timeout=tcpconn->wbuf_q.wr_timeout-t;
  3540. /* activate the timer (already properly init. in
  3541. tcpconn_new()) no need for reinit */
  3542. local_timer_add(&tcp_main_ltimer, &tcpconn->timer, nxt_timeout,
  3543. t);
  3544. tcpconn->flags|=F_CONN_MAIN_TIMER|F_CONN_READ_W|
  3545. F_CONN_WANTS_RD |
  3546. F_CONN_WRITE_W|F_CONN_WANTS_WR;
  3547. }
  3548. flags|=POLLIN;
  3549. if (unlikely(
  3550. io_watch_add(&io_h, tcpconn->s, flags,
  3551. F_TCPCONN, tcpconn)<0)){
  3552. LM_CRIT("failed to add new socket to the fd list\n");
  3553. tcpconn->flags&=~(F_CONN_WRITE_W|F_CONN_READ_W);
  3554. tcpconn_try_unhash(tcpconn); /* unhash & dec refcnt */
  3555. tcpconn_put_destroy(tcpconn);
  3556. }
  3557. break;
  3558. #endif /* TCP_CONNECT_WAIT */
  3559. #endif /* TCP_ASYNC */
  3560. default:
  3561. LM_CRIT("unknown cmd %d\n", cmd);
  3562. }
  3563. end:
  3564. return ret;
  3565. error:
  3566. return -1;
  3567. }
  3568. /* sends a tcpconn + fd to a choosen child */
  3569. inline static int send2child(struct tcp_connection* tcpconn)
  3570. {
  3571. int i;
  3572. int min_busy;
  3573. int idx;
  3574. int wfirst;
  3575. int wlast;
  3576. static int crt=0; /* current child */
  3577. int last;
  3578. if(likely(tcp_sockets_gworkers==0)) {
  3579. /* no child selection based on received socket
  3580. * - use least loaded over all */
  3581. min_busy=tcp_children[0].busy;
  3582. idx=0;
  3583. last=crt+tcp_children_no;
  3584. for (; crt<last; crt++){
  3585. i=crt%tcp_children_no;
  3586. if (!tcp_children[i].busy){
  3587. idx=i;
  3588. min_busy=0;
  3589. break;
  3590. }else if (min_busy>tcp_children[i].busy){
  3591. min_busy=tcp_children[i].busy;
  3592. idx=i;
  3593. }
  3594. }
  3595. crt=idx+1; /* next time we start with crt%tcp_children_no */
  3596. } else {
  3597. /* child selection based on received socket
  3598. * - use least loaded per received socket, starting with the first
  3599. * in its group */
  3600. if(tcpconn->rcv.bind_address->workers>0) {
  3601. wfirst = tcpconn->rcv.bind_address->workers_tcpidx;
  3602. wlast = wfirst + tcpconn->rcv.bind_address->workers;
  3603. LM_DBG("===== checking per-socket specific workers (%d/%d..%d/%d) [%s]\n",
  3604. tcp_children[wfirst].pid, tcp_children[wfirst].proc_no,
  3605. tcp_children[wlast-1].pid, tcp_children[wlast-1].proc_no,
  3606. tcpconn->rcv.bind_address->sock_str.s);
  3607. } else {
  3608. wfirst = 0;
  3609. wlast = tcp_sockets_gworkers - 1;
  3610. LM_DBG("+++++ checking per-socket generic workers (%d/%d..%d/%d) [%s]\n",
  3611. tcp_children[wfirst].pid, tcp_children[wfirst].proc_no,
  3612. tcp_children[wlast-1].pid, tcp_children[wlast-1].proc_no,
  3613. tcpconn->rcv.bind_address->sock_str.s);
  3614. }
  3615. idx = wfirst;
  3616. min_busy = tcp_children[idx].busy;
  3617. for(i=wfirst; i<wlast; i++) {
  3618. if (!tcp_children[i].busy){
  3619. idx=i;
  3620. min_busy=0;
  3621. break;
  3622. } else {
  3623. if (min_busy>tcp_children[i].busy) {
  3624. min_busy=tcp_children[i].busy;
  3625. idx=i;
  3626. }
  3627. }
  3628. }
  3629. }
  3630. tcp_children[idx].busy++;
  3631. tcp_children[idx].n_reqs++;
  3632. if (unlikely(min_busy)){
  3633. DBG("WARNING: send2child: no free tcp receiver, "
  3634. " connection passed to the least busy one (%d)\n",
  3635. min_busy);
  3636. }
  3637. LM_DBG("selected tcp worker %d %d(%ld) for activity on [%s], %p\n",
  3638. idx, tcp_children[idx].proc_no, (long)tcp_children[idx].pid,
  3639. tcpconn->rcv.bind_address->sock_str.s, tcpconn);
  3640. /* first make sure this child doesn't have pending request for
  3641. * tcp_main (to avoid a possible deadlock: e.g. child wants to
  3642. * send a release command, but the master fills its socket buffer
  3643. * with new connection commands => deadlock) */
  3644. /* answer tcp_send requests first */
  3645. while(unlikely((tcpconn->state != S_CONN_BAD) &&
  3646. (handle_ser_child(&pt[tcp_children[idx].proc_no], -1)>0)));
  3647. /* process tcp readers requests */
  3648. while(unlikely((tcpconn->state != S_CONN_BAD &&
  3649. (handle_tcp_child(&tcp_children[idx], -1)>0))));
  3650. /* the above possible pending requests might have included a
  3651. command to close this tcpconn (e.g. CONN_ERROR, CONN_EOF).
  3652. In this case the fd is already closed here (and possible
  3653. even replaced by another one with the same number) so it
  3654. must not be sent to a reader anymore */
  3655. if (unlikely(tcpconn->state == S_CONN_BAD ||
  3656. (tcpconn->flags & F_CONN_FD_CLOSED)))
  3657. return -1;
  3658. #ifdef SEND_FD_QUEUE
  3659. /* if queue full, try to queue the io */
  3660. if (unlikely(send_fd(tcp_children[idx].unix_sock, &tcpconn,
  3661. sizeof(tcpconn), tcpconn->s)<=0)){
  3662. if ((errno==EAGAIN)||(errno==EWOULDBLOCK)){
  3663. /* FIXME: remove after debugging */
  3664. LM_CRIT("tcp child %d, socket %d: queue full, %d requests queued (total handled %d)\n",
  3665. idx, tcp_children[idx].unix_sock, min_busy,
  3666. tcp_children[idx].n_reqs-1);
  3667. if (send_fd_queue_add(&send2child_q, tcp_children[idx].unix_sock,
  3668. tcpconn)!=0){
  3669. LM_ERR("queue send op. failed\n");
  3670. return -1;
  3671. }
  3672. }else{
  3673. LM_ERR("send_fd failed for %p (flags 0x%0x), fd %d\n",
  3674. tcpconn, tcpconn->flags, tcpconn->s);
  3675. return -1;
  3676. }
  3677. }
  3678. #else
  3679. if (unlikely(send_fd(tcp_children[idx].unix_sock, &tcpconn,
  3680. sizeof(tcpconn), tcpconn->s)<=0)){
  3681. LM_ERR("send_fd failed for %p (flags 0x%0x), fd %d\n",
  3682. tcpconn, tcpconn->flags, tcpconn->s);
  3683. return -1;
  3684. }
  3685. #endif
  3686. return 0;
  3687. }
  3688. /* handles a new connection, called internally by tcp_main_loop/handle_io.
  3689. * params: si - pointer to one of the tcp socket_info structures on which
  3690. * an io event was detected (connection attempt)
  3691. * returns: handle_* return convention: -1 on error, 0 on EAGAIN (no more
  3692. * io events queued), >0 on success. success/error refer only to
  3693. * the accept.
  3694. */
  3695. static inline int handle_new_connect(struct socket_info* si)
  3696. {
  3697. union sockaddr_union su;
  3698. union sockaddr_union sock_name;
  3699. unsigned sock_name_len;
  3700. union sockaddr_union* dst_su;
  3701. struct tcp_connection* tcpconn;
  3702. socklen_t su_len;
  3703. int new_sock;
  3704. /* got a connection on r */
  3705. su_len=sizeof(su);
  3706. new_sock=accept(si->socket, &(su.s), &su_len);
  3707. if (unlikely(new_sock==-1)){
  3708. if ((errno==EAGAIN)||(errno==EWOULDBLOCK))
  3709. return 0;
  3710. LM_ERR("error while accepting connection(%d): %s\n", errno, strerror(errno));
  3711. return -1;
  3712. }
  3713. if (unlikely(*tcp_connections_no>=cfg_get(tcp, tcp_cfg, max_connections))){
  3714. LM_ERR("maximum number of connections exceeded: %d/%d\n",
  3715. *tcp_connections_no,
  3716. cfg_get(tcp, tcp_cfg, max_connections));
  3717. tcp_safe_close(new_sock);
  3718. TCP_STATS_LOCAL_REJECT();
  3719. return 1; /* success, because the accept was succesfull */
  3720. }
  3721. if (unlikely(si->proto==PROTO_TLS)) {
  3722. if (unlikely(*tls_connections_no>=cfg_get(tcp, tcp_cfg, max_tls_connections))){
  3723. LM_ERR("maximum number of tls connections exceeded: %d/%d\n",
  3724. *tls_connections_no,
  3725. cfg_get(tcp, tcp_cfg, max_tls_connections));
  3726. tcp_safe_close(new_sock);
  3727. TCP_STATS_LOCAL_REJECT();
  3728. return 1; /* success, because the accept was succesfull */
  3729. }
  3730. }
  3731. if (unlikely(init_sock_opt_accept(new_sock)<0)){
  3732. LM_ERR("init_sock_opt failed\n");
  3733. tcp_safe_close(new_sock);
  3734. return 1; /* success, because the accept was succesfull */
  3735. }
  3736. (*tcp_connections_no)++;
  3737. if (unlikely(si->proto==PROTO_TLS))
  3738. (*tls_connections_no)++;
  3739. /* stats for established connections are incremented after
  3740. the first received or sent packet.
  3741. Alternatively they could be incremented here for accepted
  3742. connections, but then the connection state must be changed to
  3743. S_CONN_OK:
  3744. TCP_STATS_ESTABLISHED(S_CONN_ACCEPT);
  3745. ...
  3746. tcpconn=tcpconn_new(new_sock, &su, dst_su, si, si->proto, S_CONN_OK);
  3747. */
  3748. dst_su=&si->su;
  3749. if (unlikely(si->flags & SI_IS_ANY)){
  3750. /* INADDR_ANY => get local dst */
  3751. sock_name_len=sizeof(sock_name);
  3752. if (getsockname(new_sock, &sock_name.s, &sock_name_len)!=0){
  3753. LM_ERR("getsockname failed: %s(%d)\n",
  3754. strerror(errno), errno);
  3755. /* go on with the 0.0.0.0 dst from the sock_info */
  3756. }else{
  3757. dst_su=&sock_name;
  3758. }
  3759. }
  3760. /* add socket to list */
  3761. tcpconn=tcpconn_new(new_sock, &su, dst_su, si, si->proto, S_CONN_ACCEPT);
  3762. if (likely(tcpconn)){
  3763. tcpconn->flags|=F_CONN_PASSIVE;
  3764. #ifdef TCP_PASS_NEW_CONNECTION_ON_DATA
  3765. atomic_set(&tcpconn->refcnt, 1); /* safe, not yet available to the
  3766. outside world */
  3767. tcpconn_add(tcpconn);
  3768. /* activate the timer */
  3769. local_timer_add(&tcp_main_ltimer, &tcpconn->timer,
  3770. cfg_get(tcp, tcp_cfg, con_lifetime),
  3771. get_ticks_raw());
  3772. tcpconn->flags|=(F_CONN_MAIN_TIMER|F_CONN_READ_W|F_CONN_WANTS_RD);
  3773. if (unlikely(io_watch_add(&io_h, tcpconn->s, POLLIN,
  3774. F_TCPCONN, tcpconn)<0)){
  3775. LM_CRIT("failed to add new socket to the fd list\n");
  3776. tcpconn->flags&=~F_CONN_READ_W;
  3777. if (tcpconn_try_unhash(tcpconn))
  3778. tcpconn_put_destroy(tcpconn);
  3779. }
  3780. #else
  3781. atomic_set(&tcpconn->refcnt, 2); /* safe, not yet available to the
  3782. outside world */
  3783. /* prepare it for passing to a child */
  3784. tcpconn->flags|=F_CONN_READER;
  3785. tcpconn_add(tcpconn);
  3786. DBG("handle_new_connect: new connection from %s: %p %d flags: %04x\n",
  3787. su2a(&su, sizeof(su)), tcpconn, tcpconn->s, tcpconn->flags);
  3788. if(unlikely(send2child(tcpconn)<0)){
  3789. tcpconn->flags&=~F_CONN_READER;
  3790. if (tcpconn_try_unhash(tcpconn))
  3791. tcpconn_put(tcpconn);
  3792. tcpconn_put_destroy(tcpconn);
  3793. }
  3794. #endif
  3795. }else{ /*tcpconn==0 */
  3796. LM_ERR("tcpconn_new failed, closing socket\n");
  3797. tcp_safe_close(new_sock);
  3798. (*tcp_connections_no)--;
  3799. if (unlikely(si->proto==PROTO_TLS))
  3800. (*tls_connections_no)--;
  3801. }
  3802. return 1; /* accept() was succesfull */
  3803. }
  3804. /* handles an io event on one of the watched tcp connections
  3805. *
  3806. * params: tcpconn - pointer to the tcp_connection for which we have an io ev.
  3807. * fd_i - index in the fd_array table (needed for delete)
  3808. * returns: handle_* return convention, but on success it always returns 0
  3809. * (because it's one-shot, after a succesful execution the fd is
  3810. * removed from tcp_main's watch fd list and passed to a child =>
  3811. * tcp_main is not interested in further io events that might be
  3812. * queued for this fd)
  3813. */
  3814. inline static int handle_tcpconn_ev(struct tcp_connection* tcpconn, short ev,
  3815. int fd_i)
  3816. {
  3817. #ifdef TCP_ASYNC
  3818. int empty_q;
  3819. int bytes;
  3820. #endif /* TCP_ASYNC */
  3821. /* is refcnt!=0 really necessary?
  3822. * No, in fact it's a bug: I can have the following situation: a send only
  3823. * tcp connection used by n processes simultaneously => refcnt = n. In
  3824. * the same time I can have a read event and this situation is perfectly
  3825. * valid. -- andrei
  3826. */
  3827. #if 0
  3828. if ((tcpconn->refcnt!=0)){
  3829. /* FIXME: might be valid for sigio_rt iff fd flags are not cleared
  3830. * (there is a short window in which it could generate a sig
  3831. * that would be catched by tcp_main) */
  3832. LM_CRIT("handle_tcpconn_ev: io event on referenced"
  3833. " tcpconn (%p), refcnt=%d, fd=%d\n",
  3834. tcpconn, tcpconn->refcnt, tcpconn->s);
  3835. return -1;
  3836. }
  3837. #endif
  3838. /* pass it to child, so remove it from the io watch list and the local
  3839. * timer */
  3840. #ifdef TCP_ASYNC
  3841. empty_q=0; /* warning fix */
  3842. if (unlikely((ev & (POLLOUT|POLLERR|POLLHUP)) &&
  3843. (tcpconn->flags & F_CONN_WRITE_W))){
  3844. if (unlikely((ev & (POLLERR|POLLHUP)) ||
  3845. (wbufq_run(tcpconn->s, tcpconn, &empty_q)<0) ||
  3846. (empty_q && tcpconn_close_after_send(tcpconn))
  3847. )){
  3848. if ((tcpconn->flags & F_CONN_READ_W) && (ev & POLLIN)){
  3849. /* connection is watched for read and there is a read event
  3850. * (unfortunately if we have POLLIN here we don't know if
  3851. * there's really any data in the read buffer or the POLLIN
  3852. * was generated by the error or EOF => to avoid loosing
  3853. * data it's safer to either directly check the read buffer
  3854. * or try a read)*/
  3855. /* in most cases the read buffer will be empty, so in general
  3856. * is cheaper to check it here and then send the
  3857. * conn. to a a child only if needed (another syscall + at
  3858. * least 2 * syscalls in the reader + ...) */
  3859. if ((ioctl(tcpconn->s, FIONREAD, &bytes)>=0) && (bytes>0)){
  3860. if (unlikely(io_watch_del(&io_h, tcpconn->s, fd_i, 0)<0)){
  3861. LM_ERR("io_watch_del(1) failed: for %p, fd %d\n",
  3862. tcpconn, tcpconn->s);
  3863. }
  3864. tcpconn->flags&=~(F_CONN_WRITE_W|F_CONN_READ_W|
  3865. F_CONN_WANTS_RD|F_CONN_WANTS_WR);
  3866. tcpconn->flags|=F_CONN_FORCE_EOF|F_CONN_WR_ERROR;
  3867. goto send_to_child;
  3868. }
  3869. /* if bytes==0 or ioctl failed, destroy the connection now */
  3870. }
  3871. if (unlikely(io_watch_del(&io_h, tcpconn->s, fd_i,
  3872. IO_FD_CLOSING) < 0)){
  3873. LM_ERR("io_watch_del() failed: for %p, fd %d\n", tcpconn, tcpconn->s);
  3874. }
  3875. tcpconn->flags&=~(F_CONN_WRITE_W|F_CONN_READ_W|
  3876. F_CONN_WANTS_RD|F_CONN_WANTS_WR);
  3877. if (unlikely(ev & POLLERR)){
  3878. if (unlikely(tcpconn->state==S_CONN_CONNECT)){
  3879. #ifdef USE_DST_BLACKLIST
  3880. (void)dst_blacklist_su(BLST_ERR_CONNECT, tcpconn->rcv.proto,
  3881. &tcpconn->rcv.src_su,
  3882. &tcpconn->send_flags, 0);
  3883. #endif /* USE_DST_BLACKLIST */
  3884. TCP_EV_CONNECT_ERR(0, TCP_LADDR(tcpconn),
  3885. TCP_LPORT(tcpconn), TCP_PSU(tcpconn),
  3886. TCP_PROTO(tcpconn));
  3887. TCP_STATS_CONNECT_FAILED();
  3888. }else{
  3889. #ifdef USE_DST_BLACKLIST
  3890. (void)dst_blacklist_su(BLST_ERR_SEND, tcpconn->rcv.proto,
  3891. &tcpconn->rcv.src_su,
  3892. &tcpconn->send_flags, 0);
  3893. #endif /* USE_DST_BLACKLIST */
  3894. TCP_STATS_CON_RESET(); /* FIXME: it could != RST */
  3895. }
  3896. }
  3897. if (unlikely(!tcpconn_try_unhash(tcpconn))){
  3898. LM_CRIT("unhashed connection %p\n", tcpconn);
  3899. }
  3900. tcpconn_put_destroy(tcpconn);
  3901. goto error;
  3902. }
  3903. if (empty_q){
  3904. tcpconn->flags&=~F_CONN_WANTS_WR;
  3905. if (!(tcpconn->flags & F_CONN_READ_W)){
  3906. if (unlikely(io_watch_del(&io_h, tcpconn->s, fd_i, 0)==-1)){
  3907. LM_ERR("io_watch_del(2) failed: for %p, fd %d\n",
  3908. tcpconn, tcpconn->s);
  3909. goto error;
  3910. }
  3911. }else{
  3912. if (unlikely(io_watch_chg(&io_h, tcpconn->s,
  3913. POLLIN, fd_i)==-1)){
  3914. LM_ERR("io_watch_chg(1) failed: for %p, fd %d\n",
  3915. tcpconn, tcpconn->s);
  3916. goto error;
  3917. }
  3918. }
  3919. tcpconn->flags&=~F_CONN_WRITE_W;
  3920. }
  3921. ev&=~POLLOUT; /* clear POLLOUT */
  3922. }
  3923. if (likely(ev && (tcpconn->flags & F_CONN_READ_W))){
  3924. /* if still some other IO event (POLLIN|POLLHUP|POLLERR) and
  3925. * connection is still watched in tcp_main for reads, send it to a
  3926. * child and stop watching it for input (but continue watching for
  3927. * writes if needed): */
  3928. if (unlikely(tcpconn->flags & F_CONN_WRITE_W)){
  3929. if (unlikely(io_watch_chg(&io_h, tcpconn->s, POLLOUT, fd_i)==-1)){
  3930. LM_ERR("io_watch_chg(2) failed: for %p, fd %d\n",
  3931. tcpconn, tcpconn->s);
  3932. goto error;
  3933. }
  3934. }else
  3935. #else
  3936. {
  3937. #endif /* TCP_ASYNC */
  3938. if (unlikely(io_watch_del(&io_h, tcpconn->s, fd_i, 0)==-1)){
  3939. LM_ERR("io_watch_del(3) failed: for %p, fd %d\n",
  3940. tcpconn, tcpconn->s);
  3941. goto error;
  3942. }
  3943. #ifdef TCP_ASYNC
  3944. send_to_child:
  3945. #endif
  3946. DBG("tcp: DBG: sending to child, events %x\n", ev);
  3947. #ifdef POLLRDHUP
  3948. tcpconn->flags|=((int)!(ev & (POLLRDHUP|POLLHUP|POLLERR)) -1) &
  3949. F_CONN_EOF_SEEN;
  3950. #else /* POLLRDHUP */
  3951. tcpconn->flags|=((int)!(ev & (POLLHUP|POLLERR)) -1) & F_CONN_EOF_SEEN;
  3952. #endif /* POLLRDHUP */
  3953. tcpconn->flags|= ((int)!(ev & POLLPRI) -1) & F_CONN_OOB_DATA;
  3954. tcpconn->flags|=F_CONN_READER;
  3955. local_timer_del(&tcp_main_ltimer, &tcpconn->timer);
  3956. tcpconn->flags&=~(F_CONN_MAIN_TIMER|F_CONN_READ_W|F_CONN_WANTS_RD);
  3957. tcpconn_ref(tcpconn); /* refcnt ++ */
  3958. if (unlikely(send2child(tcpconn)<0)){
  3959. tcpconn->flags&=~F_CONN_READER;
  3960. #ifdef TCP_ASYNC
  3961. if (tcpconn->flags & F_CONN_WRITE_W){
  3962. if (unlikely(io_watch_del(&io_h, tcpconn->s, fd_i,
  3963. IO_FD_CLOSING) < 0)){
  3964. LM_ERR("io_watch_del(4) failed:" " for %p, fd %d\n",
  3965. tcpconn, tcpconn->s);
  3966. }
  3967. tcpconn->flags&=~F_CONN_WRITE_W;
  3968. }
  3969. #endif /* TCP_ASYNC */
  3970. if (tcpconn_try_unhash(tcpconn))
  3971. tcpconn_put(tcpconn);
  3972. tcpconn_put_destroy(tcpconn); /* because of the tcpconn_ref() */
  3973. }
  3974. }
  3975. return 0; /* we are not interested in possibly queued io events,
  3976. the fd was either passed to a child, closed, or for writes,
  3977. everything possible was already written */
  3978. error:
  3979. return -1;
  3980. }
  3981. /* generic handle io routine, it will call the appropiate
  3982. * handle_xxx() based on the fd_map type
  3983. *
  3984. * params: fm - pointer to a fd hash entry
  3985. * idx - index in the fd_array (or -1 if not known)
  3986. * return: -1 on error
  3987. * 0 on EAGAIN or when by some other way it is known that no more
  3988. * io events are queued on the fd (the receive buffer is empty).
  3989. * Usefull to detect when there are no more io events queued for
  3990. * sigio_rt, epoll_et, kqueue.
  3991. * >0 on successfull read from the fd (when there might be more io
  3992. * queued -- the receive buffer might still be non-empty)
  3993. */
  3994. inline static int handle_io(struct fd_map* fm, short ev, int idx)
  3995. {
  3996. int ret;
  3997. /* update the local config */
  3998. cfg_update();
  3999. switch(fm->type){
  4000. case F_SOCKINFO:
  4001. ret=handle_new_connect((struct socket_info*)fm->data);
  4002. break;
  4003. case F_TCPCONN:
  4004. ret=handle_tcpconn_ev((struct tcp_connection*)fm->data, ev, idx);
  4005. break;
  4006. case F_TCPCHILD:
  4007. ret=handle_tcp_child((struct tcp_child*)fm->data, idx);
  4008. break;
  4009. case F_PROC:
  4010. ret=handle_ser_child((struct process_table*)fm->data, idx);
  4011. break;
  4012. case F_NONE:
  4013. LM_CRIT("empty fd map: %p {%d, %d, %p}, idx %d\n",
  4014. fm, fm->fd, fm->type, fm->data, idx);
  4015. goto error;
  4016. default:
  4017. LM_CRIT("unknown fd type %d\n", fm->type);
  4018. goto error;
  4019. }
  4020. return ret;
  4021. error:
  4022. return -1;
  4023. }
  4024. /* timer handler for tcpconnection handled by tcp_main */
  4025. static ticks_t tcpconn_main_timeout(ticks_t t, struct timer_ln* tl, void* data)
  4026. {
  4027. struct tcp_connection *c;
  4028. int fd;
  4029. int tcp_async;
  4030. c=(struct tcp_connection*)data;
  4031. /* or (struct tcp...*)(tl-offset(c->timer)) */
  4032. #ifdef TCP_ASYNC
  4033. DBG( "tcp_main: entering timer for %p (ticks=%d, timeout=%d (%d s), "
  4034. "wr_timeout=%d (%d s)), write queue: %d bytes\n",
  4035. c, t, c->timeout, TICKS_TO_S(c->timeout-t),
  4036. c->wbuf_q.wr_timeout, TICKS_TO_S(c->wbuf_q.wr_timeout-t),
  4037. c->wbuf_q.queued);
  4038. tcp_async=cfg_get(tcp, tcp_cfg, async);
  4039. if (likely(TICKS_LT(t, c->timeout) && ( !tcp_async || _wbufq_empty(c) ||
  4040. TICKS_LT(t, c->wbuf_q.wr_timeout)) )){
  4041. if (unlikely(tcp_async && _wbufq_non_empty(c)))
  4042. return (ticks_t)MIN_unsigned(c->timeout-t, c->wbuf_q.wr_timeout-t);
  4043. else
  4044. return (ticks_t)(c->timeout - t);
  4045. }
  4046. /* if time out due to write, add it to the blacklist */
  4047. if (tcp_async && _wbufq_non_empty(c) && TICKS_GE(t, c->wbuf_q.wr_timeout)){
  4048. if (unlikely(c->state==S_CONN_CONNECT)){
  4049. #ifdef USE_DST_BLACKLIST
  4050. (void)dst_blacklist_su(BLST_ERR_CONNECT, c->rcv.proto, &c->rcv.src_su,
  4051. &c->send_flags, 0);
  4052. #endif /* USE_DST_BLACKLIST */
  4053. TCP_EV_CONNECT_TIMEOUT(0, TCP_LADDR(c), TCP_LPORT(c), TCP_PSU(c),
  4054. TCP_PROTO(c));
  4055. TCP_STATS_CONNECT_FAILED();
  4056. }else{
  4057. #ifdef USE_DST_BLACKLIST
  4058. (void)dst_blacklist_su(BLST_ERR_SEND, c->rcv.proto, &c->rcv.src_su,
  4059. &c->send_flags, 0);
  4060. #endif /* USE_DST_BLACKLIST */
  4061. TCP_EV_SEND_TIMEOUT(0, &c->rcv);
  4062. TCP_STATS_SEND_TIMEOUT();
  4063. }
  4064. }else{
  4065. /* idle timeout */
  4066. TCP_EV_IDLE_CONN_CLOSED(0, &c->rcv);
  4067. TCP_STATS_CON_TIMEOUT();
  4068. }
  4069. #else /* ! TCP_ASYNC */
  4070. if (TICKS_LT(t, c->timeout)){
  4071. /* timeout extended, exit */
  4072. return (ticks_t)(c->timeout - t);
  4073. }
  4074. /* idle timeout */
  4075. TCP_EV_IDLE_CONN_CLOSED(0, &c->rcv);
  4076. TCP_STATS_CON_TIMEOUT();
  4077. #endif /* TCP_ASYNC */
  4078. DBG("tcp_main: timeout for %p\n", c);
  4079. if (likely(c->flags & F_CONN_HASHED)){
  4080. c->flags&=~(F_CONN_HASHED|F_CONN_MAIN_TIMER);
  4081. c->state=S_CONN_BAD;
  4082. TCPCONN_LOCK;
  4083. _tcpconn_detach(c);
  4084. TCPCONN_UNLOCK;
  4085. }else{
  4086. c->flags&=~F_CONN_MAIN_TIMER;
  4087. LM_CRIT("timer: called with unhashed connection %p\n", c);
  4088. tcpconn_ref(c); /* ugly hack to try to go on */
  4089. }
  4090. fd=c->s;
  4091. if (likely(fd>0)){
  4092. if (likely(c->flags & (F_CONN_READ_W|F_CONN_WRITE_W))){
  4093. io_watch_del(&io_h, fd, -1, IO_FD_CLOSING);
  4094. c->flags&=~(F_CONN_READ_W|F_CONN_WRITE_W);
  4095. }
  4096. }
  4097. tcpconn_put_destroy(c);
  4098. return 0;
  4099. }
  4100. static inline void tcp_timer_run(void)
  4101. {
  4102. ticks_t ticks;
  4103. ticks=get_ticks_raw();
  4104. if (unlikely((ticks-tcp_main_prev_ticks)<TCPCONN_TIMEOUT_MIN_RUN)) return;
  4105. tcp_main_prev_ticks=ticks;
  4106. local_timer_run(&tcp_main_ltimer, ticks);
  4107. }
  4108. /* keep in sync with tcpconn_destroy, the "delete" part should be
  4109. * the same except for io_watch_del..
  4110. * Note: this function is called only on shutdown by the main ser process via
  4111. * cleanup(). However it's also safe to call it from the tcp_main process.
  4112. * => with the ser shutdown exception, it cannot execute in parallel
  4113. * with tcpconn_add() or tcpconn_destroy()*/
  4114. static inline void tcpconn_destroy_all(void)
  4115. {
  4116. struct tcp_connection *c, *next;
  4117. unsigned h;
  4118. int fd;
  4119. TCPCONN_LOCK;
  4120. for(h=0; h<TCP_ID_HASH_SIZE; h++){
  4121. c=tcpconn_id_hash[h];
  4122. while(c){
  4123. next=c->id_next;
  4124. if (is_tcp_main){
  4125. /* we cannot close or remove the fd if we are not in the
  4126. * tcp main proc.*/
  4127. if ((c->flags & F_CONN_MAIN_TIMER)){
  4128. local_timer_del(&tcp_main_ltimer, &c->timer);
  4129. c->flags&=~F_CONN_MAIN_TIMER;
  4130. } /* else still in some reader */
  4131. fd=c->s;
  4132. if (fd>0 && (c->flags & (F_CONN_READ_W|F_CONN_WRITE_W))){
  4133. io_watch_del(&io_h, fd, -1, IO_FD_CLOSING);
  4134. c->flags&=~(F_CONN_READ_W|F_CONN_WRITE_W);
  4135. }
  4136. }else{
  4137. fd=-1;
  4138. }
  4139. #ifdef USE_TLS
  4140. if (fd>0 && (c->type==PROTO_TLS || c->type==PROTO_WSS))
  4141. tls_close(c, fd);
  4142. if (unlikely(c->type==PROTO_TLS || c->type==PROTO_WSS))
  4143. (*tls_connections_no)--;
  4144. #endif
  4145. (*tcp_connections_no)--;
  4146. c->flags &= ~F_CONN_HASHED;
  4147. _tcpconn_rm(c);
  4148. if (fd>0) {
  4149. #ifdef TCP_FD_CACHE
  4150. if (likely(cfg_get(tcp, tcp_cfg, fd_cache)))
  4151. shutdown(fd, SHUT_RDWR);
  4152. #endif /* TCP_FD_CACHE */
  4153. tcp_safe_close(fd);
  4154. }
  4155. c=next;
  4156. }
  4157. }
  4158. TCPCONN_UNLOCK;
  4159. }
  4160. /* tcp main loop */
  4161. void tcp_main_loop()
  4162. {
  4163. struct socket_info* si;
  4164. int r;
  4165. is_tcp_main=1; /* mark this process as tcp main */
  4166. tcp_main_max_fd_no=get_max_open_fds();
  4167. /* init send fd queues (here because we want mem. alloc only in the tcp
  4168. * process */
  4169. #ifdef SEND_FD_QUEUE
  4170. if (init_send_fd_queues()<0){
  4171. LM_CRIT("could not init send fd queues\n");
  4172. goto error;
  4173. }
  4174. #endif
  4175. /* init io_wait (here because we want the memory allocated only in
  4176. * the tcp_main process) */
  4177. if (init_io_wait(&io_h, tcp_main_max_fd_no, tcp_poll_method)<0)
  4178. goto error;
  4179. /* init: start watching all the fds*/
  4180. /* init local timer */
  4181. tcp_main_prev_ticks=get_ticks_raw();
  4182. if (init_local_timer(&tcp_main_ltimer, get_ticks_raw())!=0){
  4183. LM_ERR("failed to init local timer\n");
  4184. goto error;
  4185. }
  4186. #ifdef TCP_FD_CACHE
  4187. if (cfg_get(tcp, tcp_cfg, fd_cache)) tcp_fd_cache_init();
  4188. #endif /* TCP_FD_CACHE */
  4189. /* add all the sockets we listen on for connections */
  4190. for (si=tcp_listen; si; si=si->next){
  4191. if ((si->proto==PROTO_TCP) &&(si->socket!=-1)){
  4192. if (io_watch_add(&io_h, si->socket, POLLIN, F_SOCKINFO, si)<0){
  4193. LM_CRIT("failed to add listen socket to the fd list\n");
  4194. goto error;
  4195. }
  4196. }else{
  4197. LM_CRIT("non tcp address in tcp_listen\n");
  4198. }
  4199. }
  4200. #ifdef USE_TLS
  4201. if (!tls_disable && tls_loaded()){
  4202. for (si=tls_listen; si; si=si->next){
  4203. if ((si->proto==PROTO_TLS) && (si->socket!=-1)){
  4204. if (io_watch_add(&io_h, si->socket, POLLIN, F_SOCKINFO, si)<0){
  4205. LM_CRIT("failed to add tls listen socket to the fd list\n");
  4206. goto error;
  4207. }
  4208. }else{
  4209. LM_CRIT("non tls address in tls_listen\n");
  4210. }
  4211. }
  4212. }
  4213. #endif
  4214. /* add all the unix sockets used for communcation with other ser processes
  4215. * (get fd, new connection a.s.o) */
  4216. for (r=1; r<process_no; r++){
  4217. if (pt[r].unix_sock>0) /* we can't have 0, we never close it!*/
  4218. if (io_watch_add(&io_h, pt[r].unix_sock, POLLIN,F_PROC, &pt[r])<0){
  4219. LM_CRIT("failed to add process %d unix socket to the fd list\n", r);
  4220. goto error;
  4221. }
  4222. }
  4223. /* add all the unix sokets used for communication with the tcp childs */
  4224. for (r=0; r<tcp_children_no; r++){
  4225. if (tcp_children[r].unix_sock>0)/*we can't have 0, we never close it!*/
  4226. if (io_watch_add(&io_h, tcp_children[r].unix_sock, POLLIN,
  4227. F_TCPCHILD, &tcp_children[r]) <0){
  4228. LM_CRIT("failed to add tcp child %d unix socket to the fd list\n", r);
  4229. goto error;
  4230. }
  4231. }
  4232. /* initialize the cfg framework */
  4233. if (cfg_child_init()) goto error;
  4234. /* main loop */
  4235. switch(io_h.poll_method){
  4236. case POLL_POLL:
  4237. while(1){
  4238. /* wait and process IO */
  4239. io_wait_loop_poll(&io_h, TCP_MAIN_SELECT_TIMEOUT, 0);
  4240. send_fd_queue_run(&send2child_q); /* then new io */
  4241. /* remove old connections */
  4242. tcp_timer_run();
  4243. }
  4244. break;
  4245. #ifdef HAVE_SELECT
  4246. case POLL_SELECT:
  4247. while(1){
  4248. io_wait_loop_select(&io_h, TCP_MAIN_SELECT_TIMEOUT, 0);
  4249. send_fd_queue_run(&send2child_q); /* then new io */
  4250. tcp_timer_run();
  4251. }
  4252. break;
  4253. #endif
  4254. #ifdef HAVE_SIGIO_RT
  4255. case POLL_SIGIO_RT:
  4256. while(1){
  4257. io_wait_loop_sigio_rt(&io_h, TCP_MAIN_SELECT_TIMEOUT);
  4258. send_fd_queue_run(&send2child_q); /* then new io */
  4259. tcp_timer_run();
  4260. }
  4261. break;
  4262. #endif
  4263. #ifdef HAVE_EPOLL
  4264. case POLL_EPOLL_LT:
  4265. while(1){
  4266. io_wait_loop_epoll(&io_h, TCP_MAIN_SELECT_TIMEOUT, 0);
  4267. send_fd_queue_run(&send2child_q); /* then new io */
  4268. tcp_timer_run();
  4269. }
  4270. break;
  4271. case POLL_EPOLL_ET:
  4272. while(1){
  4273. io_wait_loop_epoll(&io_h, TCP_MAIN_SELECT_TIMEOUT, 1);
  4274. send_fd_queue_run(&send2child_q); /* then new io */
  4275. tcp_timer_run();
  4276. }
  4277. break;
  4278. #endif
  4279. #ifdef HAVE_KQUEUE
  4280. case POLL_KQUEUE:
  4281. while(1){
  4282. io_wait_loop_kqueue(&io_h, TCP_MAIN_SELECT_TIMEOUT, 0);
  4283. send_fd_queue_run(&send2child_q); /* then new io */
  4284. tcp_timer_run();
  4285. }
  4286. break;
  4287. #endif
  4288. #ifdef HAVE_DEVPOLL
  4289. case POLL_DEVPOLL:
  4290. while(1){
  4291. io_wait_loop_devpoll(&io_h, TCP_MAIN_SELECT_TIMEOUT, 0);
  4292. send_fd_queue_run(&send2child_q); /* then new io */
  4293. tcp_timer_run();
  4294. }
  4295. break;
  4296. #endif
  4297. default:
  4298. LM_CRIT("no support for poll method %s (%d)\n",
  4299. poll_method_name(io_h.poll_method), io_h.poll_method);
  4300. goto error;
  4301. }
  4302. error:
  4303. #ifdef SEND_FD_QUEUE
  4304. destroy_send_fd_queues();
  4305. #endif
  4306. destroy_io_wait(&io_h);
  4307. LM_CRIT("exiting...");
  4308. exit(-1);
  4309. }
  4310. /* cleanup before exit */
  4311. void destroy_tcp()
  4312. {
  4313. if (tcpconn_id_hash){
  4314. if (tcpconn_lock)
  4315. TCPCONN_UNLOCK; /* hack: force-unlock the tcp lock in case
  4316. some process was terminated while holding
  4317. it; this will allow an almost gracious
  4318. shutdown */
  4319. tcpconn_destroy_all();
  4320. shm_free(tcpconn_id_hash);
  4321. tcpconn_id_hash=0;
  4322. }
  4323. DESTROY_TCP_STATS();
  4324. if (tcp_connections_no){
  4325. shm_free(tcp_connections_no);
  4326. tcp_connections_no=0;
  4327. }
  4328. if (tls_connections_no){
  4329. shm_free(tls_connections_no);
  4330. tls_connections_no=0;
  4331. }
  4332. #ifdef TCP_ASYNC
  4333. if (tcp_total_wq){
  4334. shm_free(tcp_total_wq);
  4335. tcp_total_wq=0;
  4336. }
  4337. #endif /* TCP_ASYNC */
  4338. if (connection_id){
  4339. shm_free(connection_id);
  4340. connection_id=0;
  4341. }
  4342. if (tcpconn_aliases_hash){
  4343. shm_free(tcpconn_aliases_hash);
  4344. tcpconn_aliases_hash=0;
  4345. }
  4346. if (tcpconn_lock){
  4347. lock_destroy(tcpconn_lock);
  4348. lock_dealloc((void*)tcpconn_lock);
  4349. tcpconn_lock=0;
  4350. }
  4351. if (tcp_children){
  4352. pkg_free(tcp_children);
  4353. tcp_children=0;
  4354. }
  4355. destroy_local_timer(&tcp_main_ltimer);
  4356. }
  4357. int init_tcp()
  4358. {
  4359. char* poll_err;
  4360. tcp_options_check();
  4361. if (tcp_cfg==0){
  4362. BUG("tcp_cfg not initialized\n");
  4363. goto error;
  4364. }
  4365. /* init lock */
  4366. tcpconn_lock=lock_alloc();
  4367. if (tcpconn_lock==0){
  4368. LM_CRIT("could not alloc lock\n");
  4369. goto error;
  4370. }
  4371. if (lock_init(tcpconn_lock)==0){
  4372. LM_CRIT("could not init lock\n");
  4373. lock_dealloc((void*)tcpconn_lock);
  4374. tcpconn_lock=0;
  4375. goto error;
  4376. }
  4377. /* init globals */
  4378. tcp_connections_no=shm_malloc(sizeof(int));
  4379. if (tcp_connections_no==0){
  4380. LM_CRIT("could not alloc globals\n");
  4381. goto error;
  4382. }
  4383. *tcp_connections_no=0;
  4384. tls_connections_no=shm_malloc(sizeof(int));
  4385. if (tls_connections_no==0){
  4386. LM_CRIT("could not alloc globals\n");
  4387. goto error;
  4388. }
  4389. *tls_connections_no=0;
  4390. if (INIT_TCP_STATS()!=0) goto error;
  4391. connection_id=shm_malloc(sizeof(int));
  4392. if (connection_id==0){
  4393. LM_CRIT("could not alloc globals\n");
  4394. goto error;
  4395. }
  4396. *connection_id=1;
  4397. #ifdef TCP_ASYNC
  4398. tcp_total_wq=shm_malloc(sizeof(*tcp_total_wq));
  4399. if (tcp_total_wq==0){
  4400. LM_CRIT("could not alloc globals\n");
  4401. goto error;
  4402. }
  4403. #endif /* TCP_ASYNC */
  4404. /* alloc hashtables*/
  4405. tcpconn_aliases_hash=(struct tcp_conn_alias**)
  4406. shm_malloc(TCP_ALIAS_HASH_SIZE* sizeof(struct tcp_conn_alias*));
  4407. if (tcpconn_aliases_hash==0){
  4408. LM_CRIT("could not alloc address hashtable\n");
  4409. goto error;
  4410. }
  4411. tcpconn_id_hash=(struct tcp_connection**)shm_malloc(TCP_ID_HASH_SIZE*
  4412. sizeof(struct tcp_connection*));
  4413. if (tcpconn_id_hash==0){
  4414. LM_CRIT("could not alloc id hashtable\n");
  4415. goto error;
  4416. }
  4417. /* init hashtables*/
  4418. memset((void*)tcpconn_aliases_hash, 0,
  4419. TCP_ALIAS_HASH_SIZE * sizeof(struct tcp_conn_alias*));
  4420. memset((void*)tcpconn_id_hash, 0,
  4421. TCP_ID_HASH_SIZE * sizeof(struct tcp_connection*));
  4422. /* fix config variables */
  4423. poll_err=check_poll_method(tcp_poll_method);
  4424. /* set an appropriate poll method */
  4425. if (poll_err || (tcp_poll_method==0)){
  4426. tcp_poll_method=choose_poll_method();
  4427. if (poll_err){
  4428. LM_ERR("%s, using %s instead\n",
  4429. poll_err, poll_method_name(tcp_poll_method));
  4430. }else{
  4431. LM_INFO("using %s as the io watch method (auto detected)\n",
  4432. poll_method_name(tcp_poll_method));
  4433. }
  4434. }else{
  4435. LM_INFO("using %s io watch method (config)\n",
  4436. poll_method_name(tcp_poll_method));
  4437. }
  4438. return 0;
  4439. error:
  4440. /* clean-up */
  4441. destroy_tcp();
  4442. return -1;
  4443. }
  4444. #ifdef TCP_CHILD_NON_BLOCKING
  4445. /* returns -1 on error */
  4446. static int set_non_blocking(int s)
  4447. {
  4448. int flags;
  4449. /* non-blocking */
  4450. flags=fcntl(s, F_GETFL);
  4451. if (flags==-1){
  4452. LM_ERR("fnctl failed: (%d) %s\n", errno, strerror(errno));
  4453. goto error;
  4454. }
  4455. if (fcntl(s, F_SETFL, flags|O_NONBLOCK)==-1){
  4456. LM_ERR("fcntl: set non-blocking failed: (%d) %s\n", errno, strerror(errno));
  4457. goto error;
  4458. }
  4459. return 0;
  4460. error:
  4461. return -1;
  4462. }
  4463. #endif
  4464. /* returns -1 on error, 0 on success */
  4465. int tcp_fix_child_sockets(int* fd)
  4466. {
  4467. #ifdef TCP_CHILD_NON_BLOCKING
  4468. if ((set_non_blocking(fd[0])<0) ||
  4469. (set_non_blocking(fd[1])<0)){
  4470. return -1;
  4471. }
  4472. #endif
  4473. return 0;
  4474. }
  4475. /* starts the tcp processes */
  4476. int tcp_init_children()
  4477. {
  4478. int r, i;
  4479. int reader_fd_1; /* for comm. with the tcp children read */
  4480. pid_t pid;
  4481. char si_desc[MAX_PT_DESC];
  4482. struct socket_info *si;
  4483. /* estimate max fd. no:
  4484. * 1 tcp send unix socket/all_proc,
  4485. * + 1 udp sock/udp proc + 1 tcp_child sock/tcp child*
  4486. * + no_listen_tcp */
  4487. for(r=0, si=tcp_listen; si; si=si->next, r++);
  4488. #ifdef USE_TLS
  4489. if (! tls_disable)
  4490. for (si=tls_listen; si; si=si->next, r++);
  4491. #endif
  4492. register_fds(r+tcp_max_connections+get_max_procs()-1 /* tcp main */);
  4493. #if 0
  4494. tcp_max_fd_no=get_max_procs()*2 +r-1 /* timer */ +3; /* stdin/out/err*/
  4495. /* max connections can be temporarily exceeded with estimated_process_count
  4496. * - tcp_main (tcpconn_connect called simultaneously in all all the
  4497. * processes) */
  4498. tcp_max_fd_no+=tcp_max_connections+get_max_procs()-1 /* tcp main */;
  4499. #endif
  4500. /* alloc the children array */
  4501. tcp_children=pkg_malloc(sizeof(struct tcp_child)*tcp_children_no);
  4502. if (tcp_children==0){
  4503. LM_ERR("out of memory\n");
  4504. goto error;
  4505. }
  4506. memset(tcp_children, 0, sizeof(struct tcp_child)*tcp_children_no);
  4507. /* assign own socket for tcp workers, if it is the case
  4508. * - add them from end to start of tcp children array
  4509. * - thus, have generic tcp workers at beginning */
  4510. i = tcp_children_no-1;
  4511. for(si=tcp_listen; si; si=si->next) {
  4512. if(si->workers>0) {
  4513. si->workers_tcpidx = i - si->workers + 1;
  4514. for(r=0; r<si->workers; r++) {
  4515. tcp_children[i].mysocket = si;
  4516. i--;
  4517. }
  4518. }
  4519. }
  4520. #ifdef USE_TLS
  4521. for(si=tls_listen; si; si=si->next) {
  4522. if(si->workers>0) {
  4523. si->workers_tcpidx = i - si->workers + 1;
  4524. for(r=0; r<si->workers; r++) {
  4525. tcp_children[i].mysocket = si;
  4526. i--;
  4527. }
  4528. }
  4529. }
  4530. #endif
  4531. tcp_sockets_gworkers = (i != tcp_children_no-1)?(1 + i + 1):0;
  4532. /* create the tcp sock_info structures */
  4533. /* copy the sockets --moved to main_loop*/
  4534. /* fork children & create the socket pairs*/
  4535. for(r=0; r<tcp_children_no; r++){
  4536. child_rank++;
  4537. snprintf(si_desc, MAX_PT_DESC, "tcp receiver (%s)",
  4538. (tcp_children[r].mysocket!=NULL)?
  4539. tcp_children[r].mysocket->sock_str.s:"generic");
  4540. pid=fork_tcp_process(child_rank, si_desc, r, &reader_fd_1);
  4541. if (pid<0){
  4542. LM_ERR("fork failed: %s\n", strerror(errno));
  4543. goto error;
  4544. }else if (pid>0){
  4545. /* parent */
  4546. }else{
  4547. /* child */
  4548. bind_address=0; /* force a SEGFAULT if someone uses a non-init.
  4549. bind address on tcp */
  4550. tcp_receive_loop(reader_fd_1);
  4551. }
  4552. }
  4553. return 0;
  4554. error:
  4555. return -1;
  4556. }
  4557. void tcp_get_info(struct tcp_gen_info *ti)
  4558. {
  4559. ti->tcp_readers=tcp_children_no;
  4560. ti->tcp_max_connections=tcp_max_connections;
  4561. ti->tls_max_connections=tls_max_connections;
  4562. ti->tcp_connections_no=*tcp_connections_no;
  4563. ti->tls_connections_no=*tls_connections_no;
  4564. #ifdef TCP_ASYNC
  4565. ti->tcp_write_queued=*tcp_total_wq;
  4566. #else
  4567. ti->tcp_write_queued=0;
  4568. #endif /* TCP_ASYNC */
  4569. }
  4570. #endif