jsocket.cpp 156 KB

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