jsocket.cpp 191 KB

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