jsocket.cpp 206 KB

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