socketmodule.c 252 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938
  1. /* Socket module */
  2. /*
  3. This module provides an interface to Berkeley socket IPC.
  4. Limitations:
  5. - Only AF_INET, AF_INET6 and AF_UNIX address families are supported in a
  6. portable manner, though AF_PACKET, AF_NETLINK, AF_QIPCRTR and AF_TIPC are
  7. supported under Linux.
  8. - No read/write operations (use sendall/recv or makefile instead).
  9. - Additional restrictions apply on some non-Unix platforms (compensated
  10. for by socket.py).
  11. Module interface:
  12. - socket.error: exception raised for socket specific errors, alias for OSError
  13. - socket.gaierror: exception raised for getaddrinfo/getnameinfo errors,
  14. a subclass of socket.error
  15. - socket.herror: exception raised for gethostby* errors,
  16. a subclass of socket.error
  17. - socket.gethostbyname(hostname) --> host IP address (string: 'dd.dd.dd.dd')
  18. - socket.gethostbyaddr(IP address) --> (hostname, [alias, ...], [IP addr, ...])
  19. - socket.gethostname() --> host name (string: 'spam' or 'spam.domain.com')
  20. - socket.getprotobyname(protocolname) --> protocol number
  21. - socket.getservbyname(servicename[, protocolname]) --> port number
  22. - socket.getservbyport(portnumber[, protocolname]) --> service name
  23. - socket.socket([family[, type [, proto, fileno]]]) --> new socket object
  24. (fileno specifies a pre-existing socket file descriptor)
  25. - socket.socketpair([family[, type [, proto]]]) --> (socket, socket)
  26. - socket.ntohs(16 bit value) --> new int object
  27. - socket.ntohl(32 bit value) --> new int object
  28. - socket.htons(16 bit value) --> new int object
  29. - socket.htonl(32 bit value) --> new int object
  30. - socket.getaddrinfo(host, port [, family, type, proto, flags])
  31. --> List of (family, type, proto, canonname, sockaddr)
  32. - socket.getnameinfo(sockaddr, flags) --> (host, port)
  33. - socket.AF_INET, socket.SOCK_STREAM, etc.: constants from <socket.h>
  34. - socket.has_ipv6: boolean value indicating if IPv6 is supported
  35. - socket.inet_aton(IP address) -> 32-bit packed IP representation
  36. - socket.inet_ntoa(packed IP) -> IP address string
  37. - socket.getdefaulttimeout() -> None | float
  38. - socket.setdefaulttimeout(None | float)
  39. - socket.if_nameindex() -> list of tuples (if_index, if_name)
  40. - socket.if_nametoindex(name) -> corresponding interface index
  41. - socket.if_indextoname(index) -> corresponding interface name
  42. - an internet socket address is a pair (hostname, port)
  43. where hostname can be anything recognized by gethostbyname()
  44. (including the dd.dd.dd.dd notation) and port is in host byte order
  45. - where a hostname is returned, the dd.dd.dd.dd notation is used
  46. - a UNIX domain socket address is a string specifying the pathname
  47. - an AF_PACKET socket address is a tuple containing a string
  48. specifying the ethernet interface and an integer specifying
  49. the Ethernet protocol number to be received. For example:
  50. ("eth0",0x1234). Optional 3rd,4th,5th elements in the tuple
  51. specify packet-type and ha-type/addr.
  52. - an AF_QIPCRTR socket address is a (node, port) tuple where the
  53. node and port are non-negative integers.
  54. - an AF_TIPC socket address is expressed as
  55. (addr_type, v1, v2, v3 [, scope]); where addr_type can be one of:
  56. TIPC_ADDR_NAMESEQ, TIPC_ADDR_NAME, and TIPC_ADDR_ID;
  57. and scope can be one of:
  58. TIPC_ZONE_SCOPE, TIPC_CLUSTER_SCOPE, and TIPC_NODE_SCOPE.
  59. The meaning of v1, v2 and v3 depends on the value of addr_type:
  60. if addr_type is TIPC_ADDR_NAME:
  61. v1 is the server type
  62. v2 is the port identifier
  63. v3 is ignored
  64. if addr_type is TIPC_ADDR_NAMESEQ:
  65. v1 is the server type
  66. v2 is the lower port number
  67. v3 is the upper port number
  68. if addr_type is TIPC_ADDR_ID:
  69. v1 is the node
  70. v2 is the ref
  71. v3 is ignored
  72. Local naming conventions:
  73. - names starting with sock_ are socket object methods
  74. - names starting with socket_ are module-level functions
  75. - names starting with PySocket are exported through socketmodule.h
  76. */
  77. #ifndef Py_BUILD_CORE_BUILTIN
  78. # define Py_BUILD_CORE_MODULE 1
  79. #endif
  80. #ifdef __APPLE__
  81. // Issue #35569: Expose RFC 3542 socket options.
  82. #define __APPLE_USE_RFC_3542 1
  83. #include <AvailabilityMacros.h>
  84. /* for getaddrinfo thread safety test on old versions of OS X */
  85. #ifndef MAC_OS_X_VERSION_10_5
  86. #define MAC_OS_X_VERSION_10_5 1050
  87. #endif
  88. /*
  89. * inet_aton is not available on OSX 10.3, yet we want to use a binary
  90. * that was build on 10.4 or later to work on that release, weak linking
  91. * comes to the rescue.
  92. */
  93. # pragma weak inet_aton
  94. #endif
  95. #define PY_SSIZE_T_CLEAN
  96. #include "Python.h"
  97. #include "pycore_fileutils.h" // _Py_set_inheritable()
  98. #include "pycore_moduleobject.h" // _PyModule_GetState
  99. #include "structmember.h" // PyMemberDef
  100. #ifdef _Py_MEMORY_SANITIZER
  101. # include <sanitizer/msan_interface.h>
  102. #endif
  103. /* Socket object documentation */
  104. PyDoc_STRVAR(sock_doc,
  105. "socket(family=AF_INET, type=SOCK_STREAM, proto=0) -> socket object\n\
  106. socket(family=-1, type=-1, proto=-1, fileno=None) -> socket object\n\
  107. \n\
  108. Open a socket of the given type. The family argument specifies the\n\
  109. address family; it defaults to AF_INET. The type argument specifies\n\
  110. whether this is a stream (SOCK_STREAM, this is the default)\n\
  111. or datagram (SOCK_DGRAM) socket. The protocol argument defaults to 0,\n\
  112. specifying the default protocol. Keyword arguments are accepted.\n\
  113. The socket is created as non-inheritable.\n\
  114. \n\
  115. When a fileno is passed in, family, type and proto are auto-detected,\n\
  116. unless they are explicitly set.\n\
  117. \n\
  118. A socket object represents one endpoint of a network connection.\n\
  119. \n\
  120. Methods of socket objects (keyword arguments not allowed):\n\
  121. \n\
  122. _accept() -- accept connection, returning new socket fd and client address\n\
  123. bind(addr) -- bind the socket to a local address\n\
  124. close() -- close the socket\n\
  125. connect(addr) -- connect the socket to a remote address\n\
  126. connect_ex(addr) -- connect, return an error code instead of an exception\n\
  127. dup() -- return a new socket fd duplicated from fileno()\n\
  128. fileno() -- return underlying file descriptor\n\
  129. getpeername() -- return remote address [*]\n\
  130. getsockname() -- return local address\n\
  131. getsockopt(level, optname[, buflen]) -- get socket options\n\
  132. gettimeout() -- return timeout or None\n\
  133. listen([n]) -- start listening for incoming connections\n\
  134. recv(buflen[, flags]) -- receive data\n\
  135. recv_into(buffer[, nbytes[, flags]]) -- receive data (into a buffer)\n\
  136. recvfrom(buflen[, flags]) -- receive data and sender\'s address\n\
  137. recvfrom_into(buffer[, nbytes, [, flags])\n\
  138. -- receive data and sender\'s address (into a buffer)\n\
  139. sendall(data[, flags]) -- send all data\n\
  140. send(data[, flags]) -- send data, may not send all of it\n\
  141. sendto(data[, flags], addr) -- send data to a given address\n\
  142. setblocking(bool) -- set or clear the blocking I/O flag\n\
  143. getblocking() -- return True if socket is blocking, False if non-blocking\n\
  144. setsockopt(level, optname, value[, optlen]) -- set socket options\n\
  145. settimeout(None | float) -- set or clear the timeout\n\
  146. shutdown(how) -- shut down traffic in one or both directions\n\
  147. \n\
  148. [*] not available on all platforms!");
  149. /* XXX This is a terrible mess of platform-dependent preprocessor hacks.
  150. I hope some day someone can clean this up please... */
  151. /* Hacks for gethostbyname_r(). On some non-Linux platforms, the configure
  152. script doesn't get this right, so we hardcode some platform checks below.
  153. On the other hand, not all Linux versions agree, so there the settings
  154. computed by the configure script are needed! */
  155. #ifndef __linux__
  156. # undef HAVE_GETHOSTBYNAME_R_3_ARG
  157. # undef HAVE_GETHOSTBYNAME_R_5_ARG
  158. # undef HAVE_GETHOSTBYNAME_R_6_ARG
  159. #endif
  160. #if defined(__OpenBSD__)
  161. # include <sys/uio.h>
  162. #endif
  163. #if defined(__ANDROID__) && __ANDROID_API__ < 23
  164. # undef HAVE_GETHOSTBYNAME_R
  165. #endif
  166. #ifdef HAVE_GETHOSTBYNAME_R
  167. # if defined(_AIX) && !defined(_LINUX_SOURCE_COMPAT)
  168. # define HAVE_GETHOSTBYNAME_R_3_ARG
  169. # elif defined(__sun) || defined(__sgi)
  170. # define HAVE_GETHOSTBYNAME_R_5_ARG
  171. # elif defined(__linux__)
  172. /* Rely on the configure script */
  173. # elif defined(_LINUX_SOURCE_COMPAT) /* Linux compatibility on AIX */
  174. # define HAVE_GETHOSTBYNAME_R_6_ARG
  175. # else
  176. # undef HAVE_GETHOSTBYNAME_R
  177. # endif
  178. #endif
  179. #if !defined(HAVE_GETHOSTBYNAME_R) && !defined(MS_WINDOWS)
  180. # define USE_GETHOSTBYNAME_LOCK
  181. #endif
  182. #if defined(__APPLE__) || defined(__CYGWIN__) || defined(__NetBSD__)
  183. # include <sys/ioctl.h>
  184. #endif
  185. #if defined(__sgi) && _COMPILER_VERSION>700 && !_SGIAPI
  186. /* make sure that the reentrant (gethostbyaddr_r etc)
  187. functions are declared correctly if compiling with
  188. MIPSPro 7.x in ANSI C mode (default) */
  189. /* XXX Using _SGIAPI is the wrong thing,
  190. but I don't know what the right thing is. */
  191. #undef _SGIAPI /* to avoid warning */
  192. #define _SGIAPI 1
  193. #undef _XOPEN_SOURCE
  194. #include <sys/socket.h>
  195. #include <sys/types.h>
  196. #include <netinet/in.h>
  197. #ifdef _SS_ALIGNSIZE
  198. #define HAVE_GETADDRINFO 1
  199. #define HAVE_GETNAMEINFO 1
  200. #endif
  201. #define HAVE_INET_PTON
  202. #include <netdb.h>
  203. #endif // __sgi
  204. /* Solaris fails to define this variable at all. */
  205. #if (defined(__sun) && defined(__SVR4)) && !defined(INET_ADDRSTRLEN)
  206. #define INET_ADDRSTRLEN 16
  207. #endif
  208. /* Generic includes */
  209. #ifdef HAVE_SYS_TYPES_H
  210. #include <sys/types.h>
  211. #endif
  212. #ifdef HAVE_SYS_SOCKET_H
  213. #include <sys/socket.h>
  214. #endif
  215. #ifdef HAVE_NET_IF_H
  216. #include <net/if.h>
  217. #endif
  218. #ifdef HAVE_NET_ETHERNET_H
  219. #include <net/ethernet.h>
  220. #endif
  221. /* Generic socket object definitions and includes */
  222. #define PySocket_BUILDING_SOCKET
  223. #include "socketmodule.h"
  224. /* Addressing includes */
  225. #ifndef MS_WINDOWS
  226. /* Non-MS WINDOWS includes */
  227. #ifdef HAVE_NETDB_H
  228. # include <netdb.h>
  229. #endif
  230. # include <unistd.h>
  231. /* Headers needed for inet_ntoa() and inet_addr() */
  232. # include <arpa/inet.h>
  233. # include <fcntl.h>
  234. #else /* MS_WINDOWS */
  235. /* MS_WINDOWS includes */
  236. # ifdef HAVE_FCNTL_H
  237. # include <fcntl.h>
  238. # endif
  239. /* Helpers needed for AF_HYPERV */
  240. # include <Rpc.h>
  241. /* Macros based on the IPPROTO enum, see: https://bugs.python.org/issue29515 */
  242. #define IPPROTO_ICMP IPPROTO_ICMP
  243. #define IPPROTO_IGMP IPPROTO_IGMP
  244. #define IPPROTO_GGP IPPROTO_GGP
  245. #define IPPROTO_TCP IPPROTO_TCP
  246. #define IPPROTO_PUP IPPROTO_PUP
  247. #define IPPROTO_UDP IPPROTO_UDP
  248. #define IPPROTO_IDP IPPROTO_IDP
  249. #define IPPROTO_ND IPPROTO_ND
  250. #define IPPROTO_RAW IPPROTO_RAW
  251. #define IPPROTO_MAX IPPROTO_MAX
  252. #define IPPROTO_HOPOPTS IPPROTO_HOPOPTS
  253. #define IPPROTO_IPV4 IPPROTO_IPV4
  254. #define IPPROTO_IPV6 IPPROTO_IPV6
  255. #define IPPROTO_ROUTING IPPROTO_ROUTING
  256. #define IPPROTO_FRAGMENT IPPROTO_FRAGMENT
  257. #define IPPROTO_ESP IPPROTO_ESP
  258. #define IPPROTO_AH IPPROTO_AH
  259. #define IPPROTO_ICMPV6 IPPROTO_ICMPV6
  260. #define IPPROTO_NONE IPPROTO_NONE
  261. #define IPPROTO_DSTOPTS IPPROTO_DSTOPTS
  262. #define IPPROTO_EGP IPPROTO_EGP
  263. #define IPPROTO_PIM IPPROTO_PIM
  264. #define IPPROTO_ICLFXBM IPPROTO_ICLFXBM // WinSock2 only
  265. #define IPPROTO_ST IPPROTO_ST // WinSock2 only
  266. #define IPPROTO_CBT IPPROTO_CBT // WinSock2 only
  267. #define IPPROTO_IGP IPPROTO_IGP // WinSock2 only
  268. #define IPPROTO_RDP IPPROTO_RDP // WinSock2 only
  269. #define IPPROTO_PGM IPPROTO_PGM // WinSock2 only
  270. #define IPPROTO_L2TP IPPROTO_L2TP // WinSock2 only
  271. #define IPPROTO_SCTP IPPROTO_SCTP // WinSock2 only
  272. /* Provides the IsWindows7SP1OrGreater() function */
  273. #include <versionhelpers.h>
  274. // For if_nametoindex() and if_indextoname()
  275. #include <iphlpapi.h>
  276. /* remove some flags on older version Windows during run-time.
  277. https://msdn.microsoft.com/en-us/library/windows/desktop/ms738596.aspx */
  278. typedef struct {
  279. DWORD build_number; /* available starting with this Win10 BuildNumber */
  280. const char flag_name[20];
  281. } FlagRuntimeInfo;
  282. /* IMPORTANT: make sure the list ordered by descending build_number */
  283. static FlagRuntimeInfo win_runtime_flags[] = {
  284. /* available starting with Windows 10 1709 */
  285. {16299, "TCP_KEEPIDLE"},
  286. {16299, "TCP_KEEPINTVL"},
  287. /* available starting with Windows 10 1703 */
  288. {15063, "TCP_KEEPCNT"},
  289. /* available starting with Windows 10 1607 */
  290. {14393, "TCP_FASTOPEN"}
  291. };
  292. /*[clinic input]
  293. module _socket
  294. class _socket.socket "PySocketSockObject *" "clinic_state()->sock_type"
  295. [clinic start generated code]*/
  296. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=2db2489bd2219fd8]*/
  297. static int
  298. remove_unusable_flags(PyObject *m)
  299. {
  300. PyObject *dict;
  301. OSVERSIONINFOEX info;
  302. dict = PyModule_GetDict(m);
  303. if (dict == NULL) {
  304. return -1;
  305. }
  306. #ifndef MS_WINDOWS_DESKTOP
  307. info.dwOSVersionInfoSize = sizeof(info);
  308. if (!GetVersionEx((OSVERSIONINFO*) &info)) {
  309. PyErr_SetFromWindowsErr(0);
  310. return -1;
  311. }
  312. #else
  313. /* set to Windows 10, except BuildNumber. */
  314. memset(&info, 0, sizeof(info));
  315. info.dwOSVersionInfoSize = sizeof(info);
  316. info.dwMajorVersion = 10;
  317. info.dwMinorVersion = 0;
  318. /* set Condition Mask */
  319. DWORDLONG dwlConditionMask = 0;
  320. VER_SET_CONDITION(dwlConditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL);
  321. VER_SET_CONDITION(dwlConditionMask, VER_MINORVERSION, VER_GREATER_EQUAL);
  322. VER_SET_CONDITION(dwlConditionMask, VER_BUILDNUMBER, VER_GREATER_EQUAL);
  323. #endif
  324. for (int i=0; i<sizeof(win_runtime_flags)/sizeof(FlagRuntimeInfo); i++) {
  325. #ifdef MS_WINDOWS_DESKTOP
  326. info.dwBuildNumber = win_runtime_flags[i].build_number;
  327. /* greater than or equal to the specified version?
  328. Compatibility Mode will not cheat VerifyVersionInfo(...) */
  329. BOOL isSupported = VerifyVersionInfo(
  330. &info,
  331. VER_MAJORVERSION|VER_MINORVERSION|VER_BUILDNUMBER,
  332. dwlConditionMask);
  333. #else
  334. /* note in this case 'info' is the actual OS version, whereas above
  335. it is the version to compare against. */
  336. BOOL isSupported = info.dwMajorVersion > 10 ||
  337. (info.dwMajorVersion == 10 && info.dwMinorVersion > 0) ||
  338. (info.dwMajorVersion == 10 && info.dwMinorVersion == 0 &&
  339. info.dwBuildNumber >= win_runtime_flags[i].build_number);
  340. #endif
  341. if (isSupported) {
  342. break;
  343. }
  344. else {
  345. PyObject *flag_name = PyUnicode_FromString(win_runtime_flags[i].flag_name);
  346. if (flag_name == NULL) {
  347. return -1;
  348. }
  349. PyObject *v = _PyDict_Pop(dict, flag_name, Py_None);
  350. Py_DECREF(flag_name);
  351. if (v == NULL) {
  352. return -1;
  353. }
  354. Py_DECREF(v);
  355. }
  356. }
  357. return 0;
  358. }
  359. #endif
  360. #include <stddef.h>
  361. #ifndef O_NONBLOCK
  362. # define O_NONBLOCK O_NDELAY
  363. #endif
  364. /* include Python's addrinfo.h unless it causes trouble */
  365. #if defined(__sgi) && _COMPILER_VERSION>700 && defined(_SS_ALIGNSIZE)
  366. /* Do not include addinfo.h on some newer IRIX versions.
  367. * _SS_ALIGNSIZE is defined in sys/socket.h by 6.5.21,
  368. * for example, but not by 6.5.10.
  369. */
  370. #elif defined(_MSC_VER) && _MSC_VER>1201
  371. /* Do not include addrinfo.h for MSVC7 or greater. 'addrinfo' and
  372. * EAI_* constants are defined in (the already included) ws2tcpip.h.
  373. */
  374. #else
  375. # include "addrinfo.h"
  376. #endif
  377. #ifdef __APPLE__
  378. /* On OS X, getaddrinfo returns no error indication of lookup
  379. failure, so we must use the emulation instead of the libinfo
  380. implementation. Unfortunately, performing an autoconf test
  381. for this bug would require DNS access for the machine performing
  382. the configuration, which is not acceptable. Therefore, we
  383. determine the bug just by checking for __APPLE__. If this bug
  384. gets ever fixed, perhaps checking for sys/version.h would be
  385. appropriate, which is 10/0 on the system with the bug. */
  386. #ifndef HAVE_GETNAMEINFO
  387. /* This bug seems to be fixed in Jaguar. The easiest way I could
  388. Find to check for Jaguar is that it has getnameinfo(), which
  389. older releases don't have */
  390. #undef HAVE_GETADDRINFO
  391. #endif
  392. #ifdef HAVE_INET_ATON
  393. #define USE_INET_ATON_WEAKLINK
  394. #endif
  395. #endif
  396. /* I know this is a bad practice, but it is the easiest... */
  397. #if !defined(HAVE_GETADDRINFO)
  398. /* avoid clashes with the C library definition of the symbol. */
  399. #define getaddrinfo fake_getaddrinfo
  400. #define gai_strerror fake_gai_strerror
  401. #define freeaddrinfo fake_freeaddrinfo
  402. #include "getaddrinfo.c"
  403. #endif
  404. #if !defined(HAVE_GETNAMEINFO)
  405. #define getnameinfo fake_getnameinfo
  406. #include "getnameinfo.c"
  407. #endif // HAVE_GETNAMEINFO
  408. #ifdef MS_WINDOWS
  409. #define SOCKETCLOSE closesocket
  410. #endif
  411. #ifdef MS_WIN32
  412. # undef EAFNOSUPPORT
  413. # define EAFNOSUPPORT WSAEAFNOSUPPORT
  414. #endif
  415. #ifndef SOCKETCLOSE
  416. # define SOCKETCLOSE close
  417. #endif
  418. #if (defined(HAVE_BLUETOOTH_H) || defined(HAVE_BLUETOOTH_BLUETOOTH_H)) && !defined(__NetBSD__) && !defined(__DragonFly__)
  419. #define USE_BLUETOOTH 1
  420. #if defined(__FreeBSD__)
  421. #define BTPROTO_L2CAP BLUETOOTH_PROTO_L2CAP
  422. #define BTPROTO_RFCOMM BLUETOOTH_PROTO_RFCOMM
  423. #define BTPROTO_HCI BLUETOOTH_PROTO_HCI
  424. #define SOL_HCI SOL_HCI_RAW
  425. #define HCI_FILTER SO_HCI_RAW_FILTER
  426. #define sockaddr_l2 sockaddr_l2cap
  427. #define sockaddr_rc sockaddr_rfcomm
  428. #define hci_dev hci_node
  429. #define _BT_L2_MEMB(sa, memb) ((sa)->l2cap_##memb)
  430. #define _BT_RC_MEMB(sa, memb) ((sa)->rfcomm_##memb)
  431. #define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
  432. #elif defined(__NetBSD__) || defined(__DragonFly__)
  433. #define sockaddr_l2 sockaddr_bt
  434. #define sockaddr_rc sockaddr_bt
  435. #define sockaddr_hci sockaddr_bt
  436. #define sockaddr_sco sockaddr_bt
  437. #define SOL_HCI BTPROTO_HCI
  438. #define HCI_DATA_DIR SO_HCI_DIRECTION
  439. #define _BT_L2_MEMB(sa, memb) ((sa)->bt_##memb)
  440. #define _BT_RC_MEMB(sa, memb) ((sa)->bt_##memb)
  441. #define _BT_HCI_MEMB(sa, memb) ((sa)->bt_##memb)
  442. #define _BT_SCO_MEMB(sa, memb) ((sa)->bt_##memb)
  443. #else
  444. #define _BT_L2_MEMB(sa, memb) ((sa)->l2_##memb)
  445. #define _BT_RC_MEMB(sa, memb) ((sa)->rc_##memb)
  446. #define _BT_HCI_MEMB(sa, memb) ((sa)->hci_##memb)
  447. #define _BT_SCO_MEMB(sa, memb) ((sa)->sco_##memb)
  448. #endif
  449. #endif
  450. #ifdef MS_WINDOWS_DESKTOP
  451. #define sockaddr_rc SOCKADDR_BTH_REDEF
  452. #define USE_BLUETOOTH 1
  453. #define AF_BLUETOOTH AF_BTH
  454. #define BTPROTO_RFCOMM BTHPROTO_RFCOMM
  455. #define _BT_RC_MEMB(sa, memb) ((sa)->memb)
  456. #endif /* MS_WINDOWS_DESKTOP */
  457. /* Convert "sock_addr_t *" to "struct sockaddr *". */
  458. #define SAS2SA(x) (&((x)->sa))
  459. /*
  460. * Constants for getnameinfo()
  461. */
  462. #if !defined(NI_MAXHOST)
  463. #define NI_MAXHOST 1025
  464. #endif
  465. #if !defined(NI_MAXSERV)
  466. #define NI_MAXSERV 32
  467. #endif
  468. #ifndef INVALID_SOCKET /* MS defines this */
  469. #define INVALID_SOCKET (-1)
  470. #endif
  471. #ifndef INADDR_NONE
  472. #define INADDR_NONE (-1)
  473. #endif
  474. typedef struct _socket_state {
  475. /* The sock_type variable contains pointers to various functions,
  476. some of which call new_sockobject(), which uses sock_type, so
  477. there has to be a circular reference. */
  478. PyTypeObject *sock_type;
  479. /* Global variable holding the exception type for errors detected
  480. by this module (but not argument type or memory errors, etc.). */
  481. PyObject *socket_herror;
  482. PyObject *socket_gaierror;
  483. /* Default timeout for new sockets */
  484. _PyTime_t defaulttimeout;
  485. #if defined(HAVE_ACCEPT) || defined(HAVE_ACCEPT4)
  486. #if defined(HAVE_ACCEPT4) && defined(SOCK_CLOEXEC)
  487. /* accept4() is available on Linux 2.6.28+ and glibc 2.10 */
  488. int accept4_works;
  489. #endif
  490. #endif
  491. #ifdef SOCK_CLOEXEC
  492. /* socket() and socketpair() fail with EINVAL on Linux kernel older
  493. * than 2.6.27 if SOCK_CLOEXEC flag is set in the socket type. */
  494. int sock_cloexec_works;
  495. #endif
  496. } socket_state;
  497. static inline socket_state *
  498. get_module_state(PyObject *mod)
  499. {
  500. void *state = _PyModule_GetState(mod);
  501. assert(state != NULL);
  502. return (socket_state *)state;
  503. }
  504. static struct PyModuleDef socketmodule;
  505. static inline socket_state *
  506. find_module_state_by_def(PyTypeObject *type)
  507. {
  508. PyObject *mod = PyType_GetModuleByDef(type, &socketmodule);
  509. assert(mod != NULL);
  510. return get_module_state(mod);
  511. }
  512. #define clinic_state() (find_module_state_by_def(type))
  513. #include "clinic/socketmodule.c.h"
  514. #undef clinic_state
  515. /* XXX There's a problem here: *static* functions are not supposed to have
  516. a Py prefix (or use CapitalizedWords). Later... */
  517. #if defined(HAVE_POLL_H)
  518. #include <poll.h>
  519. #elif defined(HAVE_SYS_POLL_H)
  520. #include <sys/poll.h>
  521. #endif
  522. /* Largest value to try to store in a socklen_t (used when handling
  523. ancillary data). POSIX requires socklen_t to hold at least
  524. (2**31)-1 and recommends against storing larger values, but
  525. socklen_t was originally int in the BSD interface, so to be on the
  526. safe side we use the smaller of (2**31)-1 and INT_MAX. */
  527. #if INT_MAX > 0x7fffffff
  528. #define SOCKLEN_T_LIMIT 0x7fffffff
  529. #else
  530. #define SOCKLEN_T_LIMIT INT_MAX
  531. #endif
  532. #ifdef HAVE_POLL
  533. /* Instead of select(), we'll use poll() since poll() works on any fd. */
  534. #define IS_SELECTABLE(s) 1
  535. /* Can we call select() with this socket without a buffer overrun? */
  536. #else
  537. /* If there's no timeout left, we don't have to call select, so it's a safe,
  538. * little white lie. */
  539. #define IS_SELECTABLE(s) (_PyIsSelectable_fd((s)->sock_fd) || (s)->sock_timeout <= 0)
  540. #endif
  541. static PyObject*
  542. select_error(void)
  543. {
  544. PyErr_SetString(PyExc_OSError, "unable to select on socket");
  545. return NULL;
  546. }
  547. #ifdef MS_WINDOWS
  548. #ifndef WSAEAGAIN
  549. #define WSAEAGAIN WSAEWOULDBLOCK
  550. #endif
  551. #define CHECK_ERRNO(expected) \
  552. (WSAGetLastError() == WSA ## expected)
  553. #else
  554. #define CHECK_ERRNO(expected) \
  555. (errno == expected)
  556. #endif
  557. #ifdef MS_WINDOWS
  558. # define GET_SOCK_ERROR WSAGetLastError()
  559. # define SET_SOCK_ERROR(err) WSASetLastError(err)
  560. # define SOCK_TIMEOUT_ERR WSAEWOULDBLOCK
  561. # define SOCK_INPROGRESS_ERR WSAEWOULDBLOCK
  562. #else
  563. # define GET_SOCK_ERROR errno
  564. # define SET_SOCK_ERROR(err) do { errno = err; } while (0)
  565. # define SOCK_TIMEOUT_ERR EWOULDBLOCK
  566. # define SOCK_INPROGRESS_ERR EINPROGRESS
  567. #endif
  568. #ifdef _MSC_VER
  569. # define SUPPRESS_DEPRECATED_CALL __pragma(warning(suppress: 4996))
  570. #else
  571. # define SUPPRESS_DEPRECATED_CALL
  572. #endif
  573. /* Convenience function to raise an error according to errno
  574. and return a NULL pointer from a function. */
  575. static PyObject *
  576. set_error(void)
  577. {
  578. #ifdef MS_WINDOWS
  579. int err_no = WSAGetLastError();
  580. /* PyErr_SetExcFromWindowsErr() invokes FormatMessage() which
  581. recognizes the error codes used by both GetLastError() and
  582. WSAGetLastError */
  583. if (err_no)
  584. return PyErr_SetExcFromWindowsErr(PyExc_OSError, err_no);
  585. #endif
  586. return PyErr_SetFromErrno(PyExc_OSError);
  587. }
  588. #if defined(HAVE_GETHOSTBYNAME_R) || defined (HAVE_GETHOSTBYNAME) || defined (HAVE_GETHOSTBYADDR)
  589. static PyObject *
  590. set_herror(socket_state *state, int h_error)
  591. {
  592. PyObject *v;
  593. #ifdef HAVE_HSTRERROR
  594. v = Py_BuildValue("(is)", h_error, hstrerror(h_error));
  595. #else
  596. v = Py_BuildValue("(is)", h_error, "host not found");
  597. #endif
  598. if (v != NULL) {
  599. PyErr_SetObject(state->socket_herror, v);
  600. Py_DECREF(v);
  601. }
  602. return NULL;
  603. }
  604. #endif
  605. #ifdef HAVE_GETADDRINFO
  606. static PyObject *
  607. set_gaierror(socket_state *state, int error)
  608. {
  609. PyObject *v;
  610. #ifdef EAI_SYSTEM
  611. /* EAI_SYSTEM is not available on Windows XP. */
  612. if (error == EAI_SYSTEM)
  613. return set_error();
  614. #endif
  615. #ifdef HAVE_GAI_STRERROR
  616. v = Py_BuildValue("(is)", error, gai_strerror(error));
  617. #else
  618. v = Py_BuildValue("(is)", error, "getaddrinfo failed");
  619. #endif
  620. if (v != NULL) {
  621. PyErr_SetObject(state->socket_gaierror, v);
  622. Py_DECREF(v);
  623. }
  624. return NULL;
  625. }
  626. #endif
  627. /* Function to perform the setting of socket blocking mode
  628. internally. block = (1 | 0). */
  629. static int
  630. internal_setblocking(PySocketSockObject *s, int block)
  631. {
  632. int result = -1;
  633. #ifdef MS_WINDOWS
  634. u_long arg;
  635. #endif
  636. #if !defined(MS_WINDOWS) \
  637. && !((defined(HAVE_SYS_IOCTL_H) && defined(FIONBIO)))
  638. int delay_flag, new_delay_flag;
  639. #endif
  640. Py_BEGIN_ALLOW_THREADS
  641. #ifndef MS_WINDOWS
  642. #if (defined(HAVE_SYS_IOCTL_H) && defined(FIONBIO))
  643. block = !block;
  644. if (ioctl(s->sock_fd, FIONBIO, (unsigned int *)&block) == -1)
  645. goto done;
  646. #else
  647. delay_flag = fcntl(s->sock_fd, F_GETFL, 0);
  648. if (delay_flag == -1)
  649. goto done;
  650. if (block)
  651. new_delay_flag = delay_flag & (~O_NONBLOCK);
  652. else
  653. new_delay_flag = delay_flag | O_NONBLOCK;
  654. if (new_delay_flag != delay_flag)
  655. if (fcntl(s->sock_fd, F_SETFL, new_delay_flag) == -1)
  656. goto done;
  657. #endif
  658. #else /* MS_WINDOWS */
  659. arg = !block;
  660. if (ioctlsocket(s->sock_fd, FIONBIO, &arg) != 0)
  661. goto done;
  662. #endif /* MS_WINDOWS */
  663. result = 0;
  664. done:
  665. Py_END_ALLOW_THREADS
  666. if (result) {
  667. #ifndef MS_WINDOWS
  668. PyErr_SetFromErrno(PyExc_OSError);
  669. #else
  670. PyErr_SetExcFromWindowsErr(PyExc_OSError, WSAGetLastError());
  671. #endif
  672. }
  673. return result;
  674. }
  675. static int
  676. internal_select(PySocketSockObject *s, int writing, _PyTime_t interval,
  677. int connect)
  678. {
  679. int n;
  680. #ifdef HAVE_POLL
  681. struct pollfd pollfd;
  682. _PyTime_t ms;
  683. #else
  684. fd_set fds, efds;
  685. struct timeval tv, *tvp;
  686. #endif
  687. /* must be called with the GIL held */
  688. assert(PyGILState_Check());
  689. /* Error condition is for output only */
  690. assert(!(connect && !writing));
  691. /* Guard against closed socket */
  692. if (s->sock_fd == INVALID_SOCKET)
  693. return 0;
  694. /* Prefer poll, if available, since you can poll() any fd
  695. * which can't be done with select(). */
  696. #ifdef HAVE_POLL
  697. pollfd.fd = s->sock_fd;
  698. pollfd.events = writing ? POLLOUT : POLLIN;
  699. if (connect) {
  700. /* On Windows, the socket becomes writable on connection success,
  701. but a connection failure is notified as an error. On POSIX, the
  702. socket becomes writable on connection success or on connection
  703. failure. */
  704. pollfd.events |= POLLERR;
  705. }
  706. /* s->sock_timeout is in seconds, timeout in ms */
  707. ms = _PyTime_AsMilliseconds(interval, _PyTime_ROUND_CEILING);
  708. assert(ms <= INT_MAX);
  709. /* On some OSes, typically BSD-based ones, the timeout parameter of the
  710. poll() syscall, when negative, must be exactly INFTIM, where defined,
  711. or -1. See issue 37811. */
  712. if (ms < 0) {
  713. #ifdef INFTIM
  714. ms = INFTIM;
  715. #else
  716. ms = -1;
  717. #endif
  718. }
  719. Py_BEGIN_ALLOW_THREADS;
  720. n = poll(&pollfd, 1, (int)ms);
  721. Py_END_ALLOW_THREADS;
  722. #else
  723. if (interval >= 0) {
  724. _PyTime_AsTimeval_clamp(interval, &tv, _PyTime_ROUND_CEILING);
  725. tvp = &tv;
  726. }
  727. else
  728. tvp = NULL;
  729. FD_ZERO(&fds);
  730. FD_SET(s->sock_fd, &fds);
  731. FD_ZERO(&efds);
  732. if (connect) {
  733. /* On Windows, the socket becomes writable on connection success,
  734. but a connection failure is notified as an error. On POSIX, the
  735. socket becomes writable on connection success or on connection
  736. failure. */
  737. FD_SET(s->sock_fd, &efds);
  738. }
  739. /* See if the socket is ready */
  740. Py_BEGIN_ALLOW_THREADS;
  741. if (writing)
  742. n = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
  743. NULL, &fds, &efds, tvp);
  744. else
  745. n = select(Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int),
  746. &fds, NULL, &efds, tvp);
  747. Py_END_ALLOW_THREADS;
  748. #endif
  749. if (n < 0)
  750. return -1;
  751. if (n == 0)
  752. return 1;
  753. return 0;
  754. }
  755. /* Call a socket function.
  756. On error, raise an exception and return -1 if err is set, or fill err and
  757. return -1 otherwise. If a signal was received and the signal handler raised
  758. an exception, return -1, and set err to -1 if err is set.
  759. On success, return 0, and set err to 0 if err is set.
  760. If the socket has a timeout, wait until the socket is ready before calling
  761. the function: wait until the socket is writable if writing is nonzero, wait
  762. until the socket received data otherwise.
  763. If the socket function is interrupted by a signal (failed with EINTR): retry
  764. the function, except if the signal handler raised an exception (PEP 475).
  765. When the function is retried, recompute the timeout using a monotonic clock.
  766. sock_call_ex() must be called with the GIL held. The socket function is
  767. called with the GIL released. */
  768. static int
  769. sock_call_ex(PySocketSockObject *s,
  770. int writing,
  771. int (*sock_func) (PySocketSockObject *s, void *data),
  772. void *data,
  773. int connect,
  774. int *err,
  775. _PyTime_t timeout)
  776. {
  777. int has_timeout = (timeout > 0);
  778. _PyTime_t deadline = 0;
  779. int deadline_initialized = 0;
  780. int res;
  781. /* sock_call() must be called with the GIL held. */
  782. assert(PyGILState_Check());
  783. /* outer loop to retry select() when select() is interrupted by a signal
  784. or to retry select()+sock_func() on false positive (see above) */
  785. while (1) {
  786. /* For connect(), poll even for blocking socket. The connection
  787. runs asynchronously. */
  788. if (has_timeout || connect) {
  789. if (has_timeout) {
  790. _PyTime_t interval;
  791. if (deadline_initialized) {
  792. /* recompute the timeout */
  793. interval = _PyDeadline_Get(deadline);
  794. }
  795. else {
  796. deadline_initialized = 1;
  797. deadline = _PyDeadline_Init(timeout);
  798. interval = timeout;
  799. }
  800. if (interval >= 0) {
  801. res = internal_select(s, writing, interval, connect);
  802. }
  803. else {
  804. res = 1;
  805. }
  806. }
  807. else {
  808. res = internal_select(s, writing, timeout, connect);
  809. }
  810. if (res == -1) {
  811. if (err)
  812. *err = GET_SOCK_ERROR;
  813. if (CHECK_ERRNO(EINTR)) {
  814. /* select() was interrupted by a signal */
  815. if (PyErr_CheckSignals()) {
  816. if (err)
  817. *err = -1;
  818. return -1;
  819. }
  820. /* retry select() */
  821. continue;
  822. }
  823. /* select() failed */
  824. s->errorhandler();
  825. return -1;
  826. }
  827. if (res == 1) {
  828. if (err)
  829. *err = SOCK_TIMEOUT_ERR;
  830. else
  831. PyErr_SetString(PyExc_TimeoutError, "timed out");
  832. return -1;
  833. }
  834. /* the socket is ready */
  835. }
  836. /* inner loop to retry sock_func() when sock_func() is interrupted
  837. by a signal */
  838. while (1) {
  839. Py_BEGIN_ALLOW_THREADS
  840. res = sock_func(s, data);
  841. Py_END_ALLOW_THREADS
  842. if (res) {
  843. /* sock_func() succeeded */
  844. if (err)
  845. *err = 0;
  846. return 0;
  847. }
  848. if (err)
  849. *err = GET_SOCK_ERROR;
  850. if (!CHECK_ERRNO(EINTR))
  851. break;
  852. /* sock_func() was interrupted by a signal */
  853. if (PyErr_CheckSignals()) {
  854. if (err)
  855. *err = -1;
  856. return -1;
  857. }
  858. /* retry sock_func() */
  859. }
  860. if (s->sock_timeout > 0
  861. && (CHECK_ERRNO(EWOULDBLOCK) || CHECK_ERRNO(EAGAIN))) {
  862. /* False positive: sock_func() failed with EWOULDBLOCK or EAGAIN.
  863. For example, select() could indicate a socket is ready for
  864. reading, but the data then discarded by the OS because of a
  865. wrong checksum.
  866. Loop on select() to recheck for socket readiness. */
  867. continue;
  868. }
  869. /* sock_func() failed */
  870. if (!err)
  871. s->errorhandler();
  872. /* else: err was already set before */
  873. return -1;
  874. }
  875. }
  876. static int
  877. sock_call(PySocketSockObject *s,
  878. int writing,
  879. int (*func) (PySocketSockObject *s, void *data),
  880. void *data)
  881. {
  882. return sock_call_ex(s, writing, func, data, 0, NULL, s->sock_timeout);
  883. }
  884. /* Initialize a new socket object. */
  885. static int
  886. init_sockobject(socket_state *state, PySocketSockObject *s,
  887. SOCKET_T fd, int family, int type, int proto)
  888. {
  889. s->sock_fd = fd;
  890. s->sock_family = family;
  891. s->sock_type = type;
  892. /* It's possible to pass SOCK_NONBLOCK and SOCK_CLOEXEC bit flags
  893. on some OSes as part of socket.type. We want to reset them here,
  894. to make socket.type be set to the same value on all platforms.
  895. Otherwise, simple code like 'if sock.type == SOCK_STREAM' is
  896. not portable.
  897. */
  898. #ifdef SOCK_NONBLOCK
  899. s->sock_type = s->sock_type & ~SOCK_NONBLOCK;
  900. #endif
  901. #ifdef SOCK_CLOEXEC
  902. s->sock_type = s->sock_type & ~SOCK_CLOEXEC;
  903. #endif
  904. s->sock_proto = proto;
  905. s->errorhandler = &set_error;
  906. #ifdef SOCK_NONBLOCK
  907. if (type & SOCK_NONBLOCK)
  908. s->sock_timeout = 0;
  909. else
  910. #endif
  911. {
  912. s->sock_timeout = state->defaulttimeout;
  913. if (state->defaulttimeout >= 0) {
  914. if (internal_setblocking(s, 0) == -1) {
  915. return -1;
  916. }
  917. }
  918. }
  919. s->state = state;
  920. return 0;
  921. }
  922. #ifdef HAVE_SOCKETPAIR
  923. /* Create a new socket object.
  924. This just creates the object and initializes it.
  925. If the creation fails, return NULL and set an exception (implicit
  926. in NEWOBJ()). */
  927. static PySocketSockObject *
  928. new_sockobject(socket_state *state, SOCKET_T fd, int family, int type,
  929. int proto)
  930. {
  931. PyTypeObject *tp = state->sock_type;
  932. PySocketSockObject *s = (PySocketSockObject *)tp->tp_alloc(tp, 0);
  933. if (s == NULL) {
  934. return NULL;
  935. }
  936. if (init_sockobject(state, s, fd, family, type, proto) == -1) {
  937. Py_DECREF(s);
  938. return NULL;
  939. }
  940. return s;
  941. }
  942. #endif
  943. /* Lock to allow python interpreter to continue, but only allow one
  944. thread to be in gethostbyname or getaddrinfo */
  945. #if defined(USE_GETHOSTBYNAME_LOCK)
  946. static PyThread_type_lock netdb_lock;
  947. #endif
  948. #ifdef HAVE_GETADDRINFO
  949. /* Convert a string specifying a host name or one of a few symbolic
  950. names to a numeric IP address. This usually calls gethostbyname()
  951. to do the work; the names "" and "<broadcast>" are special.
  952. Return the length (IPv4 should be 4 bytes), or negative if
  953. an error occurred; then an exception is raised. */
  954. static int
  955. setipaddr(socket_state *state, const char *name, struct sockaddr *addr_ret,
  956. size_t addr_ret_size, int af)
  957. {
  958. struct addrinfo hints, *res;
  959. int error;
  960. memset((void *) addr_ret, '\0', sizeof(*addr_ret));
  961. if (name[0] == '\0') {
  962. int siz;
  963. memset(&hints, 0, sizeof(hints));
  964. hints.ai_family = af;
  965. hints.ai_socktype = SOCK_DGRAM; /*dummy*/
  966. hints.ai_flags = AI_PASSIVE;
  967. Py_BEGIN_ALLOW_THREADS
  968. error = getaddrinfo(NULL, "0", &hints, &res);
  969. Py_END_ALLOW_THREADS
  970. /* We assume that those thread-unsafe getaddrinfo() versions
  971. *are* safe regarding their return value, ie. that a
  972. subsequent call to getaddrinfo() does not destroy the
  973. outcome of the first call. */
  974. if (error) {
  975. res = NULL; // no-op, remind us that it is invalid; gh-100795
  976. set_gaierror(state, error);
  977. return -1;
  978. }
  979. switch (res->ai_family) {
  980. case AF_INET:
  981. siz = 4;
  982. break;
  983. #ifdef ENABLE_IPV6
  984. case AF_INET6:
  985. siz = 16;
  986. break;
  987. #endif
  988. default:
  989. freeaddrinfo(res);
  990. PyErr_SetString(PyExc_OSError,
  991. "unsupported address family");
  992. return -1;
  993. }
  994. if (res->ai_next) {
  995. freeaddrinfo(res);
  996. PyErr_SetString(PyExc_OSError,
  997. "wildcard resolved to multiple address");
  998. return -1;
  999. }
  1000. if (res->ai_addrlen < addr_ret_size)
  1001. addr_ret_size = res->ai_addrlen;
  1002. memcpy(addr_ret, res->ai_addr, addr_ret_size);
  1003. freeaddrinfo(res);
  1004. return siz;
  1005. }
  1006. /* special-case broadcast - inet_addr() below can return INADDR_NONE for
  1007. * this */
  1008. if (strcmp(name, "255.255.255.255") == 0 ||
  1009. strcmp(name, "<broadcast>") == 0) {
  1010. struct sockaddr_in *sin;
  1011. if (af != AF_INET && af != AF_UNSPEC) {
  1012. PyErr_SetString(PyExc_OSError,
  1013. "address family mismatched");
  1014. return -1;
  1015. }
  1016. sin = (struct sockaddr_in *)addr_ret;
  1017. memset((void *) sin, '\0', sizeof(*sin));
  1018. sin->sin_family = AF_INET;
  1019. #ifdef HAVE_SOCKADDR_SA_LEN
  1020. sin->sin_len = sizeof(*sin);
  1021. #endif
  1022. sin->sin_addr.s_addr = INADDR_BROADCAST;
  1023. return sizeof(sin->sin_addr);
  1024. }
  1025. /* avoid a name resolution in case of numeric address */
  1026. #ifdef HAVE_INET_PTON
  1027. /* check for an IPv4 address */
  1028. if (af == AF_UNSPEC || af == AF_INET) {
  1029. struct sockaddr_in *sin = (struct sockaddr_in *)addr_ret;
  1030. memset(sin, 0, sizeof(*sin));
  1031. if (inet_pton(AF_INET, name, &sin->sin_addr) > 0) {
  1032. sin->sin_family = AF_INET;
  1033. #ifdef HAVE_SOCKADDR_SA_LEN
  1034. sin->sin_len = sizeof(*sin);
  1035. #endif
  1036. return 4;
  1037. }
  1038. }
  1039. #ifdef ENABLE_IPV6
  1040. /* check for an IPv6 address - if the address contains a scope ID, we
  1041. * fallback to getaddrinfo(), which can handle translation from interface
  1042. * name to interface index */
  1043. if ((af == AF_UNSPEC || af == AF_INET6) && !strchr(name, '%')) {
  1044. struct sockaddr_in6 *sin = (struct sockaddr_in6 *)addr_ret;
  1045. memset(sin, 0, sizeof(*sin));
  1046. if (inet_pton(AF_INET6, name, &sin->sin6_addr) > 0) {
  1047. sin->sin6_family = AF_INET6;
  1048. #ifdef HAVE_SOCKADDR_SA_LEN
  1049. sin->sin6_len = sizeof(*sin);
  1050. #endif
  1051. return 16;
  1052. }
  1053. }
  1054. #endif /* ENABLE_IPV6 */
  1055. #else /* HAVE_INET_PTON */
  1056. /* check for an IPv4 address */
  1057. if (af == AF_INET || af == AF_UNSPEC) {
  1058. struct sockaddr_in *sin = (struct sockaddr_in *)addr_ret;
  1059. memset(sin, 0, sizeof(*sin));
  1060. if ((sin->sin_addr.s_addr = inet_addr(name)) != INADDR_NONE) {
  1061. sin->sin_family = AF_INET;
  1062. #ifdef HAVE_SOCKADDR_SA_LEN
  1063. sin->sin_len = sizeof(*sin);
  1064. #endif
  1065. return 4;
  1066. }
  1067. }
  1068. #endif /* HAVE_INET_PTON */
  1069. /* perform a name resolution */
  1070. memset(&hints, 0, sizeof(hints));
  1071. hints.ai_family = af;
  1072. Py_BEGIN_ALLOW_THREADS
  1073. error = getaddrinfo(name, NULL, &hints, &res);
  1074. #if defined(__digital__) && defined(__unix__)
  1075. if (error == EAI_NONAME && af == AF_UNSPEC) {
  1076. /* On Tru64 V5.1, numeric-to-addr conversion fails
  1077. if no address family is given. Assume IPv4 for now.*/
  1078. hints.ai_family = AF_INET;
  1079. error = getaddrinfo(name, NULL, &hints, &res);
  1080. }
  1081. #endif
  1082. Py_END_ALLOW_THREADS
  1083. if (error) {
  1084. res = NULL; // no-op, remind us that it is invalid; gh-100795
  1085. set_gaierror(state, error);
  1086. return -1;
  1087. }
  1088. if (res->ai_addrlen < addr_ret_size)
  1089. addr_ret_size = res->ai_addrlen;
  1090. memcpy((char *) addr_ret, res->ai_addr, addr_ret_size);
  1091. freeaddrinfo(res);
  1092. switch (addr_ret->sa_family) {
  1093. case AF_INET:
  1094. return 4;
  1095. #ifdef ENABLE_IPV6
  1096. case AF_INET6:
  1097. return 16;
  1098. #endif
  1099. default:
  1100. PyErr_SetString(PyExc_OSError, "unknown address family");
  1101. return -1;
  1102. }
  1103. }
  1104. #endif // HAVE_GETADDRINFO
  1105. /* Convert IPv4 sockaddr to a Python str. */
  1106. static PyObject *
  1107. make_ipv4_addr(const struct sockaddr_in *addr)
  1108. {
  1109. char buf[INET_ADDRSTRLEN];
  1110. if (inet_ntop(AF_INET, &addr->sin_addr, buf, sizeof(buf)) == NULL) {
  1111. PyErr_SetFromErrno(PyExc_OSError);
  1112. return NULL;
  1113. }
  1114. return PyUnicode_FromString(buf);
  1115. }
  1116. #ifdef ENABLE_IPV6
  1117. /* Convert IPv6 sockaddr to a Python str. */
  1118. static PyObject *
  1119. make_ipv6_addr(const struct sockaddr_in6 *addr)
  1120. {
  1121. char buf[INET6_ADDRSTRLEN];
  1122. if (inet_ntop(AF_INET6, &addr->sin6_addr, buf, sizeof(buf)) == NULL) {
  1123. PyErr_SetFromErrno(PyExc_OSError);
  1124. return NULL;
  1125. }
  1126. return PyUnicode_FromString(buf);
  1127. }
  1128. #endif
  1129. #ifdef USE_BLUETOOTH
  1130. /* Convert a string representation of a Bluetooth address into a numeric
  1131. address. Returns the length (6), or raises an exception and returns -1 if
  1132. an error occurred. */
  1133. static int
  1134. setbdaddr(const char *name, bdaddr_t *bdaddr)
  1135. {
  1136. unsigned int b0, b1, b2, b3, b4, b5;
  1137. char ch;
  1138. int n;
  1139. n = sscanf(name, "%X:%X:%X:%X:%X:%X%c",
  1140. &b5, &b4, &b3, &b2, &b1, &b0, &ch);
  1141. if (n == 6 && (b0 | b1 | b2 | b3 | b4 | b5) < 256) {
  1142. #ifdef MS_WINDOWS
  1143. *bdaddr = (ULONGLONG)(b0 & 0xFF);
  1144. *bdaddr |= ((ULONGLONG)(b1 & 0xFF) << 8);
  1145. *bdaddr |= ((ULONGLONG)(b2 & 0xFF) << 16);
  1146. *bdaddr |= ((ULONGLONG)(b3 & 0xFF) << 24);
  1147. *bdaddr |= ((ULONGLONG)(b4 & 0xFF) << 32);
  1148. *bdaddr |= ((ULONGLONG)(b5 & 0xFF) << 40);
  1149. #else
  1150. bdaddr->b[0] = b0;
  1151. bdaddr->b[1] = b1;
  1152. bdaddr->b[2] = b2;
  1153. bdaddr->b[3] = b3;
  1154. bdaddr->b[4] = b4;
  1155. bdaddr->b[5] = b5;
  1156. #endif
  1157. return 6;
  1158. } else {
  1159. PyErr_SetString(PyExc_OSError, "bad bluetooth address");
  1160. return -1;
  1161. }
  1162. }
  1163. /* Create a string representation of the Bluetooth address. This is always a
  1164. string of the form 'XX:XX:XX:XX:XX:XX' where XX is a two digit hexadecimal
  1165. value (zero padded if necessary). */
  1166. static PyObject *
  1167. makebdaddr(bdaddr_t *bdaddr)
  1168. {
  1169. #ifdef MS_WINDOWS
  1170. int i;
  1171. unsigned int octets[6];
  1172. for (i = 0; i < 6; ++i) {
  1173. octets[i] = ((*bdaddr) >> (8 * i)) & 0xFF;
  1174. }
  1175. return PyUnicode_FromFormat("%02X:%02X:%02X:%02X:%02X:%02X",
  1176. octets[5], octets[4], octets[3],
  1177. octets[2], octets[1], octets[0]);
  1178. #else
  1179. return PyUnicode_FromFormat("%02X:%02X:%02X:%02X:%02X:%02X",
  1180. bdaddr->b[5], bdaddr->b[4], bdaddr->b[3],
  1181. bdaddr->b[2], bdaddr->b[1], bdaddr->b[0]);
  1182. #endif
  1183. }
  1184. #endif
  1185. /* Create an object representing the given socket address,
  1186. suitable for passing it back to bind(), connect() etc.
  1187. The family field of the sockaddr structure is inspected
  1188. to determine what kind of address it really is. */
  1189. /*ARGSUSED*/
  1190. static PyObject *
  1191. makesockaddr(SOCKET_T sockfd, struct sockaddr *addr, size_t addrlen, int proto)
  1192. {
  1193. if (addrlen == 0) {
  1194. /* No address -- may be recvfrom() from known socket */
  1195. Py_RETURN_NONE;
  1196. }
  1197. switch (addr->sa_family) {
  1198. case AF_INET:
  1199. {
  1200. const struct sockaddr_in *a = (const struct sockaddr_in *)addr;
  1201. PyObject *addrobj = make_ipv4_addr(a);
  1202. PyObject *ret = NULL;
  1203. if (addrobj) {
  1204. ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port));
  1205. Py_DECREF(addrobj);
  1206. }
  1207. return ret;
  1208. }
  1209. #if defined(AF_UNIX)
  1210. case AF_UNIX:
  1211. {
  1212. struct sockaddr_un *a = (struct sockaddr_un *) addr;
  1213. #ifdef __linux__
  1214. size_t linuxaddrlen = addrlen - offsetof(struct sockaddr_un, sun_path);
  1215. if (linuxaddrlen > 0 && a->sun_path[0] == 0) { /* Linux abstract namespace */
  1216. return PyBytes_FromStringAndSize(a->sun_path, linuxaddrlen);
  1217. }
  1218. else
  1219. #endif /* linux */
  1220. {
  1221. /* regular NULL-terminated string */
  1222. return PyUnicode_DecodeFSDefault(a->sun_path);
  1223. }
  1224. }
  1225. #endif /* AF_UNIX */
  1226. #if defined(AF_NETLINK)
  1227. case AF_NETLINK:
  1228. {
  1229. struct sockaddr_nl *a = (struct sockaddr_nl *) addr;
  1230. return Py_BuildValue("II", a->nl_pid, a->nl_groups);
  1231. }
  1232. #endif /* AF_NETLINK */
  1233. #if defined(AF_QIPCRTR)
  1234. case AF_QIPCRTR:
  1235. {
  1236. struct sockaddr_qrtr *a = (struct sockaddr_qrtr *) addr;
  1237. return Py_BuildValue("II", a->sq_node, a->sq_port);
  1238. }
  1239. #endif /* AF_QIPCRTR */
  1240. #if defined(AF_VSOCK)
  1241. case AF_VSOCK:
  1242. {
  1243. struct sockaddr_vm *a = (struct sockaddr_vm *) addr;
  1244. return Py_BuildValue("II", a->svm_cid, a->svm_port);
  1245. }
  1246. #endif /* AF_VSOCK */
  1247. #ifdef ENABLE_IPV6
  1248. case AF_INET6:
  1249. {
  1250. const struct sockaddr_in6 *a = (const struct sockaddr_in6 *)addr;
  1251. PyObject *addrobj = make_ipv6_addr(a);
  1252. PyObject *ret = NULL;
  1253. if (addrobj) {
  1254. ret = Py_BuildValue("OiII",
  1255. addrobj,
  1256. ntohs(a->sin6_port),
  1257. ntohl(a->sin6_flowinfo),
  1258. a->sin6_scope_id);
  1259. Py_DECREF(addrobj);
  1260. }
  1261. return ret;
  1262. }
  1263. #endif /* ENABLE_IPV6 */
  1264. #ifdef USE_BLUETOOTH
  1265. case AF_BLUETOOTH:
  1266. switch (proto) {
  1267. #ifdef BTPROTO_L2CAP
  1268. case BTPROTO_L2CAP:
  1269. {
  1270. struct sockaddr_l2 *a = (struct sockaddr_l2 *) addr;
  1271. PyObject *addrobj = makebdaddr(&_BT_L2_MEMB(a, bdaddr));
  1272. PyObject *ret = NULL;
  1273. if (addrobj) {
  1274. ret = Py_BuildValue("Oi",
  1275. addrobj,
  1276. _BT_L2_MEMB(a, psm));
  1277. Py_DECREF(addrobj);
  1278. }
  1279. return ret;
  1280. }
  1281. #endif /* BTPROTO_L2CAP */
  1282. case BTPROTO_RFCOMM:
  1283. {
  1284. struct sockaddr_rc *a = (struct sockaddr_rc *) addr;
  1285. PyObject *addrobj = makebdaddr(&_BT_RC_MEMB(a, bdaddr));
  1286. PyObject *ret = NULL;
  1287. if (addrobj) {
  1288. ret = Py_BuildValue("Oi",
  1289. addrobj,
  1290. _BT_RC_MEMB(a, channel));
  1291. Py_DECREF(addrobj);
  1292. }
  1293. return ret;
  1294. }
  1295. #ifdef BTPROTO_HCI
  1296. case BTPROTO_HCI:
  1297. {
  1298. struct sockaddr_hci *a = (struct sockaddr_hci *) addr;
  1299. #if defined(__NetBSD__) || defined(__DragonFly__)
  1300. return makebdaddr(&_BT_HCI_MEMB(a, bdaddr));
  1301. #else /* __NetBSD__ || __DragonFly__ */
  1302. PyObject *ret = NULL;
  1303. ret = Py_BuildValue("i", _BT_HCI_MEMB(a, dev));
  1304. return ret;
  1305. #endif /* !(__NetBSD__ || __DragonFly__) */
  1306. }
  1307. #if !defined(__FreeBSD__)
  1308. case BTPROTO_SCO:
  1309. {
  1310. struct sockaddr_sco *a = (struct sockaddr_sco *) addr;
  1311. return makebdaddr(&_BT_SCO_MEMB(a, bdaddr));
  1312. }
  1313. #endif /* !__FreeBSD__ */
  1314. #endif /* BTPROTO_HCI */
  1315. default:
  1316. PyErr_SetString(PyExc_ValueError,
  1317. "Unknown Bluetooth protocol");
  1318. return NULL;
  1319. }
  1320. #endif /* USE_BLUETOOTH */
  1321. #if defined(HAVE_NETPACKET_PACKET_H) && defined(SIOCGIFNAME)
  1322. case AF_PACKET:
  1323. {
  1324. struct sockaddr_ll *a = (struct sockaddr_ll *)addr;
  1325. const char *ifname = "";
  1326. struct ifreq ifr;
  1327. /* need to look up interface name give index */
  1328. if (a->sll_ifindex) {
  1329. ifr.ifr_ifindex = a->sll_ifindex;
  1330. if (ioctl(sockfd, SIOCGIFNAME, &ifr) == 0)
  1331. ifname = ifr.ifr_name;
  1332. }
  1333. return Py_BuildValue("shbhy#",
  1334. ifname,
  1335. ntohs(a->sll_protocol),
  1336. a->sll_pkttype,
  1337. a->sll_hatype,
  1338. a->sll_addr,
  1339. (Py_ssize_t)a->sll_halen);
  1340. }
  1341. #endif /* HAVE_NETPACKET_PACKET_H && SIOCGIFNAME */
  1342. #ifdef HAVE_LINUX_TIPC_H
  1343. case AF_TIPC:
  1344. {
  1345. struct sockaddr_tipc *a = (struct sockaddr_tipc *) addr;
  1346. if (a->addrtype == TIPC_ADDR_NAMESEQ) {
  1347. return Py_BuildValue("IIIII",
  1348. a->addrtype,
  1349. a->addr.nameseq.type,
  1350. a->addr.nameseq.lower,
  1351. a->addr.nameseq.upper,
  1352. a->scope);
  1353. } else if (a->addrtype == TIPC_ADDR_NAME) {
  1354. return Py_BuildValue("IIIII",
  1355. a->addrtype,
  1356. a->addr.name.name.type,
  1357. a->addr.name.name.instance,
  1358. a->addr.name.name.instance,
  1359. a->scope);
  1360. } else if (a->addrtype == TIPC_ADDR_ID) {
  1361. return Py_BuildValue("IIIII",
  1362. a->addrtype,
  1363. a->addr.id.node,
  1364. a->addr.id.ref,
  1365. 0,
  1366. a->scope);
  1367. } else {
  1368. PyErr_SetString(PyExc_ValueError,
  1369. "Invalid address type");
  1370. return NULL;
  1371. }
  1372. }
  1373. #endif /* HAVE_LINUX_TIPC_H */
  1374. #if defined(AF_CAN) && defined(SIOCGIFNAME)
  1375. case AF_CAN:
  1376. {
  1377. struct sockaddr_can *a = (struct sockaddr_can *)addr;
  1378. const char *ifname = "";
  1379. struct ifreq ifr;
  1380. /* need to look up interface name given index */
  1381. if (a->can_ifindex) {
  1382. ifr.ifr_ifindex = a->can_ifindex;
  1383. if (ioctl(sockfd, SIOCGIFNAME, &ifr) == 0)
  1384. ifname = ifr.ifr_name;
  1385. }
  1386. switch (proto) {
  1387. #ifdef CAN_ISOTP
  1388. case CAN_ISOTP:
  1389. {
  1390. return Py_BuildValue("O&kk", PyUnicode_DecodeFSDefault,
  1391. ifname,
  1392. a->can_addr.tp.rx_id,
  1393. a->can_addr.tp.tx_id);
  1394. }
  1395. #endif /* CAN_ISOTP */
  1396. #ifdef CAN_J1939
  1397. case CAN_J1939:
  1398. {
  1399. return Py_BuildValue("O&KIB", PyUnicode_DecodeFSDefault,
  1400. ifname,
  1401. (unsigned long long)a->can_addr.j1939.name,
  1402. (unsigned int)a->can_addr.j1939.pgn,
  1403. a->can_addr.j1939.addr);
  1404. }
  1405. #endif /* CAN_J1939 */
  1406. default:
  1407. {
  1408. return Py_BuildValue("(O&)", PyUnicode_DecodeFSDefault,
  1409. ifname);
  1410. }
  1411. }
  1412. }
  1413. #endif /* AF_CAN && SIOCGIFNAME */
  1414. #ifdef PF_SYSTEM
  1415. case PF_SYSTEM:
  1416. switch(proto) {
  1417. #ifdef SYSPROTO_CONTROL
  1418. case SYSPROTO_CONTROL:
  1419. {
  1420. struct sockaddr_ctl *a = (struct sockaddr_ctl *)addr;
  1421. return Py_BuildValue("(II)", a->sc_id, a->sc_unit);
  1422. }
  1423. #endif /* SYSPROTO_CONTROL */
  1424. default:
  1425. PyErr_SetString(PyExc_ValueError,
  1426. "Invalid address type");
  1427. return 0;
  1428. }
  1429. #endif /* PF_SYSTEM */
  1430. #ifdef HAVE_SOCKADDR_ALG
  1431. case AF_ALG:
  1432. {
  1433. struct sockaddr_alg *a = (struct sockaddr_alg *)addr;
  1434. return Py_BuildValue("s#s#HH",
  1435. a->salg_type,
  1436. strnlen((const char*)a->salg_type,
  1437. sizeof(a->salg_type)),
  1438. a->salg_name,
  1439. strnlen((const char*)a->salg_name,
  1440. sizeof(a->salg_name)),
  1441. a->salg_feat,
  1442. a->salg_mask);
  1443. }
  1444. #endif /* HAVE_SOCKADDR_ALG */
  1445. #ifdef HAVE_AF_HYPERV
  1446. case AF_HYPERV:
  1447. {
  1448. SOCKADDR_HV *a = (SOCKADDR_HV *) addr;
  1449. wchar_t *guidStr;
  1450. RPC_STATUS res = UuidToStringW(&a->VmId, &guidStr);
  1451. if (res != RPC_S_OK) {
  1452. PyErr_SetFromWindowsErr(res);
  1453. return 0;
  1454. }
  1455. PyObject *vmId = PyUnicode_FromWideChar(guidStr, -1);
  1456. res = RpcStringFreeW(&guidStr);
  1457. assert(res == RPC_S_OK);
  1458. res = UuidToStringW(&a->ServiceId, &guidStr);
  1459. if (res != RPC_S_OK) {
  1460. Py_DECREF(vmId);
  1461. PyErr_SetFromWindowsErr(res);
  1462. return 0;
  1463. }
  1464. PyObject *serviceId = PyUnicode_FromWideChar(guidStr, -1);
  1465. res = RpcStringFreeW(&guidStr);
  1466. assert(res == RPC_S_OK);
  1467. return Py_BuildValue("NN", vmId, serviceId);
  1468. }
  1469. #endif /* AF_HYPERV */
  1470. /* More cases here... */
  1471. default:
  1472. /* If we don't know the address family, don't raise an
  1473. exception -- return it as an (int, bytes) tuple. */
  1474. return Py_BuildValue("iy#",
  1475. addr->sa_family,
  1476. addr->sa_data,
  1477. sizeof(addr->sa_data));
  1478. }
  1479. }
  1480. #if defined(HAVE_BIND) || defined(HAVE_CONNECTTO) || defined(CMSG_LEN)
  1481. /* Helper for getsockaddrarg: bypass IDNA for ASCII-only host names
  1482. (in particular, numeric IP addresses). */
  1483. struct maybe_idna {
  1484. PyObject *obj;
  1485. char *buf;
  1486. };
  1487. static void
  1488. idna_cleanup(struct maybe_idna *data)
  1489. {
  1490. Py_CLEAR(data->obj);
  1491. }
  1492. static int
  1493. idna_converter(PyObject *obj, struct maybe_idna *data)
  1494. {
  1495. size_t len;
  1496. PyObject *obj2;
  1497. if (obj == NULL) {
  1498. idna_cleanup(data);
  1499. return 1;
  1500. }
  1501. data->obj = NULL;
  1502. len = -1;
  1503. if (PyBytes_Check(obj)) {
  1504. data->buf = PyBytes_AsString(obj);
  1505. len = PyBytes_Size(obj);
  1506. }
  1507. else if (PyByteArray_Check(obj)) {
  1508. data->buf = PyByteArray_AsString(obj);
  1509. len = PyByteArray_Size(obj);
  1510. }
  1511. else if (PyUnicode_Check(obj)) {
  1512. if (PyUnicode_READY(obj) == -1) {
  1513. return 0;
  1514. }
  1515. if (PyUnicode_IS_COMPACT_ASCII(obj)) {
  1516. data->buf = PyUnicode_DATA(obj);
  1517. len = PyUnicode_GET_LENGTH(obj);
  1518. }
  1519. else {
  1520. obj2 = PyUnicode_AsEncodedString(obj, "idna", NULL);
  1521. if (!obj2) {
  1522. PyErr_SetString(PyExc_TypeError, "encoding of hostname failed");
  1523. return 0;
  1524. }
  1525. assert(PyBytes_Check(obj2));
  1526. data->obj = obj2;
  1527. data->buf = PyBytes_AS_STRING(obj2);
  1528. len = PyBytes_GET_SIZE(obj2);
  1529. }
  1530. }
  1531. else {
  1532. PyErr_Format(PyExc_TypeError, "str, bytes or bytearray expected, not %s",
  1533. Py_TYPE(obj)->tp_name);
  1534. return 0;
  1535. }
  1536. if (strlen(data->buf) != len) {
  1537. Py_CLEAR(data->obj);
  1538. PyErr_SetString(PyExc_TypeError, "host name must not contain null character");
  1539. return 0;
  1540. }
  1541. return Py_CLEANUP_SUPPORTED;
  1542. }
  1543. /* Parse a socket address argument according to the socket object's
  1544. address family. Return 1 if the address was in the proper format,
  1545. 0 of not. The address is returned through addr_ret, its length
  1546. through len_ret. */
  1547. static int
  1548. getsockaddrarg(PySocketSockObject *s, PyObject *args,
  1549. sock_addr_t *addrbuf, int *len_ret, const char *caller)
  1550. {
  1551. switch (s->sock_family) {
  1552. #if defined(AF_UNIX)
  1553. case AF_UNIX:
  1554. {
  1555. Py_buffer path;
  1556. int retval = 0;
  1557. /* PEP 383. Not using PyUnicode_FSConverter since we need to
  1558. allow embedded nulls on Linux. */
  1559. if (PyUnicode_Check(args)) {
  1560. if ((args = PyUnicode_EncodeFSDefault(args)) == NULL)
  1561. return 0;
  1562. }
  1563. else
  1564. Py_INCREF(args);
  1565. if (!PyArg_Parse(args, "y*", &path)) {
  1566. Py_DECREF(args);
  1567. return retval;
  1568. }
  1569. assert(path.len >= 0);
  1570. struct sockaddr_un* addr = &addrbuf->un;
  1571. #ifdef __linux__
  1572. if (path.len == 0 || *(const char *)path.buf == 0) {
  1573. /* Linux abstract namespace extension:
  1574. - Empty address auto-binding to an abstract address
  1575. - Address that starts with null byte */
  1576. if ((size_t)path.len > sizeof addr->sun_path) {
  1577. PyErr_SetString(PyExc_OSError,
  1578. "AF_UNIX path too long");
  1579. goto unix_out;
  1580. }
  1581. *len_ret = path.len + offsetof(struct sockaddr_un, sun_path);
  1582. }
  1583. else
  1584. #endif /* linux */
  1585. {
  1586. /* regular NULL-terminated string */
  1587. if ((size_t)path.len >= sizeof addr->sun_path) {
  1588. PyErr_SetString(PyExc_OSError,
  1589. "AF_UNIX path too long");
  1590. goto unix_out;
  1591. }
  1592. addr->sun_path[path.len] = 0;
  1593. /* including the tailing NUL */
  1594. *len_ret = path.len + offsetof(struct sockaddr_un, sun_path) + 1;
  1595. }
  1596. addr->sun_family = s->sock_family;
  1597. memcpy(addr->sun_path, path.buf, path.len);
  1598. retval = 1;
  1599. unix_out:
  1600. PyBuffer_Release(&path);
  1601. Py_DECREF(args);
  1602. return retval;
  1603. }
  1604. #endif /* AF_UNIX */
  1605. #if defined(AF_NETLINK)
  1606. case AF_NETLINK:
  1607. {
  1608. int pid, groups;
  1609. struct sockaddr_nl* addr = &addrbuf->nl;
  1610. if (!PyTuple_Check(args)) {
  1611. PyErr_Format(
  1612. PyExc_TypeError,
  1613. "%s(): AF_NETLINK address must be tuple, not %.500s",
  1614. caller, Py_TYPE(args)->tp_name);
  1615. return 0;
  1616. }
  1617. if (!PyArg_ParseTuple(args,
  1618. "II;AF_NETLINK address must be a pair "
  1619. "(pid, groups)",
  1620. &pid, &groups))
  1621. {
  1622. return 0;
  1623. }
  1624. addr->nl_family = AF_NETLINK;
  1625. addr->nl_pid = pid;
  1626. addr->nl_groups = groups;
  1627. *len_ret = sizeof(*addr);
  1628. return 1;
  1629. }
  1630. #endif /* AF_NETLINK */
  1631. #if defined(AF_QIPCRTR)
  1632. case AF_QIPCRTR:
  1633. {
  1634. unsigned int node, port;
  1635. struct sockaddr_qrtr* addr = &addrbuf->sq;
  1636. if (!PyTuple_Check(args)) {
  1637. PyErr_Format(
  1638. PyExc_TypeError,
  1639. "getsockaddrarg: "
  1640. "AF_QIPCRTR address must be tuple, not %.500s",
  1641. Py_TYPE(args)->tp_name);
  1642. return 0;
  1643. }
  1644. if (!PyArg_ParseTuple(args, "II:getsockaddrarg", &node, &port))
  1645. return 0;
  1646. addr->sq_family = AF_QIPCRTR;
  1647. addr->sq_node = node;
  1648. addr->sq_port = port;
  1649. *len_ret = sizeof(*addr);
  1650. return 1;
  1651. }
  1652. #endif /* AF_QIPCRTR */
  1653. #if defined(AF_VSOCK)
  1654. case AF_VSOCK:
  1655. {
  1656. struct sockaddr_vm* addr = &addrbuf->vm;
  1657. int port, cid;
  1658. memset(addr, 0, sizeof(struct sockaddr_vm));
  1659. if (!PyTuple_Check(args)) {
  1660. PyErr_Format(
  1661. PyExc_TypeError,
  1662. "getsockaddrarg: "
  1663. "AF_VSOCK address must be tuple, not %.500s",
  1664. Py_TYPE(args)->tp_name);
  1665. return 0;
  1666. }
  1667. if (!PyArg_ParseTuple(args, "II:getsockaddrarg", &cid, &port))
  1668. return 0;
  1669. addr->svm_family = s->sock_family;
  1670. addr->svm_port = port;
  1671. addr->svm_cid = cid;
  1672. *len_ret = sizeof(*addr);
  1673. return 1;
  1674. }
  1675. #endif /* AF_VSOCK */
  1676. #ifdef AF_RDS
  1677. case AF_RDS:
  1678. /* RDS sockets use sockaddr_in: fall-through */
  1679. #endif /* AF_RDS */
  1680. #ifdef AF_DIVERT
  1681. case AF_DIVERT:
  1682. /* FreeBSD divert(4) sockets use sockaddr_in: fall-through */
  1683. #endif /* AF_DIVERT */
  1684. case AF_INET:
  1685. {
  1686. struct maybe_idna host = {NULL, NULL};
  1687. int port, result;
  1688. if (!PyTuple_Check(args)) {
  1689. PyErr_Format(
  1690. PyExc_TypeError,
  1691. "%s(): AF_INET address must be tuple, not %.500s",
  1692. caller, Py_TYPE(args)->tp_name);
  1693. return 0;
  1694. }
  1695. if (!PyArg_ParseTuple(args,
  1696. "O&i;AF_INET address must be a pair "
  1697. "(host, port)",
  1698. idna_converter, &host, &port))
  1699. {
  1700. assert(PyErr_Occurred());
  1701. if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
  1702. PyErr_Format(PyExc_OverflowError,
  1703. "%s(): port must be 0-65535.", caller);
  1704. }
  1705. return 0;
  1706. }
  1707. struct sockaddr_in* addr = &addrbuf->in;
  1708. result = setipaddr(s->state, host.buf, (struct sockaddr *)addr,
  1709. sizeof(*addr), AF_INET);
  1710. idna_cleanup(&host);
  1711. if (result < 0)
  1712. return 0;
  1713. if (port < 0 || port > 0xffff) {
  1714. PyErr_Format(
  1715. PyExc_OverflowError,
  1716. "%s(): port must be 0-65535.", caller);
  1717. return 0;
  1718. }
  1719. addr->sin_family = AF_INET;
  1720. addr->sin_port = htons((short)port);
  1721. *len_ret = sizeof *addr;
  1722. return 1;
  1723. }
  1724. #ifdef ENABLE_IPV6
  1725. case AF_INET6:
  1726. {
  1727. struct maybe_idna host = {NULL, NULL};
  1728. int port, result;
  1729. unsigned int flowinfo, scope_id;
  1730. flowinfo = scope_id = 0;
  1731. if (!PyTuple_Check(args)) {
  1732. PyErr_Format(
  1733. PyExc_TypeError,
  1734. "%s(): AF_INET6 address must be tuple, not %.500s",
  1735. caller, Py_TYPE(args)->tp_name);
  1736. return 0;
  1737. }
  1738. if (!PyArg_ParseTuple(args,
  1739. "O&i|II;AF_INET6 address must be a tuple "
  1740. "(host, port[, flowinfo[, scopeid]])",
  1741. idna_converter, &host, &port, &flowinfo,
  1742. &scope_id))
  1743. {
  1744. assert(PyErr_Occurred());
  1745. if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
  1746. PyErr_Format(PyExc_OverflowError,
  1747. "%s(): port must be 0-65535.", caller);
  1748. }
  1749. return 0;
  1750. }
  1751. struct sockaddr_in6* addr = &addrbuf->in6;
  1752. result = setipaddr(s->state, host.buf, (struct sockaddr *)addr,
  1753. sizeof(*addr), AF_INET6);
  1754. idna_cleanup(&host);
  1755. if (result < 0)
  1756. return 0;
  1757. if (port < 0 || port > 0xffff) {
  1758. PyErr_Format(
  1759. PyExc_OverflowError,
  1760. "%s(): port must be 0-65535.", caller);
  1761. return 0;
  1762. }
  1763. if (flowinfo > 0xfffff) {
  1764. PyErr_Format(
  1765. PyExc_OverflowError,
  1766. "%s(): flowinfo must be 0-1048575.", caller);
  1767. return 0;
  1768. }
  1769. addr->sin6_family = s->sock_family;
  1770. addr->sin6_port = htons((short)port);
  1771. addr->sin6_flowinfo = htonl(flowinfo);
  1772. addr->sin6_scope_id = scope_id;
  1773. *len_ret = sizeof *addr;
  1774. return 1;
  1775. }
  1776. #endif /* ENABLE_IPV6 */
  1777. #ifdef USE_BLUETOOTH
  1778. case AF_BLUETOOTH:
  1779. {
  1780. switch (s->sock_proto) {
  1781. #ifdef BTPROTO_L2CAP
  1782. case BTPROTO_L2CAP:
  1783. {
  1784. const char *straddr;
  1785. struct sockaddr_l2 *addr = &addrbuf->bt_l2;
  1786. memset(addr, 0, sizeof(struct sockaddr_l2));
  1787. _BT_L2_MEMB(addr, family) = AF_BLUETOOTH;
  1788. if (!PyArg_ParseTuple(args, "si", &straddr,
  1789. &_BT_L2_MEMB(addr, psm))) {
  1790. PyErr_Format(PyExc_OSError,
  1791. "%s(): wrong format", caller);
  1792. return 0;
  1793. }
  1794. if (setbdaddr(straddr, &_BT_L2_MEMB(addr, bdaddr)) < 0)
  1795. return 0;
  1796. *len_ret = sizeof *addr;
  1797. return 1;
  1798. }
  1799. #endif /* BTPROTO_L2CAP */
  1800. case BTPROTO_RFCOMM:
  1801. {
  1802. const char *straddr;
  1803. struct sockaddr_rc *addr = &addrbuf->bt_rc;
  1804. _BT_RC_MEMB(addr, family) = AF_BLUETOOTH;
  1805. if (!PyArg_ParseTuple(args, "si", &straddr,
  1806. &_BT_RC_MEMB(addr, channel))) {
  1807. PyErr_Format(PyExc_OSError,
  1808. "%s(): wrong format", caller);
  1809. return 0;
  1810. }
  1811. if (setbdaddr(straddr, &_BT_RC_MEMB(addr, bdaddr)) < 0)
  1812. return 0;
  1813. *len_ret = sizeof *addr;
  1814. return 1;
  1815. }
  1816. #ifdef BTPROTO_HCI
  1817. case BTPROTO_HCI:
  1818. {
  1819. struct sockaddr_hci *addr = &addrbuf->bt_hci;
  1820. #if defined(__NetBSD__) || defined(__DragonFly__)
  1821. const char *straddr;
  1822. _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH;
  1823. if (!PyBytes_Check(args)) {
  1824. PyErr_Format(PyExc_OSError, "%s: "
  1825. "wrong format", caller);
  1826. return 0;
  1827. }
  1828. straddr = PyBytes_AS_STRING(args);
  1829. if (setbdaddr(straddr, &_BT_HCI_MEMB(addr, bdaddr)) < 0)
  1830. return 0;
  1831. #else /* __NetBSD__ || __DragonFly__ */
  1832. _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH;
  1833. if (!PyArg_ParseTuple(args, "i", &_BT_HCI_MEMB(addr, dev))) {
  1834. PyErr_Format(PyExc_OSError,
  1835. "%s(): wrong format", caller);
  1836. return 0;
  1837. }
  1838. #endif /* !(__NetBSD__ || __DragonFly__) */
  1839. *len_ret = sizeof *addr;
  1840. return 1;
  1841. }
  1842. #if !defined(__FreeBSD__)
  1843. case BTPROTO_SCO:
  1844. {
  1845. const char *straddr;
  1846. struct sockaddr_sco *addr = &addrbuf->bt_sco;
  1847. _BT_SCO_MEMB(addr, family) = AF_BLUETOOTH;
  1848. if (!PyBytes_Check(args)) {
  1849. PyErr_Format(PyExc_OSError,
  1850. "%s(): wrong format", caller);
  1851. return 0;
  1852. }
  1853. straddr = PyBytes_AS_STRING(args);
  1854. if (setbdaddr(straddr, &_BT_SCO_MEMB(addr, bdaddr)) < 0)
  1855. return 0;
  1856. *len_ret = sizeof *addr;
  1857. return 1;
  1858. }
  1859. #endif /* !__FreeBSD__ */
  1860. #endif /* BTPROTO_HCI */
  1861. default:
  1862. PyErr_Format(PyExc_OSError,
  1863. "%s(): unknown Bluetooth protocol", caller);
  1864. return 0;
  1865. }
  1866. }
  1867. #endif /* USE_BLUETOOTH */
  1868. #if defined(HAVE_NETPACKET_PACKET_H) && defined(SIOCGIFINDEX)
  1869. case AF_PACKET:
  1870. {
  1871. struct ifreq ifr;
  1872. const char *interfaceName;
  1873. int protoNumber;
  1874. int hatype = 0;
  1875. int pkttype = PACKET_HOST;
  1876. Py_buffer haddr = {NULL, NULL};
  1877. if (!PyTuple_Check(args)) {
  1878. PyErr_Format(
  1879. PyExc_TypeError,
  1880. "%s(): AF_PACKET address must be tuple, not %.500s",
  1881. caller, Py_TYPE(args)->tp_name);
  1882. return 0;
  1883. }
  1884. /* XXX: improve the default error message according to the
  1885. documentation of AF_PACKET, which would be added as part
  1886. of bpo-25041. */
  1887. if (!PyArg_ParseTuple(args,
  1888. "si|iiy*;AF_PACKET address must be a tuple of "
  1889. "two to five elements",
  1890. &interfaceName, &protoNumber, &pkttype, &hatype,
  1891. &haddr))
  1892. {
  1893. assert(PyErr_Occurred());
  1894. if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
  1895. PyErr_Format(PyExc_OverflowError,
  1896. "%s(): address argument out of range", caller);
  1897. }
  1898. return 0;
  1899. }
  1900. strncpy(ifr.ifr_name, interfaceName, sizeof(ifr.ifr_name));
  1901. ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0';
  1902. if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) {
  1903. s->errorhandler();
  1904. PyBuffer_Release(&haddr);
  1905. return 0;
  1906. }
  1907. if (haddr.buf && haddr.len > 8) {
  1908. PyErr_SetString(PyExc_ValueError,
  1909. "Hardware address must be 8 bytes or less");
  1910. PyBuffer_Release(&haddr);
  1911. return 0;
  1912. }
  1913. if (protoNumber < 0 || protoNumber > 0xffff) {
  1914. PyErr_Format(
  1915. PyExc_OverflowError,
  1916. "%s(): proto must be 0-65535.", caller);
  1917. PyBuffer_Release(&haddr);
  1918. return 0;
  1919. }
  1920. struct sockaddr_ll* addr = &addrbuf->ll;
  1921. addr->sll_family = AF_PACKET;
  1922. addr->sll_protocol = htons((short)protoNumber);
  1923. addr->sll_ifindex = ifr.ifr_ifindex;
  1924. addr->sll_pkttype = pkttype;
  1925. addr->sll_hatype = hatype;
  1926. if (haddr.buf) {
  1927. memcpy(&addr->sll_addr, haddr.buf, haddr.len);
  1928. addr->sll_halen = haddr.len;
  1929. }
  1930. else
  1931. addr->sll_halen = 0;
  1932. *len_ret = sizeof *addr;
  1933. PyBuffer_Release(&haddr);
  1934. return 1;
  1935. }
  1936. #endif /* HAVE_NETPACKET_PACKET_H && SIOCGIFINDEX */
  1937. #ifdef HAVE_LINUX_TIPC_H
  1938. case AF_TIPC:
  1939. {
  1940. unsigned int atype, v1, v2, v3;
  1941. unsigned int scope = TIPC_CLUSTER_SCOPE;
  1942. if (!PyTuple_Check(args)) {
  1943. PyErr_Format(
  1944. PyExc_TypeError,
  1945. "%s(): AF_TIPC address must be tuple, not %.500s",
  1946. caller, Py_TYPE(args)->tp_name);
  1947. return 0;
  1948. }
  1949. if (!PyArg_ParseTuple(args,
  1950. "IIII|I;AF_TIPC address must be a tuple "
  1951. "(addr_type, v1, v2, v3[, scope])",
  1952. &atype, &v1, &v2, &v3, &scope))
  1953. {
  1954. return 0;
  1955. }
  1956. struct sockaddr_tipc *addr = &addrbuf->tipc;
  1957. memset(addr, 0, sizeof(struct sockaddr_tipc));
  1958. addr->family = AF_TIPC;
  1959. addr->scope = scope;
  1960. addr->addrtype = atype;
  1961. if (atype == TIPC_ADDR_NAMESEQ) {
  1962. addr->addr.nameseq.type = v1;
  1963. addr->addr.nameseq.lower = v2;
  1964. addr->addr.nameseq.upper = v3;
  1965. } else if (atype == TIPC_ADDR_NAME) {
  1966. addr->addr.name.name.type = v1;
  1967. addr->addr.name.name.instance = v2;
  1968. } else if (atype == TIPC_ADDR_ID) {
  1969. addr->addr.id.node = v1;
  1970. addr->addr.id.ref = v2;
  1971. } else {
  1972. /* Shouldn't happen */
  1973. PyErr_SetString(PyExc_TypeError, "Invalid address type");
  1974. return 0;
  1975. }
  1976. *len_ret = sizeof(*addr);
  1977. return 1;
  1978. }
  1979. #endif /* HAVE_LINUX_TIPC_H */
  1980. #if defined(AF_CAN) && defined(SIOCGIFINDEX)
  1981. case AF_CAN:
  1982. switch (s->sock_proto) {
  1983. #ifdef CAN_RAW
  1984. case CAN_RAW:
  1985. /* fall-through */
  1986. #endif
  1987. #ifdef CAN_BCM
  1988. case CAN_BCM:
  1989. #endif
  1990. #if defined(CAN_RAW) || defined(CAN_BCM)
  1991. {
  1992. PyObject *interfaceName;
  1993. struct ifreq ifr;
  1994. Py_ssize_t len;
  1995. struct sockaddr_can *addr = &addrbuf->can;
  1996. if (!PyTuple_Check(args)) {
  1997. PyErr_Format(PyExc_TypeError,
  1998. "%s(): AF_CAN address must be tuple, not %.500s",
  1999. caller, Py_TYPE(args)->tp_name);
  2000. return 0;
  2001. }
  2002. if (!PyArg_ParseTuple(args,
  2003. "O&;AF_CAN address must be a tuple "
  2004. "(interface, )",
  2005. PyUnicode_FSConverter, &interfaceName))
  2006. {
  2007. return 0;
  2008. }
  2009. len = PyBytes_GET_SIZE(interfaceName);
  2010. if (len == 0) {
  2011. ifr.ifr_ifindex = 0;
  2012. } else if ((size_t)len < sizeof(ifr.ifr_name)) {
  2013. strncpy(ifr.ifr_name, PyBytes_AS_STRING(interfaceName), sizeof(ifr.ifr_name));
  2014. ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0';
  2015. if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) {
  2016. s->errorhandler();
  2017. Py_DECREF(interfaceName);
  2018. return 0;
  2019. }
  2020. } else {
  2021. PyErr_SetString(PyExc_OSError,
  2022. "AF_CAN interface name too long");
  2023. Py_DECREF(interfaceName);
  2024. return 0;
  2025. }
  2026. addr->can_family = AF_CAN;
  2027. addr->can_ifindex = ifr.ifr_ifindex;
  2028. *len_ret = sizeof(*addr);
  2029. Py_DECREF(interfaceName);
  2030. return 1;
  2031. }
  2032. #endif /* CAN_RAW || CAN_BCM */
  2033. #ifdef CAN_ISOTP
  2034. case CAN_ISOTP:
  2035. {
  2036. PyObject *interfaceName;
  2037. struct ifreq ifr;
  2038. Py_ssize_t len;
  2039. unsigned long int rx_id, tx_id;
  2040. struct sockaddr_can *addr = &addrbuf->can;
  2041. if (!PyArg_ParseTuple(args, "O&kk", PyUnicode_FSConverter,
  2042. &interfaceName,
  2043. &rx_id,
  2044. &tx_id))
  2045. return 0;
  2046. len = PyBytes_GET_SIZE(interfaceName);
  2047. if (len == 0) {
  2048. ifr.ifr_ifindex = 0;
  2049. } else if ((size_t)len < sizeof(ifr.ifr_name)) {
  2050. strncpy(ifr.ifr_name, PyBytes_AS_STRING(interfaceName), sizeof(ifr.ifr_name));
  2051. ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0';
  2052. if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) {
  2053. s->errorhandler();
  2054. Py_DECREF(interfaceName);
  2055. return 0;
  2056. }
  2057. } else {
  2058. PyErr_SetString(PyExc_OSError,
  2059. "AF_CAN interface name too long");
  2060. Py_DECREF(interfaceName);
  2061. return 0;
  2062. }
  2063. addr->can_family = AF_CAN;
  2064. addr->can_ifindex = ifr.ifr_ifindex;
  2065. addr->can_addr.tp.rx_id = rx_id;
  2066. addr->can_addr.tp.tx_id = tx_id;
  2067. *len_ret = sizeof(*addr);
  2068. Py_DECREF(interfaceName);
  2069. return 1;
  2070. }
  2071. #endif /* CAN_ISOTP */
  2072. #ifdef CAN_J1939
  2073. case CAN_J1939:
  2074. {
  2075. PyObject *interfaceName;
  2076. struct ifreq ifr;
  2077. Py_ssize_t len;
  2078. unsigned long long j1939_name; /* at least 64 bits */
  2079. unsigned int j1939_pgn; /* at least 32 bits */
  2080. uint8_t j1939_addr;
  2081. struct sockaddr_can *addr = &addrbuf->can;
  2082. if (!PyArg_ParseTuple(args, "O&KIB", PyUnicode_FSConverter,
  2083. &interfaceName,
  2084. &j1939_name,
  2085. &j1939_pgn,
  2086. &j1939_addr))
  2087. return 0;
  2088. len = PyBytes_GET_SIZE(interfaceName);
  2089. if (len == 0) {
  2090. ifr.ifr_ifindex = 0;
  2091. } else if ((size_t)len < sizeof(ifr.ifr_name)) {
  2092. strncpy(ifr.ifr_name, PyBytes_AS_STRING(interfaceName), sizeof(ifr.ifr_name));
  2093. ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0';
  2094. if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) {
  2095. s->errorhandler();
  2096. Py_DECREF(interfaceName);
  2097. return 0;
  2098. }
  2099. } else {
  2100. PyErr_SetString(PyExc_OSError,
  2101. "AF_CAN interface name too long");
  2102. Py_DECREF(interfaceName);
  2103. return 0;
  2104. }
  2105. addr->can_family = AF_CAN;
  2106. addr->can_ifindex = ifr.ifr_ifindex;
  2107. addr->can_addr.j1939.name = (uint64_t)j1939_name;
  2108. addr->can_addr.j1939.pgn = (uint32_t)j1939_pgn;
  2109. addr->can_addr.j1939.addr = j1939_addr;
  2110. *len_ret = sizeof(*addr);
  2111. Py_DECREF(interfaceName);
  2112. return 1;
  2113. }
  2114. #endif /* CAN_J1939 */
  2115. default:
  2116. PyErr_Format(PyExc_OSError,
  2117. "%s(): unsupported CAN protocol", caller);
  2118. return 0;
  2119. }
  2120. #endif /* AF_CAN && SIOCGIFINDEX */
  2121. #ifdef PF_SYSTEM
  2122. case PF_SYSTEM:
  2123. switch (s->sock_proto) {
  2124. #ifdef SYSPROTO_CONTROL
  2125. case SYSPROTO_CONTROL:
  2126. {
  2127. struct sockaddr_ctl *addr = &addrbuf->ctl;
  2128. addr->sc_family = AF_SYSTEM;
  2129. addr->ss_sysaddr = AF_SYS_CONTROL;
  2130. if (PyUnicode_Check(args)) {
  2131. struct ctl_info info;
  2132. PyObject *ctl_name;
  2133. if (!PyArg_Parse(args, "O&",
  2134. PyUnicode_FSConverter, &ctl_name)) {
  2135. return 0;
  2136. }
  2137. if (PyBytes_GET_SIZE(ctl_name) > (Py_ssize_t)sizeof(info.ctl_name)) {
  2138. PyErr_SetString(PyExc_ValueError,
  2139. "provided string is too long");
  2140. Py_DECREF(ctl_name);
  2141. return 0;
  2142. }
  2143. strncpy(info.ctl_name, PyBytes_AS_STRING(ctl_name),
  2144. sizeof(info.ctl_name));
  2145. Py_DECREF(ctl_name);
  2146. if (ioctl(s->sock_fd, CTLIOCGINFO, &info)) {
  2147. PyErr_SetString(PyExc_OSError,
  2148. "cannot find kernel control with provided name");
  2149. return 0;
  2150. }
  2151. addr->sc_id = info.ctl_id;
  2152. addr->sc_unit = 0;
  2153. } else if (!PyArg_ParseTuple(args, "II",
  2154. &(addr->sc_id), &(addr->sc_unit))) {
  2155. PyErr_Format(PyExc_TypeError,
  2156. "%s(): PF_SYSTEM address must be a str or "
  2157. "a pair (id, unit)", caller);
  2158. return 0;
  2159. }
  2160. *len_ret = sizeof(*addr);
  2161. return 1;
  2162. }
  2163. #endif /* SYSPROTO_CONTROL */
  2164. default:
  2165. PyErr_Format(PyExc_OSError,
  2166. "%s(): unsupported PF_SYSTEM protocol", caller);
  2167. return 0;
  2168. }
  2169. #endif /* PF_SYSTEM */
  2170. #ifdef HAVE_SOCKADDR_ALG
  2171. case AF_ALG:
  2172. {
  2173. const char *type;
  2174. const char *name;
  2175. struct sockaddr_alg *sa = &addrbuf->alg;
  2176. memset(sa, 0, sizeof(*sa));
  2177. sa->salg_family = AF_ALG;
  2178. if (!PyTuple_Check(args)) {
  2179. PyErr_Format(PyExc_TypeError,
  2180. "%s(): AF_ALG address must be tuple, not %.500s",
  2181. caller, Py_TYPE(args)->tp_name);
  2182. return 0;
  2183. }
  2184. if (!PyArg_ParseTuple(args,
  2185. "ss|HH;AF_ALG address must be a tuple "
  2186. "(type, name[, feat[, mask]])",
  2187. &type, &name, &sa->salg_feat, &sa->salg_mask))
  2188. {
  2189. return 0;
  2190. }
  2191. /* sockaddr_alg has fixed-sized char arrays for type, and name
  2192. * both must be NULL terminated.
  2193. */
  2194. if (strlen(type) >= sizeof(sa->salg_type)) {
  2195. PyErr_SetString(PyExc_ValueError, "AF_ALG type too long.");
  2196. return 0;
  2197. }
  2198. strncpy((char *)sa->salg_type, type, sizeof(sa->salg_type));
  2199. if (strlen(name) >= sizeof(sa->salg_name)) {
  2200. PyErr_SetString(PyExc_ValueError, "AF_ALG name too long.");
  2201. return 0;
  2202. }
  2203. strncpy((char *)sa->salg_name, name, sizeof(sa->salg_name));
  2204. *len_ret = sizeof(*sa);
  2205. return 1;
  2206. }
  2207. #endif /* HAVE_SOCKADDR_ALG */
  2208. #ifdef HAVE_AF_HYPERV
  2209. case AF_HYPERV:
  2210. {
  2211. switch (s->sock_proto) {
  2212. case HV_PROTOCOL_RAW:
  2213. {
  2214. PyObject *vm_id_obj = NULL;
  2215. PyObject *service_id_obj = NULL;
  2216. SOCKADDR_HV *addr = &addrbuf->hv;
  2217. memset(addr, 0, sizeof(*addr));
  2218. addr->Family = AF_HYPERV;
  2219. if (!PyTuple_Check(args)) {
  2220. PyErr_Format(PyExc_TypeError,
  2221. "%s(): AF_HYPERV address must be tuple, not %.500s",
  2222. caller, Py_TYPE(args)->tp_name);
  2223. return 0;
  2224. }
  2225. if (!PyArg_ParseTuple(args,
  2226. "UU;AF_HYPERV address must be a str tuple (vm_id, service_id)",
  2227. &vm_id_obj, &service_id_obj))
  2228. {
  2229. return 0;
  2230. }
  2231. wchar_t *guid_str = PyUnicode_AsWideCharString(vm_id_obj, NULL);
  2232. if (guid_str == NULL) {
  2233. PyErr_Format(PyExc_ValueError,
  2234. "%s(): AF_HYPERV address vm_id is not a valid UUID string",
  2235. caller);
  2236. return 0;
  2237. }
  2238. RPC_STATUS rc = UuidFromStringW(guid_str, &addr->VmId);
  2239. PyMem_Free(guid_str);
  2240. if (rc != RPC_S_OK) {
  2241. PyErr_Format(PyExc_ValueError,
  2242. "%s(): AF_HYPERV address vm_id is not a valid UUID string",
  2243. caller);
  2244. return 0;
  2245. }
  2246. guid_str = PyUnicode_AsWideCharString(service_id_obj, NULL);
  2247. if (guid_str == NULL) {
  2248. PyErr_Format(PyExc_ValueError,
  2249. "%s(): AF_HYPERV address service_id is not a valid UUID string",
  2250. caller);
  2251. return 0;
  2252. }
  2253. rc = UuidFromStringW(guid_str, &addr->ServiceId);
  2254. PyMem_Free(guid_str);
  2255. if (rc != RPC_S_OK) {
  2256. PyErr_Format(PyExc_ValueError,
  2257. "%s(): AF_HYPERV address service_id is not a valid UUID string",
  2258. caller);
  2259. return 0;
  2260. }
  2261. *len_ret = sizeof(*addr);
  2262. return 1;
  2263. }
  2264. default:
  2265. PyErr_Format(PyExc_OSError,
  2266. "%s(): unsupported AF_HYPERV protocol: %d",
  2267. caller, s->sock_proto);
  2268. return 0;
  2269. }
  2270. }
  2271. #endif /* HAVE_AF_HYPERV */
  2272. /* More cases here... */
  2273. default:
  2274. PyErr_Format(PyExc_OSError, "%s(): bad family", caller);
  2275. return 0;
  2276. }
  2277. }
  2278. #endif // defined(HAVE_BIND) || defined(HAVE_CONNECTTO) || defined(CMSG_LEN)
  2279. /* Get the address length according to the socket object's address family.
  2280. Return 1 if the family is known, 0 otherwise. The length is returned
  2281. through len_ret. */
  2282. static int
  2283. getsockaddrlen(PySocketSockObject *s, socklen_t *len_ret)
  2284. {
  2285. switch (s->sock_family) {
  2286. #if defined(AF_UNIX)
  2287. case AF_UNIX:
  2288. {
  2289. *len_ret = sizeof (struct sockaddr_un);
  2290. return 1;
  2291. }
  2292. #endif /* AF_UNIX */
  2293. #if defined(AF_NETLINK)
  2294. case AF_NETLINK:
  2295. {
  2296. *len_ret = sizeof (struct sockaddr_nl);
  2297. return 1;
  2298. }
  2299. #endif /* AF_NETLINK */
  2300. #if defined(AF_QIPCRTR)
  2301. case AF_QIPCRTR:
  2302. {
  2303. *len_ret = sizeof (struct sockaddr_qrtr);
  2304. return 1;
  2305. }
  2306. #endif /* AF_QIPCRTR */
  2307. #if defined(AF_VSOCK)
  2308. case AF_VSOCK:
  2309. {
  2310. *len_ret = sizeof (struct sockaddr_vm);
  2311. return 1;
  2312. }
  2313. #endif /* AF_VSOCK */
  2314. #ifdef AF_RDS
  2315. case AF_RDS:
  2316. /* RDS sockets use sockaddr_in: fall-through */
  2317. #endif /* AF_RDS */
  2318. case AF_INET:
  2319. {
  2320. *len_ret = sizeof (struct sockaddr_in);
  2321. return 1;
  2322. }
  2323. #ifdef ENABLE_IPV6
  2324. case AF_INET6:
  2325. {
  2326. *len_ret = sizeof (struct sockaddr_in6);
  2327. return 1;
  2328. }
  2329. #endif /* ENABLE_IPV6 */
  2330. #ifdef USE_BLUETOOTH
  2331. case AF_BLUETOOTH:
  2332. {
  2333. switch(s->sock_proto)
  2334. {
  2335. #ifdef BTPROTO_L2CAP
  2336. case BTPROTO_L2CAP:
  2337. *len_ret = sizeof (struct sockaddr_l2);
  2338. return 1;
  2339. #endif /* BTPROTO_L2CAP */
  2340. case BTPROTO_RFCOMM:
  2341. *len_ret = sizeof (struct sockaddr_rc);
  2342. return 1;
  2343. #ifdef BTPROTO_HCI
  2344. case BTPROTO_HCI:
  2345. *len_ret = sizeof (struct sockaddr_hci);
  2346. return 1;
  2347. #if !defined(__FreeBSD__)
  2348. case BTPROTO_SCO:
  2349. *len_ret = sizeof (struct sockaddr_sco);
  2350. return 1;
  2351. #endif /* !__FreeBSD__ */
  2352. #endif /* BTPROTO_HCI */
  2353. default:
  2354. PyErr_SetString(PyExc_OSError, "getsockaddrlen: "
  2355. "unknown BT protocol");
  2356. return 0;
  2357. }
  2358. }
  2359. #endif /* USE_BLUETOOTH */
  2360. #ifdef HAVE_NETPACKET_PACKET_H
  2361. case AF_PACKET:
  2362. {
  2363. *len_ret = sizeof (struct sockaddr_ll);
  2364. return 1;
  2365. }
  2366. #endif /* HAVE_NETPACKET_PACKET_H */
  2367. #ifdef HAVE_LINUX_TIPC_H
  2368. case AF_TIPC:
  2369. {
  2370. *len_ret = sizeof (struct sockaddr_tipc);
  2371. return 1;
  2372. }
  2373. #endif /* HAVE_LINUX_TIPC_H */
  2374. #ifdef AF_CAN
  2375. case AF_CAN:
  2376. {
  2377. *len_ret = sizeof (struct sockaddr_can);
  2378. return 1;
  2379. }
  2380. #endif /* AF_CAN */
  2381. #ifdef PF_SYSTEM
  2382. case PF_SYSTEM:
  2383. switch(s->sock_proto) {
  2384. #ifdef SYSPROTO_CONTROL
  2385. case SYSPROTO_CONTROL:
  2386. *len_ret = sizeof (struct sockaddr_ctl);
  2387. return 1;
  2388. #endif /* SYSPROTO_CONTROL */
  2389. default:
  2390. PyErr_SetString(PyExc_OSError, "getsockaddrlen: "
  2391. "unknown PF_SYSTEM protocol");
  2392. return 0;
  2393. }
  2394. #endif /* PF_SYSTEM */
  2395. #ifdef HAVE_SOCKADDR_ALG
  2396. case AF_ALG:
  2397. {
  2398. *len_ret = sizeof (struct sockaddr_alg);
  2399. return 1;
  2400. }
  2401. #endif /* HAVE_SOCKADDR_ALG */
  2402. #ifdef HAVE_AF_HYPERV
  2403. case AF_HYPERV:
  2404. {
  2405. *len_ret = sizeof (SOCKADDR_HV);
  2406. return 1;
  2407. }
  2408. #endif /* HAVE_AF_HYPERV */
  2409. /* More cases here... */
  2410. default:
  2411. PyErr_SetString(PyExc_OSError, "getsockaddrlen: bad family");
  2412. return 0;
  2413. }
  2414. }
  2415. /* Support functions for the sendmsg() and recvmsg[_into]() methods.
  2416. Currently, these methods are only compiled if the RFC 2292/3542
  2417. CMSG_LEN() macro is available. Older systems seem to have used
  2418. sizeof(struct cmsghdr) + (length) where CMSG_LEN() is used now, so
  2419. it may be possible to define CMSG_LEN() that way if it's not
  2420. provided. Some architectures might need extra padding after the
  2421. cmsghdr, however, and CMSG_LEN() would have to take account of
  2422. this. */
  2423. #ifdef CMSG_LEN
  2424. /* If length is in range, set *result to CMSG_LEN(length) and return
  2425. true; otherwise, return false. */
  2426. static int
  2427. get_CMSG_LEN(size_t length, size_t *result)
  2428. {
  2429. size_t tmp;
  2430. if (length > (SOCKLEN_T_LIMIT - CMSG_LEN(0)))
  2431. return 0;
  2432. tmp = CMSG_LEN(length);
  2433. if (tmp > SOCKLEN_T_LIMIT || tmp < length)
  2434. return 0;
  2435. *result = tmp;
  2436. return 1;
  2437. }
  2438. #ifdef CMSG_SPACE
  2439. /* If length is in range, set *result to CMSG_SPACE(length) and return
  2440. true; otherwise, return false. */
  2441. static int
  2442. get_CMSG_SPACE(size_t length, size_t *result)
  2443. {
  2444. size_t tmp;
  2445. /* Use CMSG_SPACE(1) here in order to take account of the padding
  2446. necessary before *and* after the data. */
  2447. if (length > (SOCKLEN_T_LIMIT - CMSG_SPACE(1)))
  2448. return 0;
  2449. tmp = CMSG_SPACE(length);
  2450. if (tmp > SOCKLEN_T_LIMIT || tmp < length)
  2451. return 0;
  2452. *result = tmp;
  2453. return 1;
  2454. }
  2455. #endif
  2456. /* Return true iff msg->msg_controllen is valid, cmsgh is a valid
  2457. pointer in msg->msg_control with at least "space" bytes after it,
  2458. and its cmsg_len member inside the buffer. */
  2459. static int
  2460. cmsg_min_space(struct msghdr *msg, struct cmsghdr *cmsgh, size_t space)
  2461. {
  2462. size_t cmsg_offset;
  2463. static const size_t cmsg_len_end = (offsetof(struct cmsghdr, cmsg_len) +
  2464. sizeof(cmsgh->cmsg_len));
  2465. /* Note that POSIX allows msg_controllen to be of signed type. */
  2466. if (cmsgh == NULL || msg->msg_control == NULL)
  2467. return 0;
  2468. /* Note that POSIX allows msg_controllen to be of a signed type. This is
  2469. annoying under OS X as it's unsigned there and so it triggers a
  2470. tautological comparison warning under Clang when compared against 0.
  2471. Since the check is valid on other platforms, silence the warning under
  2472. Clang. */
  2473. #ifdef __clang__
  2474. #pragma clang diagnostic push
  2475. #pragma clang diagnostic ignored "-Wtautological-compare"
  2476. #endif
  2477. #if defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))
  2478. #pragma GCC diagnostic push
  2479. #pragma GCC diagnostic ignored "-Wtype-limits"
  2480. #endif
  2481. if (msg->msg_controllen < 0)
  2482. return 0;
  2483. #if defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))
  2484. #pragma GCC diagnostic pop
  2485. #endif
  2486. #ifdef __clang__
  2487. #pragma clang diagnostic pop
  2488. #endif
  2489. if (space < cmsg_len_end)
  2490. space = cmsg_len_end;
  2491. cmsg_offset = (char *)cmsgh - (char *)msg->msg_control;
  2492. return (cmsg_offset <= (size_t)-1 - space &&
  2493. cmsg_offset + space <= msg->msg_controllen);
  2494. }
  2495. /* If pointer CMSG_DATA(cmsgh) is in buffer msg->msg_control, set
  2496. *space to number of bytes following it in the buffer and return
  2497. true; otherwise, return false. Assumes cmsgh, msg->msg_control and
  2498. msg->msg_controllen are valid. */
  2499. static int
  2500. get_cmsg_data_space(struct msghdr *msg, struct cmsghdr *cmsgh, size_t *space)
  2501. {
  2502. size_t data_offset;
  2503. char *data_ptr;
  2504. if ((data_ptr = (char *)CMSG_DATA(cmsgh)) == NULL)
  2505. return 0;
  2506. data_offset = data_ptr - (char *)msg->msg_control;
  2507. if (data_offset > msg->msg_controllen)
  2508. return 0;
  2509. *space = msg->msg_controllen - data_offset;
  2510. return 1;
  2511. }
  2512. /* If cmsgh is invalid or not contained in the buffer pointed to by
  2513. msg->msg_control, return -1. If cmsgh is valid and its associated
  2514. data is entirely contained in the buffer, set *data_len to the
  2515. length of the associated data and return 0. If only part of the
  2516. associated data is contained in the buffer but cmsgh is otherwise
  2517. valid, set *data_len to the length contained in the buffer and
  2518. return 1. */
  2519. static int
  2520. get_cmsg_data_len(struct msghdr *msg, struct cmsghdr *cmsgh, size_t *data_len)
  2521. {
  2522. size_t space, cmsg_data_len;
  2523. if (!cmsg_min_space(msg, cmsgh, CMSG_LEN(0)) ||
  2524. cmsgh->cmsg_len < CMSG_LEN(0))
  2525. return -1;
  2526. cmsg_data_len = cmsgh->cmsg_len - CMSG_LEN(0);
  2527. if (!get_cmsg_data_space(msg, cmsgh, &space))
  2528. return -1;
  2529. if (space >= cmsg_data_len) {
  2530. *data_len = cmsg_data_len;
  2531. return 0;
  2532. }
  2533. *data_len = space;
  2534. return 1;
  2535. }
  2536. #endif /* CMSG_LEN */
  2537. struct sock_accept {
  2538. socklen_t *addrlen;
  2539. sock_addr_t *addrbuf;
  2540. SOCKET_T result;
  2541. };
  2542. #if defined(HAVE_ACCEPT) || defined(HAVE_ACCEPT4)
  2543. static int
  2544. sock_accept_impl(PySocketSockObject *s, void *data)
  2545. {
  2546. struct sock_accept *ctx = data;
  2547. struct sockaddr *addr = SAS2SA(ctx->addrbuf);
  2548. socklen_t *paddrlen = ctx->addrlen;
  2549. #ifdef HAVE_SOCKADDR_ALG
  2550. /* AF_ALG does not support accept() with addr and raises
  2551. * ECONNABORTED instead. */
  2552. if (s->sock_family == AF_ALG) {
  2553. addr = NULL;
  2554. paddrlen = NULL;
  2555. *ctx->addrlen = 0;
  2556. }
  2557. #endif
  2558. #if defined(HAVE_ACCEPT4) && defined(SOCK_CLOEXEC)
  2559. socket_state *state = s->state;
  2560. if (state->accept4_works != 0) {
  2561. ctx->result = accept4(s->sock_fd, addr, paddrlen,
  2562. SOCK_CLOEXEC);
  2563. if (ctx->result == INVALID_SOCKET && state->accept4_works == -1) {
  2564. /* On Linux older than 2.6.28, accept4() fails with ENOSYS */
  2565. state->accept4_works = (errno != ENOSYS);
  2566. }
  2567. }
  2568. if (state->accept4_works == 0)
  2569. ctx->result = accept(s->sock_fd, addr, paddrlen);
  2570. #else
  2571. ctx->result = accept(s->sock_fd, addr, paddrlen);
  2572. #endif
  2573. #ifdef MS_WINDOWS
  2574. return (ctx->result != INVALID_SOCKET);
  2575. #else
  2576. return (ctx->result >= 0);
  2577. #endif
  2578. }
  2579. /* s._accept() -> (fd, address) */
  2580. static PyObject *
  2581. sock_accept(PySocketSockObject *s, PyObject *Py_UNUSED(ignored))
  2582. {
  2583. sock_addr_t addrbuf;
  2584. SOCKET_T newfd;
  2585. socklen_t addrlen;
  2586. PyObject *sock = NULL;
  2587. PyObject *addr = NULL;
  2588. PyObject *res = NULL;
  2589. struct sock_accept ctx;
  2590. if (!getsockaddrlen(s, &addrlen))
  2591. return NULL;
  2592. memset(&addrbuf, 0, addrlen);
  2593. if (!IS_SELECTABLE(s))
  2594. return select_error();
  2595. ctx.addrlen = &addrlen;
  2596. ctx.addrbuf = &addrbuf;
  2597. if (sock_call(s, 0, sock_accept_impl, &ctx) < 0)
  2598. return NULL;
  2599. newfd = ctx.result;
  2600. #ifdef MS_WINDOWS
  2601. #if defined(MS_WINDOWS_APP) || defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_SYSTEM)
  2602. #ifndef HANDLE_FLAG_INHERIT
  2603. #define HANDLE_FLAG_INHERIT 0x00000001
  2604. #endif
  2605. if (!SetHandleInformation((HANDLE)newfd, HANDLE_FLAG_INHERIT, 0)) {
  2606. PyErr_SetFromWindowsErr(0);
  2607. SOCKETCLOSE(newfd);
  2608. goto finally;
  2609. }
  2610. #endif
  2611. #else
  2612. #if defined(HAVE_ACCEPT4) && defined(SOCK_CLOEXEC)
  2613. socket_state *state = s->state;
  2614. if (!state->accept4_works)
  2615. #endif
  2616. {
  2617. if (_Py_set_inheritable(newfd, 0, NULL) < 0) {
  2618. SOCKETCLOSE(newfd);
  2619. goto finally;
  2620. }
  2621. }
  2622. #endif
  2623. sock = PyLong_FromSocket_t(newfd);
  2624. if (sock == NULL) {
  2625. SOCKETCLOSE(newfd);
  2626. goto finally;
  2627. }
  2628. addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
  2629. addrlen, s->sock_proto);
  2630. if (addr == NULL)
  2631. goto finally;
  2632. res = PyTuple_Pack(2, sock, addr);
  2633. finally:
  2634. Py_XDECREF(sock);
  2635. Py_XDECREF(addr);
  2636. return res;
  2637. }
  2638. PyDoc_STRVAR(accept_doc,
  2639. "_accept() -> (integer, address info)\n\
  2640. \n\
  2641. Wait for an incoming connection. Return a new socket file descriptor\n\
  2642. representing the connection, and the address of the client.\n\
  2643. For IP sockets, the address info is a pair (hostaddr, port).");
  2644. #endif // defined(HAVE_ACCEPT) || defined(HAVE_ACCEPT4)
  2645. /* s.setblocking(flag) method. Argument:
  2646. False -- non-blocking mode; same as settimeout(0)
  2647. True -- blocking mode; same as settimeout(None)
  2648. */
  2649. static PyObject *
  2650. sock_setblocking(PySocketSockObject *s, PyObject *arg)
  2651. {
  2652. long block;
  2653. block = PyObject_IsTrue(arg);
  2654. if (block < 0)
  2655. return NULL;
  2656. s->sock_timeout = _PyTime_FromSeconds(block ? -1 : 0);
  2657. if (internal_setblocking(s, block) == -1) {
  2658. return NULL;
  2659. }
  2660. Py_RETURN_NONE;
  2661. }
  2662. PyDoc_STRVAR(setblocking_doc,
  2663. "setblocking(flag)\n\
  2664. \n\
  2665. Set the socket to blocking (flag is true) or non-blocking (false).\n\
  2666. setblocking(True) is equivalent to settimeout(None);\n\
  2667. setblocking(False) is equivalent to settimeout(0.0).");
  2668. /* s.getblocking() method.
  2669. Returns True if socket is in blocking mode,
  2670. False if it is in non-blocking mode.
  2671. */
  2672. static PyObject *
  2673. sock_getblocking(PySocketSockObject *s, PyObject *Py_UNUSED(ignored))
  2674. {
  2675. if (s->sock_timeout) {
  2676. Py_RETURN_TRUE;
  2677. }
  2678. else {
  2679. Py_RETURN_FALSE;
  2680. }
  2681. }
  2682. PyDoc_STRVAR(getblocking_doc,
  2683. "getblocking()\n\
  2684. \n\
  2685. Returns True if socket is in blocking mode, or False if it\n\
  2686. is in non-blocking mode.");
  2687. static int
  2688. socket_parse_timeout(_PyTime_t *timeout, PyObject *timeout_obj)
  2689. {
  2690. #ifdef MS_WINDOWS
  2691. struct timeval tv;
  2692. #endif
  2693. #ifndef HAVE_POLL
  2694. _PyTime_t ms;
  2695. #endif
  2696. int overflow = 0;
  2697. if (timeout_obj == Py_None) {
  2698. *timeout = _PyTime_FromSeconds(-1);
  2699. return 0;
  2700. }
  2701. if (_PyTime_FromSecondsObject(timeout,
  2702. timeout_obj, _PyTime_ROUND_TIMEOUT) < 0)
  2703. return -1;
  2704. if (*timeout < 0) {
  2705. PyErr_SetString(PyExc_ValueError, "Timeout value out of range");
  2706. return -1;
  2707. }
  2708. #ifdef MS_WINDOWS
  2709. overflow |= (_PyTime_AsTimeval(*timeout, &tv, _PyTime_ROUND_TIMEOUT) < 0);
  2710. #endif
  2711. #ifndef HAVE_POLL
  2712. ms = _PyTime_AsMilliseconds(*timeout, _PyTime_ROUND_TIMEOUT);
  2713. overflow |= (ms > INT_MAX);
  2714. #endif
  2715. if (overflow) {
  2716. PyErr_SetString(PyExc_OverflowError,
  2717. "timeout doesn't fit into C timeval");
  2718. return -1;
  2719. }
  2720. return 0;
  2721. }
  2722. /* s.settimeout(timeout) method. Argument:
  2723. None -- no timeout, blocking mode; same as setblocking(True)
  2724. 0.0 -- non-blocking mode; same as setblocking(False)
  2725. > 0 -- timeout mode; operations time out after timeout seconds
  2726. < 0 -- illegal; raises an exception
  2727. */
  2728. static PyObject *
  2729. sock_settimeout(PySocketSockObject *s, PyObject *arg)
  2730. {
  2731. _PyTime_t timeout;
  2732. if (socket_parse_timeout(&timeout, arg) < 0)
  2733. return NULL;
  2734. s->sock_timeout = timeout;
  2735. int block = timeout < 0;
  2736. /* Blocking mode for a Python socket object means that operations
  2737. like :meth:`recv` or :meth:`sendall` will block the execution of
  2738. the current thread until they are complete or aborted with a
  2739. `TimeoutError` or `socket.error` errors. When timeout is `None`,
  2740. the underlying FD is in a blocking mode. When timeout is a positive
  2741. number, the FD is in a non-blocking mode, and socket ops are
  2742. implemented with a `select()` call.
  2743. When timeout is 0.0, the FD is in a non-blocking mode.
  2744. This table summarizes all states in which the socket object and
  2745. its underlying FD can be:
  2746. ==================== ===================== ==============
  2747. `gettimeout()` `getblocking()` FD
  2748. ==================== ===================== ==============
  2749. ``None`` ``True`` blocking
  2750. ``0.0`` ``False`` non-blocking
  2751. ``> 0`` ``True`` non-blocking
  2752. */
  2753. if (internal_setblocking(s, block) == -1) {
  2754. return NULL;
  2755. }
  2756. Py_RETURN_NONE;
  2757. }
  2758. PyDoc_STRVAR(settimeout_doc,
  2759. "settimeout(timeout)\n\
  2760. \n\
  2761. Set a timeout on socket operations. 'timeout' can be a float,\n\
  2762. giving in seconds, or None. Setting a timeout of None disables\n\
  2763. the timeout feature and is equivalent to setblocking(1).\n\
  2764. Setting a timeout of zero is the same as setblocking(0).");
  2765. /* s.gettimeout() method.
  2766. Returns the timeout associated with a socket. */
  2767. static PyObject *
  2768. sock_gettimeout(PySocketSockObject *s, PyObject *Py_UNUSED(ignored))
  2769. {
  2770. if (s->sock_timeout < 0) {
  2771. Py_RETURN_NONE;
  2772. }
  2773. else {
  2774. double seconds = _PyTime_AsSecondsDouble(s->sock_timeout);
  2775. return PyFloat_FromDouble(seconds);
  2776. }
  2777. }
  2778. PyDoc_STRVAR(gettimeout_doc,
  2779. "gettimeout() -> timeout\n\
  2780. \n\
  2781. Returns the timeout in seconds (float) associated with socket\n\
  2782. operations. A timeout of None indicates that timeouts on socket\n\
  2783. operations are disabled.");
  2784. #ifdef HAVE_SETSOCKOPT
  2785. /* s.setsockopt() method.
  2786. With an integer third argument, sets an integer optval with optlen=4.
  2787. With None as third argument and an integer fourth argument, set
  2788. optval=NULL with unsigned int as optlen.
  2789. With a string third argument, sets an option from a buffer;
  2790. use optional built-in module 'struct' to encode the string.
  2791. */
  2792. static PyObject *
  2793. sock_setsockopt(PySocketSockObject *s, PyObject *args)
  2794. {
  2795. int level;
  2796. int optname;
  2797. int res;
  2798. Py_buffer optval;
  2799. int flag;
  2800. unsigned int optlen;
  2801. PyObject *none;
  2802. #ifdef AF_VSOCK
  2803. if (s->sock_family == AF_VSOCK) {
  2804. uint64_t vflag; // Must be set width of 64 bits
  2805. /* setsockopt(level, opt, flag) */
  2806. if (PyArg_ParseTuple(args, "iiK:setsockopt",
  2807. &level, &optname, &vflag)) {
  2808. // level should always be set to AF_VSOCK
  2809. res = setsockopt(s->sock_fd, level, optname,
  2810. (void*)&vflag, sizeof vflag);
  2811. goto done;
  2812. }
  2813. return NULL;
  2814. }
  2815. #endif
  2816. /* setsockopt(level, opt, flag) */
  2817. if (PyArg_ParseTuple(args, "iii:setsockopt",
  2818. &level, &optname, &flag)) {
  2819. res = setsockopt(s->sock_fd, level, optname,
  2820. (char*)&flag, sizeof flag);
  2821. goto done;
  2822. }
  2823. PyErr_Clear();
  2824. /* setsockopt(level, opt, None, flag) */
  2825. if (PyArg_ParseTuple(args, "iiO!I:setsockopt",
  2826. &level, &optname, Py_TYPE(Py_None), &none, &optlen)) {
  2827. assert(sizeof(socklen_t) >= sizeof(unsigned int));
  2828. res = setsockopt(s->sock_fd, level, optname,
  2829. NULL, (socklen_t)optlen);
  2830. goto done;
  2831. }
  2832. PyErr_Clear();
  2833. /* setsockopt(level, opt, buffer) */
  2834. if (!PyArg_ParseTuple(args, "iiy*:setsockopt",
  2835. &level, &optname, &optval))
  2836. return NULL;
  2837. #ifdef MS_WINDOWS
  2838. if (optval.len > INT_MAX) {
  2839. PyBuffer_Release(&optval);
  2840. PyErr_Format(PyExc_OverflowError,
  2841. "socket option is larger than %i bytes",
  2842. INT_MAX);
  2843. return NULL;
  2844. }
  2845. res = setsockopt(s->sock_fd, level, optname,
  2846. optval.buf, (int)optval.len);
  2847. #else
  2848. res = setsockopt(s->sock_fd, level, optname, optval.buf, optval.len);
  2849. #endif
  2850. PyBuffer_Release(&optval);
  2851. done:
  2852. if (res < 0) {
  2853. return s->errorhandler();
  2854. }
  2855. Py_RETURN_NONE;
  2856. }
  2857. PyDoc_STRVAR(setsockopt_doc,
  2858. "setsockopt(level, option, value: int)\n\
  2859. setsockopt(level, option, value: buffer)\n\
  2860. setsockopt(level, option, None, optlen: int)\n\
  2861. \n\
  2862. Set a socket option. See the Unix manual for level and option.\n\
  2863. The value argument can either be an integer, a string buffer, or\n\
  2864. None, optlen.");
  2865. #endif
  2866. /* s.getsockopt() method.
  2867. With two arguments, retrieves an integer option.
  2868. With a third integer argument, retrieves a string buffer of that size;
  2869. use optional built-in module 'struct' to decode the string. */
  2870. static PyObject *
  2871. sock_getsockopt(PySocketSockObject *s, PyObject *args)
  2872. {
  2873. int level;
  2874. int optname;
  2875. int res;
  2876. PyObject *buf;
  2877. socklen_t buflen = 0;
  2878. int flag = 0;
  2879. socklen_t flagsize;
  2880. if (!PyArg_ParseTuple(args, "ii|i:getsockopt",
  2881. &level, &optname, &buflen))
  2882. return NULL;
  2883. if (buflen == 0) {
  2884. #ifdef AF_VSOCK
  2885. if (s->sock_family == AF_VSOCK) {
  2886. uint64_t vflag = 0; // Must be set width of 64 bits
  2887. flagsize = sizeof vflag;
  2888. res = getsockopt(s->sock_fd, level, optname,
  2889. (void *)&vflag, &flagsize);
  2890. if (res < 0)
  2891. return s->errorhandler();
  2892. return PyLong_FromUnsignedLong(vflag);
  2893. }
  2894. #endif
  2895. flagsize = sizeof flag;
  2896. res = getsockopt(s->sock_fd, level, optname,
  2897. (void *)&flag, &flagsize);
  2898. if (res < 0)
  2899. return s->errorhandler();
  2900. return PyLong_FromLong(flag);
  2901. }
  2902. #ifdef AF_VSOCK
  2903. if (s->sock_family == AF_VSOCK) {
  2904. PyErr_SetString(PyExc_OSError,
  2905. "getsockopt string buffer not allowed");
  2906. return NULL;
  2907. }
  2908. #endif
  2909. if (buflen <= 0 || buflen > 1024) {
  2910. PyErr_SetString(PyExc_OSError,
  2911. "getsockopt buflen out of range");
  2912. return NULL;
  2913. }
  2914. buf = PyBytes_FromStringAndSize((char *)NULL, buflen);
  2915. if (buf == NULL)
  2916. return NULL;
  2917. res = getsockopt(s->sock_fd, level, optname,
  2918. (void *)PyBytes_AS_STRING(buf), &buflen);
  2919. if (res < 0) {
  2920. Py_DECREF(buf);
  2921. return s->errorhandler();
  2922. }
  2923. _PyBytes_Resize(&buf, buflen);
  2924. return buf;
  2925. }
  2926. PyDoc_STRVAR(getsockopt_doc,
  2927. "getsockopt(level, option[, buffersize]) -> value\n\
  2928. \n\
  2929. Get a socket option. See the Unix manual for level and option.\n\
  2930. If a nonzero buffersize argument is given, the return value is a\n\
  2931. string of that length; otherwise it is an integer.");
  2932. #ifdef HAVE_BIND
  2933. /* s.bind(sockaddr) method */
  2934. static PyObject *
  2935. sock_bind(PySocketSockObject *s, PyObject *addro)
  2936. {
  2937. sock_addr_t addrbuf;
  2938. int addrlen;
  2939. int res;
  2940. if (!getsockaddrarg(s, addro, &addrbuf, &addrlen, "bind")) {
  2941. return NULL;
  2942. }
  2943. if (PySys_Audit("socket.bind", "OO", s, addro) < 0) {
  2944. return NULL;
  2945. }
  2946. Py_BEGIN_ALLOW_THREADS
  2947. res = bind(s->sock_fd, SAS2SA(&addrbuf), addrlen);
  2948. Py_END_ALLOW_THREADS
  2949. if (res < 0)
  2950. return s->errorhandler();
  2951. Py_RETURN_NONE;
  2952. }
  2953. PyDoc_STRVAR(bind_doc,
  2954. "bind(address)\n\
  2955. \n\
  2956. Bind the socket to a local address. For IP sockets, the address is a\n\
  2957. pair (host, port); the host must refer to the local host. For raw packet\n\
  2958. sockets the address is a tuple (ifname, proto [,pkttype [,hatype [,addr]]])");
  2959. #endif
  2960. /* s.close() method.
  2961. Set the file descriptor to -1 so operations tried subsequently
  2962. will surely fail. */
  2963. static PyObject *
  2964. sock_close(PySocketSockObject *s, PyObject *Py_UNUSED(ignored))
  2965. {
  2966. SOCKET_T fd;
  2967. int res;
  2968. fd = s->sock_fd;
  2969. if (fd != INVALID_SOCKET) {
  2970. s->sock_fd = INVALID_SOCKET;
  2971. /* We do not want to retry upon EINTR: see
  2972. http://lwn.net/Articles/576478/ and
  2973. http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
  2974. for more details. */
  2975. Py_BEGIN_ALLOW_THREADS
  2976. res = SOCKETCLOSE(fd);
  2977. Py_END_ALLOW_THREADS
  2978. /* bpo-30319: The peer can already have closed the connection.
  2979. Python ignores ECONNRESET on close(). */
  2980. if (res < 0 && errno != ECONNRESET) {
  2981. return s->errorhandler();
  2982. }
  2983. }
  2984. Py_RETURN_NONE;
  2985. }
  2986. PyDoc_STRVAR(sock_close_doc,
  2987. "close()\n\
  2988. \n\
  2989. Close the socket. It cannot be used after this call.");
  2990. static PyObject *
  2991. sock_detach(PySocketSockObject *s, PyObject *Py_UNUSED(ignored))
  2992. {
  2993. SOCKET_T fd = s->sock_fd;
  2994. s->sock_fd = INVALID_SOCKET;
  2995. return PyLong_FromSocket_t(fd);
  2996. }
  2997. PyDoc_STRVAR(detach_doc,
  2998. "detach()\n\
  2999. \n\
  3000. Close the socket object without closing the underlying file descriptor.\n\
  3001. The object cannot be used after this call, but the file descriptor\n\
  3002. can be reused for other purposes. The file descriptor is returned.");
  3003. #ifdef HAVE_CONNECT
  3004. static int
  3005. sock_connect_impl(PySocketSockObject *s, void* Py_UNUSED(data))
  3006. {
  3007. int err;
  3008. socklen_t size = sizeof err;
  3009. if (getsockopt(s->sock_fd, SOL_SOCKET, SO_ERROR, (void *)&err, &size)) {
  3010. /* getsockopt() failed */
  3011. return 0;
  3012. }
  3013. if (err == EISCONN)
  3014. return 1;
  3015. if (err != 0) {
  3016. /* sock_call_ex() uses GET_SOCK_ERROR() to get the error code */
  3017. SET_SOCK_ERROR(err);
  3018. return 0;
  3019. }
  3020. return 1;
  3021. }
  3022. static int
  3023. internal_connect(PySocketSockObject *s, struct sockaddr *addr, int addrlen,
  3024. int raise)
  3025. {
  3026. int res, err, wait_connect;
  3027. Py_BEGIN_ALLOW_THREADS
  3028. res = connect(s->sock_fd, addr, addrlen);
  3029. Py_END_ALLOW_THREADS
  3030. if (!res) {
  3031. /* connect() succeeded, the socket is connected */
  3032. return 0;
  3033. }
  3034. /* connect() failed */
  3035. /* save error, PyErr_CheckSignals() can replace it */
  3036. err = GET_SOCK_ERROR;
  3037. if (CHECK_ERRNO(EINTR)) {
  3038. if (PyErr_CheckSignals())
  3039. return -1;
  3040. /* Issue #23618: when connect() fails with EINTR, the connection is
  3041. running asynchronously.
  3042. If the socket is blocking or has a timeout, wait until the
  3043. connection completes, fails or timed out using select(), and then
  3044. get the connection status using getsockopt(SO_ERROR).
  3045. If the socket is non-blocking, raise InterruptedError. The caller is
  3046. responsible to wait until the connection completes, fails or timed
  3047. out (it's the case in asyncio for example). */
  3048. wait_connect = (s->sock_timeout != 0 && IS_SELECTABLE(s));
  3049. }
  3050. else {
  3051. wait_connect = (s->sock_timeout > 0 && err == SOCK_INPROGRESS_ERR
  3052. && IS_SELECTABLE(s));
  3053. }
  3054. if (!wait_connect) {
  3055. if (raise) {
  3056. /* restore error, maybe replaced by PyErr_CheckSignals() */
  3057. SET_SOCK_ERROR(err);
  3058. s->errorhandler();
  3059. return -1;
  3060. }
  3061. else
  3062. return err;
  3063. }
  3064. if (raise) {
  3065. /* socket.connect() raises an exception on error */
  3066. if (sock_call_ex(s, 1, sock_connect_impl, NULL,
  3067. 1, NULL, s->sock_timeout) < 0)
  3068. return -1;
  3069. }
  3070. else {
  3071. /* socket.connect_ex() returns the error code on error */
  3072. if (sock_call_ex(s, 1, sock_connect_impl, NULL,
  3073. 1, &err, s->sock_timeout) < 0)
  3074. return err;
  3075. }
  3076. return 0;
  3077. }
  3078. /* s.connect(sockaddr) method */
  3079. static PyObject *
  3080. sock_connect(PySocketSockObject *s, PyObject *addro)
  3081. {
  3082. sock_addr_t addrbuf;
  3083. int addrlen;
  3084. int res;
  3085. if (!getsockaddrarg(s, addro, &addrbuf, &addrlen, "connect")) {
  3086. return NULL;
  3087. }
  3088. if (PySys_Audit("socket.connect", "OO", s, addro) < 0) {
  3089. return NULL;
  3090. }
  3091. res = internal_connect(s, SAS2SA(&addrbuf), addrlen, 1);
  3092. if (res < 0)
  3093. return NULL;
  3094. Py_RETURN_NONE;
  3095. }
  3096. PyDoc_STRVAR(connect_doc,
  3097. "connect(address)\n\
  3098. \n\
  3099. Connect the socket to a remote address. For IP sockets, the address\n\
  3100. is a pair (host, port).");
  3101. /* s.connect_ex(sockaddr) method */
  3102. static PyObject *
  3103. sock_connect_ex(PySocketSockObject *s, PyObject *addro)
  3104. {
  3105. sock_addr_t addrbuf;
  3106. int addrlen;
  3107. int res;
  3108. if (!getsockaddrarg(s, addro, &addrbuf, &addrlen, "connect_ex")) {
  3109. return NULL;
  3110. }
  3111. if (PySys_Audit("socket.connect", "OO", s, addro) < 0) {
  3112. return NULL;
  3113. }
  3114. res = internal_connect(s, SAS2SA(&addrbuf), addrlen, 0);
  3115. if (res < 0)
  3116. return NULL;
  3117. return PyLong_FromLong((long) res);
  3118. }
  3119. PyDoc_STRVAR(connect_ex_doc,
  3120. "connect_ex(address) -> errno\n\
  3121. \n\
  3122. This is like connect(address), but returns an error code (the errno value)\n\
  3123. instead of raising an exception when an error occurs.");
  3124. #endif // HAVE_CONNECT
  3125. /* s.fileno() method */
  3126. static PyObject *
  3127. sock_fileno(PySocketSockObject *s, PyObject *Py_UNUSED(ignored))
  3128. {
  3129. return PyLong_FromSocket_t(s->sock_fd);
  3130. }
  3131. PyDoc_STRVAR(fileno_doc,
  3132. "fileno() -> integer\n\
  3133. \n\
  3134. Return the integer file descriptor of the socket.");
  3135. #ifdef HAVE_GETSOCKNAME
  3136. /* s.getsockname() method */
  3137. static PyObject *
  3138. sock_getsockname(PySocketSockObject *s, PyObject *Py_UNUSED(ignored))
  3139. {
  3140. sock_addr_t addrbuf;
  3141. int res;
  3142. socklen_t addrlen;
  3143. if (!getsockaddrlen(s, &addrlen))
  3144. return NULL;
  3145. memset(&addrbuf, 0, addrlen);
  3146. Py_BEGIN_ALLOW_THREADS
  3147. res = getsockname(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
  3148. Py_END_ALLOW_THREADS
  3149. if (res < 0)
  3150. return s->errorhandler();
  3151. return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
  3152. s->sock_proto);
  3153. }
  3154. PyDoc_STRVAR(getsockname_doc,
  3155. "getsockname() -> address info\n\
  3156. \n\
  3157. Return the address of the local endpoint. The format depends on the\n\
  3158. address family. For IPv4 sockets, the address info is a pair\n\
  3159. (hostaddr, port). For IPv6 sockets, the address info is a 4-tuple\n\
  3160. (hostaddr, port, flowinfo, scope_id).");
  3161. #endif
  3162. #ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */
  3163. /* s.getpeername() method */
  3164. static PyObject *
  3165. sock_getpeername(PySocketSockObject *s, PyObject *Py_UNUSED(ignored))
  3166. {
  3167. sock_addr_t addrbuf;
  3168. int res;
  3169. socklen_t addrlen;
  3170. if (!getsockaddrlen(s, &addrlen))
  3171. return NULL;
  3172. memset(&addrbuf, 0, addrlen);
  3173. Py_BEGIN_ALLOW_THREADS
  3174. res = getpeername(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
  3175. Py_END_ALLOW_THREADS
  3176. if (res < 0)
  3177. return s->errorhandler();
  3178. return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
  3179. s->sock_proto);
  3180. }
  3181. PyDoc_STRVAR(getpeername_doc,
  3182. "getpeername() -> address info\n\
  3183. \n\
  3184. Return the address of the remote endpoint. For IP sockets, the address\n\
  3185. info is a pair (hostaddr, port).");
  3186. #endif /* HAVE_GETPEERNAME */
  3187. #ifdef HAVE_LISTEN
  3188. /* s.listen(n) method */
  3189. static PyObject *
  3190. sock_listen(PySocketSockObject *s, PyObject *args)
  3191. {
  3192. /* We try to choose a default backlog high enough to avoid connection drops
  3193. * for common workloads, yet not too high to limit resource usage. */
  3194. int backlog = Py_MIN(SOMAXCONN, 128);
  3195. int res;
  3196. if (!PyArg_ParseTuple(args, "|i:listen", &backlog))
  3197. return NULL;
  3198. Py_BEGIN_ALLOW_THREADS
  3199. /* To avoid problems on systems that don't allow a negative backlog
  3200. * (which doesn't make sense anyway) we force a minimum value of 0. */
  3201. if (backlog < 0)
  3202. backlog = 0;
  3203. res = listen(s->sock_fd, backlog);
  3204. Py_END_ALLOW_THREADS
  3205. if (res < 0)
  3206. return s->errorhandler();
  3207. Py_RETURN_NONE;
  3208. }
  3209. PyDoc_STRVAR(listen_doc,
  3210. "listen([backlog])\n\
  3211. \n\
  3212. Enable a server to accept connections. If backlog is specified, it must be\n\
  3213. at least 0 (if it is lower, it is set to 0); it specifies the number of\n\
  3214. unaccepted connections that the system will allow before refusing new\n\
  3215. connections. If not specified, a default reasonable value is chosen.");
  3216. #endif
  3217. struct sock_recv {
  3218. char *cbuf;
  3219. Py_ssize_t len;
  3220. int flags;
  3221. Py_ssize_t result;
  3222. };
  3223. static int
  3224. sock_recv_impl(PySocketSockObject *s, void *data)
  3225. {
  3226. struct sock_recv *ctx = data;
  3227. #ifdef MS_WINDOWS
  3228. if (ctx->len > INT_MAX)
  3229. ctx->len = INT_MAX;
  3230. ctx->result = recv(s->sock_fd, ctx->cbuf, (int)ctx->len, ctx->flags);
  3231. #else
  3232. ctx->result = recv(s->sock_fd, ctx->cbuf, ctx->len, ctx->flags);
  3233. #endif
  3234. return (ctx->result >= 0);
  3235. }
  3236. /*
  3237. * This is the guts of the recv() and recv_into() methods, which reads into a
  3238. * char buffer. If you have any inc/dec ref to do to the objects that contain
  3239. * the buffer, do it in the caller. This function returns the number of bytes
  3240. * successfully read. If there was an error, it returns -1. Note that it is
  3241. * also possible that we return a number of bytes smaller than the request
  3242. * bytes.
  3243. */
  3244. static Py_ssize_t
  3245. sock_recv_guts(PySocketSockObject *s, char* cbuf, Py_ssize_t len, int flags)
  3246. {
  3247. struct sock_recv ctx;
  3248. if (!IS_SELECTABLE(s)) {
  3249. select_error();
  3250. return -1;
  3251. }
  3252. if (len == 0) {
  3253. /* If 0 bytes were requested, do nothing. */
  3254. return 0;
  3255. }
  3256. ctx.cbuf = cbuf;
  3257. ctx.len = len;
  3258. ctx.flags = flags;
  3259. if (sock_call(s, 0, sock_recv_impl, &ctx) < 0)
  3260. return -1;
  3261. return ctx.result;
  3262. }
  3263. /* s.recv(nbytes [,flags]) method */
  3264. static PyObject *
  3265. sock_recv(PySocketSockObject *s, PyObject *args)
  3266. {
  3267. Py_ssize_t recvlen, outlen;
  3268. int flags = 0;
  3269. PyObject *buf;
  3270. if (!PyArg_ParseTuple(args, "n|i:recv", &recvlen, &flags))
  3271. return NULL;
  3272. if (recvlen < 0) {
  3273. PyErr_SetString(PyExc_ValueError,
  3274. "negative buffersize in recv");
  3275. return NULL;
  3276. }
  3277. /* Allocate a new string. */
  3278. buf = PyBytes_FromStringAndSize((char *) 0, recvlen);
  3279. if (buf == NULL)
  3280. return NULL;
  3281. /* Call the guts */
  3282. outlen = sock_recv_guts(s, PyBytes_AS_STRING(buf), recvlen, flags);
  3283. if (outlen < 0) {
  3284. /* An error occurred, release the string and return an
  3285. error. */
  3286. Py_DECREF(buf);
  3287. return NULL;
  3288. }
  3289. if (outlen != recvlen) {
  3290. /* We did not read as many bytes as we anticipated, resize the
  3291. string if possible and be successful. */
  3292. _PyBytes_Resize(&buf, outlen);
  3293. }
  3294. return buf;
  3295. }
  3296. PyDoc_STRVAR(recv_doc,
  3297. "recv(buffersize[, flags]) -> data\n\
  3298. \n\
  3299. Receive up to buffersize bytes from the socket. For the optional flags\n\
  3300. argument, see the Unix manual. When no data is available, block until\n\
  3301. at least one byte is available or until the remote end is closed. When\n\
  3302. the remote end is closed and all data is read, return the empty string.");
  3303. /* s.recv_into(buffer, [nbytes [,flags]]) method */
  3304. static PyObject*
  3305. sock_recv_into(PySocketSockObject *s, PyObject *args, PyObject *kwds)
  3306. {
  3307. static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
  3308. int flags = 0;
  3309. Py_buffer pbuf;
  3310. char *buf;
  3311. Py_ssize_t buflen, readlen, recvlen = 0;
  3312. /* Get the buffer's memory */
  3313. if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ni:recv_into", kwlist,
  3314. &pbuf, &recvlen, &flags))
  3315. return NULL;
  3316. buf = pbuf.buf;
  3317. buflen = pbuf.len;
  3318. if (recvlen < 0) {
  3319. PyBuffer_Release(&pbuf);
  3320. PyErr_SetString(PyExc_ValueError,
  3321. "negative buffersize in recv_into");
  3322. return NULL;
  3323. }
  3324. if (recvlen == 0) {
  3325. /* If nbytes was not specified, use the buffer's length */
  3326. recvlen = buflen;
  3327. }
  3328. /* Check if the buffer is large enough */
  3329. if (buflen < recvlen) {
  3330. PyBuffer_Release(&pbuf);
  3331. PyErr_SetString(PyExc_ValueError,
  3332. "buffer too small for requested bytes");
  3333. return NULL;
  3334. }
  3335. /* Call the guts */
  3336. readlen = sock_recv_guts(s, buf, recvlen, flags);
  3337. if (readlen < 0) {
  3338. /* Return an error. */
  3339. PyBuffer_Release(&pbuf);
  3340. return NULL;
  3341. }
  3342. PyBuffer_Release(&pbuf);
  3343. /* Return the number of bytes read. Note that we do not do anything
  3344. special here in the case that readlen < recvlen. */
  3345. return PyLong_FromSsize_t(readlen);
  3346. }
  3347. PyDoc_STRVAR(recv_into_doc,
  3348. "recv_into(buffer, [nbytes[, flags]]) -> nbytes_read\n\
  3349. \n\
  3350. A version of recv() that stores its data into a buffer rather than creating\n\
  3351. a new string. Receive up to buffersize bytes from the socket. If buffersize\n\
  3352. is not specified (or 0), receive up to the size available in the given buffer.\n\
  3353. \n\
  3354. See recv() for documentation about the flags.");
  3355. struct sock_recvfrom {
  3356. char* cbuf;
  3357. Py_ssize_t len;
  3358. int flags;
  3359. socklen_t *addrlen;
  3360. sock_addr_t *addrbuf;
  3361. Py_ssize_t result;
  3362. };
  3363. #ifdef HAVE_RECVFROM
  3364. static int
  3365. sock_recvfrom_impl(PySocketSockObject *s, void *data)
  3366. {
  3367. struct sock_recvfrom *ctx = data;
  3368. memset(ctx->addrbuf, 0, *ctx->addrlen);
  3369. #ifdef MS_WINDOWS
  3370. if (ctx->len > INT_MAX)
  3371. ctx->len = INT_MAX;
  3372. ctx->result = recvfrom(s->sock_fd, ctx->cbuf, (int)ctx->len, ctx->flags,
  3373. SAS2SA(ctx->addrbuf), ctx->addrlen);
  3374. #else
  3375. ctx->result = recvfrom(s->sock_fd, ctx->cbuf, ctx->len, ctx->flags,
  3376. SAS2SA(ctx->addrbuf), ctx->addrlen);
  3377. #endif
  3378. return (ctx->result >= 0);
  3379. }
  3380. /*
  3381. * This is the guts of the recvfrom() and recvfrom_into() methods, which reads
  3382. * into a char buffer. If you have any inc/def ref to do to the objects that
  3383. * contain the buffer, do it in the caller. This function returns the number
  3384. * of bytes successfully read. If there was an error, it returns -1. Note
  3385. * that it is also possible that we return a number of bytes smaller than the
  3386. * request bytes.
  3387. *
  3388. * 'addr' is a return value for the address object. Note that you must decref
  3389. * it yourself.
  3390. */
  3391. static Py_ssize_t
  3392. sock_recvfrom_guts(PySocketSockObject *s, char* cbuf, Py_ssize_t len, int flags,
  3393. PyObject** addr)
  3394. {
  3395. sock_addr_t addrbuf;
  3396. socklen_t addrlen;
  3397. struct sock_recvfrom ctx;
  3398. *addr = NULL;
  3399. if (!getsockaddrlen(s, &addrlen))
  3400. return -1;
  3401. if (!IS_SELECTABLE(s)) {
  3402. select_error();
  3403. return -1;
  3404. }
  3405. ctx.cbuf = cbuf;
  3406. ctx.len = len;
  3407. ctx.flags = flags;
  3408. ctx.addrbuf = &addrbuf;
  3409. ctx.addrlen = &addrlen;
  3410. if (sock_call(s, 0, sock_recvfrom_impl, &ctx) < 0)
  3411. return -1;
  3412. *addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
  3413. s->sock_proto);
  3414. if (*addr == NULL)
  3415. return -1;
  3416. return ctx.result;
  3417. }
  3418. /* s.recvfrom(nbytes [,flags]) method */
  3419. static PyObject *
  3420. sock_recvfrom(PySocketSockObject *s, PyObject *args)
  3421. {
  3422. PyObject *buf = NULL;
  3423. PyObject *addr = NULL;
  3424. PyObject *ret = NULL;
  3425. int flags = 0;
  3426. Py_ssize_t recvlen, outlen;
  3427. if (!PyArg_ParseTuple(args, "n|i:recvfrom", &recvlen, &flags))
  3428. return NULL;
  3429. if (recvlen < 0) {
  3430. PyErr_SetString(PyExc_ValueError,
  3431. "negative buffersize in recvfrom");
  3432. return NULL;
  3433. }
  3434. buf = PyBytes_FromStringAndSize((char *) 0, recvlen);
  3435. if (buf == NULL)
  3436. return NULL;
  3437. outlen = sock_recvfrom_guts(s, PyBytes_AS_STRING(buf),
  3438. recvlen, flags, &addr);
  3439. if (outlen < 0) {
  3440. goto finally;
  3441. }
  3442. if (outlen != recvlen) {
  3443. /* We did not read as many bytes as we anticipated, resize the
  3444. string if possible and be successful. */
  3445. if (_PyBytes_Resize(&buf, outlen) < 0)
  3446. /* Oopsy, not so successful after all. */
  3447. goto finally;
  3448. }
  3449. ret = PyTuple_Pack(2, buf, addr);
  3450. finally:
  3451. Py_XDECREF(buf);
  3452. Py_XDECREF(addr);
  3453. return ret;
  3454. }
  3455. PyDoc_STRVAR(recvfrom_doc,
  3456. "recvfrom(buffersize[, flags]) -> (data, address info)\n\
  3457. \n\
  3458. Like recv(buffersize, flags) but also return the sender's address info.");
  3459. /* s.recvfrom_into(buffer[, nbytes [,flags]]) method */
  3460. static PyObject *
  3461. sock_recvfrom_into(PySocketSockObject *s, PyObject *args, PyObject* kwds)
  3462. {
  3463. static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
  3464. int flags = 0;
  3465. Py_buffer pbuf;
  3466. char *buf;
  3467. Py_ssize_t readlen, buflen, recvlen = 0;
  3468. PyObject *addr = NULL;
  3469. if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ni:recvfrom_into",
  3470. kwlist, &pbuf,
  3471. &recvlen, &flags))
  3472. return NULL;
  3473. buf = pbuf.buf;
  3474. buflen = pbuf.len;
  3475. if (recvlen < 0) {
  3476. PyBuffer_Release(&pbuf);
  3477. PyErr_SetString(PyExc_ValueError,
  3478. "negative buffersize in recvfrom_into");
  3479. return NULL;
  3480. }
  3481. if (recvlen == 0) {
  3482. /* If nbytes was not specified, use the buffer's length */
  3483. recvlen = buflen;
  3484. } else if (recvlen > buflen) {
  3485. PyBuffer_Release(&pbuf);
  3486. PyErr_SetString(PyExc_ValueError,
  3487. "nbytes is greater than the length of the buffer");
  3488. return NULL;
  3489. }
  3490. readlen = sock_recvfrom_guts(s, buf, recvlen, flags, &addr);
  3491. if (readlen < 0) {
  3492. PyBuffer_Release(&pbuf);
  3493. /* Return an error */
  3494. Py_XDECREF(addr);
  3495. return NULL;
  3496. }
  3497. PyBuffer_Release(&pbuf);
  3498. /* Return the number of bytes read and the address. Note that we do
  3499. not do anything special here in the case that readlen < recvlen. */
  3500. return Py_BuildValue("nN", readlen, addr);
  3501. }
  3502. PyDoc_STRVAR(recvfrom_into_doc,
  3503. "recvfrom_into(buffer[, nbytes[, flags]]) -> (nbytes, address info)\n\
  3504. \n\
  3505. Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address info.");
  3506. #endif
  3507. /* The sendmsg() and recvmsg[_into]() methods require a working
  3508. CMSG_LEN(). See the comment near get_CMSG_LEN(). */
  3509. #ifdef CMSG_LEN
  3510. struct sock_recvmsg {
  3511. struct msghdr *msg;
  3512. int flags;
  3513. ssize_t result;
  3514. };
  3515. static int
  3516. sock_recvmsg_impl(PySocketSockObject *s, void *data)
  3517. {
  3518. struct sock_recvmsg *ctx = data;
  3519. ctx->result = recvmsg(s->sock_fd, ctx->msg, ctx->flags);
  3520. return (ctx->result >= 0);
  3521. }
  3522. /*
  3523. * Call recvmsg() with the supplied iovec structures, flags, and
  3524. * ancillary data buffer size (controllen). Returns the tuple return
  3525. * value for recvmsg() or recvmsg_into(), with the first item provided
  3526. * by the supplied makeval() function. makeval() will be called with
  3527. * the length read and makeval_data as arguments, and must return a
  3528. * new reference (which will be decrefed if there is a subsequent
  3529. * error). On error, closes any file descriptors received via
  3530. * SCM_RIGHTS.
  3531. */
  3532. static PyObject *
  3533. sock_recvmsg_guts(PySocketSockObject *s, struct iovec *iov, int iovlen,
  3534. int flags, Py_ssize_t controllen,
  3535. PyObject *(*makeval)(ssize_t, void *), void *makeval_data)
  3536. {
  3537. sock_addr_t addrbuf;
  3538. socklen_t addrbuflen;
  3539. struct msghdr msg = {0};
  3540. PyObject *cmsg_list = NULL, *retval = NULL;
  3541. void *controlbuf = NULL;
  3542. struct cmsghdr *cmsgh;
  3543. size_t cmsgdatalen = 0;
  3544. int cmsg_status;
  3545. struct sock_recvmsg ctx;
  3546. /* XXX: POSIX says that msg_name and msg_namelen "shall be
  3547. ignored" when the socket is connected (Linux fills them in
  3548. anyway for AF_UNIX sockets at least). Normally msg_namelen
  3549. seems to be set to 0 if there's no address, but try to
  3550. initialize msg_name to something that won't be mistaken for a
  3551. real address if that doesn't happen. */
  3552. if (!getsockaddrlen(s, &addrbuflen))
  3553. return NULL;
  3554. memset(&addrbuf, 0, addrbuflen);
  3555. SAS2SA(&addrbuf)->sa_family = AF_UNSPEC;
  3556. if (controllen < 0 || controllen > SOCKLEN_T_LIMIT) {
  3557. PyErr_SetString(PyExc_ValueError,
  3558. "invalid ancillary data buffer length");
  3559. return NULL;
  3560. }
  3561. if (controllen > 0 && (controlbuf = PyMem_Malloc(controllen)) == NULL)
  3562. return PyErr_NoMemory();
  3563. /* Make the system call. */
  3564. if (!IS_SELECTABLE(s)) {
  3565. select_error();
  3566. goto finally;
  3567. }
  3568. msg.msg_name = SAS2SA(&addrbuf);
  3569. msg.msg_namelen = addrbuflen;
  3570. msg.msg_iov = iov;
  3571. msg.msg_iovlen = iovlen;
  3572. msg.msg_control = controlbuf;
  3573. msg.msg_controllen = controllen;
  3574. ctx.msg = &msg;
  3575. ctx.flags = flags;
  3576. if (sock_call(s, 0, sock_recvmsg_impl, &ctx) < 0)
  3577. goto finally;
  3578. /* Make list of (level, type, data) tuples from control messages. */
  3579. if ((cmsg_list = PyList_New(0)) == NULL)
  3580. goto err_closefds;
  3581. /* Check for empty ancillary data as old CMSG_FIRSTHDR()
  3582. implementations didn't do so. */
  3583. for (cmsgh = ((msg.msg_controllen > 0) ? CMSG_FIRSTHDR(&msg) : NULL);
  3584. cmsgh != NULL; cmsgh = CMSG_NXTHDR(&msg, cmsgh)) {
  3585. PyObject *bytes, *tuple;
  3586. int tmp;
  3587. cmsg_status = get_cmsg_data_len(&msg, cmsgh, &cmsgdatalen);
  3588. if (cmsg_status != 0) {
  3589. if (PyErr_WarnEx(PyExc_RuntimeWarning,
  3590. "received malformed or improperly-truncated "
  3591. "ancillary data", 1) == -1)
  3592. goto err_closefds;
  3593. }
  3594. if (cmsg_status < 0)
  3595. break;
  3596. if (cmsgdatalen > PY_SSIZE_T_MAX) {
  3597. PyErr_SetString(PyExc_OSError, "control message too long");
  3598. goto err_closefds;
  3599. }
  3600. bytes = PyBytes_FromStringAndSize((char *)CMSG_DATA(cmsgh),
  3601. cmsgdatalen);
  3602. tuple = Py_BuildValue("iiN", (int)cmsgh->cmsg_level,
  3603. (int)cmsgh->cmsg_type, bytes);
  3604. if (tuple == NULL)
  3605. goto err_closefds;
  3606. tmp = PyList_Append(cmsg_list, tuple);
  3607. Py_DECREF(tuple);
  3608. if (tmp != 0)
  3609. goto err_closefds;
  3610. if (cmsg_status != 0)
  3611. break;
  3612. }
  3613. retval = Py_BuildValue("NOiN",
  3614. (*makeval)(ctx.result, makeval_data),
  3615. cmsg_list,
  3616. (int)msg.msg_flags,
  3617. makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
  3618. ((msg.msg_namelen > addrbuflen) ?
  3619. addrbuflen : msg.msg_namelen),
  3620. s->sock_proto));
  3621. if (retval == NULL)
  3622. goto err_closefds;
  3623. finally:
  3624. Py_XDECREF(cmsg_list);
  3625. PyMem_Free(controlbuf);
  3626. return retval;
  3627. err_closefds:
  3628. #ifdef SCM_RIGHTS
  3629. /* Close all descriptors coming from SCM_RIGHTS, so they don't leak. */
  3630. for (cmsgh = ((msg.msg_controllen > 0) ? CMSG_FIRSTHDR(&msg) : NULL);
  3631. cmsgh != NULL; cmsgh = CMSG_NXTHDR(&msg, cmsgh)) {
  3632. cmsg_status = get_cmsg_data_len(&msg, cmsgh, &cmsgdatalen);
  3633. if (cmsg_status < 0)
  3634. break;
  3635. if (cmsgh->cmsg_level == SOL_SOCKET &&
  3636. cmsgh->cmsg_type == SCM_RIGHTS) {
  3637. size_t numfds;
  3638. int *fdp;
  3639. numfds = cmsgdatalen / sizeof(int);
  3640. fdp = (int *)CMSG_DATA(cmsgh);
  3641. while (numfds-- > 0)
  3642. close(*fdp++);
  3643. }
  3644. if (cmsg_status != 0)
  3645. break;
  3646. }
  3647. #endif /* SCM_RIGHTS */
  3648. goto finally;
  3649. }
  3650. static PyObject *
  3651. makeval_recvmsg(ssize_t received, void *data)
  3652. {
  3653. PyObject **buf = data;
  3654. if (received < PyBytes_GET_SIZE(*buf))
  3655. _PyBytes_Resize(buf, received);
  3656. return Py_XNewRef(*buf);
  3657. }
  3658. /* s.recvmsg(bufsize[, ancbufsize[, flags]]) method */
  3659. static PyObject *
  3660. sock_recvmsg(PySocketSockObject *s, PyObject *args)
  3661. {
  3662. Py_ssize_t bufsize, ancbufsize = 0;
  3663. int flags = 0;
  3664. struct iovec iov;
  3665. PyObject *buf = NULL, *retval = NULL;
  3666. if (!PyArg_ParseTuple(args, "n|ni:recvmsg", &bufsize, &ancbufsize, &flags))
  3667. return NULL;
  3668. if (bufsize < 0) {
  3669. PyErr_SetString(PyExc_ValueError, "negative buffer size in recvmsg()");
  3670. return NULL;
  3671. }
  3672. if ((buf = PyBytes_FromStringAndSize(NULL, bufsize)) == NULL)
  3673. return NULL;
  3674. iov.iov_base = PyBytes_AS_STRING(buf);
  3675. iov.iov_len = bufsize;
  3676. /* Note that we're passing a pointer to *our pointer* to the bytes
  3677. object here (&buf); makeval_recvmsg() may incref the object, or
  3678. deallocate it and set our pointer to NULL. */
  3679. retval = sock_recvmsg_guts(s, &iov, 1, flags, ancbufsize,
  3680. &makeval_recvmsg, &buf);
  3681. Py_XDECREF(buf);
  3682. return retval;
  3683. }
  3684. PyDoc_STRVAR(recvmsg_doc,
  3685. "recvmsg(bufsize[, ancbufsize[, flags]]) -> (data, ancdata, msg_flags, address)\n\
  3686. \n\
  3687. Receive normal data (up to bufsize bytes) and ancillary data from the\n\
  3688. socket. The ancbufsize argument sets the size in bytes of the\n\
  3689. internal buffer used to receive the ancillary data; it defaults to 0,\n\
  3690. meaning that no ancillary data will be received. Appropriate buffer\n\
  3691. sizes for ancillary data can be calculated using CMSG_SPACE() or\n\
  3692. CMSG_LEN(), and items which do not fit into the buffer might be\n\
  3693. truncated or discarded. The flags argument defaults to 0 and has the\n\
  3694. same meaning as for recv().\n\
  3695. \n\
  3696. The return value is a 4-tuple: (data, ancdata, msg_flags, address).\n\
  3697. The data item is a bytes object holding the non-ancillary data\n\
  3698. received. The ancdata item is a list of zero or more tuples\n\
  3699. (cmsg_level, cmsg_type, cmsg_data) representing the ancillary data\n\
  3700. (control messages) received: cmsg_level and cmsg_type are integers\n\
  3701. specifying the protocol level and protocol-specific type respectively,\n\
  3702. and cmsg_data is a bytes object holding the associated data. The\n\
  3703. msg_flags item is the bitwise OR of various flags indicating\n\
  3704. conditions on the received message; see your system documentation for\n\
  3705. details. If the receiving socket is unconnected, address is the\n\
  3706. address of the sending socket, if available; otherwise, its value is\n\
  3707. unspecified.\n\
  3708. \n\
  3709. If recvmsg() raises an exception after the system call returns, it\n\
  3710. will first attempt to close any file descriptors received via the\n\
  3711. SCM_RIGHTS mechanism.");
  3712. static PyObject *
  3713. makeval_recvmsg_into(ssize_t received, void *data)
  3714. {
  3715. return PyLong_FromSsize_t(received);
  3716. }
  3717. /* s.recvmsg_into(buffers[, ancbufsize[, flags]]) method */
  3718. static PyObject *
  3719. sock_recvmsg_into(PySocketSockObject *s, PyObject *args)
  3720. {
  3721. Py_ssize_t ancbufsize = 0;
  3722. int flags = 0;
  3723. struct iovec *iovs = NULL;
  3724. Py_ssize_t i, nitems, nbufs = 0;
  3725. Py_buffer *bufs = NULL;
  3726. PyObject *buffers_arg, *fast, *retval = NULL;
  3727. if (!PyArg_ParseTuple(args, "O|ni:recvmsg_into",
  3728. &buffers_arg, &ancbufsize, &flags))
  3729. return NULL;
  3730. if ((fast = PySequence_Fast(buffers_arg,
  3731. "recvmsg_into() argument 1 must be an "
  3732. "iterable")) == NULL)
  3733. return NULL;
  3734. nitems = PySequence_Fast_GET_SIZE(fast);
  3735. if (nitems > INT_MAX) {
  3736. PyErr_SetString(PyExc_OSError, "recvmsg_into() argument 1 is too long");
  3737. goto finally;
  3738. }
  3739. /* Fill in an iovec for each item, and save the Py_buffer
  3740. structs to release afterwards. */
  3741. if (nitems > 0 && ((iovs = PyMem_New(struct iovec, nitems)) == NULL ||
  3742. (bufs = PyMem_New(Py_buffer, nitems)) == NULL)) {
  3743. PyErr_NoMemory();
  3744. goto finally;
  3745. }
  3746. for (; nbufs < nitems; nbufs++) {
  3747. if (!PyArg_Parse(PySequence_Fast_GET_ITEM(fast, nbufs),
  3748. "w*;recvmsg_into() argument 1 must be an iterable "
  3749. "of single-segment read-write buffers",
  3750. &bufs[nbufs]))
  3751. goto finally;
  3752. iovs[nbufs].iov_base = bufs[nbufs].buf;
  3753. iovs[nbufs].iov_len = bufs[nbufs].len;
  3754. }
  3755. retval = sock_recvmsg_guts(s, iovs, nitems, flags, ancbufsize,
  3756. &makeval_recvmsg_into, NULL);
  3757. finally:
  3758. for (i = 0; i < nbufs; i++)
  3759. PyBuffer_Release(&bufs[i]);
  3760. PyMem_Free(bufs);
  3761. PyMem_Free(iovs);
  3762. Py_DECREF(fast);
  3763. return retval;
  3764. }
  3765. PyDoc_STRVAR(recvmsg_into_doc,
  3766. "recvmsg_into(buffers[, ancbufsize[, flags]]) -> (nbytes, ancdata, msg_flags, address)\n\
  3767. \n\
  3768. Receive normal data and ancillary data from the socket, scattering the\n\
  3769. non-ancillary data into a series of buffers. The buffers argument\n\
  3770. must be an iterable of objects that export writable buffers\n\
  3771. (e.g. bytearray objects); these will be filled with successive chunks\n\
  3772. of the non-ancillary data until it has all been written or there are\n\
  3773. no more buffers. The ancbufsize argument sets the size in bytes of\n\
  3774. the internal buffer used to receive the ancillary data; it defaults to\n\
  3775. 0, meaning that no ancillary data will be received. Appropriate\n\
  3776. buffer sizes for ancillary data can be calculated using CMSG_SPACE()\n\
  3777. or CMSG_LEN(), and items which do not fit into the buffer might be\n\
  3778. truncated or discarded. The flags argument defaults to 0 and has the\n\
  3779. same meaning as for recv().\n\
  3780. \n\
  3781. The return value is a 4-tuple: (nbytes, ancdata, msg_flags, address).\n\
  3782. The nbytes item is the total number of bytes of non-ancillary data\n\
  3783. written into the buffers. The ancdata item is a list of zero or more\n\
  3784. tuples (cmsg_level, cmsg_type, cmsg_data) representing the ancillary\n\
  3785. data (control messages) received: cmsg_level and cmsg_type are\n\
  3786. integers specifying the protocol level and protocol-specific type\n\
  3787. respectively, and cmsg_data is a bytes object holding the associated\n\
  3788. data. The msg_flags item is the bitwise OR of various flags\n\
  3789. indicating conditions on the received message; see your system\n\
  3790. documentation for details. If the receiving socket is unconnected,\n\
  3791. address is the address of the sending socket, if available; otherwise,\n\
  3792. its value is unspecified.\n\
  3793. \n\
  3794. If recvmsg_into() raises an exception after the system call returns,\n\
  3795. it will first attempt to close any file descriptors received via the\n\
  3796. SCM_RIGHTS mechanism.");
  3797. #endif /* CMSG_LEN */
  3798. struct sock_send {
  3799. char *buf;
  3800. Py_ssize_t len;
  3801. int flags;
  3802. Py_ssize_t result;
  3803. };
  3804. static int
  3805. sock_send_impl(PySocketSockObject *s, void *data)
  3806. {
  3807. struct sock_send *ctx = data;
  3808. #ifdef MS_WINDOWS
  3809. if (ctx->len > INT_MAX)
  3810. ctx->len = INT_MAX;
  3811. ctx->result = send(s->sock_fd, ctx->buf, (int)ctx->len, ctx->flags);
  3812. #else
  3813. ctx->result = send(s->sock_fd, ctx->buf, ctx->len, ctx->flags);
  3814. #endif
  3815. return (ctx->result >= 0);
  3816. }
  3817. /* s.send(data [,flags]) method */
  3818. static PyObject *
  3819. sock_send(PySocketSockObject *s, PyObject *args)
  3820. {
  3821. int flags = 0;
  3822. Py_buffer pbuf;
  3823. struct sock_send ctx;
  3824. if (!PyArg_ParseTuple(args, "y*|i:send", &pbuf, &flags))
  3825. return NULL;
  3826. if (!IS_SELECTABLE(s)) {
  3827. PyBuffer_Release(&pbuf);
  3828. return select_error();
  3829. }
  3830. ctx.buf = pbuf.buf;
  3831. ctx.len = pbuf.len;
  3832. ctx.flags = flags;
  3833. if (sock_call(s, 1, sock_send_impl, &ctx) < 0) {
  3834. PyBuffer_Release(&pbuf);
  3835. return NULL;
  3836. }
  3837. PyBuffer_Release(&pbuf);
  3838. return PyLong_FromSsize_t(ctx.result);
  3839. }
  3840. PyDoc_STRVAR(send_doc,
  3841. "send(data[, flags]) -> count\n\
  3842. \n\
  3843. Send a data string to the socket. For the optional flags\n\
  3844. argument, see the Unix manual. Return the number of bytes\n\
  3845. sent; this may be less than len(data) if the network is busy.");
  3846. /* s.sendall(data [,flags]) method */
  3847. static PyObject *
  3848. sock_sendall(PySocketSockObject *s, PyObject *args)
  3849. {
  3850. char *buf;
  3851. Py_ssize_t len, n;
  3852. int flags = 0;
  3853. Py_buffer pbuf;
  3854. struct sock_send ctx;
  3855. int has_timeout = (s->sock_timeout > 0);
  3856. _PyTime_t timeout = s->sock_timeout;
  3857. _PyTime_t deadline = 0;
  3858. int deadline_initialized = 0;
  3859. PyObject *res = NULL;
  3860. if (!PyArg_ParseTuple(args, "y*|i:sendall", &pbuf, &flags))
  3861. return NULL;
  3862. buf = pbuf.buf;
  3863. len = pbuf.len;
  3864. if (!IS_SELECTABLE(s)) {
  3865. PyBuffer_Release(&pbuf);
  3866. return select_error();
  3867. }
  3868. do {
  3869. if (has_timeout) {
  3870. if (deadline_initialized) {
  3871. /* recompute the timeout */
  3872. timeout = _PyDeadline_Get(deadline);
  3873. }
  3874. else {
  3875. deadline_initialized = 1;
  3876. deadline = _PyDeadline_Init(timeout);
  3877. }
  3878. if (timeout <= 0) {
  3879. PyErr_SetString(PyExc_TimeoutError, "timed out");
  3880. goto done;
  3881. }
  3882. }
  3883. ctx.buf = buf;
  3884. ctx.len = len;
  3885. ctx.flags = flags;
  3886. if (sock_call_ex(s, 1, sock_send_impl, &ctx, 0, NULL, timeout) < 0)
  3887. goto done;
  3888. n = ctx.result;
  3889. assert(n >= 0);
  3890. buf += n;
  3891. len -= n;
  3892. /* We must run our signal handlers before looping again.
  3893. send() can return a successful partial write when it is
  3894. interrupted, so we can't restrict ourselves to EINTR. */
  3895. if (PyErr_CheckSignals())
  3896. goto done;
  3897. } while (len > 0);
  3898. PyBuffer_Release(&pbuf);
  3899. res = Py_NewRef(Py_None);
  3900. done:
  3901. PyBuffer_Release(&pbuf);
  3902. return res;
  3903. }
  3904. PyDoc_STRVAR(sendall_doc,
  3905. "sendall(data[, flags])\n\
  3906. \n\
  3907. Send a data string to the socket. For the optional flags\n\
  3908. argument, see the Unix manual. This calls send() repeatedly\n\
  3909. until all data is sent. If an error occurs, it's impossible\n\
  3910. to tell how much data has been sent.");
  3911. #ifdef HAVE_SENDTO
  3912. struct sock_sendto {
  3913. char *buf;
  3914. Py_ssize_t len;
  3915. int flags;
  3916. int addrlen;
  3917. sock_addr_t *addrbuf;
  3918. Py_ssize_t result;
  3919. };
  3920. static int
  3921. sock_sendto_impl(PySocketSockObject *s, void *data)
  3922. {
  3923. struct sock_sendto *ctx = data;
  3924. #ifdef MS_WINDOWS
  3925. if (ctx->len > INT_MAX)
  3926. ctx->len = INT_MAX;
  3927. ctx->result = sendto(s->sock_fd, ctx->buf, (int)ctx->len, ctx->flags,
  3928. SAS2SA(ctx->addrbuf), ctx->addrlen);
  3929. #else
  3930. ctx->result = sendto(s->sock_fd, ctx->buf, ctx->len, ctx->flags,
  3931. SAS2SA(ctx->addrbuf), ctx->addrlen);
  3932. #endif
  3933. return (ctx->result >= 0);
  3934. }
  3935. /* s.sendto(data, [flags,] sockaddr) method */
  3936. static PyObject *
  3937. sock_sendto(PySocketSockObject *s, PyObject *args)
  3938. {
  3939. Py_buffer pbuf;
  3940. PyObject *addro;
  3941. Py_ssize_t arglen;
  3942. sock_addr_t addrbuf;
  3943. int addrlen, flags;
  3944. struct sock_sendto ctx;
  3945. flags = 0;
  3946. arglen = PyTuple_Size(args);
  3947. switch (arglen) {
  3948. case 2:
  3949. if (!PyArg_ParseTuple(args, "y*O:sendto", &pbuf, &addro)) {
  3950. return NULL;
  3951. }
  3952. break;
  3953. case 3:
  3954. if (!PyArg_ParseTuple(args, "y*iO:sendto",
  3955. &pbuf, &flags, &addro)) {
  3956. return NULL;
  3957. }
  3958. break;
  3959. default:
  3960. PyErr_Format(PyExc_TypeError,
  3961. "sendto() takes 2 or 3 arguments (%zd given)",
  3962. arglen);
  3963. return NULL;
  3964. }
  3965. if (!IS_SELECTABLE(s)) {
  3966. PyBuffer_Release(&pbuf);
  3967. return select_error();
  3968. }
  3969. if (!getsockaddrarg(s, addro, &addrbuf, &addrlen, "sendto")) {
  3970. PyBuffer_Release(&pbuf);
  3971. return NULL;
  3972. }
  3973. if (PySys_Audit("socket.sendto", "OO", s, addro) < 0) {
  3974. return NULL;
  3975. }
  3976. ctx.buf = pbuf.buf;
  3977. ctx.len = pbuf.len;
  3978. ctx.flags = flags;
  3979. ctx.addrlen = addrlen;
  3980. ctx.addrbuf = &addrbuf;
  3981. if (sock_call(s, 1, sock_sendto_impl, &ctx) < 0) {
  3982. PyBuffer_Release(&pbuf);
  3983. return NULL;
  3984. }
  3985. PyBuffer_Release(&pbuf);
  3986. return PyLong_FromSsize_t(ctx.result);
  3987. }
  3988. PyDoc_STRVAR(sendto_doc,
  3989. "sendto(data[, flags], address) -> count\n\
  3990. \n\
  3991. Like send(data, flags) but allows specifying the destination address.\n\
  3992. For IP sockets, the address is a pair (hostaddr, port).");
  3993. #endif
  3994. /* The sendmsg() and recvmsg[_into]() methods require a working
  3995. CMSG_LEN(). See the comment near get_CMSG_LEN(). */
  3996. #ifdef CMSG_LEN
  3997. struct sock_sendmsg {
  3998. struct msghdr *msg;
  3999. int flags;
  4000. ssize_t result;
  4001. };
  4002. static int
  4003. sock_sendmsg_iovec(PySocketSockObject *s, PyObject *data_arg,
  4004. struct msghdr *msg,
  4005. Py_buffer **databufsout, Py_ssize_t *ndatabufsout) {
  4006. Py_ssize_t ndataparts, ndatabufs = 0;
  4007. int result = -1;
  4008. struct iovec *iovs = NULL;
  4009. PyObject *data_fast = NULL;
  4010. Py_buffer *databufs = NULL;
  4011. /* Fill in an iovec for each message part, and save the Py_buffer
  4012. structs to release afterwards. */
  4013. data_fast = PySequence_Fast(data_arg,
  4014. "sendmsg() argument 1 must be an "
  4015. "iterable");
  4016. if (data_fast == NULL) {
  4017. goto finally;
  4018. }
  4019. ndataparts = PySequence_Fast_GET_SIZE(data_fast);
  4020. if (ndataparts > INT_MAX) {
  4021. PyErr_SetString(PyExc_OSError, "sendmsg() argument 1 is too long");
  4022. goto finally;
  4023. }
  4024. msg->msg_iovlen = ndataparts;
  4025. if (ndataparts > 0) {
  4026. iovs = PyMem_New(struct iovec, ndataparts);
  4027. if (iovs == NULL) {
  4028. PyErr_NoMemory();
  4029. goto finally;
  4030. }
  4031. msg->msg_iov = iovs;
  4032. databufs = PyMem_New(Py_buffer, ndataparts);
  4033. if (databufs == NULL) {
  4034. PyErr_NoMemory();
  4035. goto finally;
  4036. }
  4037. }
  4038. for (; ndatabufs < ndataparts; ndatabufs++) {
  4039. if (!PyArg_Parse(PySequence_Fast_GET_ITEM(data_fast, ndatabufs),
  4040. "y*;sendmsg() argument 1 must be an iterable of "
  4041. "bytes-like objects",
  4042. &databufs[ndatabufs]))
  4043. goto finally;
  4044. iovs[ndatabufs].iov_base = databufs[ndatabufs].buf;
  4045. iovs[ndatabufs].iov_len = databufs[ndatabufs].len;
  4046. }
  4047. result = 0;
  4048. finally:
  4049. *databufsout = databufs;
  4050. *ndatabufsout = ndatabufs;
  4051. Py_XDECREF(data_fast);
  4052. return result;
  4053. }
  4054. static int
  4055. sock_sendmsg_impl(PySocketSockObject *s, void *data)
  4056. {
  4057. struct sock_sendmsg *ctx = data;
  4058. ctx->result = sendmsg(s->sock_fd, ctx->msg, ctx->flags);
  4059. return (ctx->result >= 0);
  4060. }
  4061. /* s.sendmsg(buffers[, ancdata[, flags[, address]]]) method */
  4062. static PyObject *
  4063. sock_sendmsg(PySocketSockObject *s, PyObject *args)
  4064. {
  4065. Py_ssize_t i, ndatabufs = 0, ncmsgs, ncmsgbufs = 0;
  4066. Py_buffer *databufs = NULL;
  4067. sock_addr_t addrbuf;
  4068. struct msghdr msg;
  4069. struct cmsginfo {
  4070. int level;
  4071. int type;
  4072. Py_buffer data;
  4073. } *cmsgs = NULL;
  4074. void *controlbuf = NULL;
  4075. size_t controllen, controllen_last;
  4076. int addrlen, flags = 0;
  4077. PyObject *data_arg, *cmsg_arg = NULL, *addr_arg = NULL,
  4078. *cmsg_fast = NULL, *retval = NULL;
  4079. struct sock_sendmsg ctx;
  4080. if (!PyArg_ParseTuple(args, "O|OiO:sendmsg",
  4081. &data_arg, &cmsg_arg, &flags, &addr_arg)) {
  4082. return NULL;
  4083. }
  4084. memset(&msg, 0, sizeof(msg));
  4085. /* Parse destination address. */
  4086. if (addr_arg != NULL && addr_arg != Py_None) {
  4087. if (!getsockaddrarg(s, addr_arg, &addrbuf, &addrlen,
  4088. "sendmsg"))
  4089. {
  4090. goto finally;
  4091. }
  4092. if (PySys_Audit("socket.sendmsg", "OO", s, addr_arg) < 0) {
  4093. return NULL;
  4094. }
  4095. msg.msg_name = &addrbuf;
  4096. msg.msg_namelen = addrlen;
  4097. } else {
  4098. if (PySys_Audit("socket.sendmsg", "OO", s, Py_None) < 0) {
  4099. return NULL;
  4100. }
  4101. }
  4102. /* Fill in an iovec for each message part, and save the Py_buffer
  4103. structs to release afterwards. */
  4104. if (sock_sendmsg_iovec(s, data_arg, &msg, &databufs, &ndatabufs) == -1) {
  4105. goto finally;
  4106. }
  4107. if (cmsg_arg == NULL)
  4108. ncmsgs = 0;
  4109. else {
  4110. if ((cmsg_fast = PySequence_Fast(cmsg_arg,
  4111. "sendmsg() argument 2 must be an "
  4112. "iterable")) == NULL)
  4113. goto finally;
  4114. ncmsgs = PySequence_Fast_GET_SIZE(cmsg_fast);
  4115. }
  4116. #ifndef CMSG_SPACE
  4117. if (ncmsgs > 1) {
  4118. PyErr_SetString(PyExc_OSError,
  4119. "sending multiple control messages is not supported "
  4120. "on this system");
  4121. goto finally;
  4122. }
  4123. #endif
  4124. /* Save level, type and Py_buffer for each control message,
  4125. and calculate total size. */
  4126. if (ncmsgs > 0 && (cmsgs = PyMem_New(struct cmsginfo, ncmsgs)) == NULL) {
  4127. PyErr_NoMemory();
  4128. goto finally;
  4129. }
  4130. controllen = controllen_last = 0;
  4131. while (ncmsgbufs < ncmsgs) {
  4132. size_t bufsize, space;
  4133. if (!PyArg_Parse(PySequence_Fast_GET_ITEM(cmsg_fast, ncmsgbufs),
  4134. "(iiy*):[sendmsg() ancillary data items]",
  4135. &cmsgs[ncmsgbufs].level,
  4136. &cmsgs[ncmsgbufs].type,
  4137. &cmsgs[ncmsgbufs].data))
  4138. goto finally;
  4139. bufsize = cmsgs[ncmsgbufs++].data.len;
  4140. #ifdef CMSG_SPACE
  4141. if (!get_CMSG_SPACE(bufsize, &space)) {
  4142. #else
  4143. if (!get_CMSG_LEN(bufsize, &space)) {
  4144. #endif
  4145. PyErr_SetString(PyExc_OSError, "ancillary data item too large");
  4146. goto finally;
  4147. }
  4148. controllen += space;
  4149. if (controllen > SOCKLEN_T_LIMIT || controllen < controllen_last) {
  4150. PyErr_SetString(PyExc_OSError, "too much ancillary data");
  4151. goto finally;
  4152. }
  4153. controllen_last = controllen;
  4154. }
  4155. /* Construct ancillary data block from control message info. */
  4156. if (ncmsgbufs > 0) {
  4157. struct cmsghdr *cmsgh = NULL;
  4158. controlbuf = PyMem_Malloc(controllen);
  4159. if (controlbuf == NULL) {
  4160. PyErr_NoMemory();
  4161. goto finally;
  4162. }
  4163. msg.msg_control = controlbuf;
  4164. msg.msg_controllen = controllen;
  4165. /* Need to zero out the buffer as a workaround for glibc's
  4166. CMSG_NXTHDR() implementation. After getting the pointer to
  4167. the next header, it checks its (uninitialized) cmsg_len
  4168. member to see if the "message" fits in the buffer, and
  4169. returns NULL if it doesn't. Zero-filling the buffer
  4170. ensures that this doesn't happen. */
  4171. memset(controlbuf, 0, controllen);
  4172. for (i = 0; i < ncmsgbufs; i++) {
  4173. size_t msg_len, data_len = cmsgs[i].data.len;
  4174. int enough_space = 0;
  4175. cmsgh = (i == 0) ? CMSG_FIRSTHDR(&msg) : CMSG_NXTHDR(&msg, cmsgh);
  4176. if (cmsgh == NULL) {
  4177. PyErr_Format(PyExc_RuntimeError,
  4178. "unexpected NULL result from %s()",
  4179. (i == 0) ? "CMSG_FIRSTHDR" : "CMSG_NXTHDR");
  4180. goto finally;
  4181. }
  4182. if (!get_CMSG_LEN(data_len, &msg_len)) {
  4183. PyErr_SetString(PyExc_RuntimeError,
  4184. "item size out of range for CMSG_LEN()");
  4185. goto finally;
  4186. }
  4187. if (cmsg_min_space(&msg, cmsgh, msg_len)) {
  4188. size_t space;
  4189. cmsgh->cmsg_len = msg_len;
  4190. if (get_cmsg_data_space(&msg, cmsgh, &space))
  4191. enough_space = (space >= data_len);
  4192. }
  4193. if (!enough_space) {
  4194. PyErr_SetString(PyExc_RuntimeError,
  4195. "ancillary data does not fit in calculated "
  4196. "space");
  4197. goto finally;
  4198. }
  4199. cmsgh->cmsg_level = cmsgs[i].level;
  4200. cmsgh->cmsg_type = cmsgs[i].type;
  4201. memcpy(CMSG_DATA(cmsgh), cmsgs[i].data.buf, data_len);
  4202. }
  4203. }
  4204. /* Make the system call. */
  4205. if (!IS_SELECTABLE(s)) {
  4206. select_error();
  4207. goto finally;
  4208. }
  4209. ctx.msg = &msg;
  4210. ctx.flags = flags;
  4211. if (sock_call(s, 1, sock_sendmsg_impl, &ctx) < 0)
  4212. goto finally;
  4213. retval = PyLong_FromSsize_t(ctx.result);
  4214. finally:
  4215. PyMem_Free(controlbuf);
  4216. for (i = 0; i < ncmsgbufs; i++)
  4217. PyBuffer_Release(&cmsgs[i].data);
  4218. PyMem_Free(cmsgs);
  4219. Py_XDECREF(cmsg_fast);
  4220. PyMem_Free(msg.msg_iov);
  4221. for (i = 0; i < ndatabufs; i++) {
  4222. PyBuffer_Release(&databufs[i]);
  4223. }
  4224. PyMem_Free(databufs);
  4225. return retval;
  4226. }
  4227. PyDoc_STRVAR(sendmsg_doc,
  4228. "sendmsg(buffers[, ancdata[, flags[, address]]]) -> count\n\
  4229. \n\
  4230. Send normal and ancillary data to the socket, gathering the\n\
  4231. non-ancillary data from a series of buffers and concatenating it into\n\
  4232. a single message. The buffers argument specifies the non-ancillary\n\
  4233. data as an iterable of bytes-like objects (e.g. bytes objects).\n\
  4234. The ancdata argument specifies the ancillary data (control messages)\n\
  4235. as an iterable of zero or more tuples (cmsg_level, cmsg_type,\n\
  4236. cmsg_data), where cmsg_level and cmsg_type are integers specifying the\n\
  4237. protocol level and protocol-specific type respectively, and cmsg_data\n\
  4238. is a bytes-like object holding the associated data. The flags\n\
  4239. argument defaults to 0 and has the same meaning as for send(). If\n\
  4240. address is supplied and not None, it sets a destination address for\n\
  4241. the message. The return value is the number of bytes of non-ancillary\n\
  4242. data sent.");
  4243. #endif /* CMSG_LEN */
  4244. #ifdef HAVE_SOCKADDR_ALG
  4245. static PyObject*
  4246. sock_sendmsg_afalg(PySocketSockObject *self, PyObject *args, PyObject *kwds)
  4247. {
  4248. PyObject *retval = NULL;
  4249. Py_ssize_t i, ndatabufs = 0;
  4250. Py_buffer *databufs = NULL;
  4251. PyObject *data_arg = NULL;
  4252. Py_buffer iv = {NULL, NULL};
  4253. PyObject *opobj = NULL;
  4254. int op = -1;
  4255. PyObject *assoclenobj = NULL;
  4256. int assoclen = -1;
  4257. unsigned int *uiptr;
  4258. int flags = 0;
  4259. struct msghdr msg;
  4260. struct cmsghdr *header = NULL;
  4261. struct af_alg_iv *alg_iv = NULL;
  4262. struct sock_sendmsg ctx;
  4263. Py_ssize_t controllen;
  4264. void *controlbuf = NULL;
  4265. static char *keywords[] = {"msg", "op", "iv", "assoclen", "flags", 0};
  4266. if (self->sock_family != AF_ALG) {
  4267. PyErr_SetString(PyExc_OSError,
  4268. "algset is only supported for AF_ALG");
  4269. return NULL;
  4270. }
  4271. if (!PyArg_ParseTupleAndKeywords(args, kwds,
  4272. "|O$O!y*O!i:sendmsg_afalg", keywords,
  4273. &data_arg,
  4274. &PyLong_Type, &opobj, &iv,
  4275. &PyLong_Type, &assoclenobj, &flags)) {
  4276. return NULL;
  4277. }
  4278. memset(&msg, 0, sizeof(msg));
  4279. /* op is a required, keyword-only argument >= 0 */
  4280. if (opobj != NULL) {
  4281. op = _PyLong_AsInt(opobj);
  4282. }
  4283. if (op < 0) {
  4284. /* override exception from _PyLong_AsInt() */
  4285. PyErr_SetString(PyExc_TypeError,
  4286. "Invalid or missing argument 'op'");
  4287. goto finally;
  4288. }
  4289. /* assoclen is optional but must be >= 0 */
  4290. if (assoclenobj != NULL) {
  4291. assoclen = _PyLong_AsInt(assoclenobj);
  4292. if (assoclen == -1 && PyErr_Occurred()) {
  4293. goto finally;
  4294. }
  4295. if (assoclen < 0) {
  4296. PyErr_SetString(PyExc_TypeError,
  4297. "assoclen must be positive");
  4298. goto finally;
  4299. }
  4300. }
  4301. controllen = CMSG_SPACE(4);
  4302. if (iv.buf != NULL) {
  4303. controllen += CMSG_SPACE(sizeof(*alg_iv) + iv.len);
  4304. }
  4305. if (assoclen >= 0) {
  4306. controllen += CMSG_SPACE(4);
  4307. }
  4308. controlbuf = PyMem_Malloc(controllen);
  4309. if (controlbuf == NULL) {
  4310. PyErr_NoMemory();
  4311. goto finally;
  4312. }
  4313. memset(controlbuf, 0, controllen);
  4314. msg.msg_controllen = controllen;
  4315. msg.msg_control = controlbuf;
  4316. /* Fill in an iovec for each message part, and save the Py_buffer
  4317. structs to release afterwards. */
  4318. if (data_arg != NULL) {
  4319. if (sock_sendmsg_iovec(self, data_arg, &msg, &databufs, &ndatabufs) == -1) {
  4320. goto finally;
  4321. }
  4322. }
  4323. /* set operation to encrypt or decrypt */
  4324. header = CMSG_FIRSTHDR(&msg);
  4325. if (header == NULL) {
  4326. PyErr_SetString(PyExc_RuntimeError,
  4327. "unexpected NULL result from CMSG_FIRSTHDR");
  4328. goto finally;
  4329. }
  4330. header->cmsg_level = SOL_ALG;
  4331. header->cmsg_type = ALG_SET_OP;
  4332. header->cmsg_len = CMSG_LEN(4);
  4333. uiptr = (void*)CMSG_DATA(header);
  4334. *uiptr = (unsigned int)op;
  4335. /* set initialization vector */
  4336. if (iv.buf != NULL) {
  4337. header = CMSG_NXTHDR(&msg, header);
  4338. if (header == NULL) {
  4339. PyErr_SetString(PyExc_RuntimeError,
  4340. "unexpected NULL result from CMSG_NXTHDR(iv)");
  4341. goto finally;
  4342. }
  4343. header->cmsg_level = SOL_ALG;
  4344. header->cmsg_type = ALG_SET_IV;
  4345. header->cmsg_len = CMSG_SPACE(sizeof(*alg_iv) + iv.len);
  4346. alg_iv = (void*)CMSG_DATA(header);
  4347. alg_iv->ivlen = iv.len;
  4348. memcpy(alg_iv->iv, iv.buf, iv.len);
  4349. }
  4350. /* set length of associated data for AEAD */
  4351. if (assoclen >= 0) {
  4352. header = CMSG_NXTHDR(&msg, header);
  4353. if (header == NULL) {
  4354. PyErr_SetString(PyExc_RuntimeError,
  4355. "unexpected NULL result from CMSG_NXTHDR(assoc)");
  4356. goto finally;
  4357. }
  4358. header->cmsg_level = SOL_ALG;
  4359. header->cmsg_type = ALG_SET_AEAD_ASSOCLEN;
  4360. header->cmsg_len = CMSG_LEN(4);
  4361. uiptr = (void*)CMSG_DATA(header);
  4362. *uiptr = (unsigned int)assoclen;
  4363. }
  4364. ctx.msg = &msg;
  4365. ctx.flags = flags;
  4366. if (sock_call(self, 1, sock_sendmsg_impl, &ctx) < 0) {
  4367. goto finally;
  4368. }
  4369. retval = PyLong_FromSsize_t(ctx.result);
  4370. finally:
  4371. PyMem_Free(controlbuf);
  4372. if (iv.buf != NULL) {
  4373. PyBuffer_Release(&iv);
  4374. }
  4375. PyMem_Free(msg.msg_iov);
  4376. for (i = 0; i < ndatabufs; i++) {
  4377. PyBuffer_Release(&databufs[i]);
  4378. }
  4379. PyMem_Free(databufs);
  4380. return retval;
  4381. }
  4382. PyDoc_STRVAR(sendmsg_afalg_doc,
  4383. "sendmsg_afalg([msg], *, op[, iv[, assoclen[, flags=MSG_MORE]]])\n\
  4384. \n\
  4385. Set operation mode, IV and length of associated data for an AF_ALG\n\
  4386. operation socket.");
  4387. #endif
  4388. #ifdef HAVE_SHUTDOWN
  4389. /* s.shutdown(how) method */
  4390. static PyObject *
  4391. sock_shutdown(PySocketSockObject *s, PyObject *arg)
  4392. {
  4393. int how;
  4394. int res;
  4395. how = _PyLong_AsInt(arg);
  4396. if (how == -1 && PyErr_Occurred())
  4397. return NULL;
  4398. Py_BEGIN_ALLOW_THREADS
  4399. res = shutdown(s->sock_fd, how);
  4400. Py_END_ALLOW_THREADS
  4401. if (res < 0)
  4402. return s->errorhandler();
  4403. Py_RETURN_NONE;
  4404. }
  4405. PyDoc_STRVAR(shutdown_doc,
  4406. "shutdown(flag)\n\
  4407. \n\
  4408. Shut down the reading side of the socket (flag == SHUT_RD), the writing side\n\
  4409. of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).");
  4410. #endif
  4411. #if defined(MS_WINDOWS) && defined(SIO_RCVALL)
  4412. static PyObject*
  4413. sock_ioctl(PySocketSockObject *s, PyObject *arg)
  4414. {
  4415. unsigned long cmd = SIO_RCVALL;
  4416. PyObject *argO;
  4417. DWORD recv;
  4418. if (!PyArg_ParseTuple(arg, "kO:ioctl", &cmd, &argO))
  4419. return NULL;
  4420. switch (cmd) {
  4421. case SIO_RCVALL: {
  4422. unsigned int option = RCVALL_ON;
  4423. if (!PyArg_ParseTuple(arg, "kI:ioctl", &cmd, &option))
  4424. return NULL;
  4425. if (WSAIoctl(s->sock_fd, cmd, &option, sizeof(option),
  4426. NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
  4427. return set_error();
  4428. }
  4429. return PyLong_FromUnsignedLong(recv); }
  4430. case SIO_KEEPALIVE_VALS: {
  4431. struct tcp_keepalive ka;
  4432. if (!PyArg_ParseTuple(arg, "k(kkk):ioctl", &cmd,
  4433. &ka.onoff, &ka.keepalivetime, &ka.keepaliveinterval))
  4434. return NULL;
  4435. if (WSAIoctl(s->sock_fd, cmd, &ka, sizeof(ka),
  4436. NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
  4437. return set_error();
  4438. }
  4439. return PyLong_FromUnsignedLong(recv); }
  4440. #if defined(SIO_LOOPBACK_FAST_PATH)
  4441. case SIO_LOOPBACK_FAST_PATH: {
  4442. unsigned int option;
  4443. if (!PyArg_ParseTuple(arg, "kI:ioctl", &cmd, &option))
  4444. return NULL;
  4445. if (WSAIoctl(s->sock_fd, cmd, &option, sizeof(option),
  4446. NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
  4447. return set_error();
  4448. }
  4449. return PyLong_FromUnsignedLong(recv); }
  4450. #endif
  4451. default:
  4452. PyErr_Format(PyExc_ValueError, "invalid ioctl command %lu", cmd);
  4453. return NULL;
  4454. }
  4455. }
  4456. PyDoc_STRVAR(sock_ioctl_doc,
  4457. "ioctl(cmd, option) -> long\n\
  4458. \n\
  4459. Control the socket with WSAIoctl syscall. Currently supported 'cmd' values are\n\
  4460. SIO_RCVALL: 'option' must be one of the socket.RCVALL_* constants.\n\
  4461. SIO_KEEPALIVE_VALS: 'option' is a tuple of (onoff, timeout, interval).\n\
  4462. SIO_LOOPBACK_FAST_PATH: 'option' is a boolean value, and is disabled by default");
  4463. #endif
  4464. #if defined(MS_WINDOWS)
  4465. static PyObject*
  4466. sock_share(PySocketSockObject *s, PyObject *arg)
  4467. {
  4468. WSAPROTOCOL_INFOW info;
  4469. DWORD processId;
  4470. int result;
  4471. if (!PyArg_ParseTuple(arg, "I", &processId))
  4472. return NULL;
  4473. Py_BEGIN_ALLOW_THREADS
  4474. result = WSADuplicateSocketW(s->sock_fd, processId, &info);
  4475. Py_END_ALLOW_THREADS
  4476. if (result == SOCKET_ERROR)
  4477. return set_error();
  4478. return PyBytes_FromStringAndSize((const char*)&info, sizeof(info));
  4479. }
  4480. PyDoc_STRVAR(sock_share_doc,
  4481. "share(process_id) -> bytes\n\
  4482. \n\
  4483. Share the socket with another process. The target process id\n\
  4484. must be provided and the resulting bytes object passed to the target\n\
  4485. process. There the shared socket can be instantiated by calling\n\
  4486. socket.fromshare().");
  4487. #endif
  4488. /* List of methods for socket objects */
  4489. static PyMethodDef sock_methods[] = {
  4490. #if defined(HAVE_ACCEPT) || defined(HAVE_ACCEPT4)
  4491. {"_accept", (PyCFunction)sock_accept, METH_NOARGS,
  4492. accept_doc},
  4493. #endif
  4494. #ifdef HAVE_BIND
  4495. {"bind", (PyCFunction)sock_bind, METH_O,
  4496. bind_doc},
  4497. #endif
  4498. {"close", (PyCFunction)sock_close, METH_NOARGS,
  4499. sock_close_doc},
  4500. #ifdef HAVE_CONNECT
  4501. {"connect", (PyCFunction)sock_connect, METH_O,
  4502. connect_doc},
  4503. {"connect_ex", (PyCFunction)sock_connect_ex, METH_O,
  4504. connect_ex_doc},
  4505. #endif
  4506. {"detach", (PyCFunction)sock_detach, METH_NOARGS,
  4507. detach_doc},
  4508. {"fileno", (PyCFunction)sock_fileno, METH_NOARGS,
  4509. fileno_doc},
  4510. #ifdef HAVE_GETPEERNAME
  4511. {"getpeername", (PyCFunction)sock_getpeername,
  4512. METH_NOARGS, getpeername_doc},
  4513. #endif
  4514. #ifdef HAVE_GETSOCKNAME
  4515. {"getsockname", (PyCFunction)sock_getsockname,
  4516. METH_NOARGS, getsockname_doc},
  4517. #endif
  4518. {"getsockopt", (PyCFunction)sock_getsockopt, METH_VARARGS,
  4519. getsockopt_doc},
  4520. #if defined(MS_WINDOWS) && defined(SIO_RCVALL)
  4521. {"ioctl", (PyCFunction)sock_ioctl, METH_VARARGS,
  4522. sock_ioctl_doc},
  4523. #endif
  4524. #if defined(MS_WINDOWS)
  4525. {"share", (PyCFunction)sock_share, METH_VARARGS,
  4526. sock_share_doc},
  4527. #endif
  4528. #ifdef HAVE_LISTEN
  4529. {"listen", (PyCFunction)sock_listen, METH_VARARGS,
  4530. listen_doc},
  4531. #endif
  4532. {"recv", (PyCFunction)sock_recv, METH_VARARGS,
  4533. recv_doc},
  4534. {"recv_into", _PyCFunction_CAST(sock_recv_into), METH_VARARGS | METH_KEYWORDS,
  4535. recv_into_doc},
  4536. #ifdef HAVE_RECVFROM
  4537. {"recvfrom", (PyCFunction)sock_recvfrom, METH_VARARGS,
  4538. recvfrom_doc},
  4539. {"recvfrom_into", _PyCFunction_CAST(sock_recvfrom_into), METH_VARARGS | METH_KEYWORDS,
  4540. recvfrom_into_doc},
  4541. #endif
  4542. {"send", (PyCFunction)sock_send, METH_VARARGS,
  4543. send_doc},
  4544. {"sendall", (PyCFunction)sock_sendall, METH_VARARGS,
  4545. sendall_doc},
  4546. #ifdef HAVE_SENDTO
  4547. {"sendto", (PyCFunction)sock_sendto, METH_VARARGS,
  4548. sendto_doc},
  4549. #endif
  4550. {"setblocking", (PyCFunction)sock_setblocking, METH_O,
  4551. setblocking_doc},
  4552. {"getblocking", (PyCFunction)sock_getblocking, METH_NOARGS,
  4553. getblocking_doc},
  4554. {"settimeout", (PyCFunction)sock_settimeout, METH_O,
  4555. settimeout_doc},
  4556. {"gettimeout", (PyCFunction)sock_gettimeout, METH_NOARGS,
  4557. gettimeout_doc},
  4558. #ifdef HAVE_SETSOCKOPT
  4559. {"setsockopt", (PyCFunction)sock_setsockopt, METH_VARARGS,
  4560. setsockopt_doc},
  4561. #endif
  4562. #ifdef HAVE_SHUTDOWN
  4563. {"shutdown", (PyCFunction)sock_shutdown, METH_O,
  4564. shutdown_doc},
  4565. #endif
  4566. #ifdef CMSG_LEN
  4567. {"recvmsg", (PyCFunction)sock_recvmsg, METH_VARARGS,
  4568. recvmsg_doc},
  4569. {"recvmsg_into", (PyCFunction)sock_recvmsg_into, METH_VARARGS,
  4570. recvmsg_into_doc,},
  4571. {"sendmsg", (PyCFunction)sock_sendmsg, METH_VARARGS,
  4572. sendmsg_doc},
  4573. #endif
  4574. #ifdef HAVE_SOCKADDR_ALG
  4575. {"sendmsg_afalg", _PyCFunction_CAST(sock_sendmsg_afalg), METH_VARARGS | METH_KEYWORDS,
  4576. sendmsg_afalg_doc},
  4577. #endif
  4578. {NULL, NULL} /* sentinel */
  4579. };
  4580. /* SockObject members */
  4581. static PyMemberDef sock_memberlist[] = {
  4582. {"family", T_INT, offsetof(PySocketSockObject, sock_family), READONLY, "the socket family"},
  4583. {"type", T_INT, offsetof(PySocketSockObject, sock_type), READONLY, "the socket type"},
  4584. {"proto", T_INT, offsetof(PySocketSockObject, sock_proto), READONLY, "the socket protocol"},
  4585. {0},
  4586. };
  4587. static PyGetSetDef sock_getsetlist[] = {
  4588. {"timeout", (getter)sock_gettimeout, NULL, PyDoc_STR("the socket timeout")},
  4589. {NULL} /* sentinel */
  4590. };
  4591. /* Deallocate a socket object in response to the last Py_DECREF().
  4592. First close the file description. */
  4593. static void
  4594. sock_finalize(PySocketSockObject *s)
  4595. {
  4596. SOCKET_T fd;
  4597. /* Save the current exception, if any. */
  4598. PyObject *exc = PyErr_GetRaisedException();
  4599. if (s->sock_fd != INVALID_SOCKET) {
  4600. if (PyErr_ResourceWarning((PyObject *)s, 1, "unclosed %R", s)) {
  4601. /* Spurious errors can appear at shutdown */
  4602. if (PyErr_ExceptionMatches(PyExc_Warning)) {
  4603. PyErr_WriteUnraisable((PyObject *)s);
  4604. }
  4605. }
  4606. /* Only close the socket *after* logging the ResourceWarning warning
  4607. to allow the logger to call socket methods like
  4608. socket.getsockname(). If the socket is closed before, socket
  4609. methods fails with the EBADF error. */
  4610. fd = s->sock_fd;
  4611. s->sock_fd = INVALID_SOCKET;
  4612. /* We do not want to retry upon EINTR: see sock_close() */
  4613. Py_BEGIN_ALLOW_THREADS
  4614. (void) SOCKETCLOSE(fd);
  4615. Py_END_ALLOW_THREADS
  4616. }
  4617. /* Restore the saved exception. */
  4618. PyErr_SetRaisedException(exc);
  4619. }
  4620. static int
  4621. sock_traverse(PySocketSockObject *s, visitproc visit, void *arg)
  4622. {
  4623. Py_VISIT(Py_TYPE(s));
  4624. return 0;
  4625. }
  4626. static void
  4627. sock_dealloc(PySocketSockObject *s)
  4628. {
  4629. if (PyObject_CallFinalizerFromDealloc((PyObject *)s) < 0) {
  4630. return;
  4631. }
  4632. PyTypeObject *tp = Py_TYPE(s);
  4633. PyObject_GC_UnTrack(s);
  4634. tp->tp_free((PyObject *)s);
  4635. Py_DECREF(tp);
  4636. }
  4637. static PyObject *
  4638. sock_repr(PySocketSockObject *s)
  4639. {
  4640. long sock_fd;
  4641. /* On Windows, this test is needed because SOCKET_T is unsigned */
  4642. if (s->sock_fd == INVALID_SOCKET) {
  4643. sock_fd = -1;
  4644. }
  4645. #if SIZEOF_SOCKET_T > SIZEOF_LONG
  4646. else if (s->sock_fd > LONG_MAX) {
  4647. /* this can occur on Win64, and actually there is a special
  4648. ugly printf formatter for decimal pointer length integer
  4649. printing, only bother if necessary*/
  4650. PyErr_SetString(PyExc_OverflowError,
  4651. "no printf formatter to display "
  4652. "the socket descriptor in decimal");
  4653. return NULL;
  4654. }
  4655. #endif
  4656. else
  4657. sock_fd = (long)s->sock_fd;
  4658. return PyUnicode_FromFormat(
  4659. "<socket object, fd=%ld, family=%d, type=%d, proto=%d>",
  4660. sock_fd, s->sock_family,
  4661. s->sock_type,
  4662. s->sock_proto);
  4663. }
  4664. /* Create a new, uninitialized socket object. */
  4665. static PyObject *
  4666. sock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  4667. {
  4668. PyObject *new;
  4669. new = type->tp_alloc(type, 0);
  4670. if (new != NULL) {
  4671. ((PySocketSockObject *)new)->sock_fd = INVALID_SOCKET;
  4672. ((PySocketSockObject *)new)->sock_timeout = _PyTime_FromSeconds(-1);
  4673. ((PySocketSockObject *)new)->errorhandler = &set_error;
  4674. }
  4675. return new;
  4676. }
  4677. /* Initialize a new socket object. */
  4678. /*ARGSUSED*/
  4679. #ifndef HAVE_SOCKET
  4680. #define socket stub_socket
  4681. static int
  4682. socket(int domain, int type, int protocol)
  4683. {
  4684. errno = ENOTSUP;
  4685. return INVALID_SOCKET;
  4686. }
  4687. #endif
  4688. /*[clinic input]
  4689. _socket.socket.__init__ as sock_initobj
  4690. family: int = -1
  4691. type: int = -1
  4692. proto: int = -1
  4693. fileno as fdobj: object = NULL
  4694. [clinic start generated code]*/
  4695. static int
  4696. sock_initobj_impl(PySocketSockObject *self, int family, int type, int proto,
  4697. PyObject *fdobj)
  4698. /*[clinic end generated code: output=d114d026b9a9a810 input=04cfc32953f5cc25]*/
  4699. {
  4700. SOCKET_T fd = INVALID_SOCKET;
  4701. socket_state *state = find_module_state_by_def(Py_TYPE(self));
  4702. #ifndef MS_WINDOWS
  4703. #ifdef SOCK_CLOEXEC
  4704. int *atomic_flag_works = &state->sock_cloexec_works;
  4705. #else
  4706. int *atomic_flag_works = NULL;
  4707. #endif
  4708. #endif
  4709. #ifdef MS_WINDOWS
  4710. /* In this case, we don't use the family, type and proto args */
  4711. if (fdobj == NULL || fdobj == Py_None)
  4712. #endif
  4713. {
  4714. if (PySys_Audit("socket.__new__", "Oiii",
  4715. self, family, type, proto) < 0) {
  4716. return -1;
  4717. }
  4718. }
  4719. if (fdobj != NULL && fdobj != Py_None) {
  4720. #ifdef MS_WINDOWS
  4721. /* recreate a socket that was duplicated */
  4722. if (PyBytes_Check(fdobj)) {
  4723. WSAPROTOCOL_INFOW info;
  4724. if (PyBytes_GET_SIZE(fdobj) != sizeof(info)) {
  4725. PyErr_Format(PyExc_ValueError,
  4726. "socket descriptor string has wrong size, "
  4727. "should be %zu bytes.", sizeof(info));
  4728. return -1;
  4729. }
  4730. memcpy(&info, PyBytes_AS_STRING(fdobj), sizeof(info));
  4731. if (PySys_Audit("socket.__new__", "Oiii", self,
  4732. info.iAddressFamily, info.iSocketType,
  4733. info.iProtocol) < 0) {
  4734. return -1;
  4735. }
  4736. Py_BEGIN_ALLOW_THREADS
  4737. fd = WSASocketW(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
  4738. FROM_PROTOCOL_INFO, &info, 0, WSA_FLAG_OVERLAPPED);
  4739. Py_END_ALLOW_THREADS
  4740. if (fd == INVALID_SOCKET) {
  4741. set_error();
  4742. return -1;
  4743. }
  4744. if (!SetHandleInformation((HANDLE)fd, HANDLE_FLAG_INHERIT, 0)) {
  4745. PyErr_SetFromWindowsErr(0);
  4746. closesocket(fd);
  4747. return -1;
  4748. }
  4749. family = info.iAddressFamily;
  4750. type = info.iSocketType;
  4751. proto = info.iProtocol;
  4752. }
  4753. else
  4754. #endif
  4755. {
  4756. fd = PyLong_AsSocket_t(fdobj);
  4757. if (fd == (SOCKET_T)(-1) && PyErr_Occurred())
  4758. return -1;
  4759. #ifdef MS_WINDOWS
  4760. if (fd == INVALID_SOCKET) {
  4761. #else
  4762. if (fd < 0) {
  4763. #endif
  4764. PyErr_SetString(PyExc_ValueError, "negative file descriptor");
  4765. return -1;
  4766. }
  4767. /* validate that passed file descriptor is valid and a socket. */
  4768. sock_addr_t addrbuf;
  4769. socklen_t addrlen = sizeof(sock_addr_t);
  4770. memset(&addrbuf, 0, addrlen);
  4771. #ifdef HAVE_GETSOCKNAME
  4772. if (getsockname(fd, SAS2SA(&addrbuf), &addrlen) == 0) {
  4773. if (family == -1) {
  4774. family = SAS2SA(&addrbuf)->sa_family;
  4775. }
  4776. } else {
  4777. #ifdef MS_WINDOWS
  4778. /* getsockname() on an unbound socket is an error on Windows.
  4779. Invalid descriptor and not a socket is same error code.
  4780. Error out if family must be resolved, or bad descriptor. */
  4781. if (family == -1 || CHECK_ERRNO(ENOTSOCK)) {
  4782. #else
  4783. /* getsockname() is not supported for SOL_ALG on Linux. */
  4784. if (family == -1 || CHECK_ERRNO(EBADF) || CHECK_ERRNO(ENOTSOCK)) {
  4785. #endif
  4786. set_error();
  4787. return -1;
  4788. }
  4789. }
  4790. #endif // HAVE_GETSOCKNAME
  4791. #ifdef SO_TYPE
  4792. if (type == -1) {
  4793. int tmp;
  4794. socklen_t slen = sizeof(tmp);
  4795. if (getsockopt(fd, SOL_SOCKET, SO_TYPE,
  4796. (void *)&tmp, &slen) == 0)
  4797. {
  4798. type = tmp;
  4799. } else {
  4800. set_error();
  4801. return -1;
  4802. }
  4803. }
  4804. #else
  4805. type = SOCK_STREAM;
  4806. #endif
  4807. #ifdef SO_PROTOCOL
  4808. if (proto == -1) {
  4809. int tmp;
  4810. socklen_t slen = sizeof(tmp);
  4811. if (getsockopt(fd, SOL_SOCKET, SO_PROTOCOL,
  4812. (void *)&tmp, &slen) == 0)
  4813. {
  4814. proto = tmp;
  4815. } else {
  4816. set_error();
  4817. return -1;
  4818. }
  4819. }
  4820. #else
  4821. proto = 0;
  4822. #endif
  4823. }
  4824. }
  4825. else {
  4826. /* No fd, default to AF_INET and SOCK_STREAM */
  4827. if (family == -1) {
  4828. family = AF_INET;
  4829. }
  4830. if (type == -1) {
  4831. type = SOCK_STREAM;
  4832. }
  4833. if (proto == -1) {
  4834. proto = 0;
  4835. }
  4836. #ifdef MS_WINDOWS
  4837. Py_BEGIN_ALLOW_THREADS
  4838. fd = WSASocketW(family, type, proto,
  4839. NULL, 0,
  4840. WSA_FLAG_OVERLAPPED | WSA_FLAG_NO_HANDLE_INHERIT);
  4841. Py_END_ALLOW_THREADS
  4842. if (fd == INVALID_SOCKET) {
  4843. set_error();
  4844. return -1;
  4845. }
  4846. #else
  4847. /* UNIX */
  4848. Py_BEGIN_ALLOW_THREADS
  4849. #ifdef SOCK_CLOEXEC
  4850. if (state->sock_cloexec_works != 0) {
  4851. fd = socket(family, type | SOCK_CLOEXEC, proto);
  4852. if (state->sock_cloexec_works == -1) {
  4853. if (fd >= 0) {
  4854. state->sock_cloexec_works = 1;
  4855. }
  4856. else if (errno == EINVAL) {
  4857. /* Linux older than 2.6.27 does not support SOCK_CLOEXEC */
  4858. state->sock_cloexec_works = 0;
  4859. fd = socket(family, type, proto);
  4860. }
  4861. }
  4862. }
  4863. else
  4864. #endif
  4865. {
  4866. fd = socket(family, type, proto);
  4867. }
  4868. Py_END_ALLOW_THREADS
  4869. if (fd == INVALID_SOCKET) {
  4870. set_error();
  4871. return -1;
  4872. }
  4873. if (_Py_set_inheritable(fd, 0, atomic_flag_works) < 0) {
  4874. SOCKETCLOSE(fd);
  4875. return -1;
  4876. }
  4877. #endif
  4878. }
  4879. if (init_sockobject(state, self, fd, family, type, proto) == -1) {
  4880. SOCKETCLOSE(fd);
  4881. return -1;
  4882. }
  4883. return 0;
  4884. }
  4885. /* Type object for socket objects. */
  4886. static PyType_Slot sock_slots[] = {
  4887. {Py_tp_dealloc, sock_dealloc},
  4888. {Py_tp_traverse, sock_traverse},
  4889. {Py_tp_repr, sock_repr},
  4890. {Py_tp_doc, (void *)sock_doc},
  4891. {Py_tp_methods, sock_methods},
  4892. {Py_tp_members, sock_memberlist},
  4893. {Py_tp_getset, sock_getsetlist},
  4894. {Py_tp_init, sock_initobj},
  4895. {Py_tp_new, sock_new},
  4896. {Py_tp_finalize, sock_finalize},
  4897. {0, NULL},
  4898. };
  4899. static PyType_Spec sock_spec = {
  4900. .name = "_socket.socket",
  4901. .basicsize = sizeof(PySocketSockObject),
  4902. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
  4903. Py_TPFLAGS_IMMUTABLETYPE),
  4904. .slots = sock_slots,
  4905. };
  4906. #ifdef HAVE_GETHOSTNAME
  4907. /* Python interface to gethostname(). */
  4908. /*ARGSUSED*/
  4909. static PyObject *
  4910. socket_gethostname(PyObject *self, PyObject *unused)
  4911. {
  4912. if (PySys_Audit("socket.gethostname", NULL) < 0) {
  4913. return NULL;
  4914. }
  4915. #ifdef MS_WINDOWS
  4916. /* Don't use winsock's gethostname, as this returns the ANSI
  4917. version of the hostname, whereas we need a Unicode string.
  4918. Otherwise, gethostname apparently also returns the DNS name. */
  4919. wchar_t buf[MAX_COMPUTERNAME_LENGTH + 1];
  4920. DWORD size = Py_ARRAY_LENGTH(buf);
  4921. wchar_t *name;
  4922. PyObject *result;
  4923. if (GetComputerNameExW(ComputerNamePhysicalDnsHostname, buf, &size))
  4924. return PyUnicode_FromWideChar(buf, size);
  4925. if (GetLastError() != ERROR_MORE_DATA)
  4926. return PyErr_SetFromWindowsErr(0);
  4927. if (size == 0)
  4928. return PyUnicode_New(0, 0);
  4929. /* MSDN says ERROR_MORE_DATA may occur because DNS allows longer
  4930. names */
  4931. name = PyMem_New(wchar_t, size);
  4932. if (!name) {
  4933. PyErr_NoMemory();
  4934. return NULL;
  4935. }
  4936. if (!GetComputerNameExW(ComputerNamePhysicalDnsHostname,
  4937. name,
  4938. &size))
  4939. {
  4940. PyErr_SetFromWindowsErr(0);
  4941. PyMem_Free(name);
  4942. return NULL;
  4943. }
  4944. result = PyUnicode_FromWideChar(name, size);
  4945. PyMem_Free(name);
  4946. return result;
  4947. #else
  4948. char buf[1024];
  4949. int res;
  4950. Py_BEGIN_ALLOW_THREADS
  4951. res = gethostname(buf, (int) sizeof buf - 1);
  4952. Py_END_ALLOW_THREADS
  4953. if (res < 0)
  4954. return set_error();
  4955. buf[sizeof buf - 1] = '\0';
  4956. return PyUnicode_DecodeFSDefault(buf);
  4957. #endif
  4958. }
  4959. PyDoc_STRVAR(gethostname_doc,
  4960. "gethostname() -> string\n\
  4961. \n\
  4962. Return the current host name.");
  4963. #endif
  4964. #ifdef HAVE_SETHOSTNAME
  4965. PyDoc_STRVAR(sethostname_doc,
  4966. "sethostname(name)\n\n\
  4967. Sets the hostname to name.");
  4968. static PyObject *
  4969. socket_sethostname(PyObject *self, PyObject *args)
  4970. {
  4971. PyObject *hnobj;
  4972. Py_buffer buf;
  4973. int res, flag = 0;
  4974. #if defined(_AIX) || (defined(__sun) && defined(__SVR4) && Py_SUNOS_VERSION <= 510)
  4975. /* issue #18259, sethostname is not declared in any useful header file on AIX
  4976. * the same is true for Solaris 10 */
  4977. extern int sethostname(const char *, size_t);
  4978. #endif
  4979. if (!PyArg_ParseTuple(args, "S:sethostname", &hnobj)) {
  4980. PyErr_Clear();
  4981. if (!PyArg_ParseTuple(args, "O&:sethostname",
  4982. PyUnicode_FSConverter, &hnobj))
  4983. return NULL;
  4984. flag = 1;
  4985. }
  4986. if (PySys_Audit("socket.sethostname", "(O)", hnobj) < 0) {
  4987. return NULL;
  4988. }
  4989. res = PyObject_GetBuffer(hnobj, &buf, PyBUF_SIMPLE);
  4990. if (!res) {
  4991. res = sethostname(buf.buf, buf.len);
  4992. PyBuffer_Release(&buf);
  4993. }
  4994. if (flag)
  4995. Py_DECREF(hnobj);
  4996. if (res)
  4997. return set_error();
  4998. Py_RETURN_NONE;
  4999. }
  5000. #endif
  5001. #ifdef HAVE_GETADDRINFO
  5002. /* Python interface to gethostbyname(name). */
  5003. /*ARGSUSED*/
  5004. static PyObject *
  5005. socket_gethostbyname(PyObject *self, PyObject *args)
  5006. {
  5007. char *name;
  5008. struct sockaddr_in addrbuf;
  5009. PyObject *ret = NULL;
  5010. if (!PyArg_ParseTuple(args, "et:gethostbyname", "idna", &name))
  5011. return NULL;
  5012. if (PySys_Audit("socket.gethostbyname", "O", args) < 0) {
  5013. goto finally;
  5014. }
  5015. socket_state *state = get_module_state(self);
  5016. int rc = setipaddr(state, name, (struct sockaddr *)&addrbuf,
  5017. sizeof(addrbuf), AF_INET);
  5018. if (rc < 0) {
  5019. goto finally;
  5020. }
  5021. ret = make_ipv4_addr(&addrbuf);
  5022. finally:
  5023. PyMem_Free(name);
  5024. return ret;
  5025. }
  5026. PyDoc_STRVAR(gethostbyname_doc,
  5027. "gethostbyname(host) -> address\n\
  5028. \n\
  5029. Return the IP address (a string of the form '255.255.255.255') for a host.");
  5030. #endif
  5031. #if defined(HAVE_GETHOSTBYNAME_R) || defined (HAVE_GETHOSTBYNAME) || defined (HAVE_GETHOSTBYADDR)
  5032. static PyObject*
  5033. sock_decode_hostname(const char *name)
  5034. {
  5035. #ifdef MS_WINDOWS
  5036. /* Issue #26227: gethostbyaddr() returns a string encoded
  5037. * to the ANSI code page */
  5038. return PyUnicode_DecodeMBCS(name, strlen(name), "surrogatepass");
  5039. #else
  5040. /* Decode from UTF-8 */
  5041. return PyUnicode_FromString(name);
  5042. #endif
  5043. }
  5044. /* Convenience function common to gethostbyname_ex and gethostbyaddr */
  5045. static PyObject *
  5046. gethost_common(socket_state *state, struct hostent *h, struct sockaddr *addr,
  5047. size_t alen, int af)
  5048. {
  5049. char **pch;
  5050. PyObject *rtn_tuple = (PyObject *)NULL;
  5051. PyObject *name_list = (PyObject *)NULL;
  5052. PyObject *addr_list = (PyObject *)NULL;
  5053. PyObject *tmp;
  5054. PyObject *name;
  5055. if (h == NULL) {
  5056. /* Let's get real error message to return */
  5057. set_herror(state, h_errno);
  5058. return NULL;
  5059. }
  5060. if (h->h_addrtype != af) {
  5061. /* Let's get real error message to return */
  5062. errno = EAFNOSUPPORT;
  5063. PyErr_SetFromErrno(PyExc_OSError);
  5064. return NULL;
  5065. }
  5066. switch (af) {
  5067. case AF_INET:
  5068. if (alen < sizeof(struct sockaddr_in))
  5069. return NULL;
  5070. break;
  5071. #ifdef ENABLE_IPV6
  5072. case AF_INET6:
  5073. if (alen < sizeof(struct sockaddr_in6))
  5074. return NULL;
  5075. break;
  5076. #endif
  5077. }
  5078. if ((name_list = PyList_New(0)) == NULL)
  5079. goto err;
  5080. if ((addr_list = PyList_New(0)) == NULL)
  5081. goto err;
  5082. /* SF #1511317: h_aliases can be NULL */
  5083. if (h->h_aliases) {
  5084. for (pch = h->h_aliases; ; pch++) {
  5085. int status;
  5086. char *host_alias;
  5087. // pch can be misaligned
  5088. memcpy(&host_alias, pch, sizeof(host_alias));
  5089. if (host_alias == NULL) {
  5090. break;
  5091. }
  5092. tmp = PyUnicode_FromString(host_alias);
  5093. if (tmp == NULL)
  5094. goto err;
  5095. status = PyList_Append(name_list, tmp);
  5096. Py_DECREF(tmp);
  5097. if (status)
  5098. goto err;
  5099. }
  5100. }
  5101. for (pch = h->h_addr_list; ; pch++) {
  5102. int status;
  5103. char *host_address;
  5104. // pch can be misaligned
  5105. memcpy(&host_address, pch, sizeof(host_address));
  5106. if (host_address == NULL) {
  5107. break;
  5108. }
  5109. switch (af) {
  5110. case AF_INET:
  5111. {
  5112. struct sockaddr_in sin;
  5113. memset(&sin, 0, sizeof(sin));
  5114. sin.sin_family = af;
  5115. #ifdef HAVE_SOCKADDR_SA_LEN
  5116. sin.sin_len = sizeof(sin);
  5117. #endif
  5118. memcpy(&sin.sin_addr, host_address, sizeof(sin.sin_addr));
  5119. tmp = make_ipv4_addr(&sin);
  5120. if (pch == h->h_addr_list && alen >= sizeof(sin))
  5121. memcpy((char *) addr, &sin, sizeof(sin));
  5122. break;
  5123. }
  5124. #ifdef ENABLE_IPV6
  5125. case AF_INET6:
  5126. {
  5127. struct sockaddr_in6 sin6;
  5128. memset(&sin6, 0, sizeof(sin6));
  5129. sin6.sin6_family = af;
  5130. #ifdef HAVE_SOCKADDR_SA_LEN
  5131. sin6.sin6_len = sizeof(sin6);
  5132. #endif
  5133. memcpy(&sin6.sin6_addr, host_address, sizeof(sin6.sin6_addr));
  5134. tmp = make_ipv6_addr(&sin6);
  5135. if (pch == h->h_addr_list && alen >= sizeof(sin6))
  5136. memcpy((char *) addr, &sin6, sizeof(sin6));
  5137. break;
  5138. }
  5139. #endif
  5140. default: /* can't happen */
  5141. PyErr_SetString(PyExc_OSError,
  5142. "unsupported address family");
  5143. return NULL;
  5144. }
  5145. if (tmp == NULL)
  5146. goto err;
  5147. status = PyList_Append(addr_list, tmp);
  5148. Py_DECREF(tmp);
  5149. if (status)
  5150. goto err;
  5151. }
  5152. name = sock_decode_hostname(h->h_name);
  5153. if (name == NULL)
  5154. goto err;
  5155. rtn_tuple = Py_BuildValue("NOO", name, name_list, addr_list);
  5156. err:
  5157. Py_XDECREF(name_list);
  5158. Py_XDECREF(addr_list);
  5159. return rtn_tuple;
  5160. }
  5161. #endif
  5162. #if defined(HAVE_GETHOSTBYNAME_R) || defined (HAVE_GETHOSTBYNAME)
  5163. /* Python interface to gethostbyname_ex(name). */
  5164. /*ARGSUSED*/
  5165. static PyObject *
  5166. socket_gethostbyname_ex(PyObject *self, PyObject *args)
  5167. {
  5168. char *name;
  5169. struct hostent *h;
  5170. sock_addr_t addr;
  5171. struct sockaddr *sa;
  5172. PyObject *ret = NULL;
  5173. #ifdef HAVE_GETHOSTBYNAME_R
  5174. struct hostent hp_allocated;
  5175. #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
  5176. struct hostent_data data;
  5177. #else
  5178. char buf[16384];
  5179. int buf_len = (sizeof buf) - 1;
  5180. int errnop;
  5181. #endif
  5182. #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
  5183. int result;
  5184. #endif
  5185. #endif /* HAVE_GETHOSTBYNAME_R */
  5186. if (!PyArg_ParseTuple(args, "et:gethostbyname_ex", "idna", &name))
  5187. return NULL;
  5188. if (PySys_Audit("socket.gethostbyname", "O", args) < 0) {
  5189. goto finally;
  5190. }
  5191. socket_state *state = get_module_state(self);
  5192. if (setipaddr(state, name, SAS2SA(&addr), sizeof(addr), AF_INET) < 0) {
  5193. goto finally;
  5194. }
  5195. Py_BEGIN_ALLOW_THREADS
  5196. #ifdef HAVE_GETHOSTBYNAME_R
  5197. #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
  5198. gethostbyname_r(name, &hp_allocated, buf, buf_len,
  5199. &h, &errnop);
  5200. #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
  5201. h = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop);
  5202. #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
  5203. memset((void *) &data, '\0', sizeof(data));
  5204. result = gethostbyname_r(name, &hp_allocated, &data);
  5205. h = (result != 0) ? NULL : &hp_allocated;
  5206. #endif
  5207. #else /* not HAVE_GETHOSTBYNAME_R */
  5208. #ifdef USE_GETHOSTBYNAME_LOCK
  5209. PyThread_acquire_lock(netdb_lock, 1);
  5210. #endif
  5211. SUPPRESS_DEPRECATED_CALL
  5212. h = gethostbyname(name);
  5213. #endif /* HAVE_GETHOSTBYNAME_R */
  5214. Py_END_ALLOW_THREADS
  5215. /* Some C libraries would require addr.__ss_family instead of
  5216. addr.ss_family.
  5217. Therefore, we cast the sockaddr_storage into sockaddr to
  5218. access sa_family. */
  5219. sa = SAS2SA(&addr);
  5220. ret = gethost_common(state, h, SAS2SA(&addr), sizeof(addr),
  5221. sa->sa_family);
  5222. #ifdef USE_GETHOSTBYNAME_LOCK
  5223. PyThread_release_lock(netdb_lock);
  5224. #endif
  5225. finally:
  5226. PyMem_Free(name);
  5227. return ret;
  5228. }
  5229. PyDoc_STRVAR(ghbn_ex_doc,
  5230. "gethostbyname_ex(host) -> (name, aliaslist, addresslist)\n\
  5231. \n\
  5232. Return the true host name, a list of aliases, and a list of IP addresses,\n\
  5233. for a host. The host argument is a string giving a host name or IP number.");
  5234. #endif
  5235. #if defined(HAVE_GETHOSTBYNAME_R) || defined (HAVE_GETHOSTBYADDR)
  5236. /* Python interface to gethostbyaddr(IP). */
  5237. /*ARGSUSED*/
  5238. static PyObject *
  5239. socket_gethostbyaddr(PyObject *self, PyObject *args)
  5240. {
  5241. sock_addr_t addr;
  5242. struct sockaddr *sa = SAS2SA(&addr);
  5243. char *ip_num;
  5244. struct hostent *h;
  5245. PyObject *ret = NULL;
  5246. #ifdef HAVE_GETHOSTBYNAME_R
  5247. struct hostent hp_allocated;
  5248. #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
  5249. struct hostent_data data;
  5250. #else
  5251. /* glibcs up to 2.10 assume that the buf argument to
  5252. gethostbyaddr_r is 8-byte aligned, which at least llvm-gcc
  5253. does not ensure. The attribute below instructs the compiler
  5254. to maintain this alignment. */
  5255. char buf[16384] Py_ALIGNED(8);
  5256. int buf_len = (sizeof buf) - 1;
  5257. int errnop;
  5258. #endif
  5259. #ifdef HAVE_GETHOSTBYNAME_R_3_ARG
  5260. int result;
  5261. #endif
  5262. #endif /* HAVE_GETHOSTBYNAME_R */
  5263. const char *ap;
  5264. int al;
  5265. int af;
  5266. if (!PyArg_ParseTuple(args, "et:gethostbyaddr", "idna", &ip_num))
  5267. return NULL;
  5268. if (PySys_Audit("socket.gethostbyaddr", "O", args) < 0) {
  5269. goto finally;
  5270. }
  5271. af = AF_UNSPEC;
  5272. socket_state *state = get_module_state(self);
  5273. if (setipaddr(state, ip_num, sa, sizeof(addr), af) < 0) {
  5274. goto finally;
  5275. }
  5276. af = sa->sa_family;
  5277. ap = NULL;
  5278. /* al = 0; */
  5279. switch (af) {
  5280. case AF_INET:
  5281. ap = (char *)&((struct sockaddr_in *)sa)->sin_addr;
  5282. al = sizeof(((struct sockaddr_in *)sa)->sin_addr);
  5283. break;
  5284. #ifdef ENABLE_IPV6
  5285. case AF_INET6:
  5286. ap = (char *)&((struct sockaddr_in6 *)sa)->sin6_addr;
  5287. al = sizeof(((struct sockaddr_in6 *)sa)->sin6_addr);
  5288. break;
  5289. #endif
  5290. default:
  5291. PyErr_SetString(PyExc_OSError, "unsupported address family");
  5292. goto finally;
  5293. }
  5294. Py_BEGIN_ALLOW_THREADS
  5295. #ifdef HAVE_GETHOSTBYNAME_R
  5296. #if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
  5297. gethostbyaddr_r(ap, al, af,
  5298. &hp_allocated, buf, buf_len,
  5299. &h, &errnop);
  5300. #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
  5301. h = gethostbyaddr_r(ap, al, af,
  5302. &hp_allocated, buf, buf_len, &errnop);
  5303. #else /* HAVE_GETHOSTBYNAME_R_3_ARG */
  5304. memset((void *) &data, '\0', sizeof(data));
  5305. result = gethostbyaddr_r(ap, al, af, &hp_allocated, &data);
  5306. h = (result != 0) ? NULL : &hp_allocated;
  5307. #endif
  5308. #else /* not HAVE_GETHOSTBYNAME_R */
  5309. #ifdef USE_GETHOSTBYNAME_LOCK
  5310. PyThread_acquire_lock(netdb_lock, 1);
  5311. #endif
  5312. SUPPRESS_DEPRECATED_CALL
  5313. h = gethostbyaddr(ap, al, af);
  5314. #endif /* HAVE_GETHOSTBYNAME_R */
  5315. Py_END_ALLOW_THREADS
  5316. ret = gethost_common(state, h, SAS2SA(&addr), sizeof(addr), af);
  5317. #ifdef USE_GETHOSTBYNAME_LOCK
  5318. PyThread_release_lock(netdb_lock);
  5319. #endif
  5320. finally:
  5321. PyMem_Free(ip_num);
  5322. return ret;
  5323. }
  5324. PyDoc_STRVAR(gethostbyaddr_doc,
  5325. "gethostbyaddr(host) -> (name, aliaslist, addresslist)\n\
  5326. \n\
  5327. Return the true host name, a list of aliases, and a list of IP addresses,\n\
  5328. for a host. The host argument is a string giving a host name or IP number.");
  5329. #endif
  5330. #ifdef HAVE_GETSERVBYNAME
  5331. /* Python interface to getservbyname(name).
  5332. This only returns the port number, since the other info is already
  5333. known or not useful (like the list of aliases). */
  5334. /*ARGSUSED*/
  5335. static PyObject *
  5336. socket_getservbyname(PyObject *self, PyObject *args)
  5337. {
  5338. const char *name, *proto=NULL;
  5339. struct servent *sp;
  5340. if (!PyArg_ParseTuple(args, "s|s:getservbyname", &name, &proto))
  5341. return NULL;
  5342. if (PySys_Audit("socket.getservbyname", "ss", name, proto) < 0) {
  5343. return NULL;
  5344. }
  5345. Py_BEGIN_ALLOW_THREADS
  5346. sp = getservbyname(name, proto);
  5347. Py_END_ALLOW_THREADS
  5348. if (sp == NULL) {
  5349. PyErr_SetString(PyExc_OSError, "service/proto not found");
  5350. return NULL;
  5351. }
  5352. return PyLong_FromLong((long) ntohs(sp->s_port));
  5353. }
  5354. PyDoc_STRVAR(getservbyname_doc,
  5355. "getservbyname(servicename[, protocolname]) -> integer\n\
  5356. \n\
  5357. Return a port number from a service name and protocol name.\n\
  5358. The optional protocol name, if given, should be 'tcp' or 'udp',\n\
  5359. otherwise any protocol will match.");
  5360. #endif
  5361. #ifdef HAVE_GETSERVBYPORT
  5362. /* Python interface to getservbyport(port).
  5363. This only returns the service name, since the other info is already
  5364. known or not useful (like the list of aliases). */
  5365. /*ARGSUSED*/
  5366. static PyObject *
  5367. socket_getservbyport(PyObject *self, PyObject *args)
  5368. {
  5369. int port;
  5370. const char *proto=NULL;
  5371. struct servent *sp;
  5372. if (!PyArg_ParseTuple(args, "i|s:getservbyport", &port, &proto))
  5373. return NULL;
  5374. if (port < 0 || port > 0xffff) {
  5375. PyErr_SetString(
  5376. PyExc_OverflowError,
  5377. "getservbyport: port must be 0-65535.");
  5378. return NULL;
  5379. }
  5380. if (PySys_Audit("socket.getservbyport", "is", port, proto) < 0) {
  5381. return NULL;
  5382. }
  5383. Py_BEGIN_ALLOW_THREADS
  5384. sp = getservbyport(htons((short)port), proto);
  5385. Py_END_ALLOW_THREADS
  5386. if (sp == NULL) {
  5387. PyErr_SetString(PyExc_OSError, "port/proto not found");
  5388. return NULL;
  5389. }
  5390. return PyUnicode_FromString(sp->s_name);
  5391. }
  5392. PyDoc_STRVAR(getservbyport_doc,
  5393. "getservbyport(port[, protocolname]) -> string\n\
  5394. \n\
  5395. Return the service name from a port number and protocol name.\n\
  5396. The optional protocol name, if given, should be 'tcp' or 'udp',\n\
  5397. otherwise any protocol will match.");
  5398. #endif
  5399. #ifdef HAVE_GETPROTOBYNAME
  5400. /* Python interface to getprotobyname(name).
  5401. This only returns the protocol number, since the other info is
  5402. already known or not useful (like the list of aliases). */
  5403. /*ARGSUSED*/
  5404. static PyObject *
  5405. socket_getprotobyname(PyObject *self, PyObject *args)
  5406. {
  5407. const char *name;
  5408. struct protoent *sp;
  5409. if (!PyArg_ParseTuple(args, "s:getprotobyname", &name))
  5410. return NULL;
  5411. Py_BEGIN_ALLOW_THREADS
  5412. sp = getprotobyname(name);
  5413. Py_END_ALLOW_THREADS
  5414. if (sp == NULL) {
  5415. PyErr_SetString(PyExc_OSError, "protocol not found");
  5416. return NULL;
  5417. }
  5418. return PyLong_FromLong((long) sp->p_proto);
  5419. }
  5420. PyDoc_STRVAR(getprotobyname_doc,
  5421. "getprotobyname(name) -> integer\n\
  5422. \n\
  5423. Return the protocol number for the named protocol. (Rarely used.)");
  5424. #endif
  5425. static PyObject *
  5426. socket_close(PyObject *self, PyObject *fdobj)
  5427. {
  5428. SOCKET_T fd;
  5429. int res;
  5430. fd = PyLong_AsSocket_t(fdobj);
  5431. if (fd == (SOCKET_T)(-1) && PyErr_Occurred())
  5432. return NULL;
  5433. Py_BEGIN_ALLOW_THREADS
  5434. res = SOCKETCLOSE(fd);
  5435. Py_END_ALLOW_THREADS
  5436. /* bpo-30319: The peer can already have closed the connection.
  5437. Python ignores ECONNRESET on close(). */
  5438. if (res < 0 && !CHECK_ERRNO(ECONNRESET)) {
  5439. return set_error();
  5440. }
  5441. Py_RETURN_NONE;
  5442. }
  5443. PyDoc_STRVAR(close_doc,
  5444. "close(integer) -> None\n\
  5445. \n\
  5446. Close an integer socket file descriptor. This is like os.close(), but for\n\
  5447. sockets; on some platforms os.close() won't work for socket file descriptors.");
  5448. #ifndef NO_DUP
  5449. /* dup() function for socket fds */
  5450. static PyObject *
  5451. socket_dup(PyObject *self, PyObject *fdobj)
  5452. {
  5453. SOCKET_T fd, newfd;
  5454. PyObject *newfdobj;
  5455. #ifdef MS_WINDOWS
  5456. WSAPROTOCOL_INFOW info;
  5457. #endif
  5458. fd = PyLong_AsSocket_t(fdobj);
  5459. if (fd == (SOCKET_T)(-1) && PyErr_Occurred()) {
  5460. return NULL;
  5461. }
  5462. #ifdef MS_WINDOWS
  5463. if (WSADuplicateSocketW(fd, GetCurrentProcessId(), &info))
  5464. return set_error();
  5465. newfd = WSASocketW(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
  5466. FROM_PROTOCOL_INFO,
  5467. &info, 0, WSA_FLAG_OVERLAPPED);
  5468. if (newfd == INVALID_SOCKET) {
  5469. return set_error();
  5470. }
  5471. if (!SetHandleInformation((HANDLE)newfd, HANDLE_FLAG_INHERIT, 0)) {
  5472. PyErr_SetFromWindowsErr(0);
  5473. closesocket(newfd);
  5474. return NULL;
  5475. }
  5476. #else
  5477. /* On UNIX, dup can be used to duplicate the file descriptor of a socket */
  5478. newfd = _Py_dup(fd);
  5479. if (newfd == INVALID_SOCKET) {
  5480. return NULL;
  5481. }
  5482. #endif
  5483. newfdobj = PyLong_FromSocket_t(newfd);
  5484. if (newfdobj == NULL) {
  5485. SOCKETCLOSE(newfd);
  5486. }
  5487. return newfdobj;
  5488. }
  5489. PyDoc_STRVAR(dup_doc,
  5490. "dup(integer) -> integer\n\
  5491. \n\
  5492. Duplicate an integer socket file descriptor. This is like os.dup(), but for\n\
  5493. sockets; on some platforms os.dup() won't work for socket file descriptors.");
  5494. #endif
  5495. #ifdef HAVE_SOCKETPAIR
  5496. /* Create a pair of sockets using the socketpair() function.
  5497. Arguments as for socket() except the default family is AF_UNIX if
  5498. defined on the platform; otherwise, the default is AF_INET. */
  5499. /*ARGSUSED*/
  5500. static PyObject *
  5501. socket_socketpair(PyObject *self, PyObject *args)
  5502. {
  5503. PySocketSockObject *s0 = NULL, *s1 = NULL;
  5504. SOCKET_T sv[2];
  5505. int family, type = SOCK_STREAM, proto = 0;
  5506. PyObject *res = NULL;
  5507. socket_state *state = get_module_state(self);
  5508. #ifdef SOCK_CLOEXEC
  5509. int *atomic_flag_works = &state->sock_cloexec_works;
  5510. #else
  5511. int *atomic_flag_works = NULL;
  5512. #endif
  5513. int ret;
  5514. #if defined(AF_UNIX)
  5515. family = AF_UNIX;
  5516. #else
  5517. family = AF_INET;
  5518. #endif
  5519. if (!PyArg_ParseTuple(args, "|iii:socketpair",
  5520. &family, &type, &proto))
  5521. return NULL;
  5522. /* Create a pair of socket fds */
  5523. Py_BEGIN_ALLOW_THREADS
  5524. #ifdef SOCK_CLOEXEC
  5525. if (state->sock_cloexec_works != 0) {
  5526. ret = socketpair(family, type | SOCK_CLOEXEC, proto, sv);
  5527. if (state->sock_cloexec_works == -1) {
  5528. if (ret >= 0) {
  5529. state->sock_cloexec_works = 1;
  5530. }
  5531. else if (errno == EINVAL) {
  5532. /* Linux older than 2.6.27 does not support SOCK_CLOEXEC */
  5533. state->sock_cloexec_works = 0;
  5534. ret = socketpair(family, type, proto, sv);
  5535. }
  5536. }
  5537. }
  5538. else
  5539. #endif
  5540. {
  5541. ret = socketpair(family, type, proto, sv);
  5542. }
  5543. Py_END_ALLOW_THREADS
  5544. if (ret < 0)
  5545. return set_error();
  5546. if (_Py_set_inheritable(sv[0], 0, atomic_flag_works) < 0)
  5547. goto finally;
  5548. if (_Py_set_inheritable(sv[1], 0, atomic_flag_works) < 0)
  5549. goto finally;
  5550. s0 = new_sockobject(state, sv[0], family, type, proto);
  5551. if (s0 == NULL)
  5552. goto finally;
  5553. s1 = new_sockobject(state, sv[1], family, type, proto);
  5554. if (s1 == NULL)
  5555. goto finally;
  5556. res = PyTuple_Pack(2, s0, s1);
  5557. finally:
  5558. if (res == NULL) {
  5559. if (s0 == NULL)
  5560. SOCKETCLOSE(sv[0]);
  5561. if (s1 == NULL)
  5562. SOCKETCLOSE(sv[1]);
  5563. }
  5564. Py_XDECREF(s0);
  5565. Py_XDECREF(s1);
  5566. return res;
  5567. }
  5568. PyDoc_STRVAR(socketpair_doc,
  5569. "socketpair([family[, type [, proto]]]) -> (socket object, socket object)\n\
  5570. \n\
  5571. Create a pair of socket objects from the sockets returned by the platform\n\
  5572. socketpair() function.\n\
  5573. The arguments are the same as for socket() except the default family is\n\
  5574. AF_UNIX if defined on the platform; otherwise, the default is AF_INET.");
  5575. #endif /* HAVE_SOCKETPAIR */
  5576. static PyObject *
  5577. socket_ntohs(PyObject *self, PyObject *args)
  5578. {
  5579. int x;
  5580. if (!PyArg_ParseTuple(args, "i:ntohs", &x)) {
  5581. return NULL;
  5582. }
  5583. if (x < 0) {
  5584. PyErr_SetString(PyExc_OverflowError,
  5585. "ntohs: can't convert negative Python int to C "
  5586. "16-bit unsigned integer");
  5587. return NULL;
  5588. }
  5589. if (x > 0xffff) {
  5590. PyErr_SetString(PyExc_OverflowError,
  5591. "ntohs: Python int too large to convert to C "
  5592. "16-bit unsigned integer");
  5593. return NULL;
  5594. }
  5595. return PyLong_FromUnsignedLong(ntohs((unsigned short)x));
  5596. }
  5597. PyDoc_STRVAR(ntohs_doc,
  5598. "ntohs(integer) -> integer\n\
  5599. \n\
  5600. Convert a 16-bit unsigned integer from network to host byte order.");
  5601. static PyObject *
  5602. socket_ntohl(PyObject *self, PyObject *arg)
  5603. {
  5604. unsigned long x;
  5605. if (PyLong_Check(arg)) {
  5606. x = PyLong_AsUnsignedLong(arg);
  5607. if (x == (unsigned long) -1 && PyErr_Occurred())
  5608. return NULL;
  5609. #if SIZEOF_LONG > 4
  5610. {
  5611. unsigned long y;
  5612. /* only want the trailing 32 bits */
  5613. y = x & 0xFFFFFFFFUL;
  5614. if (y ^ x)
  5615. return PyErr_Format(PyExc_OverflowError,
  5616. "int larger than 32 bits");
  5617. x = y;
  5618. }
  5619. #endif
  5620. }
  5621. else
  5622. return PyErr_Format(PyExc_TypeError,
  5623. "expected int, %s found",
  5624. Py_TYPE(arg)->tp_name);
  5625. return PyLong_FromUnsignedLong(ntohl(x));
  5626. }
  5627. PyDoc_STRVAR(ntohl_doc,
  5628. "ntohl(integer) -> integer\n\
  5629. \n\
  5630. Convert a 32-bit integer from network to host byte order.");
  5631. static PyObject *
  5632. socket_htons(PyObject *self, PyObject *args)
  5633. {
  5634. int x;
  5635. if (!PyArg_ParseTuple(args, "i:htons", &x)) {
  5636. return NULL;
  5637. }
  5638. if (x < 0) {
  5639. PyErr_SetString(PyExc_OverflowError,
  5640. "htons: can't convert negative Python int to C "
  5641. "16-bit unsigned integer");
  5642. return NULL;
  5643. }
  5644. if (x > 0xffff) {
  5645. PyErr_SetString(PyExc_OverflowError,
  5646. "htons: Python int too large to convert to C "
  5647. "16-bit unsigned integer");
  5648. return NULL;
  5649. }
  5650. return PyLong_FromUnsignedLong(htons((unsigned short)x));
  5651. }
  5652. PyDoc_STRVAR(htons_doc,
  5653. "htons(integer) -> integer\n\
  5654. \n\
  5655. Convert a 16-bit unsigned integer from host to network byte order.");
  5656. static PyObject *
  5657. socket_htonl(PyObject *self, PyObject *arg)
  5658. {
  5659. unsigned long x;
  5660. if (PyLong_Check(arg)) {
  5661. x = PyLong_AsUnsignedLong(arg);
  5662. if (x == (unsigned long) -1 && PyErr_Occurred())
  5663. return NULL;
  5664. #if SIZEOF_LONG > 4
  5665. {
  5666. unsigned long y;
  5667. /* only want the trailing 32 bits */
  5668. y = x & 0xFFFFFFFFUL;
  5669. if (y ^ x)
  5670. return PyErr_Format(PyExc_OverflowError,
  5671. "int larger than 32 bits");
  5672. x = y;
  5673. }
  5674. #endif
  5675. }
  5676. else
  5677. return PyErr_Format(PyExc_TypeError,
  5678. "expected int, %s found",
  5679. Py_TYPE(arg)->tp_name);
  5680. return PyLong_FromUnsignedLong(htonl((unsigned long)x));
  5681. }
  5682. PyDoc_STRVAR(htonl_doc,
  5683. "htonl(integer) -> integer\n\
  5684. \n\
  5685. Convert a 32-bit integer from host to network byte order.");
  5686. /* socket.inet_aton() and socket.inet_ntoa() functions. */
  5687. PyDoc_STRVAR(inet_aton_doc,
  5688. "inet_aton(string) -> bytes giving packed 32-bit IP representation\n\
  5689. \n\
  5690. Convert an IP address in string format (123.45.67.89) to the 32-bit packed\n\
  5691. binary format used in low-level network functions.");
  5692. static PyObject*
  5693. socket_inet_aton(PyObject *self, PyObject *args)
  5694. {
  5695. #ifdef HAVE_INET_ATON
  5696. struct in_addr buf;
  5697. #endif
  5698. #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
  5699. #if (SIZEOF_INT != 4)
  5700. #error "Not sure if in_addr_t exists and int is not 32-bits."
  5701. #endif
  5702. /* Have to use inet_addr() instead */
  5703. unsigned int packed_addr;
  5704. #endif
  5705. const char *ip_addr;
  5706. if (!PyArg_ParseTuple(args, "s:inet_aton", &ip_addr))
  5707. return NULL;
  5708. #ifdef HAVE_INET_ATON
  5709. #ifdef USE_INET_ATON_WEAKLINK
  5710. if (inet_aton != NULL) {
  5711. #endif
  5712. if (inet_aton(ip_addr, &buf))
  5713. return PyBytes_FromStringAndSize((char *)(&buf),
  5714. sizeof(buf));
  5715. PyErr_SetString(PyExc_OSError,
  5716. "illegal IP address string passed to inet_aton");
  5717. return NULL;
  5718. #ifdef USE_INET_ATON_WEAKLINK
  5719. } else {
  5720. #endif
  5721. #endif
  5722. #if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
  5723. /* special-case this address as inet_addr might return INADDR_NONE
  5724. * for this */
  5725. if (strcmp(ip_addr, "255.255.255.255") == 0) {
  5726. packed_addr = INADDR_BROADCAST;
  5727. } else {
  5728. SUPPRESS_DEPRECATED_CALL
  5729. packed_addr = inet_addr(ip_addr);
  5730. if (packed_addr == INADDR_NONE) { /* invalid address */
  5731. PyErr_SetString(PyExc_OSError,
  5732. "illegal IP address string passed to inet_aton");
  5733. return NULL;
  5734. }
  5735. }
  5736. return PyBytes_FromStringAndSize((char *) &packed_addr,
  5737. sizeof(packed_addr));
  5738. #ifdef USE_INET_ATON_WEAKLINK
  5739. }
  5740. #endif
  5741. #endif
  5742. }
  5743. #ifdef HAVE_INET_NTOA
  5744. PyDoc_STRVAR(inet_ntoa_doc,
  5745. "inet_ntoa(packed_ip) -> ip_address_string\n\
  5746. \n\
  5747. Convert an IP address from 32-bit packed binary format to string format");
  5748. static PyObject*
  5749. socket_inet_ntoa(PyObject *self, PyObject *args)
  5750. {
  5751. Py_buffer packed_ip;
  5752. struct in_addr packed_addr;
  5753. if (!PyArg_ParseTuple(args, "y*:inet_ntoa", &packed_ip)) {
  5754. return NULL;
  5755. }
  5756. if (packed_ip.len != sizeof(packed_addr)) {
  5757. PyErr_SetString(PyExc_OSError,
  5758. "packed IP wrong length for inet_ntoa");
  5759. PyBuffer_Release(&packed_ip);
  5760. return NULL;
  5761. }
  5762. memcpy(&packed_addr, packed_ip.buf, packed_ip.len);
  5763. PyBuffer_Release(&packed_ip);
  5764. SUPPRESS_DEPRECATED_CALL
  5765. return PyUnicode_FromString(inet_ntoa(packed_addr));
  5766. }
  5767. #endif // HAVE_INET_NTOA
  5768. #ifdef HAVE_INET_PTON
  5769. PyDoc_STRVAR(inet_pton_doc,
  5770. "inet_pton(af, ip) -> packed IP address string\n\
  5771. \n\
  5772. Convert an IP address from string format to a packed string suitable\n\
  5773. for use with low-level network functions.");
  5774. static PyObject *
  5775. socket_inet_pton(PyObject *self, PyObject *args)
  5776. {
  5777. int af;
  5778. const char* ip;
  5779. int retval;
  5780. #ifdef ENABLE_IPV6
  5781. char packed[Py_MAX(sizeof(struct in_addr), sizeof(struct in6_addr))];
  5782. #else
  5783. char packed[sizeof(struct in_addr)];
  5784. #endif
  5785. if (!PyArg_ParseTuple(args, "is:inet_pton", &af, &ip)) {
  5786. return NULL;
  5787. }
  5788. #if !defined(ENABLE_IPV6) && defined(AF_INET6)
  5789. if(af == AF_INET6) {
  5790. PyErr_SetString(PyExc_OSError,
  5791. "can't use AF_INET6, IPv6 is disabled");
  5792. return NULL;
  5793. }
  5794. #endif
  5795. retval = inet_pton(af, ip, packed);
  5796. if (retval < 0) {
  5797. PyErr_SetFromErrno(PyExc_OSError);
  5798. return NULL;
  5799. } else if (retval == 0) {
  5800. PyErr_SetString(PyExc_OSError,
  5801. "illegal IP address string passed to inet_pton");
  5802. return NULL;
  5803. } else if (af == AF_INET) {
  5804. return PyBytes_FromStringAndSize(packed,
  5805. sizeof(struct in_addr));
  5806. #ifdef ENABLE_IPV6
  5807. } else if (af == AF_INET6) {
  5808. return PyBytes_FromStringAndSize(packed,
  5809. sizeof(struct in6_addr));
  5810. #endif
  5811. } else {
  5812. PyErr_SetString(PyExc_OSError, "unknown address family");
  5813. return NULL;
  5814. }
  5815. }
  5816. PyDoc_STRVAR(inet_ntop_doc,
  5817. "inet_ntop(af, packed_ip) -> string formatted IP address\n\
  5818. \n\
  5819. Convert a packed IP address of the given family to string format.");
  5820. static PyObject *
  5821. socket_inet_ntop(PyObject *self, PyObject *args)
  5822. {
  5823. int af;
  5824. Py_buffer packed_ip;
  5825. const char* retval;
  5826. #ifdef ENABLE_IPV6
  5827. char ip[Py_MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN)];
  5828. #else
  5829. char ip[INET_ADDRSTRLEN];
  5830. #endif
  5831. if (!PyArg_ParseTuple(args, "iy*:inet_ntop", &af, &packed_ip)) {
  5832. return NULL;
  5833. }
  5834. if (af == AF_INET) {
  5835. if (packed_ip.len != sizeof(struct in_addr)) {
  5836. PyErr_SetString(PyExc_ValueError,
  5837. "invalid length of packed IP address string");
  5838. PyBuffer_Release(&packed_ip);
  5839. return NULL;
  5840. }
  5841. #ifdef ENABLE_IPV6
  5842. } else if (af == AF_INET6) {
  5843. if (packed_ip.len != sizeof(struct in6_addr)) {
  5844. PyErr_SetString(PyExc_ValueError,
  5845. "invalid length of packed IP address string");
  5846. PyBuffer_Release(&packed_ip);
  5847. return NULL;
  5848. }
  5849. #endif
  5850. } else {
  5851. PyErr_Format(PyExc_ValueError,
  5852. "unknown address family %d", af);
  5853. PyBuffer_Release(&packed_ip);
  5854. return NULL;
  5855. }
  5856. /* inet_ntop guarantee NUL-termination of resulting string. */
  5857. retval = inet_ntop(af, packed_ip.buf, ip, sizeof(ip));
  5858. if (!retval) {
  5859. PyErr_SetFromErrno(PyExc_OSError);
  5860. PyBuffer_Release(&packed_ip);
  5861. return NULL;
  5862. } else {
  5863. PyBuffer_Release(&packed_ip);
  5864. return PyUnicode_FromString(retval);
  5865. }
  5866. }
  5867. #endif /* HAVE_INET_PTON */
  5868. #ifdef HAVE_GETADDRINFO
  5869. /* Python interface to getaddrinfo(host, port). */
  5870. /*ARGSUSED*/
  5871. static PyObject *
  5872. socket_getaddrinfo(PyObject *self, PyObject *args, PyObject* kwargs)
  5873. {
  5874. static char* kwnames[] = {"host", "port", "family", "type", "proto",
  5875. "flags", 0};
  5876. struct addrinfo hints, *res;
  5877. struct addrinfo *res0 = NULL;
  5878. PyObject *hobj = NULL;
  5879. PyObject *pobj = (PyObject *)NULL;
  5880. PyObject *pstr = NULL;
  5881. const char *hptr, *pptr;
  5882. int family, socktype, protocol, flags;
  5883. int error;
  5884. PyObject *all = (PyObject *)NULL;
  5885. PyObject *idna = NULL;
  5886. socktype = protocol = flags = 0;
  5887. family = AF_UNSPEC;
  5888. if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO|iiii:getaddrinfo",
  5889. kwnames, &hobj, &pobj, &family, &socktype,
  5890. &protocol, &flags)) {
  5891. return NULL;
  5892. }
  5893. if (hobj == Py_None) {
  5894. hptr = NULL;
  5895. } else if (PyUnicode_Check(hobj)) {
  5896. idna = PyUnicode_AsEncodedString(hobj, "idna", NULL);
  5897. if (!idna)
  5898. return NULL;
  5899. assert(PyBytes_Check(idna));
  5900. hptr = PyBytes_AS_STRING(idna);
  5901. } else if (PyBytes_Check(hobj)) {
  5902. hptr = PyBytes_AsString(hobj);
  5903. } else {
  5904. PyErr_SetString(PyExc_TypeError,
  5905. "getaddrinfo() argument 1 must be string or None");
  5906. return NULL;
  5907. }
  5908. if (PyLong_CheckExact(pobj)) {
  5909. pstr = PyObject_Str(pobj);
  5910. if (pstr == NULL)
  5911. goto err;
  5912. assert(PyUnicode_Check(pstr));
  5913. pptr = PyUnicode_AsUTF8(pstr);
  5914. if (pptr == NULL)
  5915. goto err;
  5916. } else if (PyUnicode_Check(pobj)) {
  5917. pptr = PyUnicode_AsUTF8(pobj);
  5918. if (pptr == NULL)
  5919. goto err;
  5920. } else if (PyBytes_Check(pobj)) {
  5921. pptr = PyBytes_AS_STRING(pobj);
  5922. } else if (pobj == Py_None) {
  5923. pptr = (char *)NULL;
  5924. } else {
  5925. PyErr_SetString(PyExc_OSError, "Int or String expected");
  5926. goto err;
  5927. }
  5928. #if defined(__APPLE__) && defined(AI_NUMERICSERV)
  5929. if ((flags & AI_NUMERICSERV) && (pptr == NULL || (pptr[0] == '0' && pptr[1] == 0))) {
  5930. /* On OSX up to at least OSX 10.8 getaddrinfo crashes
  5931. * if AI_NUMERICSERV is set and the servname is NULL or "0".
  5932. * This workaround avoids a segfault in libsystem.
  5933. */
  5934. pptr = "00";
  5935. }
  5936. #endif
  5937. if (PySys_Audit("socket.getaddrinfo", "OOiii",
  5938. hobj, pobj, family, socktype, protocol) < 0) {
  5939. return NULL;
  5940. }
  5941. memset(&hints, 0, sizeof(hints));
  5942. hints.ai_family = family;
  5943. hints.ai_socktype = socktype;
  5944. hints.ai_protocol = protocol;
  5945. hints.ai_flags = flags;
  5946. Py_BEGIN_ALLOW_THREADS
  5947. error = getaddrinfo(hptr, pptr, &hints, &res0);
  5948. Py_END_ALLOW_THREADS
  5949. if (error) {
  5950. res0 = NULL; // gh-100795
  5951. socket_state *state = get_module_state(self);
  5952. set_gaierror(state, error);
  5953. goto err;
  5954. }
  5955. all = PyList_New(0);
  5956. if (all == NULL)
  5957. goto err;
  5958. for (res = res0; res; res = res->ai_next) {
  5959. PyObject *single;
  5960. PyObject *addr =
  5961. makesockaddr(-1, res->ai_addr, res->ai_addrlen, protocol);
  5962. if (addr == NULL)
  5963. goto err;
  5964. single = Py_BuildValue("iiisO", res->ai_family,
  5965. res->ai_socktype, res->ai_protocol,
  5966. res->ai_canonname ? res->ai_canonname : "",
  5967. addr);
  5968. Py_DECREF(addr);
  5969. if (single == NULL)
  5970. goto err;
  5971. if (PyList_Append(all, single)) {
  5972. Py_DECREF(single);
  5973. goto err;
  5974. }
  5975. Py_DECREF(single);
  5976. }
  5977. Py_XDECREF(idna);
  5978. Py_XDECREF(pstr);
  5979. if (res0)
  5980. freeaddrinfo(res0);
  5981. return all;
  5982. err:
  5983. Py_XDECREF(all);
  5984. Py_XDECREF(idna);
  5985. Py_XDECREF(pstr);
  5986. if (res0)
  5987. freeaddrinfo(res0);
  5988. return (PyObject *)NULL;
  5989. }
  5990. PyDoc_STRVAR(getaddrinfo_doc,
  5991. "getaddrinfo(host, port [, family, type, proto, flags])\n\
  5992. -> list of (family, type, proto, canonname, sockaddr)\n\
  5993. \n\
  5994. Resolve host and port into addrinfo struct.");
  5995. #endif // HAVE_GETADDRINFO
  5996. #ifdef HAVE_GETNAMEINFO
  5997. /* Python interface to getnameinfo(sa, flags). */
  5998. /*ARGSUSED*/
  5999. static PyObject *
  6000. socket_getnameinfo(PyObject *self, PyObject *args)
  6001. {
  6002. PyObject *sa = (PyObject *)NULL;
  6003. int flags;
  6004. const char *hostp;
  6005. int port;
  6006. unsigned int flowinfo, scope_id;
  6007. char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV];
  6008. struct addrinfo hints, *res = NULL;
  6009. int error;
  6010. PyObject *ret = (PyObject *)NULL;
  6011. PyObject *name;
  6012. flags = flowinfo = scope_id = 0;
  6013. if (!PyArg_ParseTuple(args, "Oi:getnameinfo", &sa, &flags))
  6014. return NULL;
  6015. if (!PyTuple_Check(sa)) {
  6016. PyErr_SetString(PyExc_TypeError,
  6017. "getnameinfo() argument 1 must be a tuple");
  6018. return NULL;
  6019. }
  6020. if (!PyArg_ParseTuple(sa, "si|II;getnameinfo(): illegal sockaddr argument",
  6021. &hostp, &port, &flowinfo, &scope_id))
  6022. {
  6023. return NULL;
  6024. }
  6025. if (flowinfo > 0xfffff) {
  6026. PyErr_SetString(PyExc_OverflowError,
  6027. "getnameinfo(): flowinfo must be 0-1048575.");
  6028. return NULL;
  6029. }
  6030. if (PySys_Audit("socket.getnameinfo", "(O)", sa) < 0) {
  6031. return NULL;
  6032. }
  6033. PyOS_snprintf(pbuf, sizeof(pbuf), "%d", port);
  6034. memset(&hints, 0, sizeof(hints));
  6035. hints.ai_family = AF_UNSPEC;
  6036. hints.ai_socktype = SOCK_DGRAM; /* make numeric port happy */
  6037. hints.ai_flags = AI_NUMERICHOST; /* don't do any name resolution */
  6038. Py_BEGIN_ALLOW_THREADS
  6039. error = getaddrinfo(hostp, pbuf, &hints, &res);
  6040. Py_END_ALLOW_THREADS
  6041. if (error) {
  6042. res = NULL; // gh-100795
  6043. socket_state *state = get_module_state(self);
  6044. set_gaierror(state, error);
  6045. goto fail;
  6046. }
  6047. if (res->ai_next) {
  6048. PyErr_SetString(PyExc_OSError,
  6049. "sockaddr resolved to multiple addresses");
  6050. goto fail;
  6051. }
  6052. switch (res->ai_family) {
  6053. case AF_INET:
  6054. {
  6055. if (PyTuple_GET_SIZE(sa) != 2) {
  6056. PyErr_SetString(PyExc_OSError,
  6057. "IPv4 sockaddr must be 2 tuple");
  6058. goto fail;
  6059. }
  6060. break;
  6061. }
  6062. #ifdef ENABLE_IPV6
  6063. case AF_INET6:
  6064. {
  6065. struct sockaddr_in6 *sin6;
  6066. sin6 = (struct sockaddr_in6 *)res->ai_addr;
  6067. sin6->sin6_flowinfo = htonl(flowinfo);
  6068. sin6->sin6_scope_id = scope_id;
  6069. break;
  6070. }
  6071. #endif
  6072. }
  6073. Py_BEGIN_ALLOW_THREADS
  6074. error = getnameinfo(res->ai_addr, (socklen_t) res->ai_addrlen,
  6075. hbuf, sizeof(hbuf), pbuf, sizeof(pbuf), flags);
  6076. Py_END_ALLOW_THREADS
  6077. if (error) {
  6078. socket_state *state = get_module_state(self);
  6079. set_gaierror(state, error);
  6080. goto fail;
  6081. }
  6082. name = sock_decode_hostname(hbuf);
  6083. if (name == NULL)
  6084. goto fail;
  6085. ret = Py_BuildValue("Ns", name, pbuf);
  6086. fail:
  6087. if (res)
  6088. freeaddrinfo(res);
  6089. return ret;
  6090. }
  6091. PyDoc_STRVAR(getnameinfo_doc,
  6092. "getnameinfo(sockaddr, flags) --> (host, port)\n\
  6093. \n\
  6094. Get host and port for a sockaddr.");
  6095. #endif // HAVE_GETNAMEINFO
  6096. /* Python API to getting and setting the default timeout value. */
  6097. static PyObject *
  6098. socket_getdefaulttimeout(PyObject *self, PyObject *Py_UNUSED(ignored))
  6099. {
  6100. socket_state *state = get_module_state(self);
  6101. if (state->defaulttimeout < 0) {
  6102. Py_RETURN_NONE;
  6103. }
  6104. else {
  6105. double seconds = _PyTime_AsSecondsDouble(state->defaulttimeout);
  6106. return PyFloat_FromDouble(seconds);
  6107. }
  6108. }
  6109. PyDoc_STRVAR(getdefaulttimeout_doc,
  6110. "getdefaulttimeout() -> timeout\n\
  6111. \n\
  6112. Returns the default timeout in seconds (float) for new socket objects.\n\
  6113. A value of None indicates that new socket objects have no timeout.\n\
  6114. When the socket module is first imported, the default is None.");
  6115. static PyObject *
  6116. socket_setdefaulttimeout(PyObject *self, PyObject *arg)
  6117. {
  6118. _PyTime_t timeout;
  6119. if (socket_parse_timeout(&timeout, arg) < 0)
  6120. return NULL;
  6121. socket_state *state = get_module_state(self);
  6122. state->defaulttimeout = timeout;
  6123. Py_RETURN_NONE;
  6124. }
  6125. PyDoc_STRVAR(setdefaulttimeout_doc,
  6126. "setdefaulttimeout(timeout)\n\
  6127. \n\
  6128. Set the default timeout in seconds (float) for new socket objects.\n\
  6129. A value of None indicates that new socket objects have no timeout.\n\
  6130. When the socket module is first imported, the default is None.");
  6131. #if defined(HAVE_IF_NAMEINDEX) || defined(MS_WINDOWS)
  6132. /* Python API for getting interface indices and names */
  6133. static PyObject *
  6134. socket_if_nameindex(PyObject *self, PyObject *arg)
  6135. {
  6136. PyObject *list = PyList_New(0);
  6137. if (list == NULL) {
  6138. return NULL;
  6139. }
  6140. #ifdef MS_WINDOWS
  6141. PMIB_IF_TABLE2 tbl;
  6142. int ret;
  6143. if ((ret = GetIfTable2Ex(MibIfTableRaw, &tbl)) != NO_ERROR) {
  6144. Py_DECREF(list);
  6145. // ret is used instead of GetLastError()
  6146. return PyErr_SetFromWindowsErr(ret);
  6147. }
  6148. for (ULONG i = 0; i < tbl->NumEntries; ++i) {
  6149. MIB_IF_ROW2 r = tbl->Table[i];
  6150. WCHAR buf[NDIS_IF_MAX_STRING_SIZE + 1];
  6151. if ((ret = ConvertInterfaceLuidToNameW(&r.InterfaceLuid, buf,
  6152. Py_ARRAY_LENGTH(buf)))) {
  6153. Py_DECREF(list);
  6154. FreeMibTable(tbl);
  6155. // ret is used instead of GetLastError()
  6156. return PyErr_SetFromWindowsErr(ret);
  6157. }
  6158. PyObject *tuple = Py_BuildValue("Iu", r.InterfaceIndex, buf);
  6159. if (tuple == NULL || PyList_Append(list, tuple) == -1) {
  6160. Py_XDECREF(tuple);
  6161. Py_DECREF(list);
  6162. FreeMibTable(tbl);
  6163. return NULL;
  6164. }
  6165. Py_DECREF(tuple);
  6166. }
  6167. FreeMibTable(tbl);
  6168. return list;
  6169. #else
  6170. int i;
  6171. struct if_nameindex *ni;
  6172. ni = if_nameindex();
  6173. if (ni == NULL) {
  6174. PyErr_SetFromErrno(PyExc_OSError);
  6175. Py_DECREF(list);
  6176. return NULL;
  6177. }
  6178. #ifdef _Py_MEMORY_SANITIZER
  6179. __msan_unpoison(ni, sizeof(ni));
  6180. __msan_unpoison(&ni[0], sizeof(ni[0]));
  6181. #endif
  6182. for (i = 0; ni[i].if_index != 0 && i < INT_MAX; i++) {
  6183. #ifdef _Py_MEMORY_SANITIZER
  6184. /* This one isn't the end sentinel, the next one must exist. */
  6185. __msan_unpoison(&ni[i+1], sizeof(ni[0]));
  6186. /* Otherwise Py_BuildValue internals are flagged by MSan when
  6187. they access the not-msan-tracked if_name string data. */
  6188. {
  6189. char *to_sanitize = ni[i].if_name;
  6190. do {
  6191. __msan_unpoison(to_sanitize, 1);
  6192. } while (*to_sanitize++ != '\0');
  6193. }
  6194. #endif
  6195. PyObject *ni_tuple = Py_BuildValue("IO&",
  6196. ni[i].if_index, PyUnicode_DecodeFSDefault, ni[i].if_name);
  6197. if (ni_tuple == NULL || PyList_Append(list, ni_tuple) == -1) {
  6198. Py_XDECREF(ni_tuple);
  6199. Py_DECREF(list);
  6200. if_freenameindex(ni);
  6201. return NULL;
  6202. }
  6203. Py_DECREF(ni_tuple);
  6204. }
  6205. if_freenameindex(ni);
  6206. return list;
  6207. #endif
  6208. }
  6209. PyDoc_STRVAR(if_nameindex_doc,
  6210. "if_nameindex()\n\
  6211. \n\
  6212. Returns a list of network interface information (index, name) tuples.");
  6213. static PyObject *
  6214. socket_if_nametoindex(PyObject *self, PyObject *args)
  6215. {
  6216. PyObject *oname;
  6217. #ifdef MS_WINDOWS
  6218. NET_IFINDEX index;
  6219. #else
  6220. unsigned long index;
  6221. #endif
  6222. if (!PyArg_ParseTuple(args, "O&:if_nametoindex",
  6223. PyUnicode_FSConverter, &oname))
  6224. return NULL;
  6225. index = if_nametoindex(PyBytes_AS_STRING(oname));
  6226. Py_DECREF(oname);
  6227. if (index == 0) {
  6228. /* if_nametoindex() doesn't set errno */
  6229. PyErr_SetString(PyExc_OSError, "no interface with this name");
  6230. return NULL;
  6231. }
  6232. return PyLong_FromUnsignedLong(index);
  6233. }
  6234. PyDoc_STRVAR(if_nametoindex_doc,
  6235. "if_nametoindex(if_name)\n\
  6236. \n\
  6237. Returns the interface index corresponding to the interface name if_name.");
  6238. static PyObject *
  6239. socket_if_indextoname(PyObject *self, PyObject *arg)
  6240. {
  6241. unsigned long index_long = PyLong_AsUnsignedLong(arg);
  6242. if (index_long == (unsigned long) -1 && PyErr_Occurred()) {
  6243. return NULL;
  6244. }
  6245. #ifdef MS_WINDOWS
  6246. NET_IFINDEX index = (NET_IFINDEX)index_long;
  6247. #else
  6248. unsigned int index = (unsigned int)index_long;
  6249. #endif
  6250. if ((unsigned long)index != index_long) {
  6251. PyErr_SetString(PyExc_OverflowError, "index is too large");
  6252. return NULL;
  6253. }
  6254. char name[IF_NAMESIZE + 1];
  6255. if (if_indextoname(index, name) == NULL) {
  6256. PyErr_SetFromErrno(PyExc_OSError);
  6257. return NULL;
  6258. }
  6259. return PyUnicode_DecodeFSDefault(name);
  6260. }
  6261. PyDoc_STRVAR(if_indextoname_doc,
  6262. "if_indextoname(if_index)\n\
  6263. \n\
  6264. Returns the interface name corresponding to the interface index if_index.");
  6265. #endif // defined(HAVE_IF_NAMEINDEX) || defined(MS_WINDOWS)
  6266. #ifdef CMSG_LEN
  6267. /* Python interface to CMSG_LEN(length). */
  6268. static PyObject *
  6269. socket_CMSG_LEN(PyObject *self, PyObject *args)
  6270. {
  6271. Py_ssize_t length;
  6272. size_t result;
  6273. if (!PyArg_ParseTuple(args, "n:CMSG_LEN", &length))
  6274. return NULL;
  6275. if (length < 0 || !get_CMSG_LEN(length, &result)) {
  6276. PyErr_Format(PyExc_OverflowError, "CMSG_LEN() argument out of range");
  6277. return NULL;
  6278. }
  6279. return PyLong_FromSize_t(result);
  6280. }
  6281. PyDoc_STRVAR(CMSG_LEN_doc,
  6282. "CMSG_LEN(length) -> control message length\n\
  6283. \n\
  6284. Return the total length, without trailing padding, of an ancillary\n\
  6285. data item with associated data of the given length. This value can\n\
  6286. often be used as the buffer size for recvmsg() to receive a single\n\
  6287. item of ancillary data, but RFC 3542 requires portable applications to\n\
  6288. use CMSG_SPACE() and thus include space for padding, even when the\n\
  6289. item will be the last in the buffer. Raises OverflowError if length\n\
  6290. is outside the permissible range of values.");
  6291. #ifdef CMSG_SPACE
  6292. /* Python interface to CMSG_SPACE(length). */
  6293. static PyObject *
  6294. socket_CMSG_SPACE(PyObject *self, PyObject *args)
  6295. {
  6296. Py_ssize_t length;
  6297. size_t result;
  6298. if (!PyArg_ParseTuple(args, "n:CMSG_SPACE", &length))
  6299. return NULL;
  6300. if (length < 0 || !get_CMSG_SPACE(length, &result)) {
  6301. PyErr_SetString(PyExc_OverflowError,
  6302. "CMSG_SPACE() argument out of range");
  6303. return NULL;
  6304. }
  6305. return PyLong_FromSize_t(result);
  6306. }
  6307. PyDoc_STRVAR(CMSG_SPACE_doc,
  6308. "CMSG_SPACE(length) -> buffer size\n\
  6309. \n\
  6310. Return the buffer size needed for recvmsg() to receive an ancillary\n\
  6311. data item with associated data of the given length, along with any\n\
  6312. trailing padding. The buffer space needed to receive multiple items\n\
  6313. is the sum of the CMSG_SPACE() values for their associated data\n\
  6314. lengths. Raises OverflowError if length is outside the permissible\n\
  6315. range of values.");
  6316. #endif /* CMSG_SPACE */
  6317. #endif /* CMSG_LEN */
  6318. /* List of functions exported by this module. */
  6319. static PyMethodDef socket_methods[] = {
  6320. #ifdef HAVE_GETADDRINFO
  6321. {"gethostbyname", socket_gethostbyname,
  6322. METH_VARARGS, gethostbyname_doc},
  6323. #endif
  6324. #if defined(HAVE_GETHOSTBYNAME_R) || defined (HAVE_GETHOSTBYNAME)
  6325. {"gethostbyname_ex", socket_gethostbyname_ex,
  6326. METH_VARARGS, ghbn_ex_doc},
  6327. #endif
  6328. #if defined(HAVE_GETHOSTBYNAME_R) || defined (HAVE_GETHOSTBYADDR)
  6329. {"gethostbyaddr", socket_gethostbyaddr,
  6330. METH_VARARGS, gethostbyaddr_doc},
  6331. #endif
  6332. #ifdef HAVE_GETHOSTNAME
  6333. {"gethostname", socket_gethostname,
  6334. METH_NOARGS, gethostname_doc},
  6335. #endif
  6336. #ifdef HAVE_SETHOSTNAME
  6337. {"sethostname", socket_sethostname,
  6338. METH_VARARGS, sethostname_doc},
  6339. #endif
  6340. #ifdef HAVE_GETSERVBYNAME
  6341. {"getservbyname", socket_getservbyname,
  6342. METH_VARARGS, getservbyname_doc},
  6343. #endif
  6344. #ifdef HAVE_GETSERVBYPORT
  6345. {"getservbyport", socket_getservbyport,
  6346. METH_VARARGS, getservbyport_doc},
  6347. #endif
  6348. #ifdef HAVE_GETPROTOBYNAME
  6349. {"getprotobyname", socket_getprotobyname,
  6350. METH_VARARGS, getprotobyname_doc},
  6351. #endif
  6352. {"close", socket_close,
  6353. METH_O, close_doc},
  6354. #ifndef NO_DUP
  6355. {"dup", socket_dup,
  6356. METH_O, dup_doc},
  6357. #endif
  6358. #ifdef HAVE_SOCKETPAIR
  6359. {"socketpair", socket_socketpair,
  6360. METH_VARARGS, socketpair_doc},
  6361. #endif
  6362. {"ntohs", socket_ntohs,
  6363. METH_VARARGS, ntohs_doc},
  6364. {"ntohl", socket_ntohl,
  6365. METH_O, ntohl_doc},
  6366. {"htons", socket_htons,
  6367. METH_VARARGS, htons_doc},
  6368. {"htonl", socket_htonl,
  6369. METH_O, htonl_doc},
  6370. {"inet_aton", socket_inet_aton,
  6371. METH_VARARGS, inet_aton_doc},
  6372. #ifdef HAVE_INET_NTOA
  6373. {"inet_ntoa", socket_inet_ntoa,
  6374. METH_VARARGS, inet_ntoa_doc},
  6375. #endif
  6376. #ifdef HAVE_INET_PTON
  6377. {"inet_pton", socket_inet_pton,
  6378. METH_VARARGS, inet_pton_doc},
  6379. {"inet_ntop", socket_inet_ntop,
  6380. METH_VARARGS, inet_ntop_doc},
  6381. #endif
  6382. #ifdef HAVE_GETADDRINFO
  6383. {"getaddrinfo", _PyCFunction_CAST(socket_getaddrinfo),
  6384. METH_VARARGS | METH_KEYWORDS, getaddrinfo_doc},
  6385. #endif
  6386. #ifdef HAVE_GETNAMEINFO
  6387. {"getnameinfo", socket_getnameinfo,
  6388. METH_VARARGS, getnameinfo_doc},
  6389. #endif
  6390. {"getdefaulttimeout", socket_getdefaulttimeout,
  6391. METH_NOARGS, getdefaulttimeout_doc},
  6392. {"setdefaulttimeout", socket_setdefaulttimeout,
  6393. METH_O, setdefaulttimeout_doc},
  6394. #if defined(HAVE_IF_NAMEINDEX) || defined(MS_WINDOWS)
  6395. {"if_nameindex", socket_if_nameindex,
  6396. METH_NOARGS, if_nameindex_doc},
  6397. {"if_nametoindex", socket_if_nametoindex,
  6398. METH_VARARGS, if_nametoindex_doc},
  6399. {"if_indextoname", socket_if_indextoname,
  6400. METH_O, if_indextoname_doc},
  6401. #endif
  6402. #ifdef CMSG_LEN
  6403. {"CMSG_LEN", socket_CMSG_LEN,
  6404. METH_VARARGS, CMSG_LEN_doc},
  6405. #ifdef CMSG_SPACE
  6406. {"CMSG_SPACE", socket_CMSG_SPACE,
  6407. METH_VARARGS, CMSG_SPACE_doc},
  6408. #endif
  6409. #endif
  6410. {NULL, NULL} /* Sentinel */
  6411. };
  6412. #ifdef MS_WINDOWS
  6413. #define OS_INIT_DEFINED
  6414. /* Additional initialization and cleanup for Windows */
  6415. static void
  6416. os_cleanup(void)
  6417. {
  6418. WSACleanup();
  6419. }
  6420. static int
  6421. os_init(void)
  6422. {
  6423. WSADATA WSAData;
  6424. int ret;
  6425. ret = WSAStartup(0x0101, &WSAData);
  6426. switch (ret) {
  6427. case 0: /* No error */
  6428. Py_AtExit(os_cleanup);
  6429. return 1; /* Success */
  6430. case WSASYSNOTREADY:
  6431. PyErr_SetString(PyExc_ImportError,
  6432. "WSAStartup failed: network not ready");
  6433. break;
  6434. case WSAVERNOTSUPPORTED:
  6435. case WSAEINVAL:
  6436. PyErr_SetString(
  6437. PyExc_ImportError,
  6438. "WSAStartup failed: requested version not supported");
  6439. break;
  6440. default:
  6441. PyErr_Format(PyExc_ImportError, "WSAStartup failed: error code %d", ret);
  6442. break;
  6443. }
  6444. return 0; /* Failure */
  6445. }
  6446. #endif /* MS_WINDOWS */
  6447. #ifndef OS_INIT_DEFINED
  6448. static int
  6449. os_init(void)
  6450. {
  6451. return 1; /* Success */
  6452. }
  6453. #endif
  6454. static void
  6455. sock_free_api(PySocketModule_APIObject *capi)
  6456. {
  6457. Py_DECREF(capi->Sock_Type);
  6458. Py_DECREF(capi->error);
  6459. Py_DECREF(capi->timeout_error);
  6460. PyMem_Free(capi);
  6461. }
  6462. static void
  6463. sock_destroy_api(PyObject *capsule)
  6464. {
  6465. void *capi = PyCapsule_GetPointer(capsule, PySocket_CAPSULE_NAME);
  6466. sock_free_api(capi);
  6467. }
  6468. static PySocketModule_APIObject *
  6469. sock_get_api(socket_state *state)
  6470. {
  6471. PySocketModule_APIObject *capi = PyMem_Malloc(sizeof(PySocketModule_APIObject));
  6472. if (capi == NULL) {
  6473. PyErr_NoMemory();
  6474. return NULL;
  6475. }
  6476. capi->Sock_Type = (PyTypeObject *)Py_NewRef(state->sock_type);
  6477. capi->error = Py_NewRef(PyExc_OSError);
  6478. capi->timeout_error = Py_NewRef(PyExc_TimeoutError);
  6479. return capi;
  6480. }
  6481. /* Initialize the _socket module.
  6482. This module is actually called "_socket", and there's a wrapper
  6483. "socket.py" which implements some additional functionality.
  6484. The import of "_socket" may fail with an ImportError exception if
  6485. os-specific initialization fails. On Windows, this does WINSOCK
  6486. initialization. When WINSOCK is initialized successfully, a call to
  6487. WSACleanup() is scheduled to be made at exit time.
  6488. */
  6489. PyDoc_STRVAR(socket_doc,
  6490. "Implementation module for socket operations.\n\
  6491. \n\
  6492. See the socket module for documentation.");
  6493. static int
  6494. socket_exec(PyObject *m)
  6495. {
  6496. if (!os_init()) {
  6497. goto error;
  6498. }
  6499. socket_state *state = get_module_state(m);
  6500. state->defaulttimeout = _PYTIME_FROMSECONDS(-1);
  6501. #if defined(HAVE_ACCEPT) || defined(HAVE_ACCEPT4)
  6502. #if defined(HAVE_ACCEPT4) && defined(SOCK_CLOEXEC)
  6503. state->accept4_works = -1;
  6504. #endif
  6505. #endif
  6506. #ifdef SOCK_CLOEXEC
  6507. state->sock_cloexec_works = -1;
  6508. #endif
  6509. #define ADD_EXC(MOD, NAME, VAR, BASE) do { \
  6510. VAR = PyErr_NewException("socket." NAME, BASE, NULL); \
  6511. if (VAR == NULL) { \
  6512. goto error; \
  6513. } \
  6514. if (PyModule_AddObjectRef(MOD, NAME, VAR) < 0) { \
  6515. goto error; \
  6516. } \
  6517. } while (0)
  6518. ADD_EXC(m, "herror", state->socket_herror, PyExc_OSError);
  6519. ADD_EXC(m, "gaierror", state->socket_gaierror, PyExc_OSError);
  6520. #undef ADD_EXC
  6521. if (PyModule_AddObjectRef(m, "error", PyExc_OSError) < 0) {
  6522. goto error;
  6523. }
  6524. if (PyModule_AddObjectRef(m, "timeout", PyExc_TimeoutError) < 0) {
  6525. goto error;
  6526. }
  6527. PyObject *sock_type = PyType_FromMetaclass(NULL, m, &sock_spec, NULL);
  6528. if (sock_type == NULL) {
  6529. goto error;
  6530. }
  6531. state->sock_type = (PyTypeObject *)sock_type;
  6532. if (PyModule_AddObjectRef(m, "SocketType", sock_type) < 0) {
  6533. goto error;
  6534. }
  6535. if (PyModule_AddType(m, state->sock_type) < 0) {
  6536. goto error;
  6537. }
  6538. PyObject *has_ipv6;
  6539. #ifdef ENABLE_IPV6
  6540. has_ipv6 = Py_True;
  6541. #else
  6542. has_ipv6 = Py_False;
  6543. #endif
  6544. if (PyModule_AddObjectRef(m, "has_ipv6", has_ipv6) < 0) {
  6545. goto error;
  6546. }
  6547. /* Export C API */
  6548. PySocketModule_APIObject *capi = sock_get_api(state);
  6549. if (capi == NULL) {
  6550. goto error;
  6551. }
  6552. PyObject *capsule = PyCapsule_New(capi,
  6553. PySocket_CAPSULE_NAME,
  6554. sock_destroy_api);
  6555. if (capsule == NULL) {
  6556. sock_free_api(capi);
  6557. goto error;
  6558. }
  6559. int rc = PyModule_AddObjectRef(m, PySocket_CAPI_NAME, capsule);
  6560. Py_DECREF(capsule);
  6561. if (rc < 0) {
  6562. goto error;
  6563. }
  6564. #define ADD_INT_MACRO(MOD, INT) do { \
  6565. if (PyModule_AddIntConstant(MOD, #INT, INT) < 0) { \
  6566. goto error; \
  6567. } \
  6568. } while (0)
  6569. #define ADD_INT_CONST(MOD, NAME, INT) do { \
  6570. if (PyModule_AddIntConstant(MOD, NAME, INT) < 0) { \
  6571. goto error; \
  6572. } \
  6573. } while (0)
  6574. #define ADD_STR_CONST(MOD, NAME, STR) do { \
  6575. if (PyModule_AddStringConstant(MOD, NAME, STR) < 0) { \
  6576. goto error; \
  6577. } \
  6578. } while (0)
  6579. /* Address families (we only support AF_INET and AF_UNIX) */
  6580. #ifdef AF_UNSPEC
  6581. ADD_INT_MACRO(m, AF_UNSPEC);
  6582. #endif
  6583. ADD_INT_MACRO(m, AF_INET);
  6584. #if defined(AF_UNIX)
  6585. ADD_INT_MACRO(m, AF_UNIX);
  6586. #endif /* AF_UNIX */
  6587. #ifdef AF_AX25
  6588. /* Amateur Radio AX.25 */
  6589. ADD_INT_MACRO(m, AF_AX25);
  6590. #endif
  6591. #ifdef AF_IPX
  6592. ADD_INT_MACRO(m, AF_IPX); /* Novell IPX */
  6593. #endif
  6594. #ifdef AF_APPLETALK
  6595. /* Appletalk DDP */
  6596. ADD_INT_MACRO(m, AF_APPLETALK);
  6597. #endif
  6598. #ifdef AF_NETROM
  6599. /* Amateur radio NetROM */
  6600. ADD_INT_MACRO(m, AF_NETROM);
  6601. #endif
  6602. #ifdef AF_BRIDGE
  6603. /* Multiprotocol bridge */
  6604. ADD_INT_MACRO(m, AF_BRIDGE);
  6605. #endif
  6606. #ifdef AF_ATMPVC
  6607. /* ATM PVCs */
  6608. ADD_INT_MACRO(m, AF_ATMPVC);
  6609. #endif
  6610. #ifdef AF_AAL5
  6611. /* Reserved for Werner's ATM */
  6612. ADD_INT_MACRO(m, AF_AAL5);
  6613. #endif
  6614. #ifdef HAVE_SOCKADDR_ALG
  6615. ADD_INT_MACRO(m, AF_ALG); /* Linux crypto */
  6616. #endif
  6617. #ifdef AF_X25
  6618. /* Reserved for X.25 project */
  6619. ADD_INT_MACRO(m, AF_X25);
  6620. #endif
  6621. #ifdef AF_INET6
  6622. ADD_INT_MACRO(m, AF_INET6); /* IP version 6 */
  6623. #endif
  6624. #ifdef AF_ROSE
  6625. /* Amateur Radio X.25 PLP */
  6626. ADD_INT_MACRO(m, AF_ROSE);
  6627. #endif
  6628. #ifdef AF_DECnet
  6629. /* Reserved for DECnet project */
  6630. ADD_INT_MACRO(m, AF_DECnet);
  6631. #endif
  6632. #ifdef AF_NETBEUI
  6633. /* Reserved for 802.2LLC project */
  6634. ADD_INT_MACRO(m, AF_NETBEUI);
  6635. #endif
  6636. #ifdef AF_SECURITY
  6637. /* Security callback pseudo AF */
  6638. ADD_INT_MACRO(m, AF_SECURITY);
  6639. #endif
  6640. #ifdef AF_KEY
  6641. /* PF_KEY key management API */
  6642. ADD_INT_MACRO(m, AF_KEY);
  6643. #endif
  6644. #ifdef AF_NETLINK
  6645. /* */
  6646. ADD_INT_MACRO(m, AF_NETLINK);
  6647. ADD_INT_MACRO(m, NETLINK_ROUTE);
  6648. #ifdef NETLINK_SKIP
  6649. ADD_INT_MACRO(m, NETLINK_SKIP);
  6650. #endif
  6651. #ifdef NETLINK_W1
  6652. ADD_INT_MACRO(m, NETLINK_W1);
  6653. #endif
  6654. ADD_INT_MACRO(m, NETLINK_USERSOCK);
  6655. ADD_INT_MACRO(m, NETLINK_FIREWALL);
  6656. #ifdef NETLINK_TCPDIAG
  6657. ADD_INT_MACRO(m, NETLINK_TCPDIAG);
  6658. #endif
  6659. #ifdef NETLINK_NFLOG
  6660. ADD_INT_MACRO(m, NETLINK_NFLOG);
  6661. #endif
  6662. #ifdef NETLINK_XFRM
  6663. ADD_INT_MACRO(m, NETLINK_XFRM);
  6664. #endif
  6665. #ifdef NETLINK_ARPD
  6666. ADD_INT_MACRO(m, NETLINK_ARPD);
  6667. #endif
  6668. #ifdef NETLINK_ROUTE6
  6669. ADD_INT_MACRO(m, NETLINK_ROUTE6);
  6670. #endif
  6671. ADD_INT_MACRO(m, NETLINK_IP6_FW);
  6672. #ifdef NETLINK_DNRTMSG
  6673. ADD_INT_MACRO(m, NETLINK_DNRTMSG);
  6674. #endif
  6675. #ifdef NETLINK_TAPBASE
  6676. ADD_INT_MACRO(m, NETLINK_TAPBASE);
  6677. #endif
  6678. #ifdef NETLINK_CRYPTO
  6679. ADD_INT_MACRO(m, NETLINK_CRYPTO);
  6680. #endif
  6681. #endif /* AF_NETLINK */
  6682. #ifdef AF_QIPCRTR
  6683. /* Qualcomm IPCROUTER */
  6684. ADD_INT_MACRO(m, AF_QIPCRTR);
  6685. #endif
  6686. #ifdef AF_VSOCK
  6687. ADD_INT_CONST(m, "AF_VSOCK", AF_VSOCK);
  6688. ADD_INT_CONST(m, "SO_VM_SOCKETS_BUFFER_SIZE", 0);
  6689. ADD_INT_CONST(m, "SO_VM_SOCKETS_BUFFER_MIN_SIZE", 1);
  6690. ADD_INT_CONST(m, "SO_VM_SOCKETS_BUFFER_MAX_SIZE", 2);
  6691. ADD_INT_CONST(m, "VMADDR_CID_ANY", 0xffffffff);
  6692. ADD_INT_CONST(m, "VMADDR_PORT_ANY", 0xffffffff);
  6693. ADD_INT_CONST(m, "VMADDR_CID_HOST", 2);
  6694. ADD_INT_CONST(m, "VM_SOCKETS_INVALID_VERSION", 0xffffffff);
  6695. ADD_INT_CONST(m, "IOCTL_VM_SOCKETS_GET_LOCAL_CID", _IO(7, 0xb9));
  6696. #endif
  6697. #ifdef AF_ROUTE
  6698. /* Alias to emulate 4.4BSD */
  6699. ADD_INT_MACRO(m, AF_ROUTE);
  6700. #endif
  6701. #ifdef AF_LINK
  6702. ADD_INT_MACRO(m, AF_LINK);
  6703. #endif
  6704. #ifdef AF_ASH
  6705. /* Ash */
  6706. ADD_INT_MACRO(m, AF_ASH);
  6707. #endif
  6708. #ifdef AF_ECONET
  6709. /* Acorn Econet */
  6710. ADD_INT_MACRO(m, AF_ECONET);
  6711. #endif
  6712. #ifdef AF_ATMSVC
  6713. /* ATM SVCs */
  6714. ADD_INT_MACRO(m, AF_ATMSVC);
  6715. #endif
  6716. #ifdef AF_SNA
  6717. /* Linux SNA Project (nutters!) */
  6718. ADD_INT_MACRO(m, AF_SNA);
  6719. #endif
  6720. #ifdef AF_IRDA
  6721. /* IRDA sockets */
  6722. ADD_INT_MACRO(m, AF_IRDA);
  6723. #endif
  6724. #ifdef AF_PPPOX
  6725. /* PPPoX sockets */
  6726. ADD_INT_MACRO(m, AF_PPPOX);
  6727. #endif
  6728. #ifdef AF_WANPIPE
  6729. /* Wanpipe API Sockets */
  6730. ADD_INT_MACRO(m, AF_WANPIPE);
  6731. #endif
  6732. #ifdef AF_LLC
  6733. /* Linux LLC */
  6734. ADD_INT_MACRO(m, AF_LLC);
  6735. #endif
  6736. #ifdef HAVE_AF_HYPERV
  6737. /* Hyper-V sockets */
  6738. ADD_INT_MACRO(m, AF_HYPERV);
  6739. /* for proto */
  6740. ADD_INT_MACRO(m, HV_PROTOCOL_RAW);
  6741. /* for setsockopt() */
  6742. ADD_INT_MACRO(m, HVSOCKET_CONNECT_TIMEOUT);
  6743. ADD_INT_MACRO(m, HVSOCKET_CONNECT_TIMEOUT_MAX);
  6744. ADD_INT_MACRO(m, HVSOCKET_CONNECTED_SUSPEND);
  6745. ADD_INT_MACRO(m, HVSOCKET_ADDRESS_FLAG_PASSTHRU);
  6746. /* for bind() or connect() */
  6747. ADD_STR_CONST(m, "HV_GUID_ZERO", "00000000-0000-0000-0000-000000000000");
  6748. ADD_STR_CONST(m, "HV_GUID_WILDCARD", "00000000-0000-0000-0000-000000000000");
  6749. ADD_STR_CONST(m, "HV_GUID_BROADCAST", "FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF");
  6750. ADD_STR_CONST(m, "HV_GUID_CHILDREN", "90DB8B89-0D35-4F79-8CE9-49EA0AC8B7CD");
  6751. ADD_STR_CONST(m, "HV_GUID_LOOPBACK", "E0E16197-DD56-4A10-9195-5EE7A155A838");
  6752. ADD_STR_CONST(m, "HV_GUID_PARENT", "A42E7CDA-D03F-480C-9CC2-A4DE20ABB878");
  6753. #endif /* HAVE_AF_HYPERV */
  6754. #ifdef USE_BLUETOOTH
  6755. ADD_INT_MACRO(m, AF_BLUETOOTH);
  6756. #ifdef BTPROTO_L2CAP
  6757. ADD_INT_MACRO(m, BTPROTO_L2CAP);
  6758. #endif /* BTPROTO_L2CAP */
  6759. #ifdef BTPROTO_HCI
  6760. ADD_INT_MACRO(m, BTPROTO_HCI);
  6761. ADD_INT_MACRO(m, SOL_HCI);
  6762. #if !defined(__NetBSD__) && !defined(__DragonFly__)
  6763. ADD_INT_MACRO(m, HCI_FILTER);
  6764. #if !defined(__FreeBSD__)
  6765. ADD_INT_MACRO(m, HCI_TIME_STAMP);
  6766. ADD_INT_MACRO(m, HCI_DATA_DIR);
  6767. #endif /* !__FreeBSD__ */
  6768. #endif /* !__NetBSD__ && !__DragonFly__ */
  6769. #endif /* BTPROTO_HCI */
  6770. #ifdef BTPROTO_RFCOMM
  6771. ADD_INT_MACRO(m, BTPROTO_RFCOMM);
  6772. #endif /* BTPROTO_RFCOMM */
  6773. ADD_STR_CONST(m, "BDADDR_ANY", "00:00:00:00:00:00");
  6774. ADD_STR_CONST(m, "BDADDR_LOCAL", "00:00:00:FF:FF:FF");
  6775. #ifdef BTPROTO_SCO
  6776. ADD_INT_MACRO(m, BTPROTO_SCO);
  6777. #endif /* BTPROTO_SCO */
  6778. #endif /* USE_BLUETOOTH */
  6779. #ifdef AF_CAN
  6780. /* Controller Area Network */
  6781. ADD_INT_MACRO(m, AF_CAN);
  6782. #endif
  6783. #ifdef PF_CAN
  6784. /* Controller Area Network */
  6785. ADD_INT_MACRO(m, PF_CAN);
  6786. #endif
  6787. /* Reliable Datagram Sockets */
  6788. #ifdef AF_RDS
  6789. ADD_INT_MACRO(m, AF_RDS);
  6790. #endif
  6791. #ifdef PF_RDS
  6792. ADD_INT_MACRO(m, PF_RDS);
  6793. #endif
  6794. /* Kernel event messages */
  6795. #ifdef PF_SYSTEM
  6796. ADD_INT_MACRO(m, PF_SYSTEM);
  6797. #endif
  6798. #ifdef AF_SYSTEM
  6799. ADD_INT_MACRO(m, AF_SYSTEM);
  6800. #endif
  6801. /* FreeBSD divert(4) */
  6802. #ifdef PF_DIVERT
  6803. ADD_INT_MACRO(m, PF_DIVERT);
  6804. #endif
  6805. #ifdef AF_DIVERT
  6806. ADD_INT_MACRO(m, AF_DIVERT);
  6807. #endif
  6808. #ifdef AF_PACKET
  6809. ADD_INT_MACRO(m, AF_PACKET);
  6810. #endif
  6811. #ifdef PF_PACKET
  6812. ADD_INT_MACRO(m, PF_PACKET);
  6813. #endif
  6814. #ifdef PACKET_HOST
  6815. ADD_INT_MACRO(m, PACKET_HOST);
  6816. #endif
  6817. #ifdef PACKET_BROADCAST
  6818. ADD_INT_MACRO(m, PACKET_BROADCAST);
  6819. #endif
  6820. #ifdef PACKET_MULTICAST
  6821. ADD_INT_MACRO(m, PACKET_MULTICAST);
  6822. #endif
  6823. #ifdef PACKET_OTHERHOST
  6824. ADD_INT_MACRO(m, PACKET_OTHERHOST);
  6825. #endif
  6826. #ifdef PACKET_OUTGOING
  6827. ADD_INT_MACRO(m, PACKET_OUTGOING);
  6828. #endif
  6829. #ifdef PACKET_LOOPBACK
  6830. ADD_INT_MACRO(m, PACKET_LOOPBACK);
  6831. #endif
  6832. #ifdef PACKET_FASTROUTE
  6833. ADD_INT_MACRO(m, PACKET_FASTROUTE);
  6834. #endif
  6835. #ifdef HAVE_LINUX_TIPC_H
  6836. ADD_INT_MACRO(m, AF_TIPC);
  6837. /* for addresses */
  6838. ADD_INT_MACRO(m, TIPC_ADDR_NAMESEQ);
  6839. ADD_INT_MACRO(m, TIPC_ADDR_NAME);
  6840. ADD_INT_MACRO(m, TIPC_ADDR_ID);
  6841. ADD_INT_MACRO(m, TIPC_ZONE_SCOPE);
  6842. ADD_INT_MACRO(m, TIPC_CLUSTER_SCOPE);
  6843. ADD_INT_MACRO(m, TIPC_NODE_SCOPE);
  6844. /* for setsockopt() */
  6845. ADD_INT_MACRO(m, SOL_TIPC);
  6846. ADD_INT_MACRO(m, TIPC_IMPORTANCE);
  6847. ADD_INT_MACRO(m, TIPC_SRC_DROPPABLE);
  6848. ADD_INT_MACRO(m, TIPC_DEST_DROPPABLE);
  6849. ADD_INT_MACRO(m, TIPC_CONN_TIMEOUT);
  6850. ADD_INT_MACRO(m, TIPC_LOW_IMPORTANCE);
  6851. ADD_INT_MACRO(m, TIPC_MEDIUM_IMPORTANCE);
  6852. ADD_INT_MACRO(m, TIPC_HIGH_IMPORTANCE);
  6853. ADD_INT_MACRO(m, TIPC_CRITICAL_IMPORTANCE);
  6854. /* for subscriptions */
  6855. ADD_INT_MACRO(m, TIPC_SUB_PORTS);
  6856. ADD_INT_MACRO(m, TIPC_SUB_SERVICE);
  6857. #ifdef TIPC_SUB_CANCEL
  6858. /* doesn't seem to be available everywhere */
  6859. ADD_INT_MACRO(m, TIPC_SUB_CANCEL);
  6860. #endif
  6861. ADD_INT_MACRO(m, TIPC_WAIT_FOREVER);
  6862. ADD_INT_MACRO(m, TIPC_PUBLISHED);
  6863. ADD_INT_MACRO(m, TIPC_WITHDRAWN);
  6864. ADD_INT_MACRO(m, TIPC_SUBSCR_TIMEOUT);
  6865. ADD_INT_MACRO(m, TIPC_CFG_SRV);
  6866. ADD_INT_MACRO(m, TIPC_TOP_SRV);
  6867. #endif
  6868. #ifdef HAVE_SOCKADDR_ALG
  6869. /* Socket options */
  6870. ADD_INT_MACRO(m, ALG_SET_KEY);
  6871. ADD_INT_MACRO(m, ALG_SET_IV);
  6872. ADD_INT_MACRO(m, ALG_SET_OP);
  6873. ADD_INT_MACRO(m, ALG_SET_AEAD_ASSOCLEN);
  6874. ADD_INT_MACRO(m, ALG_SET_AEAD_AUTHSIZE);
  6875. ADD_INT_MACRO(m, ALG_SET_PUBKEY);
  6876. /* Operations */
  6877. ADD_INT_MACRO(m, ALG_OP_DECRYPT);
  6878. ADD_INT_MACRO(m, ALG_OP_ENCRYPT);
  6879. ADD_INT_MACRO(m, ALG_OP_SIGN);
  6880. ADD_INT_MACRO(m, ALG_OP_VERIFY);
  6881. #endif
  6882. /* IEEE 802.3 protocol numbers required for a standard TCP/IP network stack */
  6883. #ifdef ETHERTYPE_ARP
  6884. ADD_INT_MACRO(m, ETHERTYPE_ARP);
  6885. #endif
  6886. #ifdef ETHERTYPE_IP
  6887. ADD_INT_MACRO(m, ETHERTYPE_IP);
  6888. #endif
  6889. #ifdef ETHERTYPE_IPV6
  6890. ADD_INT_MACRO(m, ETHERTYPE_IPV6);
  6891. #endif
  6892. #ifdef ETHERTYPE_VLAN
  6893. ADD_INT_MACRO(m, ETHERTYPE_VLAN);
  6894. #endif
  6895. /* Linux pseudo-protocol for sniffing every packet */
  6896. #ifdef ETH_P_ALL
  6897. ADD_INT_MACRO(m, ETH_P_ALL);
  6898. #endif
  6899. /* Socket types */
  6900. ADD_INT_MACRO(m, SOCK_STREAM);
  6901. ADD_INT_MACRO(m, SOCK_DGRAM);
  6902. /* We have incomplete socket support. */
  6903. #ifdef SOCK_RAW
  6904. /* SOCK_RAW is marked as optional in the POSIX specification */
  6905. ADD_INT_MACRO(m, SOCK_RAW);
  6906. #endif
  6907. #ifdef SOCK_SEQPACKET
  6908. ADD_INT_MACRO(m, SOCK_SEQPACKET);
  6909. #endif
  6910. #if defined(SOCK_RDM)
  6911. ADD_INT_MACRO(m, SOCK_RDM);
  6912. #endif
  6913. #ifdef SOCK_CLOEXEC
  6914. ADD_INT_MACRO(m, SOCK_CLOEXEC);
  6915. #endif
  6916. #ifdef SOCK_NONBLOCK
  6917. ADD_INT_MACRO(m, SOCK_NONBLOCK);
  6918. #endif
  6919. #ifdef SO_DEBUG
  6920. ADD_INT_MACRO(m, SO_DEBUG);
  6921. #endif
  6922. #ifdef SO_ACCEPTCONN
  6923. ADD_INT_MACRO(m, SO_ACCEPTCONN);
  6924. #endif
  6925. #ifdef SO_REUSEADDR
  6926. ADD_INT_MACRO(m, SO_REUSEADDR);
  6927. #endif
  6928. #ifdef SO_EXCLUSIVEADDRUSE
  6929. ADD_INT_MACRO(m, SO_EXCLUSIVEADDRUSE);
  6930. #endif
  6931. #ifdef SO_INCOMING_CPU
  6932. ADD_INT_MACRO(m, SO_INCOMING_CPU);
  6933. #endif
  6934. #ifdef SO_KEEPALIVE
  6935. ADD_INT_MACRO(m, SO_KEEPALIVE);
  6936. #endif
  6937. #ifdef SO_DONTROUTE
  6938. ADD_INT_MACRO(m, SO_DONTROUTE);
  6939. #endif
  6940. #ifdef SO_BROADCAST
  6941. ADD_INT_MACRO(m, SO_BROADCAST);
  6942. #endif
  6943. #ifdef SO_USELOOPBACK
  6944. ADD_INT_MACRO(m, SO_USELOOPBACK);
  6945. #endif
  6946. #ifdef SO_LINGER
  6947. ADD_INT_MACRO(m, SO_LINGER);
  6948. #endif
  6949. #ifdef SO_OOBINLINE
  6950. ADD_INT_MACRO(m, SO_OOBINLINE);
  6951. #endif
  6952. #ifndef __GNU__
  6953. #ifdef SO_REUSEPORT
  6954. ADD_INT_MACRO(m, SO_REUSEPORT);
  6955. #endif
  6956. #endif
  6957. #ifdef SO_SNDBUF
  6958. ADD_INT_MACRO(m, SO_SNDBUF);
  6959. #endif
  6960. #ifdef SO_RCVBUF
  6961. ADD_INT_MACRO(m, SO_RCVBUF);
  6962. #endif
  6963. #ifdef SO_SNDLOWAT
  6964. ADD_INT_MACRO(m, SO_SNDLOWAT);
  6965. #endif
  6966. #ifdef SO_RCVLOWAT
  6967. ADD_INT_MACRO(m, SO_RCVLOWAT);
  6968. #endif
  6969. #ifdef SO_SNDTIMEO
  6970. ADD_INT_MACRO(m, SO_SNDTIMEO);
  6971. #endif
  6972. #ifdef SO_RCVTIMEO
  6973. ADD_INT_MACRO(m, SO_RCVTIMEO);
  6974. #endif
  6975. #ifdef SO_ERROR
  6976. ADD_INT_MACRO(m, SO_ERROR);
  6977. #endif
  6978. #ifdef SO_TYPE
  6979. ADD_INT_MACRO(m, SO_TYPE);
  6980. #endif
  6981. #ifdef SO_SETFIB
  6982. ADD_INT_MACRO(m, SO_SETFIB);
  6983. #endif
  6984. #ifdef SO_PASSCRED
  6985. ADD_INT_MACRO(m, SO_PASSCRED);
  6986. #endif
  6987. #ifdef SO_PEERCRED
  6988. ADD_INT_MACRO(m, SO_PEERCRED);
  6989. #endif
  6990. #ifdef LOCAL_PEERCRED
  6991. ADD_INT_MACRO(m, LOCAL_PEERCRED);
  6992. #endif
  6993. #ifdef SO_PASSSEC
  6994. ADD_INT_MACRO(m, SO_PASSSEC);
  6995. #endif
  6996. #ifdef SO_PEERSEC
  6997. ADD_INT_MACRO(m, SO_PEERSEC);
  6998. #endif
  6999. #ifdef SO_BINDTODEVICE
  7000. ADD_INT_MACRO(m, SO_BINDTODEVICE);
  7001. #endif
  7002. #ifdef SO_PRIORITY
  7003. ADD_INT_MACRO(m, SO_PRIORITY);
  7004. #endif
  7005. #ifdef SO_MARK
  7006. ADD_INT_MACRO(m, SO_MARK);
  7007. #endif
  7008. #ifdef SO_USER_COOKIE
  7009. ADD_INT_MACRO(m, SO_USER_COOKIE);
  7010. #endif
  7011. #ifdef SO_RTABLE
  7012. ADD_INT_MACRO(m, SO_RTABLE);
  7013. #endif
  7014. #ifdef SO_DOMAIN
  7015. ADD_INT_MACRO(m, SO_DOMAIN);
  7016. #endif
  7017. #ifdef SO_PROTOCOL
  7018. ADD_INT_MACRO(m, SO_PROTOCOL);
  7019. #endif
  7020. #ifdef LOCAL_CREDS
  7021. ADD_INT_MACRO(m, LOCAL_CREDS);
  7022. #endif
  7023. #ifdef LOCAL_CREDS_PERSISTENT
  7024. ADD_INT_MACRO(m, LOCAL_CREDS_PERSISTENT);
  7025. #endif
  7026. /* Maximum number of connections for "listen" */
  7027. #ifdef SOMAXCONN
  7028. ADD_INT_MACRO(m, SOMAXCONN);
  7029. #else
  7030. ADD_INT_CONST(m, "SOMAXCONN", 5); /* Common value */
  7031. #endif
  7032. /* Ancillary message types */
  7033. #ifdef SCM_RIGHTS
  7034. ADD_INT_MACRO(m, SCM_RIGHTS);
  7035. #endif
  7036. #ifdef SCM_CREDENTIALS
  7037. ADD_INT_MACRO(m, SCM_CREDENTIALS);
  7038. #endif
  7039. #ifdef SCM_CREDS
  7040. ADD_INT_MACRO(m, SCM_CREDS);
  7041. #endif
  7042. #ifdef SCM_CREDS2
  7043. ADD_INT_MACRO(m, SCM_CREDS2);
  7044. #endif
  7045. /* Flags for send, recv */
  7046. #ifdef MSG_OOB
  7047. ADD_INT_MACRO(m, MSG_OOB);
  7048. #endif
  7049. #ifdef MSG_PEEK
  7050. ADD_INT_MACRO(m, MSG_PEEK);
  7051. #endif
  7052. #ifdef MSG_DONTROUTE
  7053. ADD_INT_MACRO(m, MSG_DONTROUTE);
  7054. #endif
  7055. #ifdef MSG_DONTWAIT
  7056. ADD_INT_MACRO(m, MSG_DONTWAIT);
  7057. #endif
  7058. #ifdef MSG_EOR
  7059. ADD_INT_MACRO(m, MSG_EOR);
  7060. #endif
  7061. #ifdef MSG_TRUNC
  7062. // workaround for https://github.com/WebAssembly/wasi-libc/issues/305
  7063. #if defined(__wasi__) && !defined(__WASI_RIFLAGS_RECV_DATA_TRUNCATED)
  7064. # define __WASI_RIFLAGS_RECV_DATA_TRUNCATED 2
  7065. #endif
  7066. ADD_INT_MACRO(m, MSG_TRUNC);
  7067. #endif
  7068. #ifdef MSG_CTRUNC
  7069. ADD_INT_MACRO(m, MSG_CTRUNC);
  7070. #endif
  7071. #ifdef MSG_WAITALL
  7072. ADD_INT_MACRO(m, MSG_WAITALL);
  7073. #endif
  7074. #ifdef MSG_BTAG
  7075. ADD_INT_MACRO(m, MSG_BTAG);
  7076. #endif
  7077. #ifdef MSG_ETAG
  7078. ADD_INT_MACRO(m, MSG_ETAG);
  7079. #endif
  7080. #ifdef MSG_NOSIGNAL
  7081. ADD_INT_MACRO(m, MSG_NOSIGNAL);
  7082. #endif
  7083. #ifdef MSG_NOTIFICATION
  7084. ADD_INT_MACRO(m, MSG_NOTIFICATION);
  7085. #endif
  7086. #ifdef MSG_CMSG_CLOEXEC
  7087. ADD_INT_MACRO(m, MSG_CMSG_CLOEXEC);
  7088. #endif
  7089. #ifdef MSG_ERRQUEUE
  7090. ADD_INT_MACRO(m, MSG_ERRQUEUE);
  7091. #endif
  7092. #ifdef MSG_CONFIRM
  7093. ADD_INT_MACRO(m, MSG_CONFIRM);
  7094. #endif
  7095. #ifdef MSG_MORE
  7096. ADD_INT_MACRO(m, MSG_MORE);
  7097. #endif
  7098. #ifdef MSG_EOF
  7099. ADD_INT_MACRO(m, MSG_EOF);
  7100. #endif
  7101. #ifdef MSG_BCAST
  7102. ADD_INT_MACRO(m, MSG_BCAST);
  7103. #endif
  7104. #ifdef MSG_MCAST
  7105. ADD_INT_MACRO(m, MSG_MCAST);
  7106. #endif
  7107. #ifdef MSG_FASTOPEN
  7108. ADD_INT_MACRO(m, MSG_FASTOPEN);
  7109. #endif
  7110. /* Protocol level and numbers, usable for [gs]etsockopt */
  7111. #ifdef SOL_SOCKET
  7112. ADD_INT_MACRO(m, SOL_SOCKET);
  7113. #endif
  7114. #ifdef SOL_IP
  7115. ADD_INT_MACRO(m, SOL_IP);
  7116. #else
  7117. ADD_INT_CONST(m, "SOL_IP", 0);
  7118. #endif
  7119. #ifdef SOL_IPX
  7120. ADD_INT_MACRO(m, SOL_IPX);
  7121. #endif
  7122. #ifdef SOL_AX25
  7123. ADD_INT_MACRO(m, SOL_AX25);
  7124. #endif
  7125. #ifdef SOL_ATALK
  7126. ADD_INT_MACRO(m, SOL_ATALK);
  7127. #endif
  7128. #ifdef SOL_NETROM
  7129. ADD_INT_MACRO(m, SOL_NETROM);
  7130. #endif
  7131. #ifdef SOL_ROSE
  7132. ADD_INT_MACRO(m, SOL_ROSE);
  7133. #endif
  7134. #ifdef SOL_TCP
  7135. ADD_INT_MACRO(m, SOL_TCP);
  7136. #else
  7137. ADD_INT_CONST(m, "SOL_TCP", 6);
  7138. #endif
  7139. #ifdef SOL_UDP
  7140. ADD_INT_MACRO(m, SOL_UDP);
  7141. #else
  7142. ADD_INT_CONST(m, "SOL_UDP", 17);
  7143. #endif
  7144. #ifdef SOL_CAN_BASE
  7145. ADD_INT_MACRO(m, SOL_CAN_BASE);
  7146. #endif
  7147. #ifdef SOL_CAN_RAW
  7148. ADD_INT_MACRO(m, SOL_CAN_RAW);
  7149. ADD_INT_MACRO(m, CAN_RAW);
  7150. #endif
  7151. #if defined(HAVE_LINUX_CAN_H) || defined(HAVE_NETCAN_CAN_H)
  7152. ADD_INT_MACRO(m, CAN_EFF_FLAG);
  7153. ADD_INT_MACRO(m, CAN_RTR_FLAG);
  7154. ADD_INT_MACRO(m, CAN_ERR_FLAG);
  7155. ADD_INT_MACRO(m, CAN_SFF_MASK);
  7156. ADD_INT_MACRO(m, CAN_EFF_MASK);
  7157. ADD_INT_MACRO(m, CAN_ERR_MASK);
  7158. #ifdef CAN_ISOTP
  7159. ADD_INT_MACRO(m, CAN_ISOTP);
  7160. #endif
  7161. #ifdef CAN_J1939
  7162. ADD_INT_MACRO(m, CAN_J1939);
  7163. #endif
  7164. #endif
  7165. #if defined(HAVE_LINUX_CAN_RAW_H) || defined(HAVE_NETCAN_CAN_H)
  7166. ADD_INT_MACRO(m, CAN_RAW_FILTER);
  7167. #ifdef CAN_RAW_ERR_FILTER
  7168. ADD_INT_MACRO(m, CAN_RAW_ERR_FILTER);
  7169. #endif
  7170. ADD_INT_MACRO(m, CAN_RAW_LOOPBACK);
  7171. ADD_INT_MACRO(m, CAN_RAW_RECV_OWN_MSGS);
  7172. #endif
  7173. #ifdef HAVE_LINUX_CAN_RAW_FD_FRAMES
  7174. ADD_INT_MACRO(m, CAN_RAW_FD_FRAMES);
  7175. #endif
  7176. #ifdef HAVE_LINUX_CAN_RAW_JOIN_FILTERS
  7177. ADD_INT_MACRO(m, CAN_RAW_JOIN_FILTERS);
  7178. #endif
  7179. #ifdef HAVE_LINUX_CAN_BCM_H
  7180. ADD_INT_MACRO(m, CAN_BCM);
  7181. /* BCM opcodes */
  7182. ADD_INT_CONST(m, "CAN_BCM_TX_SETUP", TX_SETUP);
  7183. ADD_INT_CONST(m, "CAN_BCM_TX_DELETE", TX_DELETE);
  7184. ADD_INT_CONST(m, "CAN_BCM_TX_READ", TX_READ);
  7185. ADD_INT_CONST(m, "CAN_BCM_TX_SEND", TX_SEND);
  7186. ADD_INT_CONST(m, "CAN_BCM_RX_SETUP", RX_SETUP);
  7187. ADD_INT_CONST(m, "CAN_BCM_RX_DELETE", RX_DELETE);
  7188. ADD_INT_CONST(m, "CAN_BCM_RX_READ", RX_READ);
  7189. ADD_INT_CONST(m, "CAN_BCM_TX_STATUS", TX_STATUS);
  7190. ADD_INT_CONST(m, "CAN_BCM_TX_EXPIRED", TX_EXPIRED);
  7191. ADD_INT_CONST(m, "CAN_BCM_RX_STATUS", RX_STATUS);
  7192. ADD_INT_CONST(m, "CAN_BCM_RX_TIMEOUT", RX_TIMEOUT);
  7193. ADD_INT_CONST(m, "CAN_BCM_RX_CHANGED", RX_CHANGED);
  7194. /* BCM flags */
  7195. ADD_INT_CONST(m, "CAN_BCM_SETTIMER", SETTIMER);
  7196. ADD_INT_CONST(m, "CAN_BCM_STARTTIMER", STARTTIMER);
  7197. ADD_INT_CONST(m, "CAN_BCM_TX_COUNTEVT", TX_COUNTEVT);
  7198. ADD_INT_CONST(m, "CAN_BCM_TX_ANNOUNCE", TX_ANNOUNCE);
  7199. ADD_INT_CONST(m, "CAN_BCM_TX_CP_CAN_ID", TX_CP_CAN_ID);
  7200. ADD_INT_CONST(m, "CAN_BCM_RX_FILTER_ID", RX_FILTER_ID);
  7201. ADD_INT_CONST(m, "CAN_BCM_RX_CHECK_DLC", RX_CHECK_DLC);
  7202. ADD_INT_CONST(m, "CAN_BCM_RX_NO_AUTOTIMER", RX_NO_AUTOTIMER);
  7203. ADD_INT_CONST(m, "CAN_BCM_RX_ANNOUNCE_RESUME", RX_ANNOUNCE_RESUME);
  7204. ADD_INT_CONST(m, "CAN_BCM_TX_RESET_MULTI_IDX", TX_RESET_MULTI_IDX);
  7205. ADD_INT_CONST(m, "CAN_BCM_RX_RTR_FRAME", RX_RTR_FRAME);
  7206. #ifdef CAN_FD_FRAME
  7207. /* CAN_FD_FRAME was only introduced in the 4.8.x kernel series */
  7208. ADD_INT_CONST(m, "CAN_BCM_CAN_FD_FRAME", CAN_FD_FRAME);
  7209. #endif
  7210. #endif
  7211. #ifdef HAVE_LINUX_CAN_J1939_H
  7212. ADD_INT_MACRO(m, J1939_MAX_UNICAST_ADDR);
  7213. ADD_INT_MACRO(m, J1939_IDLE_ADDR);
  7214. ADD_INT_MACRO(m, J1939_NO_ADDR);
  7215. ADD_INT_MACRO(m, J1939_NO_NAME);
  7216. ADD_INT_MACRO(m, J1939_PGN_REQUEST);
  7217. ADD_INT_MACRO(m, J1939_PGN_ADDRESS_CLAIMED);
  7218. ADD_INT_MACRO(m, J1939_PGN_ADDRESS_COMMANDED);
  7219. ADD_INT_MACRO(m, J1939_PGN_PDU1_MAX);
  7220. ADD_INT_MACRO(m, J1939_PGN_MAX);
  7221. ADD_INT_MACRO(m, J1939_NO_PGN);
  7222. /* J1939 socket options */
  7223. ADD_INT_MACRO(m, SO_J1939_FILTER);
  7224. ADD_INT_MACRO(m, SO_J1939_PROMISC);
  7225. ADD_INT_MACRO(m, SO_J1939_SEND_PRIO);
  7226. ADD_INT_MACRO(m, SO_J1939_ERRQUEUE);
  7227. ADD_INT_MACRO(m, SCM_J1939_DEST_ADDR);
  7228. ADD_INT_MACRO(m, SCM_J1939_DEST_NAME);
  7229. ADD_INT_MACRO(m, SCM_J1939_PRIO);
  7230. ADD_INT_MACRO(m, SCM_J1939_ERRQUEUE);
  7231. ADD_INT_MACRO(m, J1939_NLA_PAD);
  7232. ADD_INT_MACRO(m, J1939_NLA_BYTES_ACKED);
  7233. ADD_INT_MACRO(m, J1939_EE_INFO_NONE);
  7234. ADD_INT_MACRO(m, J1939_EE_INFO_TX_ABORT);
  7235. ADD_INT_MACRO(m, J1939_FILTER_MAX);
  7236. #endif
  7237. #ifdef SOL_RDS
  7238. ADD_INT_MACRO(m, SOL_RDS);
  7239. #endif
  7240. #ifdef HAVE_SOCKADDR_ALG
  7241. ADD_INT_MACRO(m, SOL_ALG);
  7242. #endif
  7243. #ifdef RDS_CANCEL_SENT_TO
  7244. ADD_INT_MACRO(m, RDS_CANCEL_SENT_TO);
  7245. #endif
  7246. #ifdef RDS_GET_MR
  7247. ADD_INT_MACRO(m, RDS_GET_MR);
  7248. #endif
  7249. #ifdef RDS_FREE_MR
  7250. ADD_INT_MACRO(m, RDS_FREE_MR);
  7251. #endif
  7252. #ifdef RDS_RECVERR
  7253. ADD_INT_MACRO(m, RDS_RECVERR);
  7254. #endif
  7255. #ifdef RDS_CONG_MONITOR
  7256. ADD_INT_MACRO(m, RDS_CONG_MONITOR);
  7257. #endif
  7258. #ifdef RDS_GET_MR_FOR_DEST
  7259. ADD_INT_MACRO(m, RDS_GET_MR_FOR_DEST);
  7260. #endif
  7261. #ifdef IPPROTO_IP
  7262. ADD_INT_MACRO(m, IPPROTO_IP);
  7263. #else
  7264. ADD_INT_CONST(m, "IPPROTO_IP", 0);
  7265. #endif
  7266. #ifdef IPPROTO_HOPOPTS
  7267. ADD_INT_MACRO(m, IPPROTO_HOPOPTS);
  7268. #endif
  7269. #ifdef IPPROTO_ICMP
  7270. ADD_INT_MACRO(m, IPPROTO_ICMP);
  7271. #else
  7272. ADD_INT_CONST(m, "IPPROTO_ICMP", 1);
  7273. #endif
  7274. #ifdef IPPROTO_IGMP
  7275. ADD_INT_MACRO(m, IPPROTO_IGMP);
  7276. #endif
  7277. #ifdef IPPROTO_GGP
  7278. ADD_INT_MACRO(m, IPPROTO_GGP);
  7279. #endif
  7280. #ifdef IPPROTO_IPV4
  7281. ADD_INT_MACRO(m, IPPROTO_IPV4);
  7282. #endif
  7283. #ifdef IPPROTO_IPV6
  7284. ADD_INT_MACRO(m, IPPROTO_IPV6);
  7285. #endif
  7286. #ifdef IPPROTO_IPIP
  7287. ADD_INT_MACRO(m, IPPROTO_IPIP);
  7288. #endif
  7289. #ifdef IPPROTO_TCP
  7290. ADD_INT_MACRO(m, IPPROTO_TCP);
  7291. #else
  7292. ADD_INT_CONST(m, "IPPROTO_TCP", 6);
  7293. #endif
  7294. #ifdef IPPROTO_EGP
  7295. ADD_INT_MACRO(m, IPPROTO_EGP);
  7296. #endif
  7297. #ifdef IPPROTO_PUP
  7298. ADD_INT_MACRO(m, IPPROTO_PUP);
  7299. #endif
  7300. #ifdef IPPROTO_UDP
  7301. ADD_INT_MACRO(m, IPPROTO_UDP);
  7302. #else
  7303. ADD_INT_CONST(m, "IPPROTO_UDP", 17);
  7304. #endif
  7305. #ifdef IPPROTO_UDPLITE
  7306. ADD_INT_MACRO(m, IPPROTO_UDPLITE);
  7307. #ifndef UDPLITE_SEND_CSCOV
  7308. #define UDPLITE_SEND_CSCOV 10
  7309. #endif
  7310. ADD_INT_MACRO(m, UDPLITE_SEND_CSCOV);
  7311. #ifndef UDPLITE_RECV_CSCOV
  7312. #define UDPLITE_RECV_CSCOV 11
  7313. #endif
  7314. ADD_INT_MACRO(m, UDPLITE_RECV_CSCOV);
  7315. #endif
  7316. #ifdef IPPROTO_IDP
  7317. ADD_INT_MACRO(m, IPPROTO_IDP);
  7318. #endif
  7319. #ifdef IPPROTO_HELLO
  7320. ADD_INT_MACRO(m, IPPROTO_HELLO);
  7321. #endif
  7322. #ifdef IPPROTO_ND
  7323. ADD_INT_MACRO(m, IPPROTO_ND);
  7324. #endif
  7325. #ifdef IPPROTO_TP
  7326. ADD_INT_MACRO(m, IPPROTO_TP);
  7327. #endif
  7328. #ifdef IPPROTO_ROUTING
  7329. ADD_INT_MACRO(m, IPPROTO_ROUTING);
  7330. #endif
  7331. #ifdef IPPROTO_FRAGMENT
  7332. ADD_INT_MACRO(m, IPPROTO_FRAGMENT);
  7333. #endif
  7334. #ifdef IPPROTO_RSVP
  7335. ADD_INT_MACRO(m, IPPROTO_RSVP);
  7336. #endif
  7337. #ifdef IPPROTO_GRE
  7338. ADD_INT_MACRO(m, IPPROTO_GRE);
  7339. #endif
  7340. #ifdef IPPROTO_ESP
  7341. ADD_INT_MACRO(m, IPPROTO_ESP);
  7342. #endif
  7343. #ifdef IPPROTO_AH
  7344. ADD_INT_MACRO(m, IPPROTO_AH);
  7345. #endif
  7346. #ifdef IPPROTO_MOBILE
  7347. ADD_INT_MACRO(m, IPPROTO_MOBILE);
  7348. #endif
  7349. #ifdef IPPROTO_ICMPV6
  7350. ADD_INT_MACRO(m, IPPROTO_ICMPV6);
  7351. #endif
  7352. #ifdef IPPROTO_NONE
  7353. ADD_INT_MACRO(m, IPPROTO_NONE);
  7354. #endif
  7355. #ifdef IPPROTO_DSTOPTS
  7356. ADD_INT_MACRO(m, IPPROTO_DSTOPTS);
  7357. #endif
  7358. #ifdef IPPROTO_XTP
  7359. ADD_INT_MACRO(m, IPPROTO_XTP);
  7360. #endif
  7361. #ifdef IPPROTO_EON
  7362. ADD_INT_MACRO(m, IPPROTO_EON);
  7363. #endif
  7364. #ifdef IPPROTO_PIM
  7365. ADD_INT_MACRO(m, IPPROTO_PIM);
  7366. #endif
  7367. #ifdef IPPROTO_IPCOMP
  7368. ADD_INT_MACRO(m, IPPROTO_IPCOMP);
  7369. #endif
  7370. #ifdef IPPROTO_VRRP
  7371. ADD_INT_MACRO(m, IPPROTO_VRRP);
  7372. #endif
  7373. #ifdef IPPROTO_SCTP
  7374. ADD_INT_MACRO(m, IPPROTO_SCTP);
  7375. #endif
  7376. #ifdef IPPROTO_BIP
  7377. ADD_INT_MACRO(m, IPPROTO_BIP);
  7378. #endif
  7379. #ifdef IPPROTO_MPTCP
  7380. ADD_INT_MACRO(m, IPPROTO_MPTCP);
  7381. #endif
  7382. /**/
  7383. #ifdef IPPROTO_RAW
  7384. ADD_INT_MACRO(m, IPPROTO_RAW);
  7385. #else
  7386. ADD_INT_CONST(m, "IPPROTO_RAW", 255);
  7387. #endif
  7388. #ifdef IPPROTO_MAX
  7389. ADD_INT_MACRO(m, IPPROTO_MAX);
  7390. #endif
  7391. #ifdef MS_WINDOWS
  7392. ADD_INT_MACRO(m, IPPROTO_ICLFXBM);
  7393. ADD_INT_MACRO(m, IPPROTO_ST);
  7394. ADD_INT_MACRO(m, IPPROTO_CBT);
  7395. ADD_INT_MACRO(m, IPPROTO_IGP);
  7396. ADD_INT_MACRO(m, IPPROTO_RDP);
  7397. ADD_INT_MACRO(m, IPPROTO_PGM);
  7398. ADD_INT_MACRO(m, IPPROTO_L2TP);
  7399. ADD_INT_MACRO(m, IPPROTO_SCTP);
  7400. #endif
  7401. #ifdef SYSPROTO_CONTROL
  7402. ADD_INT_MACRO(m, SYSPROTO_CONTROL);
  7403. #endif
  7404. /* Some port configuration */
  7405. #ifdef IPPORT_RESERVED
  7406. ADD_INT_MACRO(m, IPPORT_RESERVED);
  7407. #else
  7408. ADD_INT_CONST(m, "IPPORT_RESERVED", 1024);
  7409. #endif
  7410. #ifdef IPPORT_USERRESERVED
  7411. ADD_INT_MACRO(m, IPPORT_USERRESERVED);
  7412. #else
  7413. ADD_INT_CONST(m, "IPPORT_USERRESERVED", 5000);
  7414. #endif
  7415. /* Some reserved IP v.4 addresses */
  7416. #ifdef INADDR_ANY
  7417. ADD_INT_MACRO(m, INADDR_ANY);
  7418. #else
  7419. ADD_INT_CONST(m, "INADDR_ANY", 0x00000000);
  7420. #endif
  7421. #ifdef INADDR_BROADCAST
  7422. ADD_INT_MACRO(m, INADDR_BROADCAST);
  7423. #else
  7424. ADD_INT_CONST(m, "INADDR_BROADCAST", 0xffffffff);
  7425. #endif
  7426. #ifdef INADDR_LOOPBACK
  7427. ADD_INT_MACRO(m, INADDR_LOOPBACK);
  7428. #else
  7429. ADD_INT_CONST(m, "INADDR_LOOPBACK", 0x7F000001);
  7430. #endif
  7431. #ifdef INADDR_UNSPEC_GROUP
  7432. ADD_INT_MACRO(m, INADDR_UNSPEC_GROUP);
  7433. #else
  7434. ADD_INT_CONST(m, "INADDR_UNSPEC_GROUP", 0xe0000000);
  7435. #endif
  7436. #ifdef INADDR_ALLHOSTS_GROUP
  7437. ADD_INT_CONST(m, "INADDR_ALLHOSTS_GROUP",
  7438. INADDR_ALLHOSTS_GROUP);
  7439. #else
  7440. ADD_INT_CONST(m, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
  7441. #endif
  7442. #ifdef INADDR_MAX_LOCAL_GROUP
  7443. ADD_INT_MACRO(m, INADDR_MAX_LOCAL_GROUP);
  7444. #else
  7445. ADD_INT_CONST(m, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
  7446. #endif
  7447. #ifdef INADDR_NONE
  7448. ADD_INT_MACRO(m, INADDR_NONE);
  7449. #else
  7450. ADD_INT_CONST(m, "INADDR_NONE", 0xffffffff);
  7451. #endif
  7452. /* IPv4 [gs]etsockopt options */
  7453. #ifdef IP_OPTIONS
  7454. ADD_INT_MACRO(m, IP_OPTIONS);
  7455. #endif
  7456. #ifdef IP_HDRINCL
  7457. ADD_INT_MACRO(m, IP_HDRINCL);
  7458. #endif
  7459. #ifdef IP_TOS
  7460. ADD_INT_MACRO(m, IP_TOS);
  7461. #endif
  7462. #ifdef IP_TTL
  7463. ADD_INT_MACRO(m, IP_TTL);
  7464. #endif
  7465. #ifdef IP_RECVOPTS
  7466. ADD_INT_MACRO(m, IP_RECVOPTS);
  7467. #endif
  7468. #ifdef IP_RECVRETOPTS
  7469. ADD_INT_MACRO(m, IP_RECVRETOPTS);
  7470. #endif
  7471. #ifdef IP_RECVTOS
  7472. ADD_INT_MACRO(m, IP_RECVTOS);
  7473. #endif
  7474. #ifdef IP_RECVDSTADDR
  7475. ADD_INT_MACRO(m, IP_RECVDSTADDR);
  7476. #endif
  7477. #ifdef IP_RETOPTS
  7478. ADD_INT_MACRO(m, IP_RETOPTS);
  7479. #endif
  7480. #ifdef IP_MULTICAST_IF
  7481. ADD_INT_MACRO(m, IP_MULTICAST_IF);
  7482. #endif
  7483. #ifdef IP_MULTICAST_TTL
  7484. ADD_INT_MACRO(m, IP_MULTICAST_TTL);
  7485. #endif
  7486. #ifdef IP_MULTICAST_LOOP
  7487. ADD_INT_MACRO(m, IP_MULTICAST_LOOP);
  7488. #endif
  7489. #ifdef IP_ADD_MEMBERSHIP
  7490. ADD_INT_MACRO(m, IP_ADD_MEMBERSHIP);
  7491. #endif
  7492. #ifdef IP_DROP_MEMBERSHIP
  7493. ADD_INT_MACRO(m, IP_DROP_MEMBERSHIP);
  7494. #endif
  7495. #ifdef IP_DEFAULT_MULTICAST_TTL
  7496. ADD_INT_MACRO(m, IP_DEFAULT_MULTICAST_TTL);
  7497. #endif
  7498. #ifdef IP_DEFAULT_MULTICAST_LOOP
  7499. ADD_INT_MACRO(m, IP_DEFAULT_MULTICAST_LOOP);
  7500. #endif
  7501. #ifdef IP_MAX_MEMBERSHIPS
  7502. ADD_INT_MACRO(m, IP_MAX_MEMBERSHIPS);
  7503. #endif
  7504. #ifdef IP_TRANSPARENT
  7505. ADD_INT_MACRO(m, IP_TRANSPARENT);
  7506. #endif
  7507. #ifdef IP_PKTINFO
  7508. ADD_INT_MACRO(m, IP_PKTINFO);
  7509. #endif
  7510. #ifdef IP_BIND_ADDRESS_NO_PORT
  7511. ADD_INT_MACRO(m, IP_BIND_ADDRESS_NO_PORT);
  7512. #endif
  7513. #ifdef IP_UNBLOCK_SOURCE
  7514. ADD_INT_MACRO(m, IP_UNBLOCK_SOURCE);
  7515. #endif
  7516. #ifdef IP_BLOCK_SOURCE
  7517. ADD_INT_MACRO(m, IP_BLOCK_SOURCE);
  7518. #endif
  7519. #ifdef IP_ADD_SOURCE_MEMBERSHIP
  7520. ADD_INT_MACRO(m, IP_ADD_SOURCE_MEMBERSHIP);
  7521. #endif
  7522. #ifdef IP_DROP_SOURCE_MEMBERSHIP
  7523. ADD_INT_MACRO(m, IP_DROP_SOURCE_MEMBERSHIP);
  7524. #endif
  7525. /* IPv6 [gs]etsockopt options, defined in RFC2553 */
  7526. #ifdef IPV6_JOIN_GROUP
  7527. ADD_INT_MACRO(m, IPV6_JOIN_GROUP);
  7528. #endif
  7529. #ifdef IPV6_LEAVE_GROUP
  7530. ADD_INT_MACRO(m, IPV6_LEAVE_GROUP);
  7531. #endif
  7532. #ifdef IPV6_MULTICAST_HOPS
  7533. ADD_INT_MACRO(m, IPV6_MULTICAST_HOPS);
  7534. #endif
  7535. #ifdef IPV6_MULTICAST_IF
  7536. ADD_INT_MACRO(m, IPV6_MULTICAST_IF);
  7537. #endif
  7538. #ifdef IPV6_MULTICAST_LOOP
  7539. ADD_INT_MACRO(m, IPV6_MULTICAST_LOOP);
  7540. #endif
  7541. #ifdef IPV6_UNICAST_HOPS
  7542. ADD_INT_MACRO(m, IPV6_UNICAST_HOPS);
  7543. #endif
  7544. /* Additional IPV6 socket options, defined in RFC 3493 */
  7545. #ifdef IPV6_V6ONLY
  7546. ADD_INT_MACRO(m, IPV6_V6ONLY);
  7547. #endif
  7548. /* Advanced IPV6 socket options, from RFC 3542 */
  7549. #ifdef IPV6_CHECKSUM
  7550. ADD_INT_MACRO(m, IPV6_CHECKSUM);
  7551. #endif
  7552. #ifdef IPV6_DONTFRAG
  7553. ADD_INT_MACRO(m, IPV6_DONTFRAG);
  7554. #endif
  7555. #ifdef IPV6_DSTOPTS
  7556. ADD_INT_MACRO(m, IPV6_DSTOPTS);
  7557. #endif
  7558. #ifdef IPV6_HOPLIMIT
  7559. ADD_INT_MACRO(m, IPV6_HOPLIMIT);
  7560. #endif
  7561. #ifdef IPV6_HOPOPTS
  7562. ADD_INT_MACRO(m, IPV6_HOPOPTS);
  7563. #endif
  7564. #ifdef IPV6_NEXTHOP
  7565. ADD_INT_MACRO(m, IPV6_NEXTHOP);
  7566. #endif
  7567. #ifdef IPV6_PATHMTU
  7568. ADD_INT_MACRO(m, IPV6_PATHMTU);
  7569. #endif
  7570. #ifdef IPV6_PKTINFO
  7571. ADD_INT_MACRO(m, IPV6_PKTINFO);
  7572. #endif
  7573. #ifdef IPV6_RECVDSTOPTS
  7574. ADD_INT_MACRO(m, IPV6_RECVDSTOPTS);
  7575. #endif
  7576. #ifdef IPV6_RECVHOPLIMIT
  7577. ADD_INT_MACRO(m, IPV6_RECVHOPLIMIT);
  7578. #endif
  7579. #ifdef IPV6_RECVHOPOPTS
  7580. ADD_INT_MACRO(m, IPV6_RECVHOPOPTS);
  7581. #endif
  7582. #ifdef IPV6_RECVPKTINFO
  7583. ADD_INT_MACRO(m, IPV6_RECVPKTINFO);
  7584. #endif
  7585. #ifdef IPV6_RECVRTHDR
  7586. ADD_INT_MACRO(m, IPV6_RECVRTHDR);
  7587. #endif
  7588. #ifdef IPV6_RECVTCLASS
  7589. ADD_INT_MACRO(m, IPV6_RECVTCLASS);
  7590. #endif
  7591. #ifdef IPV6_RTHDR
  7592. ADD_INT_MACRO(m, IPV6_RTHDR);
  7593. #endif
  7594. #ifdef IPV6_RTHDRDSTOPTS
  7595. ADD_INT_MACRO(m, IPV6_RTHDRDSTOPTS);
  7596. #endif
  7597. #ifdef IPV6_RTHDR_TYPE_0
  7598. ADD_INT_MACRO(m, IPV6_RTHDR_TYPE_0);
  7599. #endif
  7600. #ifdef IPV6_RECVPATHMTU
  7601. ADD_INT_MACRO(m, IPV6_RECVPATHMTU);
  7602. #endif
  7603. #ifdef IPV6_TCLASS
  7604. ADD_INT_MACRO(m, IPV6_TCLASS);
  7605. #endif
  7606. #ifdef IPV6_USE_MIN_MTU
  7607. ADD_INT_MACRO(m, IPV6_USE_MIN_MTU);
  7608. #endif
  7609. /* TCP options */
  7610. #ifdef TCP_NODELAY
  7611. ADD_INT_MACRO(m, TCP_NODELAY);
  7612. #endif
  7613. #ifdef TCP_MAXSEG
  7614. ADD_INT_MACRO(m, TCP_MAXSEG);
  7615. #endif
  7616. #ifdef TCP_CORK
  7617. ADD_INT_MACRO(m, TCP_CORK);
  7618. #endif
  7619. #ifdef TCP_KEEPIDLE
  7620. ADD_INT_MACRO(m, TCP_KEEPIDLE);
  7621. #endif
  7622. /* TCP_KEEPALIVE is OSX's TCP_KEEPIDLE equivalent */
  7623. #if defined(__APPLE__) && defined(TCP_KEEPALIVE)
  7624. ADD_INT_MACRO(m, TCP_KEEPALIVE);
  7625. #endif
  7626. #ifdef TCP_KEEPINTVL
  7627. ADD_INT_MACRO(m, TCP_KEEPINTVL);
  7628. #endif
  7629. #ifdef TCP_KEEPCNT
  7630. ADD_INT_MACRO(m, TCP_KEEPCNT);
  7631. #endif
  7632. #ifdef TCP_SYNCNT
  7633. ADD_INT_MACRO(m, TCP_SYNCNT);
  7634. #endif
  7635. #ifdef TCP_LINGER2
  7636. ADD_INT_MACRO(m, TCP_LINGER2);
  7637. #endif
  7638. #ifdef TCP_DEFER_ACCEPT
  7639. ADD_INT_MACRO(m, TCP_DEFER_ACCEPT);
  7640. #endif
  7641. #ifdef TCP_WINDOW_CLAMP
  7642. ADD_INT_MACRO(m, TCP_WINDOW_CLAMP);
  7643. #endif
  7644. #ifdef TCP_INFO
  7645. ADD_INT_MACRO(m, TCP_INFO);
  7646. #endif
  7647. #ifdef TCP_CONNECTION_INFO
  7648. ADD_INT_MACRO(m, TCP_CONNECTION_INFO);
  7649. #endif
  7650. #ifdef TCP_QUICKACK
  7651. ADD_INT_MACRO(m, TCP_QUICKACK);
  7652. #endif
  7653. #ifdef TCP_CONGESTION
  7654. ADD_INT_MACRO(m, TCP_CONGESTION);
  7655. #endif
  7656. #ifdef TCP_MD5SIG
  7657. ADD_INT_MACRO(m, TCP_MD5SIG);
  7658. #endif
  7659. #ifdef TCP_THIN_LINEAR_TIMEOUTS
  7660. ADD_INT_MACRO(m, TCP_THIN_LINEAR_TIMEOUTS);
  7661. #endif
  7662. #ifdef TCP_THIN_DUPACK
  7663. ADD_INT_MACRO(m, TCP_THIN_DUPACK);
  7664. #endif
  7665. #ifdef TCP_USER_TIMEOUT
  7666. ADD_INT_MACRO(m, TCP_USER_TIMEOUT);
  7667. #endif
  7668. #ifdef TCP_REPAIR
  7669. ADD_INT_MACRO(m, TCP_REPAIR);
  7670. #endif
  7671. #ifdef TCP_REPAIR_QUEUE
  7672. ADD_INT_MACRO(m, TCP_REPAIR_QUEUE);
  7673. #endif
  7674. #ifdef TCP_QUEUE_SEQ
  7675. ADD_INT_MACRO(m, TCP_QUEUE_SEQ);
  7676. #endif
  7677. #ifdef TCP_REPAIR_OPTIONS
  7678. ADD_INT_MACRO(m, TCP_REPAIR_OPTIONS);
  7679. #endif
  7680. #ifdef TCP_FASTOPEN
  7681. ADD_INT_MACRO(m, TCP_FASTOPEN);
  7682. #endif
  7683. #ifdef TCP_TIMESTAMP
  7684. ADD_INT_MACRO(m, TCP_TIMESTAMP);
  7685. #endif
  7686. #ifdef TCP_NOTSENT_LOWAT
  7687. ADD_INT_MACRO(m, TCP_NOTSENT_LOWAT);
  7688. #endif
  7689. #ifdef TCP_CC_INFO
  7690. ADD_INT_MACRO(m, TCP_CC_INFO);
  7691. #endif
  7692. #ifdef TCP_SAVE_SYN
  7693. ADD_INT_MACRO(m, TCP_SAVE_SYN);
  7694. #endif
  7695. #ifdef TCP_SAVED_SYN
  7696. ADD_INT_MACRO(m, TCP_SAVED_SYN);
  7697. #endif
  7698. #ifdef TCP_REPAIR_WINDOW
  7699. ADD_INT_MACRO(m, TCP_REPAIR_WINDOW);
  7700. #endif
  7701. #ifdef TCP_FASTOPEN_CONNECT
  7702. ADD_INT_MACRO(m, TCP_FASTOPEN_CONNECT);
  7703. #endif
  7704. #ifdef TCP_ULP
  7705. ADD_INT_MACRO(m, TCP_ULP);
  7706. #endif
  7707. #ifdef TCP_MD5SIG_EXT
  7708. ADD_INT_MACRO(m, TCP_MD5SIG_EXT);
  7709. #endif
  7710. #ifdef TCP_FASTOPEN_KEY
  7711. ADD_INT_MACRO(m, TCP_FASTOPEN_KEY);
  7712. #endif
  7713. #ifdef TCP_FASTOPEN_NO_COOKIE
  7714. ADD_INT_MACRO(m, TCP_FASTOPEN_NO_COOKIE);
  7715. #endif
  7716. #ifdef TCP_ZEROCOPY_RECEIVE
  7717. ADD_INT_MACRO(m, TCP_ZEROCOPY_RECEIVE);
  7718. #endif
  7719. #ifdef TCP_INQ
  7720. ADD_INT_MACRO(m, TCP_INQ);
  7721. #endif
  7722. #ifdef TCP_TX_DELAY
  7723. ADD_INT_MACRO(m, TCP_TX_DELAY);
  7724. #endif
  7725. /* IPX options */
  7726. #ifdef IPX_TYPE
  7727. ADD_INT_MACRO(m, IPX_TYPE);
  7728. #endif
  7729. /* Reliable Datagram Sockets */
  7730. #ifdef RDS_CMSG_RDMA_ARGS
  7731. ADD_INT_MACRO(m, RDS_CMSG_RDMA_ARGS);
  7732. #endif
  7733. #ifdef RDS_CMSG_RDMA_DEST
  7734. ADD_INT_MACRO(m, RDS_CMSG_RDMA_DEST);
  7735. #endif
  7736. #ifdef RDS_CMSG_RDMA_MAP
  7737. ADD_INT_MACRO(m, RDS_CMSG_RDMA_MAP);
  7738. #endif
  7739. #ifdef RDS_CMSG_RDMA_STATUS
  7740. ADD_INT_MACRO(m, RDS_CMSG_RDMA_STATUS);
  7741. #endif
  7742. #ifdef RDS_CMSG_RDMA_UPDATE
  7743. ADD_INT_MACRO(m, RDS_CMSG_RDMA_UPDATE);
  7744. #endif
  7745. #ifdef RDS_RDMA_READWRITE
  7746. ADD_INT_MACRO(m, RDS_RDMA_READWRITE);
  7747. #endif
  7748. #ifdef RDS_RDMA_FENCE
  7749. ADD_INT_MACRO(m, RDS_RDMA_FENCE);
  7750. #endif
  7751. #ifdef RDS_RDMA_INVALIDATE
  7752. ADD_INT_MACRO(m, RDS_RDMA_INVALIDATE);
  7753. #endif
  7754. #ifdef RDS_RDMA_USE_ONCE
  7755. ADD_INT_MACRO(m, RDS_RDMA_USE_ONCE);
  7756. #endif
  7757. #ifdef RDS_RDMA_DONTWAIT
  7758. ADD_INT_MACRO(m, RDS_RDMA_DONTWAIT);
  7759. #endif
  7760. #ifdef RDS_RDMA_NOTIFY_ME
  7761. ADD_INT_MACRO(m, RDS_RDMA_NOTIFY_ME);
  7762. #endif
  7763. #ifdef RDS_RDMA_SILENT
  7764. ADD_INT_MACRO(m, RDS_RDMA_SILENT);
  7765. #endif
  7766. /* get{addr,name}info parameters */
  7767. #ifdef EAI_ADDRFAMILY
  7768. ADD_INT_MACRO(m, EAI_ADDRFAMILY);
  7769. #endif
  7770. #ifdef EAI_AGAIN
  7771. ADD_INT_MACRO(m, EAI_AGAIN);
  7772. #endif
  7773. #ifdef EAI_BADFLAGS
  7774. ADD_INT_MACRO(m, EAI_BADFLAGS);
  7775. #endif
  7776. #ifdef EAI_FAIL
  7777. ADD_INT_MACRO(m, EAI_FAIL);
  7778. #endif
  7779. #ifdef EAI_FAMILY
  7780. ADD_INT_MACRO(m, EAI_FAMILY);
  7781. #endif
  7782. #ifdef EAI_MEMORY
  7783. ADD_INT_MACRO(m, EAI_MEMORY);
  7784. #endif
  7785. #ifdef EAI_NODATA
  7786. ADD_INT_MACRO(m, EAI_NODATA);
  7787. #endif
  7788. #ifdef EAI_NONAME
  7789. ADD_INT_MACRO(m, EAI_NONAME);
  7790. #endif
  7791. #ifdef EAI_OVERFLOW
  7792. ADD_INT_MACRO(m, EAI_OVERFLOW);
  7793. #endif
  7794. #ifdef EAI_SERVICE
  7795. ADD_INT_MACRO(m, EAI_SERVICE);
  7796. #endif
  7797. #ifdef EAI_SOCKTYPE
  7798. ADD_INT_MACRO(m, EAI_SOCKTYPE);
  7799. #endif
  7800. #ifdef EAI_SYSTEM
  7801. ADD_INT_MACRO(m, EAI_SYSTEM);
  7802. #endif
  7803. #ifdef EAI_BADHINTS
  7804. ADD_INT_MACRO(m, EAI_BADHINTS);
  7805. #endif
  7806. #ifdef EAI_PROTOCOL
  7807. ADD_INT_MACRO(m, EAI_PROTOCOL);
  7808. #endif
  7809. #ifdef EAI_MAX
  7810. ADD_INT_MACRO(m, EAI_MAX);
  7811. #endif
  7812. #ifdef AI_PASSIVE
  7813. ADD_INT_MACRO(m, AI_PASSIVE);
  7814. #endif
  7815. #ifdef AI_CANONNAME
  7816. ADD_INT_MACRO(m, AI_CANONNAME);
  7817. #endif
  7818. #ifdef AI_NUMERICHOST
  7819. ADD_INT_MACRO(m, AI_NUMERICHOST);
  7820. #endif
  7821. #ifdef AI_NUMERICSERV
  7822. ADD_INT_MACRO(m, AI_NUMERICSERV);
  7823. #endif
  7824. #ifdef AI_MASK
  7825. ADD_INT_MACRO(m, AI_MASK);
  7826. #endif
  7827. #ifdef AI_ALL
  7828. ADD_INT_MACRO(m, AI_ALL);
  7829. #endif
  7830. #ifdef AI_V4MAPPED_CFG
  7831. ADD_INT_MACRO(m, AI_V4MAPPED_CFG);
  7832. #endif
  7833. #ifdef AI_ADDRCONFIG
  7834. ADD_INT_MACRO(m, AI_ADDRCONFIG);
  7835. #endif
  7836. #ifdef AI_V4MAPPED
  7837. ADD_INT_MACRO(m, AI_V4MAPPED);
  7838. #endif
  7839. #ifdef AI_DEFAULT
  7840. ADD_INT_MACRO(m, AI_DEFAULT);
  7841. #endif
  7842. #ifdef NI_MAXHOST
  7843. ADD_INT_MACRO(m, NI_MAXHOST);
  7844. #endif
  7845. #ifdef NI_MAXSERV
  7846. ADD_INT_MACRO(m, NI_MAXSERV);
  7847. #endif
  7848. #ifdef NI_NOFQDN
  7849. ADD_INT_MACRO(m, NI_NOFQDN);
  7850. #endif
  7851. #ifdef NI_NUMERICHOST
  7852. ADD_INT_MACRO(m, NI_NUMERICHOST);
  7853. #endif
  7854. #ifdef NI_NAMEREQD
  7855. ADD_INT_MACRO(m, NI_NAMEREQD);
  7856. #endif
  7857. #ifdef NI_NUMERICSERV
  7858. ADD_INT_MACRO(m, NI_NUMERICSERV);
  7859. #endif
  7860. #ifdef NI_DGRAM
  7861. ADD_INT_MACRO(m, NI_DGRAM);
  7862. #endif
  7863. /* shutdown() parameters */
  7864. #ifdef SHUT_RD
  7865. ADD_INT_MACRO(m, SHUT_RD);
  7866. #elif defined(SD_RECEIVE)
  7867. ADD_INT_CONST(m, "SHUT_RD", SD_RECEIVE);
  7868. #else
  7869. ADD_INT_CONST(m, "SHUT_RD", 0);
  7870. #endif
  7871. #ifdef SHUT_WR
  7872. ADD_INT_MACRO(m, SHUT_WR);
  7873. #elif defined(SD_SEND)
  7874. ADD_INT_CONST(m, "SHUT_WR", SD_SEND);
  7875. #else
  7876. ADD_INT_CONST(m, "SHUT_WR", 1);
  7877. #endif
  7878. #ifdef SHUT_RDWR
  7879. ADD_INT_MACRO(m, SHUT_RDWR);
  7880. #elif defined(SD_BOTH)
  7881. ADD_INT_CONST(m, "SHUT_RDWR", SD_BOTH);
  7882. #else
  7883. ADD_INT_CONST(m, "SHUT_RDWR", 2);
  7884. #endif
  7885. #ifdef SIO_RCVALL
  7886. {
  7887. DWORD codes[] = {SIO_RCVALL, SIO_KEEPALIVE_VALS,
  7888. #if defined(SIO_LOOPBACK_FAST_PATH)
  7889. SIO_LOOPBACK_FAST_PATH
  7890. #endif
  7891. };
  7892. const char *names[] = {"SIO_RCVALL", "SIO_KEEPALIVE_VALS",
  7893. #if defined(SIO_LOOPBACK_FAST_PATH)
  7894. "SIO_LOOPBACK_FAST_PATH"
  7895. #endif
  7896. };
  7897. int i;
  7898. for (i = 0; i < Py_ARRAY_LENGTH(codes); ++i) {
  7899. PyObject *tmp = PyLong_FromUnsignedLong(codes[i]);
  7900. if (tmp == NULL) {
  7901. goto error;
  7902. }
  7903. int rc = PyModule_AddObjectRef(m, names[i], tmp);
  7904. Py_DECREF(tmp);
  7905. if (rc < 0) {
  7906. goto error;
  7907. }
  7908. }
  7909. }
  7910. ADD_INT_MACRO(m, RCVALL_OFF);
  7911. ADD_INT_MACRO(m, RCVALL_ON);
  7912. ADD_INT_MACRO(m, RCVALL_SOCKETLEVELONLY);
  7913. #ifdef RCVALL_IPLEVEL
  7914. ADD_INT_MACRO(m, RCVALL_IPLEVEL);
  7915. #endif
  7916. #ifdef RCVALL_MAX
  7917. ADD_INT_MACRO(m, RCVALL_MAX);
  7918. #endif
  7919. #endif /* _MSTCPIP_ */
  7920. /* Initialize gethostbyname lock */
  7921. #if defined(USE_GETHOSTBYNAME_LOCK)
  7922. netdb_lock = PyThread_allocate_lock();
  7923. #endif
  7924. #ifdef MS_WINDOWS
  7925. /* remove some flags on older version Windows during run-time */
  7926. if (remove_unusable_flags(m) < 0) {
  7927. goto error;
  7928. }
  7929. #endif
  7930. #undef ADD_INT_MACRO
  7931. #undef ADD_INT_CONST
  7932. #undef ADD_STR_CONST
  7933. return 0;
  7934. error:
  7935. return -1;
  7936. }
  7937. static struct PyModuleDef_Slot socket_slots[] = {
  7938. {Py_mod_exec, socket_exec},
  7939. {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  7940. {0, NULL},
  7941. };
  7942. static int
  7943. socket_traverse(PyObject *mod, visitproc visit, void *arg)
  7944. {
  7945. socket_state *state = get_module_state(mod);
  7946. Py_VISIT(state->sock_type);
  7947. Py_VISIT(state->socket_herror);
  7948. Py_VISIT(state->socket_gaierror);
  7949. return 0;
  7950. }
  7951. static int
  7952. socket_clear(PyObject *mod)
  7953. {
  7954. socket_state *state = get_module_state(mod);
  7955. Py_CLEAR(state->sock_type);
  7956. Py_CLEAR(state->socket_herror);
  7957. Py_CLEAR(state->socket_gaierror);
  7958. return 0;
  7959. }
  7960. static void
  7961. socket_free(void *mod)
  7962. {
  7963. (void)socket_clear((PyObject *)mod);
  7964. }
  7965. static struct PyModuleDef socketmodule = {
  7966. .m_base = PyModuleDef_HEAD_INIT,
  7967. .m_name = PySocket_MODULE_NAME,
  7968. .m_doc = socket_doc,
  7969. .m_size = sizeof(socket_state),
  7970. .m_methods = socket_methods,
  7971. .m_slots = socket_slots,
  7972. .m_traverse = socket_traverse,
  7973. .m_clear = socket_clear,
  7974. .m_free = socket_free,
  7975. };
  7976. PyMODINIT_FUNC
  7977. PyInit__socket(void)
  7978. {
  7979. return PyModuleDef_Init(&socketmodule);
  7980. }