jsocket.cpp 190 KB

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