jsocket.cpp 156 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420
  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 32768
  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. int err = ERRNO();
  3249. LOGERR(err,1,"Socket closed during trigger select");
  3250. }
  3251. #else
  3252. closedummy();
  3253. #endif
  3254. }
  3255. void resettrigger()
  3256. {
  3257. #ifdef _USE_PIPE_FOR_SELECT_TRIGGER
  3258. CriticalBlock block(sect);
  3259. char c;
  3260. while((::read(dummysock[0], &c, sizeof(c))) == sizeof(c));
  3261. #endif
  3262. }
  3263. #ifdef _WIN32
  3264. #define HASHTABSIZE 256
  3265. #define HASHNULL (HASHTABSIZE-1)
  3266. #define HASHTABMASK (HASHTABSIZE-1)
  3267. byte hashtab[HASHTABSIZE];
  3268. #define HASHSOCKET(s) ((((unsigned)s)>>2)&HASHTABMASK) // with some knowledge of windows handles
  3269. void inithash()
  3270. {
  3271. memset(&hashtab,HASHNULL,sizeof(hashtab));
  3272. assertex(FD_SETSIZE<255);
  3273. }
  3274. void reinithash()
  3275. { // done this way because index of items changes and hash table not that big
  3276. inithash();
  3277. assertex(items.ordinality()<HASHTABSIZE-1);
  3278. ForEachItemIn(i,items) {
  3279. unsigned h = HASHSOCKET(items.item(i).handle);
  3280. loop {
  3281. if (hashtab[h]==HASHNULL) {
  3282. hashtab[h] = (byte)i;
  3283. break;
  3284. }
  3285. if (++h==HASHTABSIZE)
  3286. h = 0;
  3287. }
  3288. }
  3289. }
  3290. inline SelectItem &findhash(T_SOCKET handle)
  3291. {
  3292. unsigned h = HASHSOCKET(handle);
  3293. unsigned sh = h;
  3294. loop {
  3295. SelectItem &i=items.item(hashtab[h]);
  3296. if (i.handle==handle)
  3297. return i;
  3298. if (++h==HASHTABSIZE)
  3299. h = 0;
  3300. assertex(h!=sh);
  3301. }
  3302. }
  3303. inline void processfds(T_FD_SET &s,byte mode,SelectItemArray &tonotify)
  3304. {
  3305. loop {
  3306. T_SOCKET sock = popfds(s);
  3307. if (!sock)
  3308. break;
  3309. if (sock!=dummysock) {
  3310. SelectItem si = findhash(sock); // nb copies
  3311. if (!si.del) {
  3312. si.mode = mode;
  3313. tonotify.append(si);
  3314. }
  3315. }
  3316. }
  3317. }
  3318. #endif
  3319. public:
  3320. IMPLEMENT_IINTERFACE;
  3321. CSocketSelectThread(const char *trc)
  3322. : Thread("CSocketSelectThread")
  3323. {
  3324. dummysockopen = false;
  3325. opendummy();
  3326. terminating = false;
  3327. atomic_set(&tickwait,0);
  3328. waitingchange = 0;
  3329. selectvarschange = false;
  3330. validateselecterror = 0;
  3331. validateerrcount = 0;
  3332. offset = 0;
  3333. selecttrace = trc;
  3334. basesize = 0;
  3335. #ifdef _WIN32
  3336. inithash();
  3337. #endif
  3338. }
  3339. ~CSocketSelectThread()
  3340. {
  3341. closedummy();
  3342. ForEachItemIn(i,items) {
  3343. try {
  3344. SelectItem &si = items.item(i);
  3345. si.sock->Release();
  3346. si.nfy->Release();
  3347. }
  3348. catch (IException *e) {
  3349. EXCLOG(e,"~CSocketSelectThread");
  3350. e->Release();
  3351. }
  3352. }
  3353. }
  3354. Owned<IException> termexcept;
  3355. void updateItems()
  3356. {
  3357. // must be in CriticalBlock block(sect);
  3358. unsigned n = items.ordinality();
  3359. bool hashupdateneeded = (n!=basesize); // additions all come at end
  3360. for (unsigned i=0;i<n;) {
  3361. SelectItem &si = items.item(i);
  3362. if (si.del) {
  3363. si.nfy->Release();
  3364. try {
  3365. #ifdef SOCKTRACE
  3366. PROGLOG("CSocketSelectThread::updateItems release %d",si.handle);
  3367. #endif
  3368. si.sock->Release();
  3369. }
  3370. catch (IException *e) {
  3371. EXCLOG(e,"CSocketSelectThread::updateItems");
  3372. e->Release();
  3373. }
  3374. n--;
  3375. if (i<n)
  3376. si = items.item(n);
  3377. items.remove(n);
  3378. hashupdateneeded = true;
  3379. }
  3380. else
  3381. i++;
  3382. }
  3383. assertex(n<=XFD_SETSIZE-1);
  3384. #ifdef _WIN32
  3385. if (hashupdateneeded)
  3386. reinithash();
  3387. #endif
  3388. basesize = n;
  3389. }
  3390. bool add(ISocket *sock,unsigned mode,ISocketSelectNotify *nfy)
  3391. {
  3392. // maybe check once to prevent 1st delay? TBD
  3393. CriticalBlock block(sect);
  3394. unsigned n=0;
  3395. ForEachItemIn(i,items) {
  3396. SelectItem &si = items.item(i);
  3397. if (!si.del) {
  3398. if (si.sock==sock) {
  3399. si.del = true;
  3400. }
  3401. else
  3402. n++;
  3403. }
  3404. }
  3405. if (n>=XFD_SETSIZE-1) // leave 1 spare
  3406. return false;
  3407. SelectItem sn;
  3408. sn.nfy = LINK(nfy);
  3409. sn.sock = LINK(sock);
  3410. sn.mode = (byte)mode;
  3411. sn.handle = (T_SOCKET)sock->OShandle();
  3412. CHECKSOCKRANGE(sn.handle);
  3413. sn.del = false;
  3414. items.append(sn);
  3415. selectvarschange = true;
  3416. triggerselect();
  3417. return true;
  3418. }
  3419. bool remove(ISocket *sock)
  3420. {
  3421. if (terminating)
  3422. return false;
  3423. CriticalBlock block(sect);
  3424. if (sock==NULL) { // wait until no changes outstanding
  3425. while (selectvarschange) {
  3426. waitingchange++;
  3427. CriticalUnblock unblock(sect);
  3428. waitingchangesem.wait();
  3429. }
  3430. return true;
  3431. }
  3432. ForEachItemIn(i,items) {
  3433. SelectItem &si = items.item(i);
  3434. if (!si.del&&(si.sock==sock)) {
  3435. si.del = true;
  3436. selectvarschange = true;
  3437. triggerselect();
  3438. return true;
  3439. }
  3440. }
  3441. return false;
  3442. }
  3443. void stop(bool wait)
  3444. {
  3445. terminating = true;
  3446. triggerselect();
  3447. if (wait)
  3448. join();
  3449. }
  3450. bool sockOk(T_SOCKET sock)
  3451. {
  3452. PROGLOG("CSocketSelectThread: sockOk testing %d",sock);
  3453. int err = 0;
  3454. int t=0;
  3455. socklen_t tl = sizeof(t);
  3456. if (getsockopt(sock, SOL_SOCKET, SO_TYPE, (char *)&t, &tl)!=0) {
  3457. StringBuffer sockstr;
  3458. const char *tracename = sockstr.append((unsigned)sock).str();
  3459. LOGERR2(ERRNO(),1,"CSocketSelectThread select handle");
  3460. return false;
  3461. }
  3462. T_FD_SET fds;
  3463. struct timeval tv;
  3464. XFD_ZERO(&fds);
  3465. FD_SET((unsigned)sock, &fds);
  3466. //FD_SET((unsigned)sock, &except);
  3467. tv.tv_sec = 0;
  3468. tv.tv_usec = 0;
  3469. CHECKSOCKRANGE(sock);
  3470. int rc = ::select( sock + 1, NULL, (fd_set *)&fds, NULL, &tv );
  3471. if (rc<0) {
  3472. StringBuffer sockstr;
  3473. const char *tracename = sockstr.append((unsigned)sock).str();
  3474. LOGERR2(ERRNO(),2,"CSocketSelectThread select handle");
  3475. return false;
  3476. }
  3477. else if (rc>0)
  3478. PROGLOG("CSocketSelectThread: select handle %d selected(2) %d",sock,rc);
  3479. XFD_ZERO(&fds);
  3480. FD_SET((unsigned)sock, &fds);
  3481. tv.tv_sec = 0;
  3482. tv.tv_usec = 0;
  3483. rc = ::select( sock + 1, (fd_set *)&fds, NULL, NULL, &tv );
  3484. if (rc<0) {
  3485. StringBuffer sockstr;
  3486. const char *tracename = sockstr.append((unsigned)sock).str();
  3487. LOGERR2(ERRNO(),3,"CSocketSelectThread select handle");
  3488. return false;
  3489. }
  3490. else if (rc>0)
  3491. PROGLOG("CSocketSelectThread: select handle %d selected(2) %d",sock,rc);
  3492. return true;
  3493. }
  3494. bool checkSocks()
  3495. {
  3496. bool ret = false;
  3497. ForEachItemIn(i,items) {
  3498. SelectItem &si = items.item(i);
  3499. if (si.del)
  3500. ret = true; // maybe that bad one
  3501. else if (!sockOk(si.handle)) {
  3502. si.del = true;
  3503. ret = true;
  3504. }
  3505. }
  3506. return ret;
  3507. }
  3508. 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)
  3509. {
  3510. CriticalBlock block(sect);
  3511. selectvarschange = false;
  3512. if (waitingchange) {
  3513. waitingchangesem.signal(waitingchange);
  3514. waitingchange = 0;
  3515. }
  3516. if (validateselecterror) { // something went wrong so check sockets
  3517. validateerrcount++;
  3518. if (!checkSocks()) {
  3519. // bad socket not found
  3520. PROGLOG("CSocketSelectThread::updateSelectVars cannot find socket error");
  3521. if (validateerrcount>10)
  3522. throw MakeStringException(-1,"CSocketSelectThread:Socket select error %d",validateselecterror);
  3523. }
  3524. }
  3525. else
  3526. validateerrcount = 0;
  3527. updateItems();
  3528. XFD_ZERO( &rdfds );
  3529. XFD_ZERO( &wrfds );
  3530. XFD_ZERO( &exfds );
  3531. isrd=false;
  3532. iswr=false;
  3533. isex=false;
  3534. #ifdef _USE_PIPE_FOR_SELECT_TRIGGER
  3535. max_sockid=dummysockopen?dummysock[0]:0;
  3536. #else
  3537. opendummy();
  3538. max_sockid=dummysockopen?dummysock:0;
  3539. #endif
  3540. ni = items.ordinality();
  3541. #ifdef _WIN32
  3542. if (offset>=ni)
  3543. #endif
  3544. offset = 0;
  3545. unsigned j=offset;
  3546. ForEachItemIn(i,items) {
  3547. SelectItem &si = items.item(j);
  3548. j++;
  3549. if (j==ni)
  3550. j = 0;
  3551. if (si.mode & SELECTMODE_READ) {
  3552. FD_SET( si.handle, &rdfds );
  3553. isrd = true;
  3554. }
  3555. if (si.mode & SELECTMODE_WRITE) {
  3556. FD_SET( si.handle, &wrfds );
  3557. iswr = true;
  3558. }
  3559. if (si.mode & SELECTMODE_EXCEPT) {
  3560. FD_SET( si.handle, &exfds );
  3561. isex = true;
  3562. }
  3563. max_sockid=std::max(si.handle, max_sockid);
  3564. }
  3565. if (dummysockopen) {
  3566. #ifdef _USE_PIPE_FOR_SELECT_TRIGGER
  3567. FD_SET( dummysock[0], &rdfds );
  3568. isrd = true;
  3569. #else
  3570. FD_SET( dummysock, &exfds );
  3571. isex = true;
  3572. #endif
  3573. }
  3574. validateselecterror = 0;
  3575. max_sockid++;
  3576. #ifdef SOCKTRACE
  3577. PROGLOG("SOCKTRACE: selecting on %d sockets",ni);
  3578. #endif
  3579. }
  3580. int run()
  3581. {
  3582. try {
  3583. T_FD_SET rdfds;
  3584. T_FD_SET wrfds;
  3585. T_FD_SET exfds;
  3586. timeval selecttimeout;
  3587. bool isrd;
  3588. bool iswr;
  3589. bool isex;
  3590. T_SOCKET maxsockid;
  3591. unsigned ni;
  3592. selectvarschange = true;
  3593. unsigned numto = 0;
  3594. unsigned lastnumto = 0;
  3595. unsigned totnum = 0;
  3596. unsigned total = 0;
  3597. while (!terminating) {
  3598. selecttimeout.tv_sec = SELECT_TIMEOUT_SECS; // linux modifies so initialize inside loop
  3599. selecttimeout.tv_usec = 0;
  3600. if (selectvarschange) {
  3601. updateSelectVars(rdfds,wrfds,exfds,isrd,iswr,isex,ni,maxsockid);
  3602. }
  3603. if (ni==0) {
  3604. validateerrcount = 0;
  3605. atomic_inc(&tickwait);
  3606. if(!selectvarschange&&!terminating)
  3607. ticksem.wait(SELECT_TIMEOUT_SECS*1000);
  3608. atomic_dec(&tickwait);
  3609. continue;
  3610. }
  3611. T_FD_SET rs;
  3612. T_FD_SET ws;
  3613. T_FD_SET es;
  3614. T_FD_SET *rsp = isrd?cpyfds(rs,rdfds):NULL;
  3615. T_FD_SET *wsp = iswr?cpyfds(ws,wrfds):NULL;
  3616. T_FD_SET *esp = isex?cpyfds(es,exfds):NULL;
  3617. int n = ::select(maxsockid,(fd_set *)rsp,(fd_set *)wsp,(fd_set *)esp,&selecttimeout); // first parameter needed for posix
  3618. if (terminating)
  3619. break;
  3620. if (n < 0) {
  3621. CriticalBlock block(sect);
  3622. int err = ERRNO();
  3623. if (err != EINTRCALL) {
  3624. if (dummysockopen) {
  3625. LOGERR(err,12,"CSocketSelectThread select error"); // should cache error ?
  3626. validateselecterror = err;
  3627. #ifndef _USE_PIPE_FOR_SELECT_TRIGGER
  3628. closedummy(); // just in case was culprit
  3629. #endif
  3630. }
  3631. selectvarschange = true;
  3632. continue;
  3633. }
  3634. n = 0;
  3635. }
  3636. else if (n>0) {
  3637. validateerrcount = 0;
  3638. numto = 0;
  3639. lastnumto = 0;
  3640. total += n;
  3641. totnum++;
  3642. SelectItemArray tonotify;
  3643. {
  3644. CriticalBlock block(sect);
  3645. #ifdef _WIN32
  3646. if (isrd)
  3647. processfds(rs,SELECTMODE_READ,tonotify);
  3648. if (iswr)
  3649. processfds(ws,SELECTMODE_WRITE,tonotify);
  3650. if (isex)
  3651. processfds(es,SELECTMODE_EXCEPT,tonotify);
  3652. #else
  3653. unsigned i;
  3654. SelectItem *si = items.getArray(offset);
  3655. SelectItem *sie = items.getArray(ni-1)+1;
  3656. bool r = isrd;
  3657. bool w = iswr;
  3658. bool e = isex;
  3659. #ifdef _USE_PIPE_FOR_SELECT_TRIGGER
  3660. if (r&&dummysockopen&&findfds(rs,dummysock[0],r)) {
  3661. resettrigger();
  3662. --n;
  3663. }
  3664. #endif
  3665. for (i=0;(n>0)&&(i<ni);i++) {
  3666. if (r&&findfds(rs,si->handle,r)) {
  3667. if (!si->del) {
  3668. tonotify.append(*si);
  3669. tonotify.item(tonotify.length()-1).mode = SELECTMODE_READ;
  3670. }
  3671. --n;
  3672. }
  3673. if (w&&findfds(ws,si->handle,w)) {
  3674. if (!si->del) {
  3675. tonotify.append(*si);
  3676. tonotify.item(tonotify.length()-1).mode = SELECTMODE_WRITE;
  3677. }
  3678. --n;
  3679. }
  3680. if (e&&findfds(es,si->handle,e)) {
  3681. if (!si->del) {
  3682. tonotify.append(*si);
  3683. tonotify.item(tonotify.length()-1).mode = SELECTMODE_EXCEPT;
  3684. }
  3685. --n;
  3686. }
  3687. si++;
  3688. if (si==sie)
  3689. si = items.getArray();
  3690. }
  3691. #endif
  3692. }
  3693. ForEachItemIn(j,tonotify) {
  3694. SelectItem &si = tonotify.item(j);
  3695. try {
  3696. si.nfy->notifySelected(si.sock,si.mode); // ignore return
  3697. }
  3698. catch (IException *e) { // should be acted upon by notifySelected
  3699. EXCLOG(e,"CSocketSelectThread notifySelected");
  3700. throw ;
  3701. }
  3702. }
  3703. }
  3704. else {
  3705. validateerrcount = 0;
  3706. if ((++numto>=lastnumto*2)) {
  3707. lastnumto = numto;
  3708. if (selecttrace&&(numto>4))
  3709. PROGLOG("%s: Select Idle(%d), %d,%d,%0.2f",selecttrace,numto,totnum,total,totnum?((double)total/(double)totnum):0.0);
  3710. }
  3711. /*
  3712. if (numto&&(numto%100)) {
  3713. CriticalBlock block(sect);
  3714. if (!selectvarschange)
  3715. selectvarschange = checkSocks();
  3716. }
  3717. */
  3718. }
  3719. if (++offset>=ni)
  3720. offset = 0;
  3721. }
  3722. }
  3723. catch (IException *e) {
  3724. EXCLOG(e,"CSocketSelectThread");
  3725. termexcept.setown(e);
  3726. }
  3727. CriticalBlock block(sect);
  3728. try {
  3729. updateItems();
  3730. }
  3731. catch (IException *e) {
  3732. EXCLOG(e,"CSocketSelectThread(2)");
  3733. if (!termexcept)
  3734. termexcept.setown(e);
  3735. else
  3736. e->Release();
  3737. }
  3738. return 0;
  3739. }
  3740. };
  3741. class CSocketSelectHandler: public CInterface, implements ISocketSelectHandler
  3742. {
  3743. CIArrayOf<CSocketSelectThread> threads;
  3744. CriticalSection sect;
  3745. bool started;
  3746. StringAttr selecttrace;
  3747. public:
  3748. IMPLEMENT_IINTERFACE;
  3749. CSocketSelectHandler(const char *trc)
  3750. : selecttrace(trc)
  3751. {
  3752. started = false;
  3753. }
  3754. void start()
  3755. {
  3756. CriticalBlock block(sect);
  3757. if (!started) {
  3758. started = true;
  3759. ForEachItemIn(i,threads) {
  3760. threads.item(i).start();
  3761. }
  3762. }
  3763. }
  3764. void add(ISocket *sock,unsigned mode,ISocketSelectNotify *nfy)
  3765. {
  3766. CriticalBlock block(sect);
  3767. loop {
  3768. bool added=false;
  3769. ForEachItemIn(i,threads) {
  3770. if (added)
  3771. threads.item(i).remove(sock);
  3772. else
  3773. added = threads.item(i).add(sock,mode,nfy);
  3774. }
  3775. if (added)
  3776. return;
  3777. CSocketSelectThread *thread = new CSocketSelectThread(selecttrace);
  3778. threads.append(*thread);
  3779. if (started)
  3780. thread->start();
  3781. }
  3782. }
  3783. void remove(ISocket *sock)
  3784. {
  3785. CriticalBlock block(sect);
  3786. ForEachItemIn(i,threads) {
  3787. if (threads.item(i).remove(sock)&&sock)
  3788. break;
  3789. }
  3790. }
  3791. void stop(bool wait)
  3792. {
  3793. IException *e=NULL;
  3794. CriticalBlock block(sect);
  3795. unsigned i = 0;
  3796. while (i<threads.ordinality()) {
  3797. CSocketSelectThread &t=threads.item(i);
  3798. {
  3799. CriticalUnblock unblock(sect);
  3800. t.stop(wait); // not quite as quick as could be if wait true
  3801. }
  3802. if (wait && !e && t.termexcept)
  3803. e = t.termexcept.getClear();
  3804. i++;
  3805. }
  3806. #if 0 // don't throw error as too late
  3807. if (e)
  3808. throw e;
  3809. #else
  3810. ::Release(e);
  3811. #endif
  3812. }
  3813. };
  3814. ISocketSelectHandler *createSocketSelectHandler(const char *trc)
  3815. {
  3816. return new CSocketSelectHandler(trc);
  3817. }
  3818. void readBuffer(ISocket * socket, MemoryBuffer & buffer)
  3819. {
  3820. size32_t len;
  3821. socket->read(&len, sizeof(len));
  3822. _WINREV4(len);
  3823. if (len) {
  3824. void * target = buffer.reserve(len);
  3825. socket->read(target, len);
  3826. }
  3827. }
  3828. void readBuffer(ISocket * socket, MemoryBuffer & buffer, unsigned timeoutms)
  3829. {
  3830. size32_t len;
  3831. size32_t sizeGot;
  3832. socket->readtms(&len, sizeof(len), sizeof(len), sizeGot, timeoutms);
  3833. _WINREV4(len);
  3834. if (len) {
  3835. void * target = buffer.reserve(len);
  3836. socket->readtms(target, len, len, sizeGot, timeoutms);
  3837. }
  3838. }
  3839. void writeBuffer(ISocket * socket, MemoryBuffer & buffer)
  3840. {
  3841. unsigned len = buffer.length();
  3842. _WINREV4(len);
  3843. socket->write(&len, sizeof(len));
  3844. if (len)
  3845. socket->write(buffer.toByteArray(), buffer.length());
  3846. }
  3847. bool catchReadBuffer(ISocket * socket, MemoryBuffer & buffer)
  3848. {
  3849. try
  3850. {
  3851. readBuffer(socket, buffer);
  3852. return true;
  3853. }
  3854. catch (IException * e)
  3855. {
  3856. switch (e->errorCode())
  3857. {
  3858. case JSOCKERR_graceful_close:
  3859. break;
  3860. default:
  3861. EXCLOG(e,"catchReadBuffer");
  3862. break;
  3863. }
  3864. e->Release();
  3865. }
  3866. return false;
  3867. }
  3868. bool catchReadBuffer(ISocket * socket, MemoryBuffer & buffer, unsigned timeoutms)
  3869. {
  3870. try
  3871. {
  3872. readBuffer(socket, buffer, timeoutms);
  3873. return true;
  3874. }
  3875. catch (IException * e)
  3876. {
  3877. switch (e->errorCode())
  3878. {
  3879. case JSOCKERR_graceful_close:
  3880. break;
  3881. default:
  3882. EXCLOG(e,"catchReadBuffer");
  3883. break;
  3884. }
  3885. e->Release();
  3886. }
  3887. return false;
  3888. }
  3889. bool catchWriteBuffer(ISocket * socket, MemoryBuffer & buffer)
  3890. {
  3891. try
  3892. {
  3893. writeBuffer(socket, buffer);
  3894. return true;
  3895. }
  3896. catch (IException * e)
  3897. {
  3898. EXCLOG(e,"catchWriteBuffer");
  3899. e->Release();
  3900. }
  3901. return false;
  3902. }
  3903. // utility interface for simple conversations
  3904. // conversation is always between two ends,
  3905. // at any given time one end must be receiving and other sending (though these may swap during the conversation)
  3906. class CSingletonSocketConnection: public CInterface, implements IConversation
  3907. {
  3908. Owned<ISocket> sock;
  3909. Owned<ISocket> listensock;
  3910. enum { Snone, Saccept, Sconnect, Srecv, Ssend, Scancelled } state;
  3911. bool accepting;
  3912. bool cancelling;
  3913. SocketEndpoint ep;
  3914. CriticalSection crit;
  3915. public:
  3916. IMPLEMENT_IINTERFACE;
  3917. CSingletonSocketConnection(SocketEndpoint &_ep)
  3918. {
  3919. ep = _ep;
  3920. state = Snone;
  3921. cancelling = false;
  3922. }
  3923. ~CSingletonSocketConnection()
  3924. {
  3925. try {
  3926. if (sock)
  3927. sock->close();
  3928. }
  3929. catch (IException *e) {
  3930. if (e->errorCode()!=JSOCKERR_graceful_close)
  3931. EXCLOG(e,"CSingletonSocketConnection close");
  3932. e->Release();
  3933. }
  3934. }
  3935. bool connect(unsigned timeoutms)
  3936. {
  3937. CriticalBlock block(crit);
  3938. if (cancelling)
  3939. state = Scancelled;
  3940. if (state==Scancelled)
  3941. return false;
  3942. assertex(!sock);
  3943. ISocket *newsock=NULL;
  3944. state = Sconnect;
  3945. unsigned start;
  3946. if (timeoutms!=(unsigned)INFINITE)
  3947. start = msTick();
  3948. while (state==Sconnect) {
  3949. try {
  3950. CriticalUnblock unblock(crit);
  3951. newsock = ISocket::connect_wait(ep,1000*60*4);
  3952. break;
  3953. }
  3954. catch (IException * e) {
  3955. if ((e->errorCode()==JSOCKERR_timeout_expired)||(e->errorCode()==JSOCKERR_connection_failed)) {
  3956. e->Release();
  3957. if ((state==Sconnect)&&(timeoutms!=(unsigned)INFINITE)&&(msTick()-start>timeoutms)) {
  3958. state = Snone;
  3959. return false;
  3960. }
  3961. }
  3962. else {
  3963. state = Scancelled;
  3964. EXCLOG(e,"CSingletonSocketConnection::connect");
  3965. e->Release();
  3966. return false;
  3967. }
  3968. }
  3969. }
  3970. if (state!=Sconnect) {
  3971. ::Release(newsock);
  3972. newsock = NULL;
  3973. }
  3974. if (!newsock) {
  3975. state = Scancelled;
  3976. return false;
  3977. }
  3978. sock.setown(newsock);
  3979. return true;
  3980. }
  3981. bool send(MemoryBuffer &mb)
  3982. {
  3983. CriticalBlock block(crit);
  3984. if (cancelling)
  3985. state = Scancelled;
  3986. if (state==Scancelled)
  3987. return false;
  3988. assertex(sock);
  3989. state = Srecv;
  3990. try {
  3991. CriticalUnblock unblock(crit);
  3992. writeBuffer(sock,mb);
  3993. }
  3994. catch (IException * e) {
  3995. state = Scancelled;
  3996. EXCLOG(e,"CSingletonSocketConnection::send");
  3997. e->Release();
  3998. return false;
  3999. }
  4000. state = Snone;
  4001. return true;
  4002. }
  4003. unsigned short setRandomPort(unsigned short base, unsigned num)
  4004. {
  4005. loop {
  4006. try {
  4007. ep.port = base+(unsigned short)(getRandom()%num);
  4008. listensock.setown(ISocket::create(ep.port));
  4009. return ep.port;
  4010. }
  4011. catch (IException *e) {
  4012. if (e->errorCode()!=JSOCKERR_port_in_use) {
  4013. state = Scancelled;
  4014. EXCLOG(e,"CSingletonSocketConnection::setRandomPort");
  4015. e->Release();
  4016. break;
  4017. }
  4018. e->Release();
  4019. }
  4020. }
  4021. return 0;
  4022. }
  4023. bool accept(unsigned timeoutms)
  4024. {
  4025. CriticalBlock block(crit);
  4026. if (cancelling)
  4027. state = Scancelled;
  4028. if (state==Scancelled)
  4029. return false;
  4030. if (!sock) {
  4031. ISocket *newsock=NULL;
  4032. state = Saccept;
  4033. loop {
  4034. try {
  4035. {
  4036. CriticalUnblock unblock(crit);
  4037. if (!listensock)
  4038. listensock.setown(ISocket::create(ep.port));
  4039. if ((timeoutms!=(unsigned)INFINITE)&&(!listensock->wait_read(timeoutms))) {
  4040. state = Snone;
  4041. return false;
  4042. }
  4043. }
  4044. if (cancelling)
  4045. state = Scancelled;
  4046. if (state==Scancelled)
  4047. return false;
  4048. {
  4049. CriticalUnblock unblock(crit);
  4050. newsock=listensock->accept(true);
  4051. break;
  4052. }
  4053. }
  4054. catch (IException *e) {
  4055. if (e->errorCode()==JSOCKERR_graceful_close)
  4056. PROGLOG("CSingletonSocketConnection: Closed socket on accept - retrying...");
  4057. else {
  4058. state = Scancelled;
  4059. EXCLOG(e,"CSingletonSocketConnection::accept");
  4060. e->Release();
  4061. break;
  4062. }
  4063. e->Release();
  4064. }
  4065. }
  4066. if (state!=Saccept) {
  4067. ::Release(newsock);
  4068. newsock = NULL;
  4069. }
  4070. if (!newsock) {
  4071. state = Scancelled;
  4072. return false;
  4073. }
  4074. sock.setown(newsock);
  4075. }
  4076. return true;
  4077. }
  4078. bool recv(MemoryBuffer &mb, unsigned timeoutms)
  4079. {
  4080. CriticalBlock block(crit);
  4081. if (cancelling)
  4082. state = Scancelled;
  4083. if (state==Scancelled)
  4084. return false;
  4085. assertex(sock);
  4086. state = Srecv;
  4087. try {
  4088. CriticalUnblock unblock(crit);
  4089. readBuffer(sock,mb,timeoutms);
  4090. }
  4091. catch (IException *e) {
  4092. if (e->errorCode()==JSOCKERR_timeout_expired)
  4093. state = Snone;
  4094. else {
  4095. state = Scancelled;
  4096. if (e->errorCode()!=JSOCKERR_graceful_close)
  4097. EXCLOG(e,"CSingletonSocketConnection::recv");
  4098. }
  4099. e->Release();
  4100. return false;
  4101. }
  4102. state = Snone;
  4103. return true;
  4104. }
  4105. virtual void cancel()
  4106. {
  4107. CriticalBlock block(crit);
  4108. while (state!=Scancelled) {
  4109. cancelling = true;
  4110. try {
  4111. switch (state) {
  4112. case Saccept:
  4113. {
  4114. if (listensock)
  4115. listensock->cancel_accept();
  4116. }
  4117. break;
  4118. case Sconnect:
  4119. // wait for timeout
  4120. break;
  4121. case Srecv:
  4122. {
  4123. if (sock)
  4124. sock->close();
  4125. }
  4126. break;
  4127. case Ssend:
  4128. // wait for finished
  4129. break;
  4130. default:
  4131. state = Scancelled;
  4132. break;
  4133. }
  4134. }
  4135. catch (IException *e) {
  4136. EXCLOG(e,"CSingletonSocketConnection::cancel");
  4137. e->Release();
  4138. }
  4139. {
  4140. CriticalUnblock unblock(crit);
  4141. Sleep(1000);
  4142. }
  4143. }
  4144. }
  4145. };
  4146. IConversation *createSingletonSocketConnection(unsigned short port,SocketEndpoint *_ep)
  4147. {
  4148. SocketEndpoint ep;
  4149. if (_ep)
  4150. ep = *_ep;
  4151. if (port)
  4152. ep.port = port;
  4153. return new CSingletonSocketConnection(ep);
  4154. }
  4155. // interface for reading from multiple sockets using the BF_SYNC_TRANSFER_PUSH protocol
  4156. class CSocketBufferReader: public CInterface, implements ISocketBufferReader
  4157. {
  4158. class SocketElem: public CInterface, implements ISocketSelectNotify
  4159. {
  4160. CSocketBufferReader *parent;
  4161. unsigned num; // top bit used for ready
  4162. MemoryAttr blk;
  4163. CriticalSection sect;
  4164. Linked<ISocket> sock;
  4165. bool active;
  4166. bool pending;
  4167. public:
  4168. IMPLEMENT_IINTERFACE;
  4169. void init(CSocketBufferReader *_parent,ISocket *_sock,unsigned _n)
  4170. {
  4171. parent = _parent;
  4172. num = _n;
  4173. sock.set(_sock);
  4174. active = true;
  4175. pending = false;
  4176. }
  4177. virtual bool notifySelected(ISocket *socket,unsigned selected)
  4178. {
  4179. assertex(sock==socket);
  4180. {
  4181. CriticalBlock block(sect);
  4182. if (pending) {
  4183. active = false;
  4184. parent->remove(sock);
  4185. return false;
  4186. }
  4187. pending = true;
  4188. unsigned t1=usTick();
  4189. size32_t sz = sock->receive_block_size();
  4190. unsigned t2=usTick();
  4191. if (sz)
  4192. sock->receive_block(blk.allocate(sz),sz);
  4193. else
  4194. parent->remove(sock);
  4195. unsigned t3=usTick();
  4196. if (t3-t1>60*1000000)
  4197. PROGLOG("CSocketBufferReader(%d): slow receive_block (%d,%d) sz=%d",num,t2-t1,t3-t2,sz);
  4198. }
  4199. parent->enqueue(this); // nb outside sect critical block
  4200. return false; // always return false
  4201. }
  4202. unsigned get(MemoryBuffer &mb)
  4203. {
  4204. CriticalBlock block(sect);
  4205. assertex(pending);
  4206. size32_t sz = blk.length();
  4207. if (sz)
  4208. mb.setBuffer(sz,blk.detach(),true);
  4209. pending = false;
  4210. if (!active) {
  4211. active = true;
  4212. parent->add(*this);
  4213. }
  4214. return num;
  4215. }
  4216. size32_t size()
  4217. {
  4218. return blk.length();
  4219. }
  4220. ISocket *getSocket() { return sock; }
  4221. } *elems;
  4222. SimpleInterThreadQueueOf<SocketElem, false> readyq;
  4223. Owned<ISocketSelectHandler> selecthandler;
  4224. size32_t buffersize;
  4225. size32_t buffermax;
  4226. unsigned bufferwaiting;
  4227. CriticalSection buffersect;
  4228. Semaphore buffersem;
  4229. bool isdone;
  4230. public:
  4231. IMPLEMENT_IINTERFACE;
  4232. CSocketBufferReader(const char *trc)
  4233. {
  4234. selecthandler.setown(createSocketSelectHandler(trc));
  4235. elems = NULL;
  4236. }
  4237. ~CSocketBufferReader()
  4238. {
  4239. delete [] elems;
  4240. }
  4241. virtual void init(unsigned num,ISocket **sockets,size32_t _buffermax)
  4242. {
  4243. elems = new SocketElem[num];
  4244. for (unsigned i=0;i<num;i++) {
  4245. ISocket *sock = sockets[i];
  4246. if (sock) { // can have gaps
  4247. elems[i].init(this,sock,i);
  4248. add(elems[i]);
  4249. }
  4250. }
  4251. buffersize = 0;
  4252. buffermax = _buffermax;
  4253. bufferwaiting = 0;
  4254. isdone = false;
  4255. selecthandler->start();
  4256. }
  4257. virtual unsigned get(MemoryBuffer &mb)
  4258. {
  4259. SocketElem &e = *readyq.dequeue();
  4260. CriticalBlock block(buffersect);
  4261. assertex(buffersize>=e.size());
  4262. buffersize-=e.size();
  4263. if (bufferwaiting) {
  4264. buffersem.signal(bufferwaiting);
  4265. bufferwaiting = 0;
  4266. }
  4267. return e.get(mb);
  4268. }
  4269. virtual void done(bool wait)
  4270. {
  4271. buffersem.signal(0x10000);
  4272. isdone = true;
  4273. selecthandler->stop(wait);
  4274. if (wait) {
  4275. delete [] elems;
  4276. elems = NULL;
  4277. }
  4278. }
  4279. void enqueue(SocketElem *elem)
  4280. {
  4281. if (elem) {
  4282. CriticalBlock block(buffersect);
  4283. size32_t sz = elem->size();
  4284. while ((buffersize>0)&&(sz>0)&&(buffersize+sz>buffermax)) {
  4285. if (isdone)
  4286. return;
  4287. bufferwaiting++;
  4288. CriticalUnblock unblock(buffersect);
  4289. buffersem.wait();
  4290. }
  4291. buffersize += sz;
  4292. }
  4293. readyq.enqueue(elem);
  4294. }
  4295. void remove(ISocket *sock)
  4296. {
  4297. selecthandler->remove(sock);
  4298. }
  4299. void add(SocketElem &elem)
  4300. {
  4301. selecthandler->add(elem.getSocket(),SELECTMODE_READ,&elem);
  4302. }
  4303. };
  4304. ISocketBufferReader *createSocketBufferReader(const char *trc)
  4305. {
  4306. return new CSocketBufferReader(trc);
  4307. }
  4308. extern jlib_decl void markNodeCentral(SocketEndpoint &ep)
  4309. {
  4310. #ifdef CENTRAL_NODE_RANDOM_DELAY
  4311. CriticalBlock block(CSocket::crit);
  4312. CentralNodeArray.append(ep);
  4313. #endif
  4314. }
  4315. static CSocket *prepareSocket(unsigned idx,const SocketEndpoint &ep, ISocketConnectNotify &inotify)
  4316. {
  4317. Owned<CSocket> sock = new CSocket(ep,sm_tcp,NULL);
  4318. int err = sock->pre_connect(false);
  4319. if ((err == EINPROGRESS)||(err == EWOULDBLOCK))
  4320. return sock.getClear();
  4321. if (err==0) {
  4322. int err = sock->post_connect();
  4323. if (err==0)
  4324. inotify.connected(idx,ep,sock);
  4325. else {
  4326. sock->errclose();
  4327. inotify.failed(idx,ep,err);
  4328. }
  4329. }
  4330. else
  4331. inotify.failed(idx,ep,err);
  4332. return NULL;
  4333. }
  4334. void multiConnect(const SocketEndpointArray &eps,ISocketConnectNotify &inotify,unsigned timeout)
  4335. {
  4336. class SocketElem: public CInterface, implements ISocketSelectNotify
  4337. {
  4338. CriticalSection *sect;
  4339. ISocketSelectHandler *handler;
  4340. unsigned *remaining;
  4341. Semaphore *notifysem;
  4342. ISocketConnectNotify *inotify;
  4343. public:
  4344. Owned<CSocket> sock;
  4345. SocketEndpoint ep;
  4346. unsigned idx;
  4347. IMPLEMENT_IINTERFACE;
  4348. void init(CSocket *_sock,unsigned _idx,SocketEndpoint &_ep,CriticalSection *_sect,ISocketSelectHandler *_handler,ISocketConnectNotify *_inotify, unsigned *_remaining, Semaphore *_notifysem)
  4349. {
  4350. ep = _ep;
  4351. idx = _idx;
  4352. inotify = _inotify;
  4353. sock.setown(_sock),
  4354. sect = _sect;
  4355. handler = _handler;
  4356. remaining = _remaining;
  4357. notifysem = _notifysem;
  4358. }
  4359. virtual bool notifySelected(ISocket *socket,unsigned selected)
  4360. {
  4361. CriticalBlock block(*sect);
  4362. handler->remove(socket);
  4363. int err = sock->post_connect();
  4364. CSocket *newsock = NULL;
  4365. {
  4366. CriticalUnblock unblock(*sect); // up to caller to cope with multithread
  4367. if (err==0)
  4368. inotify->connected(idx,ep,sock);
  4369. else if ((err==ETIMEDOUT)||(err==ECONNREFUSED)) {
  4370. // don't give up so easily (maybe listener not yet started (i.e. racing))
  4371. newsock = prepareSocket(idx,ep,*inotify);
  4372. Sleep(100); // not very nice but without this would just loop
  4373. }
  4374. else
  4375. inotify->failed(idx,ep,err);
  4376. }
  4377. if (newsock) {
  4378. sock.setown(newsock);
  4379. handler->add(sock,SELECTMODE_WRITE|SELECTMODE_EXCEPT,this);
  4380. }
  4381. else {
  4382. sock.clear();
  4383. (*remaining)--;
  4384. notifysem->signal();
  4385. }
  4386. return false;
  4387. }
  4388. } *elems;
  4389. unsigned n = eps.ordinality();
  4390. unsigned remaining = n;
  4391. if (!n)
  4392. return;
  4393. elems = new SocketElem[n];
  4394. unsigned i;
  4395. CriticalSection sect;
  4396. Semaphore notifysem;
  4397. Owned<ISocketSelectHandler> selecthandler = createSocketSelectHandler(
  4398. #ifdef _DEBUG
  4399. "multiConnect"
  4400. #else
  4401. NULL
  4402. #endif
  4403. );
  4404. StringBuffer name;
  4405. for (i=0;i<n;i++) {
  4406. CSocket* sock = prepareSocket(i,eps.item(i),inotify);
  4407. if (sock) {
  4408. elems[i].init(sock,i,eps.item(i),&sect,selecthandler,&inotify,&remaining,&notifysem);
  4409. selecthandler->add(sock,SELECTMODE_WRITE|SELECTMODE_EXCEPT,&elems[i]);
  4410. }
  4411. else
  4412. remaining--;
  4413. }
  4414. if (remaining) {
  4415. unsigned lastremaining=remaining;
  4416. selecthandler->start();
  4417. loop {
  4418. bool to=!notifysem.wait(timeout);
  4419. {
  4420. CriticalBlock block(sect);
  4421. if (remaining==0)
  4422. break;
  4423. if (to&&(remaining==lastremaining))
  4424. break; // nothing happened recently
  4425. lastremaining = remaining;
  4426. }
  4427. }
  4428. selecthandler->stop(true);
  4429. }
  4430. selecthandler.clear();
  4431. if (remaining) {
  4432. for (unsigned j=0;j<n;j++) { // mop up timeouts
  4433. SocketElem &elem = elems[j];
  4434. if (elem.sock.get()) {
  4435. elem.sock.clear();
  4436. inotify.failed(j,elem.ep,-1);
  4437. remaining--;
  4438. if (remaining==0)
  4439. break;
  4440. }
  4441. }
  4442. delete [] elems;
  4443. }
  4444. }
  4445. void multiConnect(const SocketEndpointArray &eps, PointerIArrayOf<ISocket> &retsockets,unsigned timeout)
  4446. {
  4447. unsigned n = eps.ordinality();
  4448. if (n==0)
  4449. return;
  4450. if (n==1) { // no need for multi
  4451. ISocket *sock = NULL;
  4452. try {
  4453. sock = ISocket::connect_timeout(eps.item(0),timeout);
  4454. }
  4455. catch (IException *e) { // ignore error just append NULL
  4456. sock = NULL;
  4457. e->Release();
  4458. }
  4459. retsockets.append(sock);
  4460. return;
  4461. }
  4462. while (retsockets.ordinality()<n)
  4463. retsockets.append(NULL);
  4464. CriticalSection sect;
  4465. class cNotify: implements ISocketConnectNotify
  4466. {
  4467. CriticalSection &sect;
  4468. PointerIArrayOf<ISocket> &retsockets;
  4469. public:
  4470. cNotify(PointerIArrayOf<ISocket> &_retsockets,CriticalSection &_sect)
  4471. : retsockets(_retsockets),sect(_sect)
  4472. {
  4473. }
  4474. void connected(unsigned idx,const SocketEndpoint &ep,ISocket *sock)
  4475. {
  4476. CriticalBlock block(sect);
  4477. assertex(idx<retsockets.ordinality());
  4478. sock->Link();
  4479. retsockets.replace(sock,idx);
  4480. }
  4481. void failed(unsigned idx,const SocketEndpoint &ep,int err)
  4482. {
  4483. StringBuffer s;
  4484. PROGLOG("multiConnect failed to %s with %d",ep.getUrlStr(s).str(),err);
  4485. }
  4486. } notify(retsockets,sect);
  4487. multiConnect(eps,notify,timeout);
  4488. }
  4489. inline void flushText(StringBuffer &text,unsigned short port,unsigned &rep,unsigned &range)
  4490. {
  4491. if (rep) {
  4492. text.append('*').append(rep+1);
  4493. rep = 0;
  4494. }
  4495. else if (range) {
  4496. text.append('-').append(range);
  4497. range = 0;
  4498. }
  4499. if (port)
  4500. text.append(':').append(port);
  4501. }
  4502. StringBuffer &SocketEndpointArray::getText(StringBuffer &text)
  4503. {
  4504. unsigned count = ordinality();
  4505. if (!count)
  4506. return text;
  4507. if (count==1)
  4508. return item(0).getUrlStr(text);
  4509. byte lastip[4];
  4510. const SocketEndpoint &first = item(0);
  4511. bool lastis4 = first.getNetAddress(sizeof(lastip),&lastip)==sizeof(lastip);
  4512. unsigned short lastport = first.port;
  4513. first.getIpText(text);
  4514. unsigned rep=0;
  4515. unsigned range=0;
  4516. for (unsigned i=1;i<count;i++) {
  4517. byte ip[4];
  4518. const SocketEndpoint &ep = item(i);
  4519. bool is4 = ep.getNetAddress(sizeof(ip),&ip)==sizeof(ip);
  4520. if (!lastis4||!is4) {
  4521. flushText(text,lastport,rep,range);
  4522. text.append(',');
  4523. ep.getIpText(text);
  4524. }
  4525. else { // try and shorten
  4526. unsigned j;
  4527. for (j=0;j<4;j++)
  4528. if (ip[j]!=lastip[j])
  4529. break;
  4530. if (ep.port==lastport) {
  4531. if (j==4) {
  4532. if (range) // cant have range and rep
  4533. j--; // pretend only 3 matched
  4534. else {
  4535. rep++;
  4536. continue;
  4537. }
  4538. }
  4539. else if ((j==3)&&(lastip[3]+1==ip[3])&&(rep==0)) {
  4540. range = ip[3];
  4541. lastip[3] = (byte)range;
  4542. continue;
  4543. }
  4544. }
  4545. flushText(text,lastport,rep,range);
  4546. // output diff
  4547. text.append(',');
  4548. if (j==4)
  4549. j--;
  4550. for (unsigned k=j;k<4;k++) {
  4551. if (k>j)
  4552. text.append('.');
  4553. text.append((int)ip[k]);
  4554. }
  4555. }
  4556. memcpy(&lastip,&ip,sizeof(lastip));
  4557. lastis4 = is4;
  4558. lastport = ep.port;
  4559. }
  4560. flushText(text,lastport,rep,range);
  4561. return text;
  4562. }
  4563. inline const char *getnum(const char *s,unsigned &n)
  4564. {
  4565. n = 0;
  4566. while (isdigit(*s)) {
  4567. n = n*10+(*s-'0');
  4568. s++;
  4569. }
  4570. return s;
  4571. }
  4572. inline bool appendv4range(SocketEndpointArray *array,char *str,SocketEndpoint &ep, unsigned defport)
  4573. {
  4574. char *s = str;
  4575. unsigned dc = 0;
  4576. unsigned port = defport;
  4577. unsigned rng = 0;
  4578. unsigned rep = 1;
  4579. bool notip = false;
  4580. while (*s) {
  4581. if (*s=='.') {
  4582. dc++;
  4583. s++;
  4584. }
  4585. else if (*s==':') {
  4586. *s = 0;
  4587. s = (char *)getnum(s+1,port);
  4588. }
  4589. else if (*s=='-') {
  4590. *s = 0;
  4591. s = (char *)getnum(s+1,rng);
  4592. }
  4593. else if (*s=='*') {
  4594. *s = 0;
  4595. s = (char *)getnum(s+1,rep);
  4596. }
  4597. else {
  4598. if (!isdigit(*s))
  4599. notip = true;
  4600. s++;
  4601. }
  4602. }
  4603. ep.port = port;
  4604. if (*str) {
  4605. if (!notip&&((dc<3)&&((dc!=1)||(strlen(str)!=1)))) {
  4606. if (!ep.isIp4()) {
  4607. return false;
  4608. }
  4609. StringBuffer tmp;
  4610. ep.getIpText(tmp);
  4611. size32_t l = tmp.length();
  4612. dc++;
  4613. loop {
  4614. if (tmp.length()==0)
  4615. return false;
  4616. if (tmp.charAt(tmp.length()-1)=='.')
  4617. if (--dc==0)
  4618. break;
  4619. tmp.setLength(tmp.length()-1);
  4620. }
  4621. tmp.append(str);
  4622. if (rng) {
  4623. tmp.appendf("-%d",rng);
  4624. rep = ep.ipsetrange(tmp.str());
  4625. }
  4626. else
  4627. ep.ipset(tmp.str());
  4628. }
  4629. else if (rng) { // not nice as have to add back range (must be better way - maybe ipincrementto) TBD
  4630. StringBuffer tmp;
  4631. tmp.appendf("%s-%d",str,rng);
  4632. rep = ep.ipsetrange(tmp.str());
  4633. }
  4634. else if (*str)
  4635. ep.ipset(str);
  4636. if (ep.isNull())
  4637. ep.port = 0;
  4638. for (unsigned i=0;i<rep;i++) {
  4639. array->append(ep);
  4640. if (rng)
  4641. ep.ipincrement(1);
  4642. }
  4643. }
  4644. else {// just a port change
  4645. if (ep.isNull()) // avoid null values with ports
  4646. ep.port = 0;
  4647. array->append(ep);
  4648. }
  4649. return true;
  4650. }
  4651. void SocketEndpointArray::fromText(const char *text,unsigned defport)
  4652. {
  4653. // this is quite complicated with (mixed) IPv4 and IPv6
  4654. // only support 'full' IPv6 and no ranges
  4655. char *str = strdup(text);
  4656. char *s = str;
  4657. SocketEndpoint ep;
  4658. bool eol = false;
  4659. loop {
  4660. while (isspace(*s)||(*s==','))
  4661. s++;
  4662. if (!*s)
  4663. break;
  4664. char *e=s;
  4665. if (*e=='[') { // we have a IPv6
  4666. while (*e&&(*e!=']'))
  4667. e++;
  4668. while ((*e!=',')&&!isspace(*e)) {
  4669. if (!*s) {
  4670. eol = true;
  4671. break;
  4672. }
  4673. e++;
  4674. }
  4675. *e = 0;
  4676. ep.set(s,defport);
  4677. if (ep.isNull()) {
  4678. // Error TBD
  4679. }
  4680. append(ep);
  4681. }
  4682. else {
  4683. bool hascolon = false;
  4684. bool isv6 = false;
  4685. do {
  4686. if (*e==':') {
  4687. if (hascolon)
  4688. isv6 = true;
  4689. else
  4690. hascolon = true;
  4691. }
  4692. e++;
  4693. if (!*e) {
  4694. eol = true;
  4695. break;
  4696. }
  4697. } while (!isspace(*e)&&(*e!=','));
  4698. *e = 0;
  4699. if (isv6) {
  4700. ep.set(s,defport);
  4701. if (ep.isNull()) {
  4702. // Error TBD
  4703. }
  4704. append(ep);
  4705. }
  4706. else {
  4707. if (!appendv4range(this,s,ep,defport)) {
  4708. // Error TBD
  4709. }
  4710. }
  4711. }
  4712. if (eol)
  4713. break;
  4714. s = e+1;
  4715. }
  4716. free(str);
  4717. }
  4718. bool IpSubNet::set(const char *_net,const char *_mask)
  4719. {
  4720. if (!_net||!decodeNumericIP(_net,net)) { // _net NULL means match everything
  4721. memset(net,0,sizeof(net));
  4722. memset(mask,0,sizeof(mask));
  4723. return (_net==NULL);
  4724. }
  4725. if (!_mask||!decodeNumericIP(_mask,mask)) { // _mask NULL means match exact
  4726. memset(mask,0xff,sizeof(mask));
  4727. return (_mask==NULL);
  4728. }
  4729. if (isIp4(net)!=isIp4(mask))
  4730. return false;
  4731. for (unsigned j=0;j<4;j++)
  4732. if (net[j]&~mask[j])
  4733. return false;
  4734. return true;
  4735. }
  4736. bool IpSubNet::test(const IpAddress &ip)
  4737. {
  4738. unsigned i;
  4739. if (ip.getNetAddress(sizeof(i),&i)==sizeof(i)) {
  4740. if (!isIp4(net))
  4741. return false;
  4742. return (i&mask[3])==(net[3]&mask[3]);
  4743. }
  4744. unsigned na[4];
  4745. if (ip.getNetAddress(sizeof(na),&na)==sizeof(na)) {
  4746. for (unsigned j=0;j<4;j++)
  4747. if ((na[j]&mask[j])!=(net[j]&mask[j]))
  4748. return false;
  4749. return true;
  4750. }
  4751. return false;
  4752. }
  4753. StringBuffer IpSubNet::getNetText(StringBuffer &text)
  4754. {
  4755. char tmp[INET6_ADDRSTRLEN];
  4756. return text.append(_inet_ntop(isIp4(net)?AF_INET:AF_INET6, &net, tmp, sizeof(tmp)));
  4757. }
  4758. StringBuffer IpSubNet::getMaskText(StringBuffer &text)
  4759. {
  4760. char tmp[INET6_ADDRSTRLEN];
  4761. return text.append(_inet_ntop(isIp4(net)?AF_INET:AF_INET6, &mask, tmp, sizeof(tmp))); // isIp4(net) is correct here
  4762. }
  4763. bool IpSubNet::isNull()
  4764. {
  4765. for (unsigned i=0;i<4;i++)
  4766. if (net[i]||mask[i])
  4767. return false;
  4768. return true;
  4769. }
  4770. IpSubNet &queryPreferredSubnet()
  4771. {
  4772. return PreferredSubnet;
  4773. }
  4774. bool setPreferredSubnet(const char *ip,const char *mask)
  4775. {
  4776. // also resets cached host IP
  4777. if (PreferredSubnet.set(ip,mask))
  4778. {
  4779. if (!cachehostip.isNull())
  4780. {
  4781. cachehostip.ipset(NULL);
  4782. queryHostIP();
  4783. }
  4784. return true;
  4785. }
  4786. else
  4787. return false;
  4788. }
  4789. StringBuffer lookupHostName(const IpAddress &ip,StringBuffer &ret)
  4790. {
  4791. // not a common routine (no Jlib function!) only support IPv4 initially
  4792. unsigned ipa;
  4793. if (ip.getNetAddress(sizeof(ipa),&ipa)==sizeof(ipa)) {
  4794. struct hostent *phostent = gethostbyaddr( (char *) &ipa, sizeof(ipa), PF_INET);
  4795. if (phostent)
  4796. ret.append(phostent->h_name);
  4797. else
  4798. ip.getIpText(ret);
  4799. }
  4800. else
  4801. ip.getIpText(ret);
  4802. return ret;
  4803. }
  4804. struct SocketEndpointHTElem
  4805. {
  4806. IInterface *ii;
  4807. SocketEndpoint ep;
  4808. SocketEndpointHTElem(const SocketEndpoint _ep,IInterface *_ii) { ep.set(_ep); ii = _ii; }
  4809. ~SocketEndpointHTElem() { ::Release(ii); }
  4810. };
  4811. class jlib_decl CSocketEndpointHashTable : public SuperHashTableOf<SocketEndpointHTElem, SocketEndpoint>, implements ISocketEndpointHashTable
  4812. {
  4813. virtual void onAdd(void *) {}
  4814. virtual void onRemove(void *e) { delete (SocketEndpointHTElem *)e; }
  4815. unsigned getHashFromElement(const void *e) const
  4816. {
  4817. return ((const SocketEndpointHTElem *)e)->ep.hash(0);
  4818. }
  4819. unsigned getHashFromFindParam(const void *fp) const
  4820. {
  4821. return ((const SocketEndpoint *)fp)->hash(0);
  4822. }
  4823. const void * getFindParam(const void *p) const
  4824. {
  4825. return &((const SocketEndpointHTElem *)p)->ep;
  4826. }
  4827. bool matchesFindParam(const void * et, const void *fp, unsigned) const
  4828. {
  4829. return ((const SocketEndpointHTElem *)et)->ep.equals(*(SocketEndpoint *)fp);
  4830. }
  4831. IMPLEMENT_SUPERHASHTABLEOF_REF_FIND(SocketEndpointHTElem,SocketEndpoint);
  4832. public:
  4833. IMPLEMENT_IINTERFACE;
  4834. CSocketEndpointHashTable() {}
  4835. ~CSocketEndpointHashTable() { kill(); }
  4836. void add(const SocketEndpoint &ep, IInterface *i)
  4837. {
  4838. SocketEndpointHTElem *e = SuperHashTableOf<SocketEndpointHTElem,SocketEndpoint>::find(&ep);
  4839. if (e) {
  4840. ::Release(e->ii);
  4841. e->ii = i;
  4842. }
  4843. else {
  4844. e = new SocketEndpointHTElem(ep,i);
  4845. SuperHashTableOf<SocketEndpointHTElem,SocketEndpoint>::add(*e);
  4846. }
  4847. }
  4848. void remove(const SocketEndpoint &ep)
  4849. {
  4850. SuperHashTableOf<SocketEndpointHTElem,SocketEndpoint>::remove(&ep);
  4851. }
  4852. IInterface *find(const SocketEndpoint &ep)
  4853. {
  4854. SocketEndpointHTElem *e = SuperHashTableOf<SocketEndpointHTElem,SocketEndpoint>::find(&ep);
  4855. if (e)
  4856. return e->ii;
  4857. return NULL;
  4858. }
  4859. };
  4860. ISocketEndpointHashTable *createSocketEndpointHashTable()
  4861. {
  4862. CSocketEndpointHashTable *ht = new CSocketEndpointHashTable;
  4863. return ht;
  4864. }
  4865. class CSocketConnectWait: public CInterface, implements ISocketConnectWait
  4866. {
  4867. Owned<CSocket> sock;
  4868. bool done;
  4869. CTimeMon connecttm;
  4870. unsigned startt;
  4871. bool oneshot;
  4872. bool isopen;
  4873. int initerr;
  4874. void successfulConnect()
  4875. {
  4876. STATS.connects++;
  4877. STATS.connecttime+=usTick()-startt;
  4878. #ifdef _TRACE
  4879. char peer[256];
  4880. peer[0] = 'C';
  4881. peer[1] = '!';
  4882. strcpy(peer+2,sock->hostname?sock->hostname:"(NULL)");
  4883. free(sock->tracename);
  4884. sock->tracename = strdup(peer);
  4885. #endif
  4886. }
  4887. void failedConnect()
  4888. {
  4889. STATS.failedconnects++;
  4890. STATS.failedconnecttime+=usTick()-startt;
  4891. const char* tracename = sock->tracename;
  4892. THROWJSOCKEXCEPTION(JSOCKERR_connection_failed);
  4893. }
  4894. public:
  4895. IMPLEMENT_IINTERFACE;
  4896. CSocketConnectWait(SocketEndpoint &ep,unsigned connecttimeoutms)
  4897. : connecttm(connecttimeoutms)
  4898. {
  4899. oneshot = (connecttimeoutms==0); // i.e. as long as one connect takes
  4900. done = false;
  4901. startt = usTick();
  4902. sock.setown(new CSocket(ep,sm_tcp,NULL));
  4903. isopen = true;
  4904. initerr = sock->pre_connect(false);
  4905. }
  4906. ISocket *wait(unsigned timems)
  4907. {
  4908. // this is a bit spagetti due to dual timeouts etc
  4909. CTimeMon waittm(timems);
  4910. unsigned refuseddelay = 1;
  4911. bool waittimedout = false;
  4912. bool connectimedout = false;
  4913. do {
  4914. bool connectdone = false;
  4915. unsigned remaining;
  4916. connectimedout = connecttm.timedout(&remaining);
  4917. unsigned waitremaining;
  4918. waittimedout = waittm.timedout(&waitremaining);
  4919. if (oneshot||(waitremaining<remaining))
  4920. remaining = waitremaining;
  4921. int err = 0;
  4922. if (!isopen||initerr) {
  4923. isopen = true;
  4924. err = initerr?initerr:sock->pre_connect(false);
  4925. initerr = 0;
  4926. if ((err == EINPROGRESS)||(err == EWOULDBLOCK))
  4927. err = 0; // continue
  4928. else {
  4929. if (err==0)
  4930. connectdone = true; // done immediately
  4931. else if(!oneshot) // probably ECONNREFUSED but treat all errors same
  4932. refused_sleep((waitremaining==remaining)?waittm:connecttm,refuseddelay); // this stops becoming cpu bound
  4933. }
  4934. }
  4935. if (!connectdone&&(err==0)) {
  4936. SOCKET s = sock->sock;
  4937. T_FD_SET fds;
  4938. struct timeval tv;
  4939. XFD_ZERO(&fds);
  4940. FD_SET((unsigned)s, &fds);
  4941. T_FD_SET except;
  4942. XFD_ZERO(&except);
  4943. FD_SET((unsigned)s, &except);
  4944. tv.tv_sec = remaining / 1000;
  4945. tv.tv_usec = (remaining % 1000)*1000;
  4946. CHECKSOCKRANGE(s);
  4947. int rc = ::select( s + 1, NULL, (fd_set *)&fds, (fd_set *)&except, &tv );
  4948. if (rc==0)
  4949. break; // timeout
  4950. done = true;
  4951. err = 0;
  4952. if (rc>0) {
  4953. // select succeeded - return error from socket (0 if connected)
  4954. socklen_t errlen = sizeof(err);
  4955. rc = getsockopt(s, SOL_SOCKET, SO_ERROR, (char *)&err, &errlen); // check for error
  4956. if ((rc!=0)&&!err)
  4957. err = ERRNO(); // some implementations of getsockopt duff
  4958. if (err&&!oneshot) // probably ECONNREFUSED but treat all errors same
  4959. refused_sleep((waitremaining==remaining)?waittm:connecttm,refuseddelay); // this stops becoming cpu bound
  4960. }
  4961. else { // select failed
  4962. err = ERRNO();
  4963. LOGERR(err,2,"CSocketConnectWait ::select");
  4964. }
  4965. }
  4966. if (err==0) {
  4967. err = sock->post_connect();
  4968. if (err==0) {
  4969. successfulConnect();
  4970. return sock.getClear();
  4971. }
  4972. }
  4973. sock->errclose();
  4974. isopen = false;
  4975. } while (!waittimedout&&!oneshot);
  4976. if (connectimedout) {
  4977. STATS.failedconnects++;
  4978. STATS.failedconnecttime+=usTick()-startt;
  4979. const char* tracename = sock->tracename;
  4980. THROWJSOCKEXCEPTION(JSOCKERR_connection_failed);
  4981. }
  4982. return NULL;
  4983. }
  4984. };
  4985. ISocketConnectWait *nonBlockingConnect(SocketEndpoint &ep,unsigned connecttimeoutms)
  4986. {
  4987. return new CSocketConnectWait(ep,connecttimeoutms);
  4988. }