GCDAsyncSocket.m 226 KB

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