jsocket.cpp 156 KB

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