tcp_main.c 146 KB

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