GCDAsyncUdpSocket.m 138 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632
  1. //
  2. // GCDAsyncUdpSocket
  3. //
  4. // This class is in the public domain.
  5. // Originally created by Robbie Hanson of Deusty LLC.
  6. // Updated and maintained by Deusty LLC and the Apple development community.
  7. //
  8. // https://github.com/robbiehanson/CocoaAsyncSocket
  9. //
  10. #import "GCDAsyncUdpSocket.h"
  11. #if ! __has_feature(objc_arc)
  12. #warning This file must be compiled with ARC. Use -fobjc-arc flag (or convert project to ARC).
  13. // For more information see: https://github.com/robbiehanson/CocoaAsyncSocket/wiki/ARC
  14. #endif
  15. #if TARGET_OS_IPHONE
  16. #import <CFNetwork/CFNetwork.h>
  17. #import <UIKit/UIKit.h>
  18. #endif
  19. #import <arpa/inet.h>
  20. #import <fcntl.h>
  21. #import <ifaddrs.h>
  22. #import <netdb.h>
  23. #import <net/if.h>
  24. #import <sys/socket.h>
  25. #import <sys/types.h>
  26. #if 0
  27. // Logging Enabled - See log level below
  28. // Logging uses the CocoaLumberjack framework (which is also GCD based).
  29. // https://github.com/robbiehanson/CocoaLumberjack
  30. //
  31. // It allows us to do a lot of logging without significantly slowing down the code.
  32. #import "DDLog.h"
  33. #define LogAsync NO
  34. #define LogContext 65535
  35. #define LogObjc(flg, frmt, ...) LOG_OBJC_MAYBE(LogAsync, logLevel, flg, LogContext, frmt, ##__VA_ARGS__)
  36. #define LogC(flg, frmt, ...) LOG_C_MAYBE(LogAsync, logLevel, flg, LogContext, frmt, ##__VA_ARGS__)
  37. #define LogError(frmt, ...) LogObjc(LOG_FLAG_ERROR, (@"%@: " frmt), THIS_FILE, ##__VA_ARGS__)
  38. #define LogWarn(frmt, ...) LogObjc(LOG_FLAG_WARN, (@"%@: " frmt), THIS_FILE, ##__VA_ARGS__)
  39. #define LogInfo(frmt, ...) LogObjc(LOG_FLAG_INFO, (@"%@: " frmt), THIS_FILE, ##__VA_ARGS__)
  40. #define LogVerbose(frmt, ...) LogObjc(LOG_FLAG_VERBOSE, (@"%@: " frmt), THIS_FILE, ##__VA_ARGS__)
  41. #define LogCError(frmt, ...) LogC(LOG_FLAG_ERROR, (@"%@: " frmt), THIS_FILE, ##__VA_ARGS__)
  42. #define LogCWarn(frmt, ...) LogC(LOG_FLAG_WARN, (@"%@: " frmt), THIS_FILE, ##__VA_ARGS__)
  43. #define LogCInfo(frmt, ...) LogC(LOG_FLAG_INFO, (@"%@: " frmt), THIS_FILE, ##__VA_ARGS__)
  44. #define LogCVerbose(frmt, ...) LogC(LOG_FLAG_VERBOSE, (@"%@: " frmt), THIS_FILE, ##__VA_ARGS__)
  45. #define LogTrace() LogObjc(LOG_FLAG_VERBOSE, @"%@: %@", THIS_FILE, THIS_METHOD)
  46. #define LogCTrace() LogC(LOG_FLAG_VERBOSE, @"%@: %s", THIS_FILE, __FUNCTION__)
  47. // Log levels : off, error, warn, info, verbose
  48. static const int logLevel = LOG_LEVEL_VERBOSE;
  49. #else
  50. // Logging Disabled
  51. #define LogError(frmt, ...) {}
  52. #define LogWarn(frmt, ...) {}
  53. #define LogInfo(frmt, ...) {}
  54. #define LogVerbose(frmt, ...) {}
  55. #define LogCError(frmt, ...) {}
  56. #define LogCWarn(frmt, ...) {}
  57. #define LogCInfo(frmt, ...) {}
  58. #define LogCVerbose(frmt, ...) {}
  59. #define LogTrace() {}
  60. #define LogCTrace(frmt, ...) {}
  61. #endif
  62. /**
  63. * Seeing a return statements within an inner block
  64. * can sometimes be mistaken for a return point of the enclosing method.
  65. * This makes inline blocks a bit easier to read.
  66. **/
  67. #define return_from_block return
  68. /**
  69. * A socket file descriptor is really just an integer.
  70. * It represents the index of the socket within the kernel.
  71. * This makes invalid file descriptor comparisons easier to read.
  72. **/
  73. #define SOCKET_NULL -1
  74. /**
  75. * Just to type less code.
  76. **/
  77. #define AutoreleasedBlock(block) ^{ @autoreleasepool { block(); }}
  78. @class GCDAsyncUdpSendPacket;
  79. NSString *const GCDAsyncUdpSocketException = @"GCDAsyncUdpSocketException";
  80. NSString *const GCDAsyncUdpSocketErrorDomain = @"GCDAsyncUdpSocketErrorDomain";
  81. NSString *const GCDAsyncUdpSocketQueueName = @"GCDAsyncUdpSocket";
  82. NSString *const GCDAsyncUdpSocketThreadName = @"GCDAsyncUdpSocket-CFStream";
  83. enum GCDAsyncUdpSocketFlags
  84. {
  85. kDidCreateSockets = 1 << 0, // If set, the sockets have been created.
  86. kDidBind = 1 << 1, // If set, bind has been called.
  87. kConnecting = 1 << 2, // If set, a connection attempt is in progress.
  88. kDidConnect = 1 << 3, // If set, socket is connected.
  89. kReceiveOnce = 1 << 4, // If set, one-at-a-time receive is enabled
  90. kReceiveContinuous = 1 << 5, // If set, continuous receive is enabled
  91. kIPv4Deactivated = 1 << 6, // If set, socket4 was closed due to bind or connect on IPv6.
  92. kIPv6Deactivated = 1 << 7, // If set, socket6 was closed due to bind or connect on IPv4.
  93. kSend4SourceSuspended = 1 << 8, // If set, send4Source is suspended.
  94. kSend6SourceSuspended = 1 << 9, // If set, send6Source is suspended.
  95. kReceive4SourceSuspended = 1 << 10, // If set, receive4Source is suspended.
  96. kReceive6SourceSuspended = 1 << 11, // If set, receive6Source is suspended.
  97. kSock4CanAcceptBytes = 1 << 12, // If set, we know socket4 can accept bytes. If unset, it's unknown.
  98. kSock6CanAcceptBytes = 1 << 13, // If set, we know socket6 can accept bytes. If unset, it's unknown.
  99. kForbidSendReceive = 1 << 14, // If set, no new send or receive operations are allowed to be queued.
  100. kCloseAfterSends = 1 << 15, // If set, close as soon as no more sends are queued.
  101. kFlipFlop = 1 << 16, // Used to alternate between IPv4 and IPv6 sockets.
  102. #if TARGET_OS_IPHONE
  103. kAddedStreamListener = 1 << 17, // If set, CFStreams have been added to listener thread
  104. #endif
  105. };
  106. enum GCDAsyncUdpSocketConfig
  107. {
  108. kIPv4Disabled = 1 << 0, // If set, IPv4 is disabled
  109. kIPv6Disabled = 1 << 1, // If set, IPv6 is disabled
  110. kPreferIPv4 = 1 << 2, // If set, IPv4 is preferred over IPv6
  111. kPreferIPv6 = 1 << 3, // If set, IPv6 is preferred over IPv4
  112. };
  113. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  114. #pragma mark -
  115. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  116. @interface GCDAsyncUdpSocket ()
  117. {
  118. #if __has_feature(objc_arc_weak)
  119. __weak id delegate;
  120. #else
  121. __unsafe_unretained id delegate;
  122. #endif
  123. dispatch_queue_t delegateQueue;
  124. GCDAsyncUdpSocketReceiveFilterBlock receiveFilterBlock;
  125. dispatch_queue_t receiveFilterQueue;
  126. BOOL receiveFilterAsync;
  127. GCDAsyncUdpSocketSendFilterBlock sendFilterBlock;
  128. dispatch_queue_t sendFilterQueue;
  129. BOOL sendFilterAsync;
  130. uint32_t flags;
  131. uint16_t config;
  132. uint16_t max4ReceiveSize;
  133. uint32_t max6ReceiveSize;
  134. uint16_t maxSendSize;
  135. int socket4FD;
  136. int socket6FD;
  137. dispatch_queue_t socketQueue;
  138. dispatch_source_t send4Source;
  139. dispatch_source_t send6Source;
  140. dispatch_source_t receive4Source;
  141. dispatch_source_t receive6Source;
  142. dispatch_source_t sendTimer;
  143. GCDAsyncUdpSendPacket *currentSend;
  144. NSMutableArray *sendQueue;
  145. unsigned long socket4FDBytesAvailable;
  146. unsigned long socket6FDBytesAvailable;
  147. uint32_t pendingFilterOperations;
  148. NSData *cachedLocalAddress4;
  149. NSString *cachedLocalHost4;
  150. uint16_t cachedLocalPort4;
  151. NSData *cachedLocalAddress6;
  152. NSString *cachedLocalHost6;
  153. uint16_t cachedLocalPort6;
  154. NSData *cachedConnectedAddress;
  155. NSString *cachedConnectedHost;
  156. uint16_t cachedConnectedPort;
  157. int cachedConnectedFamily;
  158. void *IsOnSocketQueueOrTargetQueueKey;
  159. #if TARGET_OS_IPHONE
  160. CFStreamClientContext streamContext;
  161. CFReadStreamRef readStream4;
  162. CFReadStreamRef readStream6;
  163. CFWriteStreamRef writeStream4;
  164. CFWriteStreamRef writeStream6;
  165. #endif
  166. id userData;
  167. }
  168. - (void)resumeSend4Source;
  169. - (void)resumeSend6Source;
  170. - (void)resumeReceive4Source;
  171. - (void)resumeReceive6Source;
  172. - (void)closeSockets;
  173. - (void)maybeConnect;
  174. - (BOOL)connectWithAddress4:(NSData *)address4 error:(NSError **)errPtr;
  175. - (BOOL)connectWithAddress6:(NSData *)address6 error:(NSError **)errPtr;
  176. - (void)maybeDequeueSend;
  177. - (void)doPreSend;
  178. - (void)doSend;
  179. - (void)endCurrentSend;
  180. - (void)setupSendTimerWithTimeout:(NSTimeInterval)timeout;
  181. - (void)doReceive;
  182. - (void)doReceiveEOF;
  183. - (void)closeWithError:(NSError *)error;
  184. - (BOOL)performMulticastRequest:(int)requestType forGroup:(NSString *)group onInterface:(NSString *)interface error:(NSError **)errPtr;
  185. #if TARGET_OS_IPHONE
  186. - (BOOL)createReadAndWriteStreams:(NSError **)errPtr;
  187. - (BOOL)registerForStreamCallbacks:(NSError **)errPtr;
  188. - (BOOL)addStreamsToRunLoop:(NSError **)errPtr;
  189. - (BOOL)openStreams:(NSError **)errPtr;
  190. - (void)removeStreamsFromRunLoop;
  191. - (void)closeReadAndWriteStreams;
  192. #endif
  193. + (NSString *)hostFromSockaddr4:(const struct sockaddr_in *)pSockaddr4;
  194. + (NSString *)hostFromSockaddr6:(const struct sockaddr_in6 *)pSockaddr6;
  195. + (uint16_t)portFromSockaddr4:(const struct sockaddr_in *)pSockaddr4;
  196. + (uint16_t)portFromSockaddr6:(const struct sockaddr_in6 *)pSockaddr6;
  197. #if TARGET_OS_IPHONE
  198. // Forward declaration
  199. + (void)listenerThread:(id)unused;
  200. #endif
  201. @end
  202. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  203. #pragma mark -
  204. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  205. /**
  206. * The GCDAsyncUdpSendPacket encompasses the instructions for a single send/write.
  207. **/
  208. @interface GCDAsyncUdpSendPacket : NSObject {
  209. @public
  210. NSData *buffer;
  211. NSTimeInterval timeout;
  212. long tag;
  213. BOOL resolveInProgress;
  214. BOOL filterInProgress;
  215. NSArray *resolvedAddresses;
  216. NSError *resolveError;
  217. NSData *address;
  218. int addressFamily;
  219. }
  220. - (instancetype)initWithData:(NSData *)d timeout:(NSTimeInterval)t tag:(long)i NS_DESIGNATED_INITIALIZER;
  221. @end
  222. @implementation GCDAsyncUdpSendPacket
  223. // Cover the superclass' designated initializer
  224. - (instancetype)init NS_UNAVAILABLE
  225. {
  226. NSAssert(0, @"Use the designated initializer");
  227. return nil;
  228. }
  229. - (instancetype)initWithData:(NSData *)d timeout:(NSTimeInterval)t tag:(long)i
  230. {
  231. if ((self = [super init]))
  232. {
  233. buffer = d;
  234. timeout = t;
  235. tag = i;
  236. resolveInProgress = NO;
  237. }
  238. return self;
  239. }
  240. @end
  241. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  242. #pragma mark -
  243. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  244. @interface GCDAsyncUdpSpecialPacket : NSObject {
  245. @public
  246. // uint8_t type;
  247. BOOL resolveInProgress;
  248. NSArray *addresses;
  249. NSError *error;
  250. }
  251. - (instancetype)init NS_DESIGNATED_INITIALIZER;
  252. @end
  253. @implementation GCDAsyncUdpSpecialPacket
  254. - (instancetype)init
  255. {
  256. self = [super init];
  257. return self;
  258. }
  259. @end
  260. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  261. #pragma mark -
  262. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  263. @implementation GCDAsyncUdpSocket
  264. - (instancetype)init
  265. {
  266. LogTrace();
  267. return [self initWithDelegate:nil delegateQueue:NULL socketQueue:NULL];
  268. }
  269. - (instancetype)initWithSocketQueue:(dispatch_queue_t)sq
  270. {
  271. LogTrace();
  272. return [self initWithDelegate:nil delegateQueue:NULL socketQueue:sq];
  273. }
  274. - (instancetype)initWithDelegate:(id<GCDAsyncUdpSocketDelegate>)aDelegate delegateQueue:(dispatch_queue_t)dq
  275. {
  276. LogTrace();
  277. return [self initWithDelegate:aDelegate delegateQueue:dq socketQueue:NULL];
  278. }
  279. - (instancetype)initWithDelegate:(id<GCDAsyncUdpSocketDelegate>)aDelegate delegateQueue:(dispatch_queue_t)dq socketQueue:(dispatch_queue_t)sq
  280. {
  281. LogTrace();
  282. if ((self = [super init]))
  283. {
  284. delegate = aDelegate;
  285. if (dq)
  286. {
  287. delegateQueue = dq;
  288. #if !OS_OBJECT_USE_OBJC
  289. dispatch_retain(delegateQueue);
  290. #endif
  291. }
  292. max4ReceiveSize = 65535;
  293. max6ReceiveSize = 65535;
  294. maxSendSize = 65535;
  295. socket4FD = SOCKET_NULL;
  296. socket6FD = SOCKET_NULL;
  297. if (sq)
  298. {
  299. NSAssert(sq != dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0),
  300. @"The given socketQueue parameter must not be a concurrent queue.");
  301. NSAssert(sq != dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0),
  302. @"The given socketQueue parameter must not be a concurrent queue.");
  303. NSAssert(sq != dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
  304. @"The given socketQueue parameter must not be a concurrent queue.");
  305. socketQueue = sq;
  306. #if !OS_OBJECT_USE_OBJC
  307. dispatch_retain(socketQueue);
  308. #endif
  309. }
  310. else
  311. {
  312. socketQueue = dispatch_queue_create([GCDAsyncUdpSocketQueueName UTF8String], NULL);
  313. }
  314. // The dispatch_queue_set_specific() and dispatch_get_specific() functions take a "void *key" parameter.
  315. // From the documentation:
  316. //
  317. // > Keys are only compared as pointers and are never dereferenced.
  318. // > Thus, you can use a pointer to a static variable for a specific subsystem or
  319. // > any other value that allows you to identify the value uniquely.
  320. //
  321. // We're just going to use the memory address of an ivar.
  322. // Specifically an ivar that is explicitly named for our purpose to make the code more readable.
  323. //
  324. // However, it feels tedious (and less readable) to include the "&" all the time:
  325. // dispatch_get_specific(&IsOnSocketQueueOrTargetQueueKey)
  326. //
  327. // So we're going to make it so it doesn't matter if we use the '&' or not,
  328. // by assigning the value of the ivar to the address of the ivar.
  329. // Thus: IsOnSocketQueueOrTargetQueueKey == &IsOnSocketQueueOrTargetQueueKey;
  330. IsOnSocketQueueOrTargetQueueKey = &IsOnSocketQueueOrTargetQueueKey;
  331. void *nonNullUnusedPointer = (__bridge void *)self;
  332. dispatch_queue_set_specific(socketQueue, IsOnSocketQueueOrTargetQueueKey, nonNullUnusedPointer, NULL);
  333. currentSend = nil;
  334. sendQueue = [[NSMutableArray alloc] initWithCapacity:5];
  335. #if TARGET_OS_IPHONE
  336. [[NSNotificationCenter defaultCenter] addObserver:self
  337. selector:@selector(applicationWillEnterForeground:)
  338. name:UIApplicationWillEnterForegroundNotification
  339. object:nil];
  340. #endif
  341. }
  342. return self;
  343. }
  344. - (void)dealloc
  345. {
  346. LogInfo(@"%@ - %@ (start)", THIS_METHOD, self);
  347. #if TARGET_OS_IPHONE
  348. [[NSNotificationCenter defaultCenter] removeObserver:self];
  349. #endif
  350. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  351. {
  352. [self closeWithError:nil];
  353. }
  354. else
  355. {
  356. dispatch_sync(socketQueue, ^{
  357. [self closeWithError:nil];
  358. });
  359. }
  360. delegate = nil;
  361. #if !OS_OBJECT_USE_OBJC
  362. if (delegateQueue) dispatch_release(delegateQueue);
  363. #endif
  364. delegateQueue = NULL;
  365. #if !OS_OBJECT_USE_OBJC
  366. if (socketQueue) dispatch_release(socketQueue);
  367. #endif
  368. socketQueue = NULL;
  369. LogInfo(@"%@ - %@ (finish)", THIS_METHOD, self);
  370. }
  371. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  372. #pragma mark Configuration
  373. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  374. - (id<GCDAsyncUdpSocketDelegate>)delegate
  375. {
  376. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  377. {
  378. return delegate;
  379. }
  380. else
  381. {
  382. __block id result = nil;
  383. dispatch_sync(socketQueue, ^{
  384. result = self->delegate;
  385. });
  386. return result;
  387. }
  388. }
  389. - (void)setDelegate:(id<GCDAsyncUdpSocketDelegate>)newDelegate synchronously:(BOOL)synchronously
  390. {
  391. dispatch_block_t block = ^{
  392. self->delegate = newDelegate;
  393. };
  394. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) {
  395. block();
  396. }
  397. else {
  398. if (synchronously)
  399. dispatch_sync(socketQueue, block);
  400. else
  401. dispatch_async(socketQueue, block);
  402. }
  403. }
  404. - (void)setDelegate:(id<GCDAsyncUdpSocketDelegate>)newDelegate
  405. {
  406. [self setDelegate:newDelegate synchronously:NO];
  407. }
  408. - (void)synchronouslySetDelegate:(id<GCDAsyncUdpSocketDelegate>)newDelegate
  409. {
  410. [self setDelegate:newDelegate synchronously:YES];
  411. }
  412. - (dispatch_queue_t)delegateQueue
  413. {
  414. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  415. {
  416. return delegateQueue;
  417. }
  418. else
  419. {
  420. __block dispatch_queue_t result = NULL;
  421. dispatch_sync(socketQueue, ^{
  422. result = self->delegateQueue;
  423. });
  424. return result;
  425. }
  426. }
  427. - (void)setDelegateQueue:(dispatch_queue_t)newDelegateQueue synchronously:(BOOL)synchronously
  428. {
  429. dispatch_block_t block = ^{
  430. #if !OS_OBJECT_USE_OBJC
  431. if (self->delegateQueue) dispatch_release(self->delegateQueue);
  432. if (newDelegateQueue) dispatch_retain(newDelegateQueue);
  433. #endif
  434. self->delegateQueue = newDelegateQueue;
  435. };
  436. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) {
  437. block();
  438. }
  439. else {
  440. if (synchronously)
  441. dispatch_sync(socketQueue, block);
  442. else
  443. dispatch_async(socketQueue, block);
  444. }
  445. }
  446. - (void)setDelegateQueue:(dispatch_queue_t)newDelegateQueue
  447. {
  448. [self setDelegateQueue:newDelegateQueue synchronously:NO];
  449. }
  450. - (void)synchronouslySetDelegateQueue:(dispatch_queue_t)newDelegateQueue
  451. {
  452. [self setDelegateQueue:newDelegateQueue synchronously:YES];
  453. }
  454. - (void)getDelegate:(id<GCDAsyncUdpSocketDelegate> *)delegatePtr delegateQueue:(dispatch_queue_t *)delegateQueuePtr
  455. {
  456. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  457. {
  458. if (delegatePtr) *delegatePtr = delegate;
  459. if (delegateQueuePtr) *delegateQueuePtr = delegateQueue;
  460. }
  461. else
  462. {
  463. __block id dPtr = NULL;
  464. __block dispatch_queue_t dqPtr = NULL;
  465. dispatch_sync(socketQueue, ^{
  466. dPtr = self->delegate;
  467. dqPtr = self->delegateQueue;
  468. });
  469. if (delegatePtr) *delegatePtr = dPtr;
  470. if (delegateQueuePtr) *delegateQueuePtr = dqPtr;
  471. }
  472. }
  473. - (void)setDelegate:(id<GCDAsyncUdpSocketDelegate>)newDelegate delegateQueue:(dispatch_queue_t)newDelegateQueue synchronously:(BOOL)synchronously
  474. {
  475. dispatch_block_t block = ^{
  476. self->delegate = newDelegate;
  477. #if !OS_OBJECT_USE_OBJC
  478. if (self->delegateQueue) dispatch_release(self->delegateQueue);
  479. if (newDelegateQueue) dispatch_retain(newDelegateQueue);
  480. #endif
  481. self->delegateQueue = newDelegateQueue;
  482. };
  483. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey)) {
  484. block();
  485. }
  486. else {
  487. if (synchronously)
  488. dispatch_sync(socketQueue, block);
  489. else
  490. dispatch_async(socketQueue, block);
  491. }
  492. }
  493. - (void)setDelegate:(id<GCDAsyncUdpSocketDelegate>)newDelegate delegateQueue:(dispatch_queue_t)newDelegateQueue
  494. {
  495. [self setDelegate:newDelegate delegateQueue:newDelegateQueue synchronously:NO];
  496. }
  497. - (void)synchronouslySetDelegate:(id<GCDAsyncUdpSocketDelegate>)newDelegate delegateQueue:(dispatch_queue_t)newDelegateQueue
  498. {
  499. [self setDelegate:newDelegate delegateQueue:newDelegateQueue synchronously:YES];
  500. }
  501. - (BOOL)isIPv4Enabled
  502. {
  503. // Note: YES means kIPv4Disabled is OFF
  504. __block BOOL result = NO;
  505. dispatch_block_t block = ^{
  506. result = ((self->config & kIPv4Disabled) == 0);
  507. };
  508. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  509. block();
  510. else
  511. dispatch_sync(socketQueue, block);
  512. return result;
  513. }
  514. - (void)setIPv4Enabled:(BOOL)flag
  515. {
  516. // Note: YES means kIPv4Disabled is OFF
  517. dispatch_block_t block = ^{
  518. LogVerbose(@"%@ %@", THIS_METHOD, (flag ? @"YES" : @"NO"));
  519. if (flag)
  520. self->config &= ~kIPv4Disabled;
  521. else
  522. self->config |= kIPv4Disabled;
  523. };
  524. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  525. block();
  526. else
  527. dispatch_async(socketQueue, block);
  528. }
  529. - (BOOL)isIPv6Enabled
  530. {
  531. // Note: YES means kIPv6Disabled is OFF
  532. __block BOOL result = NO;
  533. dispatch_block_t block = ^{
  534. result = ((self->config & kIPv6Disabled) == 0);
  535. };
  536. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  537. block();
  538. else
  539. dispatch_sync(socketQueue, block);
  540. return result;
  541. }
  542. - (void)setIPv6Enabled:(BOOL)flag
  543. {
  544. // Note: YES means kIPv6Disabled is OFF
  545. dispatch_block_t block = ^{
  546. LogVerbose(@"%@ %@", THIS_METHOD, (flag ? @"YES" : @"NO"));
  547. if (flag)
  548. self->config &= ~kIPv6Disabled;
  549. else
  550. self->config |= kIPv6Disabled;
  551. };
  552. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  553. block();
  554. else
  555. dispatch_async(socketQueue, block);
  556. }
  557. - (BOOL)isIPv4Preferred
  558. {
  559. __block BOOL result = NO;
  560. dispatch_block_t block = ^{
  561. result = (self->config & kPreferIPv4) ? YES : NO;
  562. };
  563. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  564. block();
  565. else
  566. dispatch_sync(socketQueue, block);
  567. return result;
  568. }
  569. - (BOOL)isIPv6Preferred
  570. {
  571. __block BOOL result = NO;
  572. dispatch_block_t block = ^{
  573. result = (self->config & kPreferIPv6) ? YES : NO;
  574. };
  575. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  576. block();
  577. else
  578. dispatch_sync(socketQueue, block);
  579. return result;
  580. }
  581. - (BOOL)isIPVersionNeutral
  582. {
  583. __block BOOL result = NO;
  584. dispatch_block_t block = ^{
  585. result = (self->config & (kPreferIPv4 | kPreferIPv6)) == 0;
  586. };
  587. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  588. block();
  589. else
  590. dispatch_sync(socketQueue, block);
  591. return result;
  592. }
  593. - (void)setPreferIPv4
  594. {
  595. dispatch_block_t block = ^{
  596. LogTrace();
  597. self->config |= kPreferIPv4;
  598. self->config &= ~kPreferIPv6;
  599. };
  600. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  601. block();
  602. else
  603. dispatch_async(socketQueue, block);
  604. }
  605. - (void)setPreferIPv6
  606. {
  607. dispatch_block_t block = ^{
  608. LogTrace();
  609. self->config &= ~kPreferIPv4;
  610. self->config |= kPreferIPv6;
  611. };
  612. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  613. block();
  614. else
  615. dispatch_async(socketQueue, block);
  616. }
  617. - (void)setIPVersionNeutral
  618. {
  619. dispatch_block_t block = ^{
  620. LogTrace();
  621. self->config &= ~kPreferIPv4;
  622. self->config &= ~kPreferIPv6;
  623. };
  624. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  625. block();
  626. else
  627. dispatch_async(socketQueue, block);
  628. }
  629. - (uint16_t)maxReceiveIPv4BufferSize
  630. {
  631. __block uint16_t result = 0;
  632. dispatch_block_t block = ^{
  633. result = self->max4ReceiveSize;
  634. };
  635. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  636. block();
  637. else
  638. dispatch_sync(socketQueue, block);
  639. return result;
  640. }
  641. - (void)setMaxReceiveIPv4BufferSize:(uint16_t)max
  642. {
  643. dispatch_block_t block = ^{
  644. LogVerbose(@"%@ %u", THIS_METHOD, (unsigned)max);
  645. self->max4ReceiveSize = max;
  646. };
  647. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  648. block();
  649. else
  650. dispatch_async(socketQueue, block);
  651. }
  652. - (uint32_t)maxReceiveIPv6BufferSize
  653. {
  654. __block uint32_t result = 0;
  655. dispatch_block_t block = ^{
  656. result = self->max6ReceiveSize;
  657. };
  658. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  659. block();
  660. else
  661. dispatch_sync(socketQueue, block);
  662. return result;
  663. }
  664. - (void)setMaxReceiveIPv6BufferSize:(uint32_t)max
  665. {
  666. dispatch_block_t block = ^{
  667. LogVerbose(@"%@ %u", THIS_METHOD, (unsigned)max);
  668. self->max6ReceiveSize = max;
  669. };
  670. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  671. block();
  672. else
  673. dispatch_async(socketQueue, block);
  674. }
  675. - (void)setMaxSendBufferSize:(uint16_t)max
  676. {
  677. dispatch_block_t block = ^{
  678. LogVerbose(@"%@ %u", THIS_METHOD, (unsigned)max);
  679. self->maxSendSize = max;
  680. };
  681. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  682. block();
  683. else
  684. dispatch_async(socketQueue, block);
  685. }
  686. - (uint16_t)maxSendBufferSize
  687. {
  688. __block uint16_t result = 0;
  689. dispatch_block_t block = ^{
  690. result = self->maxSendSize;
  691. };
  692. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  693. block();
  694. else
  695. dispatch_sync(socketQueue, block);
  696. return result;
  697. }
  698. - (id)userData
  699. {
  700. __block id result = nil;
  701. dispatch_block_t block = ^{
  702. result = self->userData;
  703. };
  704. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  705. block();
  706. else
  707. dispatch_sync(socketQueue, block);
  708. return result;
  709. }
  710. - (void)setUserData:(id)arbitraryUserData
  711. {
  712. dispatch_block_t block = ^{
  713. if (self->userData != arbitraryUserData)
  714. {
  715. self->userData = arbitraryUserData;
  716. }
  717. };
  718. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  719. block();
  720. else
  721. dispatch_async(socketQueue, block);
  722. }
  723. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  724. #pragma mark Delegate Helpers
  725. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  726. - (void)notifyDidConnectToAddress:(NSData *)anAddress
  727. {
  728. LogTrace();
  729. __strong id<GCDAsyncUdpSocketDelegate> theDelegate = delegate;
  730. if (delegateQueue && [theDelegate respondsToSelector:@selector(udpSocket:didConnectToAddress:)])
  731. {
  732. NSData *address = [anAddress copy]; // In case param is NSMutableData
  733. dispatch_async(delegateQueue, ^{ @autoreleasepool {
  734. [theDelegate udpSocket:self didConnectToAddress:address];
  735. }});
  736. }
  737. }
  738. - (void)notifyDidNotConnect:(NSError *)error
  739. {
  740. LogTrace();
  741. __strong id<GCDAsyncUdpSocketDelegate> theDelegate = delegate;
  742. if (delegateQueue && [theDelegate respondsToSelector:@selector(udpSocket:didNotConnect:)])
  743. {
  744. dispatch_async(delegateQueue, ^{ @autoreleasepool {
  745. [theDelegate udpSocket:self didNotConnect:error];
  746. }});
  747. }
  748. }
  749. - (void)notifyDidSendDataWithTag:(long)tag
  750. {
  751. LogTrace();
  752. __strong id<GCDAsyncUdpSocketDelegate> theDelegate = delegate;
  753. if (delegateQueue && [theDelegate respondsToSelector:@selector(udpSocket:didSendDataWithTag:)])
  754. {
  755. dispatch_async(delegateQueue, ^{ @autoreleasepool {
  756. [theDelegate udpSocket:self didSendDataWithTag:tag];
  757. }});
  758. }
  759. }
  760. - (void)notifyDidNotSendDataWithTag:(long)tag dueToError:(NSError *)error
  761. {
  762. LogTrace();
  763. __strong id<GCDAsyncUdpSocketDelegate> theDelegate = delegate;
  764. if (delegateQueue && [theDelegate respondsToSelector:@selector(udpSocket:didNotSendDataWithTag:dueToError:)])
  765. {
  766. dispatch_async(delegateQueue, ^{ @autoreleasepool {
  767. [theDelegate udpSocket:self didNotSendDataWithTag:tag dueToError:error];
  768. }});
  769. }
  770. }
  771. - (void)notifyDidReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)context
  772. {
  773. LogTrace();
  774. SEL selector = @selector(udpSocket:didReceiveData:fromAddress:withFilterContext:);
  775. __strong id<GCDAsyncUdpSocketDelegate> theDelegate = delegate;
  776. if (delegateQueue && [theDelegate respondsToSelector:selector])
  777. {
  778. dispatch_async(delegateQueue, ^{ @autoreleasepool {
  779. [theDelegate udpSocket:self didReceiveData:data fromAddress:address withFilterContext:context];
  780. }});
  781. }
  782. }
  783. - (void)notifyDidCloseWithError:(NSError *)error
  784. {
  785. LogTrace();
  786. __strong id<GCDAsyncUdpSocketDelegate> theDelegate = delegate;
  787. if (delegateQueue && [theDelegate respondsToSelector:@selector(udpSocketDidClose:withError:)])
  788. {
  789. dispatch_async(delegateQueue, ^{ @autoreleasepool {
  790. [theDelegate udpSocketDidClose:self withError:error];
  791. }});
  792. }
  793. }
  794. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  795. #pragma mark Errors
  796. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  797. - (NSError *)badConfigError:(NSString *)errMsg
  798. {
  799. NSDictionary *userInfo = @{NSLocalizedDescriptionKey : errMsg};
  800. return [NSError errorWithDomain:GCDAsyncUdpSocketErrorDomain
  801. code:GCDAsyncUdpSocketBadConfigError
  802. userInfo:userInfo];
  803. }
  804. - (NSError *)badParamError:(NSString *)errMsg
  805. {
  806. NSDictionary *userInfo = @{NSLocalizedDescriptionKey : errMsg};
  807. return [NSError errorWithDomain:GCDAsyncUdpSocketErrorDomain
  808. code:GCDAsyncUdpSocketBadParamError
  809. userInfo:userInfo];
  810. }
  811. - (NSError *)gaiError:(int)gai_error
  812. {
  813. NSString *errMsg = [NSString stringWithCString:gai_strerror(gai_error) encoding:NSASCIIStringEncoding];
  814. NSDictionary *userInfo = @{NSLocalizedDescriptionKey : errMsg};
  815. return [NSError errorWithDomain:@"kCFStreamErrorDomainNetDB" code:gai_error userInfo:userInfo];
  816. }
  817. - (NSError *)errnoErrorWithReason:(NSString *)reason
  818. {
  819. NSString *errMsg = [NSString stringWithUTF8String:strerror(errno)];
  820. NSDictionary *userInfo;
  821. if (reason)
  822. userInfo = @{NSLocalizedDescriptionKey : errMsg,
  823. NSLocalizedFailureReasonErrorKey : reason};
  824. else
  825. userInfo = @{NSLocalizedDescriptionKey : errMsg};
  826. return [NSError errorWithDomain:NSPOSIXErrorDomain code:errno userInfo:userInfo];
  827. }
  828. - (NSError *)errnoError
  829. {
  830. return [self errnoErrorWithReason:nil];
  831. }
  832. /**
  833. * Returns a standard send timeout error.
  834. **/
  835. - (NSError *)sendTimeoutError
  836. {
  837. NSString *errMsg = NSLocalizedStringWithDefaultValue(@"GCDAsyncUdpSocketSendTimeoutError",
  838. @"GCDAsyncUdpSocket", [NSBundle mainBundle],
  839. @"Send operation timed out", nil);
  840. NSDictionary *userInfo = @{NSLocalizedDescriptionKey : errMsg};
  841. return [NSError errorWithDomain:GCDAsyncUdpSocketErrorDomain
  842. code:GCDAsyncUdpSocketSendTimeoutError
  843. userInfo:userInfo];
  844. }
  845. - (NSError *)socketClosedError
  846. {
  847. NSString *errMsg = NSLocalizedStringWithDefaultValue(@"GCDAsyncUdpSocketClosedError",
  848. @"GCDAsyncUdpSocket", [NSBundle mainBundle],
  849. @"Socket closed", nil);
  850. NSDictionary *userInfo = @{NSLocalizedDescriptionKey : errMsg};
  851. return [NSError errorWithDomain:GCDAsyncUdpSocketErrorDomain code:GCDAsyncUdpSocketClosedError userInfo:userInfo];
  852. }
  853. - (NSError *)otherError:(NSString *)errMsg
  854. {
  855. NSDictionary *userInfo = @{NSLocalizedDescriptionKey : errMsg};
  856. return [NSError errorWithDomain:GCDAsyncUdpSocketErrorDomain
  857. code:GCDAsyncUdpSocketOtherError
  858. userInfo:userInfo];
  859. }
  860. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  861. #pragma mark Utilities
  862. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  863. - (BOOL)preOp:(NSError **)errPtr
  864. {
  865. NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue");
  866. if (delegate == nil) // Must have delegate set
  867. {
  868. if (errPtr)
  869. {
  870. NSString *msg = @"Attempting to use socket without a delegate. Set a delegate first.";
  871. *errPtr = [self badConfigError:msg];
  872. }
  873. return NO;
  874. }
  875. if (delegateQueue == NULL) // Must have delegate queue set
  876. {
  877. if (errPtr)
  878. {
  879. NSString *msg = @"Attempting to use socket without a delegate queue. Set a delegate queue first.";
  880. *errPtr = [self badConfigError:msg];
  881. }
  882. return NO;
  883. }
  884. return YES;
  885. }
  886. /**
  887. * This method executes on a global concurrent queue.
  888. * When complete, it executes the given completion block on the socketQueue.
  889. **/
  890. - (void)asyncResolveHost:(NSString *)aHost
  891. port:(uint16_t)port
  892. withCompletionBlock:(void (^)(NSArray *addresses, NSError *error))completionBlock
  893. {
  894. LogTrace();
  895. // Check parameter(s)
  896. if (aHost == nil)
  897. {
  898. NSString *msg = @"The host param is nil. Should be domain name or IP address string.";
  899. NSError *error = [self badParamError:msg];
  900. // We should still use dispatch_async since this method is expected to be asynchronous
  901. dispatch_async(socketQueue, ^{ @autoreleasepool {
  902. completionBlock(nil, error);
  903. }});
  904. return;
  905. }
  906. // It's possible that the given aHost parameter is actually a NSMutableString.
  907. // So we want to copy it now, within this block that will be executed synchronously.
  908. // This way the asynchronous lookup block below doesn't have to worry about it changing.
  909. NSString *host = [aHost copy];
  910. dispatch_queue_t globalConcurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
  911. dispatch_async(globalConcurrentQueue, ^{ @autoreleasepool {
  912. NSMutableArray *addresses = [NSMutableArray arrayWithCapacity:2];
  913. NSError *error = nil;
  914. if ([host isEqualToString:@"localhost"] || [host isEqualToString:@"loopback"])
  915. {
  916. // Use LOOPBACK address
  917. struct sockaddr_in sockaddr4;
  918. memset(&sockaddr4, 0, sizeof(sockaddr4));
  919. sockaddr4.sin_len = sizeof(struct sockaddr_in);
  920. sockaddr4.sin_family = AF_INET;
  921. sockaddr4.sin_port = htons(port);
  922. sockaddr4.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  923. struct sockaddr_in6 sockaddr6;
  924. memset(&sockaddr6, 0, sizeof(sockaddr6));
  925. sockaddr6.sin6_len = sizeof(struct sockaddr_in6);
  926. sockaddr6.sin6_family = AF_INET6;
  927. sockaddr6.sin6_port = htons(port);
  928. sockaddr6.sin6_addr = in6addr_loopback;
  929. // Wrap the native address structures and add to list
  930. [addresses addObject:[NSData dataWithBytes:&sockaddr4 length:sizeof(sockaddr4)]];
  931. [addresses addObject:[NSData dataWithBytes:&sockaddr6 length:sizeof(sockaddr6)]];
  932. }
  933. else
  934. {
  935. NSString *portStr = [NSString stringWithFormat:@"%hu", port];
  936. struct addrinfo hints, *res, *res0;
  937. memset(&hints, 0, sizeof(hints));
  938. hints.ai_family = PF_UNSPEC;
  939. hints.ai_socktype = SOCK_DGRAM;
  940. hints.ai_protocol = IPPROTO_UDP;
  941. int gai_error = getaddrinfo([host UTF8String], [portStr UTF8String], &hints, &res0);
  942. if (gai_error)
  943. {
  944. error = [self gaiError:gai_error];
  945. }
  946. else
  947. {
  948. for(res = res0; res; res = res->ai_next)
  949. {
  950. if (res->ai_family == AF_INET)
  951. {
  952. // Found IPv4 address
  953. // Wrap the native address structure and add to list
  954. [addresses addObject:[NSData dataWithBytes:res->ai_addr length:res->ai_addrlen]];
  955. }
  956. else if (res->ai_family == AF_INET6)
  957. {
  958. // Fixes connection issues with IPv6, it is the same solution for udp socket.
  959. // https://github.com/robbiehanson/CocoaAsyncSocket/issues/429#issuecomment-222477158
  960. struct sockaddr_in6 *sockaddr = (struct sockaddr_in6 *)(void *)res->ai_addr;
  961. in_port_t *portPtr = &sockaddr->sin6_port;
  962. if ((portPtr != NULL) && (*portPtr == 0)) {
  963. *portPtr = htons(port);
  964. }
  965. // Found IPv6 address
  966. // Wrap the native address structure and add to list
  967. [addresses addObject:[NSData dataWithBytes:res->ai_addr length:res->ai_addrlen]];
  968. }
  969. }
  970. freeaddrinfo(res0);
  971. if ([addresses count] == 0)
  972. {
  973. error = [self gaiError:EAI_FAIL];
  974. }
  975. }
  976. }
  977. dispatch_async(self->socketQueue, ^{ @autoreleasepool {
  978. completionBlock(addresses, error);
  979. }});
  980. }});
  981. }
  982. /**
  983. * This method picks an address from the given list of addresses.
  984. * The address picked depends upon which protocols are disabled, deactived, & preferred.
  985. *
  986. * Returns the address family (AF_INET or AF_INET6) of the picked address,
  987. * or AF_UNSPEC and the corresponding error is there's a problem.
  988. **/
  989. - (int)getAddress:(NSData **)addressPtr error:(NSError **)errorPtr fromAddresses:(NSArray *)addresses
  990. {
  991. NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue");
  992. NSAssert([addresses count] > 0, @"Expected at least one address");
  993. int resultAF = AF_UNSPEC;
  994. NSData *resultAddress = nil;
  995. NSError *resultError = nil;
  996. // Check for problems
  997. BOOL resolvedIPv4Address = NO;
  998. BOOL resolvedIPv6Address = NO;
  999. for (NSData *address in addresses)
  1000. {
  1001. switch ([[self class] familyFromAddress:address])
  1002. {
  1003. case AF_INET : resolvedIPv4Address = YES; break;
  1004. case AF_INET6 : resolvedIPv6Address = YES; break;
  1005. default : NSAssert(NO, @"Addresses array contains invalid address");
  1006. }
  1007. }
  1008. BOOL isIPv4Disabled = (config & kIPv4Disabled) ? YES : NO;
  1009. BOOL isIPv6Disabled = (config & kIPv6Disabled) ? YES : NO;
  1010. if (isIPv4Disabled && !resolvedIPv6Address)
  1011. {
  1012. NSString *msg = @"IPv4 has been disabled and DNS lookup found no IPv6 address(es).";
  1013. resultError = [self otherError:msg];
  1014. if (addressPtr) *addressPtr = resultAddress;
  1015. if (errorPtr) *errorPtr = resultError;
  1016. return resultAF;
  1017. }
  1018. if (isIPv6Disabled && !resolvedIPv4Address)
  1019. {
  1020. NSString *msg = @"IPv6 has been disabled and DNS lookup found no IPv4 address(es).";
  1021. resultError = [self otherError:msg];
  1022. if (addressPtr) *addressPtr = resultAddress;
  1023. if (errorPtr) *errorPtr = resultError;
  1024. return resultAF;
  1025. }
  1026. BOOL isIPv4Deactivated = (flags & kIPv4Deactivated) ? YES : NO;
  1027. BOOL isIPv6Deactivated = (flags & kIPv6Deactivated) ? YES : NO;
  1028. if (isIPv4Deactivated && !resolvedIPv6Address)
  1029. {
  1030. NSString *msg = @"IPv4 has been deactivated due to bind/connect, and DNS lookup found no IPv6 address(es).";
  1031. resultError = [self otherError:msg];
  1032. if (addressPtr) *addressPtr = resultAddress;
  1033. if (errorPtr) *errorPtr = resultError;
  1034. return resultAF;
  1035. }
  1036. if (isIPv6Deactivated && !resolvedIPv4Address)
  1037. {
  1038. NSString *msg = @"IPv6 has been deactivated due to bind/connect, and DNS lookup found no IPv4 address(es).";
  1039. resultError = [self otherError:msg];
  1040. if (addressPtr) *addressPtr = resultAddress;
  1041. if (errorPtr) *errorPtr = resultError;
  1042. return resultAF;
  1043. }
  1044. // Extract first IPv4 and IPv6 address in list
  1045. BOOL ipv4WasFirstInList = YES;
  1046. NSData *address4 = nil;
  1047. NSData *address6 = nil;
  1048. for (NSData *address in addresses)
  1049. {
  1050. int af = [[self class] familyFromAddress:address];
  1051. if (af == AF_INET)
  1052. {
  1053. if (address4 == nil)
  1054. {
  1055. address4 = address;
  1056. if (address6)
  1057. break;
  1058. else
  1059. ipv4WasFirstInList = YES;
  1060. }
  1061. }
  1062. else // af == AF_INET6
  1063. {
  1064. if (address6 == nil)
  1065. {
  1066. address6 = address;
  1067. if (address4)
  1068. break;
  1069. else
  1070. ipv4WasFirstInList = NO;
  1071. }
  1072. }
  1073. }
  1074. // Determine socket type
  1075. BOOL preferIPv4 = (config & kPreferIPv4) ? YES : NO;
  1076. BOOL preferIPv6 = (config & kPreferIPv6) ? YES : NO;
  1077. BOOL useIPv4 = ((preferIPv4 && address4) || (address6 == nil));
  1078. BOOL useIPv6 = ((preferIPv6 && address6) || (address4 == nil));
  1079. NSAssert(!(preferIPv4 && preferIPv6), @"Invalid config state");
  1080. NSAssert(!(useIPv4 && useIPv6), @"Invalid logic");
  1081. if (useIPv4 || (!useIPv6 && ipv4WasFirstInList))
  1082. {
  1083. resultAF = AF_INET;
  1084. resultAddress = address4;
  1085. }
  1086. else
  1087. {
  1088. resultAF = AF_INET6;
  1089. resultAddress = address6;
  1090. }
  1091. if (addressPtr) *addressPtr = resultAddress;
  1092. if (errorPtr) *errorPtr = resultError;
  1093. return resultAF;
  1094. }
  1095. /**
  1096. * Finds the address(es) of an interface description.
  1097. * An inteface description may be an interface name (en0, en1, lo0) or corresponding IP (192.168.4.34).
  1098. **/
  1099. - (void)convertIntefaceDescription:(NSString *)interfaceDescription
  1100. port:(uint16_t)port
  1101. intoAddress4:(NSData **)interfaceAddr4Ptr
  1102. address6:(NSData **)interfaceAddr6Ptr
  1103. {
  1104. NSData *addr4 = nil;
  1105. NSData *addr6 = nil;
  1106. if (interfaceDescription == nil)
  1107. {
  1108. // ANY address
  1109. struct sockaddr_in sockaddr4;
  1110. memset(&sockaddr4, 0, sizeof(sockaddr4));
  1111. sockaddr4.sin_len = sizeof(sockaddr4);
  1112. sockaddr4.sin_family = AF_INET;
  1113. sockaddr4.sin_port = htons(port);
  1114. sockaddr4.sin_addr.s_addr = htonl(INADDR_ANY);
  1115. struct sockaddr_in6 sockaddr6;
  1116. memset(&sockaddr6, 0, sizeof(sockaddr6));
  1117. sockaddr6.sin6_len = sizeof(sockaddr6);
  1118. sockaddr6.sin6_family = AF_INET6;
  1119. sockaddr6.sin6_port = htons(port);
  1120. sockaddr6.sin6_addr = in6addr_any;
  1121. addr4 = [NSData dataWithBytes:&sockaddr4 length:sizeof(sockaddr4)];
  1122. addr6 = [NSData dataWithBytes:&sockaddr6 length:sizeof(sockaddr6)];
  1123. }
  1124. else if ([interfaceDescription isEqualToString:@"localhost"] ||
  1125. [interfaceDescription isEqualToString:@"loopback"])
  1126. {
  1127. // LOOPBACK address
  1128. struct sockaddr_in sockaddr4;
  1129. memset(&sockaddr4, 0, sizeof(sockaddr4));
  1130. sockaddr4.sin_len = sizeof(struct sockaddr_in);
  1131. sockaddr4.sin_family = AF_INET;
  1132. sockaddr4.sin_port = htons(port);
  1133. sockaddr4.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  1134. struct sockaddr_in6 sockaddr6;
  1135. memset(&sockaddr6, 0, sizeof(sockaddr6));
  1136. sockaddr6.sin6_len = sizeof(struct sockaddr_in6);
  1137. sockaddr6.sin6_family = AF_INET6;
  1138. sockaddr6.sin6_port = htons(port);
  1139. sockaddr6.sin6_addr = in6addr_loopback;
  1140. addr4 = [NSData dataWithBytes:&sockaddr4 length:sizeof(sockaddr4)];
  1141. addr6 = [NSData dataWithBytes:&sockaddr6 length:sizeof(sockaddr6)];
  1142. }
  1143. else
  1144. {
  1145. const char *iface = [interfaceDescription UTF8String];
  1146. struct ifaddrs *addrs;
  1147. const struct ifaddrs *cursor;
  1148. if ((getifaddrs(&addrs) == 0))
  1149. {
  1150. cursor = addrs;
  1151. while (cursor != NULL)
  1152. {
  1153. if ((addr4 == nil) && (cursor->ifa_addr->sa_family == AF_INET))
  1154. {
  1155. // IPv4
  1156. struct sockaddr_in *addr = (struct sockaddr_in *)(void *)cursor->ifa_addr;
  1157. if (strcmp(cursor->ifa_name, iface) == 0)
  1158. {
  1159. // Name match
  1160. struct sockaddr_in nativeAddr4 = *addr;
  1161. nativeAddr4.sin_port = htons(port);
  1162. addr4 = [NSData dataWithBytes:&nativeAddr4 length:sizeof(nativeAddr4)];
  1163. }
  1164. else
  1165. {
  1166. char ip[INET_ADDRSTRLEN];
  1167. const char *conversion;
  1168. conversion = inet_ntop(AF_INET, &addr->sin_addr, ip, sizeof(ip));
  1169. if ((conversion != NULL) && (strcmp(ip, iface) == 0))
  1170. {
  1171. // IP match
  1172. struct sockaddr_in nativeAddr4 = *addr;
  1173. nativeAddr4.sin_port = htons(port);
  1174. addr4 = [NSData dataWithBytes:&nativeAddr4 length:sizeof(nativeAddr4)];
  1175. }
  1176. }
  1177. }
  1178. else if ((addr6 == nil) && (cursor->ifa_addr->sa_family == AF_INET6))
  1179. {
  1180. // IPv6
  1181. const struct sockaddr_in6 *addr = (const struct sockaddr_in6 *)(const void *)cursor->ifa_addr;
  1182. if (strcmp(cursor->ifa_name, iface) == 0)
  1183. {
  1184. // Name match
  1185. struct sockaddr_in6 nativeAddr6 = *addr;
  1186. nativeAddr6.sin6_port = htons(port);
  1187. addr6 = [NSData dataWithBytes:&nativeAddr6 length:sizeof(nativeAddr6)];
  1188. }
  1189. else
  1190. {
  1191. char ip[INET6_ADDRSTRLEN];
  1192. const char *conversion;
  1193. conversion = inet_ntop(AF_INET6, &addr->sin6_addr, ip, sizeof(ip));
  1194. if ((conversion != NULL) && (strcmp(ip, iface) == 0))
  1195. {
  1196. // IP match
  1197. struct sockaddr_in6 nativeAddr6 = *addr;
  1198. nativeAddr6.sin6_port = htons(port);
  1199. addr6 = [NSData dataWithBytes:&nativeAddr6 length:sizeof(nativeAddr6)];
  1200. }
  1201. }
  1202. }
  1203. cursor = cursor->ifa_next;
  1204. }
  1205. freeifaddrs(addrs);
  1206. }
  1207. }
  1208. if (interfaceAddr4Ptr) *interfaceAddr4Ptr = addr4;
  1209. if (interfaceAddr6Ptr) *interfaceAddr6Ptr = addr6;
  1210. }
  1211. /**
  1212. * Converts a numeric hostname into its corresponding address.
  1213. * The hostname is expected to be an IPv4 or IPv6 address represented as a human-readable string. (e.g. 192.168.4.34)
  1214. **/
  1215. - (void)convertNumericHost:(NSString *)numericHost
  1216. port:(uint16_t)port
  1217. intoAddress4:(NSData **)addr4Ptr
  1218. address6:(NSData **)addr6Ptr
  1219. {
  1220. NSData *addr4 = nil;
  1221. NSData *addr6 = nil;
  1222. if (numericHost)
  1223. {
  1224. NSString *portStr = [NSString stringWithFormat:@"%hu", port];
  1225. struct addrinfo hints, *res, *res0;
  1226. memset(&hints, 0, sizeof(hints));
  1227. hints.ai_family = PF_UNSPEC;
  1228. hints.ai_socktype = SOCK_DGRAM;
  1229. hints.ai_protocol = IPPROTO_UDP;
  1230. hints.ai_flags = AI_NUMERICHOST; // No name resolution should be attempted
  1231. if (getaddrinfo([numericHost UTF8String], [portStr UTF8String], &hints, &res0) == 0)
  1232. {
  1233. for (res = res0; res; res = res->ai_next)
  1234. {
  1235. if ((addr4 == nil) && (res->ai_family == AF_INET))
  1236. {
  1237. // Found IPv4 address
  1238. // Wrap the native address structure
  1239. addr4 = [NSData dataWithBytes:res->ai_addr length:res->ai_addrlen];
  1240. }
  1241. else if ((addr6 == nil) && (res->ai_family == AF_INET6))
  1242. {
  1243. // Found IPv6 address
  1244. // Wrap the native address structure
  1245. addr6 = [NSData dataWithBytes:res->ai_addr length:res->ai_addrlen];
  1246. }
  1247. }
  1248. freeaddrinfo(res0);
  1249. }
  1250. }
  1251. if (addr4Ptr) *addr4Ptr = addr4;
  1252. if (addr6Ptr) *addr6Ptr = addr6;
  1253. }
  1254. - (BOOL)isConnectedToAddress4:(NSData *)someAddr4
  1255. {
  1256. NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue");
  1257. NSAssert(flags & kDidConnect, @"Not connected");
  1258. NSAssert(cachedConnectedAddress, @"Expected cached connected address");
  1259. if (cachedConnectedFamily != AF_INET)
  1260. {
  1261. return NO;
  1262. }
  1263. const struct sockaddr_in *sSockaddr4 = (const struct sockaddr_in *)[someAddr4 bytes];
  1264. const struct sockaddr_in *cSockaddr4 = (const struct sockaddr_in *)[cachedConnectedAddress bytes];
  1265. if (memcmp(&sSockaddr4->sin_addr, &cSockaddr4->sin_addr, sizeof(struct in_addr)) != 0)
  1266. {
  1267. return NO;
  1268. }
  1269. if (memcmp(&sSockaddr4->sin_port, &cSockaddr4->sin_port, sizeof(in_port_t)) != 0)
  1270. {
  1271. return NO;
  1272. }
  1273. return YES;
  1274. }
  1275. - (BOOL)isConnectedToAddress6:(NSData *)someAddr6
  1276. {
  1277. NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue");
  1278. NSAssert(flags & kDidConnect, @"Not connected");
  1279. NSAssert(cachedConnectedAddress, @"Expected cached connected address");
  1280. if (cachedConnectedFamily != AF_INET6)
  1281. {
  1282. return NO;
  1283. }
  1284. const struct sockaddr_in6 *sSockaddr6 = (const struct sockaddr_in6 *)[someAddr6 bytes];
  1285. const struct sockaddr_in6 *cSockaddr6 = (const struct sockaddr_in6 *)[cachedConnectedAddress bytes];
  1286. if (memcmp(&sSockaddr6->sin6_addr, &cSockaddr6->sin6_addr, sizeof(struct in6_addr)) != 0)
  1287. {
  1288. return NO;
  1289. }
  1290. if (memcmp(&sSockaddr6->sin6_port, &cSockaddr6->sin6_port, sizeof(in_port_t)) != 0)
  1291. {
  1292. return NO;
  1293. }
  1294. return YES;
  1295. }
  1296. - (unsigned int)indexOfInterfaceAddr4:(NSData *)interfaceAddr4
  1297. {
  1298. if (interfaceAddr4 == nil)
  1299. return 0;
  1300. if ([interfaceAddr4 length] != sizeof(struct sockaddr_in))
  1301. return 0;
  1302. int result = 0;
  1303. const struct sockaddr_in *ifaceAddr = (const struct sockaddr_in *)[interfaceAddr4 bytes];
  1304. struct ifaddrs *addrs;
  1305. const struct ifaddrs *cursor;
  1306. if ((getifaddrs(&addrs) == 0))
  1307. {
  1308. cursor = addrs;
  1309. while (cursor != NULL)
  1310. {
  1311. if (cursor->ifa_addr->sa_family == AF_INET)
  1312. {
  1313. // IPv4
  1314. const struct sockaddr_in *addr = (const struct sockaddr_in *)(const void *)cursor->ifa_addr;
  1315. if (memcmp(&addr->sin_addr, &ifaceAddr->sin_addr, sizeof(struct in_addr)) == 0)
  1316. {
  1317. result = if_nametoindex(cursor->ifa_name);
  1318. break;
  1319. }
  1320. }
  1321. cursor = cursor->ifa_next;
  1322. }
  1323. freeifaddrs(addrs);
  1324. }
  1325. return result;
  1326. }
  1327. - (unsigned int)indexOfInterfaceAddr6:(NSData *)interfaceAddr6
  1328. {
  1329. if (interfaceAddr6 == nil)
  1330. return 0;
  1331. if ([interfaceAddr6 length] != sizeof(struct sockaddr_in6))
  1332. return 0;
  1333. int result = 0;
  1334. const struct sockaddr_in6 *ifaceAddr = (const struct sockaddr_in6 *)[interfaceAddr6 bytes];
  1335. struct ifaddrs *addrs;
  1336. const struct ifaddrs *cursor;
  1337. if ((getifaddrs(&addrs) == 0))
  1338. {
  1339. cursor = addrs;
  1340. while (cursor != NULL)
  1341. {
  1342. if (cursor->ifa_addr->sa_family == AF_INET6)
  1343. {
  1344. // IPv6
  1345. const struct sockaddr_in6 *addr = (const struct sockaddr_in6 *)(const void *)cursor->ifa_addr;
  1346. if (memcmp(&addr->sin6_addr, &ifaceAddr->sin6_addr, sizeof(struct in6_addr)) == 0)
  1347. {
  1348. result = if_nametoindex(cursor->ifa_name);
  1349. break;
  1350. }
  1351. }
  1352. cursor = cursor->ifa_next;
  1353. }
  1354. freeifaddrs(addrs);
  1355. }
  1356. return result;
  1357. }
  1358. - (void)setupSendAndReceiveSourcesForSocket4
  1359. {
  1360. LogTrace();
  1361. NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue");
  1362. send4Source = dispatch_source_create(DISPATCH_SOURCE_TYPE_WRITE, socket4FD, 0, socketQueue);
  1363. receive4Source = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, socket4FD, 0, socketQueue);
  1364. // Setup event handlers
  1365. dispatch_source_set_event_handler(send4Source, ^{ @autoreleasepool {
  1366. LogVerbose(@"send4EventBlock");
  1367. LogVerbose(@"dispatch_source_get_data(send4Source) = %lu", dispatch_source_get_data(send4Source));
  1368. self->flags |= kSock4CanAcceptBytes;
  1369. // If we're ready to send data, do so immediately.
  1370. // Otherwise pause the send source or it will continue to fire over and over again.
  1371. if (self->currentSend == nil)
  1372. {
  1373. LogVerbose(@"Nothing to send");
  1374. [self suspendSend4Source];
  1375. }
  1376. else if (self->currentSend->resolveInProgress)
  1377. {
  1378. LogVerbose(@"currentSend - waiting for address resolve");
  1379. [self suspendSend4Source];
  1380. }
  1381. else if (self->currentSend->filterInProgress)
  1382. {
  1383. LogVerbose(@"currentSend - waiting on sendFilter");
  1384. [self suspendSend4Source];
  1385. }
  1386. else
  1387. {
  1388. [self doSend];
  1389. }
  1390. }});
  1391. dispatch_source_set_event_handler(receive4Source, ^{ @autoreleasepool {
  1392. LogVerbose(@"receive4EventBlock");
  1393. self->socket4FDBytesAvailable = dispatch_source_get_data(self->receive4Source);
  1394. LogVerbose(@"socket4FDBytesAvailable: %lu", socket4FDBytesAvailable);
  1395. if (self->socket4FDBytesAvailable > 0)
  1396. [self doReceive];
  1397. else
  1398. [self doReceiveEOF];
  1399. }});
  1400. // Setup cancel handlers
  1401. __block int socketFDRefCount = 2;
  1402. int theSocketFD = socket4FD;
  1403. #if !OS_OBJECT_USE_OBJC
  1404. dispatch_source_t theSendSource = send4Source;
  1405. dispatch_source_t theReceiveSource = receive4Source;
  1406. #endif
  1407. dispatch_source_set_cancel_handler(send4Source, ^{
  1408. LogVerbose(@"send4CancelBlock");
  1409. #if !OS_OBJECT_USE_OBJC
  1410. LogVerbose(@"dispatch_release(send4Source)");
  1411. dispatch_release(theSendSource);
  1412. #endif
  1413. if (--socketFDRefCount == 0)
  1414. {
  1415. LogVerbose(@"close(socket4FD)");
  1416. close(theSocketFD);
  1417. }
  1418. });
  1419. dispatch_source_set_cancel_handler(receive4Source, ^{
  1420. LogVerbose(@"receive4CancelBlock");
  1421. #if !OS_OBJECT_USE_OBJC
  1422. LogVerbose(@"dispatch_release(receive4Source)");
  1423. dispatch_release(theReceiveSource);
  1424. #endif
  1425. if (--socketFDRefCount == 0)
  1426. {
  1427. LogVerbose(@"close(socket4FD)");
  1428. close(theSocketFD);
  1429. }
  1430. });
  1431. // We will not be able to receive until the socket is bound to a port,
  1432. // either explicitly via bind, or implicitly by connect or by sending data.
  1433. //
  1434. // But we should be able to send immediately.
  1435. socket4FDBytesAvailable = 0;
  1436. flags |= kSock4CanAcceptBytes;
  1437. flags |= kSend4SourceSuspended;
  1438. flags |= kReceive4SourceSuspended;
  1439. }
  1440. - (void)setupSendAndReceiveSourcesForSocket6
  1441. {
  1442. LogTrace();
  1443. NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue");
  1444. send6Source = dispatch_source_create(DISPATCH_SOURCE_TYPE_WRITE, socket6FD, 0, socketQueue);
  1445. receive6Source = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, socket6FD, 0, socketQueue);
  1446. // Setup event handlers
  1447. dispatch_source_set_event_handler(send6Source, ^{ @autoreleasepool {
  1448. LogVerbose(@"send6EventBlock");
  1449. LogVerbose(@"dispatch_source_get_data(send6Source) = %lu", dispatch_source_get_data(send6Source));
  1450. self->flags |= kSock6CanAcceptBytes;
  1451. // If we're ready to send data, do so immediately.
  1452. // Otherwise pause the send source or it will continue to fire over and over again.
  1453. if (self->currentSend == nil)
  1454. {
  1455. LogVerbose(@"Nothing to send");
  1456. [self suspendSend6Source];
  1457. }
  1458. else if (self->currentSend->resolveInProgress)
  1459. {
  1460. LogVerbose(@"currentSend - waiting for address resolve");
  1461. [self suspendSend6Source];
  1462. }
  1463. else if (self->currentSend->filterInProgress)
  1464. {
  1465. LogVerbose(@"currentSend - waiting on sendFilter");
  1466. [self suspendSend6Source];
  1467. }
  1468. else
  1469. {
  1470. [self doSend];
  1471. }
  1472. }});
  1473. dispatch_source_set_event_handler(receive6Source, ^{ @autoreleasepool {
  1474. LogVerbose(@"receive6EventBlock");
  1475. self->socket6FDBytesAvailable = dispatch_source_get_data(self->receive6Source);
  1476. LogVerbose(@"socket6FDBytesAvailable: %lu", socket6FDBytesAvailable);
  1477. if (self->socket6FDBytesAvailable > 0)
  1478. [self doReceive];
  1479. else
  1480. [self doReceiveEOF];
  1481. }});
  1482. // Setup cancel handlers
  1483. __block int socketFDRefCount = 2;
  1484. int theSocketFD = socket6FD;
  1485. #if !OS_OBJECT_USE_OBJC
  1486. dispatch_source_t theSendSource = send6Source;
  1487. dispatch_source_t theReceiveSource = receive6Source;
  1488. #endif
  1489. dispatch_source_set_cancel_handler(send6Source, ^{
  1490. LogVerbose(@"send6CancelBlock");
  1491. #if !OS_OBJECT_USE_OBJC
  1492. LogVerbose(@"dispatch_release(send6Source)");
  1493. dispatch_release(theSendSource);
  1494. #endif
  1495. if (--socketFDRefCount == 0)
  1496. {
  1497. LogVerbose(@"close(socket6FD)");
  1498. close(theSocketFD);
  1499. }
  1500. });
  1501. dispatch_source_set_cancel_handler(receive6Source, ^{
  1502. LogVerbose(@"receive6CancelBlock");
  1503. #if !OS_OBJECT_USE_OBJC
  1504. LogVerbose(@"dispatch_release(receive6Source)");
  1505. dispatch_release(theReceiveSource);
  1506. #endif
  1507. if (--socketFDRefCount == 0)
  1508. {
  1509. LogVerbose(@"close(socket6FD)");
  1510. close(theSocketFD);
  1511. }
  1512. });
  1513. // We will not be able to receive until the socket is bound to a port,
  1514. // either explicitly via bind, or implicitly by connect or by sending data.
  1515. //
  1516. // But we should be able to send immediately.
  1517. socket6FDBytesAvailable = 0;
  1518. flags |= kSock6CanAcceptBytes;
  1519. flags |= kSend6SourceSuspended;
  1520. flags |= kReceive6SourceSuspended;
  1521. }
  1522. - (BOOL)createSocket4:(BOOL)useIPv4 socket6:(BOOL)useIPv6 error:(NSError * __autoreleasing *)errPtr
  1523. {
  1524. LogTrace();
  1525. NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue");
  1526. NSAssert(((flags & kDidCreateSockets) == 0), @"Sockets have already been created");
  1527. // CreateSocket Block
  1528. // This block will be invoked below.
  1529. int(^createSocket)(int) = ^int (int domain) {
  1530. int socketFD = socket(domain, SOCK_DGRAM, 0);
  1531. if (socketFD == SOCKET_NULL)
  1532. {
  1533. if (errPtr)
  1534. *errPtr = [self errnoErrorWithReason:@"Error in socket() function"];
  1535. return SOCKET_NULL;
  1536. }
  1537. int status;
  1538. // Set socket options
  1539. status = fcntl(socketFD, F_SETFL, O_NONBLOCK);
  1540. if (status == -1)
  1541. {
  1542. if (errPtr)
  1543. *errPtr = [self errnoErrorWithReason:@"Error enabling non-blocking IO on socket (fcntl)"];
  1544. close(socketFD);
  1545. return SOCKET_NULL;
  1546. }
  1547. int reuseaddr = 1;
  1548. status = setsockopt(socketFD, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr));
  1549. if (status == -1)
  1550. {
  1551. if (errPtr)
  1552. *errPtr = [self errnoErrorWithReason:@"Error enabling address reuse (setsockopt)"];
  1553. close(socketFD);
  1554. return SOCKET_NULL;
  1555. }
  1556. int nosigpipe = 1;
  1557. status = setsockopt(socketFD, SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe, sizeof(nosigpipe));
  1558. if (status == -1)
  1559. {
  1560. if (errPtr)
  1561. *errPtr = [self errnoErrorWithReason:@"Error disabling sigpipe (setsockopt)"];
  1562. close(socketFD);
  1563. return SOCKET_NULL;
  1564. }
  1565. /**
  1566. * The theoretical maximum size of any IPv4 UDP packet is UINT16_MAX = 65535.
  1567. * The theoretical maximum size of any IPv6 UDP packet is UINT32_MAX = 4294967295.
  1568. *
  1569. * The default maximum size of the UDP buffer in iOS is 9216 bytes.
  1570. *
  1571. * This is the reason of #222(GCD does not necessarily return the size of an entire UDP packet) and
  1572. * #535(GCDAsyncUDPSocket can not send data when data is greater than 9K)
  1573. *
  1574. *
  1575. * Enlarge the maximum size of UDP packet.
  1576. * I can not ensure the protocol type now so that the max size is set to 65535 :)
  1577. **/
  1578. status = setsockopt(socketFD, SOL_SOCKET, SO_SNDBUF, (const char*)&self->maxSendSize, sizeof(int));
  1579. if (status == -1)
  1580. {
  1581. if (errPtr)
  1582. *errPtr = [self errnoErrorWithReason:@"Error setting send buffer size (setsockopt)"];
  1583. close(socketFD);
  1584. return SOCKET_NULL;
  1585. }
  1586. status = setsockopt(socketFD, SOL_SOCKET, SO_RCVBUF, (const char*)&self->maxSendSize, sizeof(int));
  1587. if (status == -1)
  1588. {
  1589. if (errPtr)
  1590. *errPtr = [self errnoErrorWithReason:@"Error setting receive buffer size (setsockopt)"];
  1591. close(socketFD);
  1592. return SOCKET_NULL;
  1593. }
  1594. return socketFD;
  1595. };
  1596. // Create sockets depending upon given configuration.
  1597. if (useIPv4)
  1598. {
  1599. LogVerbose(@"Creating IPv4 socket");
  1600. socket4FD = createSocket(AF_INET);
  1601. if (socket4FD == SOCKET_NULL)
  1602. {
  1603. // errPtr set in local createSocket() block
  1604. return NO;
  1605. }
  1606. }
  1607. if (useIPv6)
  1608. {
  1609. LogVerbose(@"Creating IPv6 socket");
  1610. socket6FD = createSocket(AF_INET6);
  1611. if (socket6FD == SOCKET_NULL)
  1612. {
  1613. // errPtr set in local createSocket() block
  1614. if (socket4FD != SOCKET_NULL)
  1615. {
  1616. close(socket4FD);
  1617. socket4FD = SOCKET_NULL;
  1618. }
  1619. return NO;
  1620. }
  1621. }
  1622. // Setup send and receive sources
  1623. if (useIPv4)
  1624. [self setupSendAndReceiveSourcesForSocket4];
  1625. if (useIPv6)
  1626. [self setupSendAndReceiveSourcesForSocket6];
  1627. flags |= kDidCreateSockets;
  1628. return YES;
  1629. }
  1630. - (BOOL)createSockets:(NSError **)errPtr
  1631. {
  1632. LogTrace();
  1633. BOOL useIPv4 = [self isIPv4Enabled];
  1634. BOOL useIPv6 = [self isIPv6Enabled];
  1635. return [self createSocket4:useIPv4 socket6:useIPv6 error:errPtr];
  1636. }
  1637. - (void)suspendSend4Source
  1638. {
  1639. if (send4Source && !(flags & kSend4SourceSuspended))
  1640. {
  1641. LogVerbose(@"dispatch_suspend(send4Source)");
  1642. dispatch_suspend(send4Source);
  1643. flags |= kSend4SourceSuspended;
  1644. }
  1645. }
  1646. - (void)suspendSend6Source
  1647. {
  1648. if (send6Source && !(flags & kSend6SourceSuspended))
  1649. {
  1650. LogVerbose(@"dispatch_suspend(send6Source)");
  1651. dispatch_suspend(send6Source);
  1652. flags |= kSend6SourceSuspended;
  1653. }
  1654. }
  1655. - (void)resumeSend4Source
  1656. {
  1657. if (send4Source && (flags & kSend4SourceSuspended))
  1658. {
  1659. LogVerbose(@"dispatch_resume(send4Source)");
  1660. dispatch_resume(send4Source);
  1661. flags &= ~kSend4SourceSuspended;
  1662. }
  1663. }
  1664. - (void)resumeSend6Source
  1665. {
  1666. if (send6Source && (flags & kSend6SourceSuspended))
  1667. {
  1668. LogVerbose(@"dispatch_resume(send6Source)");
  1669. dispatch_resume(send6Source);
  1670. flags &= ~kSend6SourceSuspended;
  1671. }
  1672. }
  1673. - (void)suspendReceive4Source
  1674. {
  1675. if (receive4Source && !(flags & kReceive4SourceSuspended))
  1676. {
  1677. LogVerbose(@"dispatch_suspend(receive4Source)");
  1678. dispatch_suspend(receive4Source);
  1679. flags |= kReceive4SourceSuspended;
  1680. }
  1681. }
  1682. - (void)suspendReceive6Source
  1683. {
  1684. if (receive6Source && !(flags & kReceive6SourceSuspended))
  1685. {
  1686. LogVerbose(@"dispatch_suspend(receive6Source)");
  1687. dispatch_suspend(receive6Source);
  1688. flags |= kReceive6SourceSuspended;
  1689. }
  1690. }
  1691. - (void)resumeReceive4Source
  1692. {
  1693. if (receive4Source && (flags & kReceive4SourceSuspended))
  1694. {
  1695. LogVerbose(@"dispatch_resume(receive4Source)");
  1696. dispatch_resume(receive4Source);
  1697. flags &= ~kReceive4SourceSuspended;
  1698. }
  1699. }
  1700. - (void)resumeReceive6Source
  1701. {
  1702. if (receive6Source && (flags & kReceive6SourceSuspended))
  1703. {
  1704. LogVerbose(@"dispatch_resume(receive6Source)");
  1705. dispatch_resume(receive6Source);
  1706. flags &= ~kReceive6SourceSuspended;
  1707. }
  1708. }
  1709. - (void)closeSocket4
  1710. {
  1711. if (socket4FD != SOCKET_NULL)
  1712. {
  1713. LogVerbose(@"dispatch_source_cancel(send4Source)");
  1714. dispatch_source_cancel(send4Source);
  1715. LogVerbose(@"dispatch_source_cancel(receive4Source)");
  1716. dispatch_source_cancel(receive4Source);
  1717. // For some crazy reason (in my opinion), cancelling a dispatch source doesn't
  1718. // invoke the cancel handler if the dispatch source is paused.
  1719. // So we have to unpause the source if needed.
  1720. // This allows the cancel handler to be run, which in turn releases the source and closes the socket.
  1721. [self resumeSend4Source];
  1722. [self resumeReceive4Source];
  1723. // The sockets will be closed by the cancel handlers of the corresponding source
  1724. send4Source = NULL;
  1725. receive4Source = NULL;
  1726. socket4FD = SOCKET_NULL;
  1727. // Clear socket states
  1728. socket4FDBytesAvailable = 0;
  1729. flags &= ~kSock4CanAcceptBytes;
  1730. // Clear cached info
  1731. cachedLocalAddress4 = nil;
  1732. cachedLocalHost4 = nil;
  1733. cachedLocalPort4 = 0;
  1734. }
  1735. }
  1736. - (void)closeSocket6
  1737. {
  1738. if (socket6FD != SOCKET_NULL)
  1739. {
  1740. LogVerbose(@"dispatch_source_cancel(send6Source)");
  1741. dispatch_source_cancel(send6Source);
  1742. LogVerbose(@"dispatch_source_cancel(receive6Source)");
  1743. dispatch_source_cancel(receive6Source);
  1744. // For some crazy reason (in my opinion), cancelling a dispatch source doesn't
  1745. // invoke the cancel handler if the dispatch source is paused.
  1746. // So we have to unpause the source if needed.
  1747. // This allows the cancel handler to be run, which in turn releases the source and closes the socket.
  1748. [self resumeSend6Source];
  1749. [self resumeReceive6Source];
  1750. send6Source = NULL;
  1751. receive6Source = NULL;
  1752. // The sockets will be closed by the cancel handlers of the corresponding source
  1753. socket6FD = SOCKET_NULL;
  1754. // Clear socket states
  1755. socket6FDBytesAvailable = 0;
  1756. flags &= ~kSock6CanAcceptBytes;
  1757. // Clear cached info
  1758. cachedLocalAddress6 = nil;
  1759. cachedLocalHost6 = nil;
  1760. cachedLocalPort6 = 0;
  1761. }
  1762. }
  1763. - (void)closeSockets
  1764. {
  1765. [self closeSocket4];
  1766. [self closeSocket6];
  1767. flags &= ~kDidCreateSockets;
  1768. }
  1769. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1770. #pragma mark Diagnostics
  1771. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  1772. - (BOOL)getLocalAddress:(NSData **)dataPtr
  1773. host:(NSString **)hostPtr
  1774. port:(uint16_t *)portPtr
  1775. forSocket:(int)socketFD
  1776. withFamily:(int)socketFamily
  1777. {
  1778. NSData *data = nil;
  1779. NSString *host = nil;
  1780. uint16_t port = 0;
  1781. if (socketFamily == AF_INET)
  1782. {
  1783. struct sockaddr_in sockaddr4;
  1784. socklen_t sockaddr4len = sizeof(sockaddr4);
  1785. if (getsockname(socketFD, (struct sockaddr *)&sockaddr4, &sockaddr4len) == 0)
  1786. {
  1787. data = [NSData dataWithBytes:&sockaddr4 length:sockaddr4len];
  1788. host = [[self class] hostFromSockaddr4:&sockaddr4];
  1789. port = [[self class] portFromSockaddr4:&sockaddr4];
  1790. }
  1791. else
  1792. {
  1793. LogWarn(@"Error in getsockname: %@", [self errnoError]);
  1794. }
  1795. }
  1796. else if (socketFamily == AF_INET6)
  1797. {
  1798. struct sockaddr_in6 sockaddr6;
  1799. socklen_t sockaddr6len = sizeof(sockaddr6);
  1800. if (getsockname(socketFD, (struct sockaddr *)&sockaddr6, &sockaddr6len) == 0)
  1801. {
  1802. data = [NSData dataWithBytes:&sockaddr6 length:sockaddr6len];
  1803. host = [[self class] hostFromSockaddr6:&sockaddr6];
  1804. port = [[self class] portFromSockaddr6:&sockaddr6];
  1805. }
  1806. else
  1807. {
  1808. LogWarn(@"Error in getsockname: %@", [self errnoError]);
  1809. }
  1810. }
  1811. if (dataPtr) *dataPtr = data;
  1812. if (hostPtr) *hostPtr = host;
  1813. if (portPtr) *portPtr = port;
  1814. return (data != nil);
  1815. }
  1816. - (void)maybeUpdateCachedLocalAddress4Info
  1817. {
  1818. NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue");
  1819. if ( cachedLocalAddress4 || ((flags & kDidBind) == 0) || (socket4FD == SOCKET_NULL) )
  1820. {
  1821. return;
  1822. }
  1823. NSData *address = nil;
  1824. NSString *host = nil;
  1825. uint16_t port = 0;
  1826. if ([self getLocalAddress:&address host:&host port:&port forSocket:socket4FD withFamily:AF_INET])
  1827. {
  1828. cachedLocalAddress4 = address;
  1829. cachedLocalHost4 = host;
  1830. cachedLocalPort4 = port;
  1831. }
  1832. }
  1833. - (void)maybeUpdateCachedLocalAddress6Info
  1834. {
  1835. NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue");
  1836. if ( cachedLocalAddress6 || ((flags & kDidBind) == 0) || (socket6FD == SOCKET_NULL) )
  1837. {
  1838. return;
  1839. }
  1840. NSData *address = nil;
  1841. NSString *host = nil;
  1842. uint16_t port = 0;
  1843. if ([self getLocalAddress:&address host:&host port:&port forSocket:socket6FD withFamily:AF_INET6])
  1844. {
  1845. cachedLocalAddress6 = address;
  1846. cachedLocalHost6 = host;
  1847. cachedLocalPort6 = port;
  1848. }
  1849. }
  1850. - (NSData *)localAddress
  1851. {
  1852. __block NSData *result = nil;
  1853. dispatch_block_t block = ^{
  1854. if (self->socket4FD != SOCKET_NULL)
  1855. {
  1856. [self maybeUpdateCachedLocalAddress4Info];
  1857. result = self->cachedLocalAddress4;
  1858. }
  1859. else
  1860. {
  1861. [self maybeUpdateCachedLocalAddress6Info];
  1862. result = self->cachedLocalAddress6;
  1863. }
  1864. };
  1865. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  1866. block();
  1867. else
  1868. dispatch_sync(socketQueue, AutoreleasedBlock(block));
  1869. return result;
  1870. }
  1871. - (NSString *)localHost
  1872. {
  1873. __block NSString *result = nil;
  1874. dispatch_block_t block = ^{
  1875. if (self->socket4FD != SOCKET_NULL)
  1876. {
  1877. [self maybeUpdateCachedLocalAddress4Info];
  1878. result = self->cachedLocalHost4;
  1879. }
  1880. else
  1881. {
  1882. [self maybeUpdateCachedLocalAddress6Info];
  1883. result = self->cachedLocalHost6;
  1884. }
  1885. };
  1886. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  1887. block();
  1888. else
  1889. dispatch_sync(socketQueue, AutoreleasedBlock(block));
  1890. return result;
  1891. }
  1892. - (uint16_t)localPort
  1893. {
  1894. __block uint16_t result = 0;
  1895. dispatch_block_t block = ^{
  1896. if (self->socket4FD != SOCKET_NULL)
  1897. {
  1898. [self maybeUpdateCachedLocalAddress4Info];
  1899. result = self->cachedLocalPort4;
  1900. }
  1901. else
  1902. {
  1903. [self maybeUpdateCachedLocalAddress6Info];
  1904. result = self->cachedLocalPort6;
  1905. }
  1906. };
  1907. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  1908. block();
  1909. else
  1910. dispatch_sync(socketQueue, AutoreleasedBlock(block));
  1911. return result;
  1912. }
  1913. - (NSData *)localAddress_IPv4
  1914. {
  1915. __block NSData *result = nil;
  1916. dispatch_block_t block = ^{
  1917. [self maybeUpdateCachedLocalAddress4Info];
  1918. result = self->cachedLocalAddress4;
  1919. };
  1920. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  1921. block();
  1922. else
  1923. dispatch_sync(socketQueue, AutoreleasedBlock(block));
  1924. return result;
  1925. }
  1926. - (NSString *)localHost_IPv4
  1927. {
  1928. __block NSString *result = nil;
  1929. dispatch_block_t block = ^{
  1930. [self maybeUpdateCachedLocalAddress4Info];
  1931. result = self->cachedLocalHost4;
  1932. };
  1933. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  1934. block();
  1935. else
  1936. dispatch_sync(socketQueue, AutoreleasedBlock(block));
  1937. return result;
  1938. }
  1939. - (uint16_t)localPort_IPv4
  1940. {
  1941. __block uint16_t result = 0;
  1942. dispatch_block_t block = ^{
  1943. [self maybeUpdateCachedLocalAddress4Info];
  1944. result = self->cachedLocalPort4;
  1945. };
  1946. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  1947. block();
  1948. else
  1949. dispatch_sync(socketQueue, AutoreleasedBlock(block));
  1950. return result;
  1951. }
  1952. - (NSData *)localAddress_IPv6
  1953. {
  1954. __block NSData *result = nil;
  1955. dispatch_block_t block = ^{
  1956. [self maybeUpdateCachedLocalAddress6Info];
  1957. result = self->cachedLocalAddress6;
  1958. };
  1959. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  1960. block();
  1961. else
  1962. dispatch_sync(socketQueue, AutoreleasedBlock(block));
  1963. return result;
  1964. }
  1965. - (NSString *)localHost_IPv6
  1966. {
  1967. __block NSString *result = nil;
  1968. dispatch_block_t block = ^{
  1969. [self maybeUpdateCachedLocalAddress6Info];
  1970. result = self->cachedLocalHost6;
  1971. };
  1972. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  1973. block();
  1974. else
  1975. dispatch_sync(socketQueue, AutoreleasedBlock(block));
  1976. return result;
  1977. }
  1978. - (uint16_t)localPort_IPv6
  1979. {
  1980. __block uint16_t result = 0;
  1981. dispatch_block_t block = ^{
  1982. [self maybeUpdateCachedLocalAddress6Info];
  1983. result = self->cachedLocalPort6;
  1984. };
  1985. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  1986. block();
  1987. else
  1988. dispatch_sync(socketQueue, AutoreleasedBlock(block));
  1989. return result;
  1990. }
  1991. - (void)maybeUpdateCachedConnectedAddressInfo
  1992. {
  1993. NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue");
  1994. if (cachedConnectedAddress || (flags & kDidConnect) == 0)
  1995. {
  1996. return;
  1997. }
  1998. NSData *data = nil;
  1999. NSString *host = nil;
  2000. uint16_t port = 0;
  2001. int family = AF_UNSPEC;
  2002. if (socket4FD != SOCKET_NULL)
  2003. {
  2004. struct sockaddr_in sockaddr4;
  2005. socklen_t sockaddr4len = sizeof(sockaddr4);
  2006. if (getpeername(socket4FD, (struct sockaddr *)&sockaddr4, &sockaddr4len) == 0)
  2007. {
  2008. data = [NSData dataWithBytes:&sockaddr4 length:sockaddr4len];
  2009. host = [[self class] hostFromSockaddr4:&sockaddr4];
  2010. port = [[self class] portFromSockaddr4:&sockaddr4];
  2011. family = AF_INET;
  2012. }
  2013. else
  2014. {
  2015. LogWarn(@"Error in getpeername: %@", [self errnoError]);
  2016. }
  2017. }
  2018. else if (socket6FD != SOCKET_NULL)
  2019. {
  2020. struct sockaddr_in6 sockaddr6;
  2021. socklen_t sockaddr6len = sizeof(sockaddr6);
  2022. if (getpeername(socket6FD, (struct sockaddr *)&sockaddr6, &sockaddr6len) == 0)
  2023. {
  2024. data = [NSData dataWithBytes:&sockaddr6 length:sockaddr6len];
  2025. host = [[self class] hostFromSockaddr6:&sockaddr6];
  2026. port = [[self class] portFromSockaddr6:&sockaddr6];
  2027. family = AF_INET6;
  2028. }
  2029. else
  2030. {
  2031. LogWarn(@"Error in getpeername: %@", [self errnoError]);
  2032. }
  2033. }
  2034. cachedConnectedAddress = data;
  2035. cachedConnectedHost = host;
  2036. cachedConnectedPort = port;
  2037. cachedConnectedFamily = family;
  2038. }
  2039. - (NSData *)connectedAddress
  2040. {
  2041. __block NSData *result = nil;
  2042. dispatch_block_t block = ^{
  2043. [self maybeUpdateCachedConnectedAddressInfo];
  2044. result = self->cachedConnectedAddress;
  2045. };
  2046. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  2047. block();
  2048. else
  2049. dispatch_sync(socketQueue, AutoreleasedBlock(block));
  2050. return result;
  2051. }
  2052. - (NSString *)connectedHost
  2053. {
  2054. __block NSString *result = nil;
  2055. dispatch_block_t block = ^{
  2056. [self maybeUpdateCachedConnectedAddressInfo];
  2057. result = self->cachedConnectedHost;
  2058. };
  2059. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  2060. block();
  2061. else
  2062. dispatch_sync(socketQueue, AutoreleasedBlock(block));
  2063. return result;
  2064. }
  2065. - (uint16_t)connectedPort
  2066. {
  2067. __block uint16_t result = 0;
  2068. dispatch_block_t block = ^{
  2069. [self maybeUpdateCachedConnectedAddressInfo];
  2070. result = self->cachedConnectedPort;
  2071. };
  2072. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  2073. block();
  2074. else
  2075. dispatch_sync(socketQueue, AutoreleasedBlock(block));
  2076. return result;
  2077. }
  2078. - (BOOL)isConnected
  2079. {
  2080. __block BOOL result = NO;
  2081. dispatch_block_t block = ^{
  2082. result = (self->flags & kDidConnect) ? YES : NO;
  2083. };
  2084. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  2085. block();
  2086. else
  2087. dispatch_sync(socketQueue, block);
  2088. return result;
  2089. }
  2090. - (BOOL)isClosed
  2091. {
  2092. __block BOOL result = YES;
  2093. dispatch_block_t block = ^{
  2094. result = (self->flags & kDidCreateSockets) ? NO : YES;
  2095. };
  2096. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  2097. block();
  2098. else
  2099. dispatch_sync(socketQueue, block);
  2100. return result;
  2101. }
  2102. - (BOOL)isIPv4
  2103. {
  2104. __block BOOL result = NO;
  2105. dispatch_block_t block = ^{
  2106. if (self->flags & kDidCreateSockets)
  2107. {
  2108. result = (self->socket4FD != SOCKET_NULL);
  2109. }
  2110. else
  2111. {
  2112. result = [self isIPv4Enabled];
  2113. }
  2114. };
  2115. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  2116. block();
  2117. else
  2118. dispatch_sync(socketQueue, block);
  2119. return result;
  2120. }
  2121. - (BOOL)isIPv6
  2122. {
  2123. __block BOOL result = NO;
  2124. dispatch_block_t block = ^{
  2125. if (self->flags & kDidCreateSockets)
  2126. {
  2127. result = (self->socket6FD != SOCKET_NULL);
  2128. }
  2129. else
  2130. {
  2131. result = [self isIPv6Enabled];
  2132. }
  2133. };
  2134. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  2135. block();
  2136. else
  2137. dispatch_sync(socketQueue, block);
  2138. return result;
  2139. }
  2140. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2141. #pragma mark Binding
  2142. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2143. /**
  2144. * This method runs through the various checks required prior to a bind attempt.
  2145. * It is shared between the various bind methods.
  2146. **/
  2147. - (BOOL)preBind:(NSError **)errPtr
  2148. {
  2149. if (![self preOp:errPtr])
  2150. {
  2151. return NO;
  2152. }
  2153. if (flags & kDidBind)
  2154. {
  2155. if (errPtr)
  2156. {
  2157. NSString *msg = @"Cannot bind a socket more than once.";
  2158. *errPtr = [self badConfigError:msg];
  2159. }
  2160. return NO;
  2161. }
  2162. if ((flags & kConnecting) || (flags & kDidConnect))
  2163. {
  2164. if (errPtr)
  2165. {
  2166. NSString *msg = @"Cannot bind after connecting. If needed, bind first, then connect.";
  2167. *errPtr = [self badConfigError:msg];
  2168. }
  2169. return NO;
  2170. }
  2171. BOOL isIPv4Disabled = (config & kIPv4Disabled) ? YES : NO;
  2172. BOOL isIPv6Disabled = (config & kIPv6Disabled) ? YES : NO;
  2173. if (isIPv4Disabled && isIPv6Disabled) // Must have IPv4 or IPv6 enabled
  2174. {
  2175. if (errPtr)
  2176. {
  2177. NSString *msg = @"Both IPv4 and IPv6 have been disabled. Must enable at least one protocol first.";
  2178. *errPtr = [self badConfigError:msg];
  2179. }
  2180. return NO;
  2181. }
  2182. return YES;
  2183. }
  2184. - (BOOL)bindToPort:(uint16_t)port error:(NSError **)errPtr
  2185. {
  2186. return [self bindToPort:port interface:nil error:errPtr];
  2187. }
  2188. - (BOOL)bindToPort:(uint16_t)port interface:(NSString *)interface error:(NSError **)errPtr
  2189. {
  2190. __block BOOL result = NO;
  2191. __block NSError *err = nil;
  2192. dispatch_block_t block = ^{ @autoreleasepool {
  2193. // Run through sanity checks
  2194. if (![self preBind:&err])
  2195. {
  2196. return_from_block;
  2197. }
  2198. // Check the given interface
  2199. NSData *interface4 = nil;
  2200. NSData *interface6 = nil;
  2201. [self convertIntefaceDescription:interface port:port intoAddress4:&interface4 address6:&interface6];
  2202. if ((interface4 == nil) && (interface6 == nil))
  2203. {
  2204. NSString *msg = @"Unknown interface. Specify valid interface by name (e.g. \"en1\") or IP address.";
  2205. err = [self badParamError:msg];
  2206. return_from_block;
  2207. }
  2208. BOOL isIPv4Disabled = (self->config & kIPv4Disabled) ? YES : NO;
  2209. BOOL isIPv6Disabled = (self->config & kIPv6Disabled) ? YES : NO;
  2210. if (isIPv4Disabled && (interface6 == nil))
  2211. {
  2212. NSString *msg = @"IPv4 has been disabled and specified interface doesn't support IPv6.";
  2213. err = [self badParamError:msg];
  2214. return_from_block;
  2215. }
  2216. if (isIPv6Disabled && (interface4 == nil))
  2217. {
  2218. NSString *msg = @"IPv6 has been disabled and specified interface doesn't support IPv4.";
  2219. err = [self badParamError:msg];
  2220. return_from_block;
  2221. }
  2222. // Determine protocol(s)
  2223. BOOL useIPv4 = !isIPv4Disabled && (interface4 != nil);
  2224. BOOL useIPv6 = !isIPv6Disabled && (interface6 != nil);
  2225. // Create the socket(s) if needed
  2226. if ((self->flags & kDidCreateSockets) == 0)
  2227. {
  2228. if (![self createSocket4:useIPv4 socket6:useIPv6 error:&err])
  2229. {
  2230. return_from_block;
  2231. }
  2232. }
  2233. // Bind the socket(s)
  2234. LogVerbose(@"Binding socket to port(%hu) interface(%@)", port, interface);
  2235. if (useIPv4)
  2236. {
  2237. int status = bind(self->socket4FD, (const struct sockaddr *)[interface4 bytes], (socklen_t)[interface4 length]);
  2238. if (status == -1)
  2239. {
  2240. [self closeSockets];
  2241. NSString *reason = @"Error in bind() function";
  2242. err = [self errnoErrorWithReason:reason];
  2243. return_from_block;
  2244. }
  2245. }
  2246. if (useIPv6)
  2247. {
  2248. int status = bind(self->socket6FD, (const struct sockaddr *)[interface6 bytes], (socklen_t)[interface6 length]);
  2249. if (status == -1)
  2250. {
  2251. [self closeSockets];
  2252. NSString *reason = @"Error in bind() function";
  2253. err = [self errnoErrorWithReason:reason];
  2254. return_from_block;
  2255. }
  2256. }
  2257. // Update flags
  2258. self->flags |= kDidBind;
  2259. if (!useIPv4) self->flags |= kIPv4Deactivated;
  2260. if (!useIPv6) self->flags |= kIPv6Deactivated;
  2261. result = YES;
  2262. }};
  2263. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  2264. block();
  2265. else
  2266. dispatch_sync(socketQueue, block);
  2267. if (err)
  2268. LogError(@"Error binding to port/interface: %@", err);
  2269. if (errPtr)
  2270. *errPtr = err;
  2271. return result;
  2272. }
  2273. - (BOOL)bindToAddress:(NSData *)localAddr error:(NSError **)errPtr
  2274. {
  2275. __block BOOL result = NO;
  2276. __block NSError *err = nil;
  2277. dispatch_block_t block = ^{ @autoreleasepool {
  2278. // Run through sanity checks
  2279. if (![self preBind:&err])
  2280. {
  2281. return_from_block;
  2282. }
  2283. // Check the given address
  2284. int addressFamily = [[self class] familyFromAddress:localAddr];
  2285. if (addressFamily == AF_UNSPEC)
  2286. {
  2287. NSString *msg = @"A valid IPv4 or IPv6 address was not given";
  2288. err = [self badParamError:msg];
  2289. return_from_block;
  2290. }
  2291. NSData *localAddr4 = (addressFamily == AF_INET) ? localAddr : nil;
  2292. NSData *localAddr6 = (addressFamily == AF_INET6) ? localAddr : nil;
  2293. BOOL isIPv4Disabled = (self->config & kIPv4Disabled) ? YES : NO;
  2294. BOOL isIPv6Disabled = (self->config & kIPv6Disabled) ? YES : NO;
  2295. if (isIPv4Disabled && localAddr4)
  2296. {
  2297. NSString *msg = @"IPv4 has been disabled and an IPv4 address was passed.";
  2298. err = [self badParamError:msg];
  2299. return_from_block;
  2300. }
  2301. if (isIPv6Disabled && localAddr6)
  2302. {
  2303. NSString *msg = @"IPv6 has been disabled and an IPv6 address was passed.";
  2304. err = [self badParamError:msg];
  2305. return_from_block;
  2306. }
  2307. // Determine protocol(s)
  2308. BOOL useIPv4 = !isIPv4Disabled && (localAddr4 != nil);
  2309. BOOL useIPv6 = !isIPv6Disabled && (localAddr6 != nil);
  2310. // Create the socket(s) if needed
  2311. if ((self->flags & kDidCreateSockets) == 0)
  2312. {
  2313. if (![self createSocket4:useIPv4 socket6:useIPv6 error:&err])
  2314. {
  2315. return_from_block;
  2316. }
  2317. }
  2318. // Bind the socket(s)
  2319. if (useIPv4)
  2320. {
  2321. LogVerbose(@"Binding socket to address(%@:%hu)",
  2322. [[self class] hostFromAddress:localAddr4],
  2323. [[self class] portFromAddress:localAddr4]);
  2324. int status = bind(self->socket4FD, (const struct sockaddr *)[localAddr4 bytes], (socklen_t)[localAddr4 length]);
  2325. if (status == -1)
  2326. {
  2327. [self closeSockets];
  2328. NSString *reason = @"Error in bind() function";
  2329. err = [self errnoErrorWithReason:reason];
  2330. return_from_block;
  2331. }
  2332. }
  2333. else
  2334. {
  2335. LogVerbose(@"Binding socket to address(%@:%hu)",
  2336. [[self class] hostFromAddress:localAddr6],
  2337. [[self class] portFromAddress:localAddr6]);
  2338. int status = bind(self->socket6FD, (const struct sockaddr *)[localAddr6 bytes], (socklen_t)[localAddr6 length]);
  2339. if (status == -1)
  2340. {
  2341. [self closeSockets];
  2342. NSString *reason = @"Error in bind() function";
  2343. err = [self errnoErrorWithReason:reason];
  2344. return_from_block;
  2345. }
  2346. }
  2347. // Update flags
  2348. self->flags |= kDidBind;
  2349. if (!useIPv4) self->flags |= kIPv4Deactivated;
  2350. if (!useIPv6) self->flags |= kIPv6Deactivated;
  2351. result = YES;
  2352. }};
  2353. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  2354. block();
  2355. else
  2356. dispatch_sync(socketQueue, block);
  2357. if (err)
  2358. LogError(@"Error binding to address: %@", err);
  2359. if (errPtr)
  2360. *errPtr = err;
  2361. return result;
  2362. }
  2363. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2364. #pragma mark Connecting
  2365. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2366. /**
  2367. * This method runs through the various checks required prior to a connect attempt.
  2368. * It is shared between the various connect methods.
  2369. **/
  2370. - (BOOL)preConnect:(NSError **)errPtr
  2371. {
  2372. if (![self preOp:errPtr])
  2373. {
  2374. return NO;
  2375. }
  2376. if ((flags & kConnecting) || (flags & kDidConnect))
  2377. {
  2378. if (errPtr)
  2379. {
  2380. NSString *msg = @"Cannot connect a socket more than once.";
  2381. *errPtr = [self badConfigError:msg];
  2382. }
  2383. return NO;
  2384. }
  2385. BOOL isIPv4Disabled = (config & kIPv4Disabled) ? YES : NO;
  2386. BOOL isIPv6Disabled = (config & kIPv6Disabled) ? YES : NO;
  2387. if (isIPv4Disabled && isIPv6Disabled) // Must have IPv4 or IPv6 enabled
  2388. {
  2389. if (errPtr)
  2390. {
  2391. NSString *msg = @"Both IPv4 and IPv6 have been disabled. Must enable at least one protocol first.";
  2392. *errPtr = [self badConfigError:msg];
  2393. }
  2394. return NO;
  2395. }
  2396. return YES;
  2397. }
  2398. - (BOOL)connectToHost:(NSString *)host onPort:(uint16_t)port error:(NSError **)errPtr
  2399. {
  2400. __block BOOL result = NO;
  2401. __block NSError *err = nil;
  2402. dispatch_block_t block = ^{ @autoreleasepool {
  2403. // Run through sanity checks.
  2404. if (![self preConnect:&err])
  2405. {
  2406. return_from_block;
  2407. }
  2408. // Check parameter(s)
  2409. if (host == nil)
  2410. {
  2411. NSString *msg = @"The host param is nil. Should be domain name or IP address string.";
  2412. err = [self badParamError:msg];
  2413. return_from_block;
  2414. }
  2415. // Create the socket(s) if needed
  2416. if ((self->flags & kDidCreateSockets) == 0)
  2417. {
  2418. if (![self createSockets:&err])
  2419. {
  2420. return_from_block;
  2421. }
  2422. }
  2423. // Create special connect packet
  2424. GCDAsyncUdpSpecialPacket *packet = [[GCDAsyncUdpSpecialPacket alloc] init];
  2425. packet->resolveInProgress = YES;
  2426. // Start asynchronous DNS resolve for host:port on background queue
  2427. LogVerbose(@"Dispatching DNS resolve for connect...");
  2428. [self asyncResolveHost:host port:port withCompletionBlock:^(NSArray *addresses, NSError *error) {
  2429. // The asyncResolveHost:port:: method asynchronously dispatches a task onto the global concurrent queue,
  2430. // and immediately returns. Once the async resolve task completes,
  2431. // this block is executed on our socketQueue.
  2432. packet->resolveInProgress = NO;
  2433. packet->addresses = addresses;
  2434. packet->error = error;
  2435. [self maybeConnect];
  2436. }];
  2437. // Updates flags, add connect packet to send queue, and pump send queue
  2438. self->flags |= kConnecting;
  2439. [self->sendQueue addObject:packet];
  2440. [self maybeDequeueSend];
  2441. result = YES;
  2442. }};
  2443. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  2444. block();
  2445. else
  2446. dispatch_sync(socketQueue, block);
  2447. if (err)
  2448. LogError(@"Error connecting to host/port: %@", err);
  2449. if (errPtr)
  2450. *errPtr = err;
  2451. return result;
  2452. }
  2453. - (BOOL)connectToAddress:(NSData *)remoteAddr error:(NSError **)errPtr
  2454. {
  2455. __block BOOL result = NO;
  2456. __block NSError *err = nil;
  2457. dispatch_block_t block = ^{ @autoreleasepool {
  2458. // Run through sanity checks.
  2459. if (![self preConnect:&err])
  2460. {
  2461. return_from_block;
  2462. }
  2463. // Check parameter(s)
  2464. if (remoteAddr == nil)
  2465. {
  2466. NSString *msg = @"The address param is nil. Should be a valid address.";
  2467. err = [self badParamError:msg];
  2468. return_from_block;
  2469. }
  2470. // Create the socket(s) if needed
  2471. if ((self->flags & kDidCreateSockets) == 0)
  2472. {
  2473. if (![self createSockets:&err])
  2474. {
  2475. return_from_block;
  2476. }
  2477. }
  2478. // The remoteAddr parameter could be of type NSMutableData.
  2479. // So we copy it to be safe.
  2480. NSData *address = [remoteAddr copy];
  2481. NSArray *addresses = [NSArray arrayWithObject:address];
  2482. GCDAsyncUdpSpecialPacket *packet = [[GCDAsyncUdpSpecialPacket alloc] init];
  2483. packet->addresses = addresses;
  2484. // Updates flags, add connect packet to send queue, and pump send queue
  2485. self->flags |= kConnecting;
  2486. [self->sendQueue addObject:packet];
  2487. [self maybeDequeueSend];
  2488. result = YES;
  2489. }};
  2490. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  2491. block();
  2492. else
  2493. dispatch_sync(socketQueue, block);
  2494. if (err)
  2495. LogError(@"Error connecting to address: %@", err);
  2496. if (errPtr)
  2497. *errPtr = err;
  2498. return result;
  2499. }
  2500. - (void)maybeConnect
  2501. {
  2502. LogTrace();
  2503. NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue");
  2504. BOOL sendQueueReady = [currentSend isKindOfClass:[GCDAsyncUdpSpecialPacket class]];
  2505. if (sendQueueReady)
  2506. {
  2507. GCDAsyncUdpSpecialPacket *connectPacket = (GCDAsyncUdpSpecialPacket *)currentSend;
  2508. if (connectPacket->resolveInProgress)
  2509. {
  2510. LogVerbose(@"Waiting for DNS resolve...");
  2511. }
  2512. else
  2513. {
  2514. if (connectPacket->error)
  2515. {
  2516. [self notifyDidNotConnect:connectPacket->error];
  2517. }
  2518. else
  2519. {
  2520. NSData *address = nil;
  2521. NSError *error = nil;
  2522. int addressFamily = [self getAddress:&address error:&error fromAddresses:connectPacket->addresses];
  2523. // Perform connect
  2524. BOOL result = NO;
  2525. switch (addressFamily)
  2526. {
  2527. case AF_INET : result = [self connectWithAddress4:address error:&error]; break;
  2528. case AF_INET6 : result = [self connectWithAddress6:address error:&error]; break;
  2529. }
  2530. if (result)
  2531. {
  2532. flags |= kDidBind;
  2533. flags |= kDidConnect;
  2534. cachedConnectedAddress = address;
  2535. cachedConnectedHost = [[self class] hostFromAddress:address];
  2536. cachedConnectedPort = [[self class] portFromAddress:address];
  2537. cachedConnectedFamily = addressFamily;
  2538. [self notifyDidConnectToAddress:address];
  2539. }
  2540. else
  2541. {
  2542. [self notifyDidNotConnect:error];
  2543. }
  2544. }
  2545. flags &= ~kConnecting;
  2546. [self endCurrentSend];
  2547. [self maybeDequeueSend];
  2548. }
  2549. }
  2550. }
  2551. - (BOOL)connectWithAddress4:(NSData *)address4 error:(NSError **)errPtr
  2552. {
  2553. LogTrace();
  2554. NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue");
  2555. int status = connect(socket4FD, (const struct sockaddr *)[address4 bytes], (socklen_t)[address4 length]);
  2556. if (status != 0)
  2557. {
  2558. if (errPtr)
  2559. *errPtr = [self errnoErrorWithReason:@"Error in connect() function"];
  2560. return NO;
  2561. }
  2562. [self closeSocket6];
  2563. flags |= kIPv6Deactivated;
  2564. return YES;
  2565. }
  2566. - (BOOL)connectWithAddress6:(NSData *)address6 error:(NSError **)errPtr
  2567. {
  2568. LogTrace();
  2569. NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue");
  2570. int status = connect(socket6FD, (const struct sockaddr *)[address6 bytes], (socklen_t)[address6 length]);
  2571. if (status != 0)
  2572. {
  2573. if (errPtr)
  2574. *errPtr = [self errnoErrorWithReason:@"Error in connect() function"];
  2575. return NO;
  2576. }
  2577. [self closeSocket4];
  2578. flags |= kIPv4Deactivated;
  2579. return YES;
  2580. }
  2581. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2582. #pragma mark Multicast
  2583. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2584. - (BOOL)preJoin:(NSError **)errPtr
  2585. {
  2586. if (![self preOp:errPtr])
  2587. {
  2588. return NO;
  2589. }
  2590. if (!(flags & kDidBind))
  2591. {
  2592. if (errPtr)
  2593. {
  2594. NSString *msg = @"Must bind a socket before joining a multicast group.";
  2595. *errPtr = [self badConfigError:msg];
  2596. }
  2597. return NO;
  2598. }
  2599. if ((flags & kConnecting) || (flags & kDidConnect))
  2600. {
  2601. if (errPtr)
  2602. {
  2603. NSString *msg = @"Cannot join a multicast group if connected.";
  2604. *errPtr = [self badConfigError:msg];
  2605. }
  2606. return NO;
  2607. }
  2608. return YES;
  2609. }
  2610. - (BOOL)joinMulticastGroup:(NSString *)group error:(NSError **)errPtr
  2611. {
  2612. return [self joinMulticastGroup:group onInterface:nil error:errPtr];
  2613. }
  2614. - (BOOL)joinMulticastGroup:(NSString *)group onInterface:(NSString *)interface error:(NSError **)errPtr
  2615. {
  2616. // IP_ADD_MEMBERSHIP == IPV6_JOIN_GROUP
  2617. return [self performMulticastRequest:IP_ADD_MEMBERSHIP forGroup:group onInterface:interface error:errPtr];
  2618. }
  2619. - (BOOL)leaveMulticastGroup:(NSString *)group error:(NSError **)errPtr
  2620. {
  2621. return [self leaveMulticastGroup:group onInterface:nil error:errPtr];
  2622. }
  2623. - (BOOL)leaveMulticastGroup:(NSString *)group onInterface:(NSString *)interface error:(NSError **)errPtr
  2624. {
  2625. // IP_DROP_MEMBERSHIP == IPV6_LEAVE_GROUP
  2626. return [self performMulticastRequest:IP_DROP_MEMBERSHIP forGroup:group onInterface:interface error:errPtr];
  2627. }
  2628. - (BOOL)performMulticastRequest:(int)requestType
  2629. forGroup:(NSString *)group
  2630. onInterface:(NSString *)interface
  2631. error:(NSError **)errPtr
  2632. {
  2633. __block BOOL result = NO;
  2634. __block NSError *err = nil;
  2635. dispatch_block_t block = ^{ @autoreleasepool {
  2636. // Run through sanity checks
  2637. if (![self preJoin:&err])
  2638. {
  2639. return_from_block;
  2640. }
  2641. // Convert group to address
  2642. NSData *groupAddr4 = nil;
  2643. NSData *groupAddr6 = nil;
  2644. [self convertNumericHost:group port:0 intoAddress4:&groupAddr4 address6:&groupAddr6];
  2645. if ((groupAddr4 == nil) && (groupAddr6 == nil))
  2646. {
  2647. NSString *msg = @"Unknown group. Specify valid group IP address.";
  2648. err = [self badParamError:msg];
  2649. return_from_block;
  2650. }
  2651. // Convert interface to address
  2652. NSData *interfaceAddr4 = nil;
  2653. NSData *interfaceAddr6 = nil;
  2654. [self convertIntefaceDescription:interface port:0 intoAddress4:&interfaceAddr4 address6:&interfaceAddr6];
  2655. if ((interfaceAddr4 == nil) && (interfaceAddr6 == nil))
  2656. {
  2657. NSString *msg = @"Unknown interface. Specify valid interface by name (e.g. \"en1\") or IP address.";
  2658. err = [self badParamError:msg];
  2659. return_from_block;
  2660. }
  2661. // Perform join
  2662. if ((self->socket4FD != SOCKET_NULL) && groupAddr4 && interfaceAddr4)
  2663. {
  2664. const struct sockaddr_in *nativeGroup = (const struct sockaddr_in *)[groupAddr4 bytes];
  2665. const struct sockaddr_in *nativeIface = (const struct sockaddr_in *)[interfaceAddr4 bytes];
  2666. struct ip_mreq imreq;
  2667. imreq.imr_multiaddr = nativeGroup->sin_addr;
  2668. imreq.imr_interface = nativeIface->sin_addr;
  2669. int status = setsockopt(self->socket4FD, IPPROTO_IP, requestType, (const void *)&imreq, sizeof(imreq));
  2670. if (status != 0)
  2671. {
  2672. err = [self errnoErrorWithReason:@"Error in setsockopt() function"];
  2673. return_from_block;
  2674. }
  2675. // Using IPv4 only
  2676. [self closeSocket6];
  2677. result = YES;
  2678. }
  2679. else if ((self->socket6FD != SOCKET_NULL) && groupAddr6 && interfaceAddr6)
  2680. {
  2681. const struct sockaddr_in6 *nativeGroup = (const struct sockaddr_in6 *)[groupAddr6 bytes];
  2682. struct ipv6_mreq imreq;
  2683. imreq.ipv6mr_multiaddr = nativeGroup->sin6_addr;
  2684. imreq.ipv6mr_interface = [self indexOfInterfaceAddr6:interfaceAddr6];
  2685. int status = setsockopt(self->socket6FD, IPPROTO_IPV6, requestType, (const void *)&imreq, sizeof(imreq));
  2686. if (status != 0)
  2687. {
  2688. err = [self errnoErrorWithReason:@"Error in setsockopt() function"];
  2689. return_from_block;
  2690. }
  2691. // Using IPv6 only
  2692. [self closeSocket4];
  2693. result = YES;
  2694. }
  2695. else
  2696. {
  2697. NSString *msg = @"Socket, group, and interface do not have matching IP versions";
  2698. err = [self badParamError:msg];
  2699. return_from_block;
  2700. }
  2701. }};
  2702. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  2703. block();
  2704. else
  2705. dispatch_sync(socketQueue, block);
  2706. if (errPtr)
  2707. *errPtr = err;
  2708. return result;
  2709. }
  2710. - (BOOL)sendIPv4MulticastOnInterface:(NSString*)interface error:(NSError **)errPtr
  2711. {
  2712. __block BOOL result = NO;
  2713. __block NSError *err = nil;
  2714. dispatch_block_t block = ^{ @autoreleasepool {
  2715. if (![self preOp:&err])
  2716. {
  2717. return_from_block;
  2718. }
  2719. if ((self->flags & kDidCreateSockets) == 0)
  2720. {
  2721. if (![self createSockets:&err])
  2722. {
  2723. return_from_block;
  2724. }
  2725. }
  2726. // Convert interface to address
  2727. NSData *interfaceAddr4 = nil;
  2728. NSData *interfaceAddr6 = nil;
  2729. [self convertIntefaceDescription:interface port:0 intoAddress4:&interfaceAddr4 address6:&interfaceAddr6];
  2730. if (interfaceAddr4 == nil)
  2731. {
  2732. NSString *msg = @"Unknown interface. Specify valid interface by IP address.";
  2733. err = [self badParamError:msg];
  2734. return_from_block;
  2735. }
  2736. if (self->socket4FD != SOCKET_NULL) {
  2737. const struct sockaddr_in *nativeIface = (struct sockaddr_in *)[interfaceAddr4 bytes];
  2738. struct in_addr interface_addr = nativeIface->sin_addr;
  2739. int status = setsockopt(self->socket4FD, IPPROTO_IP, IP_MULTICAST_IF, &interface_addr, sizeof(interface_addr));
  2740. if (status != 0) {
  2741. err = [self errnoErrorWithReason:@"Error in setsockopt() function"];
  2742. return_from_block;
  2743. result = YES;
  2744. }
  2745. }
  2746. }};
  2747. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  2748. block();
  2749. else
  2750. dispatch_sync(socketQueue, block);
  2751. if (errPtr)
  2752. *errPtr = err;
  2753. return result;
  2754. }
  2755. - (BOOL)sendIPv6MulticastOnInterface:(NSString*)interface error:(NSError **)errPtr
  2756. {
  2757. __block BOOL result = NO;
  2758. __block NSError *err = nil;
  2759. dispatch_block_t block = ^{ @autoreleasepool {
  2760. if (![self preOp:&err])
  2761. {
  2762. return_from_block;
  2763. }
  2764. if ((self->flags & kDidCreateSockets) == 0)
  2765. {
  2766. if (![self createSockets:&err])
  2767. {
  2768. return_from_block;
  2769. }
  2770. }
  2771. // Convert interface to address
  2772. NSData *interfaceAddr4 = nil;
  2773. NSData *interfaceAddr6 = nil;
  2774. [self convertIntefaceDescription:interface port:0 intoAddress4:&interfaceAddr4 address6:&interfaceAddr6];
  2775. if (interfaceAddr6 == nil)
  2776. {
  2777. NSString *msg = @"Unknown interface. Specify valid interface by name (e.g. \"en1\").";
  2778. err = [self badParamError:msg];
  2779. return_from_block;
  2780. }
  2781. if ((self->socket6FD != SOCKET_NULL)) {
  2782. uint32_t scope_id = [self indexOfInterfaceAddr6:interfaceAddr6];
  2783. int status = setsockopt(self->socket6FD, IPPROTO_IPV6, IPV6_MULTICAST_IF, &scope_id, sizeof(scope_id));
  2784. if (status != 0) {
  2785. err = [self errnoErrorWithReason:@"Error in setsockopt() function"];
  2786. return_from_block;
  2787. }
  2788. result = YES;
  2789. }
  2790. }};
  2791. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  2792. block();
  2793. else
  2794. dispatch_sync(socketQueue, block);
  2795. if (errPtr)
  2796. *errPtr = err;
  2797. return result;
  2798. }
  2799. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2800. #pragma mark Reuse port
  2801. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2802. - (BOOL)enableReusePort:(BOOL)flag error:(NSError **)errPtr
  2803. {
  2804. __block BOOL result = NO;
  2805. __block NSError *err = nil;
  2806. dispatch_block_t block = ^{ @autoreleasepool {
  2807. if (![self preOp:&err])
  2808. {
  2809. return_from_block;
  2810. }
  2811. if ((self->flags & kDidCreateSockets) == 0)
  2812. {
  2813. if (![self createSockets:&err])
  2814. {
  2815. return_from_block;
  2816. }
  2817. }
  2818. int value = flag ? 1 : 0;
  2819. if (self->socket4FD != SOCKET_NULL)
  2820. {
  2821. int error = setsockopt(self->socket4FD, SOL_SOCKET, SO_REUSEPORT, (const void *)&value, sizeof(value));
  2822. if (error)
  2823. {
  2824. err = [self errnoErrorWithReason:@"Error in setsockopt() function"];
  2825. return_from_block;
  2826. }
  2827. result = YES;
  2828. }
  2829. if (self->socket6FD != SOCKET_NULL)
  2830. {
  2831. int error = setsockopt(self->socket6FD, SOL_SOCKET, SO_REUSEPORT, (const void *)&value, sizeof(value));
  2832. if (error)
  2833. {
  2834. err = [self errnoErrorWithReason:@"Error in setsockopt() function"];
  2835. return_from_block;
  2836. }
  2837. result = YES;
  2838. }
  2839. }};
  2840. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  2841. block();
  2842. else
  2843. dispatch_sync(socketQueue, block);
  2844. if (errPtr)
  2845. *errPtr = err;
  2846. return result;
  2847. }
  2848. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2849. #pragma mark Broadcast
  2850. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2851. - (BOOL)enableBroadcast:(BOOL)flag error:(NSError **)errPtr
  2852. {
  2853. __block BOOL result = NO;
  2854. __block NSError *err = nil;
  2855. dispatch_block_t block = ^{ @autoreleasepool {
  2856. if (![self preOp:&err])
  2857. {
  2858. return_from_block;
  2859. }
  2860. if ((self->flags & kDidCreateSockets) == 0)
  2861. {
  2862. if (![self createSockets:&err])
  2863. {
  2864. return_from_block;
  2865. }
  2866. }
  2867. if (self->socket4FD != SOCKET_NULL)
  2868. {
  2869. int value = flag ? 1 : 0;
  2870. int error = setsockopt(self->socket4FD, SOL_SOCKET, SO_BROADCAST, (const void *)&value, sizeof(value));
  2871. if (error)
  2872. {
  2873. err = [self errnoErrorWithReason:@"Error in setsockopt() function"];
  2874. return_from_block;
  2875. }
  2876. result = YES;
  2877. }
  2878. // IPv6 does not implement broadcast, the ability to send a packet to all hosts on the attached link.
  2879. // The same effect can be achieved by sending a packet to the link-local all hosts multicast group.
  2880. }};
  2881. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  2882. block();
  2883. else
  2884. dispatch_sync(socketQueue, block);
  2885. if (errPtr)
  2886. *errPtr = err;
  2887. return result;
  2888. }
  2889. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2890. #pragma mark Sending
  2891. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  2892. - (void)sendData:(NSData *)data withTag:(long)tag
  2893. {
  2894. [self sendData:data withTimeout:-1.0 tag:tag];
  2895. }
  2896. - (void)sendData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag
  2897. {
  2898. LogTrace();
  2899. if ([data length] == 0)
  2900. {
  2901. LogWarn(@"Ignoring attempt to send nil/empty data.");
  2902. return;
  2903. }
  2904. GCDAsyncUdpSendPacket *packet = [[GCDAsyncUdpSendPacket alloc] initWithData:data timeout:timeout tag:tag];
  2905. dispatch_async(socketQueue, ^{ @autoreleasepool {
  2906. [self->sendQueue addObject:packet];
  2907. [self maybeDequeueSend];
  2908. }});
  2909. }
  2910. - (void)sendData:(NSData *)data
  2911. toHost:(NSString *)host
  2912. port:(uint16_t)port
  2913. withTimeout:(NSTimeInterval)timeout
  2914. tag:(long)tag
  2915. {
  2916. LogTrace();
  2917. if ([data length] == 0)
  2918. {
  2919. LogWarn(@"Ignoring attempt to send nil/empty data.");
  2920. return;
  2921. }
  2922. GCDAsyncUdpSendPacket *packet = [[GCDAsyncUdpSendPacket alloc] initWithData:data timeout:timeout tag:tag];
  2923. packet->resolveInProgress = YES;
  2924. [self asyncResolveHost:host port:port withCompletionBlock:^(NSArray *addresses, NSError *error) {
  2925. // The asyncResolveHost:port:: method asynchronously dispatches a task onto the global concurrent queue,
  2926. // and immediately returns. Once the async resolve task completes,
  2927. // this block is executed on our socketQueue.
  2928. packet->resolveInProgress = NO;
  2929. packet->resolvedAddresses = addresses;
  2930. packet->resolveError = error;
  2931. if (packet == self->currentSend)
  2932. {
  2933. LogVerbose(@"currentSend - address resolved");
  2934. [self doPreSend];
  2935. }
  2936. }];
  2937. dispatch_async(socketQueue, ^{ @autoreleasepool {
  2938. [self->sendQueue addObject:packet];
  2939. [self maybeDequeueSend];
  2940. }});
  2941. }
  2942. - (void)sendData:(NSData *)data toAddress:(NSData *)remoteAddr withTimeout:(NSTimeInterval)timeout tag:(long)tag
  2943. {
  2944. LogTrace();
  2945. if ([data length] == 0)
  2946. {
  2947. LogWarn(@"Ignoring attempt to send nil/empty data.");
  2948. return;
  2949. }
  2950. GCDAsyncUdpSendPacket *packet = [[GCDAsyncUdpSendPacket alloc] initWithData:data timeout:timeout tag:tag];
  2951. packet->addressFamily = [GCDAsyncUdpSocket familyFromAddress:remoteAddr];
  2952. packet->address = remoteAddr;
  2953. dispatch_async(socketQueue, ^{ @autoreleasepool {
  2954. [self->sendQueue addObject:packet];
  2955. [self maybeDequeueSend];
  2956. }});
  2957. }
  2958. - (void)setSendFilter:(GCDAsyncUdpSocketSendFilterBlock)filterBlock withQueue:(dispatch_queue_t)filterQueue
  2959. {
  2960. [self setSendFilter:filterBlock withQueue:filterQueue isAsynchronous:YES];
  2961. }
  2962. - (void)setSendFilter:(GCDAsyncUdpSocketSendFilterBlock)filterBlock
  2963. withQueue:(dispatch_queue_t)filterQueue
  2964. isAsynchronous:(BOOL)isAsynchronous
  2965. {
  2966. GCDAsyncUdpSocketSendFilterBlock newFilterBlock = NULL;
  2967. dispatch_queue_t newFilterQueue = NULL;
  2968. if (filterBlock)
  2969. {
  2970. NSAssert(filterQueue, @"Must provide a dispatch_queue in which to run the filter block.");
  2971. newFilterBlock = [filterBlock copy];
  2972. newFilterQueue = filterQueue;
  2973. #if !OS_OBJECT_USE_OBJC
  2974. dispatch_retain(newFilterQueue);
  2975. #endif
  2976. }
  2977. dispatch_block_t block = ^{
  2978. #if !OS_OBJECT_USE_OBJC
  2979. if (self->sendFilterQueue) dispatch_release(self->sendFilterQueue);
  2980. #endif
  2981. self->sendFilterBlock = newFilterBlock;
  2982. self->sendFilterQueue = newFilterQueue;
  2983. self->sendFilterAsync = isAsynchronous;
  2984. };
  2985. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  2986. block();
  2987. else
  2988. dispatch_async(socketQueue, block);
  2989. }
  2990. - (void)maybeDequeueSend
  2991. {
  2992. LogTrace();
  2993. NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue");
  2994. // If we don't have a send operation already in progress
  2995. if (currentSend == nil)
  2996. {
  2997. // Create the sockets if needed
  2998. if ((flags & kDidCreateSockets) == 0)
  2999. {
  3000. NSError *err = nil;
  3001. if (![self createSockets:&err])
  3002. {
  3003. [self closeWithError:err];
  3004. return;
  3005. }
  3006. }
  3007. while ([sendQueue count] > 0)
  3008. {
  3009. // Dequeue the next object in the queue
  3010. currentSend = [sendQueue objectAtIndex:0];
  3011. [sendQueue removeObjectAtIndex:0];
  3012. if ([currentSend isKindOfClass:[GCDAsyncUdpSpecialPacket class]])
  3013. {
  3014. [self maybeConnect];
  3015. return; // The maybeConnect method, if it connects, will invoke this method again
  3016. }
  3017. else if (currentSend->resolveError)
  3018. {
  3019. // Notify delegate
  3020. [self notifyDidNotSendDataWithTag:currentSend->tag dueToError:currentSend->resolveError];
  3021. // Clear currentSend
  3022. currentSend = nil;
  3023. continue;
  3024. }
  3025. else
  3026. {
  3027. // Start preprocessing checks on the send packet
  3028. [self doPreSend];
  3029. break;
  3030. }
  3031. }
  3032. if ((currentSend == nil) && (flags & kCloseAfterSends))
  3033. {
  3034. [self closeWithError:nil];
  3035. }
  3036. }
  3037. }
  3038. /**
  3039. * This method is called after a sendPacket has been dequeued.
  3040. * It performs various preprocessing checks on the packet,
  3041. * and queries the sendFilter (if set) to determine if the packet can be sent.
  3042. *
  3043. * If the packet passes all checks, it will be passed on to the doSend method.
  3044. **/
  3045. - (void)doPreSend
  3046. {
  3047. LogTrace();
  3048. //
  3049. // 1. Check for problems with send packet
  3050. //
  3051. BOOL waitingForResolve = NO;
  3052. NSError *error = nil;
  3053. if (flags & kDidConnect)
  3054. {
  3055. // Connected socket
  3056. if (currentSend->resolveInProgress || currentSend->resolvedAddresses || currentSend->resolveError)
  3057. {
  3058. NSString *msg = @"Cannot specify destination of packet for connected socket";
  3059. error = [self badConfigError:msg];
  3060. }
  3061. else
  3062. {
  3063. currentSend->address = cachedConnectedAddress;
  3064. currentSend->addressFamily = cachedConnectedFamily;
  3065. }
  3066. }
  3067. else
  3068. {
  3069. // Non-Connected socket
  3070. if (currentSend->resolveInProgress)
  3071. {
  3072. // We're waiting for the packet's destination to be resolved.
  3073. waitingForResolve = YES;
  3074. }
  3075. else if (currentSend->resolveError)
  3076. {
  3077. error = currentSend->resolveError;
  3078. }
  3079. else if (currentSend->address == nil)
  3080. {
  3081. if (currentSend->resolvedAddresses == nil)
  3082. {
  3083. NSString *msg = @"You must specify destination of packet for a non-connected socket";
  3084. error = [self badConfigError:msg];
  3085. }
  3086. else
  3087. {
  3088. // Pick the proper address to use (out of possibly several resolved addresses)
  3089. NSData *address = nil;
  3090. int addressFamily = AF_UNSPEC;
  3091. addressFamily = [self getAddress:&address error:&error fromAddresses:currentSend->resolvedAddresses];
  3092. currentSend->address = address;
  3093. currentSend->addressFamily = addressFamily;
  3094. }
  3095. }
  3096. }
  3097. if (waitingForResolve)
  3098. {
  3099. // We're waiting for the packet's destination to be resolved.
  3100. LogVerbose(@"currentSend - waiting for address resolve");
  3101. if (flags & kSock4CanAcceptBytes) {
  3102. [self suspendSend4Source];
  3103. }
  3104. if (flags & kSock6CanAcceptBytes) {
  3105. [self suspendSend6Source];
  3106. }
  3107. return;
  3108. }
  3109. if (error)
  3110. {
  3111. // Unable to send packet due to some error.
  3112. // Notify delegate and move on.
  3113. [self notifyDidNotSendDataWithTag:currentSend->tag dueToError:error];
  3114. [self endCurrentSend];
  3115. [self maybeDequeueSend];
  3116. return;
  3117. }
  3118. //
  3119. // 2. Query sendFilter (if applicable)
  3120. //
  3121. if (sendFilterBlock && sendFilterQueue)
  3122. {
  3123. // Query sendFilter
  3124. if (sendFilterAsync)
  3125. {
  3126. // Scenario 1 of 3 - Need to asynchronously query sendFilter
  3127. currentSend->filterInProgress = YES;
  3128. GCDAsyncUdpSendPacket *sendPacket = currentSend;
  3129. dispatch_async(sendFilterQueue, ^{ @autoreleasepool {
  3130. BOOL allowed = self->sendFilterBlock(sendPacket->buffer, sendPacket->address, sendPacket->tag);
  3131. dispatch_async(self->socketQueue, ^{ @autoreleasepool {
  3132. sendPacket->filterInProgress = NO;
  3133. if (sendPacket == self->currentSend)
  3134. {
  3135. if (allowed)
  3136. {
  3137. [self doSend];
  3138. }
  3139. else
  3140. {
  3141. LogVerbose(@"currentSend - silently dropped by sendFilter");
  3142. [self notifyDidSendDataWithTag:self->currentSend->tag];
  3143. [self endCurrentSend];
  3144. [self maybeDequeueSend];
  3145. }
  3146. }
  3147. }});
  3148. }});
  3149. }
  3150. else
  3151. {
  3152. // Scenario 2 of 3 - Need to synchronously query sendFilter
  3153. __block BOOL allowed = YES;
  3154. dispatch_sync(sendFilterQueue, ^{ @autoreleasepool {
  3155. allowed = self->sendFilterBlock(self->currentSend->buffer, self->currentSend->address, self->currentSend->tag);
  3156. }});
  3157. if (allowed)
  3158. {
  3159. [self doSend];
  3160. }
  3161. else
  3162. {
  3163. LogVerbose(@"currentSend - silently dropped by sendFilter");
  3164. [self notifyDidSendDataWithTag:currentSend->tag];
  3165. [self endCurrentSend];
  3166. [self maybeDequeueSend];
  3167. }
  3168. }
  3169. }
  3170. else // if (!sendFilterBlock || !sendFilterQueue)
  3171. {
  3172. // Scenario 3 of 3 - No sendFilter. Just go straight into sending.
  3173. [self doSend];
  3174. }
  3175. }
  3176. /**
  3177. * This method performs the actual sending of data in the currentSend packet.
  3178. * It should only be called if the
  3179. **/
  3180. - (void)doSend
  3181. {
  3182. LogTrace();
  3183. NSAssert(currentSend != nil, @"Invalid logic");
  3184. // Perform the actual send
  3185. ssize_t result = 0;
  3186. if (flags & kDidConnect)
  3187. {
  3188. // Connected socket
  3189. const void *buffer = [currentSend->buffer bytes];
  3190. size_t length = (size_t)[currentSend->buffer length];
  3191. if (currentSend->addressFamily == AF_INET)
  3192. {
  3193. result = send(socket4FD, buffer, length, 0);
  3194. LogVerbose(@"send(socket4FD) = %d", result);
  3195. }
  3196. else
  3197. {
  3198. result = send(socket6FD, buffer, length, 0);
  3199. LogVerbose(@"send(socket6FD) = %d", result);
  3200. }
  3201. }
  3202. else
  3203. {
  3204. // Non-Connected socket
  3205. const void *buffer = [currentSend->buffer bytes];
  3206. size_t length = (size_t)[currentSend->buffer length];
  3207. const void *dst = [currentSend->address bytes];
  3208. socklen_t dstSize = (socklen_t)[currentSend->address length];
  3209. if (currentSend->addressFamily == AF_INET)
  3210. {
  3211. result = sendto(socket4FD, buffer, length, 0, dst, dstSize);
  3212. LogVerbose(@"sendto(socket4FD) = %d", result);
  3213. }
  3214. else
  3215. {
  3216. result = sendto(socket6FD, buffer, length, 0, dst, dstSize);
  3217. LogVerbose(@"sendto(socket6FD) = %d", result);
  3218. }
  3219. }
  3220. // If the socket wasn't bound before, it is now
  3221. if ((flags & kDidBind) == 0)
  3222. {
  3223. flags |= kDidBind;
  3224. }
  3225. // Check the results.
  3226. //
  3227. // From the send() & sendto() manpage:
  3228. //
  3229. // Upon successful completion, the number of bytes which were sent is returned.
  3230. // Otherwise, -1 is returned and the global variable errno is set to indicate the error.
  3231. BOOL waitingForSocket = NO;
  3232. NSError *socketError = nil;
  3233. if (result == 0)
  3234. {
  3235. waitingForSocket = YES;
  3236. }
  3237. else if (result < 0)
  3238. {
  3239. if (errno == EAGAIN)
  3240. waitingForSocket = YES;
  3241. else
  3242. socketError = [self errnoErrorWithReason:@"Error in send() function."];
  3243. }
  3244. if (waitingForSocket)
  3245. {
  3246. // Not enough room in the underlying OS socket send buffer.
  3247. // Wait for a notification of available space.
  3248. LogVerbose(@"currentSend - waiting for socket");
  3249. if (!(flags & kSock4CanAcceptBytes)) {
  3250. [self resumeSend4Source];
  3251. }
  3252. if (!(flags & kSock6CanAcceptBytes)) {
  3253. [self resumeSend6Source];
  3254. }
  3255. if ((sendTimer == NULL) && (currentSend->timeout >= 0.0))
  3256. {
  3257. // Unable to send packet right away.
  3258. // Start timer to timeout the send operation.
  3259. [self setupSendTimerWithTimeout:currentSend->timeout];
  3260. }
  3261. }
  3262. else if (socketError)
  3263. {
  3264. [self closeWithError:socketError];
  3265. }
  3266. else // done
  3267. {
  3268. [self notifyDidSendDataWithTag:currentSend->tag];
  3269. [self endCurrentSend];
  3270. [self maybeDequeueSend];
  3271. }
  3272. }
  3273. /**
  3274. * Releases all resources associated with the currentSend.
  3275. **/
  3276. - (void)endCurrentSend
  3277. {
  3278. if (sendTimer)
  3279. {
  3280. dispatch_source_cancel(sendTimer);
  3281. #if !OS_OBJECT_USE_OBJC
  3282. dispatch_release(sendTimer);
  3283. #endif
  3284. sendTimer = NULL;
  3285. }
  3286. currentSend = nil;
  3287. }
  3288. /**
  3289. * Performs the operations to timeout the current send operation, and move on.
  3290. **/
  3291. - (void)doSendTimeout
  3292. {
  3293. LogTrace();
  3294. [self notifyDidNotSendDataWithTag:currentSend->tag dueToError:[self sendTimeoutError]];
  3295. [self endCurrentSend];
  3296. [self maybeDequeueSend];
  3297. }
  3298. /**
  3299. * Sets up a timer that fires to timeout the current send operation.
  3300. * This method should only be called once per send packet.
  3301. **/
  3302. - (void)setupSendTimerWithTimeout:(NSTimeInterval)timeout
  3303. {
  3304. NSAssert(sendTimer == NULL, @"Invalid logic");
  3305. NSAssert(timeout >= 0.0, @"Invalid logic");
  3306. LogTrace();
  3307. sendTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, socketQueue);
  3308. dispatch_source_set_event_handler(sendTimer, ^{ @autoreleasepool {
  3309. [self doSendTimeout];
  3310. }});
  3311. dispatch_time_t tt = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeout * NSEC_PER_SEC));
  3312. dispatch_source_set_timer(sendTimer, tt, DISPATCH_TIME_FOREVER, 0);
  3313. dispatch_resume(sendTimer);
  3314. }
  3315. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  3316. #pragma mark Receiving
  3317. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  3318. - (BOOL)receiveOnce:(NSError **)errPtr
  3319. {
  3320. LogTrace();
  3321. __block BOOL result = NO;
  3322. __block NSError *err = nil;
  3323. dispatch_block_t block = ^{
  3324. if ((self->flags & kReceiveOnce) == 0)
  3325. {
  3326. if ((self->flags & kDidCreateSockets) == 0)
  3327. {
  3328. NSString *msg = @"Must bind socket before you can receive data. "
  3329. @"You can do this explicitly via bind, or implicitly via connect or by sending data.";
  3330. err = [self badConfigError:msg];
  3331. return_from_block;
  3332. }
  3333. self->flags |= kReceiveOnce; // Enable
  3334. self->flags &= ~kReceiveContinuous; // Disable
  3335. dispatch_async(self->socketQueue, ^{ @autoreleasepool {
  3336. [self doReceive];
  3337. }});
  3338. }
  3339. result = YES;
  3340. };
  3341. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  3342. block();
  3343. else
  3344. dispatch_sync(socketQueue, block);
  3345. if (err)
  3346. LogError(@"Error in beginReceiving: %@", err);
  3347. if (errPtr)
  3348. *errPtr = err;
  3349. return result;
  3350. }
  3351. - (BOOL)beginReceiving:(NSError **)errPtr
  3352. {
  3353. LogTrace();
  3354. __block BOOL result = NO;
  3355. __block NSError *err = nil;
  3356. dispatch_block_t block = ^{
  3357. if ((self->flags & kReceiveContinuous) == 0)
  3358. {
  3359. if ((self->flags & kDidCreateSockets) == 0)
  3360. {
  3361. NSString *msg = @"Must bind socket before you can receive data. "
  3362. @"You can do this explicitly via bind, or implicitly via connect or by sending data.";
  3363. err = [self badConfigError:msg];
  3364. return_from_block;
  3365. }
  3366. self->flags |= kReceiveContinuous; // Enable
  3367. self->flags &= ~kReceiveOnce; // Disable
  3368. dispatch_async(self->socketQueue, ^{ @autoreleasepool {
  3369. [self doReceive];
  3370. }});
  3371. }
  3372. result = YES;
  3373. };
  3374. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  3375. block();
  3376. else
  3377. dispatch_sync(socketQueue, block);
  3378. if (err)
  3379. LogError(@"Error in beginReceiving: %@", err);
  3380. if (errPtr)
  3381. *errPtr = err;
  3382. return result;
  3383. }
  3384. - (void)pauseReceiving
  3385. {
  3386. LogTrace();
  3387. dispatch_block_t block = ^{
  3388. self->flags &= ~kReceiveOnce; // Disable
  3389. self->flags &= ~kReceiveContinuous; // Disable
  3390. if (self->socket4FDBytesAvailable > 0) {
  3391. [self suspendReceive4Source];
  3392. }
  3393. if (self->socket6FDBytesAvailable > 0) {
  3394. [self suspendReceive6Source];
  3395. }
  3396. };
  3397. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  3398. block();
  3399. else
  3400. dispatch_async(socketQueue, block);
  3401. }
  3402. - (void)setReceiveFilter:(GCDAsyncUdpSocketReceiveFilterBlock)filterBlock withQueue:(dispatch_queue_t)filterQueue
  3403. {
  3404. [self setReceiveFilter:filterBlock withQueue:filterQueue isAsynchronous:YES];
  3405. }
  3406. - (void)setReceiveFilter:(GCDAsyncUdpSocketReceiveFilterBlock)filterBlock
  3407. withQueue:(dispatch_queue_t)filterQueue
  3408. isAsynchronous:(BOOL)isAsynchronous
  3409. {
  3410. GCDAsyncUdpSocketReceiveFilterBlock newFilterBlock = NULL;
  3411. dispatch_queue_t newFilterQueue = NULL;
  3412. if (filterBlock)
  3413. {
  3414. NSAssert(filterQueue, @"Must provide a dispatch_queue in which to run the filter block.");
  3415. newFilterBlock = [filterBlock copy];
  3416. newFilterQueue = filterQueue;
  3417. #if !OS_OBJECT_USE_OBJC
  3418. dispatch_retain(newFilterQueue);
  3419. #endif
  3420. }
  3421. dispatch_block_t block = ^{
  3422. #if !OS_OBJECT_USE_OBJC
  3423. if (self->receiveFilterQueue) dispatch_release(self->receiveFilterQueue);
  3424. #endif
  3425. self->receiveFilterBlock = newFilterBlock;
  3426. self->receiveFilterQueue = newFilterQueue;
  3427. self->receiveFilterAsync = isAsynchronous;
  3428. };
  3429. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  3430. block();
  3431. else
  3432. dispatch_async(socketQueue, block);
  3433. }
  3434. - (void)doReceive
  3435. {
  3436. LogTrace();
  3437. if ((flags & (kReceiveOnce | kReceiveContinuous)) == 0)
  3438. {
  3439. LogVerbose(@"Receiving is paused...");
  3440. if (socket4FDBytesAvailable > 0) {
  3441. [self suspendReceive4Source];
  3442. }
  3443. if (socket6FDBytesAvailable > 0) {
  3444. [self suspendReceive6Source];
  3445. }
  3446. return;
  3447. }
  3448. if ((flags & kReceiveOnce) && (pendingFilterOperations > 0))
  3449. {
  3450. LogVerbose(@"Receiving is temporarily paused (pending filter operations)...");
  3451. if (socket4FDBytesAvailable > 0) {
  3452. [self suspendReceive4Source];
  3453. }
  3454. if (socket6FDBytesAvailable > 0) {
  3455. [self suspendReceive6Source];
  3456. }
  3457. return;
  3458. }
  3459. if ((socket4FDBytesAvailable == 0) && (socket6FDBytesAvailable == 0))
  3460. {
  3461. LogVerbose(@"No data available to receive...");
  3462. if (socket4FDBytesAvailable == 0) {
  3463. [self resumeReceive4Source];
  3464. }
  3465. if (socket6FDBytesAvailable == 0) {
  3466. [self resumeReceive6Source];
  3467. }
  3468. return;
  3469. }
  3470. // Figure out if we should receive on socket4 or socket6
  3471. BOOL doReceive4;
  3472. if (flags & kDidConnect)
  3473. {
  3474. // Connected socket
  3475. doReceive4 = (socket4FD != SOCKET_NULL);
  3476. }
  3477. else
  3478. {
  3479. // Non-Connected socket
  3480. if (socket4FDBytesAvailable > 0)
  3481. {
  3482. if (socket6FDBytesAvailable > 0)
  3483. {
  3484. // Bytes available on socket4 & socket6
  3485. doReceive4 = (flags & kFlipFlop) ? YES : NO;
  3486. flags ^= kFlipFlop; // flags = flags xor kFlipFlop; (toggle flip flop bit)
  3487. }
  3488. else {
  3489. // Bytes available on socket4, but not socket6
  3490. doReceive4 = YES;
  3491. }
  3492. }
  3493. else {
  3494. // Bytes available on socket6, but not socket4
  3495. doReceive4 = NO;
  3496. }
  3497. }
  3498. // Perform socket IO
  3499. ssize_t result = 0;
  3500. NSData *data = nil;
  3501. NSData *addr4 = nil;
  3502. NSData *addr6 = nil;
  3503. if (doReceive4)
  3504. {
  3505. NSAssert(socket4FDBytesAvailable > 0, @"Invalid logic");
  3506. LogVerbose(@"Receiving on IPv4");
  3507. struct sockaddr_in sockaddr4;
  3508. socklen_t sockaddr4len = sizeof(sockaddr4);
  3509. // #222: GCD does not necessarily return the size of an entire UDP packet
  3510. // from dispatch_source_get_data(), so we must use the maximum packet size.
  3511. size_t bufSize = max4ReceiveSize;
  3512. void *buf = malloc(bufSize);
  3513. result = recvfrom(socket4FD, buf, bufSize, 0, (struct sockaddr *)&sockaddr4, &sockaddr4len);
  3514. LogVerbose(@"recvfrom(socket4FD) = %i", (int)result);
  3515. if (result > 0)
  3516. {
  3517. if ((size_t)result >= socket4FDBytesAvailable)
  3518. socket4FDBytesAvailable = 0;
  3519. else
  3520. socket4FDBytesAvailable -= result;
  3521. if ((size_t)result != bufSize) {
  3522. buf = realloc(buf, result);
  3523. }
  3524. data = [NSData dataWithBytesNoCopy:buf length:result freeWhenDone:YES];
  3525. addr4 = [NSData dataWithBytes:&sockaddr4 length:sockaddr4len];
  3526. }
  3527. else
  3528. {
  3529. LogVerbose(@"recvfrom(socket4FD) = %@", [self errnoError]);
  3530. socket4FDBytesAvailable = 0;
  3531. free(buf);
  3532. }
  3533. }
  3534. else
  3535. {
  3536. NSAssert(socket6FDBytesAvailable > 0, @"Invalid logic");
  3537. LogVerbose(@"Receiving on IPv6");
  3538. struct sockaddr_in6 sockaddr6;
  3539. socklen_t sockaddr6len = sizeof(sockaddr6);
  3540. // #222: GCD does not necessarily return the size of an entire UDP packet
  3541. // from dispatch_source_get_data(), so we must use the maximum packet size.
  3542. size_t bufSize = max6ReceiveSize;
  3543. void *buf = malloc(bufSize);
  3544. result = recvfrom(socket6FD, buf, bufSize, 0, (struct sockaddr *)&sockaddr6, &sockaddr6len);
  3545. LogVerbose(@"recvfrom(socket6FD) -> %i", (int)result);
  3546. if (result > 0)
  3547. {
  3548. if ((size_t)result >= socket6FDBytesAvailable)
  3549. socket6FDBytesAvailable = 0;
  3550. else
  3551. socket6FDBytesAvailable -= result;
  3552. if ((size_t)result != bufSize) {
  3553. buf = realloc(buf, result);
  3554. }
  3555. data = [NSData dataWithBytesNoCopy:buf length:result freeWhenDone:YES];
  3556. addr6 = [NSData dataWithBytes:&sockaddr6 length:sockaddr6len];
  3557. }
  3558. else
  3559. {
  3560. LogVerbose(@"recvfrom(socket6FD) = %@", [self errnoError]);
  3561. socket6FDBytesAvailable = 0;
  3562. free(buf);
  3563. }
  3564. }
  3565. BOOL waitingForSocket = NO;
  3566. BOOL notifiedDelegate = NO;
  3567. BOOL ignored = NO;
  3568. NSError *socketError = nil;
  3569. if (result == 0)
  3570. {
  3571. waitingForSocket = YES;
  3572. }
  3573. else if (result < 0)
  3574. {
  3575. if (errno == EAGAIN)
  3576. waitingForSocket = YES;
  3577. else
  3578. socketError = [self errnoErrorWithReason:@"Error in recvfrom() function"];
  3579. }
  3580. else
  3581. {
  3582. if (flags & kDidConnect)
  3583. {
  3584. if (addr4 && ![self isConnectedToAddress4:addr4])
  3585. ignored = YES;
  3586. if (addr6 && ![self isConnectedToAddress6:addr6])
  3587. ignored = YES;
  3588. }
  3589. NSData *addr = (addr4 != nil) ? addr4 : addr6;
  3590. if (!ignored)
  3591. {
  3592. if (receiveFilterBlock && receiveFilterQueue)
  3593. {
  3594. // Run data through filter, and if approved, notify delegate
  3595. __block id filterContext = nil;
  3596. __block BOOL allowed = NO;
  3597. if (receiveFilterAsync)
  3598. {
  3599. pendingFilterOperations++;
  3600. dispatch_async(receiveFilterQueue, ^{ @autoreleasepool {
  3601. allowed = self->receiveFilterBlock(data, addr, &filterContext);
  3602. // Transition back to socketQueue to get the current delegate / delegateQueue
  3603. dispatch_async(self->socketQueue, ^{ @autoreleasepool {
  3604. self->pendingFilterOperations--;
  3605. if (allowed)
  3606. {
  3607. [self notifyDidReceiveData:data fromAddress:addr withFilterContext:filterContext];
  3608. }
  3609. else
  3610. {
  3611. LogVerbose(@"received packet silently dropped by receiveFilter");
  3612. }
  3613. if (self->flags & kReceiveOnce)
  3614. {
  3615. if (allowed)
  3616. {
  3617. // The delegate has been notified,
  3618. // so our receive once operation has completed.
  3619. self->flags &= ~kReceiveOnce;
  3620. }
  3621. else if (self->pendingFilterOperations == 0)
  3622. {
  3623. // All pending filter operations have completed,
  3624. // and none were allowed through.
  3625. // Our receive once operation hasn't completed yet.
  3626. [self doReceive];
  3627. }
  3628. }
  3629. }});
  3630. }});
  3631. }
  3632. else // if (!receiveFilterAsync)
  3633. {
  3634. dispatch_sync(receiveFilterQueue, ^{ @autoreleasepool {
  3635. allowed = self->receiveFilterBlock(data, addr, &filterContext);
  3636. }});
  3637. if (allowed)
  3638. {
  3639. [self notifyDidReceiveData:data fromAddress:addr withFilterContext:filterContext];
  3640. notifiedDelegate = YES;
  3641. }
  3642. else
  3643. {
  3644. LogVerbose(@"received packet silently dropped by receiveFilter");
  3645. ignored = YES;
  3646. }
  3647. }
  3648. }
  3649. else // if (!receiveFilterBlock || !receiveFilterQueue)
  3650. {
  3651. [self notifyDidReceiveData:data fromAddress:addr withFilterContext:nil];
  3652. notifiedDelegate = YES;
  3653. }
  3654. }
  3655. }
  3656. if (waitingForSocket)
  3657. {
  3658. // Wait for a notification of available data.
  3659. if (socket4FDBytesAvailable == 0) {
  3660. [self resumeReceive4Source];
  3661. }
  3662. if (socket6FDBytesAvailable == 0) {
  3663. [self resumeReceive6Source];
  3664. }
  3665. }
  3666. else if (socketError)
  3667. {
  3668. [self closeWithError:socketError];
  3669. }
  3670. else
  3671. {
  3672. if (flags & kReceiveContinuous)
  3673. {
  3674. // Continuous receive mode
  3675. [self doReceive];
  3676. }
  3677. else
  3678. {
  3679. // One-at-a-time receive mode
  3680. if (notifiedDelegate)
  3681. {
  3682. // The delegate has been notified (no set filter).
  3683. // So our receive once operation has completed.
  3684. flags &= ~kReceiveOnce;
  3685. }
  3686. else if (ignored)
  3687. {
  3688. [self doReceive];
  3689. }
  3690. else
  3691. {
  3692. // Waiting on asynchronous receive filter...
  3693. }
  3694. }
  3695. }
  3696. }
  3697. - (void)doReceiveEOF
  3698. {
  3699. LogTrace();
  3700. [self closeWithError:[self socketClosedError]];
  3701. }
  3702. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  3703. #pragma mark Closing
  3704. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  3705. - (void)closeWithError:(NSError *)error
  3706. {
  3707. LogVerbose(@"closeWithError: %@", error);
  3708. NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue");
  3709. if (currentSend) [self endCurrentSend];
  3710. [sendQueue removeAllObjects];
  3711. // If a socket has been created, we should notify the delegate.
  3712. BOOL shouldCallDelegate = (flags & kDidCreateSockets) ? YES : NO;
  3713. // Close all sockets, send/receive sources, cfstreams, etc
  3714. #if TARGET_OS_IPHONE
  3715. [self removeStreamsFromRunLoop];
  3716. [self closeReadAndWriteStreams];
  3717. #endif
  3718. [self closeSockets];
  3719. // Clear all flags (config remains as is)
  3720. flags = 0;
  3721. if (shouldCallDelegate)
  3722. {
  3723. [self notifyDidCloseWithError:error];
  3724. }
  3725. }
  3726. - (void)close
  3727. {
  3728. LogTrace();
  3729. dispatch_block_t block = ^{ @autoreleasepool {
  3730. [self closeWithError:nil];
  3731. }};
  3732. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  3733. block();
  3734. else
  3735. dispatch_sync(socketQueue, block);
  3736. }
  3737. - (void)closeAfterSending
  3738. {
  3739. LogTrace();
  3740. dispatch_block_t block = ^{ @autoreleasepool {
  3741. self->flags |= kCloseAfterSends;
  3742. if (self->currentSend == nil && [self->sendQueue count] == 0)
  3743. {
  3744. [self closeWithError:nil];
  3745. }
  3746. }};
  3747. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  3748. block();
  3749. else
  3750. dispatch_async(socketQueue, block);
  3751. }
  3752. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  3753. #pragma mark CFStream
  3754. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  3755. #if TARGET_OS_IPHONE
  3756. static NSThread *listenerThread;
  3757. + (void)ignore:(id)_
  3758. {}
  3759. + (void)startListenerThreadIfNeeded
  3760. {
  3761. static dispatch_once_t predicate;
  3762. dispatch_once(&predicate, ^{
  3763. listenerThread = [[NSThread alloc] initWithTarget:self
  3764. selector:@selector(listenerThread:)
  3765. object:nil];
  3766. [listenerThread start];
  3767. });
  3768. }
  3769. + (void)listenerThread:(id)unused
  3770. {
  3771. @autoreleasepool {
  3772. [[NSThread currentThread] setName:GCDAsyncUdpSocketThreadName];
  3773. LogInfo(@"ListenerThread: Started");
  3774. // We can't run the run loop unless it has an associated input source or a timer.
  3775. // So we'll just create a timer that will never fire - unless the server runs for a decades.
  3776. [NSTimer scheduledTimerWithTimeInterval:[[NSDate distantFuture] timeIntervalSinceNow]
  3777. target:self
  3778. selector:@selector(ignore:)
  3779. userInfo:nil
  3780. repeats:YES];
  3781. [[NSRunLoop currentRunLoop] run];
  3782. LogInfo(@"ListenerThread: Stopped");
  3783. }
  3784. }
  3785. + (void)addStreamListener:(GCDAsyncUdpSocket *)asyncUdpSocket
  3786. {
  3787. LogTrace();
  3788. NSAssert([NSThread currentThread] == listenerThread, @"Invoked on wrong thread");
  3789. CFRunLoopRef runLoop = CFRunLoopGetCurrent();
  3790. if (asyncUdpSocket->readStream4)
  3791. CFReadStreamScheduleWithRunLoop(asyncUdpSocket->readStream4, runLoop, kCFRunLoopDefaultMode);
  3792. if (asyncUdpSocket->readStream6)
  3793. CFReadStreamScheduleWithRunLoop(asyncUdpSocket->readStream6, runLoop, kCFRunLoopDefaultMode);
  3794. if (asyncUdpSocket->writeStream4)
  3795. CFWriteStreamScheduleWithRunLoop(asyncUdpSocket->writeStream4, runLoop, kCFRunLoopDefaultMode);
  3796. if (asyncUdpSocket->writeStream6)
  3797. CFWriteStreamScheduleWithRunLoop(asyncUdpSocket->writeStream6, runLoop, kCFRunLoopDefaultMode);
  3798. }
  3799. + (void)removeStreamListener:(GCDAsyncUdpSocket *)asyncUdpSocket
  3800. {
  3801. LogTrace();
  3802. NSAssert([NSThread currentThread] == listenerThread, @"Invoked on wrong thread");
  3803. CFRunLoopRef runLoop = CFRunLoopGetCurrent();
  3804. if (asyncUdpSocket->readStream4)
  3805. CFReadStreamUnscheduleFromRunLoop(asyncUdpSocket->readStream4, runLoop, kCFRunLoopDefaultMode);
  3806. if (asyncUdpSocket->readStream6)
  3807. CFReadStreamUnscheduleFromRunLoop(asyncUdpSocket->readStream6, runLoop, kCFRunLoopDefaultMode);
  3808. if (asyncUdpSocket->writeStream4)
  3809. CFWriteStreamUnscheduleFromRunLoop(asyncUdpSocket->writeStream4, runLoop, kCFRunLoopDefaultMode);
  3810. if (asyncUdpSocket->writeStream6)
  3811. CFWriteStreamUnscheduleFromRunLoop(asyncUdpSocket->writeStream6, runLoop, kCFRunLoopDefaultMode);
  3812. }
  3813. static void CFReadStreamCallback(CFReadStreamRef stream, CFStreamEventType type, void *pInfo)
  3814. {
  3815. @autoreleasepool {
  3816. GCDAsyncUdpSocket *asyncUdpSocket = (__bridge GCDAsyncUdpSocket *)pInfo;
  3817. switch(type)
  3818. {
  3819. case kCFStreamEventOpenCompleted:
  3820. {
  3821. LogCVerbose(@"CFReadStreamCallback - Open");
  3822. break;
  3823. }
  3824. case kCFStreamEventHasBytesAvailable:
  3825. {
  3826. LogCVerbose(@"CFReadStreamCallback - HasBytesAvailable");
  3827. break;
  3828. }
  3829. case kCFStreamEventErrorOccurred:
  3830. case kCFStreamEventEndEncountered:
  3831. {
  3832. NSError *error = (__bridge_transfer NSError *)CFReadStreamCopyError(stream);
  3833. if (error == nil && type == kCFStreamEventEndEncountered)
  3834. {
  3835. error = [asyncUdpSocket socketClosedError];
  3836. }
  3837. dispatch_async(asyncUdpSocket->socketQueue, ^{ @autoreleasepool {
  3838. LogCVerbose(@"CFReadStreamCallback - %@",
  3839. (type == kCFStreamEventErrorOccurred) ? @"Error" : @"EndEncountered");
  3840. if (stream != asyncUdpSocket->readStream4 &&
  3841. stream != asyncUdpSocket->readStream6 )
  3842. {
  3843. LogCVerbose(@"CFReadStreamCallback - Ignored");
  3844. return_from_block;
  3845. }
  3846. [asyncUdpSocket closeWithError:error];
  3847. }});
  3848. break;
  3849. }
  3850. default:
  3851. {
  3852. LogCError(@"CFReadStreamCallback - UnknownType: %i", (int)type);
  3853. }
  3854. }
  3855. }
  3856. }
  3857. static void CFWriteStreamCallback(CFWriteStreamRef stream, CFStreamEventType type, void *pInfo)
  3858. {
  3859. @autoreleasepool {
  3860. GCDAsyncUdpSocket *asyncUdpSocket = (__bridge GCDAsyncUdpSocket *)pInfo;
  3861. switch(type)
  3862. {
  3863. case kCFStreamEventOpenCompleted:
  3864. {
  3865. LogCVerbose(@"CFWriteStreamCallback - Open");
  3866. break;
  3867. }
  3868. case kCFStreamEventCanAcceptBytes:
  3869. {
  3870. LogCVerbose(@"CFWriteStreamCallback - CanAcceptBytes");
  3871. break;
  3872. }
  3873. case kCFStreamEventErrorOccurred:
  3874. case kCFStreamEventEndEncountered:
  3875. {
  3876. NSError *error = (__bridge_transfer NSError *)CFWriteStreamCopyError(stream);
  3877. if (error == nil && type == kCFStreamEventEndEncountered)
  3878. {
  3879. error = [asyncUdpSocket socketClosedError];
  3880. }
  3881. dispatch_async(asyncUdpSocket->socketQueue, ^{ @autoreleasepool {
  3882. LogCVerbose(@"CFWriteStreamCallback - %@",
  3883. (type == kCFStreamEventErrorOccurred) ? @"Error" : @"EndEncountered");
  3884. if (stream != asyncUdpSocket->writeStream4 &&
  3885. stream != asyncUdpSocket->writeStream6 )
  3886. {
  3887. LogCVerbose(@"CFWriteStreamCallback - Ignored");
  3888. return_from_block;
  3889. }
  3890. [asyncUdpSocket closeWithError:error];
  3891. }});
  3892. break;
  3893. }
  3894. default:
  3895. {
  3896. LogCError(@"CFWriteStreamCallback - UnknownType: %i", (int)type);
  3897. }
  3898. }
  3899. }
  3900. }
  3901. - (BOOL)createReadAndWriteStreams:(NSError **)errPtr
  3902. {
  3903. LogTrace();
  3904. NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue");
  3905. NSError *err = nil;
  3906. if (readStream4 || writeStream4 || readStream6 || writeStream6)
  3907. {
  3908. // Streams already created
  3909. return YES;
  3910. }
  3911. if (socket4FD == SOCKET_NULL && socket6FD == SOCKET_NULL)
  3912. {
  3913. err = [self otherError:@"Cannot create streams without a file descriptor"];
  3914. goto Failed;
  3915. }
  3916. // Create streams
  3917. LogVerbose(@"Creating read and write stream(s)...");
  3918. if (socket4FD != SOCKET_NULL)
  3919. {
  3920. CFStreamCreatePairWithSocket(NULL, (CFSocketNativeHandle)socket4FD, &readStream4, &writeStream4);
  3921. if (!readStream4 || !writeStream4)
  3922. {
  3923. err = [self otherError:@"Error in CFStreamCreatePairWithSocket() [IPv4]"];
  3924. goto Failed;
  3925. }
  3926. }
  3927. if (socket6FD != SOCKET_NULL)
  3928. {
  3929. CFStreamCreatePairWithSocket(NULL, (CFSocketNativeHandle)socket6FD, &readStream6, &writeStream6);
  3930. if (!readStream6 || !writeStream6)
  3931. {
  3932. err = [self otherError:@"Error in CFStreamCreatePairWithSocket() [IPv6]"];
  3933. goto Failed;
  3934. }
  3935. }
  3936. // Ensure the CFStream's don't close our underlying socket
  3937. CFReadStreamSetProperty(readStream4, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanFalse);
  3938. CFWriteStreamSetProperty(writeStream4, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanFalse);
  3939. CFReadStreamSetProperty(readStream6, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanFalse);
  3940. CFWriteStreamSetProperty(writeStream6, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanFalse);
  3941. return YES;
  3942. Failed:
  3943. if (readStream4)
  3944. {
  3945. CFReadStreamClose(readStream4);
  3946. CFRelease(readStream4);
  3947. readStream4 = NULL;
  3948. }
  3949. if (writeStream4)
  3950. {
  3951. CFWriteStreamClose(writeStream4);
  3952. CFRelease(writeStream4);
  3953. writeStream4 = NULL;
  3954. }
  3955. if (readStream6)
  3956. {
  3957. CFReadStreamClose(readStream6);
  3958. CFRelease(readStream6);
  3959. readStream6 = NULL;
  3960. }
  3961. if (writeStream6)
  3962. {
  3963. CFWriteStreamClose(writeStream6);
  3964. CFRelease(writeStream6);
  3965. writeStream6 = NULL;
  3966. }
  3967. if (errPtr)
  3968. *errPtr = err;
  3969. return NO;
  3970. }
  3971. - (BOOL)registerForStreamCallbacks:(NSError **)errPtr
  3972. {
  3973. LogTrace();
  3974. NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue");
  3975. NSAssert(readStream4 || writeStream4 || readStream6 || writeStream6, @"Read/Write streams are null");
  3976. NSError *err = nil;
  3977. streamContext.version = 0;
  3978. streamContext.info = (__bridge void *)self;
  3979. streamContext.retain = nil;
  3980. streamContext.release = nil;
  3981. streamContext.copyDescription = nil;
  3982. CFOptionFlags readStreamEvents = kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered;
  3983. CFOptionFlags writeStreamEvents = kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered;
  3984. // readStreamEvents |= (kCFStreamEventOpenCompleted | kCFStreamEventHasBytesAvailable);
  3985. // writeStreamEvents |= (kCFStreamEventOpenCompleted | kCFStreamEventCanAcceptBytes);
  3986. if (socket4FD != SOCKET_NULL)
  3987. {
  3988. if (readStream4 == NULL || writeStream4 == NULL)
  3989. {
  3990. err = [self otherError:@"Read/Write stream4 is null"];
  3991. goto Failed;
  3992. }
  3993. BOOL r1 = CFReadStreamSetClient(readStream4, readStreamEvents, &CFReadStreamCallback, &streamContext);
  3994. BOOL r2 = CFWriteStreamSetClient(writeStream4, writeStreamEvents, &CFWriteStreamCallback, &streamContext);
  3995. if (!r1 || !r2)
  3996. {
  3997. err = [self otherError:@"Error in CFStreamSetClient(), [IPv4]"];
  3998. goto Failed;
  3999. }
  4000. }
  4001. if (socket6FD != SOCKET_NULL)
  4002. {
  4003. if (readStream6 == NULL || writeStream6 == NULL)
  4004. {
  4005. err = [self otherError:@"Read/Write stream6 is null"];
  4006. goto Failed;
  4007. }
  4008. BOOL r1 = CFReadStreamSetClient(readStream6, readStreamEvents, &CFReadStreamCallback, &streamContext);
  4009. BOOL r2 = CFWriteStreamSetClient(writeStream6, writeStreamEvents, &CFWriteStreamCallback, &streamContext);
  4010. if (!r1 || !r2)
  4011. {
  4012. err = [self otherError:@"Error in CFStreamSetClient() [IPv6]"];
  4013. goto Failed;
  4014. }
  4015. }
  4016. return YES;
  4017. Failed:
  4018. if (readStream4) {
  4019. CFReadStreamSetClient(readStream4, kCFStreamEventNone, NULL, NULL);
  4020. }
  4021. if (writeStream4) {
  4022. CFWriteStreamSetClient(writeStream4, kCFStreamEventNone, NULL, NULL);
  4023. }
  4024. if (readStream6) {
  4025. CFReadStreamSetClient(readStream6, kCFStreamEventNone, NULL, NULL);
  4026. }
  4027. if (writeStream6) {
  4028. CFWriteStreamSetClient(writeStream6, kCFStreamEventNone, NULL, NULL);
  4029. }
  4030. if (errPtr) *errPtr = err;
  4031. return NO;
  4032. }
  4033. - (BOOL)addStreamsToRunLoop:(NSError **)errPtr
  4034. {
  4035. LogTrace();
  4036. NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue");
  4037. NSAssert(readStream4 || writeStream4 || readStream6 || writeStream6, @"Read/Write streams are null");
  4038. if (!(flags & kAddedStreamListener))
  4039. {
  4040. [[self class] startListenerThreadIfNeeded];
  4041. [[self class] performSelector:@selector(addStreamListener:)
  4042. onThread:listenerThread
  4043. withObject:self
  4044. waitUntilDone:YES];
  4045. flags |= kAddedStreamListener;
  4046. }
  4047. return YES;
  4048. }
  4049. - (BOOL)openStreams:(NSError **)errPtr
  4050. {
  4051. LogTrace();
  4052. NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue");
  4053. NSAssert(readStream4 || writeStream4 || readStream6 || writeStream6, @"Read/Write streams are null");
  4054. NSError *err = nil;
  4055. if (socket4FD != SOCKET_NULL)
  4056. {
  4057. BOOL r1 = CFReadStreamOpen(readStream4);
  4058. BOOL r2 = CFWriteStreamOpen(writeStream4);
  4059. if (!r1 || !r2)
  4060. {
  4061. err = [self otherError:@"Error in CFStreamOpen() [IPv4]"];
  4062. goto Failed;
  4063. }
  4064. }
  4065. if (socket6FD != SOCKET_NULL)
  4066. {
  4067. BOOL r1 = CFReadStreamOpen(readStream6);
  4068. BOOL r2 = CFWriteStreamOpen(writeStream6);
  4069. if (!r1 || !r2)
  4070. {
  4071. err = [self otherError:@"Error in CFStreamOpen() [IPv6]"];
  4072. goto Failed;
  4073. }
  4074. }
  4075. return YES;
  4076. Failed:
  4077. if (errPtr) *errPtr = err;
  4078. return NO;
  4079. }
  4080. - (void)removeStreamsFromRunLoop
  4081. {
  4082. LogTrace();
  4083. NSAssert(dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey), @"Must be dispatched on socketQueue");
  4084. if (flags & kAddedStreamListener)
  4085. {
  4086. [[self class] performSelector:@selector(removeStreamListener:)
  4087. onThread:listenerThread
  4088. withObject:self
  4089. waitUntilDone:YES];
  4090. flags &= ~kAddedStreamListener;
  4091. }
  4092. }
  4093. - (void)closeReadAndWriteStreams
  4094. {
  4095. LogTrace();
  4096. if (readStream4)
  4097. {
  4098. CFReadStreamSetClient(readStream4, kCFStreamEventNone, NULL, NULL);
  4099. CFReadStreamClose(readStream4);
  4100. CFRelease(readStream4);
  4101. readStream4 = NULL;
  4102. }
  4103. if (writeStream4)
  4104. {
  4105. CFWriteStreamSetClient(writeStream4, kCFStreamEventNone, NULL, NULL);
  4106. CFWriteStreamClose(writeStream4);
  4107. CFRelease(writeStream4);
  4108. writeStream4 = NULL;
  4109. }
  4110. if (readStream6)
  4111. {
  4112. CFReadStreamSetClient(readStream6, kCFStreamEventNone, NULL, NULL);
  4113. CFReadStreamClose(readStream6);
  4114. CFRelease(readStream6);
  4115. readStream6 = NULL;
  4116. }
  4117. if (writeStream6)
  4118. {
  4119. CFWriteStreamSetClient(writeStream6, kCFStreamEventNone, NULL, NULL);
  4120. CFWriteStreamClose(writeStream6);
  4121. CFRelease(writeStream6);
  4122. writeStream6 = NULL;
  4123. }
  4124. }
  4125. #endif
  4126. #if TARGET_OS_IPHONE
  4127. - (void)applicationWillEnterForeground:(NSNotification *)notification
  4128. {
  4129. LogTrace();
  4130. // If the application was backgrounded, then iOS may have shut down our sockets.
  4131. // So we take a quick look to see if any of them received an EOF.
  4132. dispatch_block_t block = ^{ @autoreleasepool {
  4133. [self resumeReceive4Source];
  4134. [self resumeReceive6Source];
  4135. }};
  4136. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  4137. block();
  4138. else
  4139. dispatch_async(socketQueue, block);
  4140. }
  4141. #endif
  4142. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  4143. #pragma mark Advanced
  4144. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  4145. /**
  4146. * See header file for big discussion of this method.
  4147. **/
  4148. - (void)markSocketQueueTargetQueue:(dispatch_queue_t)socketNewTargetQueue
  4149. {
  4150. void *nonNullUnusedPointer = (__bridge void *)self;
  4151. dispatch_queue_set_specific(socketNewTargetQueue, IsOnSocketQueueOrTargetQueueKey, nonNullUnusedPointer, NULL);
  4152. }
  4153. /**
  4154. * See header file for big discussion of this method.
  4155. **/
  4156. - (void)unmarkSocketQueueTargetQueue:(dispatch_queue_t)socketOldTargetQueue
  4157. {
  4158. dispatch_queue_set_specific(socketOldTargetQueue, IsOnSocketQueueOrTargetQueueKey, NULL, NULL);
  4159. }
  4160. - (void)performBlock:(dispatch_block_t)block
  4161. {
  4162. if (dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  4163. block();
  4164. else
  4165. dispatch_sync(socketQueue, block);
  4166. }
  4167. - (int)socketFD
  4168. {
  4169. if (! dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  4170. {
  4171. LogWarn(@"%@: %@ - Method only available from within the context of a performBlock: invocation",
  4172. THIS_FILE, THIS_METHOD);
  4173. return SOCKET_NULL;
  4174. }
  4175. if (socket4FD != SOCKET_NULL)
  4176. return socket4FD;
  4177. else
  4178. return socket6FD;
  4179. }
  4180. - (int)socket4FD
  4181. {
  4182. if (! dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  4183. {
  4184. LogWarn(@"%@: %@ - Method only available from within the context of a performBlock: invocation",
  4185. THIS_FILE, THIS_METHOD);
  4186. return SOCKET_NULL;
  4187. }
  4188. return socket4FD;
  4189. }
  4190. - (int)socket6FD
  4191. {
  4192. if (! dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  4193. {
  4194. LogWarn(@"%@: %@ - Method only available from within the context of a performBlock: invocation",
  4195. THIS_FILE, THIS_METHOD);
  4196. return SOCKET_NULL;
  4197. }
  4198. return socket6FD;
  4199. }
  4200. #if TARGET_OS_IPHONE
  4201. - (CFReadStreamRef)readStream
  4202. {
  4203. if (! dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  4204. {
  4205. LogWarn(@"%@: %@ - Method only available from within the context of a performBlock: invocation",
  4206. THIS_FILE, THIS_METHOD);
  4207. return NULL;
  4208. }
  4209. NSError *err = nil;
  4210. if (![self createReadAndWriteStreams:&err])
  4211. {
  4212. LogError(@"Error creating CFStream(s): %@", err);
  4213. return NULL;
  4214. }
  4215. // Todo...
  4216. if (readStream4)
  4217. return readStream4;
  4218. else
  4219. return readStream6;
  4220. }
  4221. - (CFWriteStreamRef)writeStream
  4222. {
  4223. if (! dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  4224. {
  4225. LogWarn(@"%@: %@ - Method only available from within the context of a performBlock: invocation",
  4226. THIS_FILE, THIS_METHOD);
  4227. return NULL;
  4228. }
  4229. NSError *err = nil;
  4230. if (![self createReadAndWriteStreams:&err])
  4231. {
  4232. LogError(@"Error creating CFStream(s): %@", err);
  4233. return NULL;
  4234. }
  4235. if (writeStream4)
  4236. return writeStream4;
  4237. else
  4238. return writeStream6;
  4239. }
  4240. - (BOOL)enableBackgroundingOnSockets
  4241. {
  4242. if (! dispatch_get_specific(IsOnSocketQueueOrTargetQueueKey))
  4243. {
  4244. LogWarn(@"%@: %@ - Method only available from within the context of a performBlock: invocation",
  4245. THIS_FILE, THIS_METHOD);
  4246. return NO;
  4247. }
  4248. // Why is this commented out?
  4249. // See comments below.
  4250. // NSError *err = nil;
  4251. // if (![self createReadAndWriteStreams:&err])
  4252. // {
  4253. // LogError(@"Error creating CFStream(s): %@", err);
  4254. // return NO;
  4255. // }
  4256. //
  4257. // LogVerbose(@"Enabling backgrouding on socket");
  4258. //
  4259. // BOOL r1, r2;
  4260. //
  4261. // if (readStream4 && writeStream4)
  4262. // {
  4263. // r1 = CFReadStreamSetProperty(readStream4, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP);
  4264. // r2 = CFWriteStreamSetProperty(writeStream4, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP);
  4265. //
  4266. // if (!r1 || !r2)
  4267. // {
  4268. // LogError(@"Error setting voip type (IPv4)");
  4269. // return NO;
  4270. // }
  4271. // }
  4272. //
  4273. // if (readStream6 && writeStream6)
  4274. // {
  4275. // r1 = CFReadStreamSetProperty(readStream6, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP);
  4276. // r2 = CFWriteStreamSetProperty(writeStream6, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP);
  4277. //
  4278. // if (!r1 || !r2)
  4279. // {
  4280. // LogError(@"Error setting voip type (IPv6)");
  4281. // return NO;
  4282. // }
  4283. // }
  4284. //
  4285. // return YES;
  4286. // The above code will actually appear to work.
  4287. // The methods will return YES, and everything will appear fine.
  4288. //
  4289. // One tiny problem: the sockets will still get closed when the app gets backgrounded.
  4290. //
  4291. // Apple does not officially support backgrounding UDP sockets.
  4292. return NO;
  4293. }
  4294. #endif
  4295. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  4296. #pragma mark Class Methods
  4297. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  4298. + (NSString *)hostFromSockaddr4:(const struct sockaddr_in *)pSockaddr4
  4299. {
  4300. char addrBuf[INET_ADDRSTRLEN];
  4301. if (inet_ntop(AF_INET, &pSockaddr4->sin_addr, addrBuf, (socklen_t)sizeof(addrBuf)) == NULL)
  4302. {
  4303. addrBuf[0] = '\0';
  4304. }
  4305. return [NSString stringWithCString:addrBuf encoding:NSASCIIStringEncoding];
  4306. }
  4307. + (NSString *)hostFromSockaddr6:(const struct sockaddr_in6 *)pSockaddr6
  4308. {
  4309. char addrBuf[INET6_ADDRSTRLEN];
  4310. if (inet_ntop(AF_INET6, &pSockaddr6->sin6_addr, addrBuf, (socklen_t)sizeof(addrBuf)) == NULL)
  4311. {
  4312. addrBuf[0] = '\0';
  4313. }
  4314. return [NSString stringWithCString:addrBuf encoding:NSASCIIStringEncoding];
  4315. }
  4316. + (uint16_t)portFromSockaddr4:(const struct sockaddr_in *)pSockaddr4
  4317. {
  4318. return ntohs(pSockaddr4->sin_port);
  4319. }
  4320. + (uint16_t)portFromSockaddr6:(const struct sockaddr_in6 *)pSockaddr6
  4321. {
  4322. return ntohs(pSockaddr6->sin6_port);
  4323. }
  4324. + (NSString *)hostFromAddress:(NSData *)address
  4325. {
  4326. NSString *host = nil;
  4327. [self getHost:&host port:NULL family:NULL fromAddress:address];
  4328. return host;
  4329. }
  4330. + (uint16_t)portFromAddress:(NSData *)address
  4331. {
  4332. uint16_t port = 0;
  4333. [self getHost:NULL port:&port family:NULL fromAddress:address];
  4334. return port;
  4335. }
  4336. + (int)familyFromAddress:(NSData *)address
  4337. {
  4338. int af = AF_UNSPEC;
  4339. [self getHost:NULL port:NULL family:&af fromAddress:address];
  4340. return af;
  4341. }
  4342. + (BOOL)isIPv4Address:(NSData *)address
  4343. {
  4344. int af = AF_UNSPEC;
  4345. [self getHost:NULL port:NULL family:&af fromAddress:address];
  4346. return (af == AF_INET);
  4347. }
  4348. + (BOOL)isIPv6Address:(NSData *)address
  4349. {
  4350. int af = AF_UNSPEC;
  4351. [self getHost:NULL port:NULL family:&af fromAddress:address];
  4352. return (af == AF_INET6);
  4353. }
  4354. + (BOOL)getHost:(NSString **)hostPtr port:(uint16_t *)portPtr fromAddress:(NSData *)address
  4355. {
  4356. return [self getHost:hostPtr port:portPtr family:NULL fromAddress:address];
  4357. }
  4358. + (BOOL)getHost:(NSString **)hostPtr port:(uint16_t *)portPtr family:(int *)afPtr fromAddress:(NSData *)address
  4359. {
  4360. if ([address length] >= sizeof(struct sockaddr))
  4361. {
  4362. const struct sockaddr *addrX = (const struct sockaddr *)[address bytes];
  4363. if (addrX->sa_family == AF_INET)
  4364. {
  4365. if ([address length] >= sizeof(struct sockaddr_in))
  4366. {
  4367. const struct sockaddr_in *addr4 = (const struct sockaddr_in *)(const void *)addrX;
  4368. if (hostPtr) *hostPtr = [self hostFromSockaddr4:addr4];
  4369. if (portPtr) *portPtr = [self portFromSockaddr4:addr4];
  4370. if (afPtr) *afPtr = AF_INET;
  4371. return YES;
  4372. }
  4373. }
  4374. else if (addrX->sa_family == AF_INET6)
  4375. {
  4376. if ([address length] >= sizeof(struct sockaddr_in6))
  4377. {
  4378. const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6 *)(const void *)addrX;
  4379. if (hostPtr) *hostPtr = [self hostFromSockaddr6:addr6];
  4380. if (portPtr) *portPtr = [self portFromSockaddr6:addr6];
  4381. if (afPtr) *afPtr = AF_INET6;
  4382. return YES;
  4383. }
  4384. }
  4385. }
  4386. if (hostPtr) *hostPtr = nil;
  4387. if (portPtr) *portPtr = 0;
  4388. if (afPtr) *afPtr = AF_UNSPEC;
  4389. return NO;
  4390. }
  4391. @end