jsocket.cpp 205 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. // New IPv6 Version - IN PROGRESS
  14. /*
  15. TBD IPv6 connect
  16. multicast
  17. look at loopback
  18. */
  19. #include <string>
  20. #include <unordered_set>
  21. #include <functional>
  22. #include "platform.h"
  23. #ifdef _VER_C5
  24. #include <clwclib.h>
  25. #else
  26. #include "platform.h"
  27. #include <stdio.h>
  28. #endif
  29. #include <algorithm>
  30. #ifdef _WIN32
  31. #define WIN32_LEAN_AND_MEAN
  32. #include <windows.h>
  33. #include <winsock2.h>
  34. #include <ws2tcpip.h>
  35. #include <signal.h>
  36. #else
  37. #include <sys/types.h>
  38. #include <sys/socket.h>
  39. #include <netinet/tcp.h>
  40. #include <netinet/in.h>
  41. #include <arpa/inet.h>
  42. #include <stddef.h>
  43. #include <errno.h>
  44. #include <net/if.h>
  45. #include <poll.h>
  46. #endif
  47. #include <limits.h>
  48. #include "jmutex.hpp"
  49. #include "jsocket.hpp"
  50. #include "jexcept.hpp"
  51. #include "jio.hpp"
  52. #include "jmisc.hpp"
  53. #include "jthread.hpp"
  54. #include "jqueue.tpp"
  55. #include "jtime.hpp"
  56. #include "jprop.hpp"
  57. #include "jregexp.hpp"
  58. #include "jdebug.hpp"
  59. #include "build-config.h"
  60. // epoll only with linux
  61. #ifndef __linux__
  62. # undef _HAS_EPOLL_SUPPORT
  63. #else
  64. # define _HAS_EPOLL_SUPPORT
  65. # ifdef _HAS_EPOLL_SUPPORT
  66. # include <unistd.h>
  67. # include <sys/epoll.h>
  68. # ifndef EPOLLRDHUP
  69. // Centos 5.x bug - epoll.h does not define but its in the kernel
  70. # define EPOLLRDHUP 0x2000
  71. # endif
  72. # define MAX_RET_EVENTS 5000 // max events returned from epoll_wait() call
  73. static unsigned epoll_hdlPerThrd = UINT_MAX;
  74. # endif
  75. #endif
  76. // various options
  77. #define CONNECT_TIMEOUT_REFUSED_WAIT 1000 // maximum to sleep on connect_timeout
  78. #define TRACE_SLOW_BLOCK_TRANSFER
  79. #define DEFAULT_CONNECT_TIME (100*1000) // for connect_wait
  80. #ifdef _DEBUG
  81. // #define SIMULATE_LOST_UDP_PACKETS
  82. #endif
  83. #ifdef SIMULATE_LOST_UDP_PACKETS
  84. static const int dropThreshold = 10000;
  85. static int dropCounter = 0;
  86. #endif
  87. #ifndef _WIN32
  88. #define BLOCK_POLLED_SINGLE_CONNECTS // NB this is much slower in windows
  89. #define CENTRAL_NODE_RANDOM_DELAY
  90. #else
  91. #define USERECVSEM // to singlethread BF_SYNC_TRANSFER_PUSH
  92. #endif
  93. #ifdef _DEBUG
  94. //#define SOCKTRACE
  95. //#define EPOLLTRACE
  96. #endif
  97. #ifdef _TESTING
  98. #define _TRACE
  99. #endif
  100. #ifdef _TRACE
  101. #define THROWJSOCKEXCEPTION(exc) \
  102. { StringBuffer msg; \
  103. msg.appendf("Target: %s, Raised in: %s, line %d",tracename ,sanitizeSourceFile(__FILE__), __LINE__); \
  104. IJSOCK_Exception *e = new SocketException(exc,msg.str());\
  105. throw e; }
  106. #define THROWJSOCKEXCEPTION2(exc) \
  107. { StringBuffer msg; \
  108. msg.appendf("Raised in: %s, line %d",sanitizeSourceFile(__FILE__), __LINE__); \
  109. IJSOCK_Exception *e = new SocketException(exc,msg.str());\
  110. throw e; }
  111. #define LOGERR(err,ref,info) LogErr(err,ref,info,__LINE__,NULL)
  112. #define LOGERR2(err,ref,info) LogErr(err,ref,info,__LINE__,tracename)
  113. #else
  114. #define THROWJSOCKEXCEPTION(exc) \
  115. { IJSOCK_Exception *e = new SocketException(exc);\
  116. throw e; }
  117. #define THROWJSOCKEXCEPTION2(exc) THROWJSOCKEXCEPTION(exc)
  118. #define LOGERR(err,ref,info)
  119. #define LOGERR2(err,ref,info)
  120. #endif
  121. JSocketStatistics STATS;
  122. static const bool IP4only=false; // slighly faster if we know no IPv6
  123. static bool IP6preferred=false; // e.g. for DNS and socket create
  124. IpSubNet PreferredSubnet(NULL,NULL); // set this if you prefer a particular subnet for debugging etc
  125. // e.g. PreferredSubnet("192.168.16.0", "255.255.255.0")
  126. static RelaxedAtomic<unsigned> pre_conn_unreach_cnt{0}; // global count of pre_connect() JSE_NETUNREACH error
  127. #define IPV6_SERIALIZE_PREFIX (0x00ff00ff)
  128. class jlib_thrown_decl SocketException: public IJSOCK_Exception, public CInterface
  129. {
  130. public:
  131. IMPLEMENT_IINTERFACE;
  132. SocketException(int code,const char *_msg=NULL) : errcode(code)
  133. {
  134. if (_msg)
  135. msg = strdup(_msg);
  136. else
  137. msg = NULL;
  138. };
  139. ~SocketException() { free(msg); }
  140. int errorCode() const { return errcode; }
  141. static StringBuffer & geterrormessage(int err,StringBuffer &str)
  142. {
  143. switch (err) {
  144. case JSOCKERR_ok: return str.append("ok");
  145. case JSOCKERR_not_opened: return str.append("socket not opened");
  146. case JSOCKERR_bad_address: return str.append("bad address");
  147. case JSOCKERR_connection_failed: return str.append("connection failed");
  148. case JSOCKERR_broken_pipe: return str.append("connection is broken");
  149. case JSOCKERR_graceful_close: return str.append("connection closed other end");
  150. case JSOCKERR_invalid_access_mode: return str.append("invalid access mode");
  151. case JSOCKERR_timeout_expired: return str.append("timeout expired");
  152. case JSOCKERR_port_in_use: return str.append("port in use");
  153. case JSOCKERR_cancel_accept: return str.append("cancel accept");
  154. case JSOCKERR_connectionless_socket: return str.append("connectionless socket");
  155. case JSOCKERR_handle_too_large: return str.append("handle too large");
  156. case JSOCKERR_bad_netaddr: return str.append("bad net addr");
  157. case JSOCKERR_ipv6_not_implemented: return str.append("IPv6 not implemented");
  158. // OS errors
  159. #ifdef _WIN32
  160. case WSAEINTR: return str.append("WSAEINTR(10004) - Interrupted system call.");
  161. case WSAEBADF: return str.append("WSAEBADF(10009) - Bad file number.");
  162. case WSAEACCES: return str.append("WSAEACCES(10013) - Permission denied.");
  163. case WSAEFAULT: return str.append("WSAEFAULT(10014) - Bad address.");
  164. case WSAEINVAL: return str.append("WSAEINVAL(10022) - Invalid argument.");
  165. case WSAEMFILE: return str.append("WSAEMFILE(10024) - Too many open files.");
  166. case WSAEWOULDBLOCK: return str.append("WSAEWOULDBLOCK(10035) - Operation would block.");
  167. case WSAEINPROGRESS: return str.append("WSAEINPROGRESS(10036) - Operation now in progress.");
  168. case WSAEALREADY: return str.append("WSAEALREADY(10037) - Operation already in progress.");
  169. case WSAENOTSOCK: return str.append("WSAENOTSOCK(10038) - Socket operation on nonsocket.");
  170. case WSAEDESTADDRREQ: return str.append("WSAEDESTADDRREQ(10039) - Destination address required.");
  171. case WSAEMSGSIZE: return str.append("WSAEMSGSIZE(10040) - Message too long.");
  172. case WSAEPROTOTYPE: return str.append("WSAEPROTOTYPE(10041) - Protocol wrong type for socket.");
  173. case WSAENOPROTOOPT: return str.append("WSAENOPROTOOPT(10042) - Protocol not available.");
  174. case WSAEPROTONOSUPPORT: return str.append("WSAEPROTONOSUPPORT(10043) - Protocol not supported.");
  175. case WSAESOCKTNOSUPPORT: return str.append("WSAESOCKTNOSUPPORT(10044) - Socket type not supported.");
  176. case WSAEOPNOTSUPP: return str.append("WSAEOPNOTSUPP(10045) - Operation not supported on socket.");
  177. case WSAEPFNOSUPPORT: return str.append("WSAEPFNOSUPPORT(10046) - Protocol family not supported.");
  178. case WSAEAFNOSUPPORT: return str.append("WSAEAFNOSUPPORT(10047) - Address family not supported by protocol family.");
  179. case WSAEADDRINUSE: return str.append("WSAEADDRINUSE(10048) - Address already in use.");
  180. case WSAEADDRNOTAVAIL: return str.append("WSAEADDRNOTAVAIL(10049) - Cannot assign requested address.");
  181. case WSAENETDOWN: return str.append("WSAENETDOWN(10050) - Network is down.");
  182. case WSAENETUNREACH: return str.append("WSAENETUNREACH(10051) - Network is unreachable.");
  183. case WSAENETRESET: return str.append("WSAENETRESET(10052) - Network dropped connection on reset.");
  184. case WSAECONNABORTED: return str.append("WSAECONNABORTED(10053) - Software caused connection abort.");
  185. case WSAECONNRESET: return str.append("WSAECONNRESET(10054) - Connection reset by peer.");
  186. case WSAENOBUFS: return str.append("WSAENOBUFS(10055) - No buffer space available.");
  187. case WSAEISCONN: return str.append("WSAEISCONN(10056) - Socket is already connected.");
  188. case WSAENOTCONN: return str.append("WSAENOTCONN(10057) - Socket is not connected.");
  189. case WSAESHUTDOWN: return str.append("WSAESHUTDOWN(10058) - Cannot send after socket shutdown.");
  190. case WSAETOOMANYREFS: return str.append("WSAETOOMANYREFS(10059) - Too many references: cannot splice.");
  191. case WSAETIMEDOUT: return str.append("WSAETIMEDOUT(10060) - Connection timed out.");
  192. case WSAECONNREFUSED: return str.append("WSAECONNREFUSED(10061) - Connection refused.");
  193. case WSAELOOP: return str.append("WSAELOOP(10062) - Too many levels of symbolic links.");
  194. case WSAENAMETOOLONG: return str.append("WSAENAMETOOLONG(10063) - File name too long.");
  195. case WSAEHOSTDOWN: return str.append("WSAEHOSTDOWN(10064) - Host is down.");
  196. case WSAEHOSTUNREACH: return str.append("WSAEHOSTUNREACH(10065) - No route to host.");
  197. case WSASYSNOTREADY: return str.append("WSASYSNOTREADY(10091) - The network subsystem is unusable.");
  198. case WSAVERNOTSUPPORTED: return str.append("WSAVERNOTSUPPORTED(10092) - The Windows Sockets DLL cannot support this application.");
  199. case WSANOTINITIALISED: return str.append("WSANOTINITIALISED(10093) - Winsock not initialized.");
  200. case WSAEDISCON: return str.append("WSAEDISCON(10101) - Disconnect.");
  201. case WSAHOST_NOT_FOUND: return str.append("WSAHOST_NOT_FOUND(11001) - Host not found.");
  202. case WSATRY_AGAIN: return str.append("WSATRY_AGAIN(11002) - Nonauthoritative host not found.");
  203. case WSANO_RECOVERY: return str.append("WSANO_RECOVERY(11003) - Nonrecoverable error.");
  204. case WSANO_DATA: return str.append("WSANO_DATA(11004) - Valid name, no data record of requested type.");
  205. #else
  206. case ENOTSOCK: return str.append("ENOTSOCK - Socket operation on non-socket ");
  207. case EDESTADDRREQ: return str.append("EDESTADDRREQ - Destination address required ");
  208. case EMSGSIZE: return str.append("EMSGSIZE - Message too long ");
  209. case EPROTOTYPE: return str.append("EPROTOTYPE - Protocol wrong type for socket ");
  210. case ENOPROTOOPT: return str.append("ENOPROTOOPT - Protocol not available ");
  211. case EPROTONOSUPPORT: return str.append("EPROTONOSUPPORT - Protocol not supported ");
  212. case ESOCKTNOSUPPORT: return str.append("ESOCKTNOSUPPORT - Socket type not supported ");
  213. case EOPNOTSUPP: return str.append("EOPNOTSUPP - Operation not supported on socket ");
  214. case EPFNOSUPPORT: return str.append("EPFNOSUPPORT - Protocol family not supported ");
  215. case EAFNOSUPPORT: return str.append("EAFNOSUPPORT - Address family not supported by protocol family ");
  216. case EADDRINUSE: return str.append("EADDRINUSE - Address already in use ");
  217. case EADDRNOTAVAIL: return str.append("EADDRNOTAVAIL - Can't assign requested address ");
  218. case ENETDOWN: return str.append("ENETDOWN - Network is down ");
  219. case ENETUNREACH: return str.append("ENETUNREACH - Network is unreachable ");
  220. case ENETRESET: return str.append("ENETRESET - Network dropped connection because of reset ");
  221. case ECONNABORTED: return str.append("ECONNABORTED - Software caused connection abort ");
  222. case ECONNRESET: return str.append("ECONNRESET - Connection reset by peer ");
  223. case ENOBUFS: return str.append("ENOBUFS - No buffer space available ");
  224. case EISCONN: return str.append("EISCONN - Socket is already connected ");
  225. case ENOTCONN: return str.append("ENOTCONN - Socket is not connected ");
  226. case ESHUTDOWN: return str.append("ESHUTDOWN - Can't send after socket shutdown ");
  227. case ETOOMANYREFS: return str.append("ETOOMANYREFS - Too many references: can't splice ");
  228. case ETIMEDOUT: return str.append("ETIMEDOUT - Connection timed out ");
  229. case ECONNREFUSED: return str.append("ECONNREFUSED - Connection refused ");
  230. case EHOSTDOWN: return str.append("EHOSTDOWN - Host is down ");
  231. case EHOSTUNREACH: return str.append("EHOSTUNREACH - No route to host ");
  232. case EWOULDBLOCK: return str.append("EWOULDBLOCK - operation already in progress");
  233. case EINPROGRESS: return str.append("EINPROGRESS - operation now in progress ");
  234. #endif
  235. }
  236. IException *ose = makeOsException(err);
  237. ose->errorMessage(str);
  238. ose->Release();
  239. return str;
  240. }
  241. StringBuffer & errorMessage(StringBuffer &str) const
  242. {
  243. if (msg)
  244. return geterrormessage(errcode,str).append('\n').append(msg);
  245. return geterrormessage(errcode,str);
  246. }
  247. MessageAudience errorAudience() const
  248. {
  249. switch (errcode) {
  250. case JSOCKERR_port_in_use:
  251. return MSGAUD_operator;
  252. }
  253. return MSGAUD_user;
  254. }
  255. private:
  256. int errcode;
  257. char *msg;
  258. };
  259. IJSOCK_Exception *IPv6NotImplementedException(const char *filename,unsigned lineno)
  260. {
  261. StringBuffer msg;
  262. msg.appendf("%s(%d)",filename,lineno);
  263. return new SocketException(JSOCKERR_ipv6_not_implemented,msg.str());
  264. }
  265. struct MCASTREQ
  266. {
  267. struct in_addr imr_multiaddr; /* multicast group to join */
  268. struct in_addr imr_interface; /* interface to join on */
  269. MCASTREQ(const char *mcip)
  270. {
  271. imr_multiaddr.s_addr = inet_addr(mcip);
  272. imr_interface.s_addr = htonl(INADDR_ANY);
  273. }
  274. };
  275. #ifdef __APPLE__
  276. #ifndef MSG_NOSIGNAL
  277. #define MSG_NOSIGNAL 0x4000
  278. #endif
  279. #endif
  280. #if defined( _WIN32)
  281. #define T_SOCKET SOCKET
  282. #define T_FD_SET fd_set
  283. #define XFD_SETSIZE FD_SETSIZE
  284. //Following are defined in more modern headers
  285. #define XFD_ZERO(s) FD_ZERO(s)
  286. #define SEND_FLAGS 0
  287. #define CHECKSOCKRANGE(s)
  288. #define _USE_SELECT // Windows bug 309411 - WSAPoll does not report failed connections - wont fix
  289. // #define poll(a, b, c) WSAPoll((a), (b), (c))
  290. #elif defined(__FreeBSD__) || defined(__APPLE__)
  291. #define XFD_SETSIZE FD_SETSIZE
  292. #define T_FD_SET fd_set
  293. #define XFD_ZERO(s) FD_ZERO(s)
  294. #define T_SOCKET int
  295. #define SEND_FLAGS (MSG_NOSIGNAL)
  296. #define CHECKSOCKRANGE(s)
  297. #else
  298. #define XFD_SETSIZE 32768
  299. struct xfd_set { __fd_mask fds_bits[XFD_SETSIZE / __NFDBITS]; }; // define our own
  300. // linux 64 bit
  301. #ifdef __linux__
  302. #ifdef __64BIT__
  303. #undef __FDMASK
  304. #define __FDMASK(d) (1UL << ((d) % __NFDBITS))
  305. #undef __FDELT
  306. #define __FDELT(d) ((d) / __NFDBITS)
  307. #undef __FD_SET
  308. #define __FD_SET(d, s) (__FDS_BITS (s)[__FDELT(d)] |= __FDMASK(d))
  309. #undef __FD_ISSET
  310. #define __FD_ISSET(d, s) ((__FDS_BITS (s)[__FDELT(d)] & __FDMASK(d)) != 0)
  311. #endif
  312. #define CHECKSOCKRANGE(s) { if (s>=XFD_SETSIZE) THROWJSOCKEXCEPTION2(JSOCKERR_handle_too_large); }
  313. #endif
  314. // end 64 bit
  315. #define T_FD_SET xfd_set
  316. #define XFD_ZERO(s) memset(s,0,sizeof(xfd_set))
  317. #define T_SOCKET int
  318. #define SEND_FLAGS (MSG_NOSIGNAL)
  319. #endif
  320. #ifdef CENTRAL_NODE_RANDOM_DELAY
  321. static SocketEndpointArray CentralNodeArray;
  322. #endif
  323. enum SOCKETMODE { sm_tcp_server, sm_tcp, sm_udp_server, sm_udp, sm_multicast_server, sm_multicast};
  324. #define BADSOCKERR(err) ((err==JSE_BADF)||(err==JSE_NOTSOCK))
  325. #ifdef POLLRDHUP
  326. # define POLLINX (POLLIN | POLLRDHUP)
  327. #else
  328. # define POLLINX POLLIN
  329. #endif
  330. #ifdef _HAS_EPOLL_SUPPORT
  331. # ifdef EPOLLRDHUP
  332. # define EPOLLINX (EPOLLIN | EPOLLRDHUP)
  333. # else
  334. # define EPOLLINX EPOLLIN
  335. # endif
  336. #endif
  337. class CSocket: public ISocket, public CInterface
  338. {
  339. public:
  340. IMPLEMENT_IINTERFACE;
  341. static CriticalSection crit;
  342. protected:
  343. friend class CSocketConnectWait;
  344. enum { ss_open, ss_shutdown, ss_close, ss_pre_open } state;
  345. T_SOCKET sock;
  346. char* hostname; // host address
  347. unsigned short hostport; // host port
  348. unsigned short localPort;
  349. SOCKETMODE sockmode;
  350. IpAddress targetip;
  351. SocketEndpoint returnep; // set by set_return_addr
  352. MCASTREQ * mcastreq;
  353. size32_t nextblocksize;
  354. unsigned blockflags;
  355. unsigned blocktimeoutms;
  356. bool owned;
  357. enum {accept_not_cancelled, accept_cancel_pending, accept_cancelled} accept_cancel_state;
  358. bool in_accept;
  359. bool nonblocking;
  360. bool nagling;
  361. static unsigned connectingcount;
  362. #ifdef USERECVSEM
  363. static Semaphore receiveblocksem;
  364. bool receiveblocksemowned; // owned by this socket
  365. #endif
  366. #ifdef _TRACE
  367. char * tracename;
  368. #endif
  369. public:
  370. void open(int listen_queue_size,bool reuseports=false);
  371. bool connect_timeout( unsigned timeout, bool noexception);
  372. void connect_wait( unsigned timems);
  373. void udpconnect();
  374. void read(void* buf, size32_t min_size, size32_t max_size, size32_t &size_read,unsigned timeoutsecs);
  375. void readtms(void* buf, size32_t min_size, size32_t max_size, size32_t &size_read, unsigned timedelaysecs);
  376. void read(void* buf, size32_t size);
  377. size32_t write(void const* buf, size32_t size);
  378. size32_t writetms(void const* buf, size32_t size, unsigned timeoutms=WAIT_FOREVER);
  379. size32_t write_multiple(unsigned num,void const**buf, size32_t *size);
  380. size32_t udp_write_to(const SocketEndpoint &ep,void const* buf, size32_t size);
  381. void close();
  382. void errclose();
  383. bool connectionless() { return (sockmode!=sm_tcp)&&(sockmode!=sm_tcp_server); }
  384. void shutdown(unsigned mode=SHUTDOWN_READWRITE);
  385. ISocket* accept(bool allowcancel, SocketEndpoint *peerEp=nullptr);
  386. int wait_read(unsigned timeout);
  387. int logPollError(unsigned revents, const char *rwstr);
  388. int wait_write(unsigned timeout);
  389. int name(char *name,size32_t namemax);
  390. int peer_name(char *name,size32_t namemax);
  391. SocketEndpoint &getPeerEndpoint(SocketEndpoint &ep);
  392. IpAddress & getPeerAddress(IpAddress &addr);
  393. SocketEndpoint &getEndpoint(SocketEndpoint &ep) const override;
  394. void set_return_addr(int port,const char *name); // sets returnep
  395. void cancel_accept();
  396. size32_t get_max_send_size();
  397. bool set_nonblock(bool on=true);
  398. bool set_nagle(bool on);
  399. void set_linger(int lingersecs);
  400. void set_keep_alive(bool set);
  401. void logConnectionInfo(unsigned timeoutms, unsigned conn_mstime);
  402. virtual void set_inherit(bool inherit=false);
  403. virtual bool check_connection();
  404. virtual bool isSecure() const override;
  405. // Block functions
  406. void set_block_mode(unsigned flags,size32_t recsize=0,unsigned timeoutms=0);
  407. bool send_block(const void *blk,size32_t sz);
  408. size32_t receive_block_size();
  409. size32_t receive_block(void *blk,size32_t sz);
  410. size32_t get_send_buffer_size();
  411. void set_send_buffer_size(size32_t sz);
  412. bool join_multicast_group(SocketEndpoint &ep); // for udp multicast
  413. bool leave_multicast_group(SocketEndpoint &ep); // for udp multicast
  414. void set_ttl(unsigned _ttl);
  415. size32_t get_receive_buffer_size();
  416. void set_receive_buffer_size(size32_t sz);
  417. size32_t avail_read();
  418. int pre_connect(bool block);
  419. int post_connect();
  420. void setTraceName(const char * prefix, const char * name);
  421. void setTraceName();
  422. CSocket(const SocketEndpoint &_ep,SOCKETMODE smode,const char *name);
  423. CSocket(T_SOCKET new_sock,SOCKETMODE smode,bool _owned);
  424. virtual ~CSocket();
  425. virtual unsigned OShandle() const
  426. {
  427. return (unsigned)sock;
  428. }
  429. virtual bool isValid() const
  430. {
  431. return sock != INVALID_SOCKET;
  432. }
  433. private:
  434. int closesock()
  435. {
  436. if (sock!=INVALID_SOCKET) {
  437. T_SOCKET s = sock;
  438. sock = INVALID_SOCKET;
  439. STATS.activesockets--;
  440. #ifdef SOCKTRACE
  441. PROGLOG("SOCKTRACE: Closing socket %x %d (%p)", s, s, this);
  442. #endif
  443. #ifdef _WIN32
  444. return ::closesocket(s);
  445. #else
  446. ::shutdown(s, SHUT_WR);
  447. return ::close(s);
  448. #endif
  449. }
  450. else
  451. return 0;
  452. }
  453. };
  454. CriticalSection CSocket::crit;
  455. unsigned CSocket::connectingcount=0;
  456. #ifdef USERECVSEM
  457. Semaphore CSocket::receiveblocksem(2);
  458. #endif
  459. #ifdef _WIN32
  460. class win_socket_library
  461. {
  462. static bool initdone; // to prevent dependancy probs very early on (e.g. jlog)
  463. public:
  464. win_socket_library() { init(); }
  465. bool init()
  466. {
  467. if (initdone)
  468. return true;
  469. WSADATA wsa;
  470. if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
  471. if (WSAStartup(MAKEWORD(1, 1), &wsa) != 0) {
  472. MessageBox(NULL,"Failed to initialize windows sockets","JLib Socket Error",MB_OK);
  473. return false;
  474. }
  475. }
  476. initdone = true;
  477. return true;
  478. }
  479. ~win_socket_library()
  480. {
  481. WSACleanup();
  482. }
  483. };
  484. bool win_socket_library::initdone = false;
  485. static win_socket_library ws32_lib;
  486. #define ERRNO() WSAGetLastError()
  487. #define JSE_ADDRINUSE WSAEADDRINUSE
  488. #define JSE_CONNRESET WSAECONNRESET
  489. #define JSE_CONNABORTED WSAECONNABORTED
  490. #define JSE_NOTCONN WSAENOTCONN
  491. #define JSE_WOULDBLOCK WSAEWOULDBLOCK
  492. #define JSE_INPROGRESS WSAEINPROGRESS
  493. #define JSE_NETUNREACH WSAENETUNREACH
  494. #define JSE_NOTSOCK WSAENOTSOCK
  495. #define JSE_TIMEDOUT WSAETIMEDOUT
  496. #define JSE_CONNREFUSED WSAECONNREFUSED
  497. #define JSE_BADF WSAEBADF
  498. #define JSE_INTR WSAEINTR
  499. struct j_sockaddr_in6 {
  500. short sin6_family; /* AF_INET6 */
  501. u_short sin6_port; /* Transport level port number */
  502. u_long sin6_flowinfo; /* IPv6 flow information */
  503. struct in_addr6 sin6_addr; /* IPv6 address */
  504. u_long sin6_scope_id; /* set of interfaces for a scope */
  505. };
  506. typedef union {
  507. struct sockaddr sa;
  508. struct j_sockaddr_in6 sin6;
  509. struct sockaddr_in sin;
  510. } J_SOCKADDR;
  511. #define DEFINE_SOCKADDR(name) J_SOCKADDR name; memset(&name,0,sizeof(J_SOCKADDR))
  512. static int _inet_pton(int af, const char* src, void* dst)
  513. {
  514. DEFINE_SOCKADDR(u);
  515. int address_length;
  516. switch (af) {
  517. case AF_INET:
  518. u.sin.sin_family = AF_INET;
  519. address_length = sizeof (u.sin);
  520. break;
  521. case AF_INET6:
  522. u.sin6.sin6_family = AF_INET6;
  523. address_length = sizeof (u.sin6);
  524. break;
  525. default:
  526. #ifdef EAFNOSUPPORT
  527. errno = EAFNOSUPPORT;
  528. #else
  529. errno = 52;
  530. #endif
  531. return -1;
  532. }
  533. ws32_lib.init();
  534. int ret = WSAStringToAddress ((LPTSTR) src, af, NULL, &u.sa, &address_length);
  535. if (ret == 0) {
  536. switch (af) {
  537. case AF_INET:
  538. memcpy (dst, &u.sin.sin_addr, sizeof (struct in_addr));
  539. break;
  540. case AF_INET6:
  541. memcpy (dst, &u.sin6.sin6_addr, sizeof (u.sin6.sin6_addr));
  542. break;
  543. }
  544. return 1;
  545. }
  546. errno = WSAGetLastError();
  547. // PROGLOG("errno = %d",errno);
  548. return 0;
  549. }
  550. static const char * _inet_ntop (int af, const void *src, char *dst, socklen_t cnt)
  551. {
  552. /* struct sockaddr can't accomodate struct sockaddr_in6. */
  553. DEFINE_SOCKADDR(u);
  554. DWORD dstlen = cnt;
  555. size_t srcsize;
  556. memset(&u,0,sizeof(u));
  557. switch (af) {
  558. case AF_INET:
  559. u.sin.sin_family = AF_INET;
  560. u.sin.sin_addr = *(struct in_addr *) src;
  561. srcsize = sizeof (u.sin);
  562. break;
  563. case AF_INET6:
  564. u.sin6.sin6_family = AF_INET6;
  565. memcpy(&u.sin6.sin6_addr,src,sizeof(in_addr6));
  566. srcsize = sizeof (u.sin6);
  567. break;
  568. default:
  569. return NULL;
  570. }
  571. ws32_lib.init();
  572. if (WSAAddressToString (&u.sa, srcsize, NULL, dst, &dstlen) != 0) {
  573. errno = WSAGetLastError();
  574. return NULL;
  575. }
  576. return (const char *) dst;
  577. }
  578. int inet_aton (const char *name, struct in_addr *addr)
  579. {
  580. addr->s_addr = inet_addr (name);
  581. return (addr->s_addr == (u_long)-1)?1:0; // 255.255.255.255 has had it here
  582. }
  583. #else
  584. #define JSE_ADDRINUSE EADDRINUSE
  585. #define JSE_CONNRESET ECONNRESET
  586. #define JSE_CONNABORTED ECONNABORTED
  587. #define JSE_NOTCONN ENOTCONN
  588. #define JSE_WOULDBLOCK EWOULDBLOCK
  589. #define JSE_INPROGRESS EINPROGRESS
  590. #define JSE_NETUNREACH ENETUNREACH
  591. #define JSE_NOTSOCK ENOTSOCK
  592. #define JSE_TIMEDOUT ETIMEDOUT
  593. #define JSE_CONNREFUSED ECONNREFUSED
  594. #define JSE_BADF EBADF
  595. #define _inet_ntop inet_ntop
  596. #define _inet_pton inet_pton
  597. #define in_addr6 in6_addr
  598. typedef union {
  599. struct sockaddr sa;
  600. struct sockaddr_in6 sin6;
  601. struct sockaddr_in sin;
  602. } J_SOCKADDR;
  603. #define DEFINE_SOCKADDR(name) J_SOCKADDR name; memset(&name,0,sizeof(J_SOCKADDR))
  604. #define JSE_INTR EINTR
  605. #define ERRNO() (errno)
  606. #ifndef INADDR_NONE
  607. #define INADDR_NONE (-1)
  608. #endif
  609. #endif
  610. #ifndef INET6_ADDRSTRLEN
  611. #define INET6_ADDRSTRLEN 65
  612. #endif
  613. extern jlib_decl void throwJSocketException(int jsockErr)
  614. {
  615. THROWJSOCKEXCEPTION2(jsockErr);
  616. }
  617. extern jlib_decl IJSOCK_Exception* createJSocketException(int jsockErr, const char *_msg)
  618. {
  619. return new SocketException(jsockErr, _msg);
  620. }
  621. inline void LogErr(unsigned err,unsigned ref,const char *info,unsigned lineno,const char *tracename)
  622. {
  623. if (err)
  624. {
  625. PROGLOG("jsocket(%d,%d)%s%s err = %d%s%s",ref,lineno,
  626. (info&&*info)?" ":"",(info&&*info)?info:"",err,
  627. (tracename&&*tracename)?" : ":"",(tracename&&*tracename)?tracename:"");
  628. #ifdef _TRACELINKCLOSED
  629. if ((JSE_NOTCONN == err) || (JSE_CONNRESET == err) || (JSE_CONNABORTED == err))
  630. {
  631. PROGLOG("Socket not connected, stack:");
  632. PrintStackReport();
  633. }
  634. #endif
  635. }
  636. }
  637. inline socklen_t setSockAddr(J_SOCKADDR &u, const IpAddress &ip,unsigned short port)
  638. {
  639. if (!IP6preferred) {
  640. if (ip.getNetAddress(sizeof(in_addr),&u.sin.sin_addr)==sizeof(in_addr)) {
  641. u.sin.sin_family = AF_INET;
  642. u.sin.sin_port = htons(port);
  643. return sizeof(u.sin);
  644. }
  645. }
  646. if (IP4only)
  647. IPV6_NOT_IMPLEMENTED();
  648. ip.getNetAddress(sizeof(in_addr6),&u.sin6.sin6_addr);
  649. u.sin6.sin6_family = AF_INET6;
  650. u.sin6.sin6_port = htons(port);
  651. return sizeof(u.sin6);
  652. }
  653. inline socklen_t setSockAddrAny(J_SOCKADDR &u, unsigned short port)
  654. {
  655. if (IP6preferred) {
  656. #ifdef _WIN32
  657. IN6ADDR_SETANY((PSOCKADDR_IN6)&u.sin6.sin6_addr);
  658. #else
  659. memcpy(&u.sin6.sin6_addr,&in6addr_any,sizeof(in_addr6));
  660. #endif
  661. u.sin6.sin6_family= AF_INET6;
  662. u.sin6.sin6_port = htons(port);
  663. return sizeof(u.sin6);
  664. }
  665. u.sin.sin_addr.s_addr = htonl(INADDR_ANY);
  666. u.sin.sin_family= AF_INET;
  667. u.sin.sin_port = htons(port);
  668. return sizeof(u.sin);
  669. }
  670. inline void getSockAddrEndpoint(const J_SOCKADDR &u, socklen_t ul, SocketEndpoint &ep)
  671. {
  672. if (ul==sizeof(u.sin)) {
  673. ep.setNetAddress(sizeof(in_addr),&u.sin.sin_addr);
  674. ep.port = htons(u.sin.sin_port);
  675. }
  676. else {
  677. ep.setNetAddress(sizeof(in_addr6),&u.sin6.sin6_addr);
  678. ep.port = htons(u.sin6.sin6_port);
  679. }
  680. }
  681. /* might need fcntl(F_SETFL), or ioctl(FIONBIO) */
  682. /* Posix.1g says fcntl */
  683. #if defined(O_NONBLOCK)
  684. bool CSocket::set_nonblock(bool on)
  685. {
  686. int flags = fcntl(sock, F_GETFL, 0);
  687. if (flags == -1)
  688. return nonblocking;
  689. if (on)
  690. flags |= O_NONBLOCK;
  691. else
  692. flags &= ~O_NONBLOCK;
  693. if (fcntl(sock, F_SETFL, flags)==0) {
  694. bool wasNonBlocking = nonblocking;
  695. nonblocking = on;
  696. return wasNonBlocking;
  697. }
  698. return nonblocking;
  699. }
  700. #else
  701. bool CSocket::set_nonblock(bool on)
  702. {
  703. #ifdef _WIN32
  704. u_long yes = on?1:0;
  705. if (ioctlsocket(sock, FIONBIO, &yes)==0) {
  706. #else
  707. int yes = on?1:0;
  708. if (ioctl(sock, FIONBIO, &yes)==0) {
  709. #endif
  710. bool wasNonBlocking = nonblocking;
  711. nonblocking = on;
  712. return wasNonBlocking;
  713. }
  714. return nonblocking;
  715. }
  716. #endif
  717. bool CSocket::set_nagle(bool on)
  718. {
  719. bool ret = nagling;
  720. nagling = on;
  721. int enabled = !on;
  722. if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char*)&enabled, sizeof(enabled)) != 0) {
  723. nagling = !on;
  724. }
  725. return ret;
  726. }
  727. void CSocket::set_inherit(bool inherit)
  728. {
  729. #ifndef _WIN32
  730. long flag = fcntl(sock, F_GETFD);
  731. if(inherit)
  732. flag &= ~FD_CLOEXEC;
  733. else
  734. flag |= FD_CLOEXEC;
  735. fcntl(sock, F_SETFD, flag);
  736. #endif
  737. }
  738. size32_t CSocket::avail_read()
  739. {
  740. #ifdef _WIN32
  741. u_long avail;
  742. if (ioctlsocket(sock, FIONREAD, &avail)==0)
  743. #else
  744. int avail;
  745. if (ioctl(sock, FIONREAD, &avail)==0)
  746. #endif
  747. return (size32_t)avail;
  748. int err = ERRNO();
  749. LOGERR2(err,1,"avail_read");
  750. return 0;
  751. }
  752. #define PRE_CONN_UNREACH_ELIM 100
  753. int CSocket::pre_connect (bool block)
  754. {
  755. if (NULL == hostname || '\0' == (*hostname))
  756. {
  757. StringBuffer err;
  758. err.appendf("CSocket::pre_connect - Invalid/missing host IP address raised in : %s, line %d",sanitizeSourceFile(__FILE__), __LINE__);
  759. IJSOCK_Exception *e = new SocketException(JSOCKERR_bad_netaddr,err.str());
  760. throw e;
  761. }
  762. DEFINE_SOCKADDR(u);
  763. if (targetip.isNull()) {
  764. set_return_addr(hostport,hostname);
  765. targetip.ipset(returnep);
  766. }
  767. socklen_t ul = setSockAddr(u,targetip,hostport);
  768. sock = ::socket(u.sa.sa_family, SOCK_STREAM, targetip.isIp4()?0:PF_INET6);
  769. owned = true;
  770. state = ss_pre_open; // will be set to open by post_connect
  771. if (sock == INVALID_SOCKET) {
  772. int err = ERRNO();
  773. THROWJSOCKEXCEPTION(err);
  774. }
  775. STATS.activesockets++;
  776. int err = 0;
  777. set_nonblock(!block);
  778. int rc = ::connect(sock, &u.sa, ul);
  779. if (rc==SOCKET_ERROR) {
  780. err = ERRNO();
  781. if ((err != JSE_INPROGRESS)&&(err != JSE_WOULDBLOCK)&&(err != JSE_TIMEDOUT)&&(err!=JSE_CONNREFUSED)) { // handled by caller
  782. if (err != JSE_NETUNREACH) {
  783. pre_conn_unreach_cnt.store(0);
  784. LOGERR2(err,1,"pre_connect");
  785. } else {
  786. int ecnt = pre_conn_unreach_cnt.load();
  787. if (ecnt <= PRE_CONN_UNREACH_ELIM) {
  788. pre_conn_unreach_cnt.fetch_add(1);
  789. LOGERR2(err,1,"pre_connect network unreachable");
  790. }
  791. }
  792. } else
  793. pre_conn_unreach_cnt.store(0);
  794. } else
  795. pre_conn_unreach_cnt.store(0);
  796. #ifdef SOCKTRACE
  797. PROGLOG("SOCKTRACE: pre-connected socket%s %x %d (%p) err=%d", block?"(block)":"", sock, sock, this, err);
  798. #endif
  799. return err;
  800. }
  801. int CSocket::post_connect ()
  802. {
  803. set_nonblock(false);
  804. int err = 0;
  805. socklen_t errlen = sizeof(err);
  806. int rc = getsockopt(sock, SOL_SOCKET, SO_ERROR, (char *)&err, &errlen); // check for error
  807. if ((rc!=0)&&!err)
  808. err = ERRNO(); // some implementations of getsockopt duff
  809. if (err==0) {
  810. nagling = true;
  811. set_nagle(false);
  812. state = ss_open;
  813. SocketEndpoint ep;
  814. localPort = getEndpoint(ep).port;
  815. }
  816. else if ((err!=JSE_TIMEDOUT)&&(err!=JSE_CONNREFUSED)) // handled by caller
  817. LOGERR2(err,1,"post_connect");
  818. return err;
  819. }
  820. void CSocket::open(int listen_queue_size,bool reuseports)
  821. {
  822. // If listen_queue_size==0 then bind port to address but
  823. // do not actually listen() for accepting connections.
  824. // This is used when a unique IP:port is needed for MP client
  825. // INode/IGroup internals, but client never actually accepts connections.
  826. if (IP6preferred)
  827. sock = ::socket(AF_INET6, connectionless()?SOCK_DGRAM:SOCK_STREAM, PF_INET6);
  828. else
  829. sock = ::socket(AF_INET, connectionless()?SOCK_DGRAM:SOCK_STREAM, 0);
  830. if (sock == INVALID_SOCKET) {
  831. THROWJSOCKEXCEPTION(ERRNO());
  832. }
  833. STATS.activesockets++;
  834. #ifdef SOCKTRACE
  835. PROGLOG("SOCKTRACE: opened socket %x %d (%p)", sock,sock,this);
  836. #endif
  837. if ((hostport==0)&&(sockmode==sm_udp)) {
  838. state = ss_open;
  839. #ifdef SOCKTRACE
  840. PROGLOG("SOCKTRACE: opened socket return udp");
  841. #endif
  842. set_inherit(false);
  843. return;
  844. }
  845. #ifndef _WIN32
  846. reuseports = true; // for some reason linux requires reuse ports
  847. #endif
  848. if (reuseports && listen_queue_size) {
  849. int on = 1;
  850. setsockopt( sock, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on));
  851. }
  852. DEFINE_SOCKADDR(u);
  853. socklen_t ul;
  854. if (hostname) {
  855. if (targetip.isNull()) {
  856. set_return_addr(hostport,hostname);
  857. targetip.ipset(returnep);
  858. }
  859. ul = setSockAddr(u,targetip,hostport);
  860. }
  861. else
  862. ul = setSockAddrAny(u,hostport);
  863. int saverr;
  864. if (::bind(sock, &u.sa, ul) != 0) {
  865. saverr = ERRNO();
  866. if (saverr==JSE_ADDRINUSE) { // don't log as error (some usages probe ports)
  867. ErrPortInUse:
  868. closesock();
  869. char msg[1024];
  870. sprintf(msg,"Target: %s, port = %d, Raised in: %s, line %d",tracename,(int)hostport,sanitizeSourceFile(__FILE__), __LINE__);
  871. IJSOCK_Exception *e = new SocketException(JSOCKERR_port_in_use,msg);
  872. throw e;
  873. }
  874. else {
  875. closesock();
  876. THROWJSOCKEXCEPTION(saverr);
  877. }
  878. }
  879. if (!connectionless() && listen_queue_size) {
  880. if (::listen(sock, listen_queue_size) != 0) {
  881. saverr = ERRNO();
  882. if (saverr==JSE_ADDRINUSE)
  883. goto ErrPortInUse;
  884. closesock();
  885. THROWJSOCKEXCEPTION(saverr);
  886. }
  887. }
  888. if (mcastreq) {
  889. if (setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP,(char*)mcastreq, sizeof(*mcastreq))!=0) {
  890. saverr = ERRNO();
  891. closesock();
  892. THROWJSOCKEXCEPTION(saverr);
  893. }
  894. }
  895. state = ss_open;
  896. #ifdef SOCKTRACE
  897. PROGLOG("SOCKTRACE: opened socket return");
  898. #endif
  899. set_inherit(false);
  900. }
  901. ISocket* CSocket::accept(bool allowcancel, SocketEndpoint *peerEp)
  902. {
  903. if ((accept_cancel_state!=accept_not_cancelled) && allowcancel) {
  904. accept_cancel_state=accept_cancelled;
  905. return NULL;
  906. }
  907. if (state != ss_open) {
  908. IERRLOG("invalid accept, state = %d",(int)state);
  909. THROWJSOCKEXCEPTION(JSOCKERR_not_opened);
  910. }
  911. if (connectionless()) {
  912. THROWJSOCKEXCEPTION(JSOCKERR_connectionless_socket);
  913. }
  914. DEFINE_SOCKADDR(peerSockAddr); // used if peerIp
  915. socklen_t peerSockAddrLen = sizeof(peerSockAddr);
  916. T_SOCKET newsock;
  917. for (;;) {
  918. in_accept = true;
  919. newsock = (sock!=INVALID_SOCKET)?::accept(sock, &peerSockAddr.sa, &peerSockAddrLen):INVALID_SOCKET;
  920. in_accept = false;
  921. #ifdef SOCKTRACE
  922. PROGLOG("SOCKTRACE: accept created socket %x %d (%p)", newsock,newsock,this);
  923. #endif
  924. if (newsock!=INVALID_SOCKET) {
  925. if ((sock==INVALID_SOCKET)||(accept_cancel_state==accept_cancel_pending)) {
  926. ::close(newsock);
  927. newsock=INVALID_SOCKET;
  928. }
  929. else {
  930. accept_cancel_state = accept_not_cancelled;
  931. break;
  932. }
  933. }
  934. int saverr;
  935. saverr = ERRNO();
  936. if ((sock==INVALID_SOCKET)||(accept_cancel_state==accept_cancel_pending)) {
  937. accept_cancel_state = accept_cancelled;
  938. if (allowcancel)
  939. return NULL;
  940. THROWJSOCKEXCEPTION(JSOCKERR_cancel_accept);
  941. }
  942. if (saverr != JSE_INTR) {
  943. accept_cancel_state = accept_not_cancelled;
  944. THROWJSOCKEXCEPTION(saverr);
  945. }
  946. }
  947. if (state != ss_open) {
  948. accept_cancel_state = accept_cancelled;
  949. if (allowcancel)
  950. return NULL;
  951. THROWJSOCKEXCEPTION(JSOCKERR_cancel_accept);
  952. }
  953. if (peerEp)
  954. getSockAddrEndpoint(peerSockAddr, peerSockAddrLen, *peerEp);
  955. CSocket *ret = new CSocket(newsock,sm_tcp,true);
  956. ret->set_inherit(false);
  957. return ret;
  958. }
  959. void CSocket::set_linger(int lingertime)
  960. {
  961. struct linger l;
  962. l.l_onoff = (lingertime>=0)?1:0;
  963. l.l_linger = (lingertime>=0)?lingertime:0;
  964. if (setsockopt(sock, SOL_SOCKET, SO_LINGER, (char*)&l, sizeof(l)) != 0) {
  965. IWARNLOG("Linger not set");
  966. }
  967. }
  968. void CSocket::set_keep_alive(bool set)
  969. {
  970. int on=set?1:0;
  971. if (setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (char*)&on, sizeof(on)) != 0) {
  972. IWARNLOG("KeepAlive not set");
  973. }
  974. }
  975. int CSocket::name(char *retname,size32_t namemax)
  976. {
  977. SocketEndpoint ep;
  978. getEndpoint(ep);
  979. if (retname && namemax)
  980. {
  981. StringBuffer s;
  982. ep.getIpText(s);
  983. if (namemax-1<s.length())
  984. s.setLength(namemax-1);
  985. memcpy(retname,s.str(),s.length()+1);
  986. }
  987. return ep.port;
  988. }
  989. int CSocket::peer_name(char *retname,size32_t namemax)
  990. {
  991. // should not raise exceptions
  992. int ret = 0;
  993. if (!retname)
  994. namemax = 0;
  995. if (namemax)
  996. retname[0] = 0;
  997. if (state != ss_open) {
  998. return -1; // don't log as used to test socket
  999. }
  1000. StringBuffer s;
  1001. if (sockmode==sm_udp_server) { // udp server
  1002. returnep.getIpText(s);
  1003. ret = returnep.port;
  1004. }
  1005. else {
  1006. DEFINE_SOCKADDR(u);
  1007. socklen_t ul = sizeof(u);
  1008. if (::getpeername(sock,&u.sa, &ul)<0)
  1009. return -1; // don't log as used to test socket
  1010. SocketEndpoint ep;
  1011. getSockAddrEndpoint(u,ul,ep);
  1012. ep.getIpText(s);
  1013. ret = ep.port;
  1014. }
  1015. if (namemax>1) {
  1016. if (namemax-1<s.length())
  1017. s.setLength(namemax-1);
  1018. memcpy(retname,s.str(),s.length()+1);
  1019. }
  1020. return ret;
  1021. }
  1022. SocketEndpoint &CSocket::getPeerEndpoint(SocketEndpoint &ep)
  1023. {
  1024. if (state != ss_open) {
  1025. THROWJSOCKEXCEPTION(JSOCKERR_not_opened);
  1026. }
  1027. StringBuffer s;
  1028. if (sockmode==sm_udp_server) { // udp server
  1029. ep.set(returnep);
  1030. }
  1031. else {
  1032. DEFINE_SOCKADDR(u);
  1033. socklen_t ul = sizeof(u);
  1034. if (::getpeername(sock,&u.sa, &ul)<0) {
  1035. DBGLOG("getpeername failed %d",ERRNO());
  1036. ep.set(NULL, 0);
  1037. }
  1038. else
  1039. getSockAddrEndpoint(u,ul,ep);
  1040. }
  1041. return ep;
  1042. }
  1043. IpAddress & CSocket::getPeerAddress(IpAddress &addr)
  1044. {
  1045. SocketEndpoint ep;
  1046. getPeerEndpoint(ep);
  1047. addr = ep;
  1048. return addr;
  1049. }
  1050. void CSocket::set_return_addr(int port,const char *retname)
  1051. {
  1052. if (!returnep.ipset(retname)) {
  1053. IJSOCK_Exception *e = new SocketException(JSOCKERR_bad_address); // don't use THROWJSOCKEXCEPTION here
  1054. throw e;
  1055. }
  1056. returnep.port = port;
  1057. }
  1058. SocketEndpoint &CSocket::getEndpoint(SocketEndpoint &ep) const
  1059. {
  1060. if (state != ss_open) {
  1061. THROWJSOCKEXCEPTION(JSOCKERR_not_opened);
  1062. }
  1063. DEFINE_SOCKADDR(u);
  1064. socklen_t ul = sizeof(u);
  1065. if (::getsockname(sock,&u.sa, &ul)<0) {
  1066. THROWJSOCKEXCEPTION(ERRNO());
  1067. }
  1068. getSockAddrEndpoint(u,ul,ep);
  1069. return ep;
  1070. }
  1071. void CSocket::cancel_accept()
  1072. {
  1073. if (connectionless()) {
  1074. THROWJSOCKEXCEPTION(JSOCKERR_connectionless_socket);
  1075. }
  1076. #ifdef SOCKTRACE
  1077. PROGLOG("SOCKTRACE: Cancel accept socket %x %d (%p)", sock, sock, this);
  1078. #endif
  1079. if (!in_accept) {
  1080. accept_cancel_state = accept_cancelled;
  1081. shutdown();
  1082. errclose();
  1083. return;
  1084. }
  1085. accept_cancel_state = accept_cancel_pending;
  1086. errclose(); // this should cause accept to terminate (not supported on all linux though)
  1087. #ifdef _WIN32
  1088. for (unsigned i=0;i<5;i++) { // windows closes on different lower priority thread
  1089. Sleep(i);
  1090. if (accept_cancel_state==accept_cancelled)
  1091. return;
  1092. }
  1093. #else
  1094. Sleep(0);
  1095. if (accept_cancel_state==accept_cancelled)
  1096. return;
  1097. #endif
  1098. // Wakeup listener using a connection
  1099. SocketEndpoint ep(hostport,queryHostIP());
  1100. Owned<CSocket> sock = new CSocket(ep,sm_tcp,NULL);
  1101. try {
  1102. sock->connect_timeout(100,true);
  1103. }
  1104. catch (IJSOCK_Exception *e) {
  1105. EXCLOG(e,"CSocket::cancel_eccept");
  1106. e->Release();
  1107. }
  1108. }
  1109. // ================================================================================
  1110. // connect versions
  1111. ISocket* ISocket::connect( const SocketEndpoint &ep )
  1112. {
  1113. // general connect
  1114. return ISocket::connect_wait(ep,DEFAULT_CONNECT_TIME);
  1115. }
  1116. inline void refused_sleep(CTimeMon &tm, unsigned &refuseddelay)
  1117. {
  1118. unsigned remaining;
  1119. if (!tm.timedout(&remaining)) {
  1120. if (refuseddelay<remaining/4) {
  1121. Sleep(refuseddelay);
  1122. if (refuseddelay<CONNECT_TIMEOUT_REFUSED_WAIT/2)
  1123. refuseddelay *=2;
  1124. else
  1125. refuseddelay = CONNECT_TIMEOUT_REFUSED_WAIT;
  1126. }
  1127. else
  1128. Sleep(remaining/4); // towards end of timeout approach gradually
  1129. }
  1130. }
  1131. bool CSocket::connect_timeout( unsigned timeout, bool noexception)
  1132. {
  1133. // simple connect with timeout (no fancy stuff!)
  1134. unsigned startt = usTick();
  1135. CTimeMon tm(timeout);
  1136. unsigned remaining;
  1137. unsigned refuseddelay = 1;
  1138. int err;
  1139. while (!tm.timedout(&remaining))
  1140. {
  1141. err = pre_connect(false);
  1142. if ((err == JSE_INPROGRESS)||(err == JSE_WOULDBLOCK))
  1143. {
  1144. #ifdef _USE_SELECT
  1145. T_FD_SET fds;
  1146. struct timeval tv;
  1147. CHECKSOCKRANGE(sock);
  1148. XFD_ZERO(&fds);
  1149. FD_SET((unsigned)sock, &fds);
  1150. T_FD_SET except;
  1151. XFD_ZERO(&except);
  1152. FD_SET((unsigned)sock, &except);
  1153. tv.tv_sec = remaining / 1000;
  1154. tv.tv_usec = (remaining % 1000)*1000;
  1155. int rc = ::select( sock + 1, NULL, (fd_set *)&fds, (fd_set *)&except, &tv );
  1156. #else
  1157. struct pollfd fds[1];
  1158. fds[0].fd = sock;
  1159. fds[0].events = POLLOUT;
  1160. fds[0].revents = 0;
  1161. int rc = ::poll(fds, 1, remaining);
  1162. #endif
  1163. if (rc>0)
  1164. {
  1165. // select/poll succeeded - return error from socket (0 if connected)
  1166. socklen_t errlen = sizeof(err);
  1167. rc = getsockopt(sock, SOL_SOCKET, SO_ERROR, (char *)&err, &errlen); // check for error
  1168. if ((rc!=0)&&!err)
  1169. err = ERRNO(); // some implementations of getsockopt duff
  1170. if (err) // probably ECONNREFUSED but treat all errors same
  1171. refused_sleep(tm,refuseddelay);
  1172. }
  1173. else if (rc<0)
  1174. {
  1175. err = ERRNO();
  1176. if (err != JSE_INTR)
  1177. {
  1178. LOGERR2(err,2,"::select/poll");
  1179. errclose();
  1180. break;
  1181. }
  1182. }
  1183. }
  1184. else if (err)
  1185. refused_sleep(tm, refuseddelay); // this stops becoming cpu bound
  1186. if (err==0)
  1187. {
  1188. err = post_connect();
  1189. if (err==0)
  1190. {
  1191. STATS.connects++;
  1192. STATS.connecttime+=usTick()-startt;
  1193. #ifdef _TRACE
  1194. setTraceName();
  1195. #endif
  1196. #ifdef SOCKTRACE
  1197. unsigned conn_mstime = (usTick() - startt) / 1000;
  1198. logConnectionInfo(timeout, conn_mstime);
  1199. #endif
  1200. return true;
  1201. }
  1202. }
  1203. errclose();
  1204. }
  1205. #ifdef SOCKTRACE
  1206. PROGLOG("connect_timeout: failed %d",err);
  1207. #endif
  1208. STATS.failedconnects++;
  1209. STATS.failedconnecttime+=usTick()-startt;
  1210. if (!noexception)
  1211. THROWJSOCKEXCEPTION(JSOCKERR_connection_failed);
  1212. return false;
  1213. }
  1214. ISocket* ISocket::connect_timeout(const SocketEndpoint &ep,unsigned timeout)
  1215. {
  1216. if (ep.isNull()||(ep.port==0))
  1217. THROWJSOCKEXCEPTION2(JSOCKERR_bad_address);
  1218. Owned<CSocket> sock = new CSocket(ep,sm_tcp,NULL);
  1219. sock->connect_timeout(timeout,false);
  1220. return sock.getClear();
  1221. }
  1222. #define POLLTIME 50
  1223. void CSocket::connect_wait(unsigned timems)
  1224. {
  1225. // simple connect with timeout (no fancy stuff!)
  1226. unsigned startt = usTick();
  1227. CTimeMon tm(timems);
  1228. bool exit = false;
  1229. int err;
  1230. unsigned refuseddelay = 1;
  1231. while (!exit) {
  1232. #ifdef CENTRAL_NODE_RANDOM_DELAY
  1233. ForEachItemIn(cn,CentralNodeArray) {
  1234. const SocketEndpoint &ep=CentralNodeArray.item(cn);
  1235. if (ep.ipequals(targetip)) {
  1236. unsigned sleeptime = getRandom() % 1000;
  1237. StringBuffer s;
  1238. ep.getIpText(s);
  1239. DBGLOG("Connection to central node %s - sleeping %d milliseconds", s.str(), sleeptime);
  1240. Sleep(sleeptime);
  1241. break;
  1242. }
  1243. }
  1244. #endif
  1245. unsigned remaining;
  1246. exit = tm.timedout(&remaining);
  1247. bool blockselect = exit; // if last time round block
  1248. {
  1249. CriticalBlock block(crit);
  1250. if (++connectingcount>4)
  1251. blockselect = true;
  1252. }
  1253. err = pre_connect(blockselect);
  1254. if (blockselect)
  1255. {
  1256. if (err&&!exit)
  1257. refused_sleep(tm,refuseddelay); // probably ECONNREFUSED but treat all errors same
  1258. }
  1259. else
  1260. {
  1261. unsigned timeoutms = (exit||(remaining<10000))?10000:remaining;
  1262. #ifndef BLOCK_POLLED_SINGLE_CONNECTS
  1263. unsigned polltime = 1;
  1264. #endif
  1265. while (!blockselect && ((err == JSE_INPROGRESS)||(err == JSE_WOULDBLOCK)))
  1266. {
  1267. #ifdef _USE_SELECT
  1268. T_FD_SET fds;
  1269. struct timeval tv;
  1270. CHECKSOCKRANGE(sock);
  1271. XFD_ZERO(&fds);
  1272. FD_SET((unsigned)sock, &fds);
  1273. T_FD_SET except;
  1274. XFD_ZERO(&except);
  1275. FD_SET((unsigned)sock, &except);
  1276. #ifdef BLOCK_POLLED_SINGLE_CONNECTS
  1277. tv.tv_sec = timeoutms / 1000;
  1278. tv.tv_usec = (timeoutms % 1000)*1000;
  1279. #else
  1280. tv.tv_sec = 0;
  1281. tv.tv_usec = 0;
  1282. #endif
  1283. int rc = ::select( sock + 1, NULL, (fd_set *)&fds, (fd_set *)&except, &tv );
  1284. #else
  1285. struct pollfd fds[1];
  1286. fds[0].fd = sock;
  1287. fds[0].events = POLLOUT;
  1288. fds[0].revents = 0;
  1289. #ifdef BLOCK_POLLED_SINGLE_CONNECTS
  1290. int pollTimeOut = timeoutms;
  1291. #else
  1292. int pollTimeOut = 0;
  1293. #endif
  1294. int rc = ::poll(fds, 1, pollTimeOut);
  1295. #endif
  1296. if (rc>0)
  1297. {
  1298. // select/poll succeeded - return error from socket (0 if connected)
  1299. socklen_t errlen = sizeof(err);
  1300. rc = getsockopt(sock, SOL_SOCKET, SO_ERROR, (char *)&err, &errlen); // check for error
  1301. if ((rc!=0)&&!err)
  1302. err = ERRNO(); // some implementations of getsockopt duff
  1303. if (err)
  1304. refused_sleep(tm,refuseddelay); // probably ECONNREFUSED but treat all errors same
  1305. break;
  1306. }
  1307. if (rc<0)
  1308. {
  1309. err = ERRNO();
  1310. if (err != JSE_INTR)
  1311. {
  1312. LOGERR2(err,2,"::select/poll");
  1313. break;
  1314. }
  1315. }
  1316. if (!timeoutms)
  1317. {
  1318. #ifdef SOCKTRACE
  1319. PROGLOG("connecttimeout: timed out");
  1320. #endif
  1321. err = -1;
  1322. break;
  1323. }
  1324. #ifdef BLOCK_POLLED_SINGLE_CONNECTS
  1325. break;
  1326. #else
  1327. if (timeoutms<polltime)
  1328. polltime = timeoutms;
  1329. Sleep(polltime); // sleeps 1-50ms (to let other threads run)
  1330. timeoutms -= polltime;
  1331. if (polltime>POLLTIME/2)
  1332. polltime = POLLTIME;
  1333. else
  1334. polltime *= 2;
  1335. #endif
  1336. }
  1337. }
  1338. {
  1339. CriticalBlock block(crit);
  1340. --connectingcount;
  1341. }
  1342. if (err==0)
  1343. {
  1344. err = post_connect();
  1345. if (err==0)
  1346. {
  1347. STATS.connects++;
  1348. STATS.connecttime+=usTick()-startt;
  1349. #ifdef _TRACE
  1350. setTraceName();
  1351. #endif
  1352. #ifdef SOCKTRACE
  1353. unsigned conn_mstime = (usTick() - startt) / 1000;
  1354. logConnectionInfo(timems, conn_mstime);
  1355. #endif
  1356. return;
  1357. }
  1358. }
  1359. errclose();
  1360. }
  1361. #ifdef SOCKTRACE
  1362. PROGLOG("connect_wait: failed %d",err);
  1363. #endif
  1364. STATS.failedconnects++;
  1365. STATS.failedconnecttime+=usTick()-startt;
  1366. THROWJSOCKEXCEPTION(JSOCKERR_connection_failed);
  1367. }
  1368. void CSocket::setTraceName(const char * prefix, const char * name)
  1369. {
  1370. #ifdef _TRACE
  1371. StringBuffer peer;
  1372. peer.append(prefix);
  1373. if (state == ss_open)
  1374. peer.append(":").append(localPort).append(" -> ");
  1375. peer.append(name?name:"(NULL)");
  1376. peer.append(":").append(hostport);
  1377. if (sock != INVALID_SOCKET)
  1378. peer.append(" (").append(sock).append(")");
  1379. free(tracename);
  1380. tracename = peer.detach();
  1381. #endif
  1382. }
  1383. void CSocket::setTraceName()
  1384. {
  1385. #ifdef _TRACE
  1386. setTraceName("C!", hostname);
  1387. #endif
  1388. }
  1389. ISocket* ISocket::connect_wait( const SocketEndpoint &ep, unsigned timems)
  1390. {
  1391. if (ep.isNull()||(ep.port==0))
  1392. THROWJSOCKEXCEPTION2(JSOCKERR_bad_address);
  1393. Owned<CSocket> sock = new CSocket(ep,sm_tcp,NULL);
  1394. sock->connect_wait(timems);
  1395. return sock.getClear();
  1396. }
  1397. void CSocket::udpconnect()
  1398. {
  1399. DEFINE_SOCKADDR(u);
  1400. if (targetip.isNull()) {
  1401. set_return_addr(hostport,hostname);
  1402. targetip.ipset(returnep);
  1403. }
  1404. socklen_t ul = setSockAddr(u,targetip,hostport);
  1405. sock = ::socket(u.sa.sa_family, SOCK_DGRAM, targetip.isIp4()?0:PF_INET6);
  1406. #ifdef SOCKTRACE
  1407. PROGLOG("SOCKTRACE: udp connected socket %x %d (%p)", sock, sock, this);
  1408. #endif
  1409. STATS.activesockets++;
  1410. if (sock == INVALID_SOCKET) {
  1411. THROWJSOCKEXCEPTION(ERRNO());
  1412. }
  1413. int res = ::connect(sock, &u.sa, ul);
  1414. if (res != 0) { // works for UDP
  1415. closesock();
  1416. THROWJSOCKEXCEPTION(JSOCKERR_connection_failed);
  1417. }
  1418. nagling = false; // means nothing for UDP
  1419. state = ss_open;
  1420. #ifdef _TRACE
  1421. setTraceName();
  1422. #endif
  1423. }
  1424. int CSocket::logPollError(unsigned revents, const char *rwstr)
  1425. {
  1426. // return appropriate errno as caller will probably throw/log it
  1427. int retcode = EINVAL;
  1428. if (revents & POLLERR)
  1429. {
  1430. StringBuffer errStr;
  1431. errStr.appendf("%s POLLERR %u l:%d r:%s:%d", rwstr, sock, localPort, (hostname?hostname:"NULL"), hostport);
  1432. int serror = 0;
  1433. socklen_t serrlen = sizeof(serror);
  1434. int srtn = getsockopt(sock, SOL_SOCKET, SO_ERROR, (char *)&serror, &serrlen);
  1435. if (srtn != 0)
  1436. serror = ERRNO();
  1437. LOGERR2(serror,2,errStr.str());
  1438. retcode = serror;
  1439. }
  1440. else if (revents & POLLNVAL)
  1441. {
  1442. StringBuffer errStr;
  1443. errStr.appendf("%s POLLNVAL", rwstr);
  1444. LOGERR2(999,3,errStr.str());
  1445. }
  1446. else
  1447. {
  1448. StringBuffer errStr;
  1449. errStr.appendf("%s unknown poll() revents: 0x%x", rwstr, revents);
  1450. LOGERR2(999,4,errStr.str());
  1451. }
  1452. return retcode;
  1453. }
  1454. int CSocket::wait_read(unsigned timeout)
  1455. {
  1456. int ret = 0;
  1457. while (sock!=INVALID_SOCKET)
  1458. {
  1459. #ifdef _USE_SELECT
  1460. T_FD_SET fds;
  1461. CHECKSOCKRANGE(sock);
  1462. XFD_ZERO(&fds);
  1463. FD_SET((unsigned)sock, &fds);
  1464. if (timeout==WAIT_FOREVER)
  1465. {
  1466. ret = ::select( sock + 1, (fd_set *)&fds, NULL, NULL, NULL );
  1467. }
  1468. else
  1469. {
  1470. struct timeval tv;
  1471. tv.tv_sec = timeout / 1000;
  1472. tv.tv_usec = (timeout % 1000)*1000;
  1473. ret = ::select( sock + 1, (fd_set *)&fds, NULL, NULL, &tv );
  1474. }
  1475. #else
  1476. struct pollfd fds[1];
  1477. fds[0].fd = sock;
  1478. fds[0].events = POLLINX;
  1479. fds[0].revents = 0;
  1480. ret = ::poll(fds, 1, timeout);
  1481. #endif
  1482. if (ret == SOCKET_ERROR)
  1483. { // error
  1484. int err = ERRNO();
  1485. if (err!=JSE_INTR)
  1486. { // else retry (should adjust time but for our usage don't think it matters that much)
  1487. LOGERR2(err,1,"wait_read");
  1488. break;
  1489. }
  1490. }
  1491. else if (ret == 0)
  1492. { // timeout
  1493. break;
  1494. }
  1495. else
  1496. { // ret > 0 - ready or error
  1497. // if returning < 0 also set errno as caller will probably throw/log it
  1498. #ifdef _USE_SELECT
  1499. if (!FD_ISSET(sock, &fds))
  1500. {
  1501. LOGERR2(998,7,"wait_read");
  1502. errno = EBADF;
  1503. ret = -1;
  1504. }
  1505. #else
  1506. if ( (fds[0].revents & (POLLERR | POLLNVAL)) || (!(fds[0].revents & (POLLINX | POLLHUP))) )
  1507. {
  1508. errno = logPollError(fds[0].revents, "wait_read");
  1509. ret = -1;
  1510. }
  1511. else
  1512. {
  1513. // cannot error out on POLLRDHUP or POLLHUP as there can still be data to read
  1514. // POLLIN | POLLRDHUP | POLLHUP ok
  1515. break;
  1516. }
  1517. #endif
  1518. break;
  1519. }
  1520. }
  1521. return ret;
  1522. }
  1523. int CSocket::wait_write(unsigned timeout)
  1524. {
  1525. int ret = 0;
  1526. while (sock!=INVALID_SOCKET) {
  1527. #ifdef _USE_SELECT
  1528. T_FD_SET fds;
  1529. CHECKSOCKRANGE(sock);
  1530. XFD_ZERO(&fds);
  1531. FD_SET((unsigned)sock, &fds);
  1532. if (timeout==WAIT_FOREVER) {
  1533. ret = ::select( sock + 1, NULL, (fd_set *)&fds, NULL, NULL );
  1534. }
  1535. else {
  1536. struct timeval tv;
  1537. tv.tv_sec = timeout / 1000;
  1538. tv.tv_usec = (timeout % 1000)*1000;
  1539. ret = ::select( sock + 1, NULL, (fd_set *)&fds, NULL, &tv );
  1540. }
  1541. #else
  1542. struct pollfd fds[1];
  1543. fds[0].fd = sock;
  1544. fds[0].events = POLLOUT;
  1545. fds[0].revents = 0;
  1546. ret = ::poll(fds, 1, timeout);
  1547. #endif
  1548. if (ret==SOCKET_ERROR)
  1549. {
  1550. int err = ERRNO();
  1551. if (err!=JSE_INTR)
  1552. { // else retry (should adjust time but for our usage don't think it matters that much)
  1553. LOGERR2(err,1,"wait_write");
  1554. break;
  1555. }
  1556. }
  1557. else if (ret == 0)
  1558. { // timeout
  1559. break;
  1560. }
  1561. else
  1562. { // ret > 0 - ready or error
  1563. // if returning < 0 also set errno as caller will probably throw/log it
  1564. #ifdef _USE_SELECT
  1565. if (!FD_ISSET(sock, &fds))
  1566. {
  1567. LOGERR2(998,7,"wait_write");
  1568. errno = EBADF;
  1569. ret = -1;
  1570. }
  1571. #else
  1572. if ( (fds[0].revents & (POLLERR | POLLNVAL)) || (!(fds[0].revents & (POLLOUT | POLLHUP))) )
  1573. {
  1574. errno = logPollError(fds[0].revents, "wait_write");
  1575. ret = -1;
  1576. }
  1577. else if (fds[0].revents & POLLHUP)
  1578. {
  1579. LOGERR2(998,5,"wait_write POLLHUP");
  1580. errno = EPIPE;
  1581. ret = -1;
  1582. }
  1583. else
  1584. {
  1585. // POLLOUT ok
  1586. break;
  1587. }
  1588. #endif
  1589. break;
  1590. }
  1591. }
  1592. return ret;
  1593. }
  1594. void CSocket::readtms(void* buf, size32_t min_size, size32_t max_size, size32_t &size_read,
  1595. unsigned timeoutms)
  1596. {
  1597. if (timeoutms == WAIT_FOREVER) {
  1598. read(buf,min_size, max_size, size_read,WAIT_FOREVER);
  1599. return;
  1600. }
  1601. unsigned startt=usTick();
  1602. size_read = 0;
  1603. if (state != ss_open) {
  1604. THROWJSOCKEXCEPTION(JSOCKERR_not_opened);
  1605. }
  1606. unsigned start;
  1607. unsigned timeleft;
  1608. start = msTick();
  1609. timeleft = timeoutms;
  1610. do {
  1611. int rc = wait_read(timeleft);
  1612. if (rc < 0) {
  1613. THROWJSOCKEXCEPTION(ERRNO());
  1614. }
  1615. if (rc == 0) {
  1616. THROWJSOCKEXCEPTION(JSOCKERR_timeout_expired);
  1617. }
  1618. unsigned elapsed = (msTick()-start);
  1619. if (elapsed<timeoutms)
  1620. timeleft = timeoutms-elapsed;
  1621. else
  1622. timeleft = 0;
  1623. unsigned retrycount=100;
  1624. EintrRetry:
  1625. if (sockmode==sm_udp_server) { // udp server
  1626. DEFINE_SOCKADDR(u);
  1627. socklen_t ul=sizeof(u);
  1628. rc = recvfrom(sock, (char*)buf + size_read, max_size - size_read, 0, &u.sa,&ul);
  1629. getSockAddrEndpoint(u,ul,returnep);
  1630. }
  1631. else {
  1632. rc = recv(sock, (char*)buf + size_read, max_size - size_read, 0);
  1633. }
  1634. if (rc < 0) {
  1635. int err = ERRNO();
  1636. if (BADSOCKERR(err)) {
  1637. // don't think this should happen but convert to same as shutdown while investigation
  1638. LOGERR2(err,1,"Socket closed during read");
  1639. rc = 0;
  1640. }
  1641. else if ((err==JSE_INTR)&&(retrycount--!=0)) {
  1642. LOGERR2(err,1,"EINTR retrying");
  1643. goto EintrRetry;
  1644. }
  1645. else {
  1646. VStringBuffer errMsg("readtms(timeoutms=%d)", timeoutms);
  1647. LOGERR2(err,1,errMsg.str());
  1648. if ((err==JSE_CONNRESET)||(err==JSE_INTR)||(err==JSE_CONNABORTED)) {
  1649. errclose();
  1650. err = JSOCKERR_broken_pipe;
  1651. }
  1652. THROWJSOCKEXCEPTION(err);
  1653. }
  1654. }
  1655. if (rc == 0) {
  1656. state = ss_shutdown;
  1657. if (min_size==0)
  1658. break; // if min_read is 0 return 0 if socket closed
  1659. THROWJSOCKEXCEPTION(JSOCKERR_graceful_close);
  1660. }
  1661. size_read += rc;
  1662. } while (size_read < min_size);
  1663. STATS.reads++;
  1664. STATS.readsize += size_read;
  1665. STATS.readtime+=usTick()-startt;
  1666. }
  1667. void CSocket::read(void* buf, size32_t min_size, size32_t max_size, size32_t &size_read,
  1668. unsigned timeoutsecs)
  1669. {
  1670. unsigned startt=usTick();
  1671. size_read = 0;
  1672. unsigned start = 0;
  1673. unsigned timeleft = 0;
  1674. if (state != ss_open) {
  1675. THROWJSOCKEXCEPTION(JSOCKERR_not_opened);
  1676. }
  1677. if (timeoutsecs != WAIT_FOREVER) {
  1678. start = (unsigned)time(NULL);
  1679. timeleft = timeoutsecs;
  1680. }
  1681. do {
  1682. int rc;
  1683. if (timeoutsecs != WAIT_FOREVER) {
  1684. rc = wait_read(timeleft*1000);
  1685. if (rc < 0) {
  1686. THROWJSOCKEXCEPTION(ERRNO());
  1687. }
  1688. if (rc == 0) {
  1689. THROWJSOCKEXCEPTION(JSOCKERR_timeout_expired);
  1690. }
  1691. unsigned elapsed = ((unsigned)time(NULL))-start;
  1692. if (elapsed<timeoutsecs)
  1693. timeleft = timeoutsecs-elapsed;
  1694. else
  1695. timeleft = 0;
  1696. }
  1697. unsigned retrycount=100;
  1698. EintrRetry:
  1699. if (sockmode==sm_udp_server) { // udp server
  1700. DEFINE_SOCKADDR(u);
  1701. socklen_t ul=sizeof(u.sin);
  1702. rc = recvfrom(sock, (char*)buf + size_read, max_size - size_read, 0, &u.sa,&ul);
  1703. getSockAddrEndpoint(u,ul,returnep);
  1704. }
  1705. else {
  1706. rc = recv(sock, (char*)buf + size_read, max_size - size_read, 0);
  1707. }
  1708. if (rc < 0) {
  1709. int err = ERRNO();
  1710. if (BADSOCKERR(err)) {
  1711. // don't think this should happen but convert to same as shutdown while investigation
  1712. LOGERR2(err,3,"Socket closed during read");
  1713. rc = 0;
  1714. }
  1715. else if ((err==JSE_INTR)&&(retrycount--!=0)) {
  1716. if (sock==INVALID_SOCKET)
  1717. rc = 0; // convert an EINTR after closed to a graceful close
  1718. else {
  1719. LOGERR2(err,3,"EINTR retrying");
  1720. goto EintrRetry;
  1721. }
  1722. }
  1723. else {
  1724. LOGERR2(err,3,"read");
  1725. if ((err==JSE_CONNRESET)||(err==JSE_INTR)||(err==JSE_CONNABORTED)) {
  1726. errclose();
  1727. err = JSOCKERR_broken_pipe;
  1728. }
  1729. THROWJSOCKEXCEPTION(err);
  1730. }
  1731. }
  1732. if (rc == 0) {
  1733. state = ss_shutdown;
  1734. if (min_size==0)
  1735. break; // if min_read is 0 return 0 if socket closed
  1736. THROWJSOCKEXCEPTION(JSOCKERR_graceful_close);
  1737. }
  1738. size_read += rc;
  1739. } while (size_read < min_size);
  1740. STATS.reads++;
  1741. STATS.readsize += size_read;
  1742. STATS.readtime+=usTick()-startt;
  1743. }
  1744. void CSocket::read(void* buf, size32_t size)
  1745. {
  1746. if (!size)
  1747. return;
  1748. unsigned startt=usTick();
  1749. size32_t size_read=size;
  1750. if (state != ss_open) {
  1751. THROWJSOCKEXCEPTION(JSOCKERR_not_opened);
  1752. }
  1753. do {
  1754. unsigned retrycount=100;
  1755. EintrRetry:
  1756. int rc;
  1757. if (sockmode==sm_udp_server) { // udp server
  1758. DEFINE_SOCKADDR(u);
  1759. socklen_t ul=sizeof(u.sin);
  1760. rc = recvfrom(sock, (char*)buf, size, 0, &u.sa,&ul);
  1761. getSockAddrEndpoint(u,ul,returnep);
  1762. }
  1763. else {
  1764. rc = recv(sock, (char*)buf, size, 0);
  1765. }
  1766. if (rc < 0) {
  1767. int err = ERRNO();
  1768. if (BADSOCKERR(err)) {
  1769. // don't think this should happen but convert to same as shutdown while investigation
  1770. LOGERR2(err,5,"Socket closed during read");
  1771. rc = 0;
  1772. }
  1773. else if ((err==JSE_INTR)&&(retrycount--!=0)) {
  1774. LOGERR2(err,5,"EINTR retrying");
  1775. goto EintrRetry;
  1776. }
  1777. else {
  1778. LOGERR2(err,5,"read");
  1779. if ((err==JSE_CONNRESET)||(err==JSE_INTR)||(err==JSE_CONNABORTED)) {
  1780. errclose();
  1781. err = JSOCKERR_broken_pipe;
  1782. }
  1783. THROWJSOCKEXCEPTION(err);
  1784. }
  1785. }
  1786. if (rc == 0) {
  1787. state = ss_shutdown;
  1788. THROWJSOCKEXCEPTION(JSOCKERR_graceful_close);
  1789. }
  1790. buf = (char*)buf + rc;
  1791. size -= rc;
  1792. } while (size != 0);
  1793. STATS.reads++;
  1794. STATS.readsize += size_read;
  1795. STATS.readtime+=usTick()-startt;
  1796. }
  1797. size32_t CSocket::write(void const* buf, size32_t size)
  1798. {
  1799. if (size==0)
  1800. return 0;
  1801. unsigned startt=usTick();
  1802. size32_t size_writ = size;
  1803. if (state != ss_open) {
  1804. THROWJSOCKEXCEPTION(JSOCKERR_not_opened);
  1805. }
  1806. size32_t res=0;
  1807. do {
  1808. unsigned retrycount=100;
  1809. EintrRetry:
  1810. int rc;
  1811. if (sockmode==sm_udp_server) { // udp server
  1812. DEFINE_SOCKADDR(u);
  1813. socklen_t ul = setSockAddr(u,returnep,returnep.port);
  1814. rc = sendto(sock, (char*)buf, size, 0, &u.sa, ul);
  1815. }
  1816. #ifdef SIMULATE_LOST_UDP_PACKETS
  1817. else if (sockmode==sm_udp && size <= 24 && dropCounter++ >= dropThreshold)
  1818. {
  1819. DBGLOG("Drop size %d cmd %d", size, *(unsigned short *)buf);
  1820. dropCounter = 0;
  1821. rc = size;
  1822. }
  1823. #endif
  1824. else {
  1825. rc = send(sock, (char*)buf, size, SEND_FLAGS);
  1826. }
  1827. if (rc < 0) {
  1828. int err=ERRNO();
  1829. if (BADSOCKERR(err)) {
  1830. LOGERR2(err,7,"Socket closed during write");
  1831. rc = 0;
  1832. }
  1833. else if ((err==JSE_INTR)&&(retrycount--!=0)) {
  1834. LOGERR2(err,7,"EINTR retrying");
  1835. goto EintrRetry;
  1836. }
  1837. else {
  1838. if (((sockmode==sm_multicast)||(sockmode==sm_udp))&&(err==JSE_CONNREFUSED))
  1839. break; // ignore
  1840. LOGERR2(err,7,"write");
  1841. if ((err==JSE_CONNRESET)||(err==JSE_INTR)||(err==JSE_CONNABORTED)
  1842. #ifndef _WIN32
  1843. ||(err==EPIPE)||(err==JSE_TIMEDOUT) // linux can raise these on broken pipe
  1844. #endif
  1845. ) {
  1846. errclose();
  1847. err = JSOCKERR_broken_pipe;
  1848. }
  1849. if ((err == JSE_WOULDBLOCK) && nonblocking)
  1850. break;
  1851. THROWJSOCKEXCEPTION(err);
  1852. }
  1853. }
  1854. res += rc;
  1855. if (rc == 0) {
  1856. state = ss_shutdown;
  1857. THROWJSOCKEXCEPTION(JSOCKERR_graceful_close);
  1858. }
  1859. if (nonblocking)
  1860. break;
  1861. buf = (char*)buf + rc;
  1862. size -= rc;
  1863. } while (size != 0);
  1864. STATS.writes++;
  1865. STATS.writesize += size_writ;
  1866. STATS.writetime+=usTick()-startt;
  1867. return res;
  1868. }
  1869. size32_t CSocket::writetms(void const* buf, size32_t size, unsigned timeoutms)
  1870. {
  1871. if (size==0)
  1872. return 0;
  1873. if (state != ss_open)
  1874. {
  1875. THROWJSOCKEXCEPTION(JSOCKERR_not_opened);
  1876. }
  1877. if (timeoutms == WAIT_FOREVER)
  1878. return write(buf, size);
  1879. const char *p = (const char *)buf;
  1880. unsigned start, elapsed;
  1881. start = msTick();
  1882. elapsed = 0;
  1883. size32_t nwritten = 0;
  1884. size32_t nleft = size;
  1885. unsigned rollover = 0;
  1886. bool prevblock = set_nonblock(true);
  1887. while ( (nwritten < size) && (elapsed <= timeoutms) )
  1888. {
  1889. size32_t amnt = write(p,nleft);
  1890. // can nonblock mode write() return -1 ?
  1891. if ( (amnt == 0) || (amnt == (size32_t)-1) )
  1892. {
  1893. if (++rollover >= 20)
  1894. {
  1895. rollover = 0;
  1896. Sleep(20);
  1897. }
  1898. }
  1899. else
  1900. {
  1901. nwritten += amnt;
  1902. nleft -= amnt;
  1903. p += amnt;
  1904. }
  1905. elapsed = msTick() - start;
  1906. }
  1907. set_nonblock(prevblock);
  1908. if (nwritten < size)
  1909. {
  1910. IERRLOG("writetms timed out; timeout: %u, nwritten: %u, size: %u", timeoutms, nwritten, size);
  1911. THROWJSOCKEXCEPTION(JSOCKERR_timeout_expired);
  1912. }
  1913. return nwritten;
  1914. }
  1915. bool CSocket::check_connection()
  1916. {
  1917. if (state != ss_open)
  1918. return false;
  1919. unsigned retrycount=100;
  1920. EintrRetry:
  1921. int rc;
  1922. if (sockmode==sm_udp_server) { // udp server
  1923. DEFINE_SOCKADDR(u);
  1924. socklen_t ul = setSockAddr(u,returnep,returnep.port);
  1925. rc = sendto(sock, NULL, 0, 0, &u.sa, ul);
  1926. }
  1927. else {
  1928. rc = send(sock, NULL, 0, SEND_FLAGS);
  1929. }
  1930. if (rc < 0) {
  1931. int err=ERRNO();
  1932. if ((err==JSE_INTR)&&(retrycount--!=0)) {
  1933. LOGERR2(err,7,"EINTR retrying");
  1934. goto EintrRetry;
  1935. }
  1936. else
  1937. return false;
  1938. }
  1939. return true;
  1940. }
  1941. size32_t CSocket::udp_write_to(const SocketEndpoint &ep, void const* buf, size32_t size)
  1942. {
  1943. if (size==0)
  1944. return 0;
  1945. unsigned startt=usTick();
  1946. if (state != ss_open) {
  1947. THROWJSOCKEXCEPTION(JSOCKERR_not_opened);
  1948. }
  1949. size32_t res=0;
  1950. DEFINE_SOCKADDR(u);
  1951. for (;;) {
  1952. socklen_t ul = setSockAddr(u,ep,ep.port);
  1953. int rc = sendto(sock, (char*)buf, size, 0, &u.sa, ul);
  1954. if (rc < 0) {
  1955. int err=ERRNO();
  1956. if (((sockmode==sm_multicast)||(sockmode==sm_udp))&&(err==JSE_CONNREFUSED))
  1957. break; // ignore
  1958. if (err!=JSE_INTR) {
  1959. THROWJSOCKEXCEPTION(err);
  1960. }
  1961. }
  1962. else {
  1963. res = (size32_t)rc;
  1964. break;
  1965. }
  1966. }
  1967. STATS.writes++;
  1968. STATS.writesize += res;
  1969. STATS.writetime+=usTick()-startt;
  1970. return res;
  1971. }
  1972. size32_t CSocket::write_multiple(unsigned num,const void **buf, size32_t *size)
  1973. {
  1974. assertex(sockmode!=sm_udp_server);
  1975. assertex(!nonblocking);
  1976. if (num==1)
  1977. return write(buf[0],size[0]);
  1978. size32_t total = 0;
  1979. unsigned i;
  1980. for (i=0;i<num;i++)
  1981. total += size[i];
  1982. if (total==0)
  1983. return 0;
  1984. unsigned startt=usTick();
  1985. if (state != ss_open) {
  1986. THROWJSOCKEXCEPTION(JSOCKERR_not_opened);
  1987. }
  1988. size32_t res=0;
  1989. #ifdef _WIN32
  1990. WSABUF *bufs = (WSABUF *)alloca(sizeof(WSABUF)*num);
  1991. for (i=0;i<num;i++) {
  1992. bufs[i].buf = (char *)buf[i];
  1993. bufs[i].len = size[i];
  1994. }
  1995. unsigned retrycount=100;
  1996. EintrRetry:
  1997. DWORD sent;
  1998. if (WSASendTo(sock,bufs,num,&sent,0,NULL,0,NULL,NULL)==SOCKET_ERROR) {
  1999. int err=ERRNO();
  2000. if (BADSOCKERR(err)) {
  2001. LOGERR2(err,8,"Socket closed during write");
  2002. sent = 0;
  2003. }
  2004. else if ((err==JSE_INTR)&&(retrycount--!=0)) {
  2005. LOGERR2(err,8,"EINTR retrying");
  2006. goto EintrRetry;
  2007. }
  2008. else {
  2009. LOGERR2(err,8,"write_multiple");
  2010. if ((err==JSE_CONNRESET)||(err==JSE_INTR)||(err==JSE_CONNABORTED)||(err==JSE_TIMEDOUT)) {
  2011. errclose();
  2012. err = JSOCKERR_broken_pipe;
  2013. }
  2014. THROWJSOCKEXCEPTION(err);
  2015. }
  2016. }
  2017. if (sent == 0) {
  2018. state = ss_shutdown;
  2019. THROWJSOCKEXCEPTION(JSOCKERR_graceful_close);
  2020. }
  2021. res = sent;
  2022. #else
  2023. #ifdef USE_CORK
  2024. if (total>1024) {
  2025. class Copt
  2026. {
  2027. T_SOCKET sock;
  2028. bool nagling;
  2029. public:
  2030. Copt(T_SOCKET _sock,bool _nagling)
  2031. {
  2032. nagling = _nagling;
  2033. int enabled = 1;
  2034. int disabled = 0;
  2035. if (!nagling)
  2036. setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char*)&disabled, sizeof(disabled));
  2037. setsockopt(sock, IPPROTO_TCP, TCP_CORK, (char*)&enabled, sizeof(enabled));
  2038. }
  2039. ~Copt()
  2040. {
  2041. int enabled = 1;
  2042. int disabled = 0;
  2043. setsockopt(sock, IPPROTO_TCP, TCP_CORK, (char*)&disabled, sizeof(disabled));
  2044. if (!nagling)
  2045. setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char*)&enabled, sizeof(enabled));
  2046. }
  2047. } copt(sock,nagling);
  2048. for (i=0;i<num;i++)
  2049. res += write(buf[i],size[i]);
  2050. }
  2051. else {
  2052. byte b[1024];
  2053. byte *p=b;
  2054. for (i=0;i<num;i++) {
  2055. memcpy(p,buf[i],size[i]);
  2056. p += size[i];
  2057. }
  2058. res = write(b,total);
  2059. }
  2060. #else
  2061. // send in equal chunks about 64K
  2062. unsigned n = (total+0xffff)/0x10000;
  2063. size32_t outbufsize = (total+n-1)/n;
  2064. MemoryAttr ma;
  2065. byte *outbuf = (byte *)ma.allocate(outbufsize);
  2066. i = 0;
  2067. size32_t os = 0;
  2068. size32_t left = total;
  2069. byte *b = NULL;
  2070. size32_t s=0;
  2071. for (;;) {
  2072. while (!s&&(i<num)) {
  2073. b = (byte *)buf[i];
  2074. s = size[i];
  2075. i++;
  2076. }
  2077. if ((os==0)&&(s==left)) {
  2078. write(b,s); // go for it
  2079. break;
  2080. }
  2081. else {
  2082. size32_t cpy = outbufsize-os;
  2083. if (cpy>s)
  2084. cpy = s;
  2085. memcpy(outbuf+os,b,cpy);
  2086. os += cpy;
  2087. left -= cpy;
  2088. s -= cpy;
  2089. b += cpy;
  2090. if (left==0) {
  2091. write(outbuf,os);
  2092. break;
  2093. }
  2094. else if (os==outbufsize) {
  2095. write(outbuf,os);
  2096. os = 0;
  2097. }
  2098. }
  2099. }
  2100. #endif
  2101. #endif
  2102. STATS.writes++;
  2103. STATS.writesize += res;
  2104. STATS.writetime+=usTick()-startt;
  2105. return res;
  2106. }
  2107. bool CSocket::send_block(const void *blk,size32_t sz)
  2108. {
  2109. unsigned startt=usTick();
  2110. #ifdef TRACE_SLOW_BLOCK_TRANSFER
  2111. unsigned startt2 = startt;
  2112. unsigned startt3 = startt;
  2113. #endif
  2114. if (blockflags&BF_SYNC_TRANSFER_PULL) {
  2115. size32_t rd;
  2116. bool eof = true;
  2117. readtms(&eof,sizeof(eof),sizeof(eof),rd,blocktimeoutms);
  2118. if (eof)
  2119. return false;
  2120. #ifdef TRACE_SLOW_BLOCK_TRANSFER
  2121. startt2=usTick();
  2122. #endif
  2123. }
  2124. if (!blk||!sz) {
  2125. sz = 0;
  2126. write(&sz,sizeof(sz));
  2127. try {
  2128. bool reply;
  2129. size32_t rd;
  2130. readtms(&reply,sizeof(reply),sizeof(reply),rd,blocktimeoutms);
  2131. }
  2132. catch (IJSOCK_Exception *e) {
  2133. if ((e->errorCode()!=JSOCKERR_broken_pipe)&&(e->errorCode()!=JSOCKERR_graceful_close))
  2134. EXCLOG(e,"CSocket::send_block");
  2135. e->Release();
  2136. }
  2137. return false;
  2138. }
  2139. size32_t rsz=sz;
  2140. _WINREV(rsz);
  2141. write(&rsz,sizeof(rsz));
  2142. if (blockflags&BF_SYNC_TRANSFER_PUSH) {
  2143. #ifdef TRACE_SLOW_BLOCK_TRANSFER
  2144. startt2=usTick();
  2145. #endif
  2146. size32_t rd;
  2147. bool eof = true;
  2148. readtms(&eof,sizeof(eof),sizeof(eof),rd,blocktimeoutms);
  2149. if (eof)
  2150. return false;
  2151. #ifdef TRACE_SLOW_BLOCK_TRANSFER
  2152. startt3=usTick();
  2153. #endif
  2154. }
  2155. write(blk,sz);
  2156. if (blockflags&BF_RELIABLE_TRANSFER) {
  2157. bool isok=false;
  2158. size32_t rd;
  2159. readtms(&isok,sizeof(isok),sizeof(isok),rd,blocktimeoutms);
  2160. if (!isok)
  2161. return false;
  2162. }
  2163. unsigned nowt = usTick();
  2164. unsigned elapsed = nowt-startt;
  2165. STATS.blocksendtime+=elapsed;
  2166. STATS.numblocksends++;
  2167. STATS.blocksendsize+=sz;
  2168. if (elapsed>STATS.longestblocksend) {
  2169. STATS.longestblocksend = elapsed;
  2170. STATS.longestblocksize = sz;
  2171. }
  2172. #ifdef TRACE_SLOW_BLOCK_TRANSFER
  2173. if (elapsed>1000000*60) // over 1min
  2174. IWARNLOG("send_block took %ds to %s (%d,%d,%d)",elapsed/1000000,tracename,startt2-startt,startt3-startt2,nowt-startt3);
  2175. #endif
  2176. return true;
  2177. }
  2178. #ifdef USERECVSEM
  2179. class CSemProtect
  2180. {
  2181. Semaphore *sem;
  2182. bool *owned;
  2183. public:
  2184. CSemProtect() { clear(); }
  2185. ~CSemProtect()
  2186. {
  2187. if (sem&&*owned) {
  2188. *owned = false;
  2189. sem->signal();
  2190. }
  2191. }
  2192. void set(Semaphore *_sem,bool *_owned)
  2193. {
  2194. sem = _sem;
  2195. owned = _owned;
  2196. }
  2197. bool wait(Semaphore *_sem,bool *_owned,unsigned timeout) {
  2198. if (!*_owned&&!_sem->wait(timeout))
  2199. return false;
  2200. *_owned = true;
  2201. set(_sem,_owned);
  2202. return true;
  2203. }
  2204. void clear() { sem = NULL; owned = NULL; }
  2205. };
  2206. #endif
  2207. size32_t CSocket::receive_block_size()
  2208. {
  2209. // assumed always paired with receive_block
  2210. if (nextblocksize) {
  2211. if (blockflags&BF_SYNC_TRANSFER_PULL) {
  2212. bool eof=false;
  2213. write(&eof,sizeof(eof));
  2214. }
  2215. size32_t rd;
  2216. readtms(&nextblocksize,sizeof(nextblocksize),sizeof(nextblocksize),rd,blocktimeoutms);
  2217. _WINREV(nextblocksize);
  2218. if (nextblocksize==0) { // confirm eof
  2219. try {
  2220. bool confirm=true;
  2221. write(&confirm,sizeof(confirm));
  2222. }
  2223. catch (IJSOCK_Exception *e) {
  2224. if ((e->errorCode()!=JSOCKERR_broken_pipe)&&(e->errorCode()!=JSOCKERR_graceful_close))
  2225. EXCLOG(e,"receive_block_size");
  2226. e->Release();
  2227. }
  2228. }
  2229. else if (blockflags&BF_SYNC_TRANSFER_PUSH) { // leaves receiveblocksem clear
  2230. #ifdef USERECVSEM
  2231. CSemProtect semprot; // this will catch exception in write
  2232. while (!semprot.wait(&receiveblocksem,&receiveblocksemowned,60*1000*5))
  2233. IWARNLOG("Receive block stalled");
  2234. #endif
  2235. bool eof=false;
  2236. write(&eof,sizeof(eof));
  2237. #ifdef USERECVSEM
  2238. semprot.clear();
  2239. #endif
  2240. }
  2241. }
  2242. return nextblocksize;
  2243. }
  2244. size32_t CSocket::receive_block(void *blk,size32_t maxsize)
  2245. {
  2246. #ifdef USERECVSEM
  2247. CSemProtect semprot; // this will catch exceptions
  2248. #endif
  2249. size32_t sz = nextblocksize;
  2250. if (sz) {
  2251. if (sz==UINT_MAX) { // need to get size
  2252. if (!blk||!maxsize) {
  2253. if (blockflags&BF_SYNC_TRANSFER_PUSH) { // ignore block size
  2254. size32_t rd;
  2255. readtms(&nextblocksize,sizeof(nextblocksize),sizeof(nextblocksize),rd,blocktimeoutms);
  2256. }
  2257. if (blockflags&(BF_SYNC_TRANSFER_PULL|BF_SYNC_TRANSFER_PUSH)) { // signal eof
  2258. bool eof=true;
  2259. write(&eof,sizeof(eof));
  2260. nextblocksize = 0;
  2261. return 0;
  2262. }
  2263. }
  2264. sz = receive_block_size();
  2265. if (!sz)
  2266. return 0;
  2267. }
  2268. unsigned startt=usTick(); // include sem block but not initial handshake
  2269. #ifdef USERECVSEM
  2270. if (blockflags&BF_SYNC_TRANSFER_PUSH) // read_block_size sets semaphore
  2271. semprot.set(&receiveblocksem,&receiveblocksemowned); // this will reset semaphore on exit
  2272. #endif
  2273. nextblocksize = UINT_MAX;
  2274. size32_t rd;
  2275. if (sz<=maxsize) {
  2276. readtms(blk,sz,sz,rd,blocktimeoutms);
  2277. }
  2278. else { // truncate
  2279. readtms(blk,maxsize,maxsize,rd,blocktimeoutms);
  2280. sz -= maxsize;
  2281. void *tmp=malloc(sz);
  2282. readtms(tmp,sz,sz,rd,blocktimeoutms);
  2283. free(tmp);
  2284. sz = maxsize;
  2285. }
  2286. if (blockflags&BF_RELIABLE_TRANSFER) {
  2287. bool isok=true;
  2288. write(&isok,sizeof(isok));
  2289. }
  2290. unsigned elapsed = usTick()-startt;
  2291. STATS.blockrecvtime+=elapsed;
  2292. STATS.numblockrecvs++;
  2293. STATS.blockrecvsize+=sz;
  2294. }
  2295. return sz;
  2296. }
  2297. void CSocket::set_block_mode(unsigned flags, size32_t recsize, unsigned _timeoutms)
  2298. {
  2299. blockflags = flags;
  2300. nextblocksize = UINT_MAX;
  2301. blocktimeoutms = _timeoutms?_timeoutms:WAIT_FOREVER;
  2302. }
  2303. void CSocket::shutdown(unsigned mode)
  2304. {
  2305. if (state == ss_open) {
  2306. state = ss_shutdown;
  2307. #ifdef SOCKTRACE
  2308. PROGLOG("SOCKTRACE: shutdown(%d) socket %x %d (%p)", mode, sock, sock, this);
  2309. #endif
  2310. int rc = ::shutdown(sock, mode);
  2311. if (rc != 0) {
  2312. int err=ERRNO();
  2313. if (err==JSE_NOTCONN) {
  2314. #ifdef _TRACELINKCLOSED
  2315. DBGLOG("CSocket::shutdown(%d) failed, socket: %d", mode, sock);
  2316. #endif
  2317. LOGERR2(err,9,"shutdown");
  2318. err = JSOCKERR_broken_pipe;
  2319. }
  2320. THROWJSOCKEXCEPTION(err);
  2321. }
  2322. }
  2323. }
  2324. void CSocket::errclose()
  2325. {
  2326. #ifdef USERECVSEM
  2327. if (receiveblocksemowned) {
  2328. receiveblocksemowned = false;
  2329. receiveblocksem.signal();
  2330. }
  2331. #endif
  2332. if (state != ss_close) {
  2333. state = ss_close;
  2334. #ifdef SOCKTRACE
  2335. PROGLOG("SOCKTRACE: errclose socket %x %d (%p)", sock, sock, this);
  2336. #endif
  2337. if (mcastreq)
  2338. setsockopt(sock, IPPROTO_IP, IP_DROP_MEMBERSHIP,(char*)mcastreq,sizeof(*mcastreq));
  2339. closesock();
  2340. }
  2341. }
  2342. void CSocket::close()
  2343. {
  2344. #ifdef USERECVSEM
  2345. if (receiveblocksemowned) {
  2346. receiveblocksemowned = false;
  2347. receiveblocksem.signal();
  2348. }
  2349. #endif
  2350. if (state != ss_close) {
  2351. #ifdef SOCKTRACE
  2352. PROGLOG("SOCKTRACE: close socket %x %d (%p)", sock, sock, this);
  2353. #endif
  2354. state = ss_close;
  2355. if (mcastreq)
  2356. setsockopt(sock, IPPROTO_IP, IP_DROP_MEMBERSHIP,(char*)mcastreq,sizeof(*mcastreq));
  2357. if (closesock() != 0) {
  2358. THROWJSOCKEXCEPTION(ERRNO());
  2359. }
  2360. }
  2361. }
  2362. size32_t CSocket::get_max_send_size()
  2363. {
  2364. size32_t maxsend=0;
  2365. socklen_t size = sizeof(maxsend);
  2366. #if _WIN32
  2367. getsockopt(sock, SOL_SOCKET, SO_MAX_MSG_SIZE, (char *) &maxsend, &size);
  2368. #else
  2369. getsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char *) &maxsend, &size); // not the same but closest I can find
  2370. #endif
  2371. return maxsend;
  2372. }
  2373. size32_t CSocket::get_send_buffer_size()
  2374. {
  2375. size32_t maxsend=0;
  2376. socklen_t size = sizeof(maxsend);
  2377. getsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char *) &maxsend, &size);
  2378. return maxsend;
  2379. }
  2380. void CSocket::set_send_buffer_size(size32_t maxsend)
  2381. {
  2382. if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char *)&maxsend, sizeof(maxsend))!=0) {
  2383. LOGERR2(ERRNO(),1,"setsockopt(SO_SNDBUF)");
  2384. }
  2385. #ifdef CHECKBUFSIZE
  2386. size32_t v;
  2387. if (getsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char *)&v, sizeof(v))!=0) {
  2388. LOGERR2(ERRNO(),1,"getsockopt(SO_SNDBUF)");
  2389. }
  2390. if (v!=maxsend)
  2391. IWARNLOG("set_send_buffer_size requested %d, got %d",maxsend,v);
  2392. #endif
  2393. }
  2394. size32_t CSocket::get_receive_buffer_size()
  2395. {
  2396. size32_t max=0;
  2397. socklen_t size = sizeof(max);
  2398. getsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char *) &max, &size);
  2399. return max;
  2400. }
  2401. void CSocket::set_receive_buffer_size(size32_t max)
  2402. {
  2403. if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char *)&max, sizeof(max))!=0) {
  2404. LOGERR2(ERRNO(),1,"setsockopt(SO_RCVBUF)");
  2405. }
  2406. #ifdef CHECKBUFSIZE
  2407. size32_t v;
  2408. if (getsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char *)&v, sizeof(v))!=0) {
  2409. LOGERR2(ERRNO(),1,"getsockopt(SO_RCVBUF)");
  2410. }
  2411. if (v<max)
  2412. IWARNLOG("set_receive_buffer_size requested %d, got %d",max,v);
  2413. #endif
  2414. }
  2415. bool CSocket::join_multicast_group(SocketEndpoint &ep)
  2416. {
  2417. StringBuffer s;
  2418. ep.getIpText(s); // will improve later
  2419. MCASTREQ req(s.str());
  2420. if (setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP,(char*)&req, sizeof(req))!=0) {
  2421. return false;
  2422. }
  2423. return true;
  2424. }
  2425. bool CSocket::leave_multicast_group(SocketEndpoint &ep)
  2426. {
  2427. StringBuffer s;
  2428. ep.getIpText(s); // will improve later
  2429. MCASTREQ req(s.str());
  2430. if (setsockopt(sock, IPPROTO_IP, IP_DROP_MEMBERSHIP,(char*)&req, sizeof(req))!=0) {
  2431. return false;
  2432. }
  2433. return true;
  2434. }
  2435. void CSocket::set_ttl(unsigned _ttl)
  2436. {
  2437. if (_ttl)
  2438. {
  2439. u_char ttl = _ttl;
  2440. setsockopt(sock, IPPROTO_IP, IP_MULTICAST_TTL, (char *)&ttl, sizeof(ttl));
  2441. }
  2442. #ifdef SOCKTRACE
  2443. int ttl0 = 0;
  2444. socklen_t ttl1 = sizeof(ttl0);
  2445. getsockopt(sock, IPPROTO_IP, IP_MULTICAST_TTL, &ttl0, &ttl1);
  2446. DBGLOG("set_ttl: socket fd: %d requested ttl: %d actual ttl: %d", sock, _ttl, ttl0);
  2447. #endif
  2448. return;
  2449. }
  2450. void CSocket::logConnectionInfo(unsigned timeoutms, unsigned conn_mstime)
  2451. {
  2452. PROGLOG("SOCKTRACE: connect(%u) - time:%u ms fd:%d l:%d r:%s:%d", timeoutms, conn_mstime, sock, localPort, (hostname?hostname:"NULL"), hostport);
  2453. // PrintStackReport();
  2454. }
  2455. bool CSocket::isSecure() const
  2456. {
  2457. return false;
  2458. }
  2459. CSocket::~CSocket()
  2460. {
  2461. if (owned)
  2462. {
  2463. try
  2464. {
  2465. close();
  2466. }
  2467. catch (IException *e)
  2468. {
  2469. EXCLOG(e,"~CSocket close()");
  2470. e->Release();
  2471. }
  2472. }
  2473. free(hostname);
  2474. hostname = NULL;
  2475. #ifdef _TRACE
  2476. free(tracename);
  2477. tracename = NULL;
  2478. #endif
  2479. delete mcastreq;
  2480. }
  2481. CSocket::CSocket(const SocketEndpoint &ep,SOCKETMODE smode,const char *name)
  2482. {
  2483. state = ss_close;
  2484. nonblocking = false;
  2485. #ifdef USERECVSEM
  2486. receiveblocksemowned = false;
  2487. #endif
  2488. nagling = true; // until turned off
  2489. hostport = ep.port;
  2490. localPort = 0;
  2491. hostname = NULL;
  2492. mcastreq = NULL;
  2493. #ifdef _TRACE
  2494. tracename = NULL;
  2495. #endif
  2496. StringBuffer tmp;
  2497. if ((smode==sm_multicast_server)&&(name&&*name)) {
  2498. mcastreq = new MCASTREQ(name);
  2499. }
  2500. else {
  2501. if (!name&&!ep.isNull())
  2502. name = ep.getIpText(tmp).str();
  2503. hostname = name?strdup(name):NULL;
  2504. }
  2505. sock = INVALID_SOCKET;
  2506. sockmode = smode;
  2507. owned = true;
  2508. nextblocksize = 0;
  2509. in_accept = false;
  2510. accept_cancel_state = accept_not_cancelled;
  2511. #ifdef _TRACE
  2512. if (name)
  2513. setTraceName("T>", name);
  2514. else
  2515. {
  2516. StringBuffer hostname;
  2517. SocketEndpoint self;
  2518. self.setLocalHost(0);
  2519. self.getUrlStr(hostname);
  2520. setTraceName("S>", hostname.str());
  2521. }
  2522. #endif
  2523. }
  2524. CSocket::CSocket(T_SOCKET new_sock,SOCKETMODE smode,bool _owned)
  2525. {
  2526. nonblocking = false;
  2527. #ifdef USERECVSEM
  2528. receiveblocksemowned = false;
  2529. #endif
  2530. nagling = true; // until turned off
  2531. sock = new_sock;
  2532. if (new_sock!=INVALID_SOCKET)
  2533. STATS.activesockets++;
  2534. mcastreq = NULL;
  2535. #ifdef _TRACE
  2536. tracename = NULL;
  2537. #endif
  2538. state = ss_open;
  2539. sockmode = smode;
  2540. owned = _owned;
  2541. nextblocksize = 0;
  2542. in_accept = false;
  2543. accept_cancel_state = accept_not_cancelled;
  2544. set_nagle(false);
  2545. //set_linger(DEFAULT_LINGER_TIME); -- experiment with removing this as closesocket should still endevour to send outstanding data
  2546. char peer[256];
  2547. hostport = peer_name(peer,sizeof(peer));
  2548. hostname = strdup(peer);
  2549. SocketEndpoint ep;
  2550. localPort = getEndpoint(ep).port;
  2551. #ifdef _TRACE
  2552. setTraceName("A!", peer);
  2553. #endif
  2554. }
  2555. ISocket* ISocket::create(unsigned short p,int listen_queue_size)
  2556. {
  2557. if (p==0)
  2558. THROWJSOCKEXCEPTION2(JSOCKERR_bad_address);
  2559. SocketEndpoint ep;
  2560. ep.port = p;
  2561. Owned<CSocket> sock = new CSocket(ep,sm_tcp_server,NULL);
  2562. sock->open(listen_queue_size);
  2563. return sock.getClear();
  2564. }
  2565. ISocket* ISocket::create_ip(unsigned short p,const char *host,int listen_queue_size)
  2566. {
  2567. if (p==0)
  2568. THROWJSOCKEXCEPTION2(JSOCKERR_bad_address);
  2569. SocketEndpoint ep(host,p);
  2570. Owned<CSocket> sock = new CSocket(ep,sm_tcp_server,host);
  2571. sock->open(listen_queue_size);
  2572. return sock.getClear();
  2573. }
  2574. ISocket* ISocket::udp_create(unsigned short p)
  2575. {
  2576. SocketEndpoint ep;
  2577. ep.port=p;
  2578. Owned<CSocket> sock = new CSocket(ep,(p==0)?sm_udp:sm_udp_server,NULL);
  2579. sock->open(0);
  2580. return sock.getClear();
  2581. }
  2582. ISocket* ISocket::multicast_create(unsigned short p, const char *mcip, unsigned _ttl)
  2583. {
  2584. if (p==0)
  2585. THROWJSOCKEXCEPTION2(JSOCKERR_bad_address);
  2586. SocketEndpoint ep(mcip,p);
  2587. Owned<CSocket> sock = new CSocket(ep,sm_multicast_server,mcip);
  2588. sock->open(0,true);
  2589. if (_ttl)
  2590. sock->set_ttl(_ttl);
  2591. return sock.getClear();
  2592. }
  2593. ISocket* ISocket::multicast_create(unsigned short p, const IpAddress &ip, unsigned _ttl)
  2594. {
  2595. if (p==0)
  2596. THROWJSOCKEXCEPTION2(JSOCKERR_bad_address);
  2597. SocketEndpoint ep(p, ip);
  2598. StringBuffer tmp;
  2599. Owned<CSocket> sock = new CSocket(ep,sm_multicast_server,ip.getIpText(tmp).str());
  2600. sock->open(0,true);
  2601. if (_ttl)
  2602. sock->set_ttl(_ttl);
  2603. return sock.getClear();
  2604. }
  2605. ISocket* ISocket::udp_connect(unsigned short p, char const* name)
  2606. {
  2607. if (!name||!*name||(p==0))
  2608. THROWJSOCKEXCEPTION2(JSOCKERR_bad_address);
  2609. SocketEndpoint ep(name, p);
  2610. Owned<CSocket> sock = new CSocket(ep,sm_udp,name);
  2611. sock->udpconnect();
  2612. return sock.getClear();
  2613. }
  2614. ISocket* ISocket::udp_connect(const SocketEndpoint &ep)
  2615. {
  2616. Owned<CSocket> sock = new CSocket(ep,sm_udp,NULL);
  2617. sock->udpconnect();
  2618. return sock.getClear();
  2619. }
  2620. ISocket* ISocket::multicast_connect(unsigned short p, char const* mcip, unsigned _ttl)
  2621. {
  2622. if (p==0)
  2623. THROWJSOCKEXCEPTION2(JSOCKERR_bad_address);
  2624. SocketEndpoint ep(mcip,p);
  2625. return multicast_connect(ep, _ttl);
  2626. }
  2627. ISocket* ISocket::multicast_connect(const SocketEndpoint &ep, unsigned _ttl)
  2628. {
  2629. Owned<CSocket> sock = new CSocket(ep,sm_multicast,NULL);
  2630. sock->udpconnect();
  2631. if (_ttl)
  2632. sock->set_ttl(_ttl);
  2633. return sock.getClear();
  2634. }
  2635. ISocket* ISocket::attach(int s, bool tcpip)
  2636. {
  2637. CSocket* sock = new CSocket((SOCKET)s, tcpip?sm_tcp:sm_udp, false);
  2638. return sock;
  2639. }
  2640. bool isInterfaceIp(const IpAddress &ip, const char *ifname)
  2641. {
  2642. #ifdef _WIN32
  2643. return false;
  2644. #else
  2645. int fd = socket(AF_INET, SOCK_DGRAM, 0); // IPV6 TBD
  2646. if (fd<0)
  2647. return false;
  2648. MemoryAttr ma;
  2649. char *buf = (char *)ma.allocate(1024);
  2650. struct ifconf ifc;
  2651. ifc.ifc_len = 1024;
  2652. ifc.ifc_buf = buf;
  2653. if(ioctl(fd, SIOCGIFCONF, &ifc) < 0) // query interfaces
  2654. {
  2655. close(fd);
  2656. return false;
  2657. }
  2658. bool match = false;
  2659. struct ifreq *ifr = ifc.ifc_req;
  2660. int len = 0;
  2661. for (int i=0; i<ifc.ifc_len;
  2662. #ifdef __APPLE__
  2663. len = _SIZEOF_ADDR_IFREQ(*ifr),
  2664. #else
  2665. len = sizeof(struct ifreq),
  2666. #endif
  2667. ifr = (struct ifreq *) ((char *) ifr + len),
  2668. i += len
  2669. )
  2670. {
  2671. struct ifreq *item = ifr;
  2672. if (ifname&&*ifname)
  2673. if (!WildMatch(item->ifr_name,ifname))
  2674. continue;
  2675. IpAddress iptest((inet_ntoa(((struct sockaddr_in *)&item->ifr_addr)->sin_addr)));
  2676. if (ip.ipequals(iptest))
  2677. {
  2678. match = true;
  2679. break;
  2680. }
  2681. }
  2682. close(fd);
  2683. return match;
  2684. #endif
  2685. }
  2686. NO_SANITIZE("alignment") bool getInterfaceIp(IpAddress &ip,const char *ifname)
  2687. {
  2688. #if defined(_WIN32)
  2689. return false;
  2690. #else
  2691. static bool recursioncheck = false;
  2692. ip.ipset(NULL);
  2693. int fd = socket(AF_INET, SOCK_DGRAM, 0); // IPV6 TBD
  2694. if (fd<0)
  2695. return false;
  2696. MemoryAttr ma;
  2697. char *buf = (char *)ma.allocate(1024);
  2698. struct ifconf ifc;
  2699. ifc.ifc_len = 1024;
  2700. ifc.ifc_buf = buf;
  2701. if(ioctl(fd, SIOCGIFCONF, &ifc) < 0) // query interfaces
  2702. {
  2703. close(fd);
  2704. return false;
  2705. }
  2706. for (int loopback = 0; loopback <= 1; loopback++)
  2707. {
  2708. struct ifreq *ifr = ifc.ifc_req;
  2709. int len = 0;
  2710. for (int i=0; i<ifc.ifc_len;
  2711. #ifdef __APPLE__
  2712. len = _SIZEOF_ADDR_IFREQ(*ifr),
  2713. #else
  2714. len = sizeof(struct ifreq),
  2715. #endif
  2716. ifr = (struct ifreq *) ((char *) ifr + len),
  2717. i += len
  2718. )
  2719. {
  2720. bool useLoopback = (loopback==1);
  2721. struct ifreq *item = ifr;
  2722. if (ifname && *ifname)
  2723. if (!WildMatch(item->ifr_name,ifname))
  2724. continue;
  2725. #ifdef __APPLE__
  2726. if (item->ifr_addr.sa_family != AF_INET) // ipv6 support TBD
  2727. continue;
  2728. char host[128];
  2729. getnameinfo(&item->ifr_addr, sizeof(item->ifr_addr), host, sizeof(host), 0, 0, NI_NUMERICHOST);
  2730. IpAddress iptest(host);
  2731. #else
  2732. IpAddress iptest((inet_ntoa(((struct sockaddr_in *)&item->ifr_addr)->sin_addr)));
  2733. #endif
  2734. struct ifreq flags;
  2735. memset(&flags, 0, sizeof(flags));
  2736. strcpy(flags.ifr_name, item->ifr_name);
  2737. if (ioctl(fd, SIOCGIFFLAGS, &flags) < 0)
  2738. {
  2739. if (!recursioncheck) {
  2740. recursioncheck = true;
  2741. IERRLOG("Error retrieving interface flags for interface %s", item->ifr_name);
  2742. recursioncheck = false;
  2743. }
  2744. continue;
  2745. }
  2746. bool isLoopback = iptest.isLoopBack() || ((flags.ifr_flags & IFF_LOOPBACK) != 0);
  2747. bool isUp = (flags.ifr_flags & IFF_UP) != 0;
  2748. if ((isLoopback==useLoopback) && isUp)
  2749. {
  2750. if (ip.isNull())
  2751. ip.ipset(iptest);
  2752. else if (!PreferredSubnet.isNull()&&!PreferredSubnet.test(ip)&&PreferredSubnet.test(iptest))
  2753. ip.ipset(iptest);
  2754. }
  2755. }
  2756. if (!ip.isNull())
  2757. break;
  2758. }
  2759. close(fd);
  2760. return !ip.isNull();
  2761. #endif
  2762. }
  2763. static StringAttr cachehostname;
  2764. static IpAddress cachehostip;
  2765. static IpAddress localhostip;
  2766. static CriticalSection hostnamesect;
  2767. const char * GetCachedHostName()
  2768. {
  2769. CriticalBlock c(hostnamesect);
  2770. if (!cachehostname.get())
  2771. {
  2772. #ifndef _WIN32
  2773. IpAddress ip;
  2774. const char *ifs = queryEnvironmentConf().queryProp("interface");
  2775. if (getInterfaceIp(ip, ifs))
  2776. {
  2777. StringBuffer ips;
  2778. ip.getIpText(ips);
  2779. if (ips.length())
  2780. {
  2781. cachehostname.set(ips.str());
  2782. cachehostip.ipset(ip);
  2783. return cachehostname.get();
  2784. }
  2785. }
  2786. #endif
  2787. char temp[1024];
  2788. if (gethostname(temp, sizeof(temp))==0)
  2789. cachehostname.set(temp);
  2790. else
  2791. cachehostname.set("localhost"); // assume no NIC card
  2792. }
  2793. return cachehostname.get();
  2794. }
  2795. IpAddress & queryLocalIP()
  2796. {
  2797. CriticalBlock c(hostnamesect);
  2798. if (localhostip.isNull())
  2799. {
  2800. if (IP6preferred)
  2801. localhostip.ipset("::1"); //IPv6
  2802. else
  2803. localhostip.ipset("127.0.0.1"); //IPv4
  2804. }
  2805. return localhostip;
  2806. }
  2807. IpAddress & queryHostIP()
  2808. {
  2809. CriticalBlock c(hostnamesect);
  2810. if (cachehostip.isNull()) {
  2811. if (!cachehostip.ipset(GetCachedHostName())) {
  2812. cachehostip.ipset(queryLocalIP());
  2813. // printf("hostname %s not resolved, using localhost\n",GetCachedHostName()); // don't use jlog in case recursive
  2814. }
  2815. }
  2816. return cachehostip;
  2817. }
  2818. IpAddress &GetHostIp(IpAddress &ip)
  2819. {
  2820. ip.ipset(queryHostIP());
  2821. return ip;
  2822. }
  2823. IpAddress &localHostToNIC(IpAddress &ip)
  2824. {
  2825. if (ip.isLoopBack())
  2826. GetHostIp(ip);
  2827. return ip;
  2828. }
  2829. // IpAddress
  2830. bool getInterfaceName(StringBuffer &ifname)
  2831. {
  2832. #if defined(_WIN32)
  2833. return false;
  2834. #else
  2835. IpAddress myIp;
  2836. GetHostIp(myIp);
  2837. int fd = socket(AF_INET, SOCK_DGRAM, 0); // IPV6 TBD
  2838. if (fd<0)
  2839. return false;
  2840. MemoryAttr ma;
  2841. char *buf = (char *)ma.allocate(1024);
  2842. struct ifconf ifc;
  2843. ifc.ifc_len = 1024;
  2844. ifc.ifc_buf = buf;
  2845. if(ioctl(fd, SIOCGIFCONF, &ifc) < 0) // query interfaces
  2846. {
  2847. close(fd);
  2848. return false;
  2849. }
  2850. struct ifreq *ifr = ifc.ifc_req;
  2851. int len = 0;
  2852. for (int i=0; i<ifc.ifc_len;
  2853. #ifdef __APPLE__
  2854. len = _SIZEOF_ADDR_IFREQ(*ifr),
  2855. #else
  2856. len = sizeof(struct ifreq),
  2857. #endif
  2858. ifr = (struct ifreq *) ((char *) ifr + len),
  2859. i += len
  2860. )
  2861. {
  2862. struct ifreq *item = ifr;
  2863. IpAddress iptest((inet_ntoa(((struct sockaddr_in *)&item->ifr_addr)->sin_addr)));
  2864. if (iptest.ipequals(myIp))
  2865. {
  2866. ifname.set(item->ifr_name);
  2867. close(fd);
  2868. return true;
  2869. }
  2870. }
  2871. close(fd);
  2872. return false;
  2873. #endif
  2874. }
  2875. inline bool isIp4(const unsigned *netaddr)
  2876. {
  2877. if (IP4only)
  2878. return true;
  2879. if (netaddr[2]==0xffff0000)
  2880. return (netaddr[1]==0)&&(netaddr[0]==0);
  2881. if (netaddr[2]==0)
  2882. if ((netaddr[3]==0)&&(netaddr[0]==0)&&(netaddr[1]==0))
  2883. return true; // null address
  2884. // maybe should get loopback here
  2885. return false;
  2886. }
  2887. bool IpAddress::isIp4() const
  2888. {
  2889. return ::isIp4(netaddr);
  2890. }
  2891. bool IpAddress::isNull() const
  2892. {
  2893. return (netaddr[3]==0)&&(IP4only||((netaddr[2]==0)&&(netaddr[1]==0)&&(netaddr[0]==0)));
  2894. }
  2895. bool IpAddress::isLoopBack() const
  2896. {
  2897. if (::isIp4(netaddr)&&((netaddr[3] & 0x000000ff)==0x000007f))
  2898. return true;
  2899. return (netaddr[3]==0x1000000)&&(netaddr[2]==0)&&(netaddr[1]==0)&&(netaddr[0]==0);
  2900. }
  2901. bool IpAddress::isLocal() const
  2902. {
  2903. if (isLoopBack() || isHost())
  2904. return true;
  2905. IpAddress ip(*this);
  2906. return isInterfaceIp(ip, NULL);
  2907. }
  2908. bool IpAddress::ipequals(const IpAddress & other) const
  2909. {
  2910. // reverse compare for speed
  2911. return (other.netaddr[3]==netaddr[3])&&(IP4only||((other.netaddr[2]==netaddr[2])&&(other.netaddr[1]==netaddr[1])&&(other.netaddr[0]==netaddr[0])));
  2912. }
  2913. int IpAddress::ipcompare(const IpAddress & other) const
  2914. {
  2915. return memcmp(&netaddr, &other.netaddr, sizeof(netaddr));
  2916. }
  2917. unsigned IpAddress::iphash(unsigned prev) const
  2918. {
  2919. return hashc((const byte *)&netaddr,sizeof(netaddr),prev);
  2920. }
  2921. unsigned IpAddress::fasthash() const
  2922. {
  2923. if (IP4only || isIp4())
  2924. return netaddr[3] >> 24;
  2925. else
  2926. return iphash(0) >> 24;
  2927. }
  2928. bool IpAddress::isHost() const
  2929. {
  2930. return ipequals(queryHostIP());
  2931. }
  2932. static bool decodeNumericIP(const char *text,unsigned *netaddr)
  2933. {
  2934. if (!text)
  2935. return false;
  2936. bool isv6 = strchr(text,':')!=NULL;
  2937. StringBuffer tmp;
  2938. if ((*text=='[')&&!IP4only) {
  2939. text++;
  2940. size32_t l = strlen(text);
  2941. if ((l<=2)||(text[l-1]!=']'))
  2942. return false;
  2943. text = tmp.append(l-2,text);
  2944. }
  2945. if (!isv6&&isdigit(text[0])) {
  2946. if (_inet_pton(AF_INET, text, &netaddr[3])>0) {
  2947. netaddr[2] = netaddr[3]?0xffff0000:0; // check for NULL
  2948. netaddr[1] = 0;
  2949. netaddr[0] = 0; // special handling for loopback?
  2950. return true;
  2951. }
  2952. }
  2953. else if (isv6&&!IP4only) {
  2954. int ret = _inet_pton(AF_INET6, text, netaddr);
  2955. if (ret>=0)
  2956. return (ret>0);
  2957. int err = ERRNO();
  2958. StringBuffer tmp("_inet_pton: ");
  2959. tmp.append(text);
  2960. LOGERR(err,1,tmp.str());
  2961. }
  2962. return false;
  2963. }
  2964. static bool lookupHostAddress(const char *name,unsigned *netaddr)
  2965. {
  2966. // if IP4only or using MS V6 can only resolve IPv4 using
  2967. static bool recursioncheck = false; // needed to stop error message recursing
  2968. unsigned retry=10;
  2969. #if defined(__linux__) || defined (__APPLE__) || defined(getaddrinfo)
  2970. if (IP4only) {
  2971. #else
  2972. {
  2973. #endif
  2974. CriticalBlock c(hostnamesect);
  2975. hostent * entry = gethostbyname(name);
  2976. while (entry==NULL) {
  2977. if (retry--==0) {
  2978. if (!recursioncheck) {
  2979. recursioncheck = true;
  2980. LogErr(h_errno,1,"gethostbyname failed",__LINE__,name);
  2981. recursioncheck = false;
  2982. }
  2983. return false;
  2984. }
  2985. {
  2986. CriticalUnblock ub(hostnamesect);
  2987. Sleep((10-retry)*100);
  2988. }
  2989. entry = gethostbyname(name);
  2990. }
  2991. if (entry->h_addr_list[0]) {
  2992. unsigned ptr = 0;
  2993. if (!PreferredSubnet.isNull()) {
  2994. for (;;) {
  2995. ptr++;
  2996. if (entry->h_addr_list[ptr]==NULL) {
  2997. ptr = 0;
  2998. break;
  2999. }
  3000. IpAddress ip;
  3001. ip.setNetAddress(sizeof(unsigned),entry->h_addr_list[ptr]);
  3002. if (PreferredSubnet.test(ip))
  3003. break;
  3004. }
  3005. }
  3006. memcpy(&netaddr[3], entry->h_addr_list[ptr], sizeof(netaddr[3]));
  3007. netaddr[2] = 0xffff0000;
  3008. netaddr[1] = 0;
  3009. netaddr[0] = 0;
  3010. return true;
  3011. }
  3012. return false;
  3013. }
  3014. #if defined(__linux__) || defined (__APPLE__) || defined(getaddrinfo)
  3015. struct addrinfo hints;
  3016. memset(&hints,0,sizeof(hints));
  3017. struct addrinfo *addrInfo = NULL;
  3018. for (;;) {
  3019. memset(&hints,0,sizeof(hints));
  3020. int ret = getaddrinfo(name, NULL , &hints, &addrInfo);
  3021. if (!ret)
  3022. break;
  3023. if (retry--==0) {
  3024. if (!recursioncheck) {
  3025. recursioncheck = true;
  3026. LogErr(ret,1,"getaddrinfo failed",__LINE__,name);
  3027. #ifdef _DEBUG
  3028. PrintStackReport();
  3029. #endif
  3030. recursioncheck = false;
  3031. }
  3032. return false;
  3033. }
  3034. Sleep((10-retry)*100);
  3035. }
  3036. struct addrinfo *best = NULL;
  3037. bool snm = !PreferredSubnet.isNull();
  3038. for (;;) {
  3039. struct addrinfo *ai;
  3040. for (ai = addrInfo; ai; ai = ai->ai_next) {
  3041. // printf("flags=%d, family=%d, socktype=%d, protocol=%d, addrlen=%d, canonname=%s\n",ai->ai_flags,ai->ai_family,ai->ai_socktype,ai->ai_protocol,ai->ai_addrlen,ai->ai_canonname?ai->ai_canonname:"NULL");
  3042. switch (ai->ai_family) {
  3043. case AF_INET: {
  3044. if (snm) {
  3045. IpAddress ip;
  3046. ip.setNetAddress(sizeof(in_addr),&(((sockaddr_in *)ai->ai_addr)->sin_addr));
  3047. if (!PreferredSubnet.test(ip))
  3048. continue;
  3049. }
  3050. if ((best==NULL)||((best->ai_family==AF_INET6)&&!IP6preferred))
  3051. best = ai;
  3052. break;
  3053. }
  3054. case AF_INET6: {
  3055. if (snm) {
  3056. IpAddress ip;
  3057. ip.setNetAddress(sizeof(in_addr6),&(((sockaddr_in6 *)ai->ai_addr)->sin6_addr));
  3058. if (!PreferredSubnet.test(ip))
  3059. continue;
  3060. }
  3061. if ((best==NULL)||((best->ai_family==AF_INET)&&IP6preferred))
  3062. best = ai;
  3063. break;
  3064. }
  3065. }
  3066. }
  3067. if (best||!snm)
  3068. break;
  3069. snm = false;
  3070. }
  3071. if (best) {
  3072. if (best->ai_family==AF_INET6)
  3073. memcpy(netaddr,&(((sockaddr_in6 *)best->ai_addr)->sin6_addr),sizeof(in6_addr));
  3074. else {
  3075. memcpy(netaddr+3,&(((sockaddr_in *)best->ai_addr)->sin_addr),sizeof(in_addr));
  3076. netaddr[2] = 0xffff0000;
  3077. netaddr[1] = 0;
  3078. netaddr[0] = 0;
  3079. }
  3080. }
  3081. freeaddrinfo(addrInfo);
  3082. return best!=NULL;
  3083. #endif
  3084. return false;
  3085. }
  3086. bool IpAddress::ipset(const char *text)
  3087. {
  3088. if (text&&*text) {
  3089. if ((text[0]=='.')&&(text[1]==0)) {
  3090. ipset(queryHostIP());
  3091. return true;
  3092. }
  3093. if (decodeNumericIP(text,netaddr))
  3094. return true;
  3095. const char *s;
  3096. for (s=text;*s;s++)
  3097. if (!isdigit(*s)&&(*s!=':')&&(*s!='.'))
  3098. break;
  3099. if (!*s)
  3100. return ipset(NULL);
  3101. if (lookupHostAddress(text,netaddr))
  3102. return true;
  3103. }
  3104. memset(&netaddr,0,sizeof(netaddr));
  3105. return false;
  3106. }
  3107. inline char * addbyte(char *s,byte b)
  3108. {
  3109. if (b>=100) {
  3110. *(s++) = b/100+'0';
  3111. b %= 100;
  3112. *(s++) = b/10+'0';
  3113. b %= 10;
  3114. }
  3115. else if (b>=10) {
  3116. *(s++) = b/10+'0';
  3117. b %= 10;
  3118. }
  3119. *(s++) = b+'0';
  3120. return s;
  3121. }
  3122. StringBuffer & IpAddress::getIpText(StringBuffer & out) const
  3123. {
  3124. if (::isIp4(netaddr)) {
  3125. const byte *ip = (const byte *)&netaddr[3];
  3126. char ips[16];
  3127. char *s = ips;
  3128. for (unsigned i=0;i<4;i++) {
  3129. if (i)
  3130. *(s++) = '.';
  3131. s = addbyte(s,ip[i]);
  3132. }
  3133. return out.append(s-ips,ips);
  3134. }
  3135. char tmp[INET6_ADDRSTRLEN];
  3136. const char *res = _inet_ntop(AF_INET6, &netaddr, tmp, sizeof(tmp));
  3137. if (!res)
  3138. throw makeOsException(errno);
  3139. return out.append(res);
  3140. }
  3141. void IpAddress::ipserialize(MemoryBuffer & out) const
  3142. {
  3143. if (((netaddr[2]==0xffff0000)||(netaddr[2]==0))&&(netaddr[1]==0)&&(netaddr[0]==0)) {
  3144. if (netaddr[3]==IPV6_SERIALIZE_PREFIX)
  3145. throw MakeStringException(-1,"Invalid network address"); // hack prevention
  3146. out.append(sizeof(netaddr[3]), &netaddr[3]);
  3147. }
  3148. else {
  3149. unsigned pfx = IPV6_SERIALIZE_PREFIX;
  3150. out.append(sizeof(pfx),&pfx).append(sizeof(netaddr),&netaddr);
  3151. }
  3152. }
  3153. void IpAddress::ipdeserialize(MemoryBuffer & in)
  3154. {
  3155. unsigned pfx;
  3156. in.read(sizeof(pfx),&pfx);
  3157. if (pfx!=IPV6_SERIALIZE_PREFIX) {
  3158. netaddr[0] = 0;
  3159. netaddr[1] = 0;
  3160. netaddr[2] = (pfx == 0 || pfx == 0x1000000) ? 0 : 0xffff0000; // catch null and loopback
  3161. netaddr[3] = pfx;
  3162. }
  3163. else
  3164. in.read(sizeof(netaddr),&netaddr);
  3165. }
  3166. unsigned IpAddress::ipdistance(const IpAddress &other,unsigned offset) const
  3167. {
  3168. if (offset>3)
  3169. offset = 3;
  3170. int i1;
  3171. _cpyrev4(&i1,&netaddr[3-offset]);
  3172. int i2;
  3173. _cpyrev4(&i2,&other.netaddr[3-offset]);
  3174. i1-=i2;
  3175. if (i1>0)
  3176. return i1;
  3177. return -i1;
  3178. }
  3179. bool IpAddress::ipincrement(unsigned count,byte minoctet,byte maxoctet,unsigned short minipv6piece,unsigned maxipv6piece)
  3180. {
  3181. unsigned base;
  3182. if (::isIp4(netaddr)) {
  3183. base = maxoctet-minoctet+1;
  3184. if (!base||(base>256))
  3185. return false;
  3186. byte * ips = (byte *)&netaddr[3];
  3187. byte * ip = ips+4;
  3188. while (count) {
  3189. if (ip==ips)
  3190. return false; // overflow
  3191. ip--;
  3192. unsigned v = (count+((*ip>minoctet)?(*ip-minoctet):0));
  3193. *ip = minoctet + v%base;
  3194. count = v/base;
  3195. }
  3196. }
  3197. else {
  3198. base = maxipv6piece-minipv6piece+1;
  3199. if (!base||(base>0x10000))
  3200. return false;
  3201. unsigned short * ps = (unsigned short *)&netaddr;
  3202. unsigned short * p = ps+8;
  3203. while (count) {
  3204. if (p==ps)
  3205. return false; // overflow (actually near impossible!)
  3206. p--;
  3207. unsigned v = (count+((*p>minipv6piece)?(*p-minipv6piece):0));
  3208. *p = minipv6piece + v%base;
  3209. count = v/base;
  3210. }
  3211. }
  3212. return true;
  3213. }
  3214. unsigned IpAddress::ipsetrange( const char *text) // e.g. 10.173.72.1-65 ('-' may be omitted)
  3215. {
  3216. unsigned e=0;
  3217. unsigned f=0;
  3218. const char *r = strchr(text,'-');
  3219. bool ok;
  3220. if (r) {
  3221. e = atoi(r+1);
  3222. StringBuffer tmp(r-text,text);
  3223. ok = ipset(tmp.str());
  3224. if (!::isIp4(netaddr))
  3225. IPV6_NOT_IMPLEMENTED(); // TBD IPv6
  3226. if (ok) {
  3227. while ((r!=text)&&(*(r-1)!='.'))
  3228. r--;
  3229. f = (r!=text)?atoi(r):0;
  3230. }
  3231. }
  3232. else
  3233. ok = ipset(text);
  3234. if ((f>e)||!ok)
  3235. return 0;
  3236. return e-f+1;
  3237. }
  3238. NO_SANITIZE("alignment") size32_t IpAddress::getNetAddress(size32_t maxsz,void *dst) const
  3239. {
  3240. if (maxsz==sizeof(unsigned)) {
  3241. if (::isIp4(netaddr)) {
  3242. *(unsigned *)dst = netaddr[3];
  3243. return maxsz;
  3244. }
  3245. }
  3246. else if (!IP4only&&(maxsz==sizeof(netaddr))) {
  3247. memcpy(dst,&netaddr,maxsz);
  3248. return maxsz;
  3249. }
  3250. return 0;
  3251. }
  3252. NO_SANITIZE("alignment") void IpAddress::setNetAddress(size32_t sz,const void *src)
  3253. {
  3254. if (sz==sizeof(unsigned)) { // IPv4
  3255. netaddr[0] = 0;
  3256. netaddr[1] = 0;
  3257. netaddr[3] = *(const unsigned *)src;
  3258. netaddr[2] = netaddr[3] ? 0xffff0000 : 0; // leave as null if Ipv4 address is null
  3259. }
  3260. else if (!IP4only&&(sz==sizeof(netaddr))) { // IPv6
  3261. memcpy(&netaddr,src,sz);
  3262. if ((netaddr[2]==0)&&(netaddr[3]!=0)&&(netaddr[3]!=0x1000000)&&(netaddr[0]==0)&&(netaddr[1]==0))
  3263. netaddr[2]=0xffff0000; // use this form only
  3264. }
  3265. else
  3266. memset(&netaddr,0,sizeof(netaddr));
  3267. }
  3268. void SocketEndpoint::deserialize(MemoryBuffer & in)
  3269. {
  3270. ipdeserialize(in);
  3271. in.read(port);
  3272. }
  3273. void SocketEndpoint::serialize(MemoryBuffer & out) const
  3274. {
  3275. ipserialize(out);
  3276. out.append(port);
  3277. }
  3278. bool SocketEndpoint::set(const char *name,unsigned short _port)
  3279. {
  3280. if (name) {
  3281. if (*name=='[') {
  3282. const char *s = name+1;
  3283. const char *t = strchr(s,']');
  3284. if (t) {
  3285. StringBuffer tmp(t-s,s);
  3286. if (t[1]==':')
  3287. _port = atoi(t+2);
  3288. return set(tmp.str(),_port);
  3289. }
  3290. }
  3291. const char * colon = strchr(name, ':');
  3292. if (colon) {
  3293. if (!IP4only&&strchr(colon+1, ':'))
  3294. colon = NULL; // hello its IpV6
  3295. }
  3296. else
  3297. colon = strchr(name, '|'); // strange hole convention
  3298. char ips[260];
  3299. if (colon) {
  3300. size32_t l = colon-name;
  3301. if (l>=sizeof(ips))
  3302. l = sizeof(ips)-1;
  3303. memcpy(ips,name,l);
  3304. ips[l] = 0;
  3305. name = ips;
  3306. _port = atoi(colon+1);
  3307. }
  3308. if (ipset(name)) {
  3309. port = _port;
  3310. return true;
  3311. }
  3312. }
  3313. ipset(NULL);
  3314. port = 0;
  3315. return false;
  3316. }
  3317. void SocketEndpoint::getUrlStr(char * str, size32_t len) const
  3318. {
  3319. if (len==0)
  3320. return;
  3321. StringBuffer _str;
  3322. getUrlStr(_str);
  3323. size32_t l = _str.length()+1;
  3324. if (l>len)
  3325. {
  3326. l = len-1;
  3327. str[l] = 0;
  3328. }
  3329. memcpy(str,_str.str(),l);
  3330. }
  3331. StringBuffer &SocketEndpoint::getUrlStr(StringBuffer &str) const
  3332. {
  3333. getIpText(str);
  3334. if (port)
  3335. str.append(':').append((unsigned)port); // TBD IPv6 put [] on
  3336. return str;
  3337. }
  3338. unsigned SocketEndpoint::hash(unsigned prev) const
  3339. {
  3340. return hashc((const byte *)&port,sizeof(port),iphash(prev));
  3341. }
  3342. //---------------------------------------------------------------------------
  3343. SocketListCreator::SocketListCreator()
  3344. {
  3345. lastPort = 0;
  3346. }
  3347. void SocketListCreator::addSocket(const SocketEndpoint &ep)
  3348. {
  3349. StringBuffer ipstr;
  3350. ep.getIpText(ipstr);
  3351. addSocket(ipstr.str(), ep.port);
  3352. }
  3353. void SocketListCreator::addSocket(const char * ip, unsigned port)
  3354. {
  3355. if (fullText.length())
  3356. fullText.append("|");
  3357. const char * prev = lastIp;
  3358. const char * startCopy = ip;
  3359. if (prev)
  3360. {
  3361. if (strcmp(ip, prev) == 0)
  3362. {
  3363. fullText.append("=");
  3364. startCopy = NULL;
  3365. }
  3366. else
  3367. {
  3368. const char * cur = ip;
  3369. for (;;)
  3370. {
  3371. char n = *cur;
  3372. if (!n)
  3373. break;
  3374. if (n != *prev)
  3375. break;
  3376. cur++;
  3377. prev++;
  3378. if (n == '.')
  3379. startCopy = cur;
  3380. }
  3381. if (startCopy != ip)
  3382. fullText.append("*");
  3383. }
  3384. }
  3385. fullText.append(startCopy);
  3386. if (lastPort != port)
  3387. fullText.append(":").append(port);
  3388. lastIp.set(ip);
  3389. lastPort = port;
  3390. }
  3391. const char * SocketListCreator::getText()
  3392. {
  3393. return fullText.str();
  3394. }
  3395. void SocketListCreator::addSockets(SocketEndpointArray &array)
  3396. {
  3397. ForEachItemIn(i,array) {
  3398. const SocketEndpoint &sockep=array.item(i);
  3399. StringBuffer ipstr;
  3400. sockep.getIpText(ipstr);
  3401. addSocket(ipstr.str(),sockep.port);
  3402. }
  3403. }
  3404. //---------------------------------------------------------------------------
  3405. SocketListParser::SocketListParser(const char * text)
  3406. {
  3407. fullText.set(text);
  3408. cursor = NULL;
  3409. lastPort = 0;
  3410. }
  3411. void SocketListParser::first(unsigned port)
  3412. {
  3413. cursor = fullText;
  3414. lastIp.set(NULL);
  3415. lastPort = port;
  3416. }
  3417. bool SocketListParser::get(StringAttr & ip, unsigned & port, unsigned index, unsigned defport)
  3418. {
  3419. first(defport);
  3420. do
  3421. {
  3422. if (!next(ip, port))
  3423. return false;
  3424. } while (index--);
  3425. return true;
  3426. }
  3427. bool SocketListParser::next(StringAttr & ip, unsigned & port)
  3428. {
  3429. // IPV6TBD
  3430. StringBuffer ipText;
  3431. if (*cursor == 0)
  3432. return false;
  3433. if (*cursor == '=')
  3434. {
  3435. ipText.append(lastIp);
  3436. cursor++;
  3437. }
  3438. else if (*cursor == '*')
  3439. {
  3440. cursor++;
  3441. //count the number of dots in the tail
  3442. const char * cur = cursor;
  3443. unsigned count = 0;
  3444. for (;;)
  3445. {
  3446. char c = *cur++;
  3447. switch (c)
  3448. {
  3449. case 0:
  3450. case '|':
  3451. case ',':
  3452. case ':':
  3453. goto done;
  3454. case '.':
  3455. ++count;
  3456. break;
  3457. }
  3458. }
  3459. done:
  3460. //copy up to the appropriate dot from the previous ip.
  3461. const unsigned dotCount = 3; //more what about 6 digit ip's
  3462. cur = lastIp;
  3463. for (;;)
  3464. {
  3465. char c = *cur++;
  3466. switch (c)
  3467. {
  3468. case 0:
  3469. case '|':
  3470. case ',':
  3471. case ':':
  3472. assertex(!"Should not get here!");
  3473. goto done2;
  3474. case '.':
  3475. ipText.append(c);
  3476. if (++count == dotCount)
  3477. goto done2;
  3478. break;
  3479. default:
  3480. ipText.append(c);
  3481. break;
  3482. }
  3483. }
  3484. done2:;
  3485. }
  3486. bool inPort = false;
  3487. port = lastPort;
  3488. for (;;)
  3489. {
  3490. char c = *cursor++;
  3491. switch (c)
  3492. {
  3493. case 0:
  3494. cursor--;
  3495. goto doneCopy;
  3496. case '|':
  3497. case ',':
  3498. goto doneCopy;
  3499. case ':':
  3500. port = atoi(cursor);
  3501. inPort = true;
  3502. break;;
  3503. default:
  3504. if (!inPort)
  3505. ipText.append(c);
  3506. break;
  3507. }
  3508. }
  3509. doneCopy:
  3510. lastIp.set(ipText.str());
  3511. ip.set(lastIp);
  3512. lastPort = port;
  3513. return true;
  3514. }
  3515. unsigned SocketListParser::getSockets(SocketEndpointArray &array,unsigned defport)
  3516. {
  3517. first(defport);
  3518. StringAttr ip;
  3519. unsigned port;
  3520. while (next(ip,port)) {
  3521. SocketEndpoint ep(ip,port);
  3522. array.append(ep);
  3523. }
  3524. return array.ordinality();
  3525. }
  3526. void getSocketStatistics(JSocketStatistics &stats)
  3527. {
  3528. // should put in simple lock
  3529. memcpy(&stats,&STATS,sizeof(stats));
  3530. }
  3531. void resetSocketStatistics()
  3532. {
  3533. unsigned activesockets=STATS.activesockets;
  3534. memset(&STATS,0,sizeof(STATS));
  3535. STATS.activesockets = activesockets;
  3536. }
  3537. static StringBuffer &appendtime(StringBuffer &s,unsigned us)
  3538. {
  3539. // attemp to get into more sensible units
  3540. if (us>10000000)
  3541. return s.append(us/1000000).append('s');
  3542. if (us>10000)
  3543. return s.append(us/1000).append("ms");
  3544. return s.append(us).append("us");
  3545. }
  3546. StringBuffer &getSocketStatisticsString(JSocketStatistics &stats,StringBuffer &str)
  3547. {
  3548. str.append("connects=").append(stats.connects).append('\n');
  3549. appendtime(str.append("connecttime="),stats.connecttime).append('\n');
  3550. str.append("failedconnects=").append(stats.failedconnects).append('\n');
  3551. appendtime(str.append("failedconnecttime="),stats.failedconnecttime).append('\n');
  3552. str.append("reads=").append(stats.reads).append('\n');
  3553. appendtime(str.append("readtime="),stats.readtime).append('\n');
  3554. str.append("readsize=").append(stats.readsize).append(" bytes\n");
  3555. str.append("writes=").append(stats.writes).append('\n');
  3556. appendtime(str.append("writetime="),stats.writetime).append('\n');
  3557. str.append("writesize=").append(stats.writesize).append(" bytes").append('\n');
  3558. str.append("activesockets=").append(stats.activesockets).append('\n');
  3559. str.append("numblockrecvs=").append(stats.numblockrecvs).append('\n');
  3560. str.append("numblocksends=").append(stats.numblocksends).append('\n');
  3561. str.append("blockrecvsize=").append(stats.blockrecvsize).append('\n');
  3562. str.append("blocksendsize=").append(stats.blocksendsize).append('\n');
  3563. str.append("blockrecvtime=").append(stats.blockrecvtime).append('\n');
  3564. str.append("blocksendtime=").append(stats.blocksendtime).append('\n');
  3565. str.append("longestblocksend=").append(stats.longestblocksend).append('\n');
  3566. str.append("longestblocksize=").append(stats.longestblocksize);
  3567. return str;
  3568. }
  3569. // ===============================================================================
  3570. // select thread for handling multiple selects
  3571. struct SelectItem
  3572. {
  3573. ISocket *sock;
  3574. T_SOCKET handle;
  3575. ISocketSelectNotify *nfy;
  3576. byte mode;
  3577. bool del; // only used in select handler method
  3578. bool operator == (const SelectItem & other) const { return sock == other.sock; }
  3579. };
  3580. class SelectItemArray : public StructArrayOf<SelectItem> { };
  3581. class SelectItemArrayP : public StructArrayOf<SelectItem*> { };
  3582. #define SELECT_TIMEOUT_SECS 1 // but it does (TBD)
  3583. #ifdef _WIN32
  3584. // fd_set utility functions
  3585. inline T_FD_SET *cpyfds(T_FD_SET &dst,const T_FD_SET &src)
  3586. {
  3587. unsigned i = src.fd_count;
  3588. dst.fd_count = i;
  3589. while (i--)
  3590. dst.fd_array[i] = src.fd_array[i]; // possibly better as memcpy
  3591. return &dst;
  3592. }
  3593. inline bool findfds(T_FD_SET &s,T_SOCKET h,bool &c)
  3594. {
  3595. unsigned n = s.fd_count;
  3596. unsigned i;
  3597. for(i=0;i<n;i++) {
  3598. if (s.fd_array[i] == h) {
  3599. if (--n)
  3600. s.fd_array[i] = s.fd_array[n]; // remove item
  3601. else
  3602. c = false;
  3603. s.fd_count = n;
  3604. return true;
  3605. }
  3606. }
  3607. return false;
  3608. }
  3609. inline T_SOCKET popfds(T_FD_SET &s)
  3610. {
  3611. unsigned n = s.fd_count;
  3612. T_SOCKET ret;
  3613. if (n) {
  3614. ret = s.fd_array[--n];
  3615. s.fd_count = n;
  3616. }
  3617. else
  3618. ret = NULL;
  3619. return ret;
  3620. }
  3621. #else
  3622. #define _USE_PIPE_FOR_SELECT_TRIGGER
  3623. // not as optimized as windows but I am expecting to convert to using poll anyway
  3624. inline T_FD_SET *cpyfds(T_FD_SET &dst,const T_FD_SET &src)
  3625. {
  3626. memcpy(&dst,&src,sizeof(T_FD_SET));
  3627. return &dst;
  3628. }
  3629. inline bool findfds(T_FD_SET &s,T_SOCKET h,bool &c)
  3630. {
  3631. if ((unsigned)h>=XFD_SETSIZE)
  3632. return false;
  3633. return FD_ISSET(h,&s); // does not remove entry or set termination flag when done
  3634. }
  3635. #endif
  3636. class CSocketBaseThread: public Thread
  3637. {
  3638. protected:
  3639. bool terminating;
  3640. CriticalSection sect;
  3641. Semaphore ticksem;
  3642. std::atomic_uint tickwait;
  3643. unsigned offset;
  3644. bool selectvarschange;
  3645. unsigned waitingchange;
  3646. Semaphore waitingchangesem;
  3647. int validateselecterror;
  3648. unsigned validateerrcount;
  3649. const char *selecttrace;
  3650. unsigned basesize;
  3651. #ifdef _USE_PIPE_FOR_SELECT_TRIGGER
  3652. T_SOCKET dummysock[2];
  3653. #else
  3654. T_SOCKET dummysock;
  3655. #endif
  3656. bool dummysockopen;
  3657. CSocketBaseThread(const char *trc) : Thread("CSocketBaseThread"), tickwait(0)
  3658. {
  3659. }
  3660. ~CSocketBaseThread()
  3661. {
  3662. }
  3663. public:
  3664. void triggerselect()
  3665. {
  3666. if (tickwait)
  3667. ticksem.signal();
  3668. #ifdef _USE_PIPE_FOR_SELECT_TRIGGER
  3669. CriticalBlock block(sect);
  3670. char c = 0;
  3671. if(write(dummysock[1], &c, 1) != 1) {
  3672. int err = ERRNO();
  3673. LOGERR(err,1,"Socket closed during trigger select");
  3674. }
  3675. #else
  3676. closedummy();
  3677. #endif
  3678. }
  3679. void resettrigger()
  3680. {
  3681. #ifdef _USE_PIPE_FOR_SELECT_TRIGGER
  3682. CriticalBlock block(sect);
  3683. char c;
  3684. while((::read(dummysock[0], &c, sizeof(c))) == sizeof(c));
  3685. #endif
  3686. }
  3687. void stop(bool wait)
  3688. {
  3689. terminating = true;
  3690. triggerselect();
  3691. if (wait)
  3692. join();
  3693. }
  3694. bool sockOk(T_SOCKET sock)
  3695. {
  3696. #ifdef _DEBUG
  3697. PROGLOG("CSocketBaseThread: sockOk testing %d",sock);
  3698. #endif
  3699. int t=0;
  3700. socklen_t tl = sizeof(t);
  3701. if (getsockopt(sock, SOL_SOCKET, SO_TYPE, (char *)&t, &tl)!=0) {
  3702. StringBuffer sockstr;
  3703. const char *tracename = sockstr.append((unsigned)sock).str();
  3704. LOGERR2(ERRNO(),1,"CSocketBaseThread select handle");
  3705. return false;
  3706. }
  3707. #ifdef _USE_SELECT
  3708. T_FD_SET fds;
  3709. struct timeval tv;
  3710. CHECKSOCKRANGE(sock);
  3711. XFD_ZERO(&fds);
  3712. FD_SET((unsigned)sock, &fds);
  3713. //FD_SET((unsigned)sock, &except);
  3714. tv.tv_sec = 0;
  3715. tv.tv_usec = 0;
  3716. int rc = ::select( sock + 1, NULL, (fd_set *)&fds, NULL, &tv );
  3717. if (rc<0) {
  3718. StringBuffer sockstr;
  3719. const char *tracename = sockstr.append((unsigned)sock).str();
  3720. LOGERR2(ERRNO(),2,"CSocketBaseThread select handle");
  3721. return false;
  3722. }
  3723. # ifdef _DEBUG
  3724. else if (rc>0)
  3725. PROGLOG("CSocketBaseThread: select handle %d selected(2) %d",sock,rc);
  3726. # endif
  3727. XFD_ZERO(&fds);
  3728. FD_SET((unsigned)sock, &fds);
  3729. tv.tv_sec = 0;
  3730. tv.tv_usec = 0;
  3731. rc = ::select( sock + 1, (fd_set *)&fds, NULL, NULL, &tv );
  3732. if (rc<0) {
  3733. StringBuffer sockstr;
  3734. const char *tracename = sockstr.append((unsigned)sock).str();
  3735. LOGERR2(ERRNO(),3,"CSocketBaseThread select handle");
  3736. return false;
  3737. }
  3738. # ifdef _DEBUG
  3739. else if (rc>0)
  3740. PROGLOG("CSocketBaseThread: select handle %d selected(2) %d",sock,rc);
  3741. # endif
  3742. return true;
  3743. #else
  3744. struct pollfd fds[1];
  3745. fds[0].fd = sock;
  3746. fds[0].events = (POLLINX | POLLOUT);
  3747. fds[0].revents = 0;
  3748. int rc = ::poll(fds, 1, 0);
  3749. if (rc==0)
  3750. return true;
  3751. else if (rc>0)
  3752. {
  3753. if ( !(fds[0].revents & POLLNVAL) ) // MCK - skip POLLERR here
  3754. {
  3755. // PROGLOG("CSocketBaseThread: poll handle %d selected(2) %d",sock,rc);
  3756. return true;
  3757. }
  3758. }
  3759. else
  3760. {
  3761. int err = ERRNO();
  3762. if (err == JSE_INTR)
  3763. return true; // assume ok until next time called
  3764. }
  3765. StringBuffer sockstr;
  3766. const char *tracename = sockstr.append((unsigned)sock).str();
  3767. LOGERR2(ERRNO(),3,"CSocketBaseThread poll handle");
  3768. return false;
  3769. #endif
  3770. }
  3771. virtual void closedummy() = 0;
  3772. };
  3773. class CSocketSelectThread: public CSocketBaseThread
  3774. {
  3775. SelectItemArray items;
  3776. void opendummy()
  3777. {
  3778. CriticalBlock block(sect);
  3779. if (!dummysockopen) {
  3780. #ifdef _USE_PIPE_FOR_SELECT_TRIGGER
  3781. if(pipe(dummysock)) {
  3782. IWARNLOG("CSocketSelectThread: create pipe failed %d",ERRNO());
  3783. return;
  3784. }
  3785. for (unsigned i=0;i<2;i++) {
  3786. int flags = fcntl(dummysock[i], F_GETFL, 0);
  3787. if (flags!=-1) {
  3788. flags |= O_NONBLOCK;
  3789. fcntl(dummysock[i], F_SETFL, flags);
  3790. }
  3791. flags = fcntl(dummysock[i], F_GETFD, 0);
  3792. if (flags!=-1) {
  3793. flags |= FD_CLOEXEC;
  3794. fcntl(dummysock[i], F_SETFD, flags);
  3795. }
  3796. }
  3797. CHECKSOCKRANGE(dummysock[0]);
  3798. #else
  3799. if (IP6preferred)
  3800. dummysock = ::socket(AF_INET6, SOCK_STREAM, PF_INET6);
  3801. else
  3802. dummysock = ::socket(AF_INET, SOCK_STREAM, 0);
  3803. CHECKSOCKRANGE(dummysock);
  3804. #endif
  3805. dummysockopen = true;
  3806. }
  3807. }
  3808. void closedummy()
  3809. {
  3810. CriticalBlock block(sect);
  3811. if (dummysockopen) {
  3812. #ifdef _USE_PIPE_FOR_SELECT_TRIGGER
  3813. #ifdef SOCKTRACE
  3814. PROGLOG("SOCKTRACE: Closing dummy sockets %x %d %x %d (%p)", dummysock[0], dummysock[0], dummysock[1], dummysock[1], this);
  3815. #endif
  3816. ::close(dummysock[0]);
  3817. ::close(dummysock[1]);
  3818. #else
  3819. #ifdef _WIN32
  3820. ::closesocket(dummysock);
  3821. #else
  3822. ::close(dummysock);
  3823. #endif
  3824. #endif
  3825. dummysockopen = false;
  3826. }
  3827. }
  3828. #ifdef _WIN32
  3829. #define HASHTABSIZE 256
  3830. #define HASHNULL (HASHTABSIZE-1)
  3831. #define HASHTABMASK (HASHTABSIZE-1)
  3832. byte hashtab[HASHTABSIZE];
  3833. #define HASHSOCKET(s) ((((unsigned)s)>>2)&HASHTABMASK) // with some knowledge of windows handles
  3834. void inithash()
  3835. {
  3836. memset(&hashtab,HASHNULL,sizeof(hashtab));
  3837. assertex(FD_SETSIZE<255);
  3838. }
  3839. void reinithash()
  3840. { // done this way because index of items changes and hash table not that big
  3841. inithash();
  3842. assertex(items.ordinality()<HASHTABSIZE-1);
  3843. ForEachItemIn(i,items) {
  3844. unsigned h = HASHSOCKET(items.item(i).handle);
  3845. for (;;) {
  3846. if (hashtab[h]==HASHNULL) {
  3847. hashtab[h] = (byte)i;
  3848. break;
  3849. }
  3850. if (++h==HASHTABSIZE)
  3851. h = 0;
  3852. }
  3853. }
  3854. }
  3855. inline SelectItem &findhash(T_SOCKET handle)
  3856. {
  3857. unsigned h = HASHSOCKET(handle);
  3858. unsigned sh = h;
  3859. for (;;) {
  3860. SelectItem &i=items.element(hashtab[h]);
  3861. if (i.handle==handle)
  3862. return i;
  3863. if (++h==HASHTABSIZE)
  3864. h = 0;
  3865. assertex(h!=sh);
  3866. }
  3867. }
  3868. inline void processfds(T_FD_SET &s,byte mode,SelectItemArray &tonotify)
  3869. {
  3870. for (;;) {
  3871. T_SOCKET sock = popfds(s);
  3872. if (!sock)
  3873. break;
  3874. if (sock!=dummysock)
  3875. {
  3876. SelectItem &si = findhash(sock);
  3877. if (!si.del)
  3878. {
  3879. tonotify.append(si); // nb copies
  3880. SelectItem &itm = tonotify.element(tonotify.length()-1);
  3881. itm.nfy->Link();
  3882. itm.sock->Link();
  3883. itm.mode = mode;
  3884. }
  3885. }
  3886. }
  3887. }
  3888. #endif
  3889. public:
  3890. IMPLEMENT_IINTERFACE;
  3891. CSocketSelectThread(const char *trc)
  3892. : CSocketBaseThread("CSocketSelectThread")
  3893. {
  3894. dummysockopen = false;
  3895. opendummy();
  3896. terminating = false;
  3897. waitingchange = 0;
  3898. selectvarschange = false;
  3899. validateselecterror = 0;
  3900. validateerrcount = 0;
  3901. offset = 0;
  3902. selecttrace = trc;
  3903. basesize = 0;
  3904. #ifdef _WIN32
  3905. inithash();
  3906. #endif
  3907. }
  3908. ~CSocketSelectThread()
  3909. {
  3910. closedummy();
  3911. ForEachItemIn(i,items) {
  3912. // Release/dtors should not throw but leaving try/catch here until all paths checked
  3913. try {
  3914. SelectItem &si = items.element(i);
  3915. si.nfy->Release();
  3916. si.sock->Release();
  3917. }
  3918. catch (IException *e) {
  3919. EXCLOG(e,"~CSocketSelectThread");
  3920. e->Release();
  3921. }
  3922. }
  3923. }
  3924. Owned<IException> termexcept;
  3925. void updateItems()
  3926. {
  3927. // must be in CriticalBlock block(sect);
  3928. unsigned n = items.ordinality();
  3929. #ifdef _WIN32
  3930. bool hashupdateneeded = (n!=basesize); // additions all come at end
  3931. #endif
  3932. for (unsigned i=0;i<n;) {
  3933. SelectItem &si = items.element(i);
  3934. if (si.del) {
  3935. // Release/dtors should not throw but leaving try/catch here until all paths checked
  3936. try {
  3937. #ifdef SOCKTRACE
  3938. PROGLOG("CSocketSelectThread::updateItems release %d",si.handle);
  3939. #endif
  3940. si.nfy->Release();
  3941. si.sock->Release();
  3942. }
  3943. catch (IException *e) {
  3944. EXCLOG(e,"CSocketSelectThread::updateItems");
  3945. e->Release();
  3946. }
  3947. // NOTE: si is a reference, put last item into remove slot
  3948. n--;
  3949. if (i<n)
  3950. si = items.item(n);
  3951. items.remove(n);
  3952. #ifdef _WIN32
  3953. hashupdateneeded = true;
  3954. #endif
  3955. }
  3956. else
  3957. i++;
  3958. }
  3959. assertex(n<=XFD_SETSIZE-1);
  3960. #ifdef _WIN32
  3961. if (hashupdateneeded)
  3962. reinithash();
  3963. #endif
  3964. basesize = n;
  3965. }
  3966. bool checkSocks()
  3967. {
  3968. bool ret = false;
  3969. ForEachItemIn(i,items) {
  3970. SelectItem &si = items.element(i);
  3971. if (si.del)
  3972. ret = true; // maybe that bad one
  3973. else if (!sockOk(si.handle)) {
  3974. si.del = true;
  3975. ret = true;
  3976. }
  3977. }
  3978. return ret;
  3979. }
  3980. bool remove(ISocket *sock)
  3981. {
  3982. if (terminating)
  3983. return false;
  3984. CriticalBlock block(sect);
  3985. if (sock==NULL) { // wait until no changes outstanding
  3986. while (selectvarschange) {
  3987. waitingchange++;
  3988. CriticalUnblock unblock(sect);
  3989. waitingchangesem.wait();
  3990. }
  3991. return true;
  3992. }
  3993. ForEachItemIn(i,items) {
  3994. SelectItem &si = items.element(i);
  3995. if (!si.del&&(si.sock==sock)) {
  3996. si.del = true;
  3997. selectvarschange = true;
  3998. triggerselect();
  3999. return true;
  4000. }
  4001. }
  4002. return false;
  4003. }
  4004. bool add(ISocket *sock,unsigned mode,ISocketSelectNotify *nfy)
  4005. {
  4006. // maybe check once to prevent 1st delay? TBD
  4007. CriticalBlock block(sect);
  4008. unsigned n=0;
  4009. ForEachItemIn(i,items) {
  4010. SelectItem &si = items.element(i);
  4011. if (!si.del) {
  4012. if (si.sock==sock) {
  4013. si.del = true;
  4014. }
  4015. else
  4016. n++;
  4017. }
  4018. }
  4019. if (n>=XFD_SETSIZE-1) // leave 1 spare
  4020. return false;
  4021. SelectItem sn;
  4022. sn.nfy = LINK(nfy);
  4023. sn.sock = LINK(sock);
  4024. sn.mode = (byte)mode;
  4025. sn.handle = (T_SOCKET)sock->OShandle();
  4026. CHECKSOCKRANGE(sn.handle);
  4027. sn.del = false;
  4028. items.append(sn);
  4029. selectvarschange = true;
  4030. triggerselect();
  4031. return true;
  4032. }
  4033. void updateSelectVars(T_FD_SET &rdfds,T_FD_SET &wrfds,T_FD_SET &exfds,bool &isrd,bool &iswr,bool &isex,unsigned &ni,T_SOCKET &max_sockid)
  4034. {
  4035. CriticalBlock block(sect);
  4036. selectvarschange = false;
  4037. if (waitingchange) {
  4038. waitingchangesem.signal(waitingchange);
  4039. waitingchange = 0;
  4040. }
  4041. if (validateselecterror) { // something went wrong so check sockets
  4042. validateerrcount++;
  4043. if (!checkSocks()) {
  4044. // bad socket not found
  4045. PROGLOG("CSocketSelectThread::updateSelectVars cannot find socket error");
  4046. if (validateerrcount>10)
  4047. throw MakeStringException(-1,"CSocketSelectThread:Socket select error %d",validateselecterror);
  4048. }
  4049. }
  4050. else
  4051. validateerrcount = 0;
  4052. updateItems();
  4053. XFD_ZERO( &rdfds );
  4054. XFD_ZERO( &wrfds );
  4055. XFD_ZERO( &exfds );
  4056. isrd=false;
  4057. iswr=false;
  4058. isex=false;
  4059. #ifdef _USE_PIPE_FOR_SELECT_TRIGGER
  4060. max_sockid=dummysockopen?dummysock[0]:0;
  4061. #else
  4062. opendummy();
  4063. max_sockid=dummysockopen?dummysock:0;
  4064. #endif
  4065. ni = items.ordinality();
  4066. #ifdef _WIN32
  4067. if (offset>=ni)
  4068. #endif
  4069. offset = 0;
  4070. unsigned j = offset;
  4071. ForEachItemIn(i, items) {
  4072. SelectItem &si = items.element(j);
  4073. j++;
  4074. if (j==ni)
  4075. j = 0;
  4076. if (si.mode & SELECTMODE_READ) {
  4077. FD_SET( si.handle, &rdfds );
  4078. isrd = true;
  4079. }
  4080. if (si.mode & SELECTMODE_WRITE) {
  4081. FD_SET( si.handle, &wrfds );
  4082. iswr = true;
  4083. }
  4084. if (si.mode & SELECTMODE_EXCEPT) {
  4085. FD_SET( si.handle, &exfds );
  4086. isex = true;
  4087. }
  4088. max_sockid=std::max(si.handle, max_sockid);
  4089. }
  4090. if (dummysockopen) {
  4091. #ifdef _USE_PIPE_FOR_SELECT_TRIGGER
  4092. FD_SET( dummysock[0], &rdfds );
  4093. isrd = true;
  4094. #else
  4095. FD_SET( dummysock, &exfds );
  4096. isex = true;
  4097. #endif
  4098. }
  4099. validateselecterror = 0;
  4100. max_sockid++;
  4101. #ifdef SOCKTRACE
  4102. PROGLOG("SOCKTRACE: selecting on %d sockets",ni);
  4103. #endif
  4104. }
  4105. int run()
  4106. {
  4107. try
  4108. {
  4109. T_FD_SET rdfds;
  4110. T_FD_SET wrfds;
  4111. T_FD_SET exfds;
  4112. timeval selecttimeout;
  4113. bool isrd = false;
  4114. bool iswr = false;
  4115. bool isex = false;
  4116. T_SOCKET maxsockid = 0;
  4117. unsigned ni = 0;
  4118. selectvarschange = true;
  4119. unsigned numto = 0;
  4120. unsigned lastnumto = 0;
  4121. unsigned totnum = 0;
  4122. unsigned total = 0;
  4123. while (!terminating)
  4124. {
  4125. selecttimeout.tv_sec = SELECT_TIMEOUT_SECS; // linux modifies so initialize inside loop
  4126. selecttimeout.tv_usec = 0;
  4127. if (selectvarschange)
  4128. {
  4129. updateSelectVars(rdfds,wrfds,exfds,isrd,iswr,isex,ni,maxsockid);
  4130. }
  4131. if (ni==0)
  4132. {
  4133. validateerrcount = 0;
  4134. tickwait++;
  4135. if(!selectvarschange&&!terminating)
  4136. ticksem.wait(SELECT_TIMEOUT_SECS*1000);
  4137. tickwait--;
  4138. continue;
  4139. }
  4140. T_FD_SET rs;
  4141. T_FD_SET ws;
  4142. T_FD_SET es;
  4143. T_FD_SET *rsp = isrd?cpyfds(rs,rdfds):NULL;
  4144. T_FD_SET *wsp = iswr?cpyfds(ws,wrfds):NULL;
  4145. T_FD_SET *esp = isex?cpyfds(es,exfds):NULL;
  4146. int n = ::select(maxsockid,(fd_set *)rsp,(fd_set *)wsp,(fd_set *)esp,&selecttimeout); // first parameter needed for posix
  4147. if (terminating)
  4148. break;
  4149. if (n < 0)
  4150. {
  4151. CriticalBlock block(sect);
  4152. int err = ERRNO();
  4153. if (err != JSE_INTR)
  4154. {
  4155. if (dummysockopen)
  4156. {
  4157. LOGERR(err,12,"CSocketSelectThread select error"); // should cache error ?
  4158. validateselecterror = err;
  4159. #ifndef _USE_PIPE_FOR_SELECT_TRIGGER
  4160. closedummy(); // just in case was culprit
  4161. #endif
  4162. }
  4163. selectvarschange = true;
  4164. continue;
  4165. }
  4166. n = 0;
  4167. }
  4168. else if (n>0)
  4169. {
  4170. validateerrcount = 0;
  4171. numto = 0;
  4172. lastnumto = 0;
  4173. total += n;
  4174. totnum++;
  4175. SelectItemArray tonotify;
  4176. {
  4177. CriticalBlock block(sect);
  4178. #ifdef _WIN32
  4179. if (isrd)
  4180. processfds(rs,SELECTMODE_READ,tonotify);
  4181. if (iswr)
  4182. processfds(ws,SELECTMODE_WRITE,tonotify);
  4183. if (isex)
  4184. processfds(es,SELECTMODE_EXCEPT,tonotify);
  4185. #else
  4186. unsigned i;
  4187. SelectItem *si = items.getArray(offset);
  4188. SelectItem *sie = items.getArray(ni-1)+1;
  4189. bool r = isrd;
  4190. bool w = iswr;
  4191. bool e = isex;
  4192. #ifdef _USE_PIPE_FOR_SELECT_TRIGGER
  4193. if (r&&dummysockopen&&findfds(rs,dummysock[0],r))
  4194. {
  4195. resettrigger();
  4196. --n;
  4197. }
  4198. #endif
  4199. for (i=0;(n>0)&&(i<ni);i++)
  4200. {
  4201. unsigned addMode = 0;
  4202. if (r&&findfds(rs,si->handle,r))
  4203. {
  4204. if (!si->del)
  4205. addMode = SELECTMODE_READ;
  4206. --n;
  4207. }
  4208. if (w&&findfds(ws,si->handle,w))
  4209. {
  4210. if (!si->del)
  4211. addMode = SELECTMODE_WRITE;
  4212. --n;
  4213. }
  4214. if (e&&findfds(es,si->handle,e))
  4215. {
  4216. if (!si->del)
  4217. addMode = SELECTMODE_EXCEPT;
  4218. --n;
  4219. }
  4220. if (addMode)
  4221. {
  4222. tonotify.append(*si);
  4223. SelectItem &itm = tonotify.element(tonotify.length()-1);
  4224. itm.nfy->Link();
  4225. itm.sock->Link();
  4226. itm.mode = addMode;
  4227. }
  4228. si++;
  4229. if (si==sie)
  4230. si = items.getArray();
  4231. }
  4232. #endif
  4233. }
  4234. ForEachItemIn(j,tonotify)
  4235. {
  4236. const SelectItem &si = tonotify.item(j);
  4237. try
  4238. {
  4239. si.nfy->notifySelected(si.sock,si.mode); // ignore return
  4240. }
  4241. catch (IException *e)
  4242. { // should be acted upon by notifySelected
  4243. // could also not throw until after handling all events ...
  4244. EXCLOG(e,"CSocketSelectThread notifySelected");
  4245. throw ;
  4246. }
  4247. // Release/dtors should not throw but leaving try/catch here until all paths checked
  4248. try
  4249. {
  4250. si.nfy->Release();
  4251. si.sock->Release();
  4252. }
  4253. catch (IException *e)
  4254. {
  4255. EXCLOG(e,"CSocketSelectThread nfy/sock Release");
  4256. e->Release();
  4257. }
  4258. }
  4259. }
  4260. else
  4261. {
  4262. validateerrcount = 0;
  4263. if ((++numto>=lastnumto*2))
  4264. {
  4265. lastnumto = numto;
  4266. if (selecttrace&&(numto>4))
  4267. PROGLOG("%s: Select Idle(%d), %d,%d,%0.2f",selecttrace,numto,totnum,total,totnum?((double)total/(double)totnum):0.0);
  4268. }
  4269. /*
  4270. if (numto&&(numto%100))
  4271. {
  4272. CriticalBlock block(sect);
  4273. if (!selectvarschange)
  4274. selectvarschange = checkSocks();
  4275. }
  4276. */
  4277. }
  4278. if (++offset>=ni)
  4279. offset = 0;
  4280. }
  4281. }
  4282. catch (IException *e)
  4283. {
  4284. EXCLOG(e,"CSocketSelectThread");
  4285. termexcept.setown(e);
  4286. }
  4287. CriticalBlock block(sect);
  4288. try
  4289. {
  4290. updateItems();
  4291. }
  4292. catch (IException *e)
  4293. {
  4294. EXCLOG(e,"CSocketSelectThread(2)");
  4295. if (!termexcept)
  4296. termexcept.setown(e);
  4297. else
  4298. e->Release();
  4299. }
  4300. return 0;
  4301. }
  4302. };
  4303. class CSocketSelectHandler: implements ISocketSelectHandler, public CInterface
  4304. {
  4305. CIArrayOf<CSocketSelectThread> threads;
  4306. CriticalSection sect;
  4307. bool started;
  4308. std::atomic<bool> stopped;
  4309. StringAttr selecttrace;
  4310. public:
  4311. IMPLEMENT_IINTERFACE;
  4312. CSocketSelectHandler(const char *trc)
  4313. : started(false), stopped(false), selecttrace(trc)
  4314. {
  4315. }
  4316. ~CSocketSelectHandler()
  4317. {
  4318. stop(true);
  4319. threads.kill();
  4320. }
  4321. void start()
  4322. {
  4323. CriticalBlock block(sect);
  4324. if (!started) {
  4325. started = true;
  4326. ForEachItemIn(i,threads) {
  4327. threads.item(i).start();
  4328. }
  4329. }
  4330. }
  4331. void add(ISocket *sock,unsigned mode,ISocketSelectNotify *nfy)
  4332. {
  4333. CriticalBlock block(sect);
  4334. if (stopped)
  4335. return;
  4336. for (;;) {
  4337. bool added=false;
  4338. ForEachItemIn(i,threads) {
  4339. if (added)
  4340. threads.item(i).remove(sock);
  4341. else
  4342. added = threads.item(i).add(sock,mode,nfy);
  4343. }
  4344. if (added)
  4345. return;
  4346. CSocketSelectThread *thread = new CSocketSelectThread(selecttrace);
  4347. threads.append(*thread);
  4348. if (started)
  4349. thread->start();
  4350. }
  4351. }
  4352. void remove(ISocket *sock)
  4353. {
  4354. CriticalBlock block(sect);
  4355. ForEachItemIn(i,threads) {
  4356. if (threads.item(i).remove(sock)&&sock)
  4357. break;
  4358. }
  4359. }
  4360. void stop(bool wait)
  4361. {
  4362. IException *e=NULL;
  4363. CriticalBlock block(sect);
  4364. stopped = true;
  4365. unsigned i = 0;
  4366. while (i<threads.ordinality()) {
  4367. CSocketSelectThread &t=threads.item(i);
  4368. {
  4369. CriticalUnblock unblock(sect);
  4370. t.stop(wait); // not quite as quick as could be if wait true
  4371. }
  4372. if (wait && !e && t.termexcept)
  4373. e = t.termexcept.getClear();
  4374. i++;
  4375. }
  4376. #if 0 // don't throw error as too late
  4377. if (e)
  4378. throw e;
  4379. #else
  4380. ::Release(e);
  4381. #endif
  4382. }
  4383. };
  4384. #ifdef _HAS_EPOLL_SUPPORT
  4385. # define SOCK_ADDED 0x1
  4386. # define SOCK_REMOVED 0x2
  4387. class CSocketEpollThread: public CSocketBaseThread
  4388. {
  4389. int epfd;
  4390. SelectItem *sidummy;
  4391. SelectItemArrayP items;
  4392. struct epoll_event *epevents;
  4393. unsigned hdlPerThrd;
  4394. void epoll_op(int efd, int op, SelectItem *si, unsigned int event_mask)
  4395. {
  4396. int fd = si->handle;
  4397. int srtn;
  4398. struct epoll_event event;
  4399. // write all bytes to eliminate uninitialized warnings
  4400. memset(&event, 0, sizeof(event));
  4401. event.events = event_mask;
  4402. event.data.ptr = si;
  4403. # ifdef EPOLLTRACE
  4404. DBGLOG("EPOLL: op(%d) fd %d to epfd %d", op, fd, efd);
  4405. # endif
  4406. srtn = ::epoll_ctl(efd, op, fd, &event);
  4407. // if another thread closed fd before here don't fail
  4408. if ( (srtn < 0) && (op != EPOLL_CTL_DEL) ){
  4409. int err = ERRNO();
  4410. IWARNLOG("epoll_ctl failed op:%d, fd:%d, err=%d", op, fd, err);
  4411. }
  4412. }
  4413. void opendummy()
  4414. {
  4415. CriticalBlock block(sect);
  4416. if (!dummysockopen)
  4417. {
  4418. sidummy = new SelectItem;
  4419. sidummy->sock = nullptr;
  4420. sidummy->nfy = nullptr;
  4421. sidummy->del = true; // so its not added to tonotify ...
  4422. sidummy->mode = 0;
  4423. #ifdef _USE_PIPE_FOR_SELECT_TRIGGER
  4424. if(pipe(dummysock))
  4425. {
  4426. IWARNLOG("CSocketEpollThread: create pipe failed %d",ERRNO());
  4427. return;
  4428. }
  4429. for (unsigned i=0;i<2;i++)
  4430. {
  4431. int flags = fcntl(dummysock[i], F_GETFL, 0);
  4432. if (flags!=-1)
  4433. {
  4434. flags |= O_NONBLOCK;
  4435. fcntl(dummysock[i], F_SETFL, flags);
  4436. }
  4437. flags = fcntl(dummysock[i], F_GETFD, 0);
  4438. if (flags!=-1)
  4439. {
  4440. flags |= FD_CLOEXEC;
  4441. fcntl(dummysock[i], F_SETFD, flags);
  4442. }
  4443. }
  4444. sidummy->handle = dummysock[0];
  4445. epoll_op(epfd, EPOLL_CTL_ADD, sidummy, EPOLLINX);
  4446. #else
  4447. if (IP6preferred)
  4448. dummysock = ::socket(AF_INET6, SOCK_STREAM, PF_INET6);
  4449. else
  4450. dummysock = ::socket(AF_INET, SOCK_STREAM, 0);
  4451. // added EPOLLIN and EPOLLRDHUP also because cannot find anywhere MSG_OOB is sent
  4452. // added here to match existing select() code above which sets
  4453. // the except fd_set mask.
  4454. sidummy->handle = dummysock;
  4455. epoll_op(epfd, EPOLL_CTL_ADD, sidummy, (EPOLLINX | EPOLLPRI));
  4456. #endif
  4457. dummysockopen = true;
  4458. }
  4459. }
  4460. void closedummy()
  4461. {
  4462. CriticalBlock block(sect);
  4463. if (dummysockopen)
  4464. {
  4465. epoll_op(epfd, EPOLL_CTL_DEL, sidummy, 0);
  4466. #ifdef _USE_PIPE_FOR_SELECT_TRIGGER
  4467. #ifdef SOCKTRACE
  4468. PROGLOG("SOCKTRACE: Closing dummy sockets %x %d %x %d (%p)", dummysock[0], dummysock[0], dummysock[1], dummysock[1], this);
  4469. #endif
  4470. ::close(dummysock[0]);
  4471. ::close(dummysock[1]);
  4472. #else
  4473. ::close(dummysock);
  4474. #endif
  4475. delete sidummy;
  4476. dummysockopen = false;
  4477. }
  4478. }
  4479. void delSelItem(SelectItem *si)
  4480. {
  4481. epoll_op(epfd, EPOLL_CTL_DEL, si, 0);
  4482. // Release/dtors should not throw but leaving try/catch here until all paths checked
  4483. try
  4484. {
  4485. si->nfy->Release();
  4486. si->sock->Release();
  4487. delete si;
  4488. }
  4489. catch (IException *e)
  4490. {
  4491. EXCLOG(e,"CSocketEpollThread::delSelItem()");
  4492. e->Release();
  4493. }
  4494. }
  4495. void delSelItemPos(SelectItem *si, unsigned pos)
  4496. {
  4497. unsigned last = items.ordinality();
  4498. delSelItem(si);
  4499. last--;
  4500. if (pos < last)
  4501. items.swap(pos, last);
  4502. items.remove(last);
  4503. }
  4504. public:
  4505. IMPLEMENT_IINTERFACE;
  4506. CSocketEpollThread(const char *trc, unsigned _hdlPerThrd)
  4507. : CSocketBaseThread("CSocketEpollThread")
  4508. {
  4509. dummysockopen = false;
  4510. terminating = false;
  4511. waitingchange = 0;
  4512. selectvarschange = false;
  4513. validateselecterror = 0;
  4514. validateerrcount = 0;
  4515. offset = 0;
  4516. selecttrace = trc;
  4517. hdlPerThrd = _hdlPerThrd;
  4518. epfd = ::epoll_create(1); // NB: arg is not used in newer kernels
  4519. if (epfd < 0)
  4520. {
  4521. int err = ERRNO();
  4522. LOGERR(err,1,"epoll_create()");
  4523. THROWJSOCKEXCEPTION2(err);
  4524. }
  4525. # ifdef FD_CLOEXEC
  4526. int epflags = fcntl(epfd, F_GETFD, 0);
  4527. if (epflags != -1)
  4528. {
  4529. epflags |= FD_CLOEXEC;
  4530. fcntl(epfd, F_SETFD, epflags);
  4531. }
  4532. # endif
  4533. # ifdef EPOLLTRACE
  4534. DBGLOG("CSocketEpollThread: creating epoll fd %d", epfd );
  4535. # endif
  4536. try
  4537. {
  4538. epevents = new struct epoll_event[MAX_RET_EVENTS];
  4539. }
  4540. catch (const std::bad_alloc &e)
  4541. {
  4542. int err = ERRNO();
  4543. LOGERR(err,1,"epevents alloc()");
  4544. THROWJSOCKEXCEPTION2(err);
  4545. }
  4546. opendummy();
  4547. }
  4548. ~CSocketEpollThread()
  4549. {
  4550. closedummy();
  4551. ForEachItemIn(i, items)
  4552. {
  4553. SelectItem *si = items.element(i);
  4554. delSelItem(si);
  4555. }
  4556. if (epfd >= 0)
  4557. {
  4558. # ifdef EPOLLTRACE
  4559. DBGLOG("EPOLL: closing epfd %d", epfd);
  4560. # endif
  4561. ::close(epfd);
  4562. epfd = -1;
  4563. delete [] epevents;
  4564. }
  4565. }
  4566. Owned<IException> termexcept;
  4567. bool checkSocks()
  4568. {
  4569. bool ret = false;
  4570. // must be holding CriticalBlock (sect)
  4571. unsigned n = items.ordinality();
  4572. for (unsigned i=0;i<n;)
  4573. {
  4574. SelectItem *si = items.element(i);
  4575. if (!sockOk(si->handle))
  4576. {
  4577. delSelItemPos(si, i);
  4578. n--;
  4579. ret = true;
  4580. }
  4581. else
  4582. i++;
  4583. }
  4584. return ret;
  4585. }
  4586. bool removeSock(ISocket *sock)
  4587. {
  4588. // must be holding CriticalBlock (sect)
  4589. unsigned n = items.ordinality();
  4590. for (unsigned i=0;i<n;)
  4591. {
  4592. SelectItem *si = items.element(i);
  4593. if (si->sock==sock)
  4594. {
  4595. delSelItemPos(si, i);
  4596. n--;
  4597. return true;
  4598. }
  4599. else
  4600. i++;
  4601. }
  4602. return false;
  4603. }
  4604. bool remove(ISocket *sock)
  4605. {
  4606. CriticalBlock block(sect);
  4607. if (terminating)
  4608. return false;
  4609. if (sock==NULL)
  4610. { // wait until no changes outstanding
  4611. while (selectvarschange)
  4612. {
  4613. waitingchange++;
  4614. CriticalUnblock unblock(sect);
  4615. waitingchangesem.wait();
  4616. }
  4617. return true;
  4618. }
  4619. if (removeSock(sock))
  4620. {
  4621. selectvarschange = true;
  4622. // NB: could set terminating here if no more hdls on
  4623. // this thread and at least one other thread is present
  4624. triggerselect();
  4625. return true;
  4626. }
  4627. return false;
  4628. }
  4629. unsigned add(ISocket *sock,unsigned mode,ISocketSelectNotify *nfy)
  4630. {
  4631. if ( !sock || !nfy ||
  4632. !(mode & (SELECTMODE_READ|SELECTMODE_WRITE|SELECTMODE_EXCEPT)) )
  4633. {
  4634. IWARNLOG("EPOLL: adding fd but sock or nfy is NULL or mode is empty");
  4635. dbgassertex(false);
  4636. return 0;
  4637. }
  4638. CriticalBlock block(sect);
  4639. if (terminating)
  4640. return 0;
  4641. unsigned rm = 0;
  4642. if (removeSock(sock))
  4643. rm = SOCK_REMOVED;
  4644. unsigned n = items.ordinality();
  4645. // new handler thread
  4646. if (n >= hdlPerThrd)
  4647. return (0|rm);
  4648. SelectItem *sn = new SelectItem;
  4649. sn->nfy = LINK(nfy);
  4650. sn->sock = LINK(sock);
  4651. sn->mode = (byte)mode;
  4652. sn->handle = (T_SOCKET)sock->OShandle();
  4653. sn->del = false;
  4654. items.append(sn);
  4655. unsigned int ep_mode = 0;
  4656. if (mode & SELECTMODE_READ)
  4657. ep_mode |= EPOLLINX;
  4658. if (mode & SELECTMODE_WRITE)
  4659. ep_mode |= EPOLLOUT;
  4660. if (mode & SELECTMODE_EXCEPT)
  4661. ep_mode |= EPOLLPRI;
  4662. epoll_op(epfd, EPOLL_CTL_ADD, sn, ep_mode);
  4663. selectvarschange = true;
  4664. triggerselect();
  4665. return (SOCK_ADDED|rm);
  4666. }
  4667. void updateEpollVars(unsigned &ni)
  4668. {
  4669. CriticalBlock block(sect);
  4670. selectvarschange = false;
  4671. if (waitingchange)
  4672. {
  4673. waitingchangesem.signal(waitingchange);
  4674. waitingchange = 0;
  4675. }
  4676. if (validateselecterror)
  4677. { // something went wrong so check sockets
  4678. validateerrcount++;
  4679. if (!checkSocks())
  4680. {
  4681. // bad socket not found
  4682. IWARNLOG("CSocketEpollThread::updateEpollVars cannot find socket error");
  4683. if (validateerrcount>10)
  4684. throw MakeStringException(-1,"CSocketEpollThread:Socket epoll error %d",validateselecterror);
  4685. }
  4686. }
  4687. else
  4688. validateerrcount = 0;
  4689. #ifndef _USE_PIPE_FOR_SELECT_TRIGGER
  4690. opendummy();
  4691. #endif
  4692. ni = items.ordinality();
  4693. validateselecterror = 0;
  4694. }
  4695. int run()
  4696. {
  4697. try
  4698. {
  4699. unsigned ni = 0;
  4700. unsigned numto = 0;
  4701. unsigned lastnumto = 0;
  4702. unsigned totnum = 0;
  4703. unsigned total = 0;
  4704. selectvarschange = true;
  4705. while (!terminating)
  4706. {
  4707. if (selectvarschange)
  4708. updateEpollVars(ni);
  4709. if (ni==0)
  4710. {
  4711. validateerrcount = 0;
  4712. tickwait++;
  4713. if(!selectvarschange&&!terminating)
  4714. ticksem.wait(SELECT_TIMEOUT_SECS*1000);
  4715. tickwait--;
  4716. continue;
  4717. }
  4718. // poll for any events ...
  4719. int err = 0;
  4720. int n = ::epoll_wait(epfd, epevents, 1, 1000);
  4721. if (n < 0)
  4722. err = ERRNO();
  4723. # ifdef EPOLLTRACE
  4724. if(n > 0)
  4725. DBGLOG("EPOLL: after epoll_wait(), n = %d, ni = %d", n, ni);
  4726. # endif
  4727. if (terminating)
  4728. break;
  4729. if (n < 0)
  4730. {
  4731. CriticalBlock block(sect);
  4732. if (err != JSE_INTR)
  4733. {
  4734. if (dummysockopen)
  4735. {
  4736. LOGERR(err,12,"CSocketEpollThread epoll error"); // should cache error ?
  4737. validateselecterror = err;
  4738. #ifndef _USE_PIPE_FOR_SELECT_TRIGGER
  4739. closedummy(); // just in case was culprit
  4740. #endif
  4741. }
  4742. selectvarschange = true;
  4743. continue;
  4744. }
  4745. }
  4746. else if (n>0)
  4747. {
  4748. validateerrcount = 0;
  4749. numto = 0;
  4750. lastnumto = 0;
  4751. total += n;
  4752. totnum++;
  4753. SelectItemArray tonotify;
  4754. {
  4755. CriticalBlock block(sect);
  4756. // retrieve events, without waiting, while holding CS ...
  4757. int n2 = ::epoll_wait(epfd, epevents, MAX_RET_EVENTS, 0);
  4758. for (int j=0;j<n2;j++)
  4759. {
  4760. int tfd = -1;
  4761. SelectItem *epsi = (SelectItem *)epevents[j].data.ptr;
  4762. if (epsi)
  4763. tfd = epsi->handle;
  4764. # ifdef EPOLLTRACE
  4765. DBGLOG("EPOLL: j = %d, fd = %d, emask = %u", j, tfd, epevents[j].events);
  4766. # endif
  4767. if (tfd >= 0)
  4768. {
  4769. # ifdef _USE_PIPE_FOR_SELECT_TRIGGER
  4770. if ( (dummysockopen) && (tfd == dummysock[0]) )
  4771. {
  4772. resettrigger();
  4773. continue;
  4774. }
  4775. # endif
  4776. unsigned int ep_mode = 0;
  4777. if (epevents[j].events & (EPOLLINX | EPOLLHUP | EPOLLERR))
  4778. ep_mode |= SELECTMODE_READ;
  4779. if (epevents[j].events & EPOLLOUT)
  4780. ep_mode |= SELECTMODE_WRITE;
  4781. if (epevents[j].events & EPOLLPRI)
  4782. ep_mode |= SELECTMODE_EXCEPT;
  4783. if (ep_mode != 0)
  4784. {
  4785. tonotify.append(*epsi);
  4786. SelectItem &itm = tonotify.element(tonotify.length()-1);
  4787. itm.nfy->Link();
  4788. itm.sock->Link();
  4789. #ifdef _TRACELINKCLOSED
  4790. // temporary, to help diagnose spurious socket closes (hpcc-15043)
  4791. // currently no implementation of notifySelected() uses the mode
  4792. // argument so we can pass in the epoll events mask and log that
  4793. // if there is no data and the socket gets closed
  4794. itm.mode = epevents[j].events;
  4795. #else
  4796. itm.mode = ep_mode;
  4797. #endif
  4798. }
  4799. }
  4800. }
  4801. }
  4802. Owned<IException> nfyexcept;
  4803. ForEachItemIn(j,tonotify)
  4804. {
  4805. const SelectItem &si = tonotify.item(j);
  4806. try
  4807. {
  4808. si.nfy->notifySelected(si.sock,si.mode); // ignore return
  4809. }
  4810. catch (IException *e)
  4811. { // should be acted upon by notifySelected
  4812. // Don't throw until after handling all events ...
  4813. EXCLOG(e,"CSocketEpollThread notifySelected");
  4814. if (!nfyexcept)
  4815. nfyexcept.setown(e);
  4816. else
  4817. e->Release();
  4818. }
  4819. // Release/dtors should not throw but leaving try/catch here until all paths checked
  4820. try
  4821. {
  4822. si.nfy->Release();
  4823. si.sock->Release();
  4824. }
  4825. catch (IException *e)
  4826. {
  4827. EXCLOG(e,"CSocketEpollThread nfy/sock Release");
  4828. e->Release();
  4829. }
  4830. }
  4831. if (nfyexcept)
  4832. throw nfyexcept.getClear();
  4833. }
  4834. else
  4835. {
  4836. validateerrcount = 0;
  4837. if ((++numto>=lastnumto*2))
  4838. {
  4839. lastnumto = numto;
  4840. if (selecttrace&&(numto>4))
  4841. PROGLOG("%s: Epoll Idle(%d), %d,%d,%0.2f",selecttrace,numto,totnum,total,totnum?((double)total/(double)totnum):0.0);
  4842. }
  4843. /*
  4844. if (numto&&(numto%100))
  4845. {
  4846. CriticalBlock block(sect);
  4847. if (!selectvarschange)
  4848. selectvarschange = checkSocks();
  4849. }
  4850. */
  4851. }
  4852. }
  4853. }
  4854. catch (IException *e)
  4855. {
  4856. EXCLOG(e,"CSocketEpollThread");
  4857. termexcept.setown(e);
  4858. }
  4859. return 0;
  4860. }
  4861. };
  4862. class CSocketEpollHandler: implements ISocketSelectHandler, public CInterface
  4863. {
  4864. CIArrayOf<CSocketEpollThread> threads;
  4865. CriticalSection sect;
  4866. bool started;
  4867. std::atomic<bool> stopped;
  4868. StringAttr epolltrace;
  4869. unsigned hdlPerThrd;
  4870. public:
  4871. IMPLEMENT_IINTERFACE;
  4872. CSocketEpollHandler(const char *trc, unsigned _hdlPerThrd)
  4873. : started(false), stopped(false), epolltrace(trc), hdlPerThrd(_hdlPerThrd)
  4874. {
  4875. }
  4876. ~CSocketEpollHandler()
  4877. {
  4878. stop(true);
  4879. threads.kill();
  4880. }
  4881. void start()
  4882. {
  4883. CriticalBlock block(sect);
  4884. if (!started)
  4885. {
  4886. started = true;
  4887. ForEachItemIn(i,threads)
  4888. {
  4889. threads.item(i).start();
  4890. }
  4891. }
  4892. }
  4893. void add(ISocket *sock,unsigned mode,ISocketSelectNotify *nfy)
  4894. {
  4895. if ( !sock || !nfy ||
  4896. !(mode & (SELECTMODE_READ|SELECTMODE_WRITE|SELECTMODE_EXCEPT)) )
  4897. throw MakeStringException(-1,"CSocketEpollHandler::add() invalid sock or nfy or mode");
  4898. CriticalBlock block(sect);
  4899. if (stopped)
  4900. return;
  4901. // Create new handler thread if current one has hdlPerThrd fds.
  4902. // epoll() handles many fds faster than select so this would
  4903. // seem not as important, but we are still serializing on
  4904. // nfy events and spreading those over threads may help,
  4905. // especially with SSL as avail_read() could block more.
  4906. unsigned addrm = 0;
  4907. ForEachItemIn(i,threads)
  4908. {
  4909. if (!(addrm & SOCK_ADDED))
  4910. {
  4911. addrm |= threads.item(i).add(sock,mode,nfy);
  4912. if (addrm & (SOCK_ADDED | SOCK_REMOVED))
  4913. return;
  4914. }
  4915. else if (!(addrm & SOCK_REMOVED))
  4916. {
  4917. if (threads.item(i).remove(sock))
  4918. return;
  4919. }
  4920. }
  4921. if (addrm & SOCK_ADDED)
  4922. return;
  4923. CSocketEpollThread *thread = new CSocketEpollThread(epolltrace, hdlPerThrd);
  4924. threads.append(*thread);
  4925. if (started)
  4926. thread->start();
  4927. thread->add(sock,mode,nfy);
  4928. }
  4929. void remove(ISocket *sock)
  4930. {
  4931. CriticalBlock block(sect);
  4932. ForEachItemIn(i,threads)
  4933. {
  4934. if (threads.item(i).remove(sock))
  4935. break;
  4936. }
  4937. }
  4938. void stop(bool wait)
  4939. {
  4940. CriticalBlock block(sect);
  4941. stopped = true;
  4942. ForEachItemIn(i,threads)
  4943. {
  4944. CSocketEpollThread &t=threads.item(i);
  4945. {
  4946. CriticalUnblock unblock(sect);
  4947. t.stop(wait); // not quite as quick as could be if wait true
  4948. }
  4949. }
  4950. }
  4951. };
  4952. enum EpollMethod { EPOLL_INIT = 0, EPOLL_DISABLED, EPOLL_ENABLED };
  4953. static EpollMethod epoll_method = EPOLL_INIT;
  4954. static CriticalSection epollsect;
  4955. void check_epoll_cfg()
  4956. {
  4957. CriticalBlock block(epollsect);
  4958. // DBGLOG("check_epoll_cfg(): epoll_method = %d",epoll_method);
  4959. if (epoll_method == EPOLL_INIT)
  4960. {
  4961. if (queryEnvironmentConf().getPropBool("use_epoll", true))
  4962. epoll_method = EPOLL_ENABLED;
  4963. else
  4964. epoll_method = EPOLL_DISABLED;
  4965. // DBGLOG("check_epoll_cfg(): after reading conf file, epoll_method = %d",epoll_method);
  4966. epoll_hdlPerThrd = (unsigned)queryEnvironmentConf().getPropInt("epoll_hdlperthrd", UINT_MAX);
  4967. if (epoll_hdlPerThrd == 0)
  4968. epoll_hdlPerThrd = UINT_MAX;
  4969. // DBGLOG("check_epoll_cfg(): after reading conf file, epoll_hdlPerThrd = %u",epoll_hdlPerThrd);
  4970. }
  4971. }
  4972. #endif // _HAS_EPOLL_SUPPORT
  4973. ISocketSelectHandler *createSocketSelectHandler(const char *trc, unsigned hdlPerThrd)
  4974. {
  4975. #ifdef _HAS_EPOLL_SUPPORT
  4976. check_epoll_cfg();
  4977. if (epoll_method == EPOLL_ENABLED)
  4978. {
  4979. if (hdlPerThrd == 0)
  4980. hdlPerThrd = epoll_hdlPerThrd;
  4981. return new CSocketEpollHandler(trc, hdlPerThrd);
  4982. }
  4983. else
  4984. return new CSocketSelectHandler(trc);
  4985. #else
  4986. return new CSocketSelectHandler(trc);
  4987. #endif
  4988. }
  4989. ISocketSelectHandler *createSocketEpollHandler(const char *trc, unsigned hdlPerThrd)
  4990. {
  4991. #ifdef _HAS_EPOLL_SUPPORT
  4992. check_epoll_cfg();
  4993. if (hdlPerThrd == 0)
  4994. hdlPerThrd = epoll_hdlPerThrd;
  4995. return new CSocketEpollHandler(trc, hdlPerThrd);
  4996. #else
  4997. return new CSocketSelectHandler(trc);
  4998. #endif
  4999. }
  5000. void readBuffer(ISocket * socket, MemoryBuffer & buffer)
  5001. {
  5002. size32_t len;
  5003. socket->read(&len, sizeof(len));
  5004. _WINREV4(len);
  5005. if (len) {
  5006. void * target = buffer.reserve(len);
  5007. socket->read(target, len);
  5008. }
  5009. }
  5010. void readBuffer(ISocket * socket, MemoryBuffer & buffer, unsigned timeoutms)
  5011. {
  5012. size32_t len;
  5013. size32_t sizeGot;
  5014. socket->readtms(&len, sizeof(len), sizeof(len), sizeGot, timeoutms);
  5015. _WINREV4(len);
  5016. if (len) {
  5017. void * target = buffer.reserve(len);
  5018. socket->readtms(target, len, len, sizeGot, timeoutms);
  5019. }
  5020. }
  5021. void writeBuffer(ISocket * socket, MemoryBuffer & buffer)
  5022. {
  5023. unsigned len = buffer.length();
  5024. _WINREV4(len);
  5025. socket->write(&len, sizeof(len));
  5026. if (len)
  5027. socket->write(buffer.toByteArray(), buffer.length());
  5028. }
  5029. bool catchReadBuffer(ISocket * socket, MemoryBuffer & buffer)
  5030. {
  5031. try
  5032. {
  5033. readBuffer(socket, buffer);
  5034. return true;
  5035. }
  5036. catch (IException * e)
  5037. {
  5038. switch (e->errorCode())
  5039. {
  5040. case JSOCKERR_graceful_close:
  5041. break;
  5042. default:
  5043. EXCLOG(e,"catchReadBuffer");
  5044. break;
  5045. }
  5046. e->Release();
  5047. }
  5048. return false;
  5049. }
  5050. bool catchReadBuffer(ISocket * socket, MemoryBuffer & buffer, unsigned timeoutms)
  5051. {
  5052. try
  5053. {
  5054. readBuffer(socket, buffer, timeoutms);
  5055. return true;
  5056. }
  5057. catch (IException * e)
  5058. {
  5059. switch (e->errorCode())
  5060. {
  5061. case JSOCKERR_graceful_close:
  5062. break;
  5063. default:
  5064. EXCLOG(e,"catchReadBuffer");
  5065. break;
  5066. }
  5067. e->Release();
  5068. }
  5069. return false;
  5070. }
  5071. bool catchWriteBuffer(ISocket * socket, MemoryBuffer & buffer)
  5072. {
  5073. try
  5074. {
  5075. writeBuffer(socket, buffer);
  5076. return true;
  5077. }
  5078. catch (IException * e)
  5079. {
  5080. EXCLOG(e,"catchWriteBuffer");
  5081. e->Release();
  5082. }
  5083. return false;
  5084. }
  5085. // utility interface for simple conversations
  5086. // conversation is always between two ends,
  5087. // at any given time one end must be receiving and other sending (though these may swap during the conversation)
  5088. class CSingletonSocketConnection: implements IConversation, public CInterface
  5089. {
  5090. Owned<ISocket> sock;
  5091. Owned<ISocket> listensock;
  5092. enum { Snone, Saccept, Sconnect, Srecv, Ssend, Scancelled } state;
  5093. bool cancelling;
  5094. SocketEndpoint ep;
  5095. CriticalSection crit;
  5096. public:
  5097. IMPLEMENT_IINTERFACE;
  5098. CSingletonSocketConnection(SocketEndpoint &_ep)
  5099. {
  5100. ep = _ep;
  5101. state = Snone;
  5102. cancelling = false;
  5103. }
  5104. ~CSingletonSocketConnection()
  5105. {
  5106. try {
  5107. if (sock)
  5108. sock->close();
  5109. }
  5110. catch (IException *e) {
  5111. if (e->errorCode()!=JSOCKERR_graceful_close)
  5112. EXCLOG(e,"CSingletonSocketConnection close");
  5113. e->Release();
  5114. }
  5115. }
  5116. void set_keep_alive(bool keepalive)
  5117. {
  5118. if (sock)
  5119. sock->set_keep_alive(keepalive);
  5120. }
  5121. bool connect(unsigned timeoutms)
  5122. {
  5123. CriticalBlock block(crit);
  5124. if (cancelling)
  5125. state = Scancelled;
  5126. if (state==Scancelled)
  5127. return false;
  5128. assertex(!sock);
  5129. ISocket *newsock=NULL;
  5130. state = Sconnect;
  5131. unsigned start = 0;
  5132. if (timeoutms!=(unsigned)INFINITE)
  5133. start = msTick();
  5134. while (state==Sconnect) {
  5135. try {
  5136. CriticalUnblock unblock(crit);
  5137. newsock = ISocket::connect_wait(ep,1000*60*4);
  5138. break;
  5139. }
  5140. catch (IException * e) {
  5141. if ((e->errorCode()==JSOCKERR_timeout_expired)||(e->errorCode()==JSOCKERR_connection_failed)) {
  5142. e->Release();
  5143. if ((state==Sconnect)&&(timeoutms!=(unsigned)INFINITE)&&(msTick()-start>timeoutms)) {
  5144. state = Snone;
  5145. return false;
  5146. }
  5147. }
  5148. else {
  5149. state = Scancelled;
  5150. EXCLOG(e,"CSingletonSocketConnection::connect");
  5151. e->Release();
  5152. return false;
  5153. }
  5154. }
  5155. }
  5156. if (state!=Sconnect) {
  5157. ::Release(newsock);
  5158. newsock = NULL;
  5159. }
  5160. if (!newsock) {
  5161. state = Scancelled;
  5162. return false;
  5163. }
  5164. sock.setown(newsock);
  5165. return true;
  5166. }
  5167. bool send(MemoryBuffer &mb)
  5168. {
  5169. CriticalBlock block(crit);
  5170. if (cancelling)
  5171. state = Scancelled;
  5172. if (state==Scancelled)
  5173. return false;
  5174. assertex(sock);
  5175. state = Srecv;
  5176. try {
  5177. CriticalUnblock unblock(crit);
  5178. writeBuffer(sock,mb);
  5179. }
  5180. catch (IException * e) {
  5181. state = Scancelled;
  5182. EXCLOG(e,"CSingletonSocketConnection::send");
  5183. e->Release();
  5184. return false;
  5185. }
  5186. state = Snone;
  5187. return true;
  5188. }
  5189. unsigned short setRandomPort(unsigned short base, unsigned num)
  5190. {
  5191. for (;;) {
  5192. try {
  5193. ep.port = base+(unsigned short)(getRandom()%num);
  5194. listensock.setown(ISocket::create(ep.port));
  5195. return ep.port;
  5196. }
  5197. catch (IException *e) {
  5198. if (e->errorCode()!=JSOCKERR_port_in_use) {
  5199. state = Scancelled;
  5200. EXCLOG(e,"CSingletonSocketConnection::setRandomPort");
  5201. e->Release();
  5202. break;
  5203. }
  5204. e->Release();
  5205. }
  5206. }
  5207. return 0;
  5208. }
  5209. bool accept(unsigned timeoutms)
  5210. {
  5211. CriticalBlock block(crit);
  5212. if (cancelling)
  5213. state = Scancelled;
  5214. if (state==Scancelled)
  5215. return false;
  5216. if (!sock) {
  5217. ISocket *newsock=NULL;
  5218. state = Saccept;
  5219. for (;;) {
  5220. try {
  5221. {
  5222. CriticalUnblock unblock(crit);
  5223. if (!listensock)
  5224. listensock.setown(ISocket::create(ep.port));
  5225. if ((timeoutms!=(unsigned)INFINITE)&&(!listensock->wait_read(timeoutms))) {
  5226. state = Snone;
  5227. return false;
  5228. }
  5229. }
  5230. if (cancelling)
  5231. state = Scancelled;
  5232. if (state==Scancelled)
  5233. return false;
  5234. {
  5235. CriticalUnblock unblock(crit);
  5236. newsock=listensock->accept(true);
  5237. break;
  5238. }
  5239. }
  5240. catch (IException *e) {
  5241. if (e->errorCode()==JSOCKERR_graceful_close)
  5242. PROGLOG("CSingletonSocketConnection: Closed socket on accept - retrying...");
  5243. else {
  5244. state = Scancelled;
  5245. EXCLOG(e,"CSingletonSocketConnection::accept");
  5246. e->Release();
  5247. break;
  5248. }
  5249. e->Release();
  5250. }
  5251. }
  5252. if (state!=Saccept) {
  5253. ::Release(newsock);
  5254. newsock = NULL;
  5255. }
  5256. if (!newsock) {
  5257. state = Scancelled;
  5258. return false;
  5259. }
  5260. sock.setown(newsock);
  5261. }
  5262. return true;
  5263. }
  5264. bool recv(MemoryBuffer &mb, unsigned timeoutms)
  5265. {
  5266. CriticalBlock block(crit);
  5267. if (cancelling)
  5268. state = Scancelled;
  5269. if (state==Scancelled)
  5270. return false;
  5271. assertex(sock);
  5272. state = Srecv;
  5273. try {
  5274. CriticalUnblock unblock(crit);
  5275. readBuffer(sock,mb,timeoutms);
  5276. }
  5277. catch (IException *e) {
  5278. if (e->errorCode()==JSOCKERR_timeout_expired)
  5279. state = Snone;
  5280. else {
  5281. state = Scancelled;
  5282. if (e->errorCode()!=JSOCKERR_graceful_close)
  5283. EXCLOG(e,"CSingletonSocketConnection::recv");
  5284. }
  5285. e->Release();
  5286. return false;
  5287. }
  5288. state = Snone;
  5289. return true;
  5290. }
  5291. virtual void cancel()
  5292. {
  5293. CriticalBlock block(crit);
  5294. while (state!=Scancelled) {
  5295. cancelling = true;
  5296. try {
  5297. switch (state) {
  5298. case Saccept:
  5299. {
  5300. if (listensock)
  5301. listensock->cancel_accept();
  5302. }
  5303. break;
  5304. case Sconnect:
  5305. // wait for timeout
  5306. break;
  5307. case Srecv:
  5308. {
  5309. if (sock)
  5310. sock->close();
  5311. }
  5312. break;
  5313. case Ssend:
  5314. // wait for finished
  5315. break;
  5316. default:
  5317. state = Scancelled;
  5318. break;
  5319. }
  5320. }
  5321. catch (IException *e) {
  5322. EXCLOG(e,"CSingletonSocketConnection::cancel");
  5323. e->Release();
  5324. }
  5325. {
  5326. CriticalUnblock unblock(crit);
  5327. Sleep(1000);
  5328. }
  5329. }
  5330. }
  5331. };
  5332. IConversation *createSingletonSocketConnection(unsigned short port,SocketEndpoint *_ep)
  5333. {
  5334. SocketEndpoint ep;
  5335. if (_ep)
  5336. ep = *_ep;
  5337. if (port)
  5338. ep.port = port;
  5339. return new CSingletonSocketConnection(ep);
  5340. }
  5341. // interface for reading from multiple sockets using the BF_SYNC_TRANSFER_PUSH protocol
  5342. class CSocketBufferReader: implements ISocketBufferReader, public CInterface
  5343. {
  5344. class SocketElem: implements ISocketSelectNotify, public CInterface
  5345. {
  5346. CSocketBufferReader *parent;
  5347. unsigned num; // top bit used for ready
  5348. MemoryAttr blk;
  5349. CriticalSection sect;
  5350. Linked<ISocket> sock;
  5351. bool active;
  5352. bool pending;
  5353. public:
  5354. IMPLEMENT_IINTERFACE;
  5355. void init(CSocketBufferReader *_parent,ISocket *_sock,unsigned _n)
  5356. {
  5357. parent = _parent;
  5358. num = _n;
  5359. sock.set(_sock);
  5360. active = true;
  5361. pending = false;
  5362. }
  5363. virtual bool notifySelected(ISocket *socket,unsigned selected)
  5364. {
  5365. assertex(sock==socket);
  5366. {
  5367. CriticalBlock block(sect);
  5368. if (pending) {
  5369. active = false;
  5370. parent->remove(sock);
  5371. return false;
  5372. }
  5373. pending = true;
  5374. unsigned t1=usTick();
  5375. size32_t sz = sock->receive_block_size();
  5376. unsigned t2=usTick();
  5377. if (sz)
  5378. sock->receive_block(blk.allocate(sz),sz);
  5379. else
  5380. parent->remove(sock);
  5381. unsigned t3=usTick();
  5382. if (t3-t1>60*1000000)
  5383. PROGLOG("CSocketBufferReader(%d): slow receive_block (%d,%d) sz=%d",num,t2-t1,t3-t2,sz);
  5384. }
  5385. parent->enqueue(this); // nb outside sect critical block
  5386. return false; // always return false
  5387. }
  5388. unsigned get(MemoryBuffer &mb)
  5389. {
  5390. CriticalBlock block(sect);
  5391. assertex(pending);
  5392. size32_t sz = (size32_t)blk.length();
  5393. if (sz)
  5394. mb.setBuffer(sz,blk.detach(),true);
  5395. pending = false;
  5396. if (!active) {
  5397. active = true;
  5398. parent->add(*this);
  5399. }
  5400. return num;
  5401. }
  5402. size32_t size()
  5403. {
  5404. return (size32_t)blk.length();
  5405. }
  5406. ISocket *getSocket() { return sock; }
  5407. } *elems;
  5408. SimpleInterThreadQueueOf<SocketElem, false> readyq;
  5409. Owned<ISocketSelectHandler> selecthandler;
  5410. size32_t buffersize;
  5411. size32_t buffermax;
  5412. unsigned bufferwaiting;
  5413. CriticalSection buffersect;
  5414. Semaphore buffersem;
  5415. bool isdone;
  5416. public:
  5417. IMPLEMENT_IINTERFACE;
  5418. CSocketBufferReader(const char *trc)
  5419. {
  5420. selecthandler.setown(createSocketSelectHandler(trc));
  5421. elems = NULL;
  5422. }
  5423. ~CSocketBufferReader()
  5424. {
  5425. delete [] elems;
  5426. }
  5427. virtual void init(unsigned num,ISocket **sockets,size32_t _buffermax)
  5428. {
  5429. elems = new SocketElem[num];
  5430. for (unsigned i=0;i<num;i++) {
  5431. ISocket *sock = sockets[i];
  5432. if (sock) { // can have gaps
  5433. elems[i].init(this,sock,i);
  5434. add(elems[i]);
  5435. }
  5436. }
  5437. buffersize = 0;
  5438. buffermax = _buffermax;
  5439. bufferwaiting = 0;
  5440. isdone = false;
  5441. selecthandler->start();
  5442. }
  5443. virtual unsigned get(MemoryBuffer &mb)
  5444. {
  5445. SocketElem &e = *readyq.dequeue();
  5446. CriticalBlock block(buffersect);
  5447. assertex(buffersize>=e.size());
  5448. buffersize-=e.size();
  5449. if (bufferwaiting) {
  5450. buffersem.signal(bufferwaiting);
  5451. bufferwaiting = 0;
  5452. }
  5453. return e.get(mb);
  5454. }
  5455. virtual void done(bool wait)
  5456. {
  5457. buffersem.signal(0x10000);
  5458. isdone = true;
  5459. selecthandler->stop(wait);
  5460. if (wait) {
  5461. delete [] elems;
  5462. elems = NULL;
  5463. }
  5464. }
  5465. void enqueue(SocketElem *elem)
  5466. {
  5467. if (elem) {
  5468. CriticalBlock block(buffersect);
  5469. size32_t sz = elem->size();
  5470. while ((buffersize>0)&&(sz>0)&&(buffersize+sz>buffermax)) {
  5471. if (isdone)
  5472. return;
  5473. bufferwaiting++;
  5474. CriticalUnblock unblock(buffersect);
  5475. buffersem.wait();
  5476. }
  5477. buffersize += sz;
  5478. }
  5479. readyq.enqueue(elem);
  5480. }
  5481. void remove(ISocket *sock)
  5482. {
  5483. selecthandler->remove(sock);
  5484. }
  5485. void add(SocketElem &elem)
  5486. {
  5487. selecthandler->add(elem.getSocket(),SELECTMODE_READ,&elem);
  5488. }
  5489. };
  5490. ISocketBufferReader *createSocketBufferReader(const char *trc)
  5491. {
  5492. return new CSocketBufferReader(trc);
  5493. }
  5494. extern jlib_decl void markNodeCentral(SocketEndpoint &ep)
  5495. {
  5496. #ifdef CENTRAL_NODE_RANDOM_DELAY
  5497. CriticalBlock block(CSocket::crit);
  5498. CentralNodeArray.append(ep);
  5499. #endif
  5500. }
  5501. static CSocket *prepareSocket(unsigned idx,const SocketEndpoint &ep, ISocketConnectNotify &inotify)
  5502. {
  5503. Owned<CSocket> sock = new CSocket(ep,sm_tcp,NULL);
  5504. int err = sock->pre_connect(false);
  5505. if ((err == JSE_INPROGRESS)||(err == JSE_WOULDBLOCK))
  5506. return sock.getClear();
  5507. if (err==0) {
  5508. int err = sock->post_connect();
  5509. if (err==0)
  5510. inotify.connected(idx,ep,sock);
  5511. else {
  5512. sock->errclose();
  5513. inotify.failed(idx,ep,err);
  5514. }
  5515. }
  5516. else
  5517. inotify.failed(idx,ep,err);
  5518. return NULL;
  5519. }
  5520. void multiConnect(const SocketEndpointArray &eps,ISocketConnectNotify &inotify,unsigned timeout)
  5521. {
  5522. class SocketElem: implements ISocketSelectNotify, public CInterface
  5523. {
  5524. CriticalSection *sect;
  5525. ISocketSelectHandler *handler;
  5526. unsigned *remaining;
  5527. Semaphore *notifysem;
  5528. ISocketConnectNotify *inotify;
  5529. public:
  5530. Owned<CSocket> sock;
  5531. SocketEndpoint ep;
  5532. unsigned idx;
  5533. IMPLEMENT_IINTERFACE;
  5534. void init(CSocket *_sock,unsigned _idx,const SocketEndpoint &_ep,CriticalSection *_sect,ISocketSelectHandler *_handler,ISocketConnectNotify *_inotify, unsigned *_remaining, Semaphore *_notifysem)
  5535. {
  5536. ep = _ep;
  5537. idx = _idx;
  5538. inotify = _inotify;
  5539. sock.setown(_sock),
  5540. sect = _sect;
  5541. handler = _handler;
  5542. remaining = _remaining;
  5543. notifysem = _notifysem;
  5544. }
  5545. virtual bool notifySelected(ISocket *socket,unsigned selected)
  5546. {
  5547. CriticalBlock block(*sect);
  5548. handler->remove(socket);
  5549. int err = sock->post_connect();
  5550. CSocket *newsock = NULL;
  5551. {
  5552. CriticalUnblock unblock(*sect); // up to caller to cope with multithread
  5553. if (err==0)
  5554. inotify->connected(idx,ep,sock);
  5555. else if ((err==JSE_TIMEDOUT)||(err==JSE_CONNREFUSED)) {
  5556. // don't give up so easily (maybe listener not yet started (i.e. racing))
  5557. newsock = prepareSocket(idx,ep,*inotify);
  5558. Sleep(100); // not very nice but without this would just loop
  5559. }
  5560. else
  5561. inotify->failed(idx,ep,err);
  5562. }
  5563. if (newsock) {
  5564. sock.setown(newsock);
  5565. handler->add(sock,SELECTMODE_WRITE|SELECTMODE_EXCEPT,this);
  5566. }
  5567. else {
  5568. sock.clear();
  5569. (*remaining)--;
  5570. notifysem->signal();
  5571. }
  5572. return false;
  5573. }
  5574. } *elems;
  5575. unsigned n = eps.ordinality();
  5576. unsigned remaining = n;
  5577. if (!n)
  5578. return;
  5579. elems = new SocketElem[n];
  5580. unsigned i;
  5581. CriticalSection sect;
  5582. Semaphore notifysem;
  5583. Owned<ISocketSelectHandler> selecthandler = createSocketSelectHandler(
  5584. #ifdef _DEBUG
  5585. "multiConnect"
  5586. #else
  5587. NULL
  5588. #endif
  5589. );
  5590. StringBuffer name;
  5591. for (i=0;i<n;i++) {
  5592. CSocket* sock = prepareSocket(i,eps.item(i),inotify);
  5593. if (sock) {
  5594. elems[i].init(sock,i,eps.item(i),&sect,selecthandler,&inotify,&remaining,&notifysem);
  5595. selecthandler->add(sock,SELECTMODE_WRITE|SELECTMODE_EXCEPT,&elems[i]);
  5596. }
  5597. else
  5598. remaining--;
  5599. }
  5600. if (remaining) {
  5601. unsigned lastremaining=remaining;
  5602. selecthandler->start();
  5603. for (;;) {
  5604. bool to=!notifysem.wait(timeout);
  5605. {
  5606. CriticalBlock block(sect);
  5607. if (remaining==0)
  5608. break;
  5609. if (to&&(remaining==lastremaining))
  5610. break; // nothing happened recently
  5611. lastremaining = remaining;
  5612. }
  5613. }
  5614. selecthandler->stop(true);
  5615. }
  5616. selecthandler.clear();
  5617. if (remaining) {
  5618. for (unsigned j=0;j<n;j++) { // mop up timeouts
  5619. SocketElem &elem = elems[j];
  5620. if (elem.sock.get()) {
  5621. elem.sock.clear();
  5622. inotify.failed(j,elem.ep,-1);
  5623. remaining--;
  5624. if (remaining==0)
  5625. break;
  5626. }
  5627. }
  5628. }
  5629. delete [] elems;
  5630. }
  5631. void multiConnect(const SocketEndpointArray &eps, IPointerArrayOf<ISocket> &retsockets,unsigned timeout)
  5632. {
  5633. unsigned n = eps.ordinality();
  5634. if (n==0)
  5635. return;
  5636. if (n==1) { // no need for multi
  5637. ISocket *sock = NULL;
  5638. try {
  5639. sock = ISocket::connect_timeout(eps.item(0),timeout);
  5640. }
  5641. catch (IException *e) { // ignore error just append NULL
  5642. sock = NULL;
  5643. e->Release();
  5644. }
  5645. retsockets.append(sock);
  5646. return;
  5647. }
  5648. while (retsockets.ordinality()<n)
  5649. retsockets.append(NULL);
  5650. CriticalSection sect;
  5651. class cNotify: implements ISocketConnectNotify
  5652. {
  5653. CriticalSection &sect;
  5654. IPointerArrayOf<ISocket> &retsockets;
  5655. public:
  5656. cNotify(IPointerArrayOf<ISocket> &_retsockets,CriticalSection &_sect)
  5657. : sect(_sect), retsockets(_retsockets)
  5658. {
  5659. }
  5660. void connected(unsigned idx,const SocketEndpoint &ep,ISocket *sock)
  5661. {
  5662. CriticalBlock block(sect);
  5663. assertex(idx<retsockets.ordinality());
  5664. sock->Link();
  5665. retsockets.replace(sock,idx);
  5666. }
  5667. void failed(unsigned idx,const SocketEndpoint &ep,int err)
  5668. {
  5669. StringBuffer s;
  5670. PROGLOG("multiConnect failed to %s with %d",ep.getUrlStr(s).str(),err);
  5671. }
  5672. } notify(retsockets,sect);
  5673. multiConnect(eps,notify,timeout);
  5674. }
  5675. inline void flushText(StringBuffer &text,unsigned short port,unsigned &rep,unsigned &range)
  5676. {
  5677. if (rep) {
  5678. text.append('*').append(rep+1);
  5679. rep = 0;
  5680. }
  5681. else if (range) {
  5682. text.append('-').append(range);
  5683. range = 0;
  5684. }
  5685. if (port)
  5686. text.append(':').append(port);
  5687. }
  5688. StringBuffer &SocketEndpointArray::getText(StringBuffer &text)
  5689. {
  5690. unsigned count = ordinality();
  5691. if (!count)
  5692. return text;
  5693. if (count==1)
  5694. return item(0).getUrlStr(text);
  5695. byte lastip[4];
  5696. const SocketEndpoint &first = item(0);
  5697. bool lastis4 = first.getNetAddress(sizeof(lastip),&lastip)==sizeof(lastip);
  5698. unsigned short lastport = first.port;
  5699. first.getIpText(text);
  5700. unsigned rep=0;
  5701. unsigned range=0;
  5702. for (unsigned i=1;i<count;i++) {
  5703. byte ip[4];
  5704. const SocketEndpoint &ep = item(i);
  5705. bool is4 = ep.getNetAddress(sizeof(ip),&ip)==sizeof(ip);
  5706. if (!lastis4||!is4) {
  5707. flushText(text,lastport,rep,range);
  5708. text.append(',');
  5709. ep.getIpText(text);
  5710. }
  5711. else { // try and shorten
  5712. unsigned j;
  5713. for (j=0;j<4;j++)
  5714. if (ip[j]!=lastip[j])
  5715. break;
  5716. if (ep.port==lastport) {
  5717. if (j==4) {
  5718. if (range) // cant have range and rep
  5719. j--; // pretend only 3 matched
  5720. else {
  5721. rep++;
  5722. continue;
  5723. }
  5724. }
  5725. else if ((j==3)&&(lastip[3]+1==ip[3])&&(rep==0)) {
  5726. range = ip[3];
  5727. lastip[3] = (byte)range;
  5728. continue;
  5729. }
  5730. }
  5731. flushText(text,lastport,rep,range);
  5732. // output diff
  5733. text.append(',');
  5734. if (j==4)
  5735. j--;
  5736. for (unsigned k=j;k<4;k++) {
  5737. if (k>j)
  5738. text.append('.');
  5739. text.append((int)ip[k]);
  5740. }
  5741. }
  5742. memcpy(&lastip,&ip,sizeof(lastip));
  5743. lastis4 = is4;
  5744. lastport = ep.port;
  5745. }
  5746. flushText(text,lastport,rep,range);
  5747. return text;
  5748. }
  5749. inline const char *getnum(const char *s,unsigned &n)
  5750. {
  5751. n = 0;
  5752. while (isdigit(*s)) {
  5753. n = n*10+(*s-'0');
  5754. s++;
  5755. }
  5756. return s;
  5757. }
  5758. inline bool appendv4range(SocketEndpointArray *array,char *str,SocketEndpoint &ep, unsigned defport)
  5759. {
  5760. char *s = str;
  5761. unsigned dc = 0;
  5762. unsigned port = defport;
  5763. unsigned rng = 0;
  5764. unsigned rep = 1;
  5765. bool notip = false;
  5766. while (*s) {
  5767. if (*s=='.') {
  5768. dc++;
  5769. s++;
  5770. }
  5771. else if (*s==':') {
  5772. *s = 0;
  5773. s = (char *)getnum(s+1,port);
  5774. }
  5775. else if (*s=='-')
  5776. {
  5777. if (!notip)//don't assume '-' is an ip range delimiter
  5778. { //Allow '-' in any octet due to ip group support
  5779. *s = 0;
  5780. s = (char *)getnum(s+1,rng);
  5781. }
  5782. else
  5783. {
  5784. notip = true;
  5785. s++;
  5786. }
  5787. }
  5788. else if (*s=='*') {
  5789. *s = 0;
  5790. s = (char *)getnum(s+1,rep);
  5791. }
  5792. else {
  5793. if (!isdigit(*s))
  5794. notip = true;
  5795. s++;
  5796. }
  5797. }
  5798. ep.port = port;
  5799. if (*str) {
  5800. if (!notip&&((dc<3)&&((dc!=1)||(strlen(str)!=1)))) {
  5801. if (!ep.isIp4()) {
  5802. return false;
  5803. }
  5804. StringBuffer tmp;
  5805. ep.getIpText(tmp);
  5806. dc++;
  5807. for (;;) {
  5808. if (tmp.length()==0)
  5809. return false;
  5810. if (tmp.charAt(tmp.length()-1)=='.')
  5811. if (--dc==0)
  5812. break;
  5813. tmp.setLength(tmp.length()-1);
  5814. }
  5815. tmp.append(str);
  5816. if (rng) {
  5817. tmp.appendf("-%d",rng);
  5818. rep = ep.ipsetrange(tmp.str());
  5819. }
  5820. else
  5821. ep.ipset(tmp.str());
  5822. }
  5823. else if (rng) { // not nice as have to add back range (must be better way - maybe ipincrementto) TBD
  5824. StringBuffer tmp;
  5825. tmp.appendf("%s-%d",str,rng);
  5826. rep = ep.ipsetrange(tmp.str());
  5827. }
  5828. else if (*str)
  5829. ep.ipset(str);
  5830. if (ep.isNull())
  5831. ep.port = 0;
  5832. for (unsigned i=0;i<rep;i++) {
  5833. array->append(ep);
  5834. if (rng)
  5835. ep.ipincrement(1);
  5836. }
  5837. }
  5838. else {// just a port change
  5839. if (ep.isNull()) // avoid null values with ports
  5840. ep.port = 0;
  5841. array->append(ep);
  5842. }
  5843. return true;
  5844. }
  5845. bool SocketEndpointArray::fromName(const char *name, unsigned defport)
  5846. {
  5847. // Lookup a single name that may resolve to multiple IPs in a headless service scenario
  5848. StringArray portSplit;
  5849. portSplit.appendList(name, ":");
  5850. switch (portSplit.ordinality())
  5851. {
  5852. case 2:
  5853. defport = atoi(portSplit.item(1));
  5854. name = portSplit.item(0);
  5855. // fallthrough
  5856. case 1:
  5857. break;
  5858. default:
  5859. throw MakeStringException(-1, "Invalid name %s SocketEndpointArray::fromName", name);
  5860. }
  5861. #if defined(__linux__) || defined (__APPLE__) || defined(getaddrinfo)
  5862. if (IP4only)
  5863. #endif
  5864. {
  5865. CriticalBlock c(hostnamesect);
  5866. hostent * entry = gethostbyname(name);
  5867. if (entry && entry->h_addr_list[0])
  5868. {
  5869. unsigned ptr = 0;
  5870. for (;;)
  5871. {
  5872. ptr++;
  5873. if (entry->h_addr_list[ptr]==NULL)
  5874. break;
  5875. SocketEndpoint ep;
  5876. ep.setNetAddress(sizeof(unsigned),entry->h_addr_list[ptr]);
  5877. ep.port = defport;
  5878. append(ep);
  5879. }
  5880. }
  5881. return ordinality()>0;
  5882. }
  5883. #if defined(__linux__) || defined (__APPLE__) || defined(getaddrinfo)
  5884. struct addrinfo hints;
  5885. memset(&hints,0,sizeof(hints));
  5886. struct addrinfo *addrInfo = NULL;
  5887. memset(&hints,0,sizeof(hints));
  5888. int ret = getaddrinfo(name, NULL , &hints, &addrInfo);
  5889. if (ret == 0)
  5890. {
  5891. struct addrinfo *ai;
  5892. for (ai = addrInfo; ai; ai = ai->ai_next)
  5893. {
  5894. // DBGLOG("flags=%d, family=%d, socktype=%d, protocol=%d, addrlen=%d, canonname=%s",ai->ai_flags,ai->ai_family,ai->ai_socktype,ai->ai_protocol,ai->ai_addrlen,ai->ai_canonname?ai->ai_canonname:"NULL");
  5895. if (ai->ai_protocol == IPPROTO_IP)
  5896. {
  5897. switch (ai->ai_family)
  5898. {
  5899. case AF_INET:
  5900. {
  5901. SocketEndpoint ep;
  5902. ep.setNetAddress(sizeof(in_addr),&(((sockaddr_in *)ai->ai_addr)->sin_addr));
  5903. ep.port = defport;
  5904. append(ep);
  5905. // StringBuffer s;
  5906. // DBGLOG("Lookup %s found %s", name, ep.getUrlStr(s).str());
  5907. break;
  5908. }
  5909. case AF_INET6:
  5910. {
  5911. SocketEndpoint ep;
  5912. ep.setNetAddress(sizeof(in_addr6),&(((sockaddr_in6 *)ai->ai_addr)->sin6_addr));
  5913. ep.port = defport;
  5914. append(ep);
  5915. break;
  5916. }
  5917. }
  5918. }
  5919. }
  5920. }
  5921. freeaddrinfo(addrInfo);
  5922. #endif
  5923. return ordinality()>0;
  5924. }
  5925. void SocketEndpointArray::fromText(const char *text,unsigned defport)
  5926. {
  5927. // this is quite complicated with (mixed) IPv4 and IPv6
  5928. // only support 'full' IPv6 and no ranges
  5929. if (!text)
  5930. return;
  5931. char *str = strdup(text);
  5932. char *s = str;
  5933. SocketEndpoint ep;
  5934. bool eol = false;
  5935. for (;;) {
  5936. while (isspace(*s)||(*s==','))
  5937. s++;
  5938. if (!*s)
  5939. break;
  5940. char *e=s;
  5941. if (*e=='[') { // we have a IPv6
  5942. while (*e&&(*e!=']'))
  5943. e++;
  5944. while ((*e!=',')&&!isspace(*e)) {
  5945. if (!*s) {
  5946. eol = true;
  5947. break;
  5948. }
  5949. e++;
  5950. }
  5951. *e = 0;
  5952. ep.set(s,defport);
  5953. if (ep.isNull()) {
  5954. // Error TBD
  5955. }
  5956. append(ep);
  5957. }
  5958. else {
  5959. bool hascolon = false;
  5960. bool isv6 = false;
  5961. do {
  5962. if (*e==':') {
  5963. if (hascolon)
  5964. isv6 = true;
  5965. else
  5966. hascolon = true;
  5967. }
  5968. e++;
  5969. if (!*e) {
  5970. eol = true;
  5971. break;
  5972. }
  5973. } while (!isspace(*e)&&(*e!=','));
  5974. *e = 0;
  5975. if (isv6) {
  5976. ep.set(s,defport);
  5977. if (ep.isNull()) {
  5978. // Error TBD
  5979. }
  5980. append(ep);
  5981. }
  5982. else {
  5983. if (!appendv4range(this,s,ep,defport)) {
  5984. // Error TBD
  5985. }
  5986. }
  5987. }
  5988. if (eol)
  5989. break;
  5990. s = e+1;
  5991. }
  5992. free(str);
  5993. }
  5994. bool IpSubNet::set(const char *_net,const char *_mask)
  5995. {
  5996. if (!_net||!decodeNumericIP(_net,net)) { // _net NULL means match everything
  5997. memset(net,0,sizeof(net));
  5998. memset(mask,0,sizeof(mask));
  5999. return (_net==NULL);
  6000. }
  6001. if (!_mask||!decodeNumericIP(_mask,mask)) { // _mask NULL means match exact
  6002. memset(mask,0xff,sizeof(mask));
  6003. return (_mask==NULL);
  6004. }
  6005. if (isIp4(net)!=isIp4(mask))
  6006. return false;
  6007. for (unsigned j=0;j<4;j++)
  6008. if (net[j]&~mask[j])
  6009. return false;
  6010. return true;
  6011. }
  6012. bool IpSubNet::test(const IpAddress &ip) const
  6013. {
  6014. unsigned i;
  6015. if (ip.getNetAddress(sizeof(i),&i)==sizeof(i)) {
  6016. if (!isIp4(net))
  6017. return false;
  6018. return (i&mask[3])==(net[3]&mask[3]);
  6019. }
  6020. unsigned na[4];
  6021. if (ip.getNetAddress(sizeof(na),&na)==sizeof(na)) {
  6022. for (unsigned j=0;j<4;j++)
  6023. if ((na[j]&mask[j])!=(net[j]&mask[j]))
  6024. return false;
  6025. return true;
  6026. }
  6027. return false;
  6028. }
  6029. StringBuffer &IpSubNet::getNetText(StringBuffer &text) const
  6030. {
  6031. char tmp[INET6_ADDRSTRLEN];
  6032. const char *res = ::isIp4(net) ? _inet_ntop(AF_INET, &net[3], tmp, sizeof(tmp))
  6033. : _inet_ntop(AF_INET6, &net, tmp, sizeof(tmp));
  6034. return text.append(res);
  6035. }
  6036. StringBuffer &IpSubNet::getMaskText(StringBuffer &text) const
  6037. {
  6038. char tmp[INET6_ADDRSTRLEN];
  6039. // isIp4(net) is correct here
  6040. const char *res = ::isIp4(net) ? _inet_ntop(AF_INET, &mask[3], tmp, sizeof(tmp))
  6041. : _inet_ntop(AF_INET6, &mask, tmp, sizeof(tmp));
  6042. return text.append(res);
  6043. }
  6044. bool IpSubNet::isNull() const
  6045. {
  6046. for (unsigned i=0;i<4;i++)
  6047. if (net[i]||mask[i])
  6048. return false;
  6049. return true;
  6050. }
  6051. IpSubNet &queryPreferredSubnet()
  6052. {
  6053. return PreferredSubnet;
  6054. }
  6055. bool setPreferredSubnet(const char *ip,const char *mask)
  6056. {
  6057. // also resets cached host IP
  6058. if (PreferredSubnet.set(ip,mask))
  6059. {
  6060. if (!cachehostip.isNull())
  6061. {
  6062. cachehostip.ipset(NULL);
  6063. queryHostIP();
  6064. }
  6065. return true;
  6066. }
  6067. else
  6068. return false;
  6069. }
  6070. StringBuffer &lookupHostName(const IpAddress &ip,StringBuffer &ret)
  6071. {
  6072. // not a common routine (no Jlib function!) only support IPv4 initially
  6073. unsigned ipa;
  6074. if (ip.getNetAddress(sizeof(ipa),&ipa)==sizeof(ipa)) {
  6075. struct hostent *phostent = gethostbyaddr( (char *) &ipa, sizeof(ipa), PF_INET);
  6076. if (phostent)
  6077. ret.append(phostent->h_name);
  6078. else
  6079. ip.getIpText(ret);
  6080. }
  6081. else
  6082. ip.getIpText(ret);
  6083. return ret;
  6084. }
  6085. struct SocketEndpointHTElem
  6086. {
  6087. IInterface *ii;
  6088. SocketEndpoint ep;
  6089. SocketEndpointHTElem(const SocketEndpoint _ep,IInterface *_ii) { ep.set(_ep); ii = _ii; }
  6090. ~SocketEndpointHTElem() { ::Release(ii); }
  6091. };
  6092. class jlib_decl CSocketEndpointHashTable : public SuperHashTableOf<SocketEndpointHTElem, SocketEndpoint>, implements ISocketEndpointHashTable
  6093. {
  6094. virtual void onAdd(void *) {}
  6095. virtual void onRemove(void *e) { delete (SocketEndpointHTElem *)e; }
  6096. unsigned getHashFromElement(const void *e) const
  6097. {
  6098. return ((const SocketEndpointHTElem *)e)->ep.hash(0);
  6099. }
  6100. unsigned getHashFromFindParam(const void *fp) const
  6101. {
  6102. return ((const SocketEndpoint *)fp)->hash(0);
  6103. }
  6104. const void * getFindParam(const void *p) const
  6105. {
  6106. return &((const SocketEndpointHTElem *)p)->ep;
  6107. }
  6108. bool matchesFindParam(const void * et, const void *fp, unsigned) const
  6109. {
  6110. return ((const SocketEndpointHTElem *)et)->ep.equals(*(SocketEndpoint *)fp);
  6111. }
  6112. IMPLEMENT_SUPERHASHTABLEOF_REF_FIND(SocketEndpointHTElem,SocketEndpoint);
  6113. public:
  6114. IMPLEMENT_IINTERFACE;
  6115. CSocketEndpointHashTable() {}
  6116. ~CSocketEndpointHashTable() { _releaseAll(); }
  6117. void add(const SocketEndpoint &ep, IInterface *i)
  6118. {
  6119. SocketEndpointHTElem *e = SuperHashTableOf<SocketEndpointHTElem,SocketEndpoint>::find(&ep);
  6120. if (e) {
  6121. ::Release(e->ii);
  6122. e->ii = i;
  6123. }
  6124. else {
  6125. e = new SocketEndpointHTElem(ep,i);
  6126. SuperHashTableOf<SocketEndpointHTElem,SocketEndpoint>::add(*e);
  6127. }
  6128. }
  6129. void remove(const SocketEndpoint &ep)
  6130. {
  6131. SuperHashTableOf<SocketEndpointHTElem,SocketEndpoint>::remove(&ep);
  6132. }
  6133. IInterface *find(const SocketEndpoint &ep)
  6134. {
  6135. SocketEndpointHTElem *e = SuperHashTableOf<SocketEndpointHTElem,SocketEndpoint>::find(&ep);
  6136. if (e)
  6137. return e->ii;
  6138. return NULL;
  6139. }
  6140. };
  6141. ISocketEndpointHashTable *createSocketEndpointHashTable()
  6142. {
  6143. CSocketEndpointHashTable *ht = new CSocketEndpointHashTable;
  6144. return ht;
  6145. }
  6146. class CSocketConnectWait: implements ISocketConnectWait, public CInterface
  6147. {
  6148. Owned<CSocket> sock;
  6149. bool done;
  6150. CTimeMon connecttm;
  6151. unsigned startt;
  6152. bool oneshot;
  6153. bool isopen;
  6154. int initerr;
  6155. void successfulConnect()
  6156. {
  6157. STATS.connects++;
  6158. STATS.connecttime+=usTick()-startt;
  6159. #ifdef _TRACE
  6160. sock->setTraceName();
  6161. #endif
  6162. }
  6163. void failedConnect()
  6164. {
  6165. STATS.failedconnects++;
  6166. STATS.failedconnecttime+=usTick()-startt;
  6167. const char* tracename = sock->tracename;
  6168. THROWJSOCKEXCEPTION(JSOCKERR_connection_failed);
  6169. }
  6170. public:
  6171. IMPLEMENT_IINTERFACE;
  6172. CSocketConnectWait(SocketEndpoint &ep,unsigned connecttimeoutms)
  6173. : connecttm(connecttimeoutms)
  6174. {
  6175. oneshot = (connecttimeoutms==0); // i.e. as long as one connect takes
  6176. done = false;
  6177. startt = usTick();
  6178. sock.setown(new CSocket(ep,sm_tcp,NULL));
  6179. isopen = true;
  6180. initerr = sock->pre_connect(false);
  6181. }
  6182. ISocket *wait(unsigned timems)
  6183. {
  6184. // this is a bit spagetti due to dual timeouts etc
  6185. CTimeMon waittm(timems);
  6186. unsigned refuseddelay = 1;
  6187. bool waittimedout = false;
  6188. bool connectimedout = false;
  6189. do {
  6190. bool connectdone = false;
  6191. unsigned remaining;
  6192. connectimedout = connecttm.timedout(&remaining);
  6193. unsigned waitremaining;
  6194. waittimedout = waittm.timedout(&waitremaining);
  6195. if (oneshot||(waitremaining<remaining))
  6196. remaining = waitremaining;
  6197. int err = 0;
  6198. if (!isopen||initerr)
  6199. {
  6200. isopen = true;
  6201. err = initerr?initerr:sock->pre_connect(false);
  6202. initerr = 0;
  6203. if ((err == JSE_INPROGRESS)||(err == JSE_WOULDBLOCK))
  6204. err = 0; // continue
  6205. else
  6206. {
  6207. if (err==0)
  6208. connectdone = true; // done immediately
  6209. else if(!oneshot) // probably ECONNREFUSED but treat all errors same
  6210. refused_sleep((waitremaining==remaining)?waittm:connecttm,refuseddelay); // this stops becoming cpu bound
  6211. }
  6212. }
  6213. if (!connectdone&&(err==0))
  6214. {
  6215. SOCKET s = sock->sock;
  6216. #ifdef _USE_SELECT
  6217. CHECKSOCKRANGE(s);
  6218. T_FD_SET fds;
  6219. struct timeval tv;
  6220. XFD_ZERO(&fds);
  6221. FD_SET((unsigned)s, &fds);
  6222. T_FD_SET except;
  6223. XFD_ZERO(&except);
  6224. FD_SET((unsigned)s, &except);
  6225. tv.tv_sec = remaining / 1000;
  6226. tv.tv_usec = (remaining % 1000)*1000;
  6227. int rc = ::select( s + 1, NULL, (fd_set *)&fds, (fd_set *)&except, &tv );
  6228. #else
  6229. struct pollfd fds[1];
  6230. fds[0].fd = s;
  6231. fds[0].events = POLLOUT;
  6232. fds[0].revents = 0;
  6233. int rc = ::poll(fds, 1, remaining);
  6234. #endif
  6235. if (rc==0)
  6236. break; // timeout
  6237. done = true;
  6238. err = 0;
  6239. if (rc>0)
  6240. {
  6241. // select/poll succeeded - return error from socket (0 if connected)
  6242. socklen_t errlen = sizeof(err);
  6243. rc = getsockopt(s, SOL_SOCKET, SO_ERROR, (char *)&err, &errlen); // check for error
  6244. if ((rc!=0)&&!err)
  6245. err = ERRNO(); // some implementations of getsockopt duff
  6246. if (err&&!oneshot) // probably ECONNREFUSED but treat all errors same
  6247. refused_sleep((waitremaining==remaining)?waittm:connecttm,refuseddelay); // this stops becoming cpu bound
  6248. }
  6249. else
  6250. { // select/poll failed
  6251. err = ERRNO();
  6252. if (err != JSE_INTR)
  6253. {
  6254. LOGERR(err,2,"CSocketConnectWait ::select/poll");
  6255. sock->errclose();
  6256. isopen = false;
  6257. if (!oneshot)
  6258. connectimedout = true;
  6259. break;
  6260. }
  6261. }
  6262. }
  6263. if (err==0)
  6264. {
  6265. err = sock->post_connect();
  6266. if (err==0)
  6267. {
  6268. successfulConnect();
  6269. return sock.getClear();
  6270. }
  6271. }
  6272. sock->errclose();
  6273. isopen = false;
  6274. } while (!waittimedout&&!oneshot);
  6275. if (connectimedout)
  6276. {
  6277. STATS.failedconnects++;
  6278. STATS.failedconnecttime+=usTick()-startt;
  6279. const char* tracename = sock->tracename;
  6280. THROWJSOCKEXCEPTION(JSOCKERR_connection_failed);
  6281. }
  6282. return NULL;
  6283. }
  6284. };
  6285. ISocketConnectWait *nonBlockingConnect(SocketEndpoint &ep,unsigned connecttimeoutms)
  6286. {
  6287. return new CSocketConnectWait(ep,connecttimeoutms);
  6288. }
  6289. int wait_multiple(bool isRead, //IN true if wait read, false it wait write
  6290. UnsignedArray &socks, //IN sockets to be checked for readiness
  6291. unsigned timeoutMS, //IN timeout
  6292. UnsignedArray &readySocks) //OUT sockets ready
  6293. {
  6294. aindex_t numSocks = socks.length();
  6295. if (numSocks == 0)
  6296. THROWJSOCKEXCEPTION2(JSOCKERR_bad_address);
  6297. #ifdef _DEBUG
  6298. StringBuffer dbgSB("wait_multiple() on sockets :");
  6299. #endif
  6300. #ifdef _USE_SELECT
  6301. SOCKET maxSocket = 0;
  6302. T_FD_SET fds;
  6303. XFD_ZERO(&fds);
  6304. //Add each SOCKET in array to T_FD_SET
  6305. for (aindex_t idx = 0; idx < numSocks; idx++)
  6306. {
  6307. #ifdef _DEBUG
  6308. dbgSB.appendf(" %d",socks.item(idx));
  6309. #endif
  6310. SOCKET s = socks.item(idx);
  6311. CHECKSOCKRANGE(s);
  6312. maxSocket = s > maxSocket ? s : maxSocket;
  6313. FD_SET((unsigned)s, &fds);
  6314. }
  6315. #else
  6316. struct pollfd *fds = nullptr;
  6317. try
  6318. {
  6319. fds = new pollfd[numSocks];
  6320. }
  6321. catch (const std::bad_alloc &e)
  6322. {
  6323. int err = ERRNO();
  6324. throw MakeStringException(-1,"wait_multiple::fds malloc failure %d", err);
  6325. }
  6326. for (aindex_t idx = 0; idx < numSocks; idx++)
  6327. {
  6328. #ifdef _DEBUG
  6329. dbgSB.appendf(" %d",socks.item(idx));
  6330. #endif
  6331. SOCKET s = socks.item(idx);
  6332. fds[idx].fd = s;
  6333. fds[idx].events = isRead ? POLLINX : POLLOUT;
  6334. fds[idx].revents = 0;
  6335. }
  6336. #endif
  6337. #ifdef _DEBUG
  6338. DBGLOG("%s",dbgSB.str());
  6339. #endif
  6340. //Check socket states
  6341. int res = 0;
  6342. #ifdef _USE_SELECT
  6343. if (timeoutMS == WAIT_FOREVER)
  6344. res = ::select( maxSocket + 1, isRead ? (fd_set *)&fds : NULL, isRead ? NULL : (fd_set *)&fds, NULL, NULL );
  6345. else
  6346. {
  6347. struct timeval tv;
  6348. tv.tv_sec = timeoutMS / 1000;
  6349. tv.tv_usec = (timeoutMS % 1000)*1000;
  6350. res = ::select( maxSocket + 1, isRead ? (fd_set *)&fds : NULL, isRead ? NULL : (fd_set *)&fds, NULL, &tv );
  6351. }
  6352. #else
  6353. res = poll(fds, numSocks, timeoutMS);
  6354. #endif
  6355. if (res > 0)
  6356. {
  6357. #ifdef _DEBUG
  6358. StringBuffer dbgSB("wait_multiple() ready socket(s) :");
  6359. #endif
  6360. //Build up list of socks which are ready for accept read/write without blocking
  6361. for (aindex_t idx = 0; idx < numSocks; idx++)
  6362. {
  6363. SOCKET s = socks.item(idx);
  6364. #ifdef _USE_SELECT
  6365. if (FD_ISSET(s, &fds))
  6366. #else
  6367. if (fds[idx].revents)
  6368. #endif
  6369. {
  6370. #ifdef _DEBUG
  6371. dbgSB.appendf(" %d",s);
  6372. #endif
  6373. readySocks.append(s);
  6374. if ((int) readySocks.length() == res)
  6375. break;
  6376. }
  6377. }
  6378. #ifdef _DEBUG
  6379. DBGLOG("%s",dbgSB.str());
  6380. #endif
  6381. res = readySocks.ordinality();
  6382. }
  6383. else if (res == SOCKET_ERROR)
  6384. {
  6385. res = 0; // dont return negative on failure
  6386. int err = ERRNO();
  6387. if (err != JSE_INTR)
  6388. {
  6389. #ifndef _USE_SELECT
  6390. delete [] fds;
  6391. #endif
  6392. throw MakeStringException(-1,"wait_multiple::select/poll error %d", err);
  6393. }
  6394. }
  6395. #ifndef _USE_SELECT
  6396. delete [] fds;
  6397. #endif
  6398. return res;
  6399. }
  6400. //Given a list of sockets, wait until any one or more are ready to be read (wont block)
  6401. //returns 0 if timeout, number of waiting sockets otherwise
  6402. int wait_read_multiple(UnsignedArray &socks, //IN sockets to be checked for readiness
  6403. unsigned timeoutMS, //IN timeout
  6404. UnsignedArray &readySocks) //OUT sockets ready to be read
  6405. {
  6406. return wait_multiple(true, socks, timeoutMS, readySocks);
  6407. }
  6408. int wait_write_multiple(UnsignedArray &socks, //IN sockets to be checked for readiness
  6409. unsigned timeoutMS, //IN timeout
  6410. UnsignedArray &readySocks) //OUT sockets ready to be written
  6411. {
  6412. return wait_multiple(false, socks, timeoutMS, readySocks);
  6413. }
  6414. inline bool isIPV4Internal(const char *ip)
  6415. {
  6416. struct sockaddr_in sa;
  6417. return 0 != inet_pton(AF_INET, ip, &sa.sin_addr);
  6418. }
  6419. inline bool isIPV6Internal(const char *ip)
  6420. {
  6421. struct sockaddr_in6 sa;
  6422. return 0 != inet_pton(AF_INET6, ip, &sa.sin6_addr);
  6423. }
  6424. bool isIPV4(const char *ip)
  6425. {
  6426. if (isEmptyString(ip))
  6427. return false;
  6428. return isIPV4Internal(ip);
  6429. }
  6430. bool isIPV6(const char *ip)
  6431. {
  6432. if (isEmptyString(ip))
  6433. return false;
  6434. return isIPV6Internal(ip);
  6435. }
  6436. bool isIPAddress(const char *ip)
  6437. {
  6438. if (isEmptyString(ip))
  6439. return false;
  6440. return isIPV4(ip) || isIPV6(ip);
  6441. }
  6442. class CAllowListHandler : public CSimpleInterfaceOf<IAllowListHandler>, implements IAllowListWriter
  6443. {
  6444. typedef CSimpleInterfaceOf<IAllowListHandler> PARENT;
  6445. struct PairHasher
  6446. {
  6447. template <class T1, class T2>
  6448. std::size_t operator () (std::pair<T1, T2> const &pair) const
  6449. {
  6450. std::size_t h1 = std::hash<T1>()(pair.first);
  6451. std::size_t h2 = std::hash<T2>()(pair.second);
  6452. return h1 ^ h2;
  6453. }
  6454. };
  6455. using AllowListHT = std::unordered_set<std::pair<std::string, unsigned __int64>, PairHasher>;
  6456. AllowListPopulateFunction populateFunc;
  6457. AllowListFormatFunction roleFormatFunc;
  6458. std::unordered_set<std::pair<std::string, unsigned __int64>, PairHasher> allowList;
  6459. std::unordered_set<std::string> IPOnlyAllowList;
  6460. bool allowAnonRoles = false;
  6461. mutable CriticalSection populatedCrit;
  6462. mutable bool populated = false;
  6463. mutable bool enabled = true;
  6464. void ensurePopulated() const
  6465. {
  6466. // should be called within CS
  6467. if (populated)
  6468. return;
  6469. // NB: want to keep this method const, as used by isXX functions that are const, but if need to refresh it's effectively mutable
  6470. enabled = populateFunc(* const_cast<IAllowListWriter *>((const IAllowListWriter *)this));
  6471. populated = true;
  6472. }
  6473. public:
  6474. IMPLEMENT_IINTERFACE_O_USING(PARENT);
  6475. CAllowListHandler(AllowListPopulateFunction _populateFunc, AllowListFormatFunction _roleFormatFunc) : populateFunc(_populateFunc), roleFormatFunc(_roleFormatFunc)
  6476. {
  6477. }
  6478. // IAllowListHandler impl.
  6479. virtual bool isAllowListed(const char *ip, unsigned __int64 role, StringBuffer *responseText) const override
  6480. {
  6481. CriticalBlock block(populatedCrit);
  6482. ensurePopulated();
  6483. if (0 == role) // unknown, can only check ip
  6484. {
  6485. if (allowAnonRoles)
  6486. {
  6487. const auto &it = IPOnlyAllowList.find(ip);
  6488. if (it != IPOnlyAllowList.end())
  6489. return true;
  6490. }
  6491. }
  6492. else
  6493. {
  6494. const auto &it = allowList.find({ip, role});
  6495. if (it != allowList.end())
  6496. return true;
  6497. }
  6498. // if !enabled and no responseText supplied, generate response and warn that disabled
  6499. StringBuffer disabledResponseText;
  6500. if (!enabled && !responseText)
  6501. responseText = &disabledResponseText;
  6502. if (responseText)
  6503. {
  6504. responseText->append("Access denied! [server ip=");
  6505. queryHostIP().getIpText(*responseText);
  6506. responseText->append(", client ip=");
  6507. responseText->append(ip);
  6508. if (role)
  6509. {
  6510. responseText->append(", role=");
  6511. if (roleFormatFunc)
  6512. roleFormatFunc(*responseText, role);
  6513. else
  6514. responseText->append(role);
  6515. }
  6516. responseText->append("] not in allowlist");
  6517. }
  6518. if (enabled)
  6519. return false;
  6520. else
  6521. {
  6522. OWARNLOG("Allowlist is disabled, ignoring: %s", responseText->str());
  6523. return true;
  6524. }
  6525. }
  6526. virtual StringBuffer &getAllowList(StringBuffer &out) const override
  6527. {
  6528. CriticalBlock block(populatedCrit);
  6529. ensurePopulated();
  6530. for (const auto &it: allowList)
  6531. {
  6532. out.append(it.first.c_str()).append(", ");
  6533. if (roleFormatFunc)
  6534. roleFormatFunc(out, it.second);
  6535. else
  6536. out.append(it.second);
  6537. out.newline();
  6538. }
  6539. out.newline().appendf("Allowlist is currently: %s", enabled ? "enabled" : "disabled").newline();
  6540. return out;
  6541. }
  6542. virtual void refresh() override
  6543. {
  6544. /* NB: clear only, so that next usage will re-populated
  6545. * Do not want to repopulate now, because refresh() is likely called within a update write transaction
  6546. */
  6547. CriticalBlock block(populatedCrit);
  6548. enabled = true;
  6549. allowList.clear();
  6550. IPOnlyAllowList.clear();
  6551. populated = false;
  6552. }
  6553. // IAllowListWriter impl.
  6554. virtual void add(const char *ip, unsigned __int64 role) override
  6555. {
  6556. // NB: called via populateFunc, which is called whilst populatedCrit is locked.
  6557. allowList.insert({ ip, role });
  6558. if (allowAnonRoles)
  6559. IPOnlyAllowList.insert(ip);
  6560. }
  6561. virtual void setAllowAnonRoles(bool tf) override
  6562. {
  6563. allowAnonRoles = tf;
  6564. refresh();
  6565. }
  6566. };
  6567. IAllowListHandler *createAllowListHandler(AllowListPopulateFunction populateFunc, AllowListFormatFunction roleFormatFunc)
  6568. {
  6569. return new CAllowListHandler(populateFunc, roleFormatFunc);
  6570. }
  6571. static_assert(sizeof(IpAddress) == 16, "check size of IpAddress");
  6572. static_assert(sizeof(SocketEndpoint) == 20, "check size of SocketEndpoint");