GCDAsyncSocket.m 221 KB

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