jsocket.cpp 192 KB

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