GCDAsyncSocket.m 229 KB

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