GCDAsyncSocket.m 228 KB

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