GCDAsyncSocket.m 229 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526
  1. //
  2. // GCDAsyncSocket.m
  3. //
  4. // This class is in the public domain.
  5. // Originally created by Robbie Hanson in Q4 2010.
  6. // Updated and maintained by Deusty LLC and the Apple development community.
  7. //
  8. // https://github.com/robbiehanson/CocoaAsyncSocket
  9. //
  10. #import "GCDAsyncSocket.h"
  11. #if TARGET_OS_IPHONE
  12. #import <CFNetwork/CFNetwork.h>
  13. #endif
  14. #import <TargetConditionals.h>
  15. #import <arpa/inet.h>
  16. #import <fcntl.h>
  17. #import <ifaddrs.h>
  18. #import <netdb.h>
  19. #import <netinet/in.h>
  20. #import <net/if.h>
  21. #import <sys/socket.h>
  22. #import <sys/types.h>
  23. #import <sys/ioctl.h>
  24. #import <sys/poll.h>
  25. #import <sys/uio.h>
  26. #import <sys/un.h>
  27. #import <unistd.h>
  28. #if ! __has_feature(objc_arc)
  29. #warning This file must be compiled with ARC. Use -fobjc-arc flag (or convert project to ARC).
  30. // For more information see: https://github.com/robbiehanson/CocoaAsyncSocket/wiki/ARC
  31. #endif
  32. #ifndef GCDAsyncSocketLoggingEnabled
  33. #define GCDAsyncSocketLoggingEnabled 0
  34. #endif
  35. #if GCDAsyncSocketLoggingEnabled
  36. // Logging Enabled - See log level below
  37. // Logging uses the CocoaLumberjack framework (which is also GCD based).
  38. // https://github.com/robbiehanson/CocoaLumberjack
  39. //
  40. // It allows us to do a lot of logging without significantly slowing down the code.
  41. #import "DDLog.h"
  42. #define LogAsync YES
  43. #define LogContext GCDAsyncSocketLoggingContext
  44. #define LogObjc(flg, frmt, ...) LOG_OBJC_MAYBE(LogAsync, logLevel, flg, LogContext, frmt, ##__VA_ARGS__)
  45. #define LogC(flg, frmt, ...) LOG_C_MAYBE(LogAsync, logLevel, flg, LogContext, frmt, ##__VA_ARGS__)
  46. #define LogError(frmt, ...) LogObjc(LOG_FLAG_ERROR, (@"%@: " frmt), THIS_FILE, ##__VA_ARGS__)
  47. #define LogWarn(frmt, ...) LogObjc(LOG_FLAG_WARN, (@"%@: " frmt), THIS_FILE, ##__VA_ARGS__)
  48. #define LogInfo(frmt, ...) LogObjc(LOG_FLAG_INFO, (@"%@: " frmt), THIS_FILE, ##__VA_ARGS__)
  49. #define LogVerbose(frmt, ...) LogObjc(LOG_FLAG_VERBOSE, (@"%@: " frmt), THIS_FILE, ##__VA_ARGS__)
  50. #define LogCError(frmt, ...) LogC(LOG_FLAG_ERROR, (@"%@: " frmt), THIS_FILE, ##__VA_ARGS__)
  51. #define LogCWarn(frmt, ...) LogC(LOG_FLAG_WARN, (@"%@: " frmt), THIS_FILE, ##__VA_ARGS__)
  52. #define LogCInfo(frmt, ...) LogC(LOG_FLAG_INFO, (@"%@: " frmt), THIS_FILE, ##__VA_ARGS__)
  53. #define LogCVerbose(frmt, ...) LogC(LOG_FLAG_VERBOSE, (@"%@: " frmt), THIS_FILE, ##__VA_ARGS__)
  54. #define LogTrace() LogObjc(LOG_FLAG_VERBOSE, @"%@: %@", THIS_FILE, THIS_METHOD)
  55. #define LogCTrace() LogC(LOG_FLAG_VERBOSE, @"%@: %s", THIS_FILE, __FUNCTION__)
  56. #ifndef GCDAsyncSocketLogLevel
  57. #define GCDAsyncSocketLogLevel LOG_LEVEL_VERBOSE
  58. #endif
  59. // Log levels : off, error, warn, info, verbose
  60. static const int logLevel = GCDAsyncSocketLogLevel;
  61. #else
  62. // Logging Disabled
  63. #define LogError(frmt, ...) {}
  64. #define LogWarn(frmt, ...) {}
  65. #define LogInfo(frmt, ...) {}
  66. #define LogVerbose(frmt, ...) {}
  67. #define LogCError(frmt, ...) {}
  68. #define LogCWarn(frmt, ...) {}
  69. #define LogCInfo(frmt, ...) {}
  70. #define LogCVerbose(frmt, ...) {}
  71. #define LogTrace() {}
  72. #define LogCTrace(frmt, ...) {}
  73. #endif
  74. /**
  75. * Seeing a return statements within an inner block
  76. * can sometimes be mistaken for a return point of the enclosing method.
  77. * This makes inline blocks a bit easier to read.
  78. **/
  79. #define return_from_block return
  80. /**
  81. * A socket file descriptor is really just an integer.
  82. * It represents the index of the socket within the kernel.
  83. * This makes invalid file descriptor comparisons easier to read.
  84. **/
  85. #define SOCKET_NULL -1
  86. NSString *const GCDAsyncSocketException = @"GCDAsyncSocketException";
  87. NSString *const GCDAsyncSocketErrorDomain = @"GCDAsyncSocketErrorDomain";
  88. NSString *const GCDAsyncSocketQueueName = @"GCDAsyncSocket";
  89. NSString *const GCDAsyncSocketThreadName = @"GCDAsyncSocket-CFStream";
  90. NSString *const GCDAsyncSocketManuallyEvaluateTrust = @"GCDAsyncSocketManuallyEvaluateTrust";
  91. #if TARGET_OS_IPHONE
  92. NSString *const GCDAsyncSocketUseCFStreamForTLS = @"GCDAsyncSocketUseCFStreamForTLS";
  93. #endif
  94. NSString *const GCDAsyncSocketSSLPeerID = @"GCDAsyncSocketSSLPeerID";
  95. NSString *const GCDAsyncSocketSSLProtocolVersionMin = @"GCDAsyncSocketSSLProtocolVersionMin";
  96. NSString *const GCDAsyncSocketSSLProtocolVersionMax = @"GCDAsyncSocketSSLProtocolVersionMax";
  97. NSString *const GCDAsyncSocketSSLSessionOptionFalseStart = @"GCDAsyncSocketSSLSessionOptionFalseStart";
  98. NSString *const GCDAsyncSocketSSLSessionOptionSendOneByteRecord = @"GCDAsyncSocketSSLSessionOptionSendOneByteRecord";
  99. NSString *const GCDAsyncSocketSSLCipherSuites = @"GCDAsyncSocketSSLCipherSuites";
  100. NSString *const GCDAsyncSocketSSLALPN = @"GCDAsyncSocketSSLALPN";
  101. #if !TARGET_OS_IPHONE
  102. NSString *const GCDAsyncSocketSSLDiffieHellmanParameters = @"GCDAsyncSocketSSLDiffieHellmanParameters";
  103. #endif
  104. enum GCDAsyncSocketFlags
  105. {
  106. kSocketStarted = 1 << 0, // If set, socket has been started (accepting/connecting)
  107. kConnected = 1 << 1, // If set, the socket is connected
  108. kForbidReadsWrites = 1 << 2, // If set, no new reads or writes are allowed
  109. kReadsPaused = 1 << 3, // If set, reads are paused due to possible timeout
  110. kWritesPaused = 1 << 4, // If set, writes are paused due to possible timeout
  111. kDisconnectAfterReads = 1 << 5, // If set, disconnect after no more reads are queued
  112. kDisconnectAfterWrites = 1 << 6, // If set, disconnect after no more writes are queued
  113. kSocketCanAcceptBytes = 1 << 7, // If set, we know socket can accept bytes. If unset, it's unknown.
  114. kReadSourceSuspended = 1 << 8, // If set, the read source is suspended
  115. kWriteSourceSuspended = 1 << 9, // If set, the write source is suspended
  116. kQueuedTLS = 1 << 10, // If set, we've queued an upgrade to TLS
  117. kStartingReadTLS = 1 << 11, // If set, we're waiting for TLS negotiation to complete
  118. kStartingWriteTLS = 1 << 12, // If set, we're waiting for TLS negotiation to complete
  119. kSocketSecure = 1 << 13, // If set, socket is using secure communication via SSL/TLS
  120. kSocketHasReadEOF = 1 << 14, // If set, we have read EOF from socket
  121. kReadStreamClosed = 1 << 15, // If set, we've read EOF plus prebuffer has been drained
  122. kDealloc = 1 << 16, // If set, the socket is being deallocated
  123. #if TARGET_OS_IPHONE
  124. kAddedStreamsToRunLoop = 1 << 17, // If set, CFStreams have been added to listener thread
  125. kUsingCFStreamForTLS = 1 << 18, // If set, we're forced to use CFStream instead of SecureTransport
  126. kSecureSocketHasBytesAvailable = 1 << 19, // If set, CFReadStream has notified us of bytes available
  127. #endif
  128. };
  129. enum GCDAsyncSocketConfig
  130. {
  131. kIPv4Disabled = 1 << 0, // If set, IPv4 is disabled
  132. kIPv6Disabled = 1 << 1, // If set, IPv6 is disabled
  133. kPreferIPv6 = 1 << 2, // If set, IPv6 is preferred over IPv4
  134. kAllowHalfDuplexConnection = 1 << 3, // If set, the socket will stay open even if the read stream closes
  135. };
  136. #if TARGET_OS_IPHONE
  137. static NSThread *cfstreamThread; // Used for CFStreams
  138. static uint64_t cfstreamThreadRetainCount; // setup & teardown
  139. static dispatch_queue_t cfstreamThreadSetupQueue; // setup & teardown
  140. #endif
  141. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  142. #pragma mark -
  143. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  144. /**
  145. * A PreBuffer is used when there is more data available on the socket
  146. * than is being requested by current read request.
  147. * In this case we slurp up all data from the socket (to minimize sys calls),
  148. * and store additional yet unread data in a "prebuffer".
  149. *
  150. * The prebuffer is entirely drained before we read from the socket again.
  151. * In other words, a large chunk of data is written is written to the prebuffer.
  152. * The prebuffer is then drained via a series of one or more reads (for subsequent read request(s)).
  153. *
  154. * A ring buffer was once used for this purpose.
  155. * But a ring buffer takes up twice as much memory as needed (double the size for mirroring).
  156. * In fact, it generally takes up more than twice the needed size as everything has to be rounded up to vm_page_size.
  157. * And since the prebuffer is always completely drained after being written to, a full ring buffer isn't needed.
  158. *
  159. * The current design is very simple and straight-forward, while also keeping memory requirements lower.
  160. **/
  161. @interface GCDAsyncSocketPreBuffer : NSObject
  162. {
  163. uint8_t *preBuffer;
  164. size_t preBufferSize;
  165. uint8_t *readPointer;
  166. uint8_t *writePointer;
  167. }
  168. - (instancetype)initWithCapacity:(size_t)numBytes NS_DESIGNATED_INITIALIZER;
  169. - (void)ensureCapacityForWrite:(size_t)numBytes;
  170. - (size_t)availableBytes;
  171. - (uint8_t *)readBuffer;
  172. - (void)getReadBuffer:(uint8_t **)bufferPtr availableBytes:(size_t *)availableBytesPtr;
  173. - (size_t)availableSpace;
  174. - (uint8_t *)writeBuffer;
  175. - (void)getWriteBuffer:(uint8_t **)bufferPtr availableSpace:(size_t *)availableSpacePtr;
  176. - (void)didRead:(size_t)bytesRead;
  177. - (void)didWrite:(size_t)bytesWritten;
  178. - (void)reset;
  179. @end
  180. @implementation GCDAsyncSocketPreBuffer
  181. // Cover the superclass' designated initializer
  182. - (instancetype)init NS_UNAVAILABLE
  183. {
  184. NSAssert(0, @"Use the designated initializer");
  185. return nil;
  186. }
  187. - (instancetype)initWithCapacity:(size_t)numBytes
  188. {
  189. if ((self = [super init]))
  190. {
  191. preBufferSize = numBytes;
  192. preBuffer = malloc(preBufferSize);
  193. readPointer = preBuffer;
  194. writePointer = preBuffer;
  195. }
  196. return self;
  197. }
  198. - (void)dealloc
  199. {
  200. if (preBuffer)
  201. free(preBuffer);
  202. }
  203. - (void)ensureCapacityForWrite:(size_t)numBytes
  204. {
  205. size_t availableSpace = [self availableSpace];
  206. if (numBytes > availableSpace)
  207. {
  208. size_t additionalBytes = numBytes - availableSpace;
  209. size_t newPreBufferSize = preBufferSize + additionalBytes;
  210. uint8_t *newPreBuffer = realloc(preBuffer, newPreBufferSize);
  211. size_t readPointerOffset = readPointer - preBuffer;
  212. size_t writePointerOffset = writePointer - preBuffer;
  213. preBuffer = newPreBuffer;
  214. preBufferSize = newPreBufferSize;
  215. readPointer = preBuffer + readPointerOffset;
  216. writePointer = preBuffer + writePointerOffset;
  217. }
  218. }
  219. - (size_t)availableBytes
  220. {
  221. return writePointer - readPointer;
  222. }
  223. - (uint8_t *)readBuffer
  224. {
  225. return readPointer;
  226. }
  227. - (void)getReadBuffer:(uint8_t **)bufferPtr availableBytes:(size_t *)availableBytesPtr
  228. {
  229. if (bufferPtr) *bufferPtr = readPointer;
  230. if (availableBytesPtr) *availableBytesPtr = [self availableBytes];
  231. }
  232. - (void)didRead:(size_t)bytesRead
  233. {
  234. readPointer += bytesRead;
  235. if (readPointer == writePointer)
  236. {
  237. // The prebuffer has been drained. Reset pointers.
  238. readPointer = preBuffer;
  239. writePointer = preBuffer;
  240. }
  241. }
  242. - (size_t)availableSpace
  243. {
  244. return preBufferSize - (writePointer - preBuffer);
  245. }
  246. - (uint8_t *)writeBuffer
  247. {
  248. return writePointer;
  249. }
  250. - (void)getWriteBuffer:(uint8_t **)bufferPtr availableSpace:(size_t *)availableSpacePtr
  251. {
  252. if (bufferPtr) *bufferPtr = writePointer;
  253. if (availableSpacePtr) *availableSpacePtr = [self availableSpace];
  254. }
  255. - (void)didWrite:(size_t)bytesWritten
  256. {
  257. writePointer += bytesWritten;
  258. }
  259. - (void)reset
  260. {
  261. readPointer = preBuffer;
  262. writePointer = preBuffer;
  263. }
  264. @end
  265. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  266. #pragma mark -
  267. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  268. /**
  269. * The GCDAsyncReadPacket encompasses the instructions for any given read.
  270. * The content of a read packet allows the code to determine if we're:
  271. * - reading to a certain length
  272. * - reading to a certain separator
  273. * - or simply reading the first chunk of available data
  274. **/
  275. @interface GCDAsyncReadPacket : NSObject
  276. {
  277. @public
  278. NSMutableData *buffer;
  279. NSUInteger startOffset;
  280. NSUInteger bytesDone;
  281. NSUInteger maxLength;
  282. NSTimeInterval timeout;
  283. NSUInteger readLength;
  284. NSData *term;
  285. BOOL bufferOwner;
  286. NSUInteger originalBufferLength;
  287. long tag;
  288. }
  289. - (instancetype)initWithData:(NSMutableData *)d
  290. startOffset:(NSUInteger)s
  291. maxLength:(NSUInteger)m
  292. timeout:(NSTimeInterval)t
  293. readLength:(NSUInteger)l
  294. terminator:(NSData *)e
  295. tag:(long)i NS_DESIGNATED_INITIALIZER;
  296. - (void)ensureCapacityForAdditionalDataOfLength:(NSUInteger)bytesToRead;
  297. - (NSUInteger)optimalReadLengthWithDefault:(NSUInteger)defaultValue shouldPreBuffer:(BOOL *)shouldPreBufferPtr;
  298. - (NSUInteger)readLengthForNonTermWithHint:(NSUInteger)bytesAvailable;
  299. - (NSUInteger)readLengthForTermWithHint:(NSUInteger)bytesAvailable shouldPreBuffer:(BOOL *)shouldPreBufferPtr;
  300. - (NSUInteger)readLengthForTermWithPreBuffer:(GCDAsyncSocketPreBuffer *)preBuffer found:(BOOL *)foundPtr;
  301. - (NSInteger)searchForTermAfterPreBuffering:(ssize_t)numBytes;
  302. @end
  303. @implementation GCDAsyncReadPacket
  304. // Cover the superclass' designated initializer
  305. - (instancetype)init NS_UNAVAILABLE
  306. {
  307. NSAssert(0, @"Use the designated initializer");
  308. return nil;
  309. }
  310. - (instancetype)initWithData:(NSMutableData *)d
  311. startOffset:(NSUInteger)s
  312. maxLength:(NSUInteger)m
  313. timeout:(NSTimeInterval)t
  314. readLength:(NSUInteger)l
  315. terminator:(NSData *)e
  316. tag:(long)i
  317. {
  318. if((self = [super init]))
  319. {
  320. bytesDone = 0;
  321. maxLength = m;
  322. timeout = t;
  323. readLength = l;
  324. term = [e copy];
  325. tag = i;
  326. if (d)
  327. {
  328. buffer = d;
  329. startOffset = s;
  330. bufferOwner = NO;
  331. originalBufferLength = [d length];
  332. }
  333. else
  334. {
  335. if (readLength > 0)
  336. buffer = [[NSMutableData alloc] initWithLength:readLength];
  337. else
  338. buffer = [[NSMutableData alloc] initWithLength:0];
  339. startOffset = 0;
  340. bufferOwner = YES;
  341. originalBufferLength = 0;
  342. }
  343. }
  344. return self;
  345. }
  346. /**
  347. * Increases the length of the buffer (if needed) to ensure a read of the given size will fit.
  348. **/
  349. - (void)ensureCapacityForAdditionalDataOfLength:(NSUInteger)bytesToRead
  350. {
  351. NSUInteger buffSize = [buffer length];
  352. NSUInteger buffUsed = startOffset + bytesDone;
  353. NSUInteger buffSpace = buffSize - buffUsed;
  354. if (bytesToRead > buffSpace)
  355. {
  356. NSUInteger buffInc = bytesToRead - buffSpace;
  357. [buffer increaseLengthBy:buffInc];
  358. }
  359. }
  360. /**
  361. * This method is used when we do NOT know how much data is available to be read from the socket.
  362. * This method returns the default value unless it exceeds the specified readLength or maxLength.
  363. *
  364. * Furthermore, the shouldPreBuffer decision is based upon the packet type,
  365. * and whether the returned value would fit in the current buffer without requiring a resize of the buffer.
  366. **/
  367. - (NSUInteger)optimalReadLengthWithDefault:(NSUInteger)defaultValue shouldPreBuffer:(BOOL *)shouldPreBufferPtr
  368. {
  369. NSUInteger result;
  370. if (readLength > 0)
  371. {
  372. // Read a specific length of data
  373. result = readLength - bytesDone;
  374. // There is no need to prebuffer since we know exactly how much data we need to read.
  375. // Even if the buffer isn't currently big enough to fit this amount of data,
  376. // it would have to be resized eventually anyway.
  377. if (shouldPreBufferPtr)
  378. *shouldPreBufferPtr = NO;
  379. }
  380. else
  381. {
  382. // Either reading until we find a specified terminator,
  383. // or we're simply reading all available data.
  384. //
  385. // In other words, one of:
  386. //
  387. // - readDataToData packet
  388. // - readDataWithTimeout packet
  389. if (maxLength > 0)
  390. result = MIN(defaultValue, (maxLength - bytesDone));
  391. else
  392. result = defaultValue;
  393. // Since we don't know the size of the read in advance,
  394. // the shouldPreBuffer decision is based upon whether the returned value would fit
  395. // in the current buffer without requiring a resize of the buffer.
  396. //
  397. // This is because, in all likelyhood, the amount read from the socket will be less than the default value.
  398. // Thus we should avoid over-allocating the read buffer when we can simply use the pre-buffer instead.
  399. if (shouldPreBufferPtr)
  400. {
  401. NSUInteger buffSize = [buffer length];
  402. NSUInteger buffUsed = startOffset + bytesDone;
  403. NSUInteger buffSpace = buffSize - buffUsed;
  404. if (buffSpace >= result)
  405. *shouldPreBufferPtr = NO;
  406. else
  407. *shouldPreBufferPtr = YES;
  408. }
  409. }
  410. return result;
  411. }
  412. /**
  413. * For read packets without a set terminator, returns the amount of data
  414. * that can be read without exceeding the readLength or maxLength.
  415. *
  416. * The given parameter indicates the number of bytes estimated to be available on the socket,
  417. * which is taken into consideration during the calculation.
  418. *
  419. * The given hint MUST be greater than zero.
  420. **/
  421. - (NSUInteger)readLengthForNonTermWithHint:(NSUInteger)bytesAvailable
  422. {
  423. NSAssert(term == nil, @"This method does not apply to term reads");
  424. NSAssert(bytesAvailable > 0, @"Invalid parameter: bytesAvailable");
  425. if (readLength > 0)
  426. {
  427. // Read a specific length of data
  428. return MIN(bytesAvailable, (readLength - bytesDone));
  429. // No need to avoid resizing the buffer.
  430. // If the user provided their own buffer,
  431. // and told us to read a certain length of data that exceeds the size of the buffer,
  432. // then it is clear that our code will resize the buffer during the read operation.
  433. //
  434. // This method does not actually do any resizing.
  435. // The resizing will happen elsewhere if needed.
  436. }
  437. else
  438. {
  439. // Read all available data
  440. NSUInteger result = bytesAvailable;
  441. if (maxLength > 0)
  442. {
  443. result = MIN(result, (maxLength - bytesDone));
  444. }
  445. // No need to avoid resizing the buffer.
  446. // If the user provided their own buffer,
  447. // and told us to read all available data without giving us a maxLength,
  448. // then it is clear that our code might resize the buffer during the read operation.
  449. //
  450. // This method does not actually do any resizing.
  451. // The resizing will happen elsewhere if needed.
  452. return result;
  453. }
  454. }
  455. /**
  456. * For read packets with a set terminator, returns the amount of data
  457. * that can be read without exceeding the maxLength.
  458. *
  459. * The given parameter indicates the number of bytes estimated to be available on the socket,
  460. * which is taken into consideration during the calculation.
  461. *
  462. * To optimize memory allocations, mem copies, and mem moves
  463. * the shouldPreBuffer boolean value will indicate if the data should be read into a prebuffer first,
  464. * or if the data can be read directly into the read packet's buffer.
  465. **/
  466. - (NSUInteger)readLengthForTermWithHint:(NSUInteger)bytesAvailable shouldPreBuffer:(BOOL *)shouldPreBufferPtr
  467. {
  468. NSAssert(term != nil, @"This method does not apply to non-term reads");
  469. NSAssert(bytesAvailable > 0, @"Invalid parameter: bytesAvailable");
  470. NSUInteger result = bytesAvailable;
  471. if (maxLength > 0)
  472. {
  473. result = MIN(result, (maxLength - bytesDone));
  474. }
  475. // Should the data be read into the read packet's buffer, or into a pre-buffer first?
  476. //
  477. // One would imagine the preferred option is the faster one.
  478. // So which one is faster?
  479. //
  480. // Reading directly into the packet's buffer requires:
  481. // 1. Possibly resizing packet buffer (malloc/realloc)
  482. // 2. Filling buffer (read)
  483. // 3. Searching for term (memcmp)
  484. // 4. Possibly copying overflow into prebuffer (malloc/realloc, memcpy)
  485. //
  486. // Reading into prebuffer first:
  487. // 1. Possibly resizing prebuffer (malloc/realloc)
  488. // 2. Filling buffer (read)
  489. // 3. Searching for term (memcmp)
  490. // 4. Copying underflow into packet buffer (malloc/realloc, memcpy)
  491. // 5. Removing underflow from prebuffer (memmove)
  492. //
  493. // Comparing the performance of the two we can see that reading
  494. // data into the prebuffer first is slower due to the extra memove.
  495. //
  496. // However:
  497. // The implementation of NSMutableData is open source via core foundation's CFMutableData.
  498. // Decreasing the length of a mutable data object doesn't cause a realloc.
  499. // In other words, the capacity of a mutable data object can grow, but doesn't shrink.
  500. //
  501. // This means the prebuffer will rarely need a realloc.
  502. // The packet buffer, on the other hand, may often need a realloc.
  503. // This is especially true if we are the buffer owner.
  504. // Furthermore, if we are constantly realloc'ing the packet buffer,
  505. // and then moving the overflow into the prebuffer,
  506. // then we're consistently over-allocating memory for each term read.
  507. // And now we get into a bit of a tradeoff between speed and memory utilization.
  508. //
  509. // The end result is that the two perform very similarly.
  510. // And we can answer the original question very simply by another means.
  511. //
  512. // If we can read all the data directly into the packet's buffer without resizing it first,
  513. // then we do so. Otherwise we use the prebuffer.
  514. if (shouldPreBufferPtr)
  515. {
  516. NSUInteger buffSize = [buffer length];
  517. NSUInteger buffUsed = startOffset + bytesDone;
  518. if ((buffSize - buffUsed) >= result)
  519. *shouldPreBufferPtr = NO;
  520. else
  521. *shouldPreBufferPtr = YES;
  522. }
  523. return result;
  524. }
  525. /**
  526. * For read packets with a set terminator,
  527. * returns the amount of data that can be read from the given preBuffer,
  528. * without going over a terminator or the maxLength.
  529. *
  530. * It is assumed the terminator has not already been read.
  531. **/
  532. - (NSUInteger)readLengthForTermWithPreBuffer:(GCDAsyncSocketPreBuffer *)preBuffer found:(BOOL *)foundPtr
  533. {
  534. NSAssert(term != nil, @"This method does not apply to non-term reads");
  535. NSAssert([preBuffer availableBytes] > 0, @"Invoked with empty pre buffer!");
  536. // We know that the terminator, as a whole, doesn't exist in our own buffer.
  537. // But it is possible that a _portion_ of it exists in our buffer.
  538. // So we're going to look for the terminator starting with a portion of our own buffer.
  539. //
  540. // Example:
  541. //
  542. // term length = 3 bytes
  543. // bytesDone = 5 bytes
  544. // preBuffer length = 5 bytes
  545. //
  546. // If we append the preBuffer to our buffer,
  547. // it would look like this:
  548. //
  549. // ---------------------
  550. // |B|B|B|B|B|P|P|P|P|P|
  551. // ---------------------
  552. //
  553. // So we start our search here:
  554. //
  555. // ---------------------
  556. // |B|B|B|B|B|P|P|P|P|P|
  557. // -------^-^-^---------
  558. //
  559. // And move forwards...
  560. //
  561. // ---------------------
  562. // |B|B|B|B|B|P|P|P|P|P|
  563. // ---------^-^-^-------
  564. //
  565. // Until we find the terminator or reach the end.
  566. //
  567. // ---------------------
  568. // |B|B|B|B|B|P|P|P|P|P|
  569. // ---------------^-^-^-
  570. BOOL found = NO;
  571. NSUInteger termLength = [term length];
  572. NSUInteger preBufferLength = [preBuffer availableBytes];
  573. if ((bytesDone + preBufferLength) < termLength)
  574. {
  575. // Not enough data for a full term sequence yet
  576. return preBufferLength;
  577. }
  578. NSUInteger maxPreBufferLength;
  579. if (maxLength > 0) {
  580. maxPreBufferLength = MIN(preBufferLength, (maxLength - bytesDone));
  581. // Note: maxLength >= termLength
  582. }
  583. else {
  584. maxPreBufferLength = preBufferLength;
  585. }
  586. uint8_t seq[termLength];
  587. const void *termBuf = [term bytes];
  588. NSUInteger bufLen = MIN(bytesDone, (termLength - 1));
  589. uint8_t *buf = (uint8_t *)[buffer mutableBytes] + startOffset + bytesDone - bufLen;
  590. NSUInteger preLen = termLength - bufLen;
  591. const uint8_t *pre = [preBuffer readBuffer];
  592. NSUInteger loopCount = bufLen + maxPreBufferLength - termLength + 1; // Plus one. See example above.
  593. NSUInteger result = maxPreBufferLength;
  594. NSUInteger i;
  595. for (i = 0; i < loopCount; i++)
  596. {
  597. if (bufLen > 0)
  598. {
  599. // Combining bytes from buffer and preBuffer
  600. memcpy(seq, buf, bufLen);
  601. memcpy(seq + bufLen, pre, preLen);
  602. if (memcmp(seq, termBuf, termLength) == 0)
  603. {
  604. result = preLen;
  605. found = YES;
  606. break;
  607. }
  608. buf++;
  609. bufLen--;
  610. preLen++;
  611. }
  612. else
  613. {
  614. // Comparing directly from preBuffer
  615. if (memcmp(pre, termBuf, termLength) == 0)
  616. {
  617. NSUInteger preOffset = pre - [preBuffer readBuffer]; // pointer arithmetic
  618. result = preOffset + termLength;
  619. found = YES;
  620. break;
  621. }
  622. pre++;
  623. }
  624. }
  625. // There is no need to avoid resizing the buffer in this particular situation.
  626. if (foundPtr) *foundPtr = found;
  627. return result;
  628. }
  629. /**
  630. * For read packets with a set terminator, scans the packet buffer for the term.
  631. * It is assumed the terminator had not been fully read prior to the new bytes.
  632. *
  633. * If the term is found, the number of excess bytes after the term are returned.
  634. * If the term is not found, this method will return -1.
  635. *
  636. * Note: A return value of zero means the term was found at the very end.
  637. *
  638. * Prerequisites:
  639. * The given number of bytes have been added to the end of our buffer.
  640. * Our bytesDone variable has NOT been changed due to the prebuffered bytes.
  641. **/
  642. - (NSInteger)searchForTermAfterPreBuffering:(ssize_t)numBytes
  643. {
  644. NSAssert(term != nil, @"This method does not apply to non-term reads");
  645. // The implementation of this method is very similar to the above method.
  646. // See the above method for a discussion of the algorithm used here.
  647. uint8_t *buff = [buffer mutableBytes];
  648. NSUInteger buffLength = bytesDone + numBytes;
  649. const void *termBuff = [term bytes];
  650. NSUInteger termLength = [term length];
  651. // Note: We are dealing with unsigned integers,
  652. // so make sure the math doesn't go below zero.
  653. NSUInteger i = ((buffLength - numBytes) >= termLength) ? (buffLength - numBytes - termLength + 1) : 0;
  654. while (i + termLength <= buffLength)
  655. {
  656. uint8_t *subBuffer = buff + startOffset + i;
  657. if (memcmp(subBuffer, termBuff, termLength) == 0)
  658. {
  659. return buffLength - (i + termLength);
  660. }
  661. i++;
  662. }
  663. return -1;
  664. }
  665. @end
  666. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  667. #pragma mark -
  668. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  669. /**
  670. * The GCDAsyncWritePacket encompasses the instructions for any given write.
  671. **/
  672. @interface GCDAsyncWritePacket : NSObject
  673. {
  674. @public
  675. NSData *buffer;
  676. NSUInteger bytesDone;
  677. long tag;
  678. NSTimeInterval timeout;
  679. }
  680. - (instancetype)initWithData:(NSData *)d timeout:(NSTimeInterval)t tag:(long)i NS_DESIGNATED_INITIALIZER;
  681. @end
  682. @implementation GCDAsyncWritePacket
  683. // Cover the superclass' designated initializer
  684. - (instancetype)init NS_UNAVAILABLE
  685. {
  686. NSAssert(0, @"Use the designated initializer");
  687. return nil;
  688. }
  689. - (instancetype)initWithData:(NSData *)d timeout:(NSTimeInterval)t tag:(long)i
  690. {
  691. if((self = [super init]))
  692. {
  693. buffer = d; // Retain not copy. For performance as documented in header file.
  694. bytesDone = 0;
  695. timeout = t;
  696. tag = i;
  697. }
  698. return self;
  699. }
  700. @end
  701. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  702. #pragma mark -
  703. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  704. /**
  705. * The GCDAsyncSpecialPacket encompasses special instructions for interruptions in the read/write queues.
  706. * This class my be altered to support more than just TLS in the future.
  707. **/
  708. @interface GCDAsyncSpecialPacket : NSObject
  709. {
  710. @public
  711. NSDictionary *tlsSettings;
  712. }
  713. - (instancetype)initWithTLSSettings:(NSDictionary <NSString*,NSObject*>*)settings NS_DESIGNATED_INITIALIZER;
  714. @end
  715. @implementation GCDAsyncSpecialPacket
  716. // Cover the superclass' designated initializer
  717. - (instancetype)init NS_UNAVAILABLE
  718. {
  719. NSAssert(0, @"Use the designated initializer");
  720. return nil;
  721. }
  722. - (instancetype)initWithTLSSettings:(NSDictionary <NSString*,NSObject*>*)settings
  723. {
  724. if((self = [super init]))
  725. {
  726. tlsSettings = [settings copy];
  727. }
  728. return self;
  729. }
  730. @end
  731. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  732. #pragma mark -
  733. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  734. @implementation GCDAsyncSocket
  735. {
  736. uint32_t flags;
  737. uint16_t config;
  738. __weak id<GCDAsyncSocketDelegate> delegate;
  739. dispatch_queue_t delegateQueue;
  740. int socket4FD;
  741. int socket6FD;
  742. int socketUN;
  743. NSURL *socketUrl;
  744. int stateIndex;
  745. NSData * connectInterface4;
  746. NSData * connectInterface6;
  747. NSData * connectInterfaceUN;
  748. dispatch_queue_t socketQueue;
  749. dispatch_source_t accept4Source;
  750. dispatch_source_t accept6Source;
  751. dispatch_source_t acceptUNSource;
  752. dispatch_source_t connectTimer;
  753. dispatch_source_t readSource;
  754. dispatch_source_t writeSource;
  755. dispatch_source_t readTimer;
  756. dispatch_source_t writeTimer;
  757. NSMutableArray *readQueue;
  758. NSMutableArray *writeQueue;
  759. GCDAsyncReadPacket *currentRead;
  760. GCDAsyncWritePacket *currentWrite;
  761. unsigned long socketFDBytesAvailable;
  762. GCDAsyncSocketPreBuffer *preBuffer;
  763. #if TARGET_OS_IPHONE
  764. CFStreamClientContext streamContext;
  765. CFReadStreamRef readStream;
  766. CFWriteStreamRef writeStream;
  767. #endif
  768. SSLContextRef sslContext;
  769. GCDAsyncSocketPreBuffer *sslPreBuffer;
  770. size_t sslWriteCachedLength;
  771. OSStatus sslErrCode;
  772. OSStatus lastSSLHandshakeError;
  773. void *IsOnSocketQueueOrTargetQueueKey;
  774. id userData;
  775. NSTimeInterval alternateAddressDelay;
  776. }
  777. - (instancetype)init
  778. {
  779. return [self initWithDelegate:nil delegateQueue:NULL socketQueue:NULL];
  780. }
  781. - (instancetype)initWithSocketQueue:(dispatch_queue_t)sq
  782. {
  783. return [self initWithDelegate:nil delegateQueue:NULL socketQueue:sq];
  784. }
  785. - (instancetype)initWithDelegate:(id<GCDAsyncSocketDelegate>)aDelegate delegateQueue:(dispatch_queue_t)dq
  786. {
  787. return [self initWithDelegate:aDelegate delegateQueue:dq socketQueue:NULL];
  788. }
  789. - (instancetype)initWithDelegate:(id<GCDAsyncSocketDelegate>)aDelegate delegateQueue:(dispatch_queue_t)dq socketQueue:(dispatch_queue_t)sq
  790. {
  791. if((self = [super init]))
  792. {
  793. delegate = aDelegate;
  794. delegateQueue = dq;
  795. #if !OS_OBJECT_USE_OBJC
  796. if (dq) dispatch_retain(dq);
  797. #endif
  798. socket4FD = SOCKET_NULL;
  799. socket6FD = SOCKET_NULL;
  800. socketUN = SOCKET_NULL;
  801. socketUrl = nil;
  802. stateIndex = 0;
  803. if (sq)
  804. {
  805. NSAssert(sq != dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0),
  806. @"The given socketQueue parameter must not be a concurrent queue.");
  807. NSAssert(sq != dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0),
  808. @"The given socketQueue parameter must not be a concurrent queue.");
  809. NSAssert(sq != dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
  810. @"The given socketQueue parameter must not be a concurrent queue.");
  811. socketQueue = sq;
  812. #if !OS_OBJECT_USE_OBJC
  813. dispatch_retain(sq);
  814. #endif
  815. }
  816. else
  817. {
  818. socketQueue = dispatch_queue_create([GCDAsyncSocketQueueName UTF8String], NULL);
  819. }
  820. // The dispatch_queue_set_specific() and dispatch_get_specific() functions take a "void *key" parameter.
  821. // From the documentation:
  822. //
  823. // > Keys are only compared as pointers and are never dereferenced.
  824. // > Thus, you can use a pointer to a static variable for a specific subsystem or
  825. // > any other value that allows you to identify the value uniquely.
  826. //
  827. // We're just going to use the memory address of an ivar.
  828. // Specifically an ivar that is explicitly named for our purpose to make the code more readable.
  829. //
  830. // However, it feels tedious (and less readable) to include the "&" all the time:
  831. // dispatch_get_specific(&IsOnSocketQueueOrTargetQueueKey)
  832. //
  833. // So we're going to make it so it doesn't matter if we use the '&' or not,
  834. // by assigning the value of the ivar to the address of the ivar.
  835. // Thus: IsOnSocketQueueOrTargetQueueKey == &IsOnSocketQueueOrTargetQueueKey;
  836. IsOnSocketQueueOrTargetQueueKey = &IsOnSocketQueueOrTargetQueueKey;
  837. void *nonNullUnusedPointer = (__bridge void *)self;
  838. dispatch_queue_set_specific(socketQueue, IsOnSocketQueueOrTargetQueueKey, nonNullUnusedPointer, NULL);
  839. readQueue = [[NSMutableArray alloc] initWithCapacity:5];
  840. currentRead = nil;
  841. writeQueue = [[NSMutableArray alloc] initWithCapacity:5];
  842. currentWrite = nil;
  843. preBuffer = [[GCDAsyncSocketPreBuffer alloc] initWithCapacity:(1024 * 4)];
  844. alternateAddressDelay = 0.3;
  845. }
  846. return self;
  847. }
  848. - (void)dealloc
  849. {
  850. LogInfo(@"%@ - %@ (start)", THIS_METHOD, self);
  851. // Set dealloc flag.
  852. // This is used by closeWithError to ensure we don't accidentally retain ourself.
  853. flags |= kDealloc;
  854. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  855. {
  856. [self closeWithError:nil];
  857. }
  858. else
  859. {
  860. dispatch_sync(socketQueue, ^{
  861. [self closeWithError:nil];
  862. });
  863. }
  864. delegate = nil;
  865. #if !OS_OBJECT_USE_OBJC
  866. if (delegateQueue) dispatch_release(delegateQueue);
  867. #endif
  868. delegateQueue = NULL;
  869. #if !OS_OBJECT_USE_OBJC
  870. if (socketQueue) dispatch_release(socketQueue);
  871. #endif
  872. socketQueue = NULL;
  873. LogInfo(@"%@ - %@ (finish)", THIS_METHOD, self);
  874. }
  875. #pragma mark -
  876. + (nullable instancetype)socketFromConnectedSocketFD:(int)socketFD socketQueue:(nullable dispatch_queue_t)sq error:(NSError**)error {
  877. return [self socketFromConnectedSocketFD:socketFD delegate:nil delegateQueue:NULL socketQueue:sq error:error];
  878. }
  879. + (nullable instancetype)socketFromConnectedSocketFD:(int)socketFD delegate:(nullable id<GCDAsyncSocketDelegate>)aDelegate delegateQueue:(nullable dispatch_queue_t)dq error:(NSError**)error {
  880. return [self socketFromConnectedSocketFD:socketFD delegate:aDelegate delegateQueue:dq socketQueue:NULL error:error];
  881. }
  882. + (nullable instancetype)socketFromConnectedSocketFD:(int)socketFD delegate:(nullable id<GCDAsyncSocketDelegate>)aDelegate delegateQueue:(nullable dispatch_queue_t)dq socketQueue:(nullable dispatch_queue_t)sq error:(NSError* __autoreleasing *)error
  883. {
  884. __block BOOL errorOccured = NO;
  885. GCDAsyncSocket *socket = [[[self class] alloc] initWithDelegate:aDelegate delegateQueue:dq socketQueue:sq];
  886. dispatch_sync(socket->socketQueue, ^{ @autoreleasepool {
  887. struct sockaddr addr;
  888. socklen_t addr_size = sizeof(struct sockaddr);
  889. int retVal = getpeername(socketFD, (struct sockaddr *)&addr, &addr_size);
  890. if (retVal)
  891. {
  892. NSString *errMsg = NSLocalizedStringWithDefaultValue(@"GCDAsyncSocketOtherError",
  893. @"GCDAsyncSocket", [NSBundle mainBundle],
  894. @"Attempt to create socket from socket FD failed. getpeername() failed", nil);
  895. NSDictionary *userInfo = @{NSLocalizedDescriptionKey : errMsg};
  896. errorOccured = YES;
  897. if (error)
  898. *error = [NSError errorWithDomain:GCDAsyncSocketErrorDomain code:GCDAsyncSocketOtherError userInfo:userInfo];
  899. return;
  900. }
  901. if (addr.sa_family == AF_INET)
  902. {
  903. socket->socket4FD = socketFD;
  904. }
  905. else if (addr.sa_family == AF_INET6)
  906. {
  907. socket->socket6FD = socketFD;
  908. }
  909. else
  910. {
  911. NSString *errMsg = NSLocalizedStringWithDefaultValue(@"GCDAsyncSocketOtherError",
  912. @"GCDAsyncSocket", [NSBundle mainBundle],
  913. @"Attempt to create socket from socket FD failed. socket FD is neither IPv4 nor IPv6", nil);
  914. NSDictionary *userInfo = @{NSLocalizedDescriptionKey : errMsg};
  915. errorOccured = YES;
  916. if (error)
  917. *error = [NSError errorWithDomain:GCDAsyncSocketErrorDomain code:GCDAsyncSocketOtherError userInfo:userInfo];
  918. return;
  919. }
  920. socket->flags = kSocketStarted;
  921. [socket didConnect:socket->stateIndex];
  922. }});
  923. return errorOccured? nil: socket;
  924. }
  925. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  926. #pragma mark Configuration
  927. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  928. - (id)delegate
  929. {
  930. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  931. {
  932. return delegate;
  933. }
  934. else
  935. {
  936. __block id result;
  937. dispatch_sync(socketQueue, ^{
  938. result = self->delegate;
  939. });
  940. return result;
  941. }
  942. }
  943. - (void)setDelegate:(id)newDelegate synchronously:(BOOL)synchronously
  944. {
  945. dispatch_block_t block = ^{
  946. self->delegate = newDelegate;
  947. };
  948. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) {
  949. block();
  950. }
  951. else {
  952. if (synchronously)
  953. dispatch_sync(socketQueue, block);
  954. else
  955. dispatch_async(socketQueue, block);
  956. }
  957. }
  958. - (void)setDelegate:(id<GCDAsyncSocketDelegate>)newDelegate
  959. {
  960. [self setDelegate:newDelegate synchronously:NO];
  961. }
  962. - (void)synchronouslySetDelegate:(id<GCDAsyncSocketDelegate>)newDelegate
  963. {
  964. [self setDelegate:newDelegate synchronously:YES];
  965. }
  966. - (dispatch_queue_t)delegateQueue
  967. {
  968. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  969. {
  970. return delegateQueue;
  971. }
  972. else
  973. {
  974. __block dispatch_queue_t result;
  975. dispatch_sync(socketQueue, ^{
  976. result = self->delegateQueue;
  977. });
  978. return result;
  979. }
  980. }
  981. - (void)setDelegateQueue:(dispatch_queue_t)newDelegateQueue synchronously:(BOOL)synchronously
  982. {
  983. dispatch_block_t block = ^{
  984. #if !OS_OBJECT_USE_OBJC
  985. if (self->delegateQueue) dispatch_release(self->delegateQueue);
  986. if (newDelegateQueue) dispatch_retain(newDelegateQueue);
  987. #endif
  988. self->delegateQueue = newDelegateQueue;
  989. };
  990. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) {
  991. block();
  992. }
  993. else {
  994. if (synchronously)
  995. dispatch_sync(socketQueue, block);
  996. else
  997. dispatch_async(socketQueue, block);
  998. }
  999. }
  1000. - (void)setDelegateQueue:(dispatch_queue_t)newDelegateQueue
  1001. {
  1002. [self setDelegateQueue:newDelegateQueue synchronously:NO];
  1003. }
  1004. - (void)synchronouslySetDelegateQueue:(dispatch_queue_t)newDelegateQueue
  1005. {
  1006. [self setDelegateQueue:newDelegateQueue synchronously:YES];
  1007. }
  1008. - (void)getDelegate:(id<GCDAsyncSocketDelegate> *)delegatePtr delegateQueue:(dispatch_queue_t *)delegateQueuePtr
  1009. {
  1010. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  1011. {
  1012. if (delegatePtr) *delegatePtr = delegate;
  1013. if (delegateQueuePtr) *delegateQueuePtr = delegateQueue;
  1014. }
  1015. else
  1016. {
  1017. __block id dPtr = NULL;
  1018. __block dispatch_queue_t dqPtr = NULL;
  1019. dispatch_sync(socketQueue, ^{
  1020. dPtr = self->delegate;
  1021. dqPtr = self->delegateQueue;
  1022. });
  1023. if (delegatePtr) *delegatePtr = dPtr;
  1024. if (delegateQueuePtr) *delegateQueuePtr = dqPtr;
  1025. }
  1026. }
  1027. - (void)setDelegate:(id)newDelegate delegateQueue:(dispatch_queue_t)newDelegateQueue synchronously:(BOOL)synchronously
  1028. {
  1029. dispatch_block_t block = ^{
  1030. self->delegate = newDelegate;
  1031. #if !OS_OBJECT_USE_OBJC
  1032. if (self->delegateQueue) dispatch_release(self->delegateQueue);
  1033. if (newDelegateQueue) dispatch_retain(newDelegateQueue);
  1034. #endif
  1035. self->delegateQueue = newDelegateQueue;
  1036. };
  1037. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) {
  1038. block();
  1039. }
  1040. else {
  1041. if (synchronously)
  1042. dispatch_sync(socketQueue, block);
  1043. else
  1044. dispatch_async(socketQueue, block);
  1045. }
  1046. }
  1047. - (void)setDelegate:(id<GCDAsyncSocketDelegate>)newDelegate delegateQueue:(dispatch_queue_t)newDelegateQueue
  1048. {
  1049. [self setDelegate:newDelegate delegateQueue:newDelegateQueue synchronously:NO];
  1050. }
  1051. - (void)synchronouslySetDelegate:(id<GCDAsyncSocketDelegate>)newDelegate delegateQueue:(dispatch_queue_t)newDelegateQueue
  1052. {
  1053. [self setDelegate:newDelegate delegateQueue:newDelegateQueue synchronously:YES];
  1054. }
  1055. - (BOOL)isIPv4Enabled
  1056. {
  1057. // Note: YES means kIPv4Disabled is OFF
  1058. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  1059. {
  1060. return ((config & kIPv4Disabled) == 0);
  1061. }
  1062. else
  1063. {
  1064. __block BOOL result;
  1065. dispatch_sync(socketQueue, ^{
  1066. result = ((self->config & kIPv4Disabled) == 0);
  1067. });
  1068. return result;
  1069. }
  1070. }
  1071. - (void)setIPv4Enabled:(BOOL)flag
  1072. {
  1073. // Note: YES means kIPv4Disabled is OFF
  1074. dispatch_block_t block = ^{
  1075. if (flag)
  1076. self->config &= ~kIPv4Disabled;
  1077. else
  1078. self->config |= kIPv4Disabled;
  1079. };
  1080. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  1081. block();
  1082. else
  1083. dispatch_async(socketQueue, block);
  1084. }
  1085. - (BOOL)isIPv6Enabled
  1086. {
  1087. // Note: YES means kIPv6Disabled is OFF
  1088. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  1089. {
  1090. return ((config & kIPv6Disabled) == 0);
  1091. }
  1092. else
  1093. {
  1094. __block BOOL result;
  1095. dispatch_sync(socketQueue, ^{
  1096. result = ((self->config & kIPv6Disabled) == 0);
  1097. });
  1098. return result;
  1099. }
  1100. }
  1101. - (void)setIPv6Enabled:(BOOL)flag
  1102. {
  1103. // Note: YES means kIPv6Disabled is OFF
  1104. dispatch_block_t block = ^{
  1105. if (flag)
  1106. self->config &= ~kIPv6Disabled;
  1107. else
  1108. self->config |= kIPv6Disabled;
  1109. };
  1110. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  1111. block();
  1112. else
  1113. dispatch_async(socketQueue, block);
  1114. }
  1115. - (BOOL)isIPv4PreferredOverIPv6
  1116. {
  1117. // Note: YES means kPreferIPv6 is OFF
  1118. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  1119. {
  1120. return ((config & kPreferIPv6) == 0);
  1121. }
  1122. else
  1123. {
  1124. __block BOOL result;
  1125. dispatch_sync(socketQueue, ^{
  1126. result = ((self->config & kPreferIPv6) == 0);
  1127. });
  1128. return result;
  1129. }
  1130. }
  1131. - (void)setIPv4PreferredOverIPv6:(BOOL)flag
  1132. {
  1133. // Note: YES means kPreferIPv6 is OFF
  1134. dispatch_block_t block = ^{
  1135. if (flag)
  1136. self->config &= ~kPreferIPv6;
  1137. else
  1138. self->config |= kPreferIPv6;
  1139. };
  1140. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  1141. block();
  1142. else
  1143. dispatch_async(socketQueue, block);
  1144. }
  1145. - (NSTimeInterval) alternateAddressDelay {
  1146. __block NSTimeInterval delay;
  1147. dispatch_block_t block = ^{
  1148. delay = self->alternateAddressDelay;
  1149. };
  1150. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  1151. block();
  1152. else
  1153. dispatch_sync(socketQueue, block);
  1154. return delay;
  1155. }
  1156. - (void) setAlternateAddressDelay:(NSTimeInterval)delay {
  1157. dispatch_block_t block = ^{
  1158. self->alternateAddressDelay = delay;
  1159. };
  1160. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  1161. block();
  1162. else
  1163. dispatch_async(socketQueue, block);
  1164. }
  1165. - (id)userData
  1166. {
  1167. __block id result = nil;
  1168. dispatch_block_t block = ^{
  1169. result = self->userData;
  1170. };
  1171. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  1172. block();
  1173. else
  1174. dispatch_sync(socketQueue, block);
  1175. return result;
  1176. }
  1177. - (void)setUserData:(id)arbitraryUserData
  1178. {
  1179. dispatch_block_t block = ^{
  1180. if (self->userData != arbitraryUserData)
  1181. {
  1182. self->userData = arbitraryUserData;
  1183. }
  1184. };
  1185. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  1186. block();
  1187. else
  1188. dispatch_async(socketQueue, block);
  1189. }
  1190. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1191. #pragma mark Accepting
  1192. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1193. - (BOOL)acceptOnPort:(uint16_t)port error:(NSError **)errPtr
  1194. {
  1195. return [self acceptOnInterface:nil port:port error:errPtr];
  1196. }
  1197. - (BOOL)acceptOnInterface:(NSString *)inInterface port:(uint16_t)port error:(NSError **)errPtr
  1198. {
  1199. LogTrace();
  1200. // Just in-case interface parameter is immutable.
  1201. NSString *interface = [inInterface copy];
  1202. __block BOOL result = NO;
  1203. __block NSError *err = nil;
  1204. // CreateSocket Block
  1205. // This block will be invoked within the dispatch block below.
  1206. int(^createSocket)(int, NSData*) = ^int (int domain, NSData *interfaceAddr) {
  1207. int socketFD = socket(domain, SOCK_STREAM, 0);
  1208. if (socketFD == SOCKET_NULL)
  1209. {
  1210. NSString *reason = @"Error in socket() function";
  1211. err = [self errorWithErrno:errno reason:reason];
  1212. return SOCKET_NULL;
  1213. }
  1214. int status;
  1215. // Set socket options
  1216. status = fcntl(socketFD, F_SETFL, O_NONBLOCK);
  1217. if (status == -1)
  1218. {
  1219. NSString *reason = @"Error enabling non-blocking IO on socket (fcntl)";
  1220. err = [self errorWithErrno:errno reason:reason];
  1221. LogVerbose(@"close(socketFD)");
  1222. close(socketFD);
  1223. return SOCKET_NULL;
  1224. }
  1225. int reuseOn = 1;
  1226. status = setsockopt(socketFD, SOL_SOCKET, SO_REUSEADDR, &reuseOn, sizeof(reuseOn));
  1227. if (status == -1)
  1228. {
  1229. NSString *reason = @"Error enabling address reuse (setsockopt)";
  1230. err = [self errorWithErrno:errno reason:reason];
  1231. LogVerbose(@"close(socketFD)");
  1232. close(socketFD);
  1233. return SOCKET_NULL;
  1234. }
  1235. // Bind socket
  1236. status = bind(socketFD, (const struct sockaddr *)[interfaceAddr bytes], (socklen_t)[interfaceAddr length]);
  1237. if (status == -1)
  1238. {
  1239. NSString *reason = @"Error in bind() function";
  1240. err = [self errorWithErrno:errno reason:reason];
  1241. LogVerbose(@"close(socketFD)");
  1242. close(socketFD);
  1243. return SOCKET_NULL;
  1244. }
  1245. // Listen
  1246. status = listen(socketFD, 1024);
  1247. if (status == -1)
  1248. {
  1249. NSString *reason = @"Error in listen() function";
  1250. err = [self errorWithErrno:errno reason:reason];
  1251. LogVerbose(@"close(socketFD)");
  1252. close(socketFD);
  1253. return SOCKET_NULL;
  1254. }
  1255. return socketFD;
  1256. };
  1257. // Create dispatch block and run on socketQueue
  1258. dispatch_block_t block = ^{ @autoreleasepool {
  1259. if (self->delegate == nil) // Must have delegate set
  1260. {
  1261. NSString *msg = @"Attempting to accept without a delegate. Set a delegate first.";
  1262. err = [self badConfigError:msg];
  1263. return_from_block;
  1264. }
  1265. if (self->delegateQueue == NULL) // Must have delegate queue set
  1266. {
  1267. NSString *msg = @"Attempting to accept without a delegate queue. Set a delegate queue first.";
  1268. err = [self badConfigError:msg];
  1269. return_from_block;
  1270. }
  1271. BOOL isIPv4Disabled = (self->config & kIPv4Disabled) ? YES : NO;
  1272. BOOL isIPv6Disabled = (self->config & kIPv6Disabled) ? YES : NO;
  1273. if (isIPv4Disabled && isIPv6Disabled) // Must have IPv4 or IPv6 enabled
  1274. {
  1275. NSString *msg = @"Both IPv4 and IPv6 have been disabled. Must enable at least one protocol first.";
  1276. err = [self badConfigError:msg];
  1277. return_from_block;
  1278. }
  1279. if (![self isDisconnected]) // Must be disconnected
  1280. {
  1281. NSString *msg = @"Attempting to accept while connected or accepting connections. Disconnect first.";
  1282. err = [self badConfigError:msg];
  1283. return_from_block;
  1284. }
  1285. // Clear queues (spurious read/write requests post disconnect)
  1286. [self->readQueue removeAllObjects];
  1287. [self->writeQueue removeAllObjects];
  1288. // Resolve interface from description
  1289. NSMutableData *interface4 = nil;
  1290. NSMutableData *interface6 = nil;
  1291. [self getInterfaceAddress4:&interface4 address6:&interface6 fromDescription:interface port:port];
  1292. if ((interface4 == nil) && (interface6 == nil))
  1293. {
  1294. NSString *msg = @"Unknown interface. Specify valid interface by name (e.g. \"en1\") or IP address.";
  1295. err = [self badParamError:msg];
  1296. return_from_block;
  1297. }
  1298. if (isIPv4Disabled && (interface6 == nil))
  1299. {
  1300. NSString *msg = @"IPv4 has been disabled and specified interface doesn't support IPv6.";
  1301. err = [self badParamError:msg];
  1302. return_from_block;
  1303. }
  1304. if (isIPv6Disabled && (interface4 == nil))
  1305. {
  1306. NSString *msg = @"IPv6 has been disabled and specified interface doesn't support IPv4.";
  1307. err = [self badParamError:msg];
  1308. return_from_block;
  1309. }
  1310. BOOL enableIPv4 = !isIPv4Disabled && (interface4 != nil);
  1311. BOOL enableIPv6 = !isIPv6Disabled && (interface6 != nil);
  1312. // Create sockets, configure, bind, and listen
  1313. if (enableIPv4)
  1314. {
  1315. LogVerbose(@"Creating IPv4 socket");
  1316. self->socket4FD = createSocket(AF_INET, interface4);
  1317. if (self->socket4FD == SOCKET_NULL)
  1318. {
  1319. return_from_block;
  1320. }
  1321. }
  1322. if (enableIPv6)
  1323. {
  1324. LogVerbose(@"Creating IPv6 socket");
  1325. if (enableIPv4 && (port == 0))
  1326. {
  1327. // No specific port was specified, so we allowed the OS to pick an available port for us.
  1328. // Now we need to make sure the IPv6 socket listens on the same port as the IPv4 socket.
  1329. struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)[interface6 mutableBytes];
  1330. addr6->sin6_port = htons([self localPort4]);
  1331. }
  1332. self->socket6FD = createSocket(AF_INET6, interface6);
  1333. if (self->socket6FD == SOCKET_NULL)
  1334. {
  1335. if (self->socket4FD != SOCKET_NULL)
  1336. {
  1337. LogVerbose(@"close(socket4FD)");
  1338. close(self->socket4FD);
  1339. self->socket4FD = SOCKET_NULL;
  1340. }
  1341. return_from_block;
  1342. }
  1343. }
  1344. // Create accept sources
  1345. if (enableIPv4)
  1346. {
  1347. self->accept4Source = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, self->socket4FD, 0, self->socketQueue);
  1348. int socketFD = self->socket4FD;
  1349. dispatch_source_t acceptSource = self->accept4Source;
  1350. __weak GCDAsyncSocket *weakSelf = self;
  1351. dispatch_source_set_event_handler(self->accept4Source, ^{ @autoreleasepool {
  1352. #pragma clang diagnostic push
  1353. #pragma clang diagnostic warning "-Wimplicit-retain-self"
  1354. __strong GCDAsyncSocket *strongSelf = weakSelf;
  1355. if (strongSelf == nil) return_from_block;
  1356. LogVerbose(@"event4Block");
  1357. unsigned long i = 0;
  1358. unsigned long numPendingConnections = dispatch_source_get_data(acceptSource);
  1359. LogVerbose(@"numPendingConnections: %lu", numPendingConnections);
  1360. while ([strongSelf doAccept:socketFD] && (++i < numPendingConnections));
  1361. #pragma clang diagnostic pop
  1362. }});
  1363. dispatch_source_set_cancel_handler(self->accept4Source, ^{
  1364. #pragma clang diagnostic push
  1365. #pragma clang diagnostic warning "-Wimplicit-retain-self"
  1366. #if !OS_OBJECT_USE_OBJC
  1367. LogVerbose(@"dispatch_release(accept4Source)");
  1368. dispatch_release(acceptSource);
  1369. #endif
  1370. LogVerbose(@"close(socket4FD)");
  1371. close(socketFD);
  1372. #pragma clang diagnostic pop
  1373. });
  1374. LogVerbose(@"dispatch_resume(accept4Source)");
  1375. dispatch_resume(self->accept4Source);
  1376. }
  1377. if (enableIPv6)
  1378. {
  1379. self->accept6Source = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, self->socket6FD, 0, self->socketQueue);
  1380. int socketFD = self->socket6FD;
  1381. dispatch_source_t acceptSource = self->accept6Source;
  1382. __weak GCDAsyncSocket *weakSelf = self;
  1383. dispatch_source_set_event_handler(self->accept6Source, ^{ @autoreleasepool {
  1384. #pragma clang diagnostic push
  1385. #pragma clang diagnostic warning "-Wimplicit-retain-self"
  1386. __strong GCDAsyncSocket *strongSelf = weakSelf;
  1387. if (strongSelf == nil) return_from_block;
  1388. LogVerbose(@"event6Block");
  1389. unsigned long i = 0;
  1390. unsigned long numPendingConnections = dispatch_source_get_data(acceptSource);
  1391. LogVerbose(@"numPendingConnections: %lu", numPendingConnections);
  1392. while ([strongSelf doAccept:socketFD] && (++i < numPendingConnections));
  1393. #pragma clang diagnostic pop
  1394. }});
  1395. dispatch_source_set_cancel_handler(self->accept6Source, ^{
  1396. #pragma clang diagnostic push
  1397. #pragma clang diagnostic warning "-Wimplicit-retain-self"
  1398. #if !OS_OBJECT_USE_OBJC
  1399. LogVerbose(@"dispatch_release(accept6Source)");
  1400. dispatch_release(acceptSource);
  1401. #endif
  1402. LogVerbose(@"close(socket6FD)");
  1403. close(socketFD);
  1404. #pragma clang diagnostic pop
  1405. });
  1406. LogVerbose(@"dispatch_resume(accept6Source)");
  1407. dispatch_resume(self->accept6Source);
  1408. }
  1409. self->flags |= kSocketStarted;
  1410. result = YES;
  1411. }};
  1412. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  1413. block();
  1414. else
  1415. dispatch_sync(socketQueue, block);
  1416. if (result == NO)
  1417. {
  1418. LogInfo(@"Error in accept: %@", err);
  1419. if (errPtr)
  1420. *errPtr = err;
  1421. }
  1422. return result;
  1423. }
  1424. - (BOOL)acceptOnUrl:(NSURL *)url error:(NSError **)errPtr
  1425. {
  1426. LogTrace();
  1427. __block BOOL result = NO;
  1428. __block NSError *err = nil;
  1429. // CreateSocket Block
  1430. // This block will be invoked within the dispatch block below.
  1431. int(^createSocket)(int, NSData*) = ^int (int domain, NSData *interfaceAddr) {
  1432. int socketFD = socket(domain, SOCK_STREAM, 0);
  1433. if (socketFD == SOCKET_NULL)
  1434. {
  1435. NSString *reason = @"Error in socket() function";
  1436. err = [self errorWithErrno:errno reason:reason];
  1437. return SOCKET_NULL;
  1438. }
  1439. int status;
  1440. // Set socket options
  1441. status = fcntl(socketFD, F_SETFL, O_NONBLOCK);
  1442. if (status == -1)
  1443. {
  1444. NSString *reason = @"Error enabling non-blocking IO on socket (fcntl)";
  1445. err = [self errorWithErrno:errno reason:reason];
  1446. LogVerbose(@"close(socketFD)");
  1447. close(socketFD);
  1448. return SOCKET_NULL;
  1449. }
  1450. int reuseOn = 1;
  1451. status = setsockopt(socketFD, SOL_SOCKET, SO_REUSEADDR, &reuseOn, sizeof(reuseOn));
  1452. if (status == -1)
  1453. {
  1454. NSString *reason = @"Error enabling address reuse (setsockopt)";
  1455. err = [self errorWithErrno:errno reason:reason];
  1456. LogVerbose(@"close(socketFD)");
  1457. close(socketFD);
  1458. return SOCKET_NULL;
  1459. }
  1460. // Bind socket
  1461. status = bind(socketFD, (const struct sockaddr *)[interfaceAddr bytes], (socklen_t)[interfaceAddr length]);
  1462. if (status == -1)
  1463. {
  1464. NSString *reason = @"Error in bind() function";
  1465. err = [self errorWithErrno:errno reason:reason];
  1466. LogVerbose(@"close(socketFD)");
  1467. close(socketFD);
  1468. return SOCKET_NULL;
  1469. }
  1470. // Listen
  1471. status = listen(socketFD, 1024);
  1472. if (status == -1)
  1473. {
  1474. NSString *reason = @"Error in listen() function";
  1475. err = [self errorWithErrno:errno reason:reason];
  1476. LogVerbose(@"close(socketFD)");
  1477. close(socketFD);
  1478. return SOCKET_NULL;
  1479. }
  1480. return socketFD;
  1481. };
  1482. // Create dispatch block and run on socketQueue
  1483. dispatch_block_t block = ^{ @autoreleasepool {
  1484. if (self->delegate == nil) // Must have delegate set
  1485. {
  1486. NSString *msg = @"Attempting to accept without a delegate. Set a delegate first.";
  1487. err = [self badConfigError:msg];
  1488. return_from_block;
  1489. }
  1490. if (self->delegateQueue == NULL) // Must have delegate queue set
  1491. {
  1492. NSString *msg = @"Attempting to accept without a delegate queue. Set a delegate queue first.";
  1493. err = [self badConfigError:msg];
  1494. return_from_block;
  1495. }
  1496. if (![self isDisconnected]) // Must be disconnected
  1497. {
  1498. NSString *msg = @"Attempting to accept while connected or accepting connections. Disconnect first.";
  1499. err = [self badConfigError:msg];
  1500. return_from_block;
  1501. }
  1502. // Clear queues (spurious read/write requests post disconnect)
  1503. [self->readQueue removeAllObjects];
  1504. [self->writeQueue removeAllObjects];
  1505. // Remove a previous socket
  1506. NSError *error = nil;
  1507. NSFileManager *fileManager = [NSFileManager defaultManager];
  1508. NSString *urlPath = url.path;
  1509. if (urlPath && [fileManager fileExistsAtPath:urlPath]) {
  1510. if (![fileManager removeItemAtURL:url error:&error]) {
  1511. NSString *msg = @"Could not remove previous unix domain socket at given url.";
  1512. err = [self otherError:msg];
  1513. return_from_block;
  1514. }
  1515. }
  1516. // Resolve interface from description
  1517. NSData *interface = [self getInterfaceAddressFromUrl:url];
  1518. if (interface == nil)
  1519. {
  1520. NSString *msg = @"Invalid unix domain url. Specify a valid file url that does not exist (e.g. \"file:///tmp/socket\")";
  1521. err = [self badParamError:msg];
  1522. return_from_block;
  1523. }
  1524. // Create sockets, configure, bind, and listen
  1525. LogVerbose(@"Creating unix domain socket");
  1526. self->socketUN = createSocket(AF_UNIX, interface);
  1527. if (self->socketUN == SOCKET_NULL)
  1528. {
  1529. return_from_block;
  1530. }
  1531. self->socketUrl = url;
  1532. // Create accept sources
  1533. self->acceptUNSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, self->socketUN, 0, self->socketQueue);
  1534. int socketFD = self->socketUN;
  1535. dispatch_source_t acceptSource = self->acceptUNSource;
  1536. __weak GCDAsyncSocket *weakSelf = self;
  1537. dispatch_source_set_event_handler(self->acceptUNSource, ^{ @autoreleasepool {
  1538. __strong GCDAsyncSocket *strongSelf = weakSelf;
  1539. LogVerbose(@"eventUNBlock");
  1540. unsigned long i = 0;
  1541. unsigned long numPendingConnections = dispatch_source_get_data(acceptSource);
  1542. LogVerbose(@"numPendingConnections: %lu", numPendingConnections);
  1543. while ([strongSelf doAccept:socketFD] && (++i < numPendingConnections));
  1544. }});
  1545. dispatch_source_set_cancel_handler(self->acceptUNSource, ^{
  1546. #if !OS_OBJECT_USE_OBJC
  1547. LogVerbose(@"dispatch_release(acceptUNSource)");
  1548. dispatch_release(acceptSource);
  1549. #endif
  1550. LogVerbose(@"close(socketUN)");
  1551. close(socketFD);
  1552. });
  1553. LogVerbose(@"dispatch_resume(acceptUNSource)");
  1554. dispatch_resume(self->acceptUNSource);
  1555. self->flags |= kSocketStarted;
  1556. result = YES;
  1557. }};
  1558. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  1559. block();
  1560. else
  1561. dispatch_sync(socketQueue, block);
  1562. if (result == NO)
  1563. {
  1564. LogInfo(@"Error in accept: %@", err);
  1565. if (errPtr)
  1566. *errPtr = err;
  1567. }
  1568. return result;
  1569. }
  1570. - (BOOL)doAccept:(int)parentSocketFD
  1571. {
  1572. LogTrace();
  1573. int socketType;
  1574. int childSocketFD;
  1575. NSData *childSocketAddress;
  1576. if (parentSocketFD == socket4FD)
  1577. {
  1578. socketType = 0;
  1579. struct sockaddr_in addr;
  1580. socklen_t addrLen = sizeof(addr);
  1581. childSocketFD = accept(parentSocketFD, (struct sockaddr *)&addr, &addrLen);
  1582. if (childSocketFD == -1)
  1583. {
  1584. LogWarn(@"Accept failed with error: %@", [self errnoError]);
  1585. return NO;
  1586. }
  1587. childSocketAddress = [NSData dataWithBytes:&addr length:addrLen];
  1588. }
  1589. else if (parentSocketFD == socket6FD)
  1590. {
  1591. socketType = 1;
  1592. struct sockaddr_in6 addr;
  1593. socklen_t addrLen = sizeof(addr);
  1594. childSocketFD = accept(parentSocketFD, (struct sockaddr *)&addr, &addrLen);
  1595. if (childSocketFD == -1)
  1596. {
  1597. LogWarn(@"Accept failed with error: %@", [self errnoError]);
  1598. return NO;
  1599. }
  1600. childSocketAddress = [NSData dataWithBytes:&addr length:addrLen];
  1601. }
  1602. else // if (parentSocketFD == socketUN)
  1603. {
  1604. socketType = 2;
  1605. struct sockaddr_un addr;
  1606. socklen_t addrLen = sizeof(addr);
  1607. childSocketFD = accept(parentSocketFD, (struct sockaddr *)&addr, &addrLen);
  1608. if (childSocketFD == -1)
  1609. {
  1610. LogWarn(@"Accept failed with error: %@", [self errnoError]);
  1611. return NO;
  1612. }
  1613. childSocketAddress = [NSData dataWithBytes:&addr length:addrLen];
  1614. }
  1615. // Enable non-blocking IO on the socket
  1616. int result = fcntl(childSocketFD, F_SETFL, O_NONBLOCK);
  1617. if (result == -1)
  1618. {
  1619. LogWarn(@"Error enabling non-blocking IO on accepted socket (fcntl)");
  1620. LogVerbose(@"close(childSocketFD)");
  1621. close(childSocketFD);
  1622. return NO;
  1623. }
  1624. // Prevent SIGPIPE signals
  1625. int nosigpipe = 1;
  1626. setsockopt(childSocketFD, SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe, sizeof(nosigpipe));
  1627. // Notify delegate
  1628. if (delegateQueue)
  1629. {
  1630. __strong id<GCDAsyncSocketDelegate> theDelegate = delegate;
  1631. dispatch_async(delegateQueue, ^{ @autoreleasepool {
  1632. // Query delegate for custom socket queue
  1633. dispatch_queue_t childSocketQueue = NULL;
  1634. if ([theDelegate respondsToSelector:@selector(newSocketQueueForConnectionFromAddress:onSocket:)])
  1635. {
  1636. childSocketQueue = [theDelegate newSocketQueueForConnectionFromAddress:childSocketAddress
  1637. onSocket:self];
  1638. }
  1639. // Create GCDAsyncSocket instance for accepted socket
  1640. GCDAsyncSocket *acceptedSocket = [[[self class] alloc] initWithDelegate:theDelegate
  1641. delegateQueue:self->delegateQueue
  1642. socketQueue:childSocketQueue];
  1643. if (socketType == 0)
  1644. acceptedSocket->socket4FD = childSocketFD;
  1645. else if (socketType == 1)
  1646. acceptedSocket->socket6FD = childSocketFD;
  1647. else
  1648. acceptedSocket->socketUN = childSocketFD;
  1649. acceptedSocket->flags = (kSocketStarted | kConnected);
  1650. // Setup read and write sources for accepted socket
  1651. dispatch_async(acceptedSocket->socketQueue, ^{ @autoreleasepool {
  1652. [acceptedSocket setupReadAndWriteSourcesForNewlyConnectedSocket:childSocketFD];
  1653. }});
  1654. // Notify delegate
  1655. if ([theDelegate respondsToSelector:@selector(socket:didAcceptNewSocket:)])
  1656. {
  1657. [theDelegate socket:self didAcceptNewSocket:acceptedSocket];
  1658. }
  1659. // Release the socket queue returned from the delegate (it was retained by acceptedSocket)
  1660. #if !OS_OBJECT_USE_OBJC
  1661. if (childSocketQueue) dispatch_release(childSocketQueue);
  1662. #endif
  1663. // The accepted socket should have been retained by the delegate.
  1664. // Otherwise it gets properly released when exiting the block.
  1665. }});
  1666. }
  1667. return YES;
  1668. }
  1669. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1670. #pragma mark Connecting
  1671. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1672. /**
  1673. * This method runs through the various checks required prior to a connection attempt.
  1674. * It is shared between the connectToHost and connectToAddress methods.
  1675. *
  1676. **/
  1677. - (BOOL)preConnectWithInterface:(NSString *)interface error:(NSError **)errPtr
  1678. {
  1679. NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue");
  1680. if (delegate == nil) // Must have delegate set
  1681. {
  1682. if (errPtr)
  1683. {
  1684. NSString *msg = @"Attempting to connect without a delegate. Set a delegate first.";
  1685. *errPtr = [self badConfigError:msg];
  1686. }
  1687. return NO;
  1688. }
  1689. if (delegateQueue == NULL) // Must have delegate queue set
  1690. {
  1691. if (errPtr)
  1692. {
  1693. NSString *msg = @"Attempting to connect without a delegate queue. Set a delegate queue first.";
  1694. *errPtr = [self badConfigError:msg];
  1695. }
  1696. return NO;
  1697. }
  1698. if (![self isDisconnected]) // Must be disconnected
  1699. {
  1700. if (errPtr)
  1701. {
  1702. NSString *msg = @"Attempting to connect while connected or accepting connections. Disconnect first.";
  1703. *errPtr = [self badConfigError:msg];
  1704. }
  1705. return NO;
  1706. }
  1707. BOOL isIPv4Disabled = (config & kIPv4Disabled) ? YES : NO;
  1708. BOOL isIPv6Disabled = (config & kIPv6Disabled) ? YES : NO;
  1709. if (isIPv4Disabled && isIPv6Disabled) // Must have IPv4 or IPv6 enabled
  1710. {
  1711. if (errPtr)
  1712. {
  1713. NSString *msg = @"Both IPv4 and IPv6 have been disabled. Must enable at least one protocol first.";
  1714. *errPtr = [self badConfigError:msg];
  1715. }
  1716. return NO;
  1717. }
  1718. if (interface)
  1719. {
  1720. NSMutableData *interface4 = nil;
  1721. NSMutableData *interface6 = nil;
  1722. [self getInterfaceAddress4:&interface4 address6:&interface6 fromDescription:interface port:0];
  1723. if ((interface4 == nil) && (interface6 == nil))
  1724. {
  1725. if (errPtr)
  1726. {
  1727. NSString *msg = @"Unknown interface. Specify valid interface by name (e.g. \"en1\") or IP address.";
  1728. *errPtr = [self badParamError:msg];
  1729. }
  1730. return NO;
  1731. }
  1732. if (isIPv4Disabled && (interface6 == nil))
  1733. {
  1734. if (errPtr)
  1735. {
  1736. NSString *msg = @"IPv4 has been disabled and specified interface doesn't support IPv6.";
  1737. *errPtr = [self badParamError:msg];
  1738. }
  1739. return NO;
  1740. }
  1741. if (isIPv6Disabled && (interface4 == nil))
  1742. {
  1743. if (errPtr)
  1744. {
  1745. NSString *msg = @"IPv6 has been disabled and specified interface doesn't support IPv4.";
  1746. *errPtr = [self badParamError:msg];
  1747. }
  1748. return NO;
  1749. }
  1750. connectInterface4 = interface4;
  1751. connectInterface6 = interface6;
  1752. }
  1753. // Clear queues (spurious read/write requests post disconnect)
  1754. [readQueue removeAllObjects];
  1755. [writeQueue removeAllObjects];
  1756. return YES;
  1757. }
  1758. - (BOOL)preConnectWithUrl:(NSURL *)url error:(NSError **)errPtr
  1759. {
  1760. NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue");
  1761. if (delegate == nil) // Must have delegate set
  1762. {
  1763. if (errPtr)
  1764. {
  1765. NSString *msg = @"Attempting to connect without a delegate. Set a delegate first.";
  1766. *errPtr = [self badConfigError:msg];
  1767. }
  1768. return NO;
  1769. }
  1770. if (delegateQueue == NULL) // Must have delegate queue set
  1771. {
  1772. if (errPtr)
  1773. {
  1774. NSString *msg = @"Attempting to connect without a delegate queue. Set a delegate queue first.";
  1775. *errPtr = [self badConfigError:msg];
  1776. }
  1777. return NO;
  1778. }
  1779. if (![self isDisconnected]) // Must be disconnected
  1780. {
  1781. if (errPtr)
  1782. {
  1783. NSString *msg = @"Attempting to connect while connected or accepting connections. Disconnect first.";
  1784. *errPtr = [self badConfigError:msg];
  1785. }
  1786. return NO;
  1787. }
  1788. NSData *interface = [self getInterfaceAddressFromUrl:url];
  1789. if (interface == nil)
  1790. {
  1791. if (errPtr)
  1792. {
  1793. NSString *msg = @"Unknown interface. Specify valid interface by name (e.g. \"en1\") or IP address.";
  1794. *errPtr = [self badParamError:msg];
  1795. }
  1796. return NO;
  1797. }
  1798. connectInterfaceUN = interface;
  1799. // Clear queues (spurious read/write requests post disconnect)
  1800. [readQueue removeAllObjects];
  1801. [writeQueue removeAllObjects];
  1802. return YES;
  1803. }
  1804. - (BOOL)connectToHost:(NSString*)host onPort:(uint16_t)port error:(NSError **)errPtr
  1805. {
  1806. return [self connectToHost:host onPort:port withTimeout:-1 error:errPtr];
  1807. }
  1808. - (BOOL)connectToHost:(NSString *)host
  1809. onPort:(uint16_t)port
  1810. withTimeout:(NSTimeInterval)timeout
  1811. error:(NSError **)errPtr
  1812. {
  1813. return [self connectToHost:host onPort:port viaInterface:nil withTimeout:timeout error:errPtr];
  1814. }
  1815. - (BOOL)connectToHost:(NSString *)inHost
  1816. onPort:(uint16_t)port
  1817. viaInterface:(NSString *)inInterface
  1818. withTimeout:(NSTimeInterval)timeout
  1819. error:(NSError **)errPtr
  1820. {
  1821. LogTrace();
  1822. // Just in case immutable objects were passed
  1823. NSString *host = [inHost copy];
  1824. NSString *interface = [inInterface copy];
  1825. __block BOOL result = NO;
  1826. __block NSError *preConnectErr = nil;
  1827. dispatch_block_t block = ^{ @autoreleasepool {
  1828. // Check for problems with host parameter
  1829. if ([host length] == 0)
  1830. {
  1831. NSString *msg = @"Invalid host parameter (nil or \"\"). Should be a domain name or IP address string.";
  1832. preConnectErr = [self badParamError:msg];
  1833. return_from_block;
  1834. }
  1835. // Run through standard pre-connect checks
  1836. if (![self preConnectWithInterface:interface error:&preConnectErr])
  1837. {
  1838. return_from_block;
  1839. }
  1840. // We've made it past all the checks.
  1841. // It's time to start the connection process.
  1842. self->flags |= kSocketStarted;
  1843. LogVerbose(@"Dispatching DNS lookup...");
  1844. // It's possible that the given host parameter is actually a NSMutableString.
  1845. // So we want to copy it now, within this block that will be executed synchronously.
  1846. // This way the asynchronous lookup block below doesn't have to worry about it changing.
  1847. NSString *hostCpy = [host copy];
  1848. int aStateIndex = self->stateIndex;
  1849. __weak GCDAsyncSocket *weakSelf = self;
  1850. dispatch_queue_t globalConcurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
  1851. dispatch_async(globalConcurrentQueue, ^{ @autoreleasepool {
  1852. #pragma clang diagnostic push
  1853. #pragma clang diagnostic warning "-Wimplicit-retain-self"
  1854. NSError *lookupErr = nil;
  1855. NSMutableArray *addresses = [[self class] lookupHost:hostCpy port:port error:&lookupErr];
  1856. __strong GCDAsyncSocket *strongSelf = weakSelf;
  1857. if (strongSelf == nil) return_from_block;
  1858. if (lookupErr)
  1859. {
  1860. dispatch_async(strongSelf->socketQueue, ^{ @autoreleasepool {
  1861. [strongSelf lookup:aStateIndex didFail:lookupErr];
  1862. }});
  1863. }
  1864. else
  1865. {
  1866. NSData *address4 = nil;
  1867. NSData *address6 = nil;
  1868. for (NSData *address in addresses)
  1869. {
  1870. if (!address4 && [[self class] isIPv4Address:address])
  1871. {
  1872. address4 = address;
  1873. }
  1874. else if (!address6 && [[self class] isIPv6Address:address])
  1875. {
  1876. address6 = address;
  1877. }
  1878. }
  1879. dispatch_async(strongSelf->socketQueue, ^{ @autoreleasepool {
  1880. [strongSelf lookup:aStateIndex didSucceedWithAddress4:address4 address6:address6];
  1881. }});
  1882. }
  1883. #pragma clang diagnostic pop
  1884. }});
  1885. [self startConnectTimeout:timeout];
  1886. result = YES;
  1887. }};
  1888. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  1889. block();
  1890. else
  1891. dispatch_sync(socketQueue, block);
  1892. if (errPtr) *errPtr = preConnectErr;
  1893. return result;
  1894. }
  1895. - (BOOL)connectToAddress:(NSData *)remoteAddr error:(NSError **)errPtr
  1896. {
  1897. return [self connectToAddress:remoteAddr viaInterface:nil withTimeout:-1 error:errPtr];
  1898. }
  1899. - (BOOL)connectToAddress:(NSData *)remoteAddr withTimeout:(NSTimeInterval)timeout error:(NSError **)errPtr
  1900. {
  1901. return [self connectToAddress:remoteAddr viaInterface:nil withTimeout:timeout error:errPtr];
  1902. }
  1903. - (BOOL)connectToAddress:(NSData *)inRemoteAddr
  1904. viaInterface:(NSString *)inInterface
  1905. withTimeout:(NSTimeInterval)timeout
  1906. error:(NSError **)errPtr
  1907. {
  1908. LogTrace();
  1909. // Just in case immutable objects were passed
  1910. NSData *remoteAddr = [inRemoteAddr copy];
  1911. NSString *interface = [inInterface copy];
  1912. __block BOOL result = NO;
  1913. __block NSError *err = nil;
  1914. dispatch_block_t block = ^{ @autoreleasepool {
  1915. // Check for problems with remoteAddr parameter
  1916. NSData *address4 = nil;
  1917. NSData *address6 = nil;
  1918. if ([remoteAddr length] >= sizeof(struct sockaddr))
  1919. {
  1920. const struct sockaddr *sockaddr = (const struct sockaddr *)[remoteAddr bytes];
  1921. if (sockaddr->sa_family == AF_INET)
  1922. {
  1923. if ([remoteAddr length] == sizeof(struct sockaddr_in))
  1924. {
  1925. address4 = remoteAddr;
  1926. }
  1927. }
  1928. else if (sockaddr->sa_family == AF_INET6)
  1929. {
  1930. if ([remoteAddr length] == sizeof(struct sockaddr_in6))
  1931. {
  1932. address6 = remoteAddr;
  1933. }
  1934. }
  1935. }
  1936. if ((address4 == nil) && (address6 == nil))
  1937. {
  1938. NSString *msg = @"A valid IPv4 or IPv6 address was not given";
  1939. err = [self badParamError:msg];
  1940. return_from_block;
  1941. }
  1942. BOOL isIPv4Disabled = (self->config & kIPv4Disabled) ? YES : NO;
  1943. BOOL isIPv6Disabled = (self->config & kIPv6Disabled) ? YES : NO;
  1944. if (isIPv4Disabled && (address4 != nil))
  1945. {
  1946. NSString *msg = @"IPv4 has been disabled and an IPv4 address was passed.";
  1947. err = [self badParamError:msg];
  1948. return_from_block;
  1949. }
  1950. if (isIPv6Disabled && (address6 != nil))
  1951. {
  1952. NSString *msg = @"IPv6 has been disabled and an IPv6 address was passed.";
  1953. err = [self badParamError:msg];
  1954. return_from_block;
  1955. }
  1956. // Run through standard pre-connect checks
  1957. if (![self preConnectWithInterface:interface error:&err])
  1958. {
  1959. return_from_block;
  1960. }
  1961. // We've made it past all the checks.
  1962. // It's time to start the connection process.
  1963. if (![self connectWithAddress4:address4 address6:address6 error:&err])
  1964. {
  1965. return_from_block;
  1966. }
  1967. self->flags |= kSocketStarted;
  1968. [self startConnectTimeout:timeout];
  1969. result = YES;
  1970. }};
  1971. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  1972. block();
  1973. else
  1974. dispatch_sync(socketQueue, block);
  1975. if (result == NO)
  1976. {
  1977. if (errPtr)
  1978. *errPtr = err;
  1979. }
  1980. return result;
  1981. }
  1982. - (BOOL)connectToUrl:(NSURL *)url withTimeout:(NSTimeInterval)timeout error:(NSError **)errPtr
  1983. {
  1984. LogTrace();
  1985. __block BOOL result = NO;
  1986. __block NSError *err = nil;
  1987. dispatch_block_t block = ^{ @autoreleasepool {
  1988. // Check for problems with host parameter
  1989. if ([url.path length] == 0)
  1990. {
  1991. NSString *msg = @"Invalid unix domain socket url.";
  1992. err = [self badParamError:msg];
  1993. return_from_block;
  1994. }
  1995. // Run through standard pre-connect checks
  1996. if (![self preConnectWithUrl:url error:&err])
  1997. {
  1998. return_from_block;
  1999. }
  2000. // We've made it past all the checks.
  2001. // It's time to start the connection process.
  2002. self->flags |= kSocketStarted;
  2003. // Start the normal connection process
  2004. NSError *connectError = nil;
  2005. if (![self connectWithAddressUN:self->connectInterfaceUN error:&connectError])
  2006. {
  2007. [self closeWithError:connectError];
  2008. return_from_block;
  2009. }
  2010. [self startConnectTimeout:timeout];
  2011. result = YES;
  2012. }};
  2013. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  2014. block();
  2015. else
  2016. dispatch_sync(socketQueue, block);
  2017. if (result == NO)
  2018. {
  2019. if (errPtr)
  2020. *errPtr = err;
  2021. }
  2022. return result;
  2023. }
  2024. - (BOOL)connectToNetService:(NSNetService *)netService error:(NSError **)errPtr
  2025. {
  2026. NSArray* addresses = [netService addresses];
  2027. for (NSData* address in addresses)
  2028. {
  2029. BOOL result = [self connectToAddress:address error:errPtr];
  2030. if (result)
  2031. {
  2032. return YES;
  2033. }
  2034. }
  2035. return NO;
  2036. }
  2037. - (void)lookup:(int)aStateIndex didSucceedWithAddress4:(NSData *)address4 address6:(NSData *)address6
  2038. {
  2039. LogTrace();
  2040. NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue");
  2041. NSAssert(address4 || address6, @"Expected at least one valid address");
  2042. if (aStateIndex != stateIndex)
  2043. {
  2044. LogInfo(@"Ignoring lookupDidSucceed, already disconnected");
  2045. // The connect operation has been cancelled.
  2046. // That is, socket was disconnected, or connection has already timed out.
  2047. return;
  2048. }
  2049. // Check for problems
  2050. BOOL isIPv4Disabled = (config & kIPv4Disabled) ? YES : NO;
  2051. BOOL isIPv6Disabled = (config & kIPv6Disabled) ? YES : NO;
  2052. if (isIPv4Disabled && (address6 == nil))
  2053. {
  2054. NSString *msg = @"IPv4 has been disabled and DNS lookup found no IPv6 address.";
  2055. [self closeWithError:[self otherError:msg]];
  2056. return;
  2057. }
  2058. if (isIPv6Disabled && (address4 == nil))
  2059. {
  2060. NSString *msg = @"IPv6 has been disabled and DNS lookup found no IPv4 address.";
  2061. [self closeWithError:[self otherError:msg]];
  2062. return;
  2063. }
  2064. // Start the normal connection process
  2065. NSError *err = nil;
  2066. if (![self connectWithAddress4:address4 address6:address6 error:&err])
  2067. {
  2068. [self closeWithError:err];
  2069. }
  2070. }
  2071. /**
  2072. * This method is called if the DNS lookup fails.
  2073. * This method is executed on the socketQueue.
  2074. *
  2075. * Since the DNS lookup executed synchronously on a global concurrent queue,
  2076. * the original connection request may have already been cancelled or timed-out by the time this method is invoked.
  2077. * The lookupIndex tells us whether the lookup is still valid or not.
  2078. **/
  2079. - (void)lookup:(int)aStateIndex didFail:(NSError *)error
  2080. {
  2081. LogTrace();
  2082. NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue");
  2083. if (aStateIndex != stateIndex)
  2084. {
  2085. LogInfo(@"Ignoring lookup:didFail: - already disconnected");
  2086. // The connect operation has been cancelled.
  2087. // That is, socket was disconnected, or connection has already timed out.
  2088. return;
  2089. }
  2090. [self endConnectTimeout];
  2091. [self closeWithError:error];
  2092. }
  2093. - (BOOL)bindSocket:(int)socketFD toInterface:(NSData *)connectInterface error:(NSError **)errPtr
  2094. {
  2095. // Bind the socket to the desired interface (if needed)
  2096. if (connectInterface)
  2097. {
  2098. LogVerbose(@"Binding socket...");
  2099. if ([[self class] portFromAddress:connectInterface] > 0)
  2100. {
  2101. // Since we're going to be binding to a specific port,
  2102. // we should turn on reuseaddr to allow us to override sockets in time_wait.
  2103. int reuseOn = 1;
  2104. setsockopt(socketFD, SOL_SOCKET, SO_REUSEADDR, &reuseOn, sizeof(reuseOn));
  2105. }
  2106. const struct sockaddr *interfaceAddr = (const struct sockaddr *)[connectInterface bytes];
  2107. int result = bind(socketFD, interfaceAddr, (socklen_t)[connectInterface length]);
  2108. if (result != 0)
  2109. {
  2110. if (errPtr)
  2111. *errPtr = [self errorWithErrno:errno reason:@"Error in bind() function"];
  2112. return NO;
  2113. }
  2114. }
  2115. return YES;
  2116. }
  2117. - (int)createSocket:(int)family connectInterface:(NSData *)connectInterface errPtr:(NSError **)errPtr
  2118. {
  2119. int socketFD = socket(family, SOCK_STREAM, 0);
  2120. if (socketFD == SOCKET_NULL)
  2121. {
  2122. if (errPtr)
  2123. *errPtr = [self errorWithErrno:errno reason:@"Error in socket() function"];
  2124. return socketFD;
  2125. }
  2126. if (![self bindSocket:socketFD toInterface:connectInterface error:errPtr])
  2127. {
  2128. [self closeSocket:socketFD];
  2129. return SOCKET_NULL;
  2130. }
  2131. // Prevent SIGPIPE signals
  2132. int nosigpipe = 1;
  2133. setsockopt(socketFD, SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe, sizeof(nosigpipe));
  2134. return socketFD;
  2135. }
  2136. - (void)connectSocket:(int)socketFD address:(NSData *)address stateIndex:(int)aStateIndex
  2137. {
  2138. // If there already is a socket connected, we close socketFD and return
  2139. if (self.isConnected)
  2140. {
  2141. [self closeSocket:socketFD];
  2142. return;
  2143. }
  2144. // Start the connection process in a background queue
  2145. __weak GCDAsyncSocket *weakSelf = self;
  2146. dispatch_queue_t globalConcurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
  2147. dispatch_async(globalConcurrentQueue, ^{
  2148. #pragma clang diagnostic push
  2149. #pragma clang diagnostic warning "-Wimplicit-retain-self"
  2150. int result = connect(socketFD, (const struct sockaddr *)[address bytes], (socklen_t)[address length]);
  2151. int err = errno;
  2152. __strong GCDAsyncSocket *strongSelf = weakSelf;
  2153. if (strongSelf == nil) return_from_block;
  2154. dispatch_async(strongSelf->socketQueue, ^{ @autoreleasepool {
  2155. if (strongSelf.isConnected)
  2156. {
  2157. [strongSelf closeSocket:socketFD];
  2158. return_from_block;
  2159. }
  2160. if (result == 0)
  2161. {
  2162. [self closeUnusedSocket:socketFD];
  2163. [strongSelf didConnect:aStateIndex];
  2164. }
  2165. else
  2166. {
  2167. [strongSelf closeSocket:socketFD];
  2168. // If there are no more sockets trying to connect, we inform the error to the delegate
  2169. if (strongSelf.socket4FD == SOCKET_NULL && strongSelf.socket6FD == SOCKET_NULL)
  2170. {
  2171. NSError *error = [strongSelf errorWithErrno:err reason:@"Error in connect() function"];
  2172. [strongSelf didNotConnect:aStateIndex error:error];
  2173. }
  2174. }
  2175. }});
  2176. #pragma clang diagnostic pop
  2177. });
  2178. LogVerbose(@"Connecting...");
  2179. }
  2180. - (void)closeSocket:(int)socketFD
  2181. {
  2182. if (socketFD != SOCKET_NULL &&
  2183. (socketFD == socket6FD || socketFD == socket4FD))
  2184. {
  2185. close(socketFD);
  2186. if (socketFD == socket4FD)
  2187. {
  2188. LogVerbose(@"close(socket4FD)");
  2189. socket4FD = SOCKET_NULL;
  2190. }
  2191. else if (socketFD == socket6FD)
  2192. {
  2193. LogVerbose(@"close(socket6FD)");
  2194. socket6FD = SOCKET_NULL;
  2195. }
  2196. }
  2197. }
  2198. - (void)closeUnusedSocket:(int)usedSocketFD
  2199. {
  2200. if (usedSocketFD != socket4FD)
  2201. {
  2202. [self closeSocket:socket4FD];
  2203. }
  2204. else if (usedSocketFD != socket6FD)
  2205. {
  2206. [self closeSocket:socket6FD];
  2207. }
  2208. }
  2209. - (BOOL)connectWithAddress4:(NSData *)address4 address6:(NSData *)address6 error:(NSError **)errPtr
  2210. {
  2211. LogTrace();
  2212. NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue");
  2213. LogVerbose(@"IPv4: %@:%hu", [[self class] hostFromAddress:address4], [[self class] portFromAddress:address4]);
  2214. LogVerbose(@"IPv6: %@:%hu", [[self class] hostFromAddress:address6], [[self class] portFromAddress:address6]);
  2215. // Determine socket type
  2216. BOOL preferIPv6 = (config & kPreferIPv6) ? YES : NO;
  2217. // Create and bind the sockets
  2218. if (address4)
  2219. {
  2220. LogVerbose(@"Creating IPv4 socket");
  2221. socket4FD = [self createSocket:AF_INET connectInterface:connectInterface4 errPtr:errPtr];
  2222. }
  2223. if (address6)
  2224. {
  2225. LogVerbose(@"Creating IPv6 socket");
  2226. socket6FD = [self createSocket:AF_INET6 connectInterface:connectInterface6 errPtr:errPtr];
  2227. }
  2228. if (socket4FD == SOCKET_NULL && socket6FD == SOCKET_NULL)
  2229. {
  2230. return NO;
  2231. }
  2232. int socketFD, alternateSocketFD;
  2233. NSData *address, *alternateAddress;
  2234. if ((preferIPv6 && socket6FD != SOCKET_NULL) || socket4FD == SOCKET_NULL)
  2235. {
  2236. socketFD = socket6FD;
  2237. alternateSocketFD = socket4FD;
  2238. address = address6;
  2239. alternateAddress = address4;
  2240. }
  2241. else
  2242. {
  2243. socketFD = socket4FD;
  2244. alternateSocketFD = socket6FD;
  2245. address = address4;
  2246. alternateAddress = address6;
  2247. }
  2248. int aStateIndex = stateIndex;
  2249. [self connectSocket:socketFD address:address stateIndex:aStateIndex];
  2250. if (alternateAddress)
  2251. {
  2252. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(alternateAddressDelay * NSEC_PER_SEC)), socketQueue, ^{
  2253. [self connectSocket:alternateSocketFD address:alternateAddress stateIndex:aStateIndex];
  2254. });
  2255. }
  2256. return YES;
  2257. }
  2258. - (BOOL)connectWithAddressUN:(NSData *)address error:(NSError **)errPtr
  2259. {
  2260. LogTrace();
  2261. NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue");
  2262. // Create the socket
  2263. int socketFD;
  2264. LogVerbose(@"Creating unix domain socket");
  2265. socketUN = socket(AF_UNIX, SOCK_STREAM, 0);
  2266. socketFD = socketUN;
  2267. if (socketFD == SOCKET_NULL)
  2268. {
  2269. if (errPtr)
  2270. *errPtr = [self errorWithErrno:errno reason:@"Error in socket() function"];
  2271. return NO;
  2272. }
  2273. // Bind the socket to the desired interface (if needed)
  2274. LogVerbose(@"Binding socket...");
  2275. int reuseOn = 1;
  2276. setsockopt(socketFD, SOL_SOCKET, SO_REUSEADDR, &reuseOn, sizeof(reuseOn));
  2277. // const struct sockaddr *interfaceAddr = (const struct sockaddr *)[address bytes];
  2278. //
  2279. // int result = bind(socketFD, interfaceAddr, (socklen_t)[address length]);
  2280. // if (result != 0)
  2281. // {
  2282. // if (errPtr)
  2283. // *errPtr = [self errnoErrorWithReason:@"Error in bind() function"];
  2284. //
  2285. // return NO;
  2286. // }
  2287. // Prevent SIGPIPE signals
  2288. int nosigpipe = 1;
  2289. setsockopt(socketFD, SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe, sizeof(nosigpipe));
  2290. // Start the connection process in a background queue
  2291. int aStateIndex = stateIndex;
  2292. dispatch_queue_t globalConcurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
  2293. dispatch_async(globalConcurrentQueue, ^{
  2294. const struct sockaddr *addr = (const struct sockaddr *)[address bytes];
  2295. int result = connect(socketFD, addr, addr->sa_len);
  2296. if (result == 0)
  2297. {
  2298. dispatch_async(self->socketQueue, ^{ @autoreleasepool {
  2299. [self didConnect:aStateIndex];
  2300. }});
  2301. }
  2302. else
  2303. {
  2304. // TODO: Bad file descriptor
  2305. perror("connect");
  2306. NSError *error = [self errorWithErrno:errno reason:@"Error in connect() function"];
  2307. dispatch_async(self->socketQueue, ^{ @autoreleasepool {
  2308. [self didNotConnect:aStateIndex error:error];
  2309. }});
  2310. }
  2311. });
  2312. LogVerbose(@"Connecting...");
  2313. return YES;
  2314. }
  2315. - (void)didConnect:(int)aStateIndex
  2316. {
  2317. LogTrace();
  2318. NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue");
  2319. if (aStateIndex != stateIndex)
  2320. {
  2321. LogInfo(@"Ignoring didConnect, already disconnected");
  2322. // The connect operation has been cancelled.
  2323. // That is, socket was disconnected, or connection has already timed out.
  2324. return;
  2325. }
  2326. flags |= kConnected;
  2327. [self endConnectTimeout];
  2328. #if TARGET_OS_IPHONE
  2329. // The endConnectTimeout method executed above incremented the stateIndex.
  2330. aStateIndex = stateIndex;
  2331. #endif
  2332. // Setup read/write streams (as workaround for specific shortcomings in the iOS platform)
  2333. //
  2334. // Note:
  2335. // There may be configuration options that must be set by the delegate before opening the streams.
  2336. // The primary example is the kCFStreamNetworkServiceTypeVoIP flag, which only works on an unopened stream.
  2337. //
  2338. // Thus we wait until after the socket:didConnectToHost:port: delegate method has completed.
  2339. // This gives the delegate time to properly configure the streams if needed.
  2340. dispatch_block_t SetupStreamsPart1 = ^{
  2341. #if TARGET_OS_IPHONE
  2342. if (![self createReadAndWriteStream])
  2343. {
  2344. [self closeWithError:[self otherError:@"Error creating CFStreams"]];
  2345. return;
  2346. }
  2347. if (![self registerForStreamCallbacksIncludingReadWrite:NO])
  2348. {
  2349. [self closeWithError:[self otherError:@"Error in CFStreamSetClient"]];
  2350. return;
  2351. }
  2352. #endif
  2353. };
  2354. dispatch_block_t SetupStreamsPart2 = ^{
  2355. #if TARGET_OS_IPHONE
  2356. if (aStateIndex != self->stateIndex)
  2357. {
  2358. // The socket has been disconnected.
  2359. return;
  2360. }
  2361. if (![self addStreamsToRunLoop])
  2362. {
  2363. [self closeWithError:[self otherError:@"Error in CFStreamScheduleWithRunLoop"]];
  2364. return;
  2365. }
  2366. if (![self openStreams])
  2367. {
  2368. [self closeWithError:[self otherError:@"Error creating CFStreams"]];
  2369. return;
  2370. }
  2371. #endif
  2372. };
  2373. // Notify delegate
  2374. NSString *host = [self connectedHost];
  2375. uint16_t port = [self connectedPort];
  2376. NSURL *url = [self connectedUrl];
  2377. __strong id<GCDAsyncSocketDelegate> theDelegate = delegate;
  2378. if (delegateQueue && host != nil && [theDelegate respondsToSelector:@selector(socket:didConnectToHost:port:)])
  2379. {
  2380. SetupStreamsPart1();
  2381. dispatch_async(delegateQueue, ^{ @autoreleasepool {
  2382. [theDelegate socket:self didConnectToHost:host port:port];
  2383. dispatch_async(self->socketQueue, ^{ @autoreleasepool {
  2384. SetupStreamsPart2();
  2385. }});
  2386. }});
  2387. }
  2388. else if (delegateQueue && url != nil && [theDelegate respondsToSelector:@selector(socket:didConnectToUrl:)])
  2389. {
  2390. SetupStreamsPart1();
  2391. dispatch_async(delegateQueue, ^{ @autoreleasepool {
  2392. [theDelegate socket:self didConnectToUrl:url];
  2393. dispatch_async(self->socketQueue, ^{ @autoreleasepool {
  2394. SetupStreamsPart2();
  2395. }});
  2396. }});
  2397. }
  2398. else
  2399. {
  2400. SetupStreamsPart1();
  2401. SetupStreamsPart2();
  2402. }
  2403. // Get the connected socket
  2404. int socketFD = (socket4FD != SOCKET_NULL) ? socket4FD : (socket6FD != SOCKET_NULL) ? socket6FD : socketUN;
  2405. // Enable non-blocking IO on the socket
  2406. int result = fcntl(socketFD, F_SETFL, O_NONBLOCK);
  2407. if (result == -1)
  2408. {
  2409. NSString *errMsg = @"Error enabling non-blocking IO on socket (fcntl)";
  2410. [self closeWithError:[self otherError:errMsg]];
  2411. return;
  2412. }
  2413. // Setup our read/write sources
  2414. [self setupReadAndWriteSourcesForNewlyConnectedSocket:socketFD];
  2415. // Dequeue any pending read/write requests
  2416. [self maybeDequeueRead];
  2417. [self maybeDequeueWrite];
  2418. }
  2419. - (void)didNotConnect:(int)aStateIndex error:(NSError *)error
  2420. {
  2421. LogTrace();
  2422. NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue");
  2423. if (aStateIndex != stateIndex)
  2424. {
  2425. LogInfo(@"Ignoring didNotConnect, already disconnected");
  2426. // The connect operation has been cancelled.
  2427. // That is, socket was disconnected, or connection has already timed out.
  2428. return;
  2429. }
  2430. [self closeWithError:error];
  2431. }
  2432. - (void)startConnectTimeout:(NSTimeInterval)timeout
  2433. {
  2434. if (timeout >= 0.0)
  2435. {
  2436. connectTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, socketQueue);
  2437. __weak GCDAsyncSocket *weakSelf = self;
  2438. dispatch_source_set_event_handler(connectTimer, ^{ @autoreleasepool {
  2439. #pragma clang diagnostic push
  2440. #pragma clang diagnostic warning "-Wimplicit-retain-self"
  2441. __strong GCDAsyncSocket *strongSelf = weakSelf;
  2442. if (strongSelf == nil) return_from_block;
  2443. [strongSelf doConnectTimeout];
  2444. #pragma clang diagnostic pop
  2445. }});
  2446. #if !OS_OBJECT_USE_OBJC
  2447. dispatch_source_t theConnectTimer = connectTimer;
  2448. dispatch_source_set_cancel_handler(connectTimer, ^{
  2449. #pragma clang diagnostic push
  2450. #pragma clang diagnostic warning "-Wimplicit-retain-self"
  2451. LogVerbose(@"dispatch_release(connectTimer)");
  2452. dispatch_release(theConnectTimer);
  2453. #pragma clang diagnostic pop
  2454. });
  2455. #endif
  2456. dispatch_time_t tt = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeout * NSEC_PER_SEC));
  2457. dispatch_source_set_timer(connectTimer, tt, DISPATCH_TIME_FOREVER, 0);
  2458. dispatch_resume(connectTimer);
  2459. }
  2460. }
  2461. - (void)endConnectTimeout
  2462. {
  2463. LogTrace();
  2464. if (connectTimer)
  2465. {
  2466. dispatch_source_cancel(connectTimer);
  2467. connectTimer = NULL;
  2468. }
  2469. // Increment stateIndex.
  2470. // This will prevent us from processing results from any related background asynchronous operations.
  2471. //
  2472. // Note: This should be called from close method even if connectTimer is NULL.
  2473. // This is because one might disconnect a socket prior to a successful connection which had no timeout.
  2474. stateIndex++;
  2475. if (connectInterface4)
  2476. {
  2477. connectInterface4 = nil;
  2478. }
  2479. if (connectInterface6)
  2480. {
  2481. connectInterface6 = nil;
  2482. }
  2483. }
  2484. - (void)doConnectTimeout
  2485. {
  2486. LogTrace();
  2487. [self endConnectTimeout];
  2488. [self closeWithError:[self connectTimeoutError]];
  2489. }
  2490. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2491. #pragma mark Disconnecting
  2492. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2493. - (void)closeWithError:(NSError *)error
  2494. {
  2495. LogTrace();
  2496. NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue");
  2497. [self endConnectTimeout];
  2498. if (currentRead != nil) [self endCurrentRead];
  2499. if (currentWrite != nil) [self endCurrentWrite];
  2500. [readQueue removeAllObjects];
  2501. [writeQueue removeAllObjects];
  2502. [preBuffer reset];
  2503. #if TARGET_OS_IPHONE
  2504. {
  2505. if (readStream || writeStream)
  2506. {
  2507. [self removeStreamsFromRunLoop];
  2508. if (readStream)
  2509. {
  2510. CFReadStreamSetClient(readStream, kCFStreamEventNone, NULL, NULL);
  2511. CFReadStreamClose(readStream);
  2512. CFRelease(readStream);
  2513. readStream = NULL;
  2514. }
  2515. if (writeStream)
  2516. {
  2517. CFWriteStreamSetClient(writeStream, kCFStreamEventNone, NULL, NULL);
  2518. CFWriteStreamClose(writeStream);
  2519. CFRelease(writeStream);
  2520. writeStream = NULL;
  2521. }
  2522. }
  2523. }
  2524. #endif
  2525. [sslPreBuffer reset];
  2526. sslErrCode = lastSSLHandshakeError = noErr;
  2527. if (sslContext)
  2528. {
  2529. // Getting a linker error here about the SSLx() functions?
  2530. // You need to add the Security Framework to your application.
  2531. SSLClose(sslContext);
  2532. #if TARGET_OS_IPHONE || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 1080)
  2533. CFRelease(sslContext);
  2534. #else
  2535. SSLDisposeContext(sslContext);
  2536. #endif
  2537. sslContext = NULL;
  2538. }
  2539. // For some crazy reason (in my opinion), cancelling a dispatch source doesn't
  2540. // invoke the cancel handler if the dispatch source is paused.
  2541. // So we have to unpause the source if needed.
  2542. // This allows the cancel handler to be run, which in turn releases the source and closes the socket.
  2543. if (!accept4Source && !accept6Source && !acceptUNSource && !readSource && !writeSource)
  2544. {
  2545. LogVerbose(@"manually closing close");
  2546. if (socket4FD != SOCKET_NULL)
  2547. {
  2548. LogVerbose(@"close(socket4FD)");
  2549. close(socket4FD);
  2550. socket4FD = SOCKET_NULL;
  2551. }
  2552. if (socket6FD != SOCKET_NULL)
  2553. {
  2554. LogVerbose(@"close(socket6FD)");
  2555. close(socket6FD);
  2556. socket6FD = SOCKET_NULL;
  2557. }
  2558. if (socketUN != SOCKET_NULL)
  2559. {
  2560. LogVerbose(@"close(socketUN)");
  2561. close(socketUN);
  2562. socketUN = SOCKET_NULL;
  2563. unlink(socketUrl.path.fileSystemRepresentation);
  2564. socketUrl = nil;
  2565. }
  2566. }
  2567. else
  2568. {
  2569. if (accept4Source)
  2570. {
  2571. LogVerbose(@"dispatch_source_cancel(accept4Source)");
  2572. dispatch_source_cancel(accept4Source);
  2573. // We never suspend accept4Source
  2574. accept4Source = NULL;
  2575. }
  2576. if (accept6Source)
  2577. {
  2578. LogVerbose(@"dispatch_source_cancel(accept6Source)");
  2579. dispatch_source_cancel(accept6Source);
  2580. // We never suspend accept6Source
  2581. accept6Source = NULL;
  2582. }
  2583. if (acceptUNSource)
  2584. {
  2585. LogVerbose(@"dispatch_source_cancel(acceptUNSource)");
  2586. dispatch_source_cancel(acceptUNSource);
  2587. // We never suspend acceptUNSource
  2588. acceptUNSource = NULL;
  2589. }
  2590. if (readSource)
  2591. {
  2592. LogVerbose(@"dispatch_source_cancel(readSource)");
  2593. dispatch_source_cancel(readSource);
  2594. [self resumeReadSource];
  2595. readSource = NULL;
  2596. }
  2597. if (writeSource)
  2598. {
  2599. LogVerbose(@"dispatch_source_cancel(writeSource)");
  2600. dispatch_source_cancel(writeSource);
  2601. [self resumeWriteSource];
  2602. writeSource = NULL;
  2603. }
  2604. // The sockets will be closed by the cancel handlers of the corresponding source
  2605. socket4FD = SOCKET_NULL;
  2606. socket6FD = SOCKET_NULL;
  2607. socketUN = SOCKET_NULL;
  2608. }
  2609. // If the client has passed the connect/accept method, then the connection has at least begun.
  2610. // Notify delegate that it is now ending.
  2611. BOOL shouldCallDelegate = (flags & kSocketStarted) ? YES : NO;
  2612. BOOL isDeallocating = (flags & kDealloc) ? YES : NO;
  2613. // Clear stored socket info and all flags (config remains as is)
  2614. socketFDBytesAvailable = 0;
  2615. flags = 0;
  2616. sslWriteCachedLength = 0;
  2617. if (shouldCallDelegate)
  2618. {
  2619. __strong id<GCDAsyncSocketDelegate> theDelegate = delegate;
  2620. __strong id theSelf = isDeallocating ? nil : self;
  2621. if (delegateQueue && [theDelegate respondsToSelector: @selector(socketDidDisconnect:withError:)])
  2622. {
  2623. dispatch_async(delegateQueue, ^{ @autoreleasepool {
  2624. [theDelegate socketDidDisconnect:theSelf withError:error];
  2625. }});
  2626. }
  2627. }
  2628. }
  2629. - (void)disconnect
  2630. {
  2631. dispatch_block_t block = ^{ @autoreleasepool {
  2632. if (self->flags & kSocketStarted)
  2633. {
  2634. [self closeWithError:nil];
  2635. }
  2636. }};
  2637. // Synchronous disconnection, as documented in the header file
  2638. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  2639. block();
  2640. else
  2641. dispatch_sync(socketQueue, block);
  2642. }
  2643. - (void)disconnectAfterReading
  2644. {
  2645. dispatch_async(socketQueue, ^{ @autoreleasepool {
  2646. if (self->flags & kSocketStarted)
  2647. {
  2648. self->flags |= (kForbidReadsWrites | kDisconnectAfterReads);
  2649. [self maybeClose];
  2650. }
  2651. }});
  2652. }
  2653. - (void)disconnectAfterWriting
  2654. {
  2655. dispatch_async(socketQueue, ^{ @autoreleasepool {
  2656. if (self->flags & kSocketStarted)
  2657. {
  2658. self->flags |= (kForbidReadsWrites | kDisconnectAfterWrites);
  2659. [self maybeClose];
  2660. }
  2661. }});
  2662. }
  2663. - (void)disconnectAfterReadingAndWriting
  2664. {
  2665. dispatch_async(socketQueue, ^{ @autoreleasepool {
  2666. if (self->flags & kSocketStarted)
  2667. {
  2668. self->flags |= (kForbidReadsWrites | kDisconnectAfterReads | kDisconnectAfterWrites);
  2669. [self maybeClose];
  2670. }
  2671. }});
  2672. }
  2673. /**
  2674. * Closes the socket if possible.
  2675. * That is, if all writes have completed, and we're set to disconnect after writing,
  2676. * or if all reads have completed, and we're set to disconnect after reading.
  2677. **/
  2678. - (void)maybeClose
  2679. {
  2680. NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue");
  2681. BOOL shouldClose = NO;
  2682. if (flags & kDisconnectAfterReads)
  2683. {
  2684. if (([readQueue count] == 0) && (currentRead == nil))
  2685. {
  2686. if (flags & kDisconnectAfterWrites)
  2687. {
  2688. if (([writeQueue count] == 0) && (currentWrite == nil))
  2689. {
  2690. shouldClose = YES;
  2691. }
  2692. }
  2693. else
  2694. {
  2695. shouldClose = YES;
  2696. }
  2697. }
  2698. }
  2699. else if (flags & kDisconnectAfterWrites)
  2700. {
  2701. if (([writeQueue count] == 0) && (currentWrite == nil))
  2702. {
  2703. shouldClose = YES;
  2704. }
  2705. }
  2706. if (shouldClose)
  2707. {
  2708. [self closeWithError:nil];
  2709. }
  2710. }
  2711. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2712. #pragma mark Errors
  2713. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2714. - (NSError *)badConfigError:(NSString *)errMsg
  2715. {
  2716. NSDictionary *userInfo = @{NSLocalizedDescriptionKey : errMsg};
  2717. return [NSError errorWithDomain:GCDAsyncSocketErrorDomain code:GCDAsyncSocketBadConfigError userInfo:userInfo];
  2718. }
  2719. - (NSError *)badParamError:(NSString *)errMsg
  2720. {
  2721. NSDictionary *userInfo = @{NSLocalizedDescriptionKey : errMsg};
  2722. return [NSError errorWithDomain:GCDAsyncSocketErrorDomain code:GCDAsyncSocketBadParamError userInfo:userInfo];
  2723. }
  2724. + (NSError *)gaiError:(int)gai_error
  2725. {
  2726. NSString *errMsg = [NSString stringWithCString:gai_strerror(gai_error) encoding:NSASCIIStringEncoding];
  2727. NSDictionary *userInfo = @{NSLocalizedDescriptionKey : errMsg};
  2728. return [NSError errorWithDomain:@"kCFStreamErrorDomainNetDB" code:gai_error userInfo:userInfo];
  2729. }
  2730. - (NSError *)errorWithErrno:(int)err reason:(NSString *)reason
  2731. {
  2732. NSString *errMsg = [NSString stringWithUTF8String:strerror(err)];
  2733. NSDictionary *userInfo = @{NSLocalizedDescriptionKey : errMsg,
  2734. NSLocalizedFailureReasonErrorKey : reason};
  2735. return [NSError errorWithDomain:NSPOSIXErrorDomain code:err userInfo:userInfo];
  2736. }
  2737. - (NSError *)errnoError
  2738. {
  2739. NSString *errMsg = [NSString stringWithUTF8String:strerror(errno)];
  2740. NSDictionary *userInfo = @{NSLocalizedDescriptionKey : errMsg};
  2741. return [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:userInfo];
  2742. }
  2743. - (NSError *)sslError:(OSStatus)ssl_error
  2744. {
  2745. NSString *msg = @"Error code definition can be found in Apple's SecureTransport.h";
  2746. NSDictionary *userInfo = @{NSLocalizedRecoverySuggestionErrorKey : msg};
  2747. return [NSError errorWithDomain:@"kCFStreamErrorDomainSSL" code:ssl_error userInfo:userInfo];
  2748. }
  2749. - (NSError *)connectTimeoutError
  2750. {
  2751. NSString *errMsg = NSLocalizedStringWithDefaultValue(@"GCDAsyncSocketConnectTimeoutError",
  2752. @"GCDAsyncSocket", [NSBundle mainBundle],
  2753. @"Attempt to connect to host timed out", nil);
  2754. NSDictionary *userInfo = @{NSLocalizedDescriptionKey : errMsg};
  2755. return [NSError errorWithDomain:GCDAsyncSocketErrorDomain code:GCDAsyncSocketConnectTimeoutError userInfo:userInfo];
  2756. }
  2757. /**
  2758. * Returns a standard AsyncSocket maxed out error.
  2759. **/
  2760. - (NSError *)readMaxedOutError
  2761. {
  2762. NSString *errMsg = NSLocalizedStringWithDefaultValue(@"GCDAsyncSocketReadMaxedOutError",
  2763. @"GCDAsyncSocket", [NSBundle mainBundle],
  2764. @"Read operation reached set maximum length", nil);
  2765. NSDictionary *info = @{NSLocalizedDescriptionKey : errMsg};
  2766. return [NSError errorWithDomain:GCDAsyncSocketErrorDomain code:GCDAsyncSocketReadMaxedOutError userInfo:info];
  2767. }
  2768. /**
  2769. * Returns a standard AsyncSocket write timeout error.
  2770. **/
  2771. - (NSError *)readTimeoutError
  2772. {
  2773. NSString *errMsg = NSLocalizedStringWithDefaultValue(@"GCDAsyncSocketReadTimeoutError",
  2774. @"GCDAsyncSocket", [NSBundle mainBundle],
  2775. @"Read operation timed out", nil);
  2776. NSDictionary *userInfo = @{NSLocalizedDescriptionKey : errMsg};
  2777. return [NSError errorWithDomain:GCDAsyncSocketErrorDomain code:GCDAsyncSocketReadTimeoutError userInfo:userInfo];
  2778. }
  2779. /**
  2780. * Returns a standard AsyncSocket write timeout error.
  2781. **/
  2782. - (NSError *)writeTimeoutError
  2783. {
  2784. NSString *errMsg = NSLocalizedStringWithDefaultValue(@"GCDAsyncSocketWriteTimeoutError",
  2785. @"GCDAsyncSocket", [NSBundle mainBundle],
  2786. @"Write operation timed out", nil);
  2787. NSDictionary *userInfo = @{NSLocalizedDescriptionKey : errMsg};
  2788. return [NSError errorWithDomain:GCDAsyncSocketErrorDomain code:GCDAsyncSocketWriteTimeoutError userInfo:userInfo];
  2789. }
  2790. - (NSError *)connectionClosedError
  2791. {
  2792. NSString *errMsg = NSLocalizedStringWithDefaultValue(@"GCDAsyncSocketClosedError",
  2793. @"GCDAsyncSocket", [NSBundle mainBundle],
  2794. @"Socket closed by remote peer", nil);
  2795. NSDictionary *userInfo = @{NSLocalizedDescriptionKey : errMsg};
  2796. return [NSError errorWithDomain:GCDAsyncSocketErrorDomain code:GCDAsyncSocketClosedError userInfo:userInfo];
  2797. }
  2798. - (NSError *)otherError:(NSString *)errMsg
  2799. {
  2800. NSDictionary *userInfo = @{NSLocalizedDescriptionKey : errMsg};
  2801. return [NSError errorWithDomain:GCDAsyncSocketErrorDomain code:GCDAsyncSocketOtherError userInfo:userInfo];
  2802. }
  2803. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2804. #pragma mark Diagnostics
  2805. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2806. - (BOOL)isDisconnected
  2807. {
  2808. __block BOOL result = NO;
  2809. dispatch_block_t block = ^{
  2810. result = (self->flags & kSocketStarted) ? NO : YES;
  2811. };
  2812. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  2813. block();
  2814. else
  2815. dispatch_sync(socketQueue, block);
  2816. return result;
  2817. }
  2818. - (BOOL)isConnected
  2819. {
  2820. __block BOOL result = NO;
  2821. dispatch_block_t block = ^{
  2822. result = (self->flags & kConnected) ? YES : NO;
  2823. };
  2824. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  2825. block();
  2826. else
  2827. dispatch_sync(socketQueue, block);
  2828. return result;
  2829. }
  2830. - (NSString *)connectedHost
  2831. {
  2832. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  2833. {
  2834. if (socket4FD != SOCKET_NULL)
  2835. return [self connectedHostFromSocket4:socket4FD];
  2836. if (socket6FD != SOCKET_NULL)
  2837. return [self connectedHostFromSocket6:socket6FD];
  2838. return nil;
  2839. }
  2840. else
  2841. {
  2842. __block NSString *result = nil;
  2843. dispatch_sync(socketQueue, ^{ @autoreleasepool {
  2844. if (self->socket4FD != SOCKET_NULL)
  2845. result = [self connectedHostFromSocket4:self->socket4FD];
  2846. else if (self->socket6FD != SOCKET_NULL)
  2847. result = [self connectedHostFromSocket6:self->socket6FD];
  2848. }});
  2849. return result;
  2850. }
  2851. }
  2852. - (uint16_t)connectedPort
  2853. {
  2854. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  2855. {
  2856. if (socket4FD != SOCKET_NULL)
  2857. return [self connectedPortFromSocket4:socket4FD];
  2858. if (socket6FD != SOCKET_NULL)
  2859. return [self connectedPortFromSocket6:socket6FD];
  2860. return 0;
  2861. }
  2862. else
  2863. {
  2864. __block uint16_t result = 0;
  2865. dispatch_sync(socketQueue, ^{
  2866. // No need for autorelease pool
  2867. if (self->socket4FD != SOCKET_NULL)
  2868. result = [self connectedPortFromSocket4:self->socket4FD];
  2869. else if (self->socket6FD != SOCKET_NULL)
  2870. result = [self connectedPortFromSocket6:self->socket6FD];
  2871. });
  2872. return result;
  2873. }
  2874. }
  2875. - (NSURL *)connectedUrl
  2876. {
  2877. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  2878. {
  2879. if (socketUN != SOCKET_NULL)
  2880. return [self connectedUrlFromSocketUN:socketUN];
  2881. return nil;
  2882. }
  2883. else
  2884. {
  2885. __block NSURL *result = nil;
  2886. dispatch_sync(socketQueue, ^{ @autoreleasepool {
  2887. if (self->socketUN != SOCKET_NULL)
  2888. result = [self connectedUrlFromSocketUN:self->socketUN];
  2889. }});
  2890. return result;
  2891. }
  2892. }
  2893. - (NSString *)localHost
  2894. {
  2895. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  2896. {
  2897. if (socket4FD != SOCKET_NULL)
  2898. return [self localHostFromSocket4:socket4FD];
  2899. if (socket6FD != SOCKET_NULL)
  2900. return [self localHostFromSocket6:socket6FD];
  2901. return nil;
  2902. }
  2903. else
  2904. {
  2905. __block NSString *result = nil;
  2906. dispatch_sync(socketQueue, ^{ @autoreleasepool {
  2907. if (self->socket4FD != SOCKET_NULL)
  2908. result = [self localHostFromSocket4:self->socket4FD];
  2909. else if (self->socket6FD != SOCKET_NULL)
  2910. result = [self localHostFromSocket6:self->socket6FD];
  2911. }});
  2912. return result;
  2913. }
  2914. }
  2915. - (uint16_t)localPort
  2916. {
  2917. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  2918. {
  2919. if (socket4FD != SOCKET_NULL)
  2920. return [self localPortFromSocket4:socket4FD];
  2921. if (socket6FD != SOCKET_NULL)
  2922. return [self localPortFromSocket6:socket6FD];
  2923. return 0;
  2924. }
  2925. else
  2926. {
  2927. __block uint16_t result = 0;
  2928. dispatch_sync(socketQueue, ^{
  2929. // No need for autorelease pool
  2930. if (self->socket4FD != SOCKET_NULL)
  2931. result = [self localPortFromSocket4:self->socket4FD];
  2932. else if (self->socket6FD != SOCKET_NULL)
  2933. result = [self localPortFromSocket6:self->socket6FD];
  2934. });
  2935. return result;
  2936. }
  2937. }
  2938. - (NSString *)connectedHost4
  2939. {
  2940. if (socket4FD != SOCKET_NULL)
  2941. return [self connectedHostFromSocket4:socket4FD];
  2942. return nil;
  2943. }
  2944. - (NSString *)connectedHost6
  2945. {
  2946. if (socket6FD != SOCKET_NULL)
  2947. return [self connectedHostFromSocket6:socket6FD];
  2948. return nil;
  2949. }
  2950. - (uint16_t)connectedPort4
  2951. {
  2952. if (socket4FD != SOCKET_NULL)
  2953. return [self connectedPortFromSocket4:socket4FD];
  2954. return 0;
  2955. }
  2956. - (uint16_t)connectedPort6
  2957. {
  2958. if (socket6FD != SOCKET_NULL)
  2959. return [self connectedPortFromSocket6:socket6FD];
  2960. return 0;
  2961. }
  2962. - (NSString *)localHost4
  2963. {
  2964. if (socket4FD != SOCKET_NULL)
  2965. return [self localHostFromSocket4:socket4FD];
  2966. return nil;
  2967. }
  2968. - (NSString *)localHost6
  2969. {
  2970. if (socket6FD != SOCKET_NULL)
  2971. return [self localHostFromSocket6:socket6FD];
  2972. return nil;
  2973. }
  2974. - (uint16_t)localPort4
  2975. {
  2976. if (socket4FD != SOCKET_NULL)
  2977. return [self localPortFromSocket4:socket4FD];
  2978. return 0;
  2979. }
  2980. - (uint16_t)localPort6
  2981. {
  2982. if (socket6FD != SOCKET_NULL)
  2983. return [self localPortFromSocket6:socket6FD];
  2984. return 0;
  2985. }
  2986. - (NSString *)connectedHostFromSocket4:(int)socketFD
  2987. {
  2988. struct sockaddr_in sockaddr4;
  2989. socklen_t sockaddr4len = sizeof(sockaddr4);
  2990. if (getpeername(socketFD, (struct sockaddr *)&sockaddr4, &sockaddr4len) < 0)
  2991. {
  2992. return nil;
  2993. }
  2994. return [[self class] hostFromSockaddr4:&sockaddr4];
  2995. }
  2996. - (NSString *)connectedHostFromSocket6:(int)socketFD
  2997. {
  2998. struct sockaddr_in6 sockaddr6;
  2999. socklen_t sockaddr6len = sizeof(sockaddr6);
  3000. if (getpeername(socketFD, (struct sockaddr *)&sockaddr6, &sockaddr6len) < 0)
  3001. {
  3002. return nil;
  3003. }
  3004. return [[self class] hostFromSockaddr6:&sockaddr6];
  3005. }
  3006. - (uint16_t)connectedPortFromSocket4:(int)socketFD
  3007. {
  3008. struct sockaddr_in sockaddr4;
  3009. socklen_t sockaddr4len = sizeof(sockaddr4);
  3010. if (getpeername(socketFD, (struct sockaddr *)&sockaddr4, &sockaddr4len) < 0)
  3011. {
  3012. return 0;
  3013. }
  3014. return [[self class] portFromSockaddr4:&sockaddr4];
  3015. }
  3016. - (uint16_t)connectedPortFromSocket6:(int)socketFD
  3017. {
  3018. struct sockaddr_in6 sockaddr6;
  3019. socklen_t sockaddr6len = sizeof(sockaddr6);
  3020. if (getpeername(socketFD, (struct sockaddr *)&sockaddr6, &sockaddr6len) < 0)
  3021. {
  3022. return 0;
  3023. }
  3024. return [[self class] portFromSockaddr6:&sockaddr6];
  3025. }
  3026. - (NSURL *)connectedUrlFromSocketUN:(int)socketFD
  3027. {
  3028. struct sockaddr_un sockaddr;
  3029. socklen_t sockaddrlen = sizeof(sockaddr);
  3030. if (getpeername(socketFD, (struct sockaddr *)&sockaddr, &sockaddrlen) < 0)
  3031. {
  3032. return 0;
  3033. }
  3034. return [[self class] urlFromSockaddrUN:&sockaddr];
  3035. }
  3036. - (NSString *)localHostFromSocket4:(int)socketFD
  3037. {
  3038. struct sockaddr_in sockaddr4;
  3039. socklen_t sockaddr4len = sizeof(sockaddr4);
  3040. if (getsockname(socketFD, (struct sockaddr *)&sockaddr4, &sockaddr4len) < 0)
  3041. {
  3042. return nil;
  3043. }
  3044. return [[self class] hostFromSockaddr4:&sockaddr4];
  3045. }
  3046. - (NSString *)localHostFromSocket6:(int)socketFD
  3047. {
  3048. struct sockaddr_in6 sockaddr6;
  3049. socklen_t sockaddr6len = sizeof(sockaddr6);
  3050. if (getsockname(socketFD, (struct sockaddr *)&sockaddr6, &sockaddr6len) < 0)
  3051. {
  3052. return nil;
  3053. }
  3054. return [[self class] hostFromSockaddr6:&sockaddr6];
  3055. }
  3056. - (uint16_t)localPortFromSocket4:(int)socketFD
  3057. {
  3058. struct sockaddr_in sockaddr4;
  3059. socklen_t sockaddr4len = sizeof(sockaddr4);
  3060. if (getsockname(socketFD, (struct sockaddr *)&sockaddr4, &sockaddr4len) < 0)
  3061. {
  3062. return 0;
  3063. }
  3064. return [[self class] portFromSockaddr4:&sockaddr4];
  3065. }
  3066. - (uint16_t)localPortFromSocket6:(int)socketFD
  3067. {
  3068. struct sockaddr_in6 sockaddr6;
  3069. socklen_t sockaddr6len = sizeof(sockaddr6);
  3070. if (getsockname(socketFD, (struct sockaddr *)&sockaddr6, &sockaddr6len) < 0)
  3071. {
  3072. return 0;
  3073. }
  3074. return [[self class] portFromSockaddr6:&sockaddr6];
  3075. }
  3076. - (NSData *)connectedAddress
  3077. {
  3078. __block NSData *result = nil;
  3079. dispatch_block_t block = ^{
  3080. if (self->socket4FD != SOCKET_NULL)
  3081. {
  3082. struct sockaddr_in sockaddr4;
  3083. socklen_t sockaddr4len = sizeof(sockaddr4);
  3084. if (getpeername(self->socket4FD, (struct sockaddr *)&sockaddr4, &sockaddr4len) == 0)
  3085. {
  3086. result = [[NSData alloc] initWithBytes:&sockaddr4 length:sockaddr4len];
  3087. }
  3088. }
  3089. if (self->socket6FD != SOCKET_NULL)
  3090. {
  3091. struct sockaddr_in6 sockaddr6;
  3092. socklen_t sockaddr6len = sizeof(sockaddr6);
  3093. if (getpeername(self->socket6FD, (struct sockaddr *)&sockaddr6, &sockaddr6len) == 0)
  3094. {
  3095. result = [[NSData alloc] initWithBytes:&sockaddr6 length:sockaddr6len];
  3096. }
  3097. }
  3098. };
  3099. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  3100. block();
  3101. else
  3102. dispatch_sync(socketQueue, block);
  3103. return result;
  3104. }
  3105. - (NSData *)localAddress
  3106. {
  3107. __block NSData *result = nil;
  3108. dispatch_block_t block = ^{
  3109. if (self->socket4FD != SOCKET_NULL)
  3110. {
  3111. struct sockaddr_in sockaddr4;
  3112. socklen_t sockaddr4len = sizeof(sockaddr4);
  3113. if (getsockname(self->socket4FD, (struct sockaddr *)&sockaddr4, &sockaddr4len) == 0)
  3114. {
  3115. result = [[NSData alloc] initWithBytes:&sockaddr4 length:sockaddr4len];
  3116. }
  3117. }
  3118. if (self->socket6FD != SOCKET_NULL)
  3119. {
  3120. struct sockaddr_in6 sockaddr6;
  3121. socklen_t sockaddr6len = sizeof(sockaddr6);
  3122. if (getsockname(self->socket6FD, (struct sockaddr *)&sockaddr6, &sockaddr6len) == 0)
  3123. {
  3124. result = [[NSData alloc] initWithBytes:&sockaddr6 length:sockaddr6len];
  3125. }
  3126. }
  3127. };
  3128. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  3129. block();
  3130. else
  3131. dispatch_sync(socketQueue, block);
  3132. return result;
  3133. }
  3134. - (BOOL)isIPv4
  3135. {
  3136. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  3137. {
  3138. return (socket4FD != SOCKET_NULL);
  3139. }
  3140. else
  3141. {
  3142. __block BOOL result = NO;
  3143. dispatch_sync(socketQueue, ^{
  3144. result = (self->socket4FD != SOCKET_NULL);
  3145. });
  3146. return result;
  3147. }
  3148. }
  3149. - (BOOL)isIPv6
  3150. {
  3151. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  3152. {
  3153. return (socket6FD != SOCKET_NULL);
  3154. }
  3155. else
  3156. {
  3157. __block BOOL result = NO;
  3158. dispatch_sync(socketQueue, ^{
  3159. result = (self->socket6FD != SOCKET_NULL);
  3160. });
  3161. return result;
  3162. }
  3163. }
  3164. - (BOOL)isSecure
  3165. {
  3166. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  3167. {
  3168. return (flags & kSocketSecure) ? YES : NO;
  3169. }
  3170. else
  3171. {
  3172. __block BOOL result;
  3173. dispatch_sync(socketQueue, ^{
  3174. result = (self->flags & kSocketSecure) ? YES : NO;
  3175. });
  3176. return result;
  3177. }
  3178. }
  3179. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  3180. #pragma mark Utilities
  3181. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  3182. /**
  3183. * Finds the address of an interface description.
  3184. * An inteface description may be an interface name (en0, en1, lo0) or corresponding IP (192.168.4.34).
  3185. *
  3186. * The interface description may optionally contain a port number at the end, separated by a colon.
  3187. * If a non-zero port parameter is provided, any port number in the interface description is ignored.
  3188. *
  3189. * The returned value is a 'struct sockaddr' wrapped in an NSMutableData object.
  3190. **/
  3191. - (void)getInterfaceAddress4:(NSMutableData **)interfaceAddr4Ptr
  3192. address6:(NSMutableData **)interfaceAddr6Ptr
  3193. fromDescription:(NSString *)interfaceDescription
  3194. port:(uint16_t)port
  3195. {
  3196. NSMutableData *addr4 = nil;
  3197. NSMutableData *addr6 = nil;
  3198. NSString *interface = nil;
  3199. NSArray *components = [interfaceDescription componentsSeparatedByString:@":"];
  3200. if ([components count] > 0)
  3201. {
  3202. NSString *temp = [components objectAtIndex:0];
  3203. if ([temp length] > 0)
  3204. {
  3205. interface = temp;
  3206. }
  3207. }
  3208. if ([components count] > 1 && port == 0)
  3209. {
  3210. NSString *temp = [components objectAtIndex:1];
  3211. long portL = strtol([temp UTF8String], NULL, 10);
  3212. if (portL > 0 && portL <= UINT16_MAX)
  3213. {
  3214. port = (uint16_t)portL;
  3215. }
  3216. }
  3217. if (interface == nil)
  3218. {
  3219. // ANY address
  3220. struct sockaddr_in sockaddr4;
  3221. memset(&sockaddr4, 0, sizeof(sockaddr4));
  3222. sockaddr4.sin_len = sizeof(sockaddr4);
  3223. sockaddr4.sin_family = AF_INET;
  3224. sockaddr4.sin_port = htons(port);
  3225. sockaddr4.sin_addr.s_addr = htonl(INADDR_ANY);
  3226. struct sockaddr_in6 sockaddr6;
  3227. memset(&sockaddr6, 0, sizeof(sockaddr6));
  3228. sockaddr6.sin6_len = sizeof(sockaddr6);
  3229. sockaddr6.sin6_family = AF_INET6;
  3230. sockaddr6.sin6_port = htons(port);
  3231. sockaddr6.sin6_addr = in6addr_any;
  3232. addr4 = [NSMutableData dataWithBytes:&sockaddr4 length:sizeof(sockaddr4)];
  3233. addr6 = [NSMutableData dataWithBytes:&sockaddr6 length:sizeof(sockaddr6)];
  3234. }
  3235. else if ([interface isEqualToString:@"localhost"] || [interface isEqualToString:@"loopback"])
  3236. {
  3237. // LOOPBACK address
  3238. struct sockaddr_in sockaddr4;
  3239. memset(&sockaddr4, 0, sizeof(sockaddr4));
  3240. sockaddr4.sin_len = sizeof(sockaddr4);
  3241. sockaddr4.sin_family = AF_INET;
  3242. sockaddr4.sin_port = htons(port);
  3243. sockaddr4.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3244. struct sockaddr_in6 sockaddr6;
  3245. memset(&sockaddr6, 0, sizeof(sockaddr6));
  3246. sockaddr6.sin6_len = sizeof(sockaddr6);
  3247. sockaddr6.sin6_family = AF_INET6;
  3248. sockaddr6.sin6_port = htons(port);
  3249. sockaddr6.sin6_addr = in6addr_loopback;
  3250. addr4 = [NSMutableData dataWithBytes:&sockaddr4 length:sizeof(sockaddr4)];
  3251. addr6 = [NSMutableData dataWithBytes:&sockaddr6 length:sizeof(sockaddr6)];
  3252. }
  3253. else
  3254. {
  3255. const char *iface = [interface UTF8String];
  3256. struct ifaddrs *addrs;
  3257. const struct ifaddrs *cursor;
  3258. if ((getifaddrs(&addrs) == 0))
  3259. {
  3260. cursor = addrs;
  3261. while (cursor != NULL)
  3262. {
  3263. if ((addr4 == nil) && (cursor->ifa_addr->sa_family == AF_INET))
  3264. {
  3265. // IPv4
  3266. struct sockaddr_in nativeAddr4;
  3267. memcpy(&nativeAddr4, cursor->ifa_addr, sizeof(nativeAddr4));
  3268. if (strcmp(cursor->ifa_name, iface) == 0)
  3269. {
  3270. // Name match
  3271. nativeAddr4.sin_port = htons(port);
  3272. addr4 = [NSMutableData dataWithBytes:&nativeAddr4 length:sizeof(nativeAddr4)];
  3273. }
  3274. else
  3275. {
  3276. char ip[INET_ADDRSTRLEN];
  3277. const char *conversion = inet_ntop(AF_INET, &nativeAddr4.sin_addr, ip, sizeof(ip));
  3278. if ((conversion != NULL) && (strcmp(ip, iface) == 0))
  3279. {
  3280. // IP match
  3281. nativeAddr4.sin_port = htons(port);
  3282. addr4 = [NSMutableData dataWithBytes:&nativeAddr4 length:sizeof(nativeAddr4)];
  3283. }
  3284. }
  3285. }
  3286. else if ((addr6 == nil) && (cursor->ifa_addr->sa_family == AF_INET6))
  3287. {
  3288. // IPv6
  3289. struct sockaddr_in6 nativeAddr6;
  3290. memcpy(&nativeAddr6, cursor->ifa_addr, sizeof(nativeAddr6));
  3291. if (strcmp(cursor->ifa_name, iface) == 0)
  3292. {
  3293. // Name match
  3294. nativeAddr6.sin6_port = htons(port);
  3295. addr6 = [NSMutableData dataWithBytes:&nativeAddr6 length:sizeof(nativeAddr6)];
  3296. }
  3297. else
  3298. {
  3299. char ip[INET6_ADDRSTRLEN];
  3300. const char *conversion = inet_ntop(AF_INET6, &nativeAddr6.sin6_addr, ip, sizeof(ip));
  3301. if ((conversion != NULL) && (strcmp(ip, iface) == 0))
  3302. {
  3303. // IP match
  3304. nativeAddr6.sin6_port = htons(port);
  3305. addr6 = [NSMutableData dataWithBytes:&nativeAddr6 length:sizeof(nativeAddr6)];
  3306. }
  3307. }
  3308. }
  3309. cursor = cursor->ifa_next;
  3310. }
  3311. freeifaddrs(addrs);
  3312. }
  3313. }
  3314. if (interfaceAddr4Ptr) *interfaceAddr4Ptr = addr4;
  3315. if (interfaceAddr6Ptr) *interfaceAddr6Ptr = addr6;
  3316. }
  3317. - (NSData *)getInterfaceAddressFromUrl:(NSURL *)url
  3318. {
  3319. NSString *path = url.path;
  3320. if (path.length == 0) {
  3321. return nil;
  3322. }
  3323. struct sockaddr_un nativeAddr;
  3324. nativeAddr.sun_family = AF_UNIX;
  3325. strlcpy(nativeAddr.sun_path, path.fileSystemRepresentation, sizeof(nativeAddr.sun_path));
  3326. nativeAddr.sun_len = (unsigned char)SUN_LEN(&nativeAddr);
  3327. NSData *interface = [NSData dataWithBytes:&nativeAddr length:sizeof(struct sockaddr_un)];
  3328. return interface;
  3329. }
  3330. - (void)setupReadAndWriteSourcesForNewlyConnectedSocket:(int)socketFD
  3331. {
  3332. readSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, socketFD, 0, socketQueue);
  3333. writeSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_WRITE, socketFD, 0, socketQueue);
  3334. // Setup event handlers
  3335. __weak GCDAsyncSocket *weakSelf = self;
  3336. dispatch_source_set_event_handler(readSource, ^{ @autoreleasepool {
  3337. #pragma clang diagnostic push
  3338. #pragma clang diagnostic warning "-Wimplicit-retain-self"
  3339. __strong GCDAsyncSocket *strongSelf = weakSelf;
  3340. if (strongSelf == nil) return_from_block;
  3341. LogVerbose(@"readEventBlock");
  3342. strongSelf->socketFDBytesAvailable = dispatch_source_get_data(strongSelf->readSource);
  3343. LogVerbose(@"socketFDBytesAvailable: %lu", strongSelf->socketFDBytesAvailable);
  3344. if (strongSelf->socketFDBytesAvailable > 0)
  3345. [strongSelf doReadData];
  3346. else
  3347. [strongSelf doReadEOF];
  3348. #pragma clang diagnostic pop
  3349. }});
  3350. dispatch_source_set_event_handler(writeSource, ^{ @autoreleasepool {
  3351. #pragma clang diagnostic push
  3352. #pragma clang diagnostic warning "-Wimplicit-retain-self"
  3353. __strong GCDAsyncSocket *strongSelf = weakSelf;
  3354. if (strongSelf == nil) return_from_block;
  3355. LogVerbose(@"writeEventBlock");
  3356. strongSelf->flags |= kSocketCanAcceptBytes;
  3357. [strongSelf doWriteData];
  3358. #pragma clang diagnostic pop
  3359. }});
  3360. // Setup cancel handlers
  3361. __block int socketFDRefCount = 2;
  3362. #if !OS_OBJECT_USE_OBJC
  3363. dispatch_source_t theReadSource = readSource;
  3364. dispatch_source_t theWriteSource = writeSource;
  3365. #endif
  3366. dispatch_source_set_cancel_handler(readSource, ^{
  3367. #pragma clang diagnostic push
  3368. #pragma clang diagnostic warning "-Wimplicit-retain-self"
  3369. LogVerbose(@"readCancelBlock");
  3370. #if !OS_OBJECT_USE_OBJC
  3371. LogVerbose(@"dispatch_release(readSource)");
  3372. dispatch_release(theReadSource);
  3373. #endif
  3374. if (--socketFDRefCount == 0)
  3375. {
  3376. LogVerbose(@"close(socketFD)");
  3377. close(socketFD);
  3378. }
  3379. #pragma clang diagnostic pop
  3380. });
  3381. dispatch_source_set_cancel_handler(writeSource, ^{
  3382. #pragma clang diagnostic push
  3383. #pragma clang diagnostic warning "-Wimplicit-retain-self"
  3384. LogVerbose(@"writeCancelBlock");
  3385. #if !OS_OBJECT_USE_OBJC
  3386. LogVerbose(@"dispatch_release(writeSource)");
  3387. dispatch_release(theWriteSource);
  3388. #endif
  3389. if (--socketFDRefCount == 0)
  3390. {
  3391. LogVerbose(@"close(socketFD)");
  3392. close(socketFD);
  3393. }
  3394. #pragma clang diagnostic pop
  3395. });
  3396. // We will not be able to read until data arrives.
  3397. // But we should be able to write immediately.
  3398. socketFDBytesAvailable = 0;
  3399. flags &= ~kReadSourceSuspended;
  3400. LogVerbose(@"dispatch_resume(readSource)");
  3401. dispatch_resume(readSource);
  3402. flags |= kSocketCanAcceptBytes;
  3403. flags |= kWriteSourceSuspended;
  3404. }
  3405. - (BOOL)usingCFStreamForTLS
  3406. {
  3407. #if TARGET_OS_IPHONE
  3408. if ((flags & kSocketSecure) && (flags & kUsingCFStreamForTLS))
  3409. {
  3410. // The startTLS method was given the GCDAsyncSocketUseCFStreamForTLS flag.
  3411. return YES;
  3412. }
  3413. #endif
  3414. return NO;
  3415. }
  3416. - (BOOL)usingSecureTransportForTLS
  3417. {
  3418. // Invoking this method is equivalent to ![self usingCFStreamForTLS] (just more readable)
  3419. #if TARGET_OS_IPHONE
  3420. if ((flags & kSocketSecure) && (flags & kUsingCFStreamForTLS))
  3421. {
  3422. // The startTLS method was given the GCDAsyncSocketUseCFStreamForTLS flag.
  3423. return NO;
  3424. }
  3425. #endif
  3426. return YES;
  3427. }
  3428. - (void)suspendReadSource
  3429. {
  3430. if (!(flags & kReadSourceSuspended))
  3431. {
  3432. LogVerbose(@"dispatch_suspend(readSource)");
  3433. dispatch_suspend(readSource);
  3434. flags |= kReadSourceSuspended;
  3435. }
  3436. }
  3437. - (void)resumeReadSource
  3438. {
  3439. if (flags & kReadSourceSuspended)
  3440. {
  3441. LogVerbose(@"dispatch_resume(readSource)");
  3442. dispatch_resume(readSource);
  3443. flags &= ~kReadSourceSuspended;
  3444. }
  3445. }
  3446. - (void)suspendWriteSource
  3447. {
  3448. if (!(flags & kWriteSourceSuspended))
  3449. {
  3450. LogVerbose(@"dispatch_suspend(writeSource)");
  3451. dispatch_suspend(writeSource);
  3452. flags |= kWriteSourceSuspended;
  3453. }
  3454. }
  3455. - (void)resumeWriteSource
  3456. {
  3457. if (flags & kWriteSourceSuspended)
  3458. {
  3459. LogVerbose(@"dispatch_resume(writeSource)");
  3460. dispatch_resume(writeSource);
  3461. flags &= ~kWriteSourceSuspended;
  3462. }
  3463. }
  3464. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  3465. #pragma mark Reading
  3466. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  3467. - (void)readDataWithTimeout:(NSTimeInterval)timeout tag:(long)tag
  3468. {
  3469. [self readDataWithTimeout:timeout buffer:nil bufferOffset:0 maxLength:0 tag:tag];
  3470. }
  3471. - (void)readDataWithTimeout:(NSTimeInterval)timeout
  3472. buffer:(NSMutableData *)buffer
  3473. bufferOffset:(NSUInteger)offset
  3474. tag:(long)tag
  3475. {
  3476. [self readDataWithTimeout:timeout buffer:buffer bufferOffset:offset maxLength:0 tag:tag];
  3477. }
  3478. - (void)readDataWithTimeout:(NSTimeInterval)timeout
  3479. buffer:(NSMutableData *)buffer
  3480. bufferOffset:(NSUInteger)offset
  3481. maxLength:(NSUInteger)length
  3482. tag:(long)tag
  3483. {
  3484. if (offset > [buffer length]) {
  3485. LogWarn(@"Cannot read: offset > [buffer length]");
  3486. return;
  3487. }
  3488. GCDAsyncReadPacket *packet = [[GCDAsyncReadPacket alloc] initWithData:buffer
  3489. startOffset:offset
  3490. maxLength:length
  3491. timeout:timeout
  3492. readLength:0
  3493. terminator:nil
  3494. tag:tag];
  3495. dispatch_async(socketQueue, ^{ @autoreleasepool {
  3496. LogTrace();
  3497. if ((self->flags & kSocketStarted) && !(self->flags & kForbidReadsWrites))
  3498. {
  3499. [self->readQueue addObject:packet];
  3500. [self maybeDequeueRead];
  3501. }
  3502. }});
  3503. // Do not rely on the block being run in order to release the packet,
  3504. // as the queue might get released without the block completing.
  3505. }
  3506. - (void)readDataToLength:(NSUInteger)length withTimeout:(NSTimeInterval)timeout tag:(long)tag
  3507. {
  3508. [self readDataToLength:length withTimeout:timeout buffer:nil bufferOffset:0 tag:tag];
  3509. }
  3510. - (void)readDataToLength:(NSUInteger)length
  3511. withTimeout:(NSTimeInterval)timeout
  3512. buffer:(NSMutableData *)buffer
  3513. bufferOffset:(NSUInteger)offset
  3514. tag:(long)tag
  3515. {
  3516. if (length == 0) {
  3517. LogWarn(@"Cannot read: length == 0");
  3518. return;
  3519. }
  3520. if (offset > [buffer length]) {
  3521. LogWarn(@"Cannot read: offset > [buffer length]");
  3522. return;
  3523. }
  3524. GCDAsyncReadPacket *packet = [[GCDAsyncReadPacket alloc] initWithData:buffer
  3525. startOffset:offset
  3526. maxLength:0
  3527. timeout:timeout
  3528. readLength:length
  3529. terminator:nil
  3530. tag:tag];
  3531. dispatch_async(socketQueue, ^{ @autoreleasepool {
  3532. LogTrace();
  3533. if ((self->flags & kSocketStarted) && !(self->flags & kForbidReadsWrites))
  3534. {
  3535. [self->readQueue addObject:packet];
  3536. [self maybeDequeueRead];
  3537. }
  3538. }});
  3539. // Do not rely on the block being run in order to release the packet,
  3540. // as the queue might get released without the block completing.
  3541. }
  3542. - (void)readDataToData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag
  3543. {
  3544. [self readDataToData:data withTimeout:timeout buffer:nil bufferOffset:0 maxLength:0 tag:tag];
  3545. }
  3546. - (void)readDataToData:(NSData *)data
  3547. withTimeout:(NSTimeInterval)timeout
  3548. buffer:(NSMutableData *)buffer
  3549. bufferOffset:(NSUInteger)offset
  3550. tag:(long)tag
  3551. {
  3552. [self readDataToData:data withTimeout:timeout buffer:buffer bufferOffset:offset maxLength:0 tag:tag];
  3553. }
  3554. - (void)readDataToData:(NSData *)data withTimeout:(NSTimeInterval)timeout maxLength:(NSUInteger)length tag:(long)tag
  3555. {
  3556. [self readDataToData:data withTimeout:timeout buffer:nil bufferOffset:0 maxLength:length tag:tag];
  3557. }
  3558. - (void)readDataToData:(NSData *)data
  3559. withTimeout:(NSTimeInterval)timeout
  3560. buffer:(NSMutableData *)buffer
  3561. bufferOffset:(NSUInteger)offset
  3562. maxLength:(NSUInteger)maxLength
  3563. tag:(long)tag
  3564. {
  3565. if ([data length] == 0) {
  3566. LogWarn(@"Cannot read: [data length] == 0");
  3567. return;
  3568. }
  3569. if (offset > [buffer length]) {
  3570. LogWarn(@"Cannot read: offset > [buffer length]");
  3571. return;
  3572. }
  3573. if (maxLength > 0 && maxLength < [data length]) {
  3574. LogWarn(@"Cannot read: maxLength > 0 && maxLength < [data length]");
  3575. return;
  3576. }
  3577. GCDAsyncReadPacket *packet = [[GCDAsyncReadPacket alloc] initWithData:buffer
  3578. startOffset:offset
  3579. maxLength:maxLength
  3580. timeout:timeout
  3581. readLength:0
  3582. terminator:data
  3583. tag:tag];
  3584. dispatch_async(socketQueue, ^{ @autoreleasepool {
  3585. LogTrace();
  3586. if ((self->flags & kSocketStarted) && !(self->flags & kForbidReadsWrites))
  3587. {
  3588. [self->readQueue addObject:packet];
  3589. [self maybeDequeueRead];
  3590. }
  3591. }});
  3592. // Do not rely on the block being run in order to release the packet,
  3593. // as the queue might get released without the block completing.
  3594. }
  3595. - (float)progressOfReadReturningTag:(long *)tagPtr bytesDone:(NSUInteger *)donePtr total:(NSUInteger *)totalPtr
  3596. {
  3597. __block float result = 0.0F;
  3598. dispatch_block_t block = ^{
  3599. if (!self->currentRead || ![self->currentRead isKindOfClass:[GCDAsyncReadPacket class]])
  3600. {
  3601. // We're not reading anything right now.
  3602. if (tagPtr != NULL) *tagPtr = 0;
  3603. if (donePtr != NULL) *donePtr = 0;
  3604. if (totalPtr != NULL) *totalPtr = 0;
  3605. result = NAN;
  3606. }
  3607. else
  3608. {
  3609. // It's only possible to know the progress of our read if we're reading to a certain length.
  3610. // If we're reading to data, we of course have no idea when the data will arrive.
  3611. // If we're reading to timeout, then we have no idea when the next chunk of data will arrive.
  3612. NSUInteger done = self->currentRead->bytesDone;
  3613. NSUInteger total = self->currentRead->readLength;
  3614. if (tagPtr != NULL) *tagPtr = self->currentRead->tag;
  3615. if (donePtr != NULL) *donePtr = done;
  3616. if (totalPtr != NULL) *totalPtr = total;
  3617. if (total > 0)
  3618. result = (float)done / (float)total;
  3619. else
  3620. result = 1.0F;
  3621. }
  3622. };
  3623. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  3624. block();
  3625. else
  3626. dispatch_sync(socketQueue, block);
  3627. return result;
  3628. }
  3629. /**
  3630. * This method starts a new read, if needed.
  3631. *
  3632. * It is called when:
  3633. * - a user requests a read
  3634. * - after a read request has finished (to handle the next request)
  3635. * - immediately after the socket opens to handle any pending requests
  3636. *
  3637. * This method also handles auto-disconnect post read/write completion.
  3638. **/
  3639. - (void)maybeDequeueRead
  3640. {
  3641. LogTrace();
  3642. NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue");
  3643. // If we're not currently processing a read AND we have an available read stream
  3644. if ((currentRead == nil) && (flags & kConnected))
  3645. {
  3646. if ([readQueue count] > 0)
  3647. {
  3648. // Dequeue the next object in the write queue
  3649. currentRead = [readQueue objectAtIndex:0];
  3650. [readQueue removeObjectAtIndex:0];
  3651. if ([currentRead isKindOfClass:[GCDAsyncSpecialPacket class]])
  3652. {
  3653. LogVerbose(@"Dequeued GCDAsyncSpecialPacket");
  3654. // Attempt to start TLS
  3655. flags |= kStartingReadTLS;
  3656. // This method won't do anything unless both kStartingReadTLS and kStartingWriteTLS are set
  3657. [self maybeStartTLS];
  3658. }
  3659. else
  3660. {
  3661. LogVerbose(@"Dequeued GCDAsyncReadPacket");
  3662. // Setup read timer (if needed)
  3663. [self setupReadTimerWithTimeout:currentRead->timeout];
  3664. // Immediately read, if possible
  3665. [self doReadData];
  3666. }
  3667. }
  3668. else if (flags & kDisconnectAfterReads)
  3669. {
  3670. if (flags & kDisconnectAfterWrites)
  3671. {
  3672. if (([writeQueue count] == 0) && (currentWrite == nil))
  3673. {
  3674. [self closeWithError:nil];
  3675. }
  3676. }
  3677. else
  3678. {
  3679. [self closeWithError:nil];
  3680. }
  3681. }
  3682. else if (flags & kSocketSecure)
  3683. {
  3684. [self flushSSLBuffers];
  3685. // Edge case:
  3686. //
  3687. // We just drained all data from the ssl buffers,
  3688. // and all known data from the socket (socketFDBytesAvailable).
  3689. //
  3690. // If we didn't get any data from this process,
  3691. // then we may have reached the end of the TCP stream.
  3692. //
  3693. // Be sure callbacks are enabled so we're notified about a disconnection.
  3694. if ([preBuffer availableBytes] == 0)
  3695. {
  3696. if ([self usingCFStreamForTLS]) {
  3697. // Callbacks never disabled
  3698. }
  3699. else {
  3700. [self resumeReadSource];
  3701. }
  3702. }
  3703. }
  3704. }
  3705. }
  3706. - (void)flushSSLBuffers
  3707. {
  3708. LogTrace();
  3709. NSAssert((flags & kSocketSecure), @"Cannot flush ssl buffers on non-secure socket");
  3710. if ([preBuffer availableBytes] > 0)
  3711. {
  3712. // Only flush the ssl buffers if the prebuffer is empty.
  3713. // This is to avoid growing the prebuffer inifinitely large.
  3714. return;
  3715. }
  3716. #if TARGET_OS_IPHONE
  3717. if ([self usingCFStreamForTLS])
  3718. {
  3719. if ((flags & kSecureSocketHasBytesAvailable) && CFReadStreamHasBytesAvailable(readStream))
  3720. {
  3721. LogVerbose(@"%@ - Flushing ssl buffers into prebuffer...", THIS_METHOD);
  3722. CFIndex defaultBytesToRead = (1024 * 4);
  3723. [preBuffer ensureCapacityForWrite:defaultBytesToRead];
  3724. uint8_t *buffer = [preBuffer writeBuffer];
  3725. CFIndex result = CFReadStreamRead(readStream, buffer, defaultBytesToRead);
  3726. LogVerbose(@"%@ - CFReadStreamRead(): result = %i", THIS_METHOD, (int)result);
  3727. if (result > 0)
  3728. {
  3729. [preBuffer didWrite:result];
  3730. }
  3731. flags &= ~kSecureSocketHasBytesAvailable;
  3732. }
  3733. return;
  3734. }
  3735. #endif
  3736. __block NSUInteger estimatedBytesAvailable = 0;
  3737. dispatch_block_t updateEstimatedBytesAvailable = ^{
  3738. // Figure out if there is any data available to be read
  3739. //
  3740. // socketFDBytesAvailable <- Number of encrypted bytes we haven't read from the bsd socket
  3741. // [sslPreBuffer availableBytes] <- Number of encrypted bytes we've buffered from bsd socket
  3742. // sslInternalBufSize <- Number of decrypted bytes SecureTransport has buffered
  3743. //
  3744. // We call the variable "estimated" because we don't know how many decrypted bytes we'll get
  3745. // from the encrypted bytes in the sslPreBuffer.
  3746. // However, we do know this is an upper bound on the estimation.
  3747. estimatedBytesAvailable = self->socketFDBytesAvailable + [self->sslPreBuffer availableBytes];
  3748. size_t sslInternalBufSize = 0;
  3749. SSLGetBufferedReadSize(self->sslContext, &sslInternalBufSize);
  3750. estimatedBytesAvailable += sslInternalBufSize;
  3751. };
  3752. updateEstimatedBytesAvailable();
  3753. if (estimatedBytesAvailable > 0)
  3754. {
  3755. LogVerbose(@"%@ - Flushing ssl buffers into prebuffer...", THIS_METHOD);
  3756. BOOL done = NO;
  3757. do
  3758. {
  3759. LogVerbose(@"%@ - estimatedBytesAvailable = %lu", THIS_METHOD, (unsigned long)estimatedBytesAvailable);
  3760. // Make sure there's enough room in the prebuffer
  3761. [preBuffer ensureCapacityForWrite:estimatedBytesAvailable];
  3762. // Read data into prebuffer
  3763. uint8_t *buffer = [preBuffer writeBuffer];
  3764. size_t bytesRead = 0;
  3765. OSStatus result = SSLRead(sslContext, buffer, (size_t)estimatedBytesAvailable, &bytesRead);
  3766. LogVerbose(@"%@ - read from secure socket = %u", THIS_METHOD, (unsigned)bytesRead);
  3767. if (bytesRead > 0)
  3768. {
  3769. [preBuffer didWrite:bytesRead];
  3770. }
  3771. LogVerbose(@"%@ - prebuffer.length = %zu", THIS_METHOD, [preBuffer availableBytes]);
  3772. if (result != noErr)
  3773. {
  3774. done = YES;
  3775. }
  3776. else
  3777. {
  3778. updateEstimatedBytesAvailable();
  3779. }
  3780. } while (!done && estimatedBytesAvailable > 0);
  3781. }
  3782. }
  3783. - (void)doReadData
  3784. {
  3785. LogTrace();
  3786. // This method is called on the socketQueue.
  3787. // It might be called directly, or via the readSource when data is available to be read.
  3788. if ((currentRead == nil) || (flags & kReadsPaused))
  3789. {
  3790. LogVerbose(@"No currentRead or kReadsPaused");
  3791. // Unable to read at this time
  3792. if (flags & kSocketSecure)
  3793. {
  3794. // Here's the situation:
  3795. //
  3796. // We have an established secure connection.
  3797. // There may not be a currentRead, but there might be encrypted data sitting around for us.
  3798. // When the user does get around to issuing a read, that encrypted data will need to be decrypted.
  3799. //
  3800. // So why make the user wait?
  3801. // We might as well get a head start on decrypting some data now.
  3802. //
  3803. // The other reason we do this has to do with detecting a socket disconnection.
  3804. // The SSL/TLS protocol has it's own disconnection handshake.
  3805. // So when a secure socket is closed, a "goodbye" packet comes across the wire.
  3806. // We want to make sure we read the "goodbye" packet so we can properly detect the TCP disconnection.
  3807. [self flushSSLBuffers];
  3808. }
  3809. if ([self usingCFStreamForTLS])
  3810. {
  3811. // CFReadStream only fires once when there is available data.
  3812. // It won't fire again until we've invoked CFReadStreamRead.
  3813. }
  3814. else
  3815. {
  3816. // If the readSource is firing, we need to pause it
  3817. // or else it will continue to fire over and over again.
  3818. //
  3819. // If the readSource is not firing,
  3820. // we want it to continue monitoring the socket.
  3821. if (socketFDBytesAvailable > 0)
  3822. {
  3823. [self suspendReadSource];
  3824. }
  3825. }
  3826. return;
  3827. }
  3828. BOOL hasBytesAvailable = NO;
  3829. unsigned long estimatedBytesAvailable = 0;
  3830. if ([self usingCFStreamForTLS])
  3831. {
  3832. #if TARGET_OS_IPHONE
  3833. // Requested CFStream, rather than SecureTransport, for TLS (via GCDAsyncSocketUseCFStreamForTLS)
  3834. estimatedBytesAvailable = 0;
  3835. if ((flags & kSecureSocketHasBytesAvailable) && CFReadStreamHasBytesAvailable(readStream))
  3836. hasBytesAvailable = YES;
  3837. else
  3838. hasBytesAvailable = NO;
  3839. #endif
  3840. }
  3841. else
  3842. {
  3843. estimatedBytesAvailable = socketFDBytesAvailable;
  3844. if (flags & kSocketSecure)
  3845. {
  3846. // There are 2 buffers to be aware of here.
  3847. //
  3848. // We are using SecureTransport, a TLS/SSL security layer which sits atop TCP.
  3849. // We issue a read to the SecureTranport API, which in turn issues a read to our SSLReadFunction.
  3850. // Our SSLReadFunction then reads from the BSD socket and returns the encrypted data to SecureTransport.
  3851. // SecureTransport then decrypts the data, and finally returns the decrypted data back to us.
  3852. //
  3853. // The first buffer is one we create.
  3854. // SecureTransport often requests small amounts of data.
  3855. // This has to do with the encypted packets that are coming across the TCP stream.
  3856. // But it's non-optimal to do a bunch of small reads from the BSD socket.
  3857. // So our SSLReadFunction reads all available data from the socket (optimizing the sys call)
  3858. // and may store excess in the sslPreBuffer.
  3859. estimatedBytesAvailable += [sslPreBuffer availableBytes];
  3860. // The second buffer is within SecureTransport.
  3861. // As mentioned earlier, there are encrypted packets coming across the TCP stream.
  3862. // SecureTransport needs the entire packet to decrypt it.
  3863. // But if the entire packet produces X bytes of decrypted data,
  3864. // and we only asked SecureTransport for X/2 bytes of data,
  3865. // it must store the extra X/2 bytes of decrypted data for the next read.
  3866. //
  3867. // The SSLGetBufferedReadSize function will tell us the size of this internal buffer.
  3868. // From the documentation:
  3869. //
  3870. // "This function does not block or cause any low-level read operations to occur."
  3871. size_t sslInternalBufSize = 0;
  3872. SSLGetBufferedReadSize(sslContext, &sslInternalBufSize);
  3873. estimatedBytesAvailable += sslInternalBufSize;
  3874. }
  3875. hasBytesAvailable = (estimatedBytesAvailable > 0);
  3876. }
  3877. if ((hasBytesAvailable == NO) && ([preBuffer availableBytes] == 0))
  3878. {
  3879. LogVerbose(@"No data available to read...");
  3880. // No data available to read.
  3881. if (![self usingCFStreamForTLS])
  3882. {
  3883. // Need to wait for readSource to fire and notify us of
  3884. // available data in the socket's internal read buffer.
  3885. [self resumeReadSource];
  3886. }
  3887. return;
  3888. }
  3889. if (flags & kStartingReadTLS)
  3890. {
  3891. LogVerbose(@"Waiting for SSL/TLS handshake to complete");
  3892. // The readQueue is waiting for SSL/TLS handshake to complete.
  3893. if (flags & kStartingWriteTLS)
  3894. {
  3895. if ([self usingSecureTransportForTLS] && lastSSLHandshakeError == errSSLWouldBlock)
  3896. {
  3897. // We are in the process of a SSL Handshake.
  3898. // We were waiting for incoming data which has just arrived.
  3899. [self ssl_continueSSLHandshake];
  3900. }
  3901. }
  3902. else
  3903. {
  3904. // We are still waiting for the writeQueue to drain and start the SSL/TLS process.
  3905. // We now know data is available to read.
  3906. if (![self usingCFStreamForTLS])
  3907. {
  3908. // Suspend the read source or else it will continue to fire nonstop.
  3909. [self suspendReadSource];
  3910. }
  3911. }
  3912. return;
  3913. }
  3914. BOOL done = NO; // Completed read operation
  3915. NSError *error = nil; // Error occurred
  3916. NSUInteger totalBytesReadForCurrentRead = 0;
  3917. //
  3918. // STEP 1 - READ FROM PREBUFFER
  3919. //
  3920. if ([preBuffer availableBytes] > 0)
  3921. {
  3922. // There are 3 types of read packets:
  3923. //
  3924. // 1) Read all available data.
  3925. // 2) Read a specific length of data.
  3926. // 3) Read up to a particular terminator.
  3927. NSUInteger bytesToCopy;
  3928. if (currentRead->term != nil)
  3929. {
  3930. // Read type #3 - read up to a terminator
  3931. bytesToCopy = [currentRead readLengthForTermWithPreBuffer:preBuffer found:&done];
  3932. }
  3933. else
  3934. {
  3935. // Read type #1 or #2
  3936. bytesToCopy = [currentRead readLengthForNonTermWithHint:[preBuffer availableBytes]];
  3937. }
  3938. // Make sure we have enough room in the buffer for our read.
  3939. [currentRead ensureCapacityForAdditionalDataOfLength:bytesToCopy];
  3940. // Copy bytes from prebuffer into packet buffer
  3941. uint8_t *buffer = (uint8_t *)[currentRead->buffer mutableBytes] + currentRead->startOffset +
  3942. currentRead->bytesDone;
  3943. memcpy(buffer, [preBuffer readBuffer], bytesToCopy);
  3944. // Remove the copied bytes from the preBuffer
  3945. [preBuffer didRead:bytesToCopy];
  3946. LogVerbose(@"copied(%lu) preBufferLength(%zu)", (unsigned long)bytesToCopy, [preBuffer availableBytes]);
  3947. // Update totals
  3948. currentRead->bytesDone += bytesToCopy;
  3949. totalBytesReadForCurrentRead += bytesToCopy;
  3950. // Check to see if the read operation is done
  3951. if (currentRead->readLength > 0)
  3952. {
  3953. // Read type #2 - read a specific length of data
  3954. done = (currentRead->bytesDone == currentRead->readLength);
  3955. }
  3956. else if (currentRead->term != nil)
  3957. {
  3958. // Read type #3 - read up to a terminator
  3959. // Our 'done' variable was updated via the readLengthForTermWithPreBuffer:found: method
  3960. if (!done && currentRead->maxLength > 0)
  3961. {
  3962. // We're not done and there's a set maxLength.
  3963. // Have we reached that maxLength yet?
  3964. if (currentRead->bytesDone >= currentRead->maxLength)
  3965. {
  3966. error = [self readMaxedOutError];
  3967. }
  3968. }
  3969. }
  3970. else
  3971. {
  3972. // Read type #1 - read all available data
  3973. //
  3974. // We're done as soon as
  3975. // - we've read all available data (in prebuffer and socket)
  3976. // - we've read the maxLength of read packet.
  3977. done = ((currentRead->maxLength > 0) && (currentRead->bytesDone == currentRead->maxLength));
  3978. }
  3979. }
  3980. //
  3981. // STEP 2 - READ FROM SOCKET
  3982. //
  3983. BOOL socketEOF = (flags & kSocketHasReadEOF) ? YES : NO; // Nothing more to read via socket (end of file)
  3984. BOOL waiting = !done && !error && !socketEOF && !hasBytesAvailable; // Ran out of data, waiting for more
  3985. if (!done && !error && !socketEOF && hasBytesAvailable)
  3986. {
  3987. NSAssert(([preBuffer availableBytes] == 0), @"Invalid logic");
  3988. BOOL readIntoPreBuffer = NO;
  3989. uint8_t *buffer = NULL;
  3990. size_t bytesRead = 0;
  3991. if (flags & kSocketSecure)
  3992. {
  3993. if ([self usingCFStreamForTLS])
  3994. {
  3995. #if TARGET_OS_IPHONE
  3996. // Using CFStream, rather than SecureTransport, for TLS
  3997. NSUInteger defaultReadLength = (1024 * 32);
  3998. NSUInteger bytesToRead = [currentRead optimalReadLengthWithDefault:defaultReadLength
  3999. shouldPreBuffer:&readIntoPreBuffer];
  4000. // Make sure we have enough room in the buffer for our read.
  4001. //
  4002. // We are either reading directly into the currentRead->buffer,
  4003. // or we're reading into the temporary preBuffer.
  4004. if (readIntoPreBuffer)
  4005. {
  4006. [preBuffer ensureCapacityForWrite:bytesToRead];
  4007. buffer = [preBuffer writeBuffer];
  4008. }
  4009. else
  4010. {
  4011. [currentRead ensureCapacityForAdditionalDataOfLength:bytesToRead];
  4012. buffer = (uint8_t *)[currentRead->buffer mutableBytes]
  4013. + currentRead->startOffset
  4014. + currentRead->bytesDone;
  4015. }
  4016. // Read data into buffer
  4017. CFIndex result = CFReadStreamRead(readStream, buffer, (CFIndex)bytesToRead);
  4018. LogVerbose(@"CFReadStreamRead(): result = %i", (int)result);
  4019. if (result < 0)
  4020. {
  4021. error = (__bridge_transfer NSError *)CFReadStreamCopyError(readStream);
  4022. }
  4023. else if (result == 0)
  4024. {
  4025. socketEOF = YES;
  4026. }
  4027. else
  4028. {
  4029. waiting = YES;
  4030. bytesRead = (size_t)result;
  4031. }
  4032. // We only know how many decrypted bytes were read.
  4033. // The actual number of bytes read was likely more due to the overhead of the encryption.
  4034. // So we reset our flag, and rely on the next callback to alert us of more data.
  4035. flags &= ~kSecureSocketHasBytesAvailable;
  4036. #endif
  4037. }
  4038. else
  4039. {
  4040. // Using SecureTransport for TLS
  4041. //
  4042. // We know:
  4043. // - how many bytes are available on the socket
  4044. // - how many encrypted bytes are sitting in the sslPreBuffer
  4045. // - how many decypted bytes are sitting in the sslContext
  4046. //
  4047. // But we do NOT know:
  4048. // - how many encypted bytes are sitting in the sslContext
  4049. //
  4050. // So we play the regular game of using an upper bound instead.
  4051. NSUInteger defaultReadLength = (1024 * 32);
  4052. if (defaultReadLength < estimatedBytesAvailable) {
  4053. defaultReadLength = estimatedBytesAvailable + (1024 * 16);
  4054. }
  4055. NSUInteger bytesToRead = [currentRead optimalReadLengthWithDefault:defaultReadLength
  4056. shouldPreBuffer:&readIntoPreBuffer];
  4057. if (bytesToRead > SIZE_MAX) { // NSUInteger may be bigger than size_t
  4058. bytesToRead = SIZE_MAX;
  4059. }
  4060. // Make sure we have enough room in the buffer for our read.
  4061. //
  4062. // We are either reading directly into the currentRead->buffer,
  4063. // or we're reading into the temporary preBuffer.
  4064. if (readIntoPreBuffer)
  4065. {
  4066. [preBuffer ensureCapacityForWrite:bytesToRead];
  4067. buffer = [preBuffer writeBuffer];
  4068. }
  4069. else
  4070. {
  4071. [currentRead ensureCapacityForAdditionalDataOfLength:bytesToRead];
  4072. buffer = (uint8_t *)[currentRead->buffer mutableBytes]
  4073. + currentRead->startOffset
  4074. + currentRead->bytesDone;
  4075. }
  4076. // The documentation from Apple states:
  4077. //
  4078. // "a read operation might return errSSLWouldBlock,
  4079. // indicating that less data than requested was actually transferred"
  4080. //
  4081. // However, starting around 10.7, the function will sometimes return noErr,
  4082. // even if it didn't read as much data as requested. So we need to watch out for that.
  4083. OSStatus result;
  4084. do
  4085. {
  4086. void *loop_buffer = buffer + bytesRead;
  4087. size_t loop_bytesToRead = (size_t)bytesToRead - bytesRead;
  4088. size_t loop_bytesRead = 0;
  4089. result = SSLRead(sslContext, loop_buffer, loop_bytesToRead, &loop_bytesRead);
  4090. LogVerbose(@"read from secure socket = %u", (unsigned)loop_bytesRead);
  4091. bytesRead += loop_bytesRead;
  4092. } while ((result == noErr) && (bytesRead < bytesToRead));
  4093. if (result != noErr)
  4094. {
  4095. if (result == errSSLWouldBlock)
  4096. waiting = YES;
  4097. else
  4098. {
  4099. if (result == errSSLClosedGraceful || result == errSSLClosedAbort)
  4100. {
  4101. // We've reached the end of the stream.
  4102. // Handle this the same way we would an EOF from the socket.
  4103. socketEOF = YES;
  4104. sslErrCode = result;
  4105. }
  4106. else
  4107. {
  4108. error = [self sslError:result];
  4109. }
  4110. }
  4111. // It's possible that bytesRead > 0, even if the result was errSSLWouldBlock.
  4112. // This happens when the SSLRead function is able to read some data,
  4113. // but not the entire amount we requested.
  4114. if (bytesRead <= 0)
  4115. {
  4116. bytesRead = 0;
  4117. }
  4118. }
  4119. // Do not modify socketFDBytesAvailable.
  4120. // It will be updated via the SSLReadFunction().
  4121. }
  4122. }
  4123. else
  4124. {
  4125. // Normal socket operation
  4126. NSUInteger bytesToRead;
  4127. // There are 3 types of read packets:
  4128. //
  4129. // 1) Read all available data.
  4130. // 2) Read a specific length of data.
  4131. // 3) Read up to a particular terminator.
  4132. if (currentRead->term != nil)
  4133. {
  4134. // Read type #3 - read up to a terminator
  4135. bytesToRead = [currentRead readLengthForTermWithHint:estimatedBytesAvailable
  4136. shouldPreBuffer:&readIntoPreBuffer];
  4137. }
  4138. else
  4139. {
  4140. // Read type #1 or #2
  4141. bytesToRead = [currentRead readLengthForNonTermWithHint:estimatedBytesAvailable];
  4142. }
  4143. if (bytesToRead > SIZE_MAX) { // NSUInteger may be bigger than size_t (read param 3)
  4144. bytesToRead = SIZE_MAX;
  4145. }
  4146. // Make sure we have enough room in the buffer for our read.
  4147. //
  4148. // We are either reading directly into the currentRead->buffer,
  4149. // or we're reading into the temporary preBuffer.
  4150. if (readIntoPreBuffer)
  4151. {
  4152. [preBuffer ensureCapacityForWrite:bytesToRead];
  4153. buffer = [preBuffer writeBuffer];
  4154. }
  4155. else
  4156. {
  4157. [currentRead ensureCapacityForAdditionalDataOfLength:bytesToRead];
  4158. buffer = (uint8_t *)[currentRead->buffer mutableBytes]
  4159. + currentRead->startOffset
  4160. + currentRead->bytesDone;
  4161. }
  4162. // Read data into buffer
  4163. int socketFD = (socket4FD != SOCKET_NULL) ? socket4FD : (socket6FD != SOCKET_NULL) ? socket6FD : socketUN;
  4164. ssize_t result = read(socketFD, buffer, (size_t)bytesToRead);
  4165. LogVerbose(@"read from socket = %i", (int)result);
  4166. if (result < 0)
  4167. {
  4168. if (errno == EWOULDBLOCK)
  4169. waiting = YES;
  4170. else
  4171. error = [self errorWithErrno:errno reason:@"Error in read() function"];
  4172. socketFDBytesAvailable = 0;
  4173. }
  4174. else if (result == 0)
  4175. {
  4176. socketEOF = YES;
  4177. socketFDBytesAvailable = 0;
  4178. }
  4179. else
  4180. {
  4181. bytesRead = result;
  4182. if (bytesRead < bytesToRead)
  4183. {
  4184. // The read returned less data than requested.
  4185. // This means socketFDBytesAvailable was a bit off due to timing,
  4186. // because we read from the socket right when the readSource event was firing.
  4187. socketFDBytesAvailable = 0;
  4188. }
  4189. else
  4190. {
  4191. if (socketFDBytesAvailable <= bytesRead)
  4192. socketFDBytesAvailable = 0;
  4193. else
  4194. socketFDBytesAvailable -= bytesRead;
  4195. }
  4196. if (socketFDBytesAvailable == 0)
  4197. {
  4198. waiting = YES;
  4199. }
  4200. }
  4201. }
  4202. if (bytesRead > 0)
  4203. {
  4204. // Check to see if the read operation is done
  4205. if (currentRead->readLength > 0)
  4206. {
  4207. // Read type #2 - read a specific length of data
  4208. //
  4209. // Note: We should never be using a prebuffer when we're reading a specific length of data.
  4210. NSAssert(readIntoPreBuffer == NO, @"Invalid logic");
  4211. currentRead->bytesDone += bytesRead;
  4212. totalBytesReadForCurrentRead += bytesRead;
  4213. done = (currentRead->bytesDone == currentRead->readLength);
  4214. }
  4215. else if (currentRead->term != nil)
  4216. {
  4217. // Read type #3 - read up to a terminator
  4218. if (readIntoPreBuffer)
  4219. {
  4220. // We just read a big chunk of data into the preBuffer
  4221. [preBuffer didWrite:bytesRead];
  4222. LogVerbose(@"read data into preBuffer - preBuffer.length = %zu", [preBuffer availableBytes]);
  4223. // Search for the terminating sequence
  4224. NSUInteger bytesToCopy = [currentRead readLengthForTermWithPreBuffer:preBuffer found:&done];
  4225. LogVerbose(@"copying %lu bytes from preBuffer", (unsigned long)bytesToCopy);
  4226. // Ensure there's room on the read packet's buffer
  4227. [currentRead ensureCapacityForAdditionalDataOfLength:bytesToCopy];
  4228. // Copy bytes from prebuffer into read buffer
  4229. uint8_t *readBuf = (uint8_t *)[currentRead->buffer mutableBytes] + currentRead->startOffset
  4230. + currentRead->bytesDone;
  4231. memcpy(readBuf, [preBuffer readBuffer], bytesToCopy);
  4232. // Remove the copied bytes from the prebuffer
  4233. [preBuffer didRead:bytesToCopy];
  4234. LogVerbose(@"preBuffer.length = %zu", [preBuffer availableBytes]);
  4235. // Update totals
  4236. currentRead->bytesDone += bytesToCopy;
  4237. totalBytesReadForCurrentRead += bytesToCopy;
  4238. // Our 'done' variable was updated via the readLengthForTermWithPreBuffer:found: method above
  4239. }
  4240. else
  4241. {
  4242. // We just read a big chunk of data directly into the packet's buffer.
  4243. // We need to move any overflow into the prebuffer.
  4244. NSInteger overflow = [currentRead searchForTermAfterPreBuffering:bytesRead];
  4245. if (overflow == 0)
  4246. {
  4247. // Perfect match!
  4248. // Every byte we read stays in the read buffer,
  4249. // and the last byte we read was the last byte of the term.
  4250. currentRead->bytesDone += bytesRead;
  4251. totalBytesReadForCurrentRead += bytesRead;
  4252. done = YES;
  4253. }
  4254. else if (overflow > 0)
  4255. {
  4256. // The term was found within the data that we read,
  4257. // and there are extra bytes that extend past the end of the term.
  4258. // We need to move these excess bytes out of the read packet and into the prebuffer.
  4259. NSInteger underflow = bytesRead - overflow;
  4260. // Copy excess data into preBuffer
  4261. LogVerbose(@"copying %ld overflow bytes into preBuffer", (long)overflow);
  4262. [preBuffer ensureCapacityForWrite:overflow];
  4263. uint8_t *overflowBuffer = buffer + underflow;
  4264. memcpy([preBuffer writeBuffer], overflowBuffer, overflow);
  4265. [preBuffer didWrite:overflow];
  4266. LogVerbose(@"preBuffer.length = %zu", [preBuffer availableBytes]);
  4267. // Note: The completeCurrentRead method will trim the buffer for us.
  4268. currentRead->bytesDone += underflow;
  4269. totalBytesReadForCurrentRead += underflow;
  4270. done = YES;
  4271. }
  4272. else
  4273. {
  4274. // The term was not found within the data that we read.
  4275. currentRead->bytesDone += bytesRead;
  4276. totalBytesReadForCurrentRead += bytesRead;
  4277. done = NO;
  4278. }
  4279. }
  4280. if (!done && currentRead->maxLength > 0)
  4281. {
  4282. // We're not done and there's a set maxLength.
  4283. // Have we reached that maxLength yet?
  4284. if (currentRead->bytesDone >= currentRead->maxLength)
  4285. {
  4286. error = [self readMaxedOutError];
  4287. }
  4288. }
  4289. }
  4290. else
  4291. {
  4292. // Read type #1 - read all available data
  4293. if (readIntoPreBuffer)
  4294. {
  4295. // We just read a chunk of data into the preBuffer
  4296. [preBuffer didWrite:bytesRead];
  4297. // Now copy the data into the read packet.
  4298. //
  4299. // Recall that we didn't read directly into the packet's buffer to avoid
  4300. // over-allocating memory since we had no clue how much data was available to be read.
  4301. //
  4302. // Ensure there's room on the read packet's buffer
  4303. [currentRead ensureCapacityForAdditionalDataOfLength:bytesRead];
  4304. // Copy bytes from prebuffer into read buffer
  4305. uint8_t *readBuf = (uint8_t *)[currentRead->buffer mutableBytes] + currentRead->startOffset
  4306. + currentRead->bytesDone;
  4307. memcpy(readBuf, [preBuffer readBuffer], bytesRead);
  4308. // Remove the copied bytes from the prebuffer
  4309. [preBuffer didRead:bytesRead];
  4310. // Update totals
  4311. currentRead->bytesDone += bytesRead;
  4312. totalBytesReadForCurrentRead += bytesRead;
  4313. }
  4314. else
  4315. {
  4316. currentRead->bytesDone += bytesRead;
  4317. totalBytesReadForCurrentRead += bytesRead;
  4318. }
  4319. done = YES;
  4320. }
  4321. } // if (bytesRead > 0)
  4322. } // if (!done && !error && !socketEOF && hasBytesAvailable)
  4323. if (!done && currentRead->readLength == 0 && currentRead->term == nil)
  4324. {
  4325. // Read type #1 - read all available data
  4326. //
  4327. // We might arrive here if we read data from the prebuffer but not from the socket.
  4328. done = (totalBytesReadForCurrentRead > 0);
  4329. }
  4330. // Check to see if we're done, or if we've made progress
  4331. if (done)
  4332. {
  4333. [self completeCurrentRead];
  4334. if (!error && (!socketEOF || [preBuffer availableBytes] > 0))
  4335. {
  4336. [self maybeDequeueRead];
  4337. }
  4338. }
  4339. else if (totalBytesReadForCurrentRead > 0)
  4340. {
  4341. // We're not done read type #2 or #3 yet, but we have read in some bytes
  4342. //
  4343. // We ensure that `waiting` is set in order to resume the readSource (if it is suspended). It is
  4344. // possible to reach this point and `waiting` not be set, if the current read's length is
  4345. // sufficiently large. In that case, we may have read to some upperbound successfully, but
  4346. // that upperbound could be smaller than the desired length.
  4347. waiting = YES;
  4348. __strong id<GCDAsyncSocketDelegate> theDelegate = delegate;
  4349. if (delegateQueue && [theDelegate respondsToSelector:@selector(socket:didReadPartialDataOfLength:tag:)])
  4350. {
  4351. long theReadTag = currentRead->tag;
  4352. dispatch_async(delegateQueue, ^{ @autoreleasepool {
  4353. [theDelegate socket:self didReadPartialDataOfLength:totalBytesReadForCurrentRead tag:theReadTag];
  4354. }});
  4355. }
  4356. }
  4357. // Check for errors
  4358. if (error)
  4359. {
  4360. [self closeWithError:error];
  4361. }
  4362. else if (socketEOF)
  4363. {
  4364. [self doReadEOF];
  4365. }
  4366. else if (waiting)
  4367. {
  4368. if (![self usingCFStreamForTLS])
  4369. {
  4370. // Monitor the socket for readability (if we're not already doing so)
  4371. [self resumeReadSource];
  4372. }
  4373. }
  4374. // Do not add any code here without first adding return statements in the error cases above.
  4375. }
  4376. - (void)doReadEOF
  4377. {
  4378. LogTrace();
  4379. // This method may be called more than once.
  4380. // If the EOF is read while there is still data in the preBuffer,
  4381. // then this method may be called continually after invocations of doReadData to see if it's time to disconnect.
  4382. flags |= kSocketHasReadEOF;
  4383. if (flags & kSocketSecure)
  4384. {
  4385. // If the SSL layer has any buffered data, flush it into the preBuffer now.
  4386. [self flushSSLBuffers];
  4387. }
  4388. BOOL shouldDisconnect = NO;
  4389. NSError *error = nil;
  4390. if ((flags & kStartingReadTLS) || (flags & kStartingWriteTLS))
  4391. {
  4392. // We received an EOF during or prior to startTLS.
  4393. // The SSL/TLS handshake is now impossible, so this is an unrecoverable situation.
  4394. shouldDisconnect = YES;
  4395. if ([self usingSecureTransportForTLS])
  4396. {
  4397. error = [self sslError:errSSLClosedAbort];
  4398. }
  4399. }
  4400. else if (flags & kReadStreamClosed)
  4401. {
  4402. // The preBuffer has already been drained.
  4403. // The config allows half-duplex connections.
  4404. // We've previously checked the socket, and it appeared writeable.
  4405. // So we marked the read stream as closed and notified the delegate.
  4406. //
  4407. // As per the half-duplex contract, the socket will be closed when a write fails,
  4408. // or when the socket is manually closed.
  4409. shouldDisconnect = NO;
  4410. }
  4411. else if ([preBuffer availableBytes] > 0)
  4412. {
  4413. LogVerbose(@"Socket reached EOF, but there is still data available in prebuffer");
  4414. // Although we won't be able to read any more data from the socket,
  4415. // there is existing data that has been prebuffered that we can read.
  4416. shouldDisconnect = NO;
  4417. }
  4418. else if (config & kAllowHalfDuplexConnection)
  4419. {
  4420. // We just received an EOF (end of file) from the socket's read stream.
  4421. // This means the remote end of the socket (the peer we're connected to)
  4422. // has explicitly stated that it will not be sending us any more data.
  4423. //
  4424. // Query the socket to see if it is still writeable. (Perhaps the peer will continue reading data from us)
  4425. int socketFD = (socket4FD != SOCKET_NULL) ? socket4FD : (socket6FD != SOCKET_NULL) ? socket6FD : socketUN;
  4426. struct pollfd pfd[1];
  4427. pfd[0].fd = socketFD;
  4428. pfd[0].events = POLLOUT;
  4429. pfd[0].revents = 0;
  4430. poll(pfd, 1, 0);
  4431. if (pfd[0].revents & POLLOUT)
  4432. {
  4433. // Socket appears to still be writeable
  4434. shouldDisconnect = NO;
  4435. flags |= kReadStreamClosed;
  4436. // Notify the delegate that we're going half-duplex
  4437. __strong id<GCDAsyncSocketDelegate> theDelegate = delegate;
  4438. if (delegateQueue && [theDelegate respondsToSelector:@selector(socketDidCloseReadStream:)])
  4439. {
  4440. dispatch_async(delegateQueue, ^{ @autoreleasepool {
  4441. [theDelegate socketDidCloseReadStream:self];
  4442. }});
  4443. }
  4444. }
  4445. else
  4446. {
  4447. shouldDisconnect = YES;
  4448. }
  4449. }
  4450. else
  4451. {
  4452. shouldDisconnect = YES;
  4453. }
  4454. if (shouldDisconnect)
  4455. {
  4456. if (error == nil)
  4457. {
  4458. if ([self usingSecureTransportForTLS])
  4459. {
  4460. if (sslErrCode != noErr && sslErrCode != errSSLClosedGraceful)
  4461. {
  4462. error = [self sslError:sslErrCode];
  4463. }
  4464. else
  4465. {
  4466. error = [self connectionClosedError];
  4467. }
  4468. }
  4469. else
  4470. {
  4471. error = [self connectionClosedError];
  4472. }
  4473. }
  4474. [self closeWithError:error];
  4475. }
  4476. else
  4477. {
  4478. if (![self usingCFStreamForTLS])
  4479. {
  4480. // Suspend the read source (if needed)
  4481. [self suspendReadSource];
  4482. }
  4483. }
  4484. }
  4485. - (void)completeCurrentRead
  4486. {
  4487. LogTrace();
  4488. NSAssert(currentRead, @"Trying to complete current read when there is no current read.");
  4489. NSData *result = nil;
  4490. if (currentRead->bufferOwner)
  4491. {
  4492. // We created the buffer on behalf of the user.
  4493. // Trim our buffer to be the proper size.
  4494. [currentRead->buffer setLength:currentRead->bytesDone];
  4495. result = currentRead->buffer;
  4496. }
  4497. else
  4498. {
  4499. // We did NOT create the buffer.
  4500. // The buffer is owned by the caller.
  4501. // Only trim the buffer if we had to increase its size.
  4502. if ([currentRead->buffer length] > currentRead->originalBufferLength)
  4503. {
  4504. NSUInteger readSize = currentRead->startOffset + currentRead->bytesDone;
  4505. NSUInteger origSize = currentRead->originalBufferLength;
  4506. NSUInteger buffSize = MAX(readSize, origSize);
  4507. [currentRead->buffer setLength:buffSize];
  4508. }
  4509. uint8_t *buffer = (uint8_t *)[currentRead->buffer mutableBytes] + currentRead->startOffset;
  4510. result = [NSData dataWithBytesNoCopy:buffer length:currentRead->bytesDone freeWhenDone:NO];
  4511. }
  4512. __strong id<GCDAsyncSocketDelegate> theDelegate = delegate;
  4513. if (delegateQueue && [theDelegate respondsToSelector:@selector(socket:didReadData:withTag:)])
  4514. {
  4515. GCDAsyncReadPacket *theRead = currentRead; // Ensure currentRead retained since result may not own buffer
  4516. dispatch_async(delegateQueue, ^{ @autoreleasepool {
  4517. [theDelegate socket:self didReadData:result withTag:theRead->tag];
  4518. }});
  4519. }
  4520. [self endCurrentRead];
  4521. }
  4522. - (void)endCurrentRead
  4523. {
  4524. if (readTimer)
  4525. {
  4526. dispatch_source_cancel(readTimer);
  4527. readTimer = NULL;
  4528. }
  4529. currentRead = nil;
  4530. }
  4531. - (void)setupReadTimerWithTimeout:(NSTimeInterval)timeout
  4532. {
  4533. if (timeout >= 0.0)
  4534. {
  4535. readTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, socketQueue);
  4536. __weak GCDAsyncSocket *weakSelf = self;
  4537. dispatch_source_set_event_handler(readTimer, ^{ @autoreleasepool {
  4538. #pragma clang diagnostic push
  4539. #pragma clang diagnostic warning "-Wimplicit-retain-self"
  4540. __strong GCDAsyncSocket *strongSelf = weakSelf;
  4541. if (strongSelf == nil) return_from_block;
  4542. [strongSelf doReadTimeout];
  4543. #pragma clang diagnostic pop
  4544. }});
  4545. #if !OS_OBJECT_USE_OBJC
  4546. dispatch_source_t theReadTimer = readTimer;
  4547. dispatch_source_set_cancel_handler(readTimer, ^{
  4548. #pragma clang diagnostic push
  4549. #pragma clang diagnostic warning "-Wimplicit-retain-self"
  4550. LogVerbose(@"dispatch_release(readTimer)");
  4551. dispatch_release(theReadTimer);
  4552. #pragma clang diagnostic pop
  4553. });
  4554. #endif
  4555. dispatch_time_t tt = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeout * NSEC_PER_SEC));
  4556. dispatch_source_set_timer(readTimer, tt, DISPATCH_TIME_FOREVER, 0);
  4557. dispatch_resume(readTimer);
  4558. }
  4559. }
  4560. - (void)doReadTimeout
  4561. {
  4562. // This is a little bit tricky.
  4563. // Ideally we'd like to synchronously query the delegate about a timeout extension.
  4564. // But if we do so synchronously we risk a possible deadlock.
  4565. // So instead we have to do so asynchronously, and callback to ourselves from within the delegate block.
  4566. flags |= kReadsPaused;
  4567. __strong id<GCDAsyncSocketDelegate> theDelegate = delegate;
  4568. if (delegateQueue && [theDelegate respondsToSelector:@selector(socket:shouldTimeoutReadWithTag:elapsed:bytesDone:)])
  4569. {
  4570. GCDAsyncReadPacket *theRead = currentRead;
  4571. dispatch_async(delegateQueue, ^{ @autoreleasepool {
  4572. NSTimeInterval timeoutExtension = 0.0;
  4573. timeoutExtension = [theDelegate socket:self shouldTimeoutReadWithTag:theRead->tag
  4574. elapsed:theRead->timeout
  4575. bytesDone:theRead->bytesDone];
  4576. dispatch_async(self->socketQueue, ^{ @autoreleasepool {
  4577. [self doReadTimeoutWithExtension:timeoutExtension];
  4578. }});
  4579. }});
  4580. }
  4581. else
  4582. {
  4583. [self doReadTimeoutWithExtension:0.0];
  4584. }
  4585. }
  4586. - (void)doReadTimeoutWithExtension:(NSTimeInterval)timeoutExtension
  4587. {
  4588. if (currentRead)
  4589. {
  4590. if (timeoutExtension > 0.0)
  4591. {
  4592. currentRead->timeout += timeoutExtension;
  4593. // Reschedule the timer
  4594. dispatch_time_t tt = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeoutExtension * NSEC_PER_SEC));
  4595. dispatch_source_set_timer(readTimer, tt, DISPATCH_TIME_FOREVER, 0);
  4596. // Unpause reads, and continue
  4597. flags &= ~kReadsPaused;
  4598. [self doReadData];
  4599. }
  4600. else
  4601. {
  4602. LogVerbose(@"ReadTimeout");
  4603. [self closeWithError:[self readTimeoutError]];
  4604. }
  4605. }
  4606. }
  4607. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  4608. #pragma mark Writing
  4609. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  4610. - (void)writeData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag
  4611. {
  4612. if ([data length] == 0) return;
  4613. GCDAsyncWritePacket *packet = [[GCDAsyncWritePacket alloc] initWithData:data timeout:timeout tag:tag];
  4614. dispatch_async(socketQueue, ^{ @autoreleasepool {
  4615. LogTrace();
  4616. if ((self->flags & kSocketStarted) && !(self->flags & kForbidReadsWrites))
  4617. {
  4618. [self->writeQueue addObject:packet];
  4619. [self maybeDequeueWrite];
  4620. }
  4621. }});
  4622. // Do not rely on the block being run in order to release the packet,
  4623. // as the queue might get released without the block completing.
  4624. }
  4625. - (float)progressOfWriteReturningTag:(long *)tagPtr bytesDone:(NSUInteger *)donePtr total:(NSUInteger *)totalPtr
  4626. {
  4627. __block float result = 0.0F;
  4628. dispatch_block_t block = ^{
  4629. if (!self->currentWrite || ![self->currentWrite isKindOfClass:[GCDAsyncWritePacket class]])
  4630. {
  4631. // We're not writing anything right now.
  4632. if (tagPtr != NULL) *tagPtr = 0;
  4633. if (donePtr != NULL) *donePtr = 0;
  4634. if (totalPtr != NULL) *totalPtr = 0;
  4635. result = NAN;
  4636. }
  4637. else
  4638. {
  4639. NSUInteger done = self->currentWrite->bytesDone;
  4640. NSUInteger total = [self->currentWrite->buffer length];
  4641. if (tagPtr != NULL) *tagPtr = self->currentWrite->tag;
  4642. if (donePtr != NULL) *donePtr = done;
  4643. if (totalPtr != NULL) *totalPtr = total;
  4644. result = (float)done / (float)total;
  4645. }
  4646. };
  4647. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  4648. block();
  4649. else
  4650. dispatch_sync(socketQueue, block);
  4651. return result;
  4652. }
  4653. /**
  4654. * Conditionally starts a new write.
  4655. *
  4656. * It is called when:
  4657. * - a user requests a write
  4658. * - after a write request has finished (to handle the next request)
  4659. * - immediately after the socket opens to handle any pending requests
  4660. *
  4661. * This method also handles auto-disconnect post read/write completion.
  4662. **/
  4663. - (void)maybeDequeueWrite
  4664. {
  4665. LogTrace();
  4666. NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue");
  4667. // If we're not currently processing a write AND we have an available write stream
  4668. if ((currentWrite == nil) && (flags & kConnected))
  4669. {
  4670. if ([writeQueue count] > 0)
  4671. {
  4672. // Dequeue the next object in the write queue
  4673. currentWrite = [writeQueue objectAtIndex:0];
  4674. [writeQueue removeObjectAtIndex:0];
  4675. if ([currentWrite isKindOfClass:[GCDAsyncSpecialPacket class]])
  4676. {
  4677. LogVerbose(@"Dequeued GCDAsyncSpecialPacket");
  4678. // Attempt to start TLS
  4679. flags |= kStartingWriteTLS;
  4680. // This method won't do anything unless both kStartingReadTLS and kStartingWriteTLS are set
  4681. [self maybeStartTLS];
  4682. }
  4683. else
  4684. {
  4685. LogVerbose(@"Dequeued GCDAsyncWritePacket");
  4686. // Setup write timer (if needed)
  4687. [self setupWriteTimerWithTimeout:currentWrite->timeout];
  4688. // Immediately write, if possible
  4689. [self doWriteData];
  4690. }
  4691. }
  4692. else if (flags & kDisconnectAfterWrites)
  4693. {
  4694. if (flags & kDisconnectAfterReads)
  4695. {
  4696. if (([readQueue count] == 0) && (currentRead == nil))
  4697. {
  4698. [self closeWithError:nil];
  4699. }
  4700. }
  4701. else
  4702. {
  4703. [self closeWithError:nil];
  4704. }
  4705. }
  4706. }
  4707. }
  4708. - (void)doWriteData
  4709. {
  4710. LogTrace();
  4711. // This method is called by the writeSource via the socketQueue
  4712. if ((currentWrite == nil) || (flags & kWritesPaused))
  4713. {
  4714. LogVerbose(@"No currentWrite or kWritesPaused");
  4715. // Unable to write at this time
  4716. if ([self usingCFStreamForTLS])
  4717. {
  4718. // CFWriteStream only fires once when there is available data.
  4719. // It won't fire again until we've invoked CFWriteStreamWrite.
  4720. }
  4721. else
  4722. {
  4723. // If the writeSource is firing, we need to pause it
  4724. // or else it will continue to fire over and over again.
  4725. if (flags & kSocketCanAcceptBytes)
  4726. {
  4727. [self suspendWriteSource];
  4728. }
  4729. }
  4730. return;
  4731. }
  4732. if (!(flags & kSocketCanAcceptBytes))
  4733. {
  4734. LogVerbose(@"No space available to write...");
  4735. // No space available to write.
  4736. if (![self usingCFStreamForTLS])
  4737. {
  4738. // Need to wait for writeSource to fire and notify us of
  4739. // available space in the socket's internal write buffer.
  4740. [self resumeWriteSource];
  4741. }
  4742. return;
  4743. }
  4744. if (flags & kStartingWriteTLS)
  4745. {
  4746. LogVerbose(@"Waiting for SSL/TLS handshake to complete");
  4747. // The writeQueue is waiting for SSL/TLS handshake to complete.
  4748. if (flags & kStartingReadTLS)
  4749. {
  4750. if ([self usingSecureTransportForTLS] && lastSSLHandshakeError == errSSLWouldBlock)
  4751. {
  4752. // We are in the process of a SSL Handshake.
  4753. // We were waiting for available space in the socket's internal OS buffer to continue writing.
  4754. [self ssl_continueSSLHandshake];
  4755. }
  4756. }
  4757. else
  4758. {
  4759. // We are still waiting for the readQueue to drain and start the SSL/TLS process.
  4760. // We now know we can write to the socket.
  4761. if (![self usingCFStreamForTLS])
  4762. {
  4763. // Suspend the write source or else it will continue to fire nonstop.
  4764. [self suspendWriteSource];
  4765. }
  4766. }
  4767. return;
  4768. }
  4769. // Note: This method is not called if currentWrite is a GCDAsyncSpecialPacket (startTLS packet)
  4770. BOOL waiting = NO;
  4771. NSError *error = nil;
  4772. size_t bytesWritten = 0;
  4773. if (flags & kSocketSecure)
  4774. {
  4775. if ([self usingCFStreamForTLS])
  4776. {
  4777. #if TARGET_OS_IPHONE
  4778. //
  4779. // Writing data using CFStream (over internal TLS)
  4780. //
  4781. const uint8_t *buffer = (const uint8_t *)[currentWrite->buffer bytes] + currentWrite->bytesDone;
  4782. NSUInteger bytesToWrite = [currentWrite->buffer length] - currentWrite->bytesDone;
  4783. if (bytesToWrite > SIZE_MAX) // NSUInteger may be bigger than size_t (write param 3)
  4784. {
  4785. bytesToWrite = SIZE_MAX;
  4786. }
  4787. CFIndex result = CFWriteStreamWrite(writeStream, buffer, (CFIndex)bytesToWrite);
  4788. LogVerbose(@"CFWriteStreamWrite(%lu) = %li", (unsigned long)bytesToWrite, result);
  4789. if (result < 0)
  4790. {
  4791. error = (__bridge_transfer NSError *)CFWriteStreamCopyError(writeStream);
  4792. }
  4793. else
  4794. {
  4795. bytesWritten = (size_t)result;
  4796. // We always set waiting to true in this scenario.
  4797. // CFStream may have altered our underlying socket to non-blocking.
  4798. // Thus if we attempt to write without a callback, we may end up blocking our queue.
  4799. waiting = YES;
  4800. }
  4801. #endif
  4802. }
  4803. else
  4804. {
  4805. // We're going to use the SSLWrite function.
  4806. //
  4807. // OSStatus SSLWrite(SSLContextRef context, const void *data, size_t dataLength, size_t *processed)
  4808. //
  4809. // Parameters:
  4810. // context - An SSL session context reference.
  4811. // data - A pointer to the buffer of data to write.
  4812. // dataLength - The amount, in bytes, of data to write.
  4813. // processed - On return, the length, in bytes, of the data actually written.
  4814. //
  4815. // It sounds pretty straight-forward,
  4816. // but there are a few caveats you should be aware of.
  4817. //
  4818. // The SSLWrite method operates in a non-obvious (and rather annoying) manner.
  4819. // According to the documentation:
  4820. //
  4821. // Because you may configure the underlying connection to operate in a non-blocking manner,
  4822. // a write operation might return errSSLWouldBlock, indicating that less data than requested
  4823. // was actually transferred. In this case, you should repeat the call to SSLWrite until some
  4824. // other result is returned.
  4825. //
  4826. // This sounds perfect, but when our SSLWriteFunction returns errSSLWouldBlock,
  4827. // then the SSLWrite method returns (with the proper errSSLWouldBlock return value),
  4828. // but it sets processed to dataLength !!
  4829. //
  4830. // In other words, if the SSLWrite function doesn't completely write all the data we tell it to,
  4831. // then it doesn't tell us how many bytes were actually written. So, for example, if we tell it to
  4832. // write 256 bytes then it might actually write 128 bytes, but then report 0 bytes written.
  4833. //
  4834. // You might be wondering:
  4835. // If the SSLWrite function doesn't tell us how many bytes were written,
  4836. // then how in the world are we supposed to update our parameters (buffer & bytesToWrite)
  4837. // for the next time we invoke SSLWrite?
  4838. //
  4839. // The answer is that SSLWrite cached all the data we told it to write,
  4840. // and it will push out that data next time we call SSLWrite.
  4841. // If we call SSLWrite with new data, it will push out the cached data first, and then the new data.
  4842. // If we call SSLWrite with empty data, then it will simply push out the cached data.
  4843. //
  4844. // For this purpose we're going to break large writes into a series of smaller writes.
  4845. // This allows us to report progress back to the delegate.
  4846. OSStatus result;
  4847. BOOL hasCachedDataToWrite = (sslWriteCachedLength > 0);
  4848. BOOL hasNewDataToWrite = YES;
  4849. if (hasCachedDataToWrite)
  4850. {
  4851. size_t processed = 0;
  4852. result = SSLWrite(sslContext, NULL, 0, &processed);
  4853. if (result == noErr)
  4854. {
  4855. bytesWritten = sslWriteCachedLength;
  4856. sslWriteCachedLength = 0;
  4857. if ([currentWrite->buffer length] == (currentWrite->bytesDone + bytesWritten))
  4858. {
  4859. // We've written all data for the current write.
  4860. hasNewDataToWrite = NO;
  4861. }
  4862. }
  4863. else
  4864. {
  4865. if (result == errSSLWouldBlock)
  4866. {
  4867. waiting = YES;
  4868. }
  4869. else
  4870. {
  4871. error = [self sslError:result];
  4872. }
  4873. // Can't write any new data since we were unable to write the cached data.
  4874. hasNewDataToWrite = NO;
  4875. }
  4876. }
  4877. if (hasNewDataToWrite)
  4878. {
  4879. const uint8_t *buffer = (const uint8_t *)[currentWrite->buffer bytes]
  4880. + currentWrite->bytesDone
  4881. + bytesWritten;
  4882. NSUInteger bytesToWrite = [currentWrite->buffer length] - currentWrite->bytesDone - bytesWritten;
  4883. if (bytesToWrite > SIZE_MAX) // NSUInteger may be bigger than size_t (write param 3)
  4884. {
  4885. bytesToWrite = SIZE_MAX;
  4886. }
  4887. size_t bytesRemaining = bytesToWrite;
  4888. BOOL keepLooping = YES;
  4889. while (keepLooping)
  4890. {
  4891. const size_t sslMaxBytesToWrite = 32768;
  4892. size_t sslBytesToWrite = MIN(bytesRemaining, sslMaxBytesToWrite);
  4893. size_t sslBytesWritten = 0;
  4894. result = SSLWrite(sslContext, buffer, sslBytesToWrite, &sslBytesWritten);
  4895. if (result == noErr)
  4896. {
  4897. buffer += sslBytesWritten;
  4898. bytesWritten += sslBytesWritten;
  4899. bytesRemaining -= sslBytesWritten;
  4900. keepLooping = (bytesRemaining > 0);
  4901. }
  4902. else
  4903. {
  4904. if (result == errSSLWouldBlock)
  4905. {
  4906. waiting = YES;
  4907. sslWriteCachedLength = sslBytesToWrite;
  4908. }
  4909. else
  4910. {
  4911. error = [self sslError:result];
  4912. }
  4913. keepLooping = NO;
  4914. }
  4915. } // while (keepLooping)
  4916. } // if (hasNewDataToWrite)
  4917. }
  4918. }
  4919. else
  4920. {
  4921. //
  4922. // Writing data directly over raw socket
  4923. //
  4924. int socketFD = (socket4FD != SOCKET_NULL) ? socket4FD : (socket6FD != SOCKET_NULL) ? socket6FD : socketUN;
  4925. const uint8_t *buffer = (const uint8_t *)[currentWrite->buffer bytes] + currentWrite->bytesDone;
  4926. NSUInteger bytesToWrite = [currentWrite->buffer length] - currentWrite->bytesDone;
  4927. if (bytesToWrite > SIZE_MAX) // NSUInteger may be bigger than size_t (write param 3)
  4928. {
  4929. bytesToWrite = SIZE_MAX;
  4930. }
  4931. ssize_t result = write(socketFD, buffer, (size_t)bytesToWrite);
  4932. LogVerbose(@"wrote to socket = %zd", result);
  4933. // Check results
  4934. if (result < 0)
  4935. {
  4936. if (errno == EWOULDBLOCK)
  4937. {
  4938. waiting = YES;
  4939. }
  4940. else
  4941. {
  4942. error = [self errorWithErrno:errno reason:@"Error in write() function"];
  4943. }
  4944. }
  4945. else
  4946. {
  4947. bytesWritten = result;
  4948. }
  4949. }
  4950. // We're done with our writing.
  4951. // If we explictly ran into a situation where the socket told us there was no room in the buffer,
  4952. // then we immediately resume listening for notifications.
  4953. //
  4954. // We must do this before we dequeue another write,
  4955. // as that may in turn invoke this method again.
  4956. //
  4957. // Note that if CFStream is involved, it may have maliciously put our socket in blocking mode.
  4958. if (waiting)
  4959. {
  4960. flags &= ~kSocketCanAcceptBytes;
  4961. if (![self usingCFStreamForTLS])
  4962. {
  4963. [self resumeWriteSource];
  4964. }
  4965. }
  4966. // Check our results
  4967. BOOL done = NO;
  4968. if (bytesWritten > 0)
  4969. {
  4970. // Update total amount read for the current write
  4971. currentWrite->bytesDone += bytesWritten;
  4972. LogVerbose(@"currentWrite->bytesDone = %lu", (unsigned long)currentWrite->bytesDone);
  4973. // Is packet done?
  4974. done = (currentWrite->bytesDone == [currentWrite->buffer length]);
  4975. }
  4976. if (done)
  4977. {
  4978. [self completeCurrentWrite];
  4979. if (!error)
  4980. {
  4981. dispatch_async(socketQueue, ^{ @autoreleasepool{
  4982. [self maybeDequeueWrite];
  4983. }});
  4984. }
  4985. }
  4986. else
  4987. {
  4988. // We were unable to finish writing the data,
  4989. // so we're waiting for another callback to notify us of available space in the lower-level output buffer.
  4990. if (!waiting && !error)
  4991. {
  4992. // This would be the case if our write was able to accept some data, but not all of it.
  4993. flags &= ~kSocketCanAcceptBytes;
  4994. if (![self usingCFStreamForTLS])
  4995. {
  4996. [self resumeWriteSource];
  4997. }
  4998. }
  4999. if (bytesWritten > 0)
  5000. {
  5001. // We're not done with the entire write, but we have written some bytes
  5002. __strong id<GCDAsyncSocketDelegate> theDelegate = delegate;
  5003. if (delegateQueue && [theDelegate respondsToSelector:@selector(socket:didWritePartialDataOfLength:tag:)])
  5004. {
  5005. long theWriteTag = currentWrite->tag;
  5006. dispatch_async(delegateQueue, ^{ @autoreleasepool {
  5007. [theDelegate socket:self didWritePartialDataOfLength:bytesWritten tag:theWriteTag];
  5008. }});
  5009. }
  5010. }
  5011. }
  5012. // Check for errors
  5013. if (error)
  5014. {
  5015. [self closeWithError:[self errorWithErrno:errno reason:@"Error in write() function"]];
  5016. }
  5017. // Do not add any code here without first adding a return statement in the error case above.
  5018. }
  5019. - (void)completeCurrentWrite
  5020. {
  5021. LogTrace();
  5022. NSAssert(currentWrite, @"Trying to complete current write when there is no current write.");
  5023. __strong id<GCDAsyncSocketDelegate> theDelegate = delegate;
  5024. if (delegateQueue && [theDelegate respondsToSelector:@selector(socket:didWriteDataWithTag:)])
  5025. {
  5026. long theWriteTag = currentWrite->tag;
  5027. dispatch_async(delegateQueue, ^{ @autoreleasepool {
  5028. [theDelegate socket:self didWriteDataWithTag:theWriteTag];
  5029. }});
  5030. }
  5031. [self endCurrentWrite];
  5032. }
  5033. - (void)endCurrentWrite
  5034. {
  5035. if (writeTimer)
  5036. {
  5037. dispatch_source_cancel(writeTimer);
  5038. writeTimer = NULL;
  5039. }
  5040. currentWrite = nil;
  5041. }
  5042. - (void)setupWriteTimerWithTimeout:(NSTimeInterval)timeout
  5043. {
  5044. if (timeout >= 0.0)
  5045. {
  5046. writeTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, socketQueue);
  5047. __weak GCDAsyncSocket *weakSelf = self;
  5048. dispatch_source_set_event_handler(writeTimer, ^{ @autoreleasepool {
  5049. #pragma clang diagnostic push
  5050. #pragma clang diagnostic warning "-Wimplicit-retain-self"
  5051. __strong GCDAsyncSocket *strongSelf = weakSelf;
  5052. if (strongSelf == nil) return_from_block;
  5053. [strongSelf doWriteTimeout];
  5054. #pragma clang diagnostic pop
  5055. }});
  5056. #if !OS_OBJECT_USE_OBJC
  5057. dispatch_source_t theWriteTimer = writeTimer;
  5058. dispatch_source_set_cancel_handler(writeTimer, ^{
  5059. #pragma clang diagnostic push
  5060. #pragma clang diagnostic warning "-Wimplicit-retain-self"
  5061. LogVerbose(@"dispatch_release(writeTimer)");
  5062. dispatch_release(theWriteTimer);
  5063. #pragma clang diagnostic pop
  5064. });
  5065. #endif
  5066. dispatch_time_t tt = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeout * NSEC_PER_SEC));
  5067. dispatch_source_set_timer(writeTimer, tt, DISPATCH_TIME_FOREVER, 0);
  5068. dispatch_resume(writeTimer);
  5069. }
  5070. }
  5071. - (void)doWriteTimeout
  5072. {
  5073. // This is a little bit tricky.
  5074. // Ideally we'd like to synchronously query the delegate about a timeout extension.
  5075. // But if we do so synchronously we risk a possible deadlock.
  5076. // So instead we have to do so asynchronously, and callback to ourselves from within the delegate block.
  5077. flags |= kWritesPaused;
  5078. __strong id<GCDAsyncSocketDelegate> theDelegate = delegate;
  5079. if (delegateQueue && [theDelegate respondsToSelector:@selector(socket:shouldTimeoutWriteWithTag:elapsed:bytesDone:)])
  5080. {
  5081. GCDAsyncWritePacket *theWrite = currentWrite;
  5082. dispatch_async(delegateQueue, ^{ @autoreleasepool {
  5083. NSTimeInterval timeoutExtension = 0.0;
  5084. timeoutExtension = [theDelegate socket:self shouldTimeoutWriteWithTag:theWrite->tag
  5085. elapsed:theWrite->timeout
  5086. bytesDone:theWrite->bytesDone];
  5087. dispatch_async(self->socketQueue, ^{ @autoreleasepool {
  5088. [self doWriteTimeoutWithExtension:timeoutExtension];
  5089. }});
  5090. }});
  5091. }
  5092. else
  5093. {
  5094. [self doWriteTimeoutWithExtension:0.0];
  5095. }
  5096. }
  5097. - (void)doWriteTimeoutWithExtension:(NSTimeInterval)timeoutExtension
  5098. {
  5099. if (currentWrite)
  5100. {
  5101. if (timeoutExtension > 0.0)
  5102. {
  5103. currentWrite->timeout += timeoutExtension;
  5104. // Reschedule the timer
  5105. dispatch_time_t tt = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeoutExtension * NSEC_PER_SEC));
  5106. dispatch_source_set_timer(writeTimer, tt, DISPATCH_TIME_FOREVER, 0);
  5107. // Unpause writes, and continue
  5108. flags &= ~kWritesPaused;
  5109. [self doWriteData];
  5110. }
  5111. else
  5112. {
  5113. LogVerbose(@"WriteTimeout");
  5114. [self closeWithError:[self writeTimeoutError]];
  5115. }
  5116. }
  5117. }
  5118. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  5119. #pragma mark Security
  5120. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  5121. - (void)startTLS:(NSDictionary *)tlsSettings
  5122. {
  5123. LogTrace();
  5124. if (tlsSettings == nil)
  5125. {
  5126. // Passing nil/NULL to CFReadStreamSetProperty will appear to work the same as passing an empty dictionary,
  5127. // but causes problems if we later try to fetch the remote host's certificate.
  5128. //
  5129. // To be exact, it causes the following to return NULL instead of the normal result:
  5130. // CFReadStreamCopyProperty(readStream, kCFStreamPropertySSLPeerCertificates)
  5131. //
  5132. // So we use an empty dictionary instead, which works perfectly.
  5133. tlsSettings = [NSDictionary dictionary];
  5134. }
  5135. GCDAsyncSpecialPacket *packet = [[GCDAsyncSpecialPacket alloc] initWithTLSSettings:tlsSettings];
  5136. dispatch_async(socketQueue, ^{ @autoreleasepool {
  5137. if ((self->flags & kSocketStarted) && !(self->flags & kQueuedTLS) && !(self->flags & kForbidReadsWrites))
  5138. {
  5139. [self->readQueue addObject:packet];
  5140. [self->writeQueue addObject:packet];
  5141. self->flags |= kQueuedTLS;
  5142. [self maybeDequeueRead];
  5143. [self maybeDequeueWrite];
  5144. }
  5145. }});
  5146. }
  5147. - (void)maybeStartTLS
  5148. {
  5149. // We can't start TLS until:
  5150. // - All queued reads prior to the user calling startTLS are complete
  5151. // - All queued writes prior to the user calling startTLS are complete
  5152. //
  5153. // We'll know these conditions are met when both kStartingReadTLS and kStartingWriteTLS are set
  5154. if ((flags & kStartingReadTLS) && (flags & kStartingWriteTLS))
  5155. {
  5156. BOOL useSecureTransport = YES;
  5157. #if TARGET_OS_IPHONE
  5158. {
  5159. GCDAsyncSpecialPacket *tlsPacket = (GCDAsyncSpecialPacket *)currentRead;
  5160. NSDictionary *tlsSettings = @{};
  5161. if (tlsPacket) {
  5162. tlsSettings = tlsPacket->tlsSettings;
  5163. }
  5164. NSNumber *value = [tlsSettings objectForKey:GCDAsyncSocketUseCFStreamForTLS];
  5165. if (value && [value boolValue])
  5166. useSecureTransport = NO;
  5167. }
  5168. #endif
  5169. if (useSecureTransport)
  5170. {
  5171. [self ssl_startTLS];
  5172. }
  5173. else
  5174. {
  5175. #if TARGET_OS_IPHONE
  5176. [self cf_startTLS];
  5177. #endif
  5178. }
  5179. }
  5180. }
  5181. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  5182. #pragma mark Security via SecureTransport
  5183. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  5184. - (OSStatus)sslReadWithBuffer:(void *)buffer length:(size_t *)bufferLength
  5185. {
  5186. LogVerbose(@"sslReadWithBuffer:%p length:%lu", buffer, (unsigned long)*bufferLength);
  5187. if ((socketFDBytesAvailable == 0) && ([sslPreBuffer availableBytes] == 0))
  5188. {
  5189. LogVerbose(@"%@ - No data available to read...", THIS_METHOD);
  5190. // No data available to read.
  5191. //
  5192. // Need to wait for readSource to fire and notify us of
  5193. // available data in the socket's internal read buffer.
  5194. [self resumeReadSource];
  5195. *bufferLength = 0;
  5196. return errSSLWouldBlock;
  5197. }
  5198. size_t totalBytesRead = 0;
  5199. size_t totalBytesLeftToBeRead = *bufferLength;
  5200. BOOL done = NO;
  5201. BOOL socketError = NO;
  5202. //
  5203. // STEP 1 : READ FROM SSL PRE BUFFER
  5204. //
  5205. size_t sslPreBufferLength = [sslPreBuffer availableBytes];
  5206. if (sslPreBufferLength > 0)
  5207. {
  5208. LogVerbose(@"%@: Reading from SSL pre buffer...", THIS_METHOD);
  5209. size_t bytesToCopy;
  5210. if (sslPreBufferLength > totalBytesLeftToBeRead)
  5211. bytesToCopy = totalBytesLeftToBeRead;
  5212. else
  5213. bytesToCopy = sslPreBufferLength;
  5214. LogVerbose(@"%@: Copying %zu bytes from sslPreBuffer", THIS_METHOD, bytesToCopy);
  5215. memcpy(buffer, [sslPreBuffer readBuffer], bytesToCopy);
  5216. [sslPreBuffer didRead:bytesToCopy];
  5217. LogVerbose(@"%@: sslPreBuffer.length = %zu", THIS_METHOD, [sslPreBuffer availableBytes]);
  5218. totalBytesRead += bytesToCopy;
  5219. totalBytesLeftToBeRead -= bytesToCopy;
  5220. done = (totalBytesLeftToBeRead == 0);
  5221. if (done) LogVerbose(@"%@: Complete", THIS_METHOD);
  5222. }
  5223. //
  5224. // STEP 2 : READ FROM SOCKET
  5225. //
  5226. if (!done && (socketFDBytesAvailable > 0))
  5227. {
  5228. LogVerbose(@"%@: Reading from socket...", THIS_METHOD);
  5229. int socketFD = (socket4FD != SOCKET_NULL) ? socket4FD : (socket6FD != SOCKET_NULL) ? socket6FD : socketUN;
  5230. BOOL readIntoPreBuffer;
  5231. size_t bytesToRead;
  5232. uint8_t *buf;
  5233. if (socketFDBytesAvailable > totalBytesLeftToBeRead)
  5234. {
  5235. // Read all available data from socket into sslPreBuffer.
  5236. // Then copy requested amount into dataBuffer.
  5237. LogVerbose(@"%@: Reading into sslPreBuffer...", THIS_METHOD);
  5238. [sslPreBuffer ensureCapacityForWrite:socketFDBytesAvailable];
  5239. readIntoPreBuffer = YES;
  5240. bytesToRead = (size_t)socketFDBytesAvailable;
  5241. buf = [sslPreBuffer writeBuffer];
  5242. }
  5243. else
  5244. {
  5245. // Read available data from socket directly into dataBuffer.
  5246. LogVerbose(@"%@: Reading directly into dataBuffer...", THIS_METHOD);
  5247. readIntoPreBuffer = NO;
  5248. bytesToRead = totalBytesLeftToBeRead;
  5249. buf = (uint8_t *)buffer + totalBytesRead;
  5250. }
  5251. ssize_t result = read(socketFD, buf, bytesToRead);
  5252. LogVerbose(@"%@: read from socket = %zd", THIS_METHOD, result);
  5253. if (result < 0)
  5254. {
  5255. LogVerbose(@"%@: read errno = %i", THIS_METHOD, errno);
  5256. if (errno != EWOULDBLOCK)
  5257. {
  5258. socketError = YES;
  5259. }
  5260. socketFDBytesAvailable = 0;
  5261. }
  5262. else if (result == 0)
  5263. {
  5264. LogVerbose(@"%@: read EOF", THIS_METHOD);
  5265. socketError = YES;
  5266. socketFDBytesAvailable = 0;
  5267. }
  5268. else
  5269. {
  5270. size_t bytesReadFromSocket = result;
  5271. if (socketFDBytesAvailable > bytesReadFromSocket)
  5272. socketFDBytesAvailable -= bytesReadFromSocket;
  5273. else
  5274. socketFDBytesAvailable = 0;
  5275. if (readIntoPreBuffer)
  5276. {
  5277. [sslPreBuffer didWrite:bytesReadFromSocket];
  5278. size_t bytesToCopy = MIN(totalBytesLeftToBeRead, bytesReadFromSocket);
  5279. LogVerbose(@"%@: Copying %zu bytes out of sslPreBuffer", THIS_METHOD, bytesToCopy);
  5280. memcpy((uint8_t *)buffer + totalBytesRead, [sslPreBuffer readBuffer], bytesToCopy);
  5281. [sslPreBuffer didRead:bytesToCopy];
  5282. totalBytesRead += bytesToCopy;
  5283. totalBytesLeftToBeRead -= bytesToCopy;
  5284. LogVerbose(@"%@: sslPreBuffer.length = %zu", THIS_METHOD, [sslPreBuffer availableBytes]);
  5285. }
  5286. else
  5287. {
  5288. totalBytesRead += bytesReadFromSocket;
  5289. totalBytesLeftToBeRead -= bytesReadFromSocket;
  5290. }
  5291. done = (totalBytesLeftToBeRead == 0);
  5292. if (done) LogVerbose(@"%@: Complete", THIS_METHOD);
  5293. }
  5294. }
  5295. *bufferLength = totalBytesRead;
  5296. if (done)
  5297. return noErr;
  5298. if (socketError)
  5299. return errSSLClosedAbort;
  5300. return errSSLWouldBlock;
  5301. }
  5302. - (OSStatus)sslWriteWithBuffer:(const void *)buffer length:(size_t *)bufferLength
  5303. {
  5304. if (!(flags & kSocketCanAcceptBytes))
  5305. {
  5306. // Unable to write.
  5307. //
  5308. // Need to wait for writeSource to fire and notify us of
  5309. // available space in the socket's internal write buffer.
  5310. [self resumeWriteSource];
  5311. *bufferLength = 0;
  5312. return errSSLWouldBlock;
  5313. }
  5314. size_t bytesToWrite = *bufferLength;
  5315. size_t bytesWritten = 0;
  5316. BOOL done = NO;
  5317. BOOL socketError = NO;
  5318. int socketFD = (socket4FD != SOCKET_NULL) ? socket4FD : (socket6FD != SOCKET_NULL) ? socket6FD : socketUN;
  5319. ssize_t result = write(socketFD, buffer, bytesToWrite);
  5320. if (result < 0)
  5321. {
  5322. if (errno != EWOULDBLOCK)
  5323. {
  5324. socketError = YES;
  5325. }
  5326. flags &= ~kSocketCanAcceptBytes;
  5327. }
  5328. else if (result == 0)
  5329. {
  5330. flags &= ~kSocketCanAcceptBytes;
  5331. }
  5332. else
  5333. {
  5334. bytesWritten = result;
  5335. done = (bytesWritten == bytesToWrite);
  5336. }
  5337. *bufferLength = bytesWritten;
  5338. if (done)
  5339. return noErr;
  5340. if (socketError)
  5341. return errSSLClosedAbort;
  5342. return errSSLWouldBlock;
  5343. }
  5344. static OSStatus SSLReadFunction(SSLConnectionRef connection, void *data, size_t *dataLength)
  5345. {
  5346. GCDAsyncSocket *asyncSocket = (__bridge GCDAsyncSocket *)connection;
  5347. NSCAssert(dispatch_get_specific(asyncSocket->IsOnSocketQueueOrTargetQueueKey), @"What the deuce?");
  5348. return [asyncSocket sslReadWithBuffer:data length:dataLength];
  5349. }
  5350. static OSStatus SSLWriteFunction(SSLConnectionRef connection, const void *data, size_t *dataLength)
  5351. {
  5352. GCDAsyncSocket *asyncSocket = (__bridge GCDAsyncSocket *)connection;
  5353. NSCAssert(dispatch_get_specific(asyncSocket->IsOnSocketQueueOrTargetQueueKey), @"What the deuce?");
  5354. return [asyncSocket sslWriteWithBuffer:data length:dataLength];
  5355. }
  5356. - (void)ssl_startTLS
  5357. {
  5358. LogTrace();
  5359. LogVerbose(@"Starting TLS (via SecureTransport)...");
  5360. OSStatus status;
  5361. GCDAsyncSpecialPacket *tlsPacket = (GCDAsyncSpecialPacket *)currentRead;
  5362. if (tlsPacket == nil) // Code to quiet the analyzer
  5363. {
  5364. NSAssert(NO, @"Logic error");
  5365. [self closeWithError:[self otherError:@"Logic error"]];
  5366. return;
  5367. }
  5368. NSDictionary *tlsSettings = tlsPacket->tlsSettings;
  5369. // Create SSLContext, and setup IO callbacks and connection ref
  5370. NSNumber *isServerNumber = [tlsSettings objectForKey:(__bridge NSString *)kCFStreamSSLIsServer];
  5371. BOOL isServer = [isServerNumber boolValue];
  5372. #if TARGET_OS_IPHONE || (__MAC_OS_X_VERSION_MIN_REQUIRED >= 1080)
  5373. {
  5374. if (isServer)
  5375. sslContext = SSLCreateContext(kCFAllocatorDefault, kSSLServerSide, kSSLStreamType);
  5376. else
  5377. sslContext = SSLCreateContext(kCFAllocatorDefault, kSSLClientSide, kSSLStreamType);
  5378. if (sslContext == NULL)
  5379. {
  5380. [self closeWithError:[self otherError:@"Error in SSLCreateContext"]];
  5381. return;
  5382. }
  5383. }
  5384. #else // (__MAC_OS_X_VERSION_MIN_REQUIRED < 1080)
  5385. {
  5386. status = SSLNewContext(isServer, &sslContext);
  5387. if (status != noErr)
  5388. {
  5389. [self closeWithError:[self otherError:@"Error in SSLNewContext"]];
  5390. return;
  5391. }
  5392. }
  5393. #endif
  5394. status = SSLSetIOFuncs(sslContext, &SSLReadFunction, &SSLWriteFunction);
  5395. if (status != noErr)
  5396. {
  5397. [self closeWithError:[self otherError:@"Error in SSLSetIOFuncs"]];
  5398. return;
  5399. }
  5400. status = SSLSetConnection(sslContext, (__bridge SSLConnectionRef)self);
  5401. if (status != noErr)
  5402. {
  5403. [self closeWithError:[self otherError:@"Error in SSLSetConnection"]];
  5404. return;
  5405. }
  5406. NSNumber *shouldManuallyEvaluateTrust = [tlsSettings objectForKey:GCDAsyncSocketManuallyEvaluateTrust];
  5407. if ([shouldManuallyEvaluateTrust boolValue])
  5408. {
  5409. if (isServer)
  5410. {
  5411. [self closeWithError:[self otherError:@"Manual trust validation is not supported for server sockets"]];
  5412. return;
  5413. }
  5414. status = SSLSetSessionOption(sslContext, kSSLSessionOptionBreakOnServerAuth, true);
  5415. if (status != noErr)
  5416. {
  5417. [self closeWithError:[self otherError:@"Error in SSLSetSessionOption"]];
  5418. return;
  5419. }
  5420. #if !TARGET_OS_IPHONE && (__MAC_OS_X_VERSION_MIN_REQUIRED < 1080)
  5421. // Note from Apple's documentation:
  5422. //
  5423. // It is only necessary to call SSLSetEnableCertVerify on the Mac prior to OS X 10.8.
  5424. // On OS X 10.8 and later setting kSSLSessionOptionBreakOnServerAuth always disables the
  5425. // built-in trust evaluation. All versions of iOS behave like OS X 10.8 and thus
  5426. // SSLSetEnableCertVerify is not available on that platform at all.
  5427. status = SSLSetEnableCertVerify(sslContext, NO);
  5428. if (status != noErr)
  5429. {
  5430. [self closeWithError:[self otherError:@"Error in SSLSetEnableCertVerify"]];
  5431. return;
  5432. }
  5433. #endif
  5434. }
  5435. // Configure SSLContext from given settings
  5436. //
  5437. // Checklist:
  5438. // 1. kCFStreamSSLPeerName
  5439. // 2. kCFStreamSSLCertificates
  5440. // 3. GCDAsyncSocketSSLPeerID
  5441. // 4. GCDAsyncSocketSSLProtocolVersionMin
  5442. // 5. GCDAsyncSocketSSLProtocolVersionMax
  5443. // 6. GCDAsyncSocketSSLSessionOptionFalseStart
  5444. // 7. GCDAsyncSocketSSLSessionOptionSendOneByteRecord
  5445. // 8. GCDAsyncSocketSSLCipherSuites
  5446. // 9. GCDAsyncSocketSSLDiffieHellmanParameters (Mac)
  5447. // 10. GCDAsyncSocketSSLALPN
  5448. //
  5449. // Deprecated (throw error):
  5450. // 10. kCFStreamSSLAllowsAnyRoot
  5451. // 11. kCFStreamSSLAllowsExpiredRoots
  5452. // 12. kCFStreamSSLAllowsExpiredCertificates
  5453. // 13. kCFStreamSSLValidatesCertificateChain
  5454. // 14. kCFStreamSSLLevel
  5455. NSObject *value;
  5456. // 1. kCFStreamSSLPeerName
  5457. value = [tlsSettings objectForKey:(__bridge NSString *)kCFStreamSSLPeerName];
  5458. if ([value isKindOfClass:[NSString class]])
  5459. {
  5460. NSString *peerName = (NSString *)value;
  5461. const char *peer = [peerName UTF8String];
  5462. size_t peerLen = strlen(peer);
  5463. status = SSLSetPeerDomainName(sslContext, peer, peerLen);
  5464. if (status != noErr)
  5465. {
  5466. [self closeWithError:[self otherError:@"Error in SSLSetPeerDomainName"]];
  5467. return;
  5468. }
  5469. }
  5470. else if (value)
  5471. {
  5472. NSAssert(NO, @"Invalid value for kCFStreamSSLPeerName. Value must be of type NSString.");
  5473. [self closeWithError:[self otherError:@"Invalid value for kCFStreamSSLPeerName."]];
  5474. return;
  5475. }
  5476. // 2. kCFStreamSSLCertificates
  5477. value = [tlsSettings objectForKey:(__bridge NSString *)kCFStreamSSLCertificates];
  5478. if ([value isKindOfClass:[NSArray class]])
  5479. {
  5480. NSArray *certs = (NSArray *)value;
  5481. status = SSLSetCertificate(sslContext, (__bridge CFArrayRef)certs);
  5482. if (status != noErr)
  5483. {
  5484. [self closeWithError:[self otherError:@"Error in SSLSetCertificate"]];
  5485. return;
  5486. }
  5487. }
  5488. else if (value)
  5489. {
  5490. NSAssert(NO, @"Invalid value for kCFStreamSSLCertificates. Value must be of type NSArray.");
  5491. [self closeWithError:[self otherError:@"Invalid value for kCFStreamSSLCertificates."]];
  5492. return;
  5493. }
  5494. // 3. GCDAsyncSocketSSLPeerID
  5495. value = [tlsSettings objectForKey:GCDAsyncSocketSSLPeerID];
  5496. if ([value isKindOfClass:[NSData class]])
  5497. {
  5498. NSData *peerIdData = (NSData *)value;
  5499. status = SSLSetPeerID(sslContext, [peerIdData bytes], [peerIdData length]);
  5500. if (status != noErr)
  5501. {
  5502. [self closeWithError:[self otherError:@"Error in SSLSetPeerID"]];
  5503. return;
  5504. }
  5505. }
  5506. else if (value)
  5507. {
  5508. NSAssert(NO, @"Invalid value for GCDAsyncSocketSSLPeerID. Value must be of type NSData."
  5509. @" (You can convert strings to data using a method like"
  5510. @" [string dataUsingEncoding:NSUTF8StringEncoding])");
  5511. [self closeWithError:[self otherError:@"Invalid value for GCDAsyncSocketSSLPeerID."]];
  5512. return;
  5513. }
  5514. // 4. GCDAsyncSocketSSLProtocolVersionMin
  5515. value = [tlsSettings objectForKey:GCDAsyncSocketSSLProtocolVersionMin];
  5516. if ([value isKindOfClass:[NSNumber class]])
  5517. {
  5518. SSLProtocol minProtocol = (SSLProtocol)[(NSNumber *)value intValue];
  5519. if (minProtocol != kSSLProtocolUnknown)
  5520. {
  5521. status = SSLSetProtocolVersionMin(sslContext, minProtocol);
  5522. if (status != noErr)
  5523. {
  5524. [self closeWithError:[self otherError:@"Error in SSLSetProtocolVersionMin"]];
  5525. return;
  5526. }
  5527. }
  5528. }
  5529. else if (value)
  5530. {
  5531. NSAssert(NO, @"Invalid value for GCDAsyncSocketSSLProtocolVersionMin. Value must be of type NSNumber.");
  5532. [self closeWithError:[self otherError:@"Invalid value for GCDAsyncSocketSSLProtocolVersionMin."]];
  5533. return;
  5534. }
  5535. // 5. GCDAsyncSocketSSLProtocolVersionMax
  5536. value = [tlsSettings objectForKey:GCDAsyncSocketSSLProtocolVersionMax];
  5537. if ([value isKindOfClass:[NSNumber class]])
  5538. {
  5539. SSLProtocol maxProtocol = (SSLProtocol)[(NSNumber *)value intValue];
  5540. if (maxProtocol != kSSLProtocolUnknown)
  5541. {
  5542. status = SSLSetProtocolVersionMax(sslContext, maxProtocol);
  5543. if (status != noErr)
  5544. {
  5545. [self closeWithError:[self otherError:@"Error in SSLSetProtocolVersionMax"]];
  5546. return;
  5547. }
  5548. }
  5549. }
  5550. else if (value)
  5551. {
  5552. NSAssert(NO, @"Invalid value for GCDAsyncSocketSSLProtocolVersionMax. Value must be of type NSNumber.");
  5553. [self closeWithError:[self otherError:@"Invalid value for GCDAsyncSocketSSLProtocolVersionMax."]];
  5554. return;
  5555. }
  5556. // 6. GCDAsyncSocketSSLSessionOptionFalseStart
  5557. value = [tlsSettings objectForKey:GCDAsyncSocketSSLSessionOptionFalseStart];
  5558. if ([value isKindOfClass:[NSNumber class]])
  5559. {
  5560. NSNumber *falseStart = (NSNumber *)value;
  5561. status = SSLSetSessionOption(sslContext, kSSLSessionOptionFalseStart, [falseStart boolValue]);
  5562. if (status != noErr)
  5563. {
  5564. [self closeWithError:[self otherError:@"Error in SSLSetSessionOption (kSSLSessionOptionFalseStart)"]];
  5565. return;
  5566. }
  5567. }
  5568. else if (value)
  5569. {
  5570. NSAssert(NO, @"Invalid value for GCDAsyncSocketSSLSessionOptionFalseStart. Value must be of type NSNumber.");
  5571. [self closeWithError:[self otherError:@"Invalid value for GCDAsyncSocketSSLSessionOptionFalseStart."]];
  5572. return;
  5573. }
  5574. // 7. GCDAsyncSocketSSLSessionOptionSendOneByteRecord
  5575. value = [tlsSettings objectForKey:GCDAsyncSocketSSLSessionOptionSendOneByteRecord];
  5576. if ([value isKindOfClass:[NSNumber class]])
  5577. {
  5578. NSNumber *oneByteRecord = (NSNumber *)value;
  5579. status = SSLSetSessionOption(sslContext, kSSLSessionOptionSendOneByteRecord, [oneByteRecord boolValue]);
  5580. if (status != noErr)
  5581. {
  5582. [self closeWithError:
  5583. [self otherError:@"Error in SSLSetSessionOption (kSSLSessionOptionSendOneByteRecord)"]];
  5584. return;
  5585. }
  5586. }
  5587. else if (value)
  5588. {
  5589. NSAssert(NO, @"Invalid value for GCDAsyncSocketSSLSessionOptionSendOneByteRecord."
  5590. @" Value must be of type NSNumber.");
  5591. [self closeWithError:[self otherError:@"Invalid value for GCDAsyncSocketSSLSessionOptionSendOneByteRecord."]];
  5592. return;
  5593. }
  5594. // 8. GCDAsyncSocketSSLCipherSuites
  5595. value = [tlsSettings objectForKey:GCDAsyncSocketSSLCipherSuites];
  5596. if ([value isKindOfClass:[NSArray class]])
  5597. {
  5598. NSArray *cipherSuites = (NSArray *)value;
  5599. NSUInteger numberCiphers = [cipherSuites count];
  5600. SSLCipherSuite ciphers[numberCiphers];
  5601. NSUInteger cipherIndex;
  5602. for (cipherIndex = 0; cipherIndex < numberCiphers; cipherIndex++)
  5603. {
  5604. NSNumber *cipherObject = [cipherSuites objectAtIndex:cipherIndex];
  5605. ciphers[cipherIndex] = (SSLCipherSuite)[cipherObject unsignedIntValue];
  5606. }
  5607. status = SSLSetEnabledCiphers(sslContext, ciphers, numberCiphers);
  5608. if (status != noErr)
  5609. {
  5610. [self closeWithError:[self otherError:@"Error in SSLSetEnabledCiphers"]];
  5611. return;
  5612. }
  5613. }
  5614. else if (value)
  5615. {
  5616. NSAssert(NO, @"Invalid value for GCDAsyncSocketSSLCipherSuites. Value must be of type NSArray.");
  5617. [self closeWithError:[self otherError:@"Invalid value for GCDAsyncSocketSSLCipherSuites."]];
  5618. return;
  5619. }
  5620. // 9. GCDAsyncSocketSSLDiffieHellmanParameters
  5621. #if !TARGET_OS_IPHONE
  5622. value = [tlsSettings objectForKey:GCDAsyncSocketSSLDiffieHellmanParameters];
  5623. if ([value isKindOfClass:[NSData class]])
  5624. {
  5625. NSData *diffieHellmanData = (NSData *)value;
  5626. status = SSLSetDiffieHellmanParams(sslContext, [diffieHellmanData bytes], [diffieHellmanData length]);
  5627. if (status != noErr)
  5628. {
  5629. [self closeWithError:[self otherError:@"Error in SSLSetDiffieHellmanParams"]];
  5630. return;
  5631. }
  5632. }
  5633. else if (value)
  5634. {
  5635. NSAssert(NO, @"Invalid value for GCDAsyncSocketSSLDiffieHellmanParameters. Value must be of type NSData.");
  5636. [self closeWithError:[self otherError:@"Invalid value for GCDAsyncSocketSSLDiffieHellmanParameters."]];
  5637. return;
  5638. }
  5639. #endif
  5640. // 10. kCFStreamSSLCertificates
  5641. value = [tlsSettings objectForKey:GCDAsyncSocketSSLALPN];
  5642. if ([value isKindOfClass:[NSArray class]])
  5643. {
  5644. if (@available(iOS 11.0, macOS 10.13, tvOS 11.0, *))
  5645. {
  5646. CFArrayRef protocols = (__bridge CFArrayRef)((NSArray *) value);
  5647. status = SSLSetALPNProtocols(sslContext, protocols);
  5648. if (status != noErr)
  5649. {
  5650. [self closeWithError:[self otherError:@"Error in SSLSetALPNProtocols"]];
  5651. return;
  5652. }
  5653. }
  5654. else
  5655. {
  5656. NSAssert(NO, @"Security option unavailable - GCDAsyncSocketSSLALPN"
  5657. @" - iOS 11.0, macOS 10.13 required");
  5658. [self closeWithError:[self otherError:@"Security option unavailable - GCDAsyncSocketSSLALPN"]];
  5659. }
  5660. }
  5661. else if (value)
  5662. {
  5663. NSAssert(NO, @"Invalid value for GCDAsyncSocketSSLALPN. Value must be of type NSArray.");
  5664. [self closeWithError:[self otherError:@"Invalid value for GCDAsyncSocketSSLALPN."]];
  5665. return;
  5666. }
  5667. // DEPRECATED checks
  5668. // 10. kCFStreamSSLAllowsAnyRoot
  5669. #pragma clang diagnostic push
  5670. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  5671. value = [tlsSettings objectForKey:(__bridge NSString *)kCFStreamSSLAllowsAnyRoot];
  5672. #pragma clang diagnostic pop
  5673. if (value)
  5674. {
  5675. NSAssert(NO, @"Security option unavailable - kCFStreamSSLAllowsAnyRoot"
  5676. @" - You must use manual trust evaluation");
  5677. [self closeWithError:[self otherError:@"Security option unavailable - kCFStreamSSLAllowsAnyRoot"]];
  5678. return;
  5679. }
  5680. // 11. kCFStreamSSLAllowsExpiredRoots
  5681. #pragma clang diagnostic push
  5682. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  5683. value = [tlsSettings objectForKey:(__bridge NSString *)kCFStreamSSLAllowsExpiredRoots];
  5684. #pragma clang diagnostic pop
  5685. if (value)
  5686. {
  5687. NSAssert(NO, @"Security option unavailable - kCFStreamSSLAllowsExpiredRoots"
  5688. @" - You must use manual trust evaluation");
  5689. [self closeWithError:[self otherError:@"Security option unavailable - kCFStreamSSLAllowsExpiredRoots"]];
  5690. return;
  5691. }
  5692. // 12. kCFStreamSSLValidatesCertificateChain
  5693. #pragma clang diagnostic push
  5694. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  5695. value = [tlsSettings objectForKey:(__bridge NSString *)kCFStreamSSLValidatesCertificateChain];
  5696. #pragma clang diagnostic pop
  5697. if (value)
  5698. {
  5699. NSAssert(NO, @"Security option unavailable - kCFStreamSSLValidatesCertificateChain"
  5700. @" - You must use manual trust evaluation");
  5701. [self closeWithError:[self otherError:@"Security option unavailable - kCFStreamSSLValidatesCertificateChain"]];
  5702. return;
  5703. }
  5704. // 13. kCFStreamSSLAllowsExpiredCertificates
  5705. #pragma clang diagnostic push
  5706. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  5707. value = [tlsSettings objectForKey:(__bridge NSString *)kCFStreamSSLAllowsExpiredCertificates];
  5708. #pragma clang diagnostic pop
  5709. if (value)
  5710. {
  5711. NSAssert(NO, @"Security option unavailable - kCFStreamSSLAllowsExpiredCertificates"
  5712. @" - You must use manual trust evaluation");
  5713. [self closeWithError:[self otherError:@"Security option unavailable - kCFStreamSSLAllowsExpiredCertificates"]];
  5714. return;
  5715. }
  5716. // 14. kCFStreamSSLLevel
  5717. #pragma clang diagnostic push
  5718. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  5719. value = [tlsSettings objectForKey:(__bridge NSString *)kCFStreamSSLLevel];
  5720. #pragma clang diagnostic pop
  5721. if (value)
  5722. {
  5723. NSAssert(NO, @"Security option unavailable - kCFStreamSSLLevel"
  5724. @" - You must use GCDAsyncSocketSSLProtocolVersionMin & GCDAsyncSocketSSLProtocolVersionMax");
  5725. [self closeWithError:[self otherError:@"Security option unavailable - kCFStreamSSLLevel"]];
  5726. return;
  5727. }
  5728. // Setup the sslPreBuffer
  5729. //
  5730. // Any data in the preBuffer needs to be moved into the sslPreBuffer,
  5731. // as this data is now part of the secure read stream.
  5732. sslPreBuffer = [[GCDAsyncSocketPreBuffer alloc] initWithCapacity:(1024 * 4)];
  5733. size_t preBufferLength = [preBuffer availableBytes];
  5734. if (preBufferLength > 0)
  5735. {
  5736. [sslPreBuffer ensureCapacityForWrite:preBufferLength];
  5737. memcpy([sslPreBuffer writeBuffer], [preBuffer readBuffer], preBufferLength);
  5738. [preBuffer didRead:preBufferLength];
  5739. [sslPreBuffer didWrite:preBufferLength];
  5740. }
  5741. sslErrCode = lastSSLHandshakeError = noErr;
  5742. // Start the SSL Handshake process
  5743. [self ssl_continueSSLHandshake];
  5744. }
  5745. - (void)ssl_continueSSLHandshake
  5746. {
  5747. LogTrace();
  5748. // If the return value is noErr, the session is ready for normal secure communication.
  5749. // If the return value is errSSLWouldBlock, the SSLHandshake function must be called again.
  5750. // If the return value is errSSLServerAuthCompleted, we ask delegate if we should trust the
  5751. // server and then call SSLHandshake again to resume the handshake or close the connection
  5752. // errSSLPeerBadCert SSL error.
  5753. // Otherwise, the return value indicates an error code.
  5754. OSStatus status = SSLHandshake(sslContext);
  5755. lastSSLHandshakeError = status;
  5756. if (status == noErr)
  5757. {
  5758. LogVerbose(@"SSLHandshake complete");
  5759. flags &= ~kStartingReadTLS;
  5760. flags &= ~kStartingWriteTLS;
  5761. flags |= kSocketSecure;
  5762. __strong id<GCDAsyncSocketDelegate> theDelegate = delegate;
  5763. if (delegateQueue && [theDelegate respondsToSelector:@selector(socketDidSecure:)])
  5764. {
  5765. dispatch_async(delegateQueue, ^{ @autoreleasepool {
  5766. [theDelegate socketDidSecure:self];
  5767. }});
  5768. }
  5769. [self endCurrentRead];
  5770. [self endCurrentWrite];
  5771. [self maybeDequeueRead];
  5772. [self maybeDequeueWrite];
  5773. }
  5774. else if (status == errSSLPeerAuthCompleted)
  5775. {
  5776. LogVerbose(@"SSLHandshake peerAuthCompleted - awaiting delegate approval");
  5777. __block SecTrustRef trust = NULL;
  5778. status = SSLCopyPeerTrust(sslContext, &trust);
  5779. if (status != noErr)
  5780. {
  5781. [self closeWithError:[self sslError:status]];
  5782. return;
  5783. }
  5784. int aStateIndex = stateIndex;
  5785. dispatch_queue_t theSocketQueue = socketQueue;
  5786. __weak GCDAsyncSocket *weakSelf = self;
  5787. void (^comletionHandler)(BOOL) = ^(BOOL shouldTrust){ @autoreleasepool {
  5788. #pragma clang diagnostic push
  5789. #pragma clang diagnostic warning "-Wimplicit-retain-self"
  5790. dispatch_async(theSocketQueue, ^{ @autoreleasepool {
  5791. if (trust) {
  5792. CFRelease(trust);
  5793. trust = NULL;
  5794. }
  5795. __strong GCDAsyncSocket *strongSelf = weakSelf;
  5796. if (strongSelf)
  5797. {
  5798. [strongSelf ssl_shouldTrustPeer:shouldTrust stateIndex:aStateIndex];
  5799. }
  5800. }});
  5801. #pragma clang diagnostic pop
  5802. }};
  5803. __strong id<GCDAsyncSocketDelegate> theDelegate = delegate;
  5804. if (delegateQueue && [theDelegate respondsToSelector:@selector(socket:didReceiveTrust:completionHandler:)])
  5805. {
  5806. dispatch_async(delegateQueue, ^{ @autoreleasepool {
  5807. [theDelegate socket:self didReceiveTrust:trust completionHandler:comletionHandler];
  5808. }});
  5809. }
  5810. else
  5811. {
  5812. if (trust) {
  5813. CFRelease(trust);
  5814. trust = NULL;
  5815. }
  5816. NSString *msg = @"GCDAsyncSocketManuallyEvaluateTrust specified in tlsSettings,"
  5817. @" but delegate doesn't implement socket:shouldTrustPeer:";
  5818. [self closeWithError:[self otherError:msg]];
  5819. return;
  5820. }
  5821. }
  5822. else if (status == errSSLWouldBlock)
  5823. {
  5824. LogVerbose(@"SSLHandshake continues...");
  5825. // Handshake continues...
  5826. //
  5827. // This method will be called again from doReadData or doWriteData.
  5828. }
  5829. else
  5830. {
  5831. [self closeWithError:[self sslError:status]];
  5832. }
  5833. }
  5834. - (void)ssl_shouldTrustPeer:(BOOL)shouldTrust stateIndex:(int)aStateIndex
  5835. {
  5836. LogTrace();
  5837. if (aStateIndex != stateIndex)
  5838. {
  5839. LogInfo(@"Ignoring ssl_shouldTrustPeer - invalid state (maybe disconnected)");
  5840. // One of the following is true
  5841. // - the socket was disconnected
  5842. // - the startTLS operation timed out
  5843. // - the completionHandler was already invoked once
  5844. return;
  5845. }
  5846. // Increment stateIndex to ensure completionHandler can only be called once.
  5847. stateIndex++;
  5848. if (shouldTrust)
  5849. {
  5850. NSAssert(lastSSLHandshakeError == errSSLPeerAuthCompleted, @"ssl_shouldTrustPeer called when last error is %d and not errSSLPeerAuthCompleted", (int)lastSSLHandshakeError);
  5851. [self ssl_continueSSLHandshake];
  5852. }
  5853. else
  5854. {
  5855. [self closeWithError:[self sslError:errSSLPeerBadCert]];
  5856. }
  5857. }
  5858. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  5859. #pragma mark Security via CFStream
  5860. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  5861. #if TARGET_OS_IPHONE
  5862. - (void)cf_finishSSLHandshake
  5863. {
  5864. LogTrace();
  5865. if ((flags & kStartingReadTLS) && (flags & kStartingWriteTLS))
  5866. {
  5867. flags &= ~kStartingReadTLS;
  5868. flags &= ~kStartingWriteTLS;
  5869. flags |= kSocketSecure;
  5870. __strong id<GCDAsyncSocketDelegate> theDelegate = delegate;
  5871. if (delegateQueue && [theDelegate respondsToSelector:@selector(socketDidSecure:)])
  5872. {
  5873. dispatch_async(delegateQueue, ^{ @autoreleasepool {
  5874. [theDelegate socketDidSecure:self];
  5875. }});
  5876. }
  5877. [self endCurrentRead];
  5878. [self endCurrentWrite];
  5879. [self maybeDequeueRead];
  5880. [self maybeDequeueWrite];
  5881. }
  5882. }
  5883. - (void)cf_abortSSLHandshake:(NSError *)error
  5884. {
  5885. LogTrace();
  5886. if ((flags & kStartingReadTLS) && (flags & kStartingWriteTLS))
  5887. {
  5888. flags &= ~kStartingReadTLS;
  5889. flags &= ~kStartingWriteTLS;
  5890. [self closeWithError:error];
  5891. }
  5892. }
  5893. - (void)cf_startTLS
  5894. {
  5895. LogTrace();
  5896. LogVerbose(@"Starting TLS (via CFStream)...");
  5897. if ([preBuffer availableBytes] > 0)
  5898. {
  5899. NSString *msg = @"Invalid TLS transition. Handshake has already been read from socket.";
  5900. [self closeWithError:[self otherError:msg]];
  5901. return;
  5902. }
  5903. [self suspendReadSource];
  5904. [self suspendWriteSource];
  5905. socketFDBytesAvailable = 0;
  5906. flags &= ~kSocketCanAcceptBytes;
  5907. flags &= ~kSecureSocketHasBytesAvailable;
  5908. flags |= kUsingCFStreamForTLS;
  5909. if (![self createReadAndWriteStream])
  5910. {
  5911. [self closeWithError:[self otherError:@"Error in CFStreamCreatePairWithSocket"]];
  5912. return;
  5913. }
  5914. if (![self registerForStreamCallbacksIncludingReadWrite:YES])
  5915. {
  5916. [self closeWithError:[self otherError:@"Error in CFStreamSetClient"]];
  5917. return;
  5918. }
  5919. if (![self addStreamsToRunLoop])
  5920. {
  5921. [self closeWithError:[self otherError:@"Error in CFStreamScheduleWithRunLoop"]];
  5922. return;
  5923. }
  5924. NSAssert([currentRead isKindOfClass:[GCDAsyncSpecialPacket class]], @"Invalid read packet for startTLS");
  5925. NSAssert([currentWrite isKindOfClass:[GCDAsyncSpecialPacket class]], @"Invalid write packet for startTLS");
  5926. GCDAsyncSpecialPacket *tlsPacket = (GCDAsyncSpecialPacket *)currentRead;
  5927. CFDictionaryRef tlsSettings = (__bridge CFDictionaryRef)tlsPacket->tlsSettings;
  5928. // Getting an error concerning kCFStreamPropertySSLSettings ?
  5929. // You need to add the CFNetwork framework to your iOS application.
  5930. BOOL r1 = CFReadStreamSetProperty(readStream, kCFStreamPropertySSLSettings, tlsSettings);
  5931. BOOL r2 = CFWriteStreamSetProperty(writeStream, kCFStreamPropertySSLSettings, tlsSettings);
  5932. // For some reason, starting around the time of iOS 4.3,
  5933. // the first call to set the kCFStreamPropertySSLSettings will return true,
  5934. // but the second will return false.
  5935. //
  5936. // Order doesn't seem to matter.
  5937. // So you could call CFReadStreamSetProperty and then CFWriteStreamSetProperty, or you could reverse the order.
  5938. // Either way, the first call will return true, and the second returns false.
  5939. //
  5940. // Interestingly, this doesn't seem to affect anything.
  5941. // Which is not altogether unusual, as the documentation seems to suggest that (for many settings)
  5942. // setting it on one side of the stream automatically sets it for the other side of the stream.
  5943. //
  5944. // Although there isn't anything in the documentation to suggest that the second attempt would fail.
  5945. //
  5946. // Furthermore, this only seems to affect streams that are negotiating a security upgrade.
  5947. // In other words, the socket gets connected, there is some back-and-forth communication over the unsecure
  5948. // connection, and then a startTLS is issued.
  5949. // So this mostly affects newer protocols (XMPP, IMAP) as opposed to older protocols (HTTPS).
  5950. if (!r1 && !r2) // Yes, the && is correct - workaround for apple bug.
  5951. {
  5952. [self closeWithError:[self otherError:@"Error in CFStreamSetProperty"]];
  5953. return;
  5954. }
  5955. if (![self openStreams])
  5956. {
  5957. [self closeWithError:[self otherError:@"Error in CFStreamOpen"]];
  5958. return;
  5959. }
  5960. LogVerbose(@"Waiting for SSL Handshake to complete...");
  5961. }
  5962. #endif
  5963. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  5964. #pragma mark CFStream
  5965. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  5966. #if TARGET_OS_IPHONE
  5967. + (void)ignore:(id)_
  5968. {}
  5969. + (void)startCFStreamThreadIfNeeded
  5970. {
  5971. LogTrace();
  5972. static dispatch_once_t predicate;
  5973. dispatch_once(&predicate, ^{
  5974. cfstreamThreadRetainCount = 0;
  5975. cfstreamThreadSetupQueue = dispatch_queue_create("GCDAsyncSocket-CFStreamThreadSetup", DISPATCH_QUEUE_SERIAL);
  5976. });
  5977. dispatch_sync(cfstreamThreadSetupQueue, ^{ @autoreleasepool {
  5978. if (++cfstreamThreadRetainCount == 1)
  5979. {
  5980. cfstreamThread = [[NSThread alloc] initWithTarget:self
  5981. selector:@selector(cfstreamThread:)
  5982. object:nil];
  5983. [cfstreamThread start];
  5984. }
  5985. }});
  5986. }
  5987. + (void)stopCFStreamThreadIfNeeded
  5988. {
  5989. LogTrace();
  5990. // The creation of the cfstreamThread is relatively expensive.
  5991. // So we'd like to keep it available for recycling.
  5992. // However, there's a tradeoff here, because it shouldn't remain alive forever.
  5993. // So what we're going to do is use a little delay before taking it down.
  5994. // This way it can be reused properly in situations where multiple sockets are continually in flux.
  5995. int delayInSeconds = 30;
  5996. dispatch_time_t when = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
  5997. dispatch_after(when, cfstreamThreadSetupQueue, ^{ @autoreleasepool {
  5998. #pragma clang diagnostic push
  5999. #pragma clang diagnostic warning "-Wimplicit-retain-self"
  6000. if (cfstreamThreadRetainCount == 0)
  6001. {
  6002. LogWarn(@"Logic error concerning cfstreamThread start / stop");
  6003. return_from_block;
  6004. }
  6005. if (--cfstreamThreadRetainCount == 0)
  6006. {
  6007. [cfstreamThread cancel]; // set isCancelled flag
  6008. // wake up the thread
  6009. [[self class] performSelector:@selector(ignore:)
  6010. onThread:cfstreamThread
  6011. withObject:[NSNull null]
  6012. waitUntilDone:NO];
  6013. cfstreamThread = nil;
  6014. }
  6015. #pragma clang diagnostic pop
  6016. }});
  6017. }
  6018. + (void)cfstreamThread:(id)unused { @autoreleasepool
  6019. {
  6020. [[NSThread currentThread] setName:GCDAsyncSocketThreadName];
  6021. LogInfo(@"CFStreamThread: Started");
  6022. // We can't run the run loop unless it has an associated input source or a timer.
  6023. // So we'll just create a timer that will never fire - unless the server runs for decades.
  6024. [NSTimer scheduledTimerWithTimeInterval:[[NSDate distantFuture] timeIntervalSinceNow]
  6025. target:self
  6026. selector:@selector(ignore:)
  6027. userInfo:nil
  6028. repeats:YES];
  6029. NSThread *currentThread = [NSThread currentThread];
  6030. NSRunLoop *currentRunLoop = [NSRunLoop currentRunLoop];
  6031. BOOL isCancelled = [currentThread isCancelled];
  6032. while (!isCancelled && [currentRunLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]])
  6033. {
  6034. isCancelled = [currentThread isCancelled];
  6035. }
  6036. LogInfo(@"CFStreamThread: Stopped");
  6037. }}
  6038. + (void)scheduleCFStreams:(GCDAsyncSocket *)asyncSocket
  6039. {
  6040. LogTrace();
  6041. NSAssert([NSThread currentThread] == cfstreamThread, @"Invoked on wrong thread");
  6042. CFRunLoopRef runLoop = CFRunLoopGetCurrent();
  6043. if (asyncSocket->readStream)
  6044. CFReadStreamScheduleWithRunLoop(asyncSocket->readStream, runLoop, kCFRunLoopDefaultMode);
  6045. if (asyncSocket->writeStream)
  6046. CFWriteStreamScheduleWithRunLoop(asyncSocket->writeStream, runLoop, kCFRunLoopDefaultMode);
  6047. }
  6048. + (void)unscheduleCFStreams:(GCDAsyncSocket *)asyncSocket
  6049. {
  6050. LogTrace();
  6051. NSAssert([NSThread currentThread] == cfstreamThread, @"Invoked on wrong thread");
  6052. CFRunLoopRef runLoop = CFRunLoopGetCurrent();
  6053. if (asyncSocket->readStream)
  6054. CFReadStreamUnscheduleFromRunLoop(asyncSocket->readStream, runLoop, kCFRunLoopDefaultMode);
  6055. if (asyncSocket->writeStream)
  6056. CFWriteStreamUnscheduleFromRunLoop(asyncSocket->writeStream, runLoop, kCFRunLoopDefaultMode);
  6057. }
  6058. static void CFReadStreamCallback (CFReadStreamRef stream, CFStreamEventType type, void *pInfo)
  6059. {
  6060. GCDAsyncSocket *asyncSocket = (__bridge GCDAsyncSocket *)pInfo;
  6061. switch(type)
  6062. {
  6063. case kCFStreamEventHasBytesAvailable:
  6064. {
  6065. dispatch_async(asyncSocket->socketQueue, ^{ @autoreleasepool {
  6066. LogCVerbose(@"CFReadStreamCallback - HasBytesAvailable");
  6067. if (asyncSocket->readStream != stream)
  6068. return_from_block;
  6069. if ((asyncSocket->flags & kStartingReadTLS) && (asyncSocket->flags & kStartingWriteTLS))
  6070. {
  6071. // If we set kCFStreamPropertySSLSettings before we opened the streams, this might be a lie.
  6072. // (A callback related to the tcp stream, but not to the SSL layer).
  6073. if (CFReadStreamHasBytesAvailable(asyncSocket->readStream))
  6074. {
  6075. asyncSocket->flags |= kSecureSocketHasBytesAvailable;
  6076. [asyncSocket cf_finishSSLHandshake];
  6077. }
  6078. }
  6079. else
  6080. {
  6081. asyncSocket->flags |= kSecureSocketHasBytesAvailable;
  6082. [asyncSocket doReadData];
  6083. }
  6084. }});
  6085. break;
  6086. }
  6087. default:
  6088. {
  6089. NSError *error = (__bridge_transfer NSError *)CFReadStreamCopyError(stream);
  6090. if (error == nil && type == kCFStreamEventEndEncountered)
  6091. {
  6092. error = [asyncSocket connectionClosedError];
  6093. }
  6094. dispatch_async(asyncSocket->socketQueue, ^{ @autoreleasepool {
  6095. LogCVerbose(@"CFReadStreamCallback - Other");
  6096. if (asyncSocket->readStream != stream)
  6097. return_from_block;
  6098. if ((asyncSocket->flags & kStartingReadTLS) && (asyncSocket->flags & kStartingWriteTLS))
  6099. {
  6100. [asyncSocket cf_abortSSLHandshake:error];
  6101. }
  6102. else
  6103. {
  6104. [asyncSocket closeWithError:error];
  6105. }
  6106. }});
  6107. break;
  6108. }
  6109. }
  6110. }
  6111. static void CFWriteStreamCallback (CFWriteStreamRef stream, CFStreamEventType type, void *pInfo)
  6112. {
  6113. GCDAsyncSocket *asyncSocket = (__bridge GCDAsyncSocket *)pInfo;
  6114. switch(type)
  6115. {
  6116. case kCFStreamEventCanAcceptBytes:
  6117. {
  6118. dispatch_async(asyncSocket->socketQueue, ^{ @autoreleasepool {
  6119. LogCVerbose(@"CFWriteStreamCallback - CanAcceptBytes");
  6120. if (asyncSocket->writeStream != stream)
  6121. return_from_block;
  6122. if ((asyncSocket->flags & kStartingReadTLS) && (asyncSocket->flags & kStartingWriteTLS))
  6123. {
  6124. // If we set kCFStreamPropertySSLSettings before we opened the streams, this might be a lie.
  6125. // (A callback related to the tcp stream, but not to the SSL layer).
  6126. if (CFWriteStreamCanAcceptBytes(asyncSocket->writeStream))
  6127. {
  6128. asyncSocket->flags |= kSocketCanAcceptBytes;
  6129. [asyncSocket cf_finishSSLHandshake];
  6130. }
  6131. }
  6132. else
  6133. {
  6134. asyncSocket->flags |= kSocketCanAcceptBytes;
  6135. [asyncSocket doWriteData];
  6136. }
  6137. }});
  6138. break;
  6139. }
  6140. default:
  6141. {
  6142. NSError *error = (__bridge_transfer NSError *)CFWriteStreamCopyError(stream);
  6143. if (error == nil && type == kCFStreamEventEndEncountered)
  6144. {
  6145. error = [asyncSocket connectionClosedError];
  6146. }
  6147. dispatch_async(asyncSocket->socketQueue, ^{ @autoreleasepool {
  6148. LogCVerbose(@"CFWriteStreamCallback - Other");
  6149. if (asyncSocket->writeStream != stream)
  6150. return_from_block;
  6151. if ((asyncSocket->flags & kStartingReadTLS) && (asyncSocket->flags & kStartingWriteTLS))
  6152. {
  6153. [asyncSocket cf_abortSSLHandshake:error];
  6154. }
  6155. else
  6156. {
  6157. [asyncSocket closeWithError:error];
  6158. }
  6159. }});
  6160. break;
  6161. }
  6162. }
  6163. }
  6164. - (BOOL)createReadAndWriteStream
  6165. {
  6166. LogTrace();
  6167. NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue");
  6168. if (readStream || writeStream)
  6169. {
  6170. // Streams already created
  6171. return YES;
  6172. }
  6173. int socketFD = (socket4FD != SOCKET_NULL) ? socket4FD : (socket6FD != SOCKET_NULL) ? socket6FD : socketUN;
  6174. if (socketFD == SOCKET_NULL)
  6175. {
  6176. // Cannot create streams without a file descriptor
  6177. return NO;
  6178. }
  6179. if (![self isConnected])
  6180. {
  6181. // Cannot create streams until file descriptor is connected
  6182. return NO;
  6183. }
  6184. LogVerbose(@"Creating read and write stream...");
  6185. CFStreamCreatePairWithSocket(NULL, (CFSocketNativeHandle)socketFD, &readStream, &writeStream);
  6186. // The kCFStreamPropertyShouldCloseNativeSocket property should be false by default (for our case).
  6187. // But let's not take any chances.
  6188. if (readStream)
  6189. CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanFalse);
  6190. if (writeStream)
  6191. CFWriteStreamSetProperty(writeStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanFalse);
  6192. if ((readStream == NULL) || (writeStream == NULL))
  6193. {
  6194. LogWarn(@"Unable to create read and write stream...");
  6195. if (readStream)
  6196. {
  6197. CFReadStreamClose(readStream);
  6198. CFRelease(readStream);
  6199. readStream = NULL;
  6200. }
  6201. if (writeStream)
  6202. {
  6203. CFWriteStreamClose(writeStream);
  6204. CFRelease(writeStream);
  6205. writeStream = NULL;
  6206. }
  6207. return NO;
  6208. }
  6209. return YES;
  6210. }
  6211. - (BOOL)registerForStreamCallbacksIncludingReadWrite:(BOOL)includeReadWrite
  6212. {
  6213. LogVerbose(@"%@ %@", THIS_METHOD, (includeReadWrite ? @"YES" : @"NO"));
  6214. NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue");
  6215. NSAssert((readStream != NULL && writeStream != NULL), @"Read/Write stream is null");
  6216. streamContext.version = 0;
  6217. streamContext.info = (__bridge void *)(self);
  6218. streamContext.retain = nil;
  6219. streamContext.release = nil;
  6220. streamContext.copyDescription = nil;
  6221. CFOptionFlags readStreamEvents = kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered;
  6222. if (includeReadWrite)
  6223. readStreamEvents |= kCFStreamEventHasBytesAvailable;
  6224. if (!CFReadStreamSetClient(readStream, readStreamEvents, &CFReadStreamCallback, &streamContext))
  6225. {
  6226. return NO;
  6227. }
  6228. CFOptionFlags writeStreamEvents = kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered;
  6229. if (includeReadWrite)
  6230. writeStreamEvents |= kCFStreamEventCanAcceptBytes;
  6231. if (!CFWriteStreamSetClient(writeStream, writeStreamEvents, &CFWriteStreamCallback, &streamContext))
  6232. {
  6233. return NO;
  6234. }
  6235. return YES;
  6236. }
  6237. - (BOOL)addStreamsToRunLoop
  6238. {
  6239. LogTrace();
  6240. NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue");
  6241. NSAssert((readStream != NULL && writeStream != NULL), @"Read/Write stream is null");
  6242. if (!(flags & kAddedStreamsToRunLoop))
  6243. {
  6244. LogVerbose(@"Adding streams to runloop...");
  6245. [[self class] startCFStreamThreadIfNeeded];
  6246. dispatch_sync(cfstreamThreadSetupQueue, ^{
  6247. [[self class] performSelector:@selector(scheduleCFStreams:)
  6248. onThread:cfstreamThread
  6249. withObject:self
  6250. waitUntilDone:YES];
  6251. });
  6252. flags |= kAddedStreamsToRunLoop;
  6253. }
  6254. return YES;
  6255. }
  6256. - (void)removeStreamsFromRunLoop
  6257. {
  6258. LogTrace();
  6259. NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue");
  6260. NSAssert((readStream != NULL && writeStream != NULL), @"Read/Write stream is null");
  6261. if (flags & kAddedStreamsToRunLoop)
  6262. {
  6263. LogVerbose(@"Removing streams from runloop...");
  6264. dispatch_sync(cfstreamThreadSetupQueue, ^{
  6265. [[self class] performSelector:@selector(unscheduleCFStreams:)
  6266. onThread:cfstreamThread
  6267. withObject:self
  6268. waitUntilDone:YES];
  6269. });
  6270. [[self class] stopCFStreamThreadIfNeeded];
  6271. flags &= ~kAddedStreamsToRunLoop;
  6272. }
  6273. }
  6274. - (BOOL)openStreams
  6275. {
  6276. LogTrace();
  6277. NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue");
  6278. NSAssert((readStream != NULL && writeStream != NULL), @"Read/Write stream is null");
  6279. CFStreamStatus readStatus = CFReadStreamGetStatus(readStream);
  6280. CFStreamStatus writeStatus = CFWriteStreamGetStatus(writeStream);
  6281. if ((readStatus == kCFStreamStatusNotOpen) || (writeStatus == kCFStreamStatusNotOpen))
  6282. {
  6283. LogVerbose(@"Opening read and write stream...");
  6284. BOOL r1 = CFReadStreamOpen(readStream);
  6285. BOOL r2 = CFWriteStreamOpen(writeStream);
  6286. if (!r1 || !r2)
  6287. {
  6288. LogError(@"Error in CFStreamOpen");
  6289. return NO;
  6290. }
  6291. }
  6292. return YES;
  6293. }
  6294. #endif
  6295. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  6296. #pragma mark Advanced
  6297. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  6298. /**
  6299. * See header file for big discussion of this method.
  6300. **/
  6301. - (BOOL)autoDisconnectOnClosedReadStream
  6302. {
  6303. // Note: YES means kAllowHalfDuplexConnection is OFF
  6304. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  6305. {
  6306. return ((config & kAllowHalfDuplexConnection) == 0);
  6307. }
  6308. else
  6309. {
  6310. __block BOOL result;
  6311. dispatch_sync(socketQueue, ^{
  6312. result = ((self->config & kAllowHalfDuplexConnection) == 0);
  6313. });
  6314. return result;
  6315. }
  6316. }
  6317. /**
  6318. * See header file for big discussion of this method.
  6319. **/
  6320. - (void)setAutoDisconnectOnClosedReadStream:(BOOL)flag
  6321. {
  6322. // Note: YES means kAllowHalfDuplexConnection is OFF
  6323. dispatch_block_t block = ^{
  6324. if (flag)
  6325. self->config &= ~kAllowHalfDuplexConnection;
  6326. else
  6327. self->config |= kAllowHalfDuplexConnection;
  6328. };
  6329. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  6330. block();
  6331. else
  6332. dispatch_async(socketQueue, block);
  6333. }
  6334. /**
  6335. * See header file for big discussion of this method.
  6336. **/
  6337. - (void)markSocketQueueTargetQueue:(dispatch_queue_t)socketNewTargetQueue
  6338. {
  6339. void *nonNullUnusedPointer = (__bridge void *)self;
  6340. dispatch_queue_set_specific(socketNewTargetQueue, IsOnSocketQueueOrTargetQueueKey, nonNullUnusedPointer, NULL);
  6341. }
  6342. /**
  6343. * See header file for big discussion of this method.
  6344. **/
  6345. - (void)unmarkSocketQueueTargetQueue:(dispatch_queue_t)socketOldTargetQueue
  6346. {
  6347. dispatch_queue_set_specific(socketOldTargetQueue, IsOnSocketQueueOrTargetQueueKey, NULL, NULL);
  6348. }
  6349. /**
  6350. * See header file for big discussion of this method.
  6351. **/
  6352. - (void)performBlock:(dispatch_block_t)block
  6353. {
  6354. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  6355. block();
  6356. else
  6357. dispatch_sync(socketQueue, block);
  6358. }
  6359. /**
  6360. * Questions? Have you read the header file?
  6361. **/
  6362. - (int)socketFD
  6363. {
  6364. if (!dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  6365. {
  6366. LogWarn(@"%@ - Method only available from within the context of a performBlock: invocation", THIS_METHOD);
  6367. return SOCKET_NULL;
  6368. }
  6369. if (socket4FD != SOCKET_NULL)
  6370. return socket4FD;
  6371. else
  6372. return socket6FD;
  6373. }
  6374. /**
  6375. * Questions? Have you read the header file?
  6376. **/
  6377. - (int)socket4FD
  6378. {
  6379. if (!dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  6380. {
  6381. LogWarn(@"%@ - Method only available from within the context of a performBlock: invocation", THIS_METHOD);
  6382. return SOCKET_NULL;
  6383. }
  6384. return socket4FD;
  6385. }
  6386. /**
  6387. * Questions? Have you read the header file?
  6388. **/
  6389. - (int)socket6FD
  6390. {
  6391. if (!dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  6392. {
  6393. LogWarn(@"%@ - Method only available from within the context of a performBlock: invocation", THIS_METHOD);
  6394. return SOCKET_NULL;
  6395. }
  6396. return socket6FD;
  6397. }
  6398. #if TARGET_OS_IPHONE
  6399. /**
  6400. * Questions? Have you read the header file?
  6401. **/
  6402. - (CFReadStreamRef)readStream
  6403. {
  6404. if (!dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  6405. {
  6406. LogWarn(@"%@ - Method only available from within the context of a performBlock: invocation", THIS_METHOD);
  6407. return NULL;
  6408. }
  6409. if (readStream == NULL)
  6410. [self createReadAndWriteStream];
  6411. return readStream;
  6412. }
  6413. /**
  6414. * Questions? Have you read the header file?
  6415. **/
  6416. - (CFWriteStreamRef)writeStream
  6417. {
  6418. if (!dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  6419. {
  6420. LogWarn(@"%@ - Method only available from within the context of a performBlock: invocation", THIS_METHOD);
  6421. return NULL;
  6422. }
  6423. if (writeStream == NULL)
  6424. [self createReadAndWriteStream];
  6425. return writeStream;
  6426. }
  6427. - (BOOL)enableBackgroundingOnSocketWithCaveat:(BOOL)caveat
  6428. {
  6429. if (![self createReadAndWriteStream])
  6430. {
  6431. // Error occurred creating streams (perhaps socket isn't open)
  6432. return NO;
  6433. }
  6434. BOOL r1, r2;
  6435. LogVerbose(@"Enabling backgrouding on socket");
  6436. #pragma clang diagnostic push
  6437. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  6438. r1 = CFReadStreamSetProperty(readStream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP);
  6439. r2 = CFWriteStreamSetProperty(writeStream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP);
  6440. #pragma clang diagnostic pop
  6441. if (!r1 || !r2)
  6442. {
  6443. return NO;
  6444. }
  6445. if (!caveat)
  6446. {
  6447. if (![self openStreams])
  6448. {
  6449. return NO;
  6450. }
  6451. }
  6452. return YES;
  6453. }
  6454. /**
  6455. * Questions? Have you read the header file?
  6456. **/
  6457. - (BOOL)enableBackgroundingOnSocket
  6458. {
  6459. LogTrace();
  6460. if (!dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  6461. {
  6462. LogWarn(@"%@ - Method only available from within the context of a performBlock: invocation", THIS_METHOD);
  6463. return NO;
  6464. }
  6465. return [self enableBackgroundingOnSocketWithCaveat:NO];
  6466. }
  6467. - (BOOL)enableBackgroundingOnSocketWithCaveat // Deprecated in iOS 4.???
  6468. {
  6469. // This method was created as a workaround for a bug in iOS.
  6470. // Apple has since fixed this bug.
  6471. // I'm not entirely sure which version of iOS they fixed it in...
  6472. LogTrace();
  6473. if (!dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  6474. {
  6475. LogWarn(@"%@ - Method only available from within the context of a performBlock: invocation", THIS_METHOD);
  6476. return NO;
  6477. }
  6478. return [self enableBackgroundingOnSocketWithCaveat:YES];
  6479. }
  6480. #endif
  6481. - (SSLContextRef)sslContext
  6482. {
  6483. if (!dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  6484. {
  6485. LogWarn(@"%@ - Method only available from within the context of a performBlock: invocation", THIS_METHOD);
  6486. return NULL;
  6487. }
  6488. return sslContext;
  6489. }
  6490. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  6491. #pragma mark Class Utilities
  6492. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  6493. + (NSMutableArray *)lookupHost:(NSString *)host port:(uint16_t)port error:(NSError **)errPtr
  6494. {
  6495. LogTrace();
  6496. NSMutableArray *addresses = nil;
  6497. NSError *error = nil;
  6498. if ([host isEqualToString:@"localhost"] || [host isEqualToString:@"loopback"])
  6499. {
  6500. // Use LOOPBACK address
  6501. struct sockaddr_in nativeAddr4;
  6502. nativeAddr4.sin_len = sizeof(struct sockaddr_in);
  6503. nativeAddr4.sin_family = AF_INET;
  6504. nativeAddr4.sin_port = htons(port);
  6505. nativeAddr4.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  6506. memset(&(nativeAddr4.sin_zero), 0, sizeof(nativeAddr4.sin_zero));
  6507. struct sockaddr_in6 nativeAddr6;
  6508. nativeAddr6.sin6_len = sizeof(struct sockaddr_in6);
  6509. nativeAddr6.sin6_family = AF_INET6;
  6510. nativeAddr6.sin6_port = htons(port);
  6511. nativeAddr6.sin6_flowinfo = 0;
  6512. nativeAddr6.sin6_addr = in6addr_loopback;
  6513. nativeAddr6.sin6_scope_id = 0;
  6514. // Wrap the native address structures
  6515. NSData *address4 = [NSData dataWithBytes:&nativeAddr4 length:sizeof(nativeAddr4)];
  6516. NSData *address6 = [NSData dataWithBytes:&nativeAddr6 length:sizeof(nativeAddr6)];
  6517. addresses = [NSMutableArray arrayWithCapacity:2];
  6518. [addresses addObject:address4];
  6519. [addresses addObject:address6];
  6520. }
  6521. else
  6522. {
  6523. NSString *portStr = [NSString stringWithFormat:@"%hu", port];
  6524. struct addrinfo hints, *res, *res0;
  6525. memset(&hints, 0, sizeof(hints));
  6526. hints.ai_family = PF_UNSPEC;
  6527. hints.ai_socktype = SOCK_STREAM;
  6528. hints.ai_protocol = IPPROTO_TCP;
  6529. int gai_error = getaddrinfo([host UTF8String], [portStr UTF8String], &hints, &res0);
  6530. if (gai_error)
  6531. {
  6532. error = [self gaiError:gai_error];
  6533. }
  6534. else
  6535. {
  6536. NSUInteger capacity = 0;
  6537. for (res = res0; res; res = res->ai_next)
  6538. {
  6539. if (res->ai_family == AF_INET || res->ai_family == AF_INET6) {
  6540. capacity++;
  6541. }
  6542. }
  6543. addresses = [NSMutableArray arrayWithCapacity:capacity];
  6544. for (res = res0; res; res = res->ai_next)
  6545. {
  6546. if (res->ai_family == AF_INET)
  6547. {
  6548. // Found IPv4 address.
  6549. // Wrap the native address structure, and add to results.
  6550. NSData *address4 = [NSData dataWithBytes:res->ai_addr length:res->ai_addrlen];
  6551. [addresses addObject:address4];
  6552. }
  6553. else if (res->ai_family == AF_INET6)
  6554. {
  6555. // Fixes connection issues with IPv6
  6556. // https://github.com/robbiehanson/CocoaAsyncSocket/issues/429#issuecomment-222477158
  6557. // Found IPv6 address.
  6558. // Wrap the native address structure, and add to results.
  6559. struct sockaddr_in6 *sockaddr = (struct sockaddr_in6 *)(void *)res->ai_addr;
  6560. in_port_t *portPtr = &sockaddr->sin6_port;
  6561. if ((portPtr != NULL) && (*portPtr == 0)) {
  6562. *portPtr = htons(port);
  6563. }
  6564. NSData *address6 = [NSData dataWithBytes:res->ai_addr length:res->ai_addrlen];
  6565. [addresses addObject:address6];
  6566. }
  6567. }
  6568. freeaddrinfo(res0);
  6569. if ([addresses count] == 0)
  6570. {
  6571. error = [self gaiError:EAI_FAIL];
  6572. }
  6573. }
  6574. }
  6575. if (errPtr) *errPtr = error;
  6576. return addresses;
  6577. }
  6578. + (NSString *)hostFromSockaddr4:(const struct sockaddr_in *)pSockaddr4
  6579. {
  6580. char addrBuf[INET_ADDRSTRLEN];
  6581. if (inet_ntop(AF_INET, &pSockaddr4->sin_addr, addrBuf, (socklen_t)sizeof(addrBuf)) == NULL)
  6582. {
  6583. addrBuf[0] = '\0';
  6584. }
  6585. return [NSString stringWithCString:addrBuf encoding:NSASCIIStringEncoding];
  6586. }
  6587. + (NSString *)hostFromSockaddr6:(const struct sockaddr_in6 *)pSockaddr6
  6588. {
  6589. char addrBuf[INET6_ADDRSTRLEN];
  6590. if (inet_ntop(AF_INET6, &pSockaddr6->sin6_addr, addrBuf, (socklen_t)sizeof(addrBuf)) == NULL)
  6591. {
  6592. addrBuf[0] = '\0';
  6593. }
  6594. return [NSString stringWithCString:addrBuf encoding:NSASCIIStringEncoding];
  6595. }
  6596. + (uint16_t)portFromSockaddr4:(const struct sockaddr_in *)pSockaddr4
  6597. {
  6598. return ntohs(pSockaddr4->sin_port);
  6599. }
  6600. + (uint16_t)portFromSockaddr6:(const struct sockaddr_in6 *)pSockaddr6
  6601. {
  6602. return ntohs(pSockaddr6->sin6_port);
  6603. }
  6604. + (NSURL *)urlFromSockaddrUN:(const struct sockaddr_un *)pSockaddr
  6605. {
  6606. NSString *path = [NSString stringWithUTF8String:pSockaddr->sun_path];
  6607. return [NSURL fileURLWithPath:path];
  6608. }
  6609. + (NSString *)hostFromAddress:(NSData *)address
  6610. {
  6611. NSString *host;
  6612. if ([self getHost:&host port:NULL fromAddress:address])
  6613. return host;
  6614. else
  6615. return nil;
  6616. }
  6617. + (uint16_t)portFromAddress:(NSData *)address
  6618. {
  6619. uint16_t port;
  6620. if ([self getHost:NULL port:&port fromAddress:address])
  6621. return port;
  6622. else
  6623. return 0;
  6624. }
  6625. + (BOOL)isIPv4Address:(NSData *)address
  6626. {
  6627. if ([address length] >= sizeof(struct sockaddr))
  6628. {
  6629. const struct sockaddr *sockaddrX = [address bytes];
  6630. if (sockaddrX->sa_family == AF_INET) {
  6631. return YES;
  6632. }
  6633. }
  6634. return NO;
  6635. }
  6636. + (BOOL)isIPv6Address:(NSData *)address
  6637. {
  6638. if ([address length] >= sizeof(struct sockaddr))
  6639. {
  6640. const struct sockaddr *sockaddrX = [address bytes];
  6641. if (sockaddrX->sa_family == AF_INET6) {
  6642. return YES;
  6643. }
  6644. }
  6645. return NO;
  6646. }
  6647. + (BOOL)getHost:(NSString **)hostPtr port:(uint16_t *)portPtr fromAddress:(NSData *)address
  6648. {
  6649. return [self getHost:hostPtr port:portPtr family:NULL fromAddress:address];
  6650. }
  6651. + (BOOL)getHost:(NSString **)hostPtr port:(uint16_t *)portPtr family:(sa_family_t *)afPtr fromAddress:(NSData *)address
  6652. {
  6653. if ([address length] >= sizeof(struct sockaddr))
  6654. {
  6655. const struct sockaddr *sockaddrX = [address bytes];
  6656. if (sockaddrX->sa_family == AF_INET)
  6657. {
  6658. if ([address length] >= sizeof(struct sockaddr_in))
  6659. {
  6660. struct sockaddr_in sockaddr4;
  6661. memcpy(&sockaddr4, sockaddrX, sizeof(sockaddr4));
  6662. if (hostPtr) *hostPtr = [self hostFromSockaddr4:&sockaddr4];
  6663. if (portPtr) *portPtr = [self portFromSockaddr4:&sockaddr4];
  6664. if (afPtr) *afPtr = AF_INET;
  6665. return YES;
  6666. }
  6667. }
  6668. else if (sockaddrX->sa_family == AF_INET6)
  6669. {
  6670. if ([address length] >= sizeof(struct sockaddr_in6))
  6671. {
  6672. struct sockaddr_in6 sockaddr6;
  6673. memcpy(&sockaddr6, sockaddrX, sizeof(sockaddr6));
  6674. if (hostPtr) *hostPtr = [self hostFromSockaddr6:&sockaddr6];
  6675. if (portPtr) *portPtr = [self portFromSockaddr6:&sockaddr6];
  6676. if (afPtr) *afPtr = AF_INET6;
  6677. return YES;
  6678. }
  6679. }
  6680. }
  6681. return NO;
  6682. }
  6683. + (NSData *)CRLFData
  6684. {
  6685. return [NSData dataWithBytes:"\x0D\x0A" length:2];
  6686. }
  6687. + (NSData *)CRData
  6688. {
  6689. return [NSData dataWithBytes:"\x0D" length:1];
  6690. }
  6691. + (NSData *)LFData
  6692. {
  6693. return [NSData dataWithBytes:"\x0A" length:1];
  6694. }
  6695. + (NSData *)ZeroData
  6696. {
  6697. return [NSData dataWithBytes:"" length:1];
  6698. }
  6699. @end