jsocket.cpp 155 KB

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