GCDAsyncSocket.m 229 KB

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