jsocket.cpp 156 KB

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