pcap-linux.c 197 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187
  1. /*
  2. * pcap-linux.c: Packet capture interface to the Linux kernel
  3. *
  4. * Copyright (c) 2000 Torsten Landschoff <torsten@debian.org>
  5. * Sebastian Krahmer <krahmer@cs.uni-potsdam.de>
  6. *
  7. * License: BSD
  8. *
  9. * Redistribution and use in source and binary forms, with or without
  10. * modification, are permitted provided that the following conditions
  11. * are met:
  12. *
  13. * 1. Redistributions of source code must retain the above copyright
  14. * notice, this list of conditions and the following disclaimer.
  15. * 2. Redistributions in binary form must reproduce the above copyright
  16. * notice, this list of conditions and the following disclaimer in
  17. * the documentation and/or other materials provided with the
  18. * distribution.
  19. * 3. The names of the authors may not be used to endorse or promote
  20. * products derived from this software without specific prior
  21. * written permission.
  22. *
  23. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
  24. * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
  25. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
  26. *
  27. * Modifications: Added PACKET_MMAP support
  28. * Paolo Abeni <paolo.abeni@email.it>
  29. * Added TPACKET_V3 support
  30. * Gabor Tatarka <gabor.tatarka@ericsson.com>
  31. *
  32. * based on previous works of:
  33. * Simon Patarin <patarin@cs.unibo.it>
  34. * Phil Wood <cpw@lanl.gov>
  35. *
  36. * Monitor-mode support for mac80211 includes code taken from the iw
  37. * command; the copyright notice for that code is
  38. *
  39. * Copyright (c) 2007, 2008 Johannes Berg
  40. * Copyright (c) 2007 Andy Lutomirski
  41. * Copyright (c) 2007 Mike Kershaw
  42. * Copyright (c) 2008 Gábor Stefanik
  43. *
  44. * All rights reserved.
  45. *
  46. * Redistribution and use in source and binary forms, with or without
  47. * modification, are permitted provided that the following conditions
  48. * are met:
  49. * 1. Redistributions of source code must retain the above copyright
  50. * notice, this list of conditions and the following disclaimer.
  51. * 2. Redistributions in binary form must reproduce the above copyright
  52. * notice, this list of conditions and the following disclaimer in the
  53. * documentation and/or other materials provided with the distribution.
  54. * 3. The name of the author may not be used to endorse or promote products
  55. * derived from this software without specific prior written permission.
  56. *
  57. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  58. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  59. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  60. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  61. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  62. * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  63. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
  64. * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  65. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  66. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  67. * SUCH DAMAGE.
  68. */
  69. /*
  70. * Known problems with 2.0[.x] kernels:
  71. *
  72. * - The loopback device gives every packet twice; on 2.2[.x] kernels,
  73. * if we use PF_PACKET, we can filter out the transmitted version
  74. * of the packet by using data in the "sockaddr_ll" returned by
  75. * "recvfrom()", but, on 2.0[.x] kernels, we have to use
  76. * PF_INET/SOCK_PACKET, which means "recvfrom()" supplies a
  77. * "sockaddr_pkt" which doesn't give us enough information to let
  78. * us do that.
  79. *
  80. * - We have to set the interface's IFF_PROMISC flag ourselves, if
  81. * we're to run in promiscuous mode, which means we have to turn
  82. * it off ourselves when we're done; the kernel doesn't keep track
  83. * of how many sockets are listening promiscuously, which means
  84. * it won't get turned off automatically when no sockets are
  85. * listening promiscuously. We catch "pcap_close()" and, for
  86. * interfaces we put into promiscuous mode, take them out of
  87. * promiscuous mode - which isn't necessarily the right thing to
  88. * do, if another socket also requested promiscuous mode between
  89. * the time when we opened the socket and the time when we close
  90. * the socket.
  91. *
  92. * - MSG_TRUNC isn't supported, so you can't specify that "recvfrom()"
  93. * return the amount of data that you could have read, rather than
  94. * the amount that was returned, so we can't just allocate a buffer
  95. * whose size is the snapshot length and pass the snapshot length
  96. * as the byte count, and also pass MSG_TRUNC, so that the return
  97. * value tells us how long the packet was on the wire.
  98. *
  99. * This means that, if we want to get the actual size of the packet,
  100. * so we can return it in the "len" field of the packet header,
  101. * we have to read the entire packet, not just the part that fits
  102. * within the snapshot length, and thus waste CPU time copying data
  103. * from the kernel that our caller won't see.
  104. *
  105. * We have to get the actual size, and supply it in "len", because
  106. * otherwise, the IP dissector in tcpdump, for example, will complain
  107. * about "truncated-ip", as the packet will appear to have been
  108. * shorter, on the wire, than the IP header said it should have been.
  109. */
  110. #define _GNU_SOURCE
  111. #ifdef HAVE_CONFIG_H
  112. #include <config.h>
  113. #endif
  114. #include <errno.h>
  115. #include <stdio.h>
  116. #include <stdlib.h>
  117. #include <ctype.h>
  118. #include <unistd.h>
  119. #include <fcntl.h>
  120. #include <string.h>
  121. #include <limits.h>
  122. #include <sys/stat.h>
  123. #include <sys/socket.h>
  124. #include <sys/ioctl.h>
  125. #include <sys/utsname.h>
  126. #include <sys/mman.h>
  127. #include <linux/if.h>
  128. #include <linux/if_packet.h>
  129. #include <linux/sockios.h>
  130. #include <netinet/in.h>
  131. #include <linux/if_ether.h>
  132. #include <net/if_arp.h>
  133. #include <poll.h>
  134. #include <dirent.h>
  135. #include "pcap-int.h"
  136. #include "pcap/sll.h"
  137. #include "pcap/vlan.h"
  138. /*
  139. * If PF_PACKET is defined, we can use {SOCK_RAW,SOCK_DGRAM}/PF_PACKET
  140. * sockets rather than SOCK_PACKET sockets.
  141. *
  142. * To use them, we include <linux/if_packet.h> rather than
  143. * <netpacket/packet.h>; we do so because
  144. *
  145. * some Linux distributions (e.g., Slackware 4.0) have 2.2 or
  146. * later kernels and libc5, and don't provide a <netpacket/packet.h>
  147. * file;
  148. *
  149. * not all versions of glibc2 have a <netpacket/packet.h> file
  150. * that defines stuff needed for some of the 2.4-or-later-kernel
  151. * features, so if the system has a 2.4 or later kernel, we
  152. * still can't use those features.
  153. *
  154. * We're already including a number of other <linux/XXX.h> headers, and
  155. * this code is Linux-specific (no other OS has PF_PACKET sockets as
  156. * a raw packet capture mechanism), so it's not as if you gain any
  157. * useful portability by using <netpacket/packet.h>
  158. *
  159. * XXX - should we just include <linux/if_packet.h> even if PF_PACKET
  160. * isn't defined? It only defines one data structure in 2.0.x, so
  161. * it shouldn't cause any problems.
  162. */
  163. #ifdef PF_PACKET
  164. # include <linux/if_packet.h>
  165. /*
  166. * On at least some Linux distributions (for example, Red Hat 5.2),
  167. * there's no <netpacket/packet.h> file, but PF_PACKET is defined if
  168. * you include <sys/socket.h>, but <linux/if_packet.h> doesn't define
  169. * any of the PF_PACKET stuff such as "struct sockaddr_ll" or any of
  170. * the PACKET_xxx stuff.
  171. *
  172. * So we check whether PACKET_HOST is defined, and assume that we have
  173. * PF_PACKET sockets only if it is defined.
  174. */
  175. # ifdef PACKET_HOST
  176. # define HAVE_PF_PACKET_SOCKETS
  177. # ifdef PACKET_AUXDATA
  178. # define HAVE_PACKET_AUXDATA
  179. # endif /* PACKET_AUXDATA */
  180. # endif /* PACKET_HOST */
  181. /* check for memory mapped access avaibility. We assume every needed
  182. * struct is defined if the macro TPACKET_HDRLEN is defined, because it
  183. * uses many ring related structs and macros */
  184. # ifdef PCAP_SUPPORT_PACKET_RING
  185. # ifdef TPACKET_HDRLEN
  186. # define HAVE_PACKET_RING
  187. # ifdef TPACKET3_HDRLEN
  188. # define HAVE_TPACKET3
  189. # endif /* TPACKET3_HDRLEN */
  190. # ifdef TPACKET2_HDRLEN
  191. # define HAVE_TPACKET2
  192. # else /* TPACKET2_HDRLEN */
  193. # define TPACKET_V1 0 /* Old kernel with only V1, so no TPACKET_Vn defined */
  194. # endif /* TPACKET2_HDRLEN */
  195. # endif /* TPACKET_HDRLEN */
  196. # endif /* PCAP_SUPPORT_PACKET_RING */
  197. #endif /* PF_PACKET */
  198. #ifdef SO_ATTACH_FILTER
  199. #include <linux/types.h>
  200. #include <linux/filter.h>
  201. #endif
  202. #ifdef HAVE_LINUX_NET_TSTAMP_H
  203. #include <linux/net_tstamp.h>
  204. #endif
  205. #ifdef HAVE_LINUX_SOCKIOS_H
  206. #include <linux/sockios.h>
  207. #endif
  208. #ifdef HAVE_LINUX_IF_BONDING_H
  209. #include <linux/if_bonding.h>
  210. /*
  211. * The ioctl code to use to check whether a device is a bonding device.
  212. */
  213. #if defined(SIOCBONDINFOQUERY)
  214. #define BOND_INFO_QUERY_IOCTL SIOCBONDINFOQUERY
  215. #elif defined(BOND_INFO_QUERY_OLD)
  216. #define BOND_INFO_QUERY_IOCTL BOND_INFO_QUERY_OLD
  217. #endif
  218. #endif /* HAVE_LINUX_IF_BONDING_H */
  219. /*
  220. * Got Wireless Extensions?
  221. */
  222. #ifdef HAVE_LINUX_WIRELESS_H
  223. #include <linux/wireless.h>
  224. #endif /* HAVE_LINUX_WIRELESS_H */
  225. /*
  226. * Got libnl?
  227. */
  228. #ifdef HAVE_LIBNL
  229. #include <linux/nl80211.h>
  230. #include <netlink/genl/genl.h>
  231. #include <netlink/genl/family.h>
  232. #include <netlink/genl/ctrl.h>
  233. #include <netlink/msg.h>
  234. #include <netlink/attr.h>
  235. #endif /* HAVE_LIBNL */
  236. /*
  237. * Got ethtool support?
  238. */
  239. #ifdef HAVE_LINUX_ETHTOOL_H
  240. #include <linux/ethtool.h>
  241. #endif
  242. #ifndef HAVE_SOCKLEN_T
  243. typedef int socklen_t;
  244. #endif
  245. #ifndef MSG_TRUNC
  246. /*
  247. * This is being compiled on a system that lacks MSG_TRUNC; define it
  248. * with the value it has in the 2.2 and later kernels, so that, on
  249. * those kernels, when we pass it in the flags argument to "recvfrom()"
  250. * we're passing the right value and thus get the MSG_TRUNC behavior
  251. * we want. (We don't get that behavior on 2.0[.x] kernels, because
  252. * they didn't support MSG_TRUNC.)
  253. */
  254. #define MSG_TRUNC 0x20
  255. #endif
  256. #ifndef SOL_PACKET
  257. /*
  258. * This is being compiled on a system that lacks SOL_PACKET; define it
  259. * with the value it has in the 2.2 and later kernels, so that we can
  260. * set promiscuous mode in the good modern way rather than the old
  261. * 2.0-kernel crappy way.
  262. */
  263. #define SOL_PACKET 263
  264. #endif
  265. #define MAX_LINKHEADER_SIZE 256
  266. /*
  267. * When capturing on all interfaces we use this as the buffer size.
  268. * Should be bigger then all MTUs that occur in real life.
  269. * 64kB should be enough for now.
  270. */
  271. #define BIGGER_THAN_ALL_MTUS (64*1024)
  272. /*
  273. * Private data for capturing on Linux SOCK_PACKET or PF_PACKET sockets.
  274. */
  275. struct pcap_linux {
  276. u_int packets_read; /* count of packets read with recvfrom() */
  277. long proc_dropped; /* packets reported dropped by /proc/net/dev */
  278. struct pcap_stat stat;
  279. char *device; /* device name */
  280. int filter_in_userland; /* must filter in userland */
  281. int blocks_to_filter_in_userland;
  282. int must_do_on_close; /* stuff we must do when we close */
  283. int timeout; /* timeout for buffering */
  284. int sock_packet; /* using Linux 2.0 compatible interface */
  285. int cooked; /* using SOCK_DGRAM rather than SOCK_RAW */
  286. int ifindex; /* interface index of device we're bound to */
  287. int lo_ifindex; /* interface index of the loopback device */
  288. bpf_u_int32 oldmode; /* mode to restore when turning monitor mode off */
  289. char *mondevice; /* mac80211 monitor device we created */
  290. u_char *mmapbuf; /* memory-mapped region pointer */
  291. size_t mmapbuflen; /* size of region */
  292. int vlan_offset; /* offset at which to insert vlan tags; if -1, don't insert */
  293. u_int tp_version; /* version of tpacket_hdr for mmaped ring */
  294. u_int tp_hdrlen; /* hdrlen of tpacket_hdr for mmaped ring */
  295. u_char *oneshot_buffer; /* buffer for copy of packet */
  296. int poll_timeout; /* timeout to use in poll() */
  297. #ifdef HAVE_TPACKET3
  298. unsigned char *current_packet; /* Current packet within the TPACKET_V3 block. Move to next block if NULL. */
  299. int packets_left; /* Unhandled packets left within the block from previous call to pcap_read_linux_mmap_v3 in case of TPACKET_V3. */
  300. #endif
  301. };
  302. /*
  303. * Stuff to do when we close.
  304. */
  305. #define MUST_CLEAR_PROMISC 0x00000001 /* clear promiscuous mode */
  306. #define MUST_CLEAR_RFMON 0x00000002 /* clear rfmon (monitor) mode */
  307. #define MUST_DELETE_MONIF 0x00000004 /* delete monitor-mode interface */
  308. /*
  309. * Prototypes for internal functions and methods.
  310. */
  311. static int get_if_flags(const char *, bpf_u_int32 *, char *);
  312. static int is_wifi(int, const char *);
  313. static void map_arphrd_to_dlt(pcap_t *, int, int, const char *, int);
  314. #ifdef HAVE_PF_PACKET_SOCKETS
  315. static short int map_packet_type_to_sll_type(short int);
  316. #endif
  317. static int pcap_activate_linux(pcap_t *);
  318. static int activate_old(pcap_t *);
  319. static int activate_new(pcap_t *);
  320. static int activate_mmap(pcap_t *, int *);
  321. static int pcap_can_set_rfmon_linux(pcap_t *);
  322. static int pcap_read_linux(pcap_t *, int, pcap_handler, u_char *);
  323. static int pcap_read_packet(pcap_t *, pcap_handler, u_char *);
  324. static int pcap_inject_linux(pcap_t *, const void *, size_t);
  325. static int pcap_stats_linux(pcap_t *, struct pcap_stat *);
  326. static int pcap_setfilter_linux(pcap_t *, struct bpf_program *);
  327. static int pcap_setdirection_linux(pcap_t *, pcap_direction_t);
  328. static int pcap_set_datalink_linux(pcap_t *, int);
  329. static void pcap_cleanup_linux(pcap_t *);
  330. /*
  331. * This is what the header structure looks like in a 64-bit kernel;
  332. * we use this, rather than struct tpacket_hdr, if we're using
  333. * TPACKET_V1 in 32-bit code running on a 64-bit kernel.
  334. */
  335. struct tpacket_hdr_64 {
  336. uint64_t tp_status;
  337. unsigned int tp_len;
  338. unsigned int tp_snaplen;
  339. unsigned short tp_mac;
  340. unsigned short tp_net;
  341. unsigned int tp_sec;
  342. unsigned int tp_usec;
  343. };
  344. /*
  345. * We use this internally as the tpacket version for TPACKET_V1 in
  346. * 32-bit code on a 64-bit kernel.
  347. */
  348. #define TPACKET_V1_64 99
  349. union thdr {
  350. struct tpacket_hdr *h1;
  351. struct tpacket_hdr_64 *h1_64;
  352. #ifdef HAVE_TPACKET2
  353. struct tpacket2_hdr *h2;
  354. #endif
  355. #ifdef HAVE_TPACKET3
  356. struct tpacket_block_desc *h3;
  357. #endif
  358. void *raw;
  359. };
  360. #ifdef HAVE_PACKET_RING
  361. #define RING_GET_FRAME_AT(h, offset) (((union thdr **)h->buffer)[(offset)])
  362. #define RING_GET_CURRENT_FRAME(h) RING_GET_FRAME_AT(h, h->offset)
  363. static void destroy_ring(pcap_t *handle);
  364. static int create_ring(pcap_t *handle, int *status);
  365. static int prepare_tpacket_socket(pcap_t *handle);
  366. static void pcap_cleanup_linux_mmap(pcap_t *);
  367. static int pcap_read_linux_mmap_v1(pcap_t *, int, pcap_handler , u_char *);
  368. static int pcap_read_linux_mmap_v1_64(pcap_t *, int, pcap_handler , u_char *);
  369. #ifdef HAVE_TPACKET2
  370. static int pcap_read_linux_mmap_v2(pcap_t *, int, pcap_handler , u_char *);
  371. #endif
  372. #ifdef HAVE_TPACKET3
  373. static int pcap_read_linux_mmap_v3(pcap_t *, int, pcap_handler , u_char *);
  374. #endif
  375. static int pcap_setfilter_linux_mmap(pcap_t *, struct bpf_program *);
  376. static int pcap_setnonblock_mmap(pcap_t *p, int nonblock);
  377. static int pcap_getnonblock_mmap(pcap_t *p);
  378. static void pcap_oneshot_mmap(u_char *user, const struct pcap_pkthdr *h,
  379. const u_char *bytes);
  380. #endif
  381. /*
  382. * In pre-3.0 kernels, the tp_vlan_tci field is set to whatever the
  383. * vlan_tci field in the skbuff is. 0 can either mean "not on a VLAN"
  384. * or "on VLAN 0". There is no flag set in the tp_status field to
  385. * distinguish between them.
  386. *
  387. * In 3.0 and later kernels, if there's a VLAN tag present, the tp_vlan_tci
  388. * field is set to the VLAN tag, and the TP_STATUS_VLAN_VALID flag is set
  389. * in the tp_status field, otherwise the tp_vlan_tci field is set to 0 and
  390. * the TP_STATUS_VLAN_VALID flag isn't set in the tp_status field.
  391. *
  392. * With a pre-3.0 kernel, we cannot distinguish between packets with no
  393. * VLAN tag and packets on VLAN 0, so we will mishandle some packets, and
  394. * there's nothing we can do about that.
  395. *
  396. * So, on those systems, which never set the TP_STATUS_VLAN_VALID flag, we
  397. * continue the behavior of earlier libpcaps, wherein we treated packets
  398. * with a VLAN tag of 0 as being packets without a VLAN tag rather than packets
  399. * on VLAN 0. We do this by treating packets with a tp_vlan_tci of 0 and
  400. * with the TP_STATUS_VLAN_VALID flag not set in tp_status as not having
  401. * VLAN tags. This does the right thing on 3.0 and later kernels, and
  402. * continues the old unfixably-imperfect behavior on pre-3.0 kernels.
  403. *
  404. * If TP_STATUS_VLAN_VALID isn't defined, we test it as the 0x10 bit; it
  405. * has that value in 3.0 and later kernels.
  406. */
  407. #ifdef TP_STATUS_VLAN_VALID
  408. #define VLAN_VALID(hdr, hv) ((hv)->tp_vlan_tci != 0 || ((hdr)->tp_status & TP_STATUS_VLAN_VALID))
  409. #else
  410. /*
  411. * This is being compiled on a system that lacks TP_STATUS_VLAN_VALID,
  412. * so we testwith the value it has in the 3.0 and later kernels, so
  413. * we can test it if we're running on a system that has it. (If we're
  414. * running on a system that doesn't have it, it won't be set in the
  415. * tp_status field, so the tests of it will always fail; that means
  416. * we behave the way we did before we introduced this macro.)
  417. */
  418. #define VLAN_VALID(hdr, hv) ((hv)->tp_vlan_tci != 0 || ((hdr)->tp_status & 0x10))
  419. #endif
  420. #ifdef TP_STATUS_VLAN_TPID_VALID
  421. # define VLAN_TPID(hdr, hv) (((hv)->tp_vlan_tpid || ((hdr)->tp_status & TP_STATUS_VLAN_TPID_VALID)) ? (hv)->tp_vlan_tpid : ETH_P_8021Q)
  422. #else
  423. # define VLAN_TPID(hdr, hv) ETH_P_8021Q
  424. #endif
  425. /*
  426. * Wrap some ioctl calls
  427. */
  428. #ifdef HAVE_PF_PACKET_SOCKETS
  429. static int iface_get_id(int fd, const char *device, char *ebuf);
  430. #endif /* HAVE_PF_PACKET_SOCKETS */
  431. static int iface_get_mtu(int fd, const char *device, char *ebuf);
  432. static int iface_get_arptype(int fd, const char *device, char *ebuf);
  433. #ifdef HAVE_PF_PACKET_SOCKETS
  434. static int iface_bind(int fd, int ifindex, char *ebuf, int protocol);
  435. #ifdef IW_MODE_MONITOR
  436. static int has_wext(int sock_fd, const char *device, char *ebuf);
  437. #endif /* IW_MODE_MONITOR */
  438. static int enter_rfmon_mode(pcap_t *handle, int sock_fd,
  439. const char *device);
  440. #endif /* HAVE_PF_PACKET_SOCKETS */
  441. #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
  442. static int iface_ethtool_get_ts_info(const char *device, pcap_t *handle,
  443. char *ebuf);
  444. #endif
  445. #ifdef HAVE_PACKET_RING
  446. static int iface_get_offload(pcap_t *handle);
  447. #endif
  448. static int iface_bind_old(int fd, const char *device, char *ebuf);
  449. #ifdef SO_ATTACH_FILTER
  450. static int fix_program(pcap_t *handle, struct sock_fprog *fcode,
  451. int is_mapped);
  452. static int fix_offset(struct bpf_insn *p);
  453. static int set_kernel_filter(pcap_t *handle, struct sock_fprog *fcode);
  454. static int reset_kernel_filter(pcap_t *handle);
  455. static struct sock_filter total_insn
  456. = BPF_STMT(BPF_RET | BPF_K, 0);
  457. static struct sock_fprog total_fcode
  458. = { 1, &total_insn };
  459. #endif /* SO_ATTACH_FILTER */
  460. pcap_t *
  461. pcap_create_interface(const char *device, char *ebuf)
  462. {
  463. pcap_t *handle;
  464. handle = pcap_create_common(ebuf, sizeof (struct pcap_linux));
  465. if (handle == NULL)
  466. return NULL;
  467. handle->activate_op = pcap_activate_linux;
  468. handle->can_set_rfmon_op = pcap_can_set_rfmon_linux;
  469. #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
  470. /*
  471. * See what time stamp types we support.
  472. */
  473. if (iface_ethtool_get_ts_info(device, handle, ebuf) == -1) {
  474. pcap_close(handle);
  475. return NULL;
  476. }
  477. #endif
  478. #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
  479. /*
  480. * We claim that we support microsecond and nanosecond time
  481. * stamps.
  482. *
  483. * XXX - with adapter-supplied time stamps, can we choose
  484. * microsecond or nanosecond time stamps on arbitrary
  485. * adapters?
  486. */
  487. handle->tstamp_precision_count = 2;
  488. handle->tstamp_precision_list = malloc(2 * sizeof(u_int));
  489. if (handle->tstamp_precision_list == NULL) {
  490. pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
  491. errno, "malloc");
  492. pcap_close(handle);
  493. return NULL;
  494. }
  495. handle->tstamp_precision_list[0] = PCAP_TSTAMP_PRECISION_MICRO;
  496. handle->tstamp_precision_list[1] = PCAP_TSTAMP_PRECISION_NANO;
  497. #endif /* defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS) */
  498. return handle;
  499. }
  500. #ifdef HAVE_LIBNL
  501. /*
  502. * If interface {if} is a mac80211 driver, the file
  503. * /sys/class/net/{if}/phy80211 is a symlink to
  504. * /sys/class/ieee80211/{phydev}, for some {phydev}.
  505. *
  506. * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
  507. * least, has a "wmaster0" device and a "wlan0" device; the
  508. * latter is the one with the IP address. Both show up in
  509. * "tcpdump -D" output. Capturing on the wmaster0 device
  510. * captures with 802.11 headers.
  511. *
  512. * airmon-ng searches through /sys/class/net for devices named
  513. * monN, starting with mon0; as soon as one *doesn't* exist,
  514. * it chooses that as the monitor device name. If the "iw"
  515. * command exists, it does "iw dev {if} interface add {monif}
  516. * type monitor", where {monif} is the monitor device. It
  517. * then (sigh) sleeps .1 second, and then configures the
  518. * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
  519. * is a file, it writes {mondev}, without a newline, to that file,
  520. * and again (sigh) sleeps .1 second, and then iwconfig's that
  521. * device into monitor mode and configures it up. Otherwise,
  522. * you can't do monitor mode.
  523. *
  524. * All these devices are "glued" together by having the
  525. * /sys/class/net/{device}/phy80211 links pointing to the same
  526. * place, so, given a wmaster, wlan, or mon device, you can
  527. * find the other devices by looking for devices with
  528. * the same phy80211 link.
  529. *
  530. * To turn monitor mode off, delete the monitor interface,
  531. * either with "iw dev {monif} interface del" or by sending
  532. * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
  533. *
  534. * Note: if you try to create a monitor device named "monN", and
  535. * there's already a "monN" device, it fails, as least with
  536. * the netlink interface (which is what iw uses), with a return
  537. * value of -ENFILE. (Return values are negative errnos.) We
  538. * could probably use that to find an unused device.
  539. *
  540. * Yes, you can have multiple monitor devices for a given
  541. * physical device.
  542. */
  543. /*
  544. * Is this a mac80211 device? If so, fill in the physical device path and
  545. * return 1; if not, return 0. On an error, fill in handle->errbuf and
  546. * return PCAP_ERROR.
  547. */
  548. static int
  549. get_mac80211_phydev(pcap_t *handle, const char *device, char *phydev_path,
  550. size_t phydev_max_pathlen)
  551. {
  552. char *pathstr;
  553. ssize_t bytes_read;
  554. /*
  555. * Generate the path string for the symlink to the physical device.
  556. */
  557. if (asprintf(&pathstr, "/sys/class/net/%s/phy80211", device) == -1) {
  558. pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  559. "%s: Can't generate path name string for /sys/class/net device",
  560. device);
  561. return PCAP_ERROR;
  562. }
  563. bytes_read = readlink(pathstr, phydev_path, phydev_max_pathlen);
  564. if (bytes_read == -1) {
  565. if (errno == ENOENT || errno == EINVAL) {
  566. /*
  567. * Doesn't exist, or not a symlink; assume that
  568. * means it's not a mac80211 device.
  569. */
  570. free(pathstr);
  571. return 0;
  572. }
  573. pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
  574. errno, "%s: Can't readlink %s", device, pathstr);
  575. free(pathstr);
  576. return PCAP_ERROR;
  577. }
  578. free(pathstr);
  579. phydev_path[bytes_read] = '\0';
  580. return 1;
  581. }
  582. #ifdef HAVE_LIBNL_SOCKETS
  583. #define get_nl_errmsg nl_geterror
  584. #else
  585. /* libnl 2.x compatibility code */
  586. #define nl_sock nl_handle
  587. static inline struct nl_handle *
  588. nl_socket_alloc(void)
  589. {
  590. return nl_handle_alloc();
  591. }
  592. static inline void
  593. nl_socket_free(struct nl_handle *h)
  594. {
  595. nl_handle_destroy(h);
  596. }
  597. #define get_nl_errmsg strerror
  598. static inline int
  599. __genl_ctrl_alloc_cache(struct nl_handle *h, struct nl_cache **cache)
  600. {
  601. struct nl_cache *tmp = genl_ctrl_alloc_cache(h);
  602. if (!tmp)
  603. return -ENOMEM;
  604. *cache = tmp;
  605. return 0;
  606. }
  607. #define genl_ctrl_alloc_cache __genl_ctrl_alloc_cache
  608. #endif /* !HAVE_LIBNL_SOCKETS */
  609. struct nl80211_state {
  610. struct nl_sock *nl_sock;
  611. struct nl_cache *nl_cache;
  612. struct genl_family *nl80211;
  613. };
  614. static int
  615. nl80211_init(pcap_t *handle, struct nl80211_state *state, const char *device)
  616. {
  617. int err;
  618. state->nl_sock = nl_socket_alloc();
  619. if (!state->nl_sock) {
  620. pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  621. "%s: failed to allocate netlink handle", device);
  622. return PCAP_ERROR;
  623. }
  624. if (genl_connect(state->nl_sock)) {
  625. pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  626. "%s: failed to connect to generic netlink", device);
  627. goto out_handle_destroy;
  628. }
  629. err = genl_ctrl_alloc_cache(state->nl_sock, &state->nl_cache);
  630. if (err < 0) {
  631. pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  632. "%s: failed to allocate generic netlink cache: %s",
  633. device, get_nl_errmsg(-err));
  634. goto out_handle_destroy;
  635. }
  636. state->nl80211 = genl_ctrl_search_by_name(state->nl_cache, "nl80211");
  637. if (!state->nl80211) {
  638. pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  639. "%s: nl80211 not found", device);
  640. goto out_cache_free;
  641. }
  642. return 0;
  643. out_cache_free:
  644. nl_cache_free(state->nl_cache);
  645. out_handle_destroy:
  646. nl_socket_free(state->nl_sock);
  647. return PCAP_ERROR;
  648. }
  649. static void
  650. nl80211_cleanup(struct nl80211_state *state)
  651. {
  652. genl_family_put(state->nl80211);
  653. nl_cache_free(state->nl_cache);
  654. nl_socket_free(state->nl_sock);
  655. }
  656. static int
  657. del_mon_if(pcap_t *handle, int sock_fd, struct nl80211_state *state,
  658. const char *device, const char *mondevice);
  659. static int
  660. add_mon_if(pcap_t *handle, int sock_fd, struct nl80211_state *state,
  661. const char *device, const char *mondevice)
  662. {
  663. struct pcap_linux *handlep = handle->priv;
  664. int ifindex;
  665. struct nl_msg *msg;
  666. int err;
  667. ifindex = iface_get_id(sock_fd, device, handle->errbuf);
  668. if (ifindex == -1)
  669. return PCAP_ERROR;
  670. msg = nlmsg_alloc();
  671. if (!msg) {
  672. pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  673. "%s: failed to allocate netlink msg", device);
  674. return PCAP_ERROR;
  675. }
  676. genlmsg_put(msg, 0, 0, genl_family_get_id(state->nl80211), 0,
  677. 0, NL80211_CMD_NEW_INTERFACE, 0);
  678. NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
  679. NLA_PUT_STRING(msg, NL80211_ATTR_IFNAME, mondevice);
  680. NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, NL80211_IFTYPE_MONITOR);
  681. err = nl_send_auto_complete(state->nl_sock, msg);
  682. if (err < 0) {
  683. #if defined HAVE_LIBNL_NLE
  684. if (err == -NLE_FAILURE) {
  685. #else
  686. if (err == -ENFILE) {
  687. #endif
  688. /*
  689. * Device not available; our caller should just
  690. * keep trying. (libnl 2.x maps ENFILE to
  691. * NLE_FAILURE; it can also map other errors
  692. * to that, but there's not much we can do
  693. * about that.)
  694. */
  695. nlmsg_free(msg);
  696. return 0;
  697. } else {
  698. /*
  699. * Real failure, not just "that device is not
  700. * available.
  701. */
  702. pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  703. "%s: nl_send_auto_complete failed adding %s interface: %s",
  704. device, mondevice, get_nl_errmsg(-err));
  705. nlmsg_free(msg);
  706. return PCAP_ERROR;
  707. }
  708. }
  709. err = nl_wait_for_ack(state->nl_sock);
  710. if (err < 0) {
  711. #if defined HAVE_LIBNL_NLE
  712. if (err == -NLE_FAILURE) {
  713. #else
  714. if (err == -ENFILE) {
  715. #endif
  716. /*
  717. * Device not available; our caller should just
  718. * keep trying. (libnl 2.x maps ENFILE to
  719. * NLE_FAILURE; it can also map other errors
  720. * to that, but there's not much we can do
  721. * about that.)
  722. */
  723. nlmsg_free(msg);
  724. return 0;
  725. } else {
  726. /*
  727. * Real failure, not just "that device is not
  728. * available.
  729. */
  730. pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  731. "%s: nl_wait_for_ack failed adding %s interface: %s",
  732. device, mondevice, get_nl_errmsg(-err));
  733. nlmsg_free(msg);
  734. return PCAP_ERROR;
  735. }
  736. }
  737. /*
  738. * Success.
  739. */
  740. nlmsg_free(msg);
  741. /*
  742. * Try to remember the monitor device.
  743. */
  744. handlep->mondevice = strdup(mondevice);
  745. if (handlep->mondevice == NULL) {
  746. pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
  747. errno, "strdup");
  748. /*
  749. * Get rid of the monitor device.
  750. */
  751. del_mon_if(handle, sock_fd, state, device, mondevice);
  752. return PCAP_ERROR;
  753. }
  754. return 1;
  755. nla_put_failure:
  756. pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  757. "%s: nl_put failed adding %s interface",
  758. device, mondevice);
  759. nlmsg_free(msg);
  760. return PCAP_ERROR;
  761. }
  762. static int
  763. del_mon_if(pcap_t *handle, int sock_fd, struct nl80211_state *state,
  764. const char *device, const char *mondevice)
  765. {
  766. int ifindex;
  767. struct nl_msg *msg;
  768. int err;
  769. ifindex = iface_get_id(sock_fd, mondevice, handle->errbuf);
  770. if (ifindex == -1)
  771. return PCAP_ERROR;
  772. msg = nlmsg_alloc();
  773. if (!msg) {
  774. pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  775. "%s: failed to allocate netlink msg", device);
  776. return PCAP_ERROR;
  777. }
  778. genlmsg_put(msg, 0, 0, genl_family_get_id(state->nl80211), 0,
  779. 0, NL80211_CMD_DEL_INTERFACE, 0);
  780. NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
  781. err = nl_send_auto_complete(state->nl_sock, msg);
  782. if (err < 0) {
  783. pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  784. "%s: nl_send_auto_complete failed deleting %s interface: %s",
  785. device, mondevice, get_nl_errmsg(-err));
  786. nlmsg_free(msg);
  787. return PCAP_ERROR;
  788. }
  789. err = nl_wait_for_ack(state->nl_sock);
  790. if (err < 0) {
  791. pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  792. "%s: nl_wait_for_ack failed adding %s interface: %s",
  793. device, mondevice, get_nl_errmsg(-err));
  794. nlmsg_free(msg);
  795. return PCAP_ERROR;
  796. }
  797. /*
  798. * Success.
  799. */
  800. nlmsg_free(msg);
  801. return 1;
  802. nla_put_failure:
  803. pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  804. "%s: nl_put failed deleting %s interface",
  805. device, mondevice);
  806. nlmsg_free(msg);
  807. return PCAP_ERROR;
  808. }
  809. static int
  810. enter_rfmon_mode_mac80211(pcap_t *handle, int sock_fd, const char *device)
  811. {
  812. struct pcap_linux *handlep = handle->priv;
  813. int ret;
  814. char phydev_path[PATH_MAX+1];
  815. struct nl80211_state nlstate;
  816. struct ifreq ifr;
  817. u_int n;
  818. /*
  819. * Is this a mac80211 device?
  820. */
  821. ret = get_mac80211_phydev(handle, device, phydev_path, PATH_MAX);
  822. if (ret < 0)
  823. return ret; /* error */
  824. if (ret == 0)
  825. return 0; /* no error, but not mac80211 device */
  826. /*
  827. * XXX - is this already a monN device?
  828. * If so, we're done.
  829. * Is that determined by old Wireless Extensions ioctls?
  830. */
  831. /*
  832. * OK, it's apparently a mac80211 device.
  833. * Try to find an unused monN device for it.
  834. */
  835. ret = nl80211_init(handle, &nlstate, device);
  836. if (ret != 0)
  837. return ret;
  838. for (n = 0; n < UINT_MAX; n++) {
  839. /*
  840. * Try mon{n}.
  841. */
  842. char mondevice[3+10+1]; /* mon{UINT_MAX}\0 */
  843. pcap_snprintf(mondevice, sizeof mondevice, "mon%u", n);
  844. ret = add_mon_if(handle, sock_fd, &nlstate, device, mondevice);
  845. if (ret == 1) {
  846. /*
  847. * Success. We don't clean up the libnl state
  848. * yet, as we'll be using it later.
  849. */
  850. goto added;
  851. }
  852. if (ret < 0) {
  853. /*
  854. * Hard failure. Just return ret; handle->errbuf
  855. * has already been set.
  856. */
  857. nl80211_cleanup(&nlstate);
  858. return ret;
  859. }
  860. }
  861. pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  862. "%s: No free monN interfaces", device);
  863. nl80211_cleanup(&nlstate);
  864. return PCAP_ERROR;
  865. added:
  866. #if 0
  867. /*
  868. * Sleep for .1 seconds.
  869. */
  870. delay.tv_sec = 0;
  871. delay.tv_nsec = 500000000;
  872. nanosleep(&delay, NULL);
  873. #endif
  874. /*
  875. * If we haven't already done so, arrange to have
  876. * "pcap_close_all()" called when we exit.
  877. */
  878. if (!pcap_do_addexit(handle)) {
  879. /*
  880. * "atexit()" failed; don't put the interface
  881. * in rfmon mode, just give up.
  882. */
  883. del_mon_if(handle, sock_fd, &nlstate, device,
  884. handlep->mondevice);
  885. nl80211_cleanup(&nlstate);
  886. return PCAP_ERROR;
  887. }
  888. /*
  889. * Now configure the monitor interface up.
  890. */
  891. memset(&ifr, 0, sizeof(ifr));
  892. strlcpy(ifr.ifr_name, handlep->mondevice, sizeof(ifr.ifr_name));
  893. if (ioctl(sock_fd, SIOCGIFFLAGS, &ifr) == -1) {
  894. pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
  895. errno, "%s: Can't get flags for %s", device,
  896. handlep->mondevice);
  897. del_mon_if(handle, sock_fd, &nlstate, device,
  898. handlep->mondevice);
  899. nl80211_cleanup(&nlstate);
  900. return PCAP_ERROR;
  901. }
  902. ifr.ifr_flags |= IFF_UP|IFF_RUNNING;
  903. if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
  904. pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
  905. errno, "%s: Can't set flags for %s", device,
  906. handlep->mondevice);
  907. del_mon_if(handle, sock_fd, &nlstate, device,
  908. handlep->mondevice);
  909. nl80211_cleanup(&nlstate);
  910. return PCAP_ERROR;
  911. }
  912. /*
  913. * Success. Clean up the libnl state.
  914. */
  915. nl80211_cleanup(&nlstate);
  916. /*
  917. * Note that we have to delete the monitor device when we close
  918. * the handle.
  919. */
  920. handlep->must_do_on_close |= MUST_DELETE_MONIF;
  921. /*
  922. * Add this to the list of pcaps to close when we exit.
  923. */
  924. pcap_add_to_pcaps_to_close(handle);
  925. return 1;
  926. }
  927. #endif /* HAVE_LIBNL */
  928. #ifdef IW_MODE_MONITOR
  929. /*
  930. * Bonding devices mishandle unknown ioctls; they fail with ENODEV
  931. * rather than ENOTSUP, EOPNOTSUPP, or ENOTTY, so Wireless Extensions
  932. * will fail with ENODEV if we try to do them on a bonding device,
  933. * making us return a "no such device" indication rather than just
  934. * saying "no Wireless Extensions".
  935. *
  936. * So we check for bonding devices, if we can, before trying those
  937. * ioctls, by trying a bonding device information query ioctl to see
  938. * whether it succeeds.
  939. */
  940. static int
  941. is_bonding_device(int fd, const char *device)
  942. {
  943. #ifdef BOND_INFO_QUERY_IOCTL
  944. struct ifreq ifr;
  945. ifbond ifb;
  946. memset(&ifr, 0, sizeof ifr);
  947. strlcpy(ifr.ifr_name, device, sizeof ifr.ifr_name);
  948. memset(&ifb, 0, sizeof ifb);
  949. ifr.ifr_data = (caddr_t)&ifb;
  950. if (ioctl(fd, BOND_INFO_QUERY_IOCTL, &ifr) == 0)
  951. return 1; /* success, so it's a bonding device */
  952. #endif /* BOND_INFO_QUERY_IOCTL */
  953. return 0; /* no, it's not a bonding device */
  954. }
  955. #endif /* IW_MODE_MONITOR */
  956. static int pcap_protocol(pcap_t *handle)
  957. {
  958. int protocol;
  959. protocol = handle->opt.protocol;
  960. if (protocol == 0)
  961. protocol = ETH_P_ALL;
  962. return htons(protocol);
  963. }
  964. static int
  965. pcap_can_set_rfmon_linux(pcap_t *handle)
  966. {
  967. #ifdef HAVE_LIBNL
  968. char phydev_path[PATH_MAX+1];
  969. int ret;
  970. #endif
  971. #ifdef IW_MODE_MONITOR
  972. int sock_fd;
  973. struct iwreq ireq;
  974. #endif
  975. if (strcmp(handle->opt.device, "any") == 0) {
  976. /*
  977. * Monitor mode makes no sense on the "any" device.
  978. */
  979. return 0;
  980. }
  981. #ifdef HAVE_LIBNL
  982. /*
  983. * Bleah. There doesn't seem to be a way to ask a mac80211
  984. * device, through libnl, whether it supports monitor mode;
  985. * we'll just check whether the device appears to be a
  986. * mac80211 device and, if so, assume the device supports
  987. * monitor mode.
  988. *
  989. * wmaster devices don't appear to support the Wireless
  990. * Extensions, but we can create a mon device for a
  991. * wmaster device, so we don't bother checking whether
  992. * a mac80211 device supports the Wireless Extensions.
  993. */
  994. ret = get_mac80211_phydev(handle, handle->opt.device, phydev_path,
  995. PATH_MAX);
  996. if (ret < 0)
  997. return ret; /* error */
  998. if (ret == 1)
  999. return 1; /* mac80211 device */
  1000. #endif
  1001. #ifdef IW_MODE_MONITOR
  1002. /*
  1003. * Bleah. There doesn't appear to be an ioctl to use to ask
  1004. * whether a device supports monitor mode; we'll just do
  1005. * SIOCGIWMODE and, if it succeeds, assume the device supports
  1006. * monitor mode.
  1007. *
  1008. * Open a socket on which to attempt to get the mode.
  1009. * (We assume that if we have Wireless Extensions support
  1010. * we also have PF_PACKET support.)
  1011. */
  1012. sock_fd = socket(PF_PACKET, SOCK_RAW, pcap_protocol(handle));
  1013. if (sock_fd == -1) {
  1014. pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
  1015. errno, "socket");
  1016. return PCAP_ERROR;
  1017. }
  1018. if (is_bonding_device(sock_fd, handle->opt.device)) {
  1019. /* It's a bonding device, so don't even try. */
  1020. close(sock_fd);
  1021. return 0;
  1022. }
  1023. /*
  1024. * Attempt to get the current mode.
  1025. */
  1026. strlcpy(ireq.ifr_ifrn.ifrn_name, handle->opt.device,
  1027. sizeof ireq.ifr_ifrn.ifrn_name);
  1028. if (ioctl(sock_fd, SIOCGIWMODE, &ireq) != -1) {
  1029. /*
  1030. * Well, we got the mode; assume we can set it.
  1031. */
  1032. close(sock_fd);
  1033. return 1;
  1034. }
  1035. if (errno == ENODEV) {
  1036. /* The device doesn't even exist. */
  1037. pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
  1038. errno, "SIOCGIWMODE failed");
  1039. close(sock_fd);
  1040. return PCAP_ERROR_NO_SUCH_DEVICE;
  1041. }
  1042. close(sock_fd);
  1043. #endif
  1044. return 0;
  1045. }
  1046. /*
  1047. * Grabs the number of dropped packets by the interface from /proc/net/dev.
  1048. *
  1049. * XXX - what about /sys/class/net/{interface name}/rx_*? There are
  1050. * individual devices giving, in ASCII, various rx_ and tx_ statistics.
  1051. *
  1052. * Or can we get them in binary form from netlink?
  1053. */
  1054. static long int
  1055. linux_if_drops(const char * if_name)
  1056. {
  1057. char buffer[512];
  1058. char * bufptr;
  1059. FILE * file;
  1060. int field_to_convert = 3, if_name_sz = strlen(if_name);
  1061. long int dropped_pkts = 0;
  1062. file = fopen("/proc/net/dev", "r");
  1063. if (!file)
  1064. return 0;
  1065. while (!dropped_pkts && fgets( buffer, sizeof(buffer), file ))
  1066. {
  1067. /* search for 'bytes' -- if its in there, then
  1068. that means we need to grab the fourth field. otherwise
  1069. grab the third field. */
  1070. if (field_to_convert != 4 && strstr(buffer, "bytes"))
  1071. {
  1072. field_to_convert = 4;
  1073. continue;
  1074. }
  1075. /* find iface and make sure it actually matches -- space before the name and : after it */
  1076. if ((bufptr = strstr(buffer, if_name)) &&
  1077. (bufptr == buffer || *(bufptr-1) == ' ') &&
  1078. *(bufptr + if_name_sz) == ':')
  1079. {
  1080. bufptr = bufptr + if_name_sz + 1;
  1081. /* grab the nth field from it */
  1082. while( --field_to_convert && *bufptr != '\0')
  1083. {
  1084. while (*bufptr != '\0' && *(bufptr++) == ' ');
  1085. while (*bufptr != '\0' && *(bufptr++) != ' ');
  1086. }
  1087. /* get rid of any final spaces */
  1088. while (*bufptr != '\0' && *bufptr == ' ') bufptr++;
  1089. if (*bufptr != '\0')
  1090. dropped_pkts = strtol(bufptr, NULL, 10);
  1091. break;
  1092. }
  1093. }
  1094. fclose(file);
  1095. return dropped_pkts;
  1096. }
  1097. /*
  1098. * With older kernels promiscuous mode is kind of interesting because we
  1099. * have to reset the interface before exiting. The problem can't really
  1100. * be solved without some daemon taking care of managing usage counts.
  1101. * If we put the interface into promiscuous mode, we set a flag indicating
  1102. * that we must take it out of that mode when the interface is closed,
  1103. * and, when closing the interface, if that flag is set we take it out
  1104. * of promiscuous mode.
  1105. *
  1106. * Even with newer kernels, we have the same issue with rfmon mode.
  1107. */
  1108. static void pcap_cleanup_linux( pcap_t *handle )
  1109. {
  1110. struct pcap_linux *handlep = handle->priv;
  1111. struct ifreq ifr;
  1112. #ifdef HAVE_LIBNL
  1113. struct nl80211_state nlstate;
  1114. int ret;
  1115. #endif /* HAVE_LIBNL */
  1116. #ifdef IW_MODE_MONITOR
  1117. int oldflags;
  1118. struct iwreq ireq;
  1119. #endif /* IW_MODE_MONITOR */
  1120. if (handlep->must_do_on_close != 0) {
  1121. /*
  1122. * There's something we have to do when closing this
  1123. * pcap_t.
  1124. */
  1125. if (handlep->must_do_on_close & MUST_CLEAR_PROMISC) {
  1126. /*
  1127. * We put the interface into promiscuous mode;
  1128. * take it out of promiscuous mode.
  1129. *
  1130. * XXX - if somebody else wants it in promiscuous
  1131. * mode, this code cannot know that, so it'll take
  1132. * it out of promiscuous mode. That's not fixable
  1133. * in 2.0[.x] kernels.
  1134. */
  1135. memset(&ifr, 0, sizeof(ifr));
  1136. strlcpy(ifr.ifr_name, handlep->device,
  1137. sizeof(ifr.ifr_name));
  1138. if (ioctl(handle->fd, SIOCGIFFLAGS, &ifr) == -1) {
  1139. fprintf(stderr,
  1140. "Can't restore interface %s flags (SIOCGIFFLAGS failed: %s).\n"
  1141. "Please adjust manually.\n"
  1142. "Hint: This can't happen with Linux >= 2.2.0.\n",
  1143. handlep->device, strerror(errno));
  1144. } else {
  1145. if (ifr.ifr_flags & IFF_PROMISC) {
  1146. /*
  1147. * Promiscuous mode is currently on;
  1148. * turn it off.
  1149. */
  1150. ifr.ifr_flags &= ~IFF_PROMISC;
  1151. if (ioctl(handle->fd, SIOCSIFFLAGS,
  1152. &ifr) == -1) {
  1153. fprintf(stderr,
  1154. "Can't restore interface %s flags (SIOCSIFFLAGS failed: %s).\n"
  1155. "Please adjust manually.\n"
  1156. "Hint: This can't happen with Linux >= 2.2.0.\n",
  1157. handlep->device,
  1158. strerror(errno));
  1159. }
  1160. }
  1161. }
  1162. }
  1163. #ifdef HAVE_LIBNL
  1164. if (handlep->must_do_on_close & MUST_DELETE_MONIF) {
  1165. ret = nl80211_init(handle, &nlstate, handlep->device);
  1166. if (ret >= 0) {
  1167. ret = del_mon_if(handle, handle->fd, &nlstate,
  1168. handlep->device, handlep->mondevice);
  1169. nl80211_cleanup(&nlstate);
  1170. }
  1171. if (ret < 0) {
  1172. fprintf(stderr,
  1173. "Can't delete monitor interface %s (%s).\n"
  1174. "Please delete manually.\n",
  1175. handlep->mondevice, handle->errbuf);
  1176. }
  1177. }
  1178. #endif /* HAVE_LIBNL */
  1179. #ifdef IW_MODE_MONITOR
  1180. if (handlep->must_do_on_close & MUST_CLEAR_RFMON) {
  1181. /*
  1182. * We put the interface into rfmon mode;
  1183. * take it out of rfmon mode.
  1184. *
  1185. * XXX - if somebody else wants it in rfmon
  1186. * mode, this code cannot know that, so it'll take
  1187. * it out of rfmon mode.
  1188. */
  1189. /*
  1190. * First, take the interface down if it's up;
  1191. * otherwise, we might get EBUSY.
  1192. * If we get errors, just drive on and print
  1193. * a warning if we can't restore the mode.
  1194. */
  1195. oldflags = 0;
  1196. memset(&ifr, 0, sizeof(ifr));
  1197. strlcpy(ifr.ifr_name, handlep->device,
  1198. sizeof(ifr.ifr_name));
  1199. if (ioctl(handle->fd, SIOCGIFFLAGS, &ifr) != -1) {
  1200. if (ifr.ifr_flags & IFF_UP) {
  1201. oldflags = ifr.ifr_flags;
  1202. ifr.ifr_flags &= ~IFF_UP;
  1203. if (ioctl(handle->fd, SIOCSIFFLAGS, &ifr) == -1)
  1204. oldflags = 0; /* didn't set, don't restore */
  1205. }
  1206. }
  1207. /*
  1208. * Now restore the mode.
  1209. */
  1210. strlcpy(ireq.ifr_ifrn.ifrn_name, handlep->device,
  1211. sizeof ireq.ifr_ifrn.ifrn_name);
  1212. ireq.u.mode = handlep->oldmode;
  1213. if (ioctl(handle->fd, SIOCSIWMODE, &ireq) == -1) {
  1214. /*
  1215. * Scientist, you've failed.
  1216. */
  1217. fprintf(stderr,
  1218. "Can't restore interface %s wireless mode (SIOCSIWMODE failed: %s).\n"
  1219. "Please adjust manually.\n",
  1220. handlep->device, strerror(errno));
  1221. }
  1222. /*
  1223. * Now bring the interface back up if we brought
  1224. * it down.
  1225. */
  1226. if (oldflags != 0) {
  1227. ifr.ifr_flags = oldflags;
  1228. if (ioctl(handle->fd, SIOCSIFFLAGS, &ifr) == -1) {
  1229. fprintf(stderr,
  1230. "Can't bring interface %s back up (SIOCSIFFLAGS failed: %s).\n"
  1231. "Please adjust manually.\n",
  1232. handlep->device, strerror(errno));
  1233. }
  1234. }
  1235. }
  1236. #endif /* IW_MODE_MONITOR */
  1237. /*
  1238. * Take this pcap out of the list of pcaps for which we
  1239. * have to take the interface out of some mode.
  1240. */
  1241. pcap_remove_from_pcaps_to_close(handle);
  1242. }
  1243. if (handlep->mondevice != NULL) {
  1244. free(handlep->mondevice);
  1245. handlep->mondevice = NULL;
  1246. }
  1247. if (handlep->device != NULL) {
  1248. free(handlep->device);
  1249. handlep->device = NULL;
  1250. }
  1251. pcap_cleanup_live_common(handle);
  1252. }
  1253. /*
  1254. * Set the timeout to be used in poll() with memory-mapped packet capture.
  1255. */
  1256. static void
  1257. set_poll_timeout(struct pcap_linux *handlep)
  1258. {
  1259. #ifdef HAVE_TPACKET3
  1260. struct utsname utsname;
  1261. char *version_component, *endp;
  1262. int major, minor;
  1263. int broken_tpacket_v3 = 1;
  1264. /*
  1265. * Some versions of TPACKET_V3 have annoying bugs/misfeatures
  1266. * around which we have to work. Determine if we have those
  1267. * problems or not.
  1268. */
  1269. if (uname(&utsname) == 0) {
  1270. /*
  1271. * 3.19 is the first release with a fixed version of
  1272. * TPACKET_V3. We treat anything before that as
  1273. * not haveing a fixed version; that may really mean
  1274. * it has *no* version.
  1275. */
  1276. version_component = utsname.release;
  1277. major = strtol(version_component, &endp, 10);
  1278. if (endp != version_component && *endp == '.') {
  1279. /*
  1280. * OK, that was a valid major version.
  1281. * Get the minor version.
  1282. */
  1283. version_component = endp + 1;
  1284. minor = strtol(version_component, &endp, 10);
  1285. if (endp != version_component &&
  1286. (*endp == '.' || *endp == '\0')) {
  1287. /*
  1288. * OK, that was a valid minor version.
  1289. * Is this 3.19 or newer?
  1290. */
  1291. if (major >= 4 || (major == 3 && minor >= 19)) {
  1292. /* Yes. TPACKET_V3 works correctly. */
  1293. broken_tpacket_v3 = 0;
  1294. }
  1295. }
  1296. }
  1297. }
  1298. #endif
  1299. if (handlep->timeout == 0) {
  1300. #ifdef HAVE_TPACKET3
  1301. /*
  1302. * XXX - due to a set of (mis)features in the TPACKET_V3
  1303. * kernel code prior to the 3.19 kernel, blocking forever
  1304. * with a TPACKET_V3 socket can, if few packets are
  1305. * arriving and passing the socket filter, cause most
  1306. * packets to be dropped. See libpcap issue #335 for the
  1307. * full painful story.
  1308. *
  1309. * The workaround is to have poll() time out very quickly,
  1310. * so we grab the frames handed to us, and return them to
  1311. * the kernel, ASAP.
  1312. */
  1313. if (handlep->tp_version == TPACKET_V3 && broken_tpacket_v3)
  1314. handlep->poll_timeout = 1; /* don't block for very long */
  1315. else
  1316. #endif
  1317. handlep->poll_timeout = -1; /* block forever */
  1318. } else if (handlep->timeout > 0) {
  1319. #ifdef HAVE_TPACKET3
  1320. /*
  1321. * For TPACKET_V3, the timeout is handled by the kernel,
  1322. * so block forever; that way, we don't get extra timeouts.
  1323. * Don't do that if we have a broken TPACKET_V3, though.
  1324. */
  1325. if (handlep->tp_version == TPACKET_V3 && !broken_tpacket_v3)
  1326. handlep->poll_timeout = -1; /* block forever, let TPACKET_V3 wake us up */
  1327. else
  1328. #endif
  1329. handlep->poll_timeout = handlep->timeout; /* block for that amount of time */
  1330. } else {
  1331. /*
  1332. * Non-blocking mode; we call poll() to pick up error
  1333. * indications, but we don't want it to wait for
  1334. * anything.
  1335. */
  1336. handlep->poll_timeout = 0;
  1337. }
  1338. }
  1339. /*
  1340. * Get a handle for a live capture from the given device. You can
  1341. * pass NULL as device to get all packages (without link level
  1342. * information of course). If you pass 1 as promisc the interface
  1343. * will be set to promiscous mode (XXX: I think this usage should
  1344. * be deprecated and functions be added to select that later allow
  1345. * modification of that values -- Torsten).
  1346. */
  1347. static int
  1348. pcap_activate_linux(pcap_t *handle)
  1349. {
  1350. struct pcap_linux *handlep = handle->priv;
  1351. const char *device;
  1352. struct ifreq ifr;
  1353. int status = 0;
  1354. int ret;
  1355. device = handle->opt.device;
  1356. /*
  1357. * Make sure the name we were handed will fit into the ioctls we
  1358. * might perform on the device; if not, return a "No such device"
  1359. * indication, as the Linux kernel shouldn't support creating
  1360. * a device whose name won't fit into those ioctls.
  1361. *
  1362. * "Will fit" means "will fit, complete with a null terminator",
  1363. * so if the length, which does *not* include the null terminator,
  1364. * is greater than *or equal to* the size of the field into which
  1365. * we'll be copying it, that won't fit.
  1366. */
  1367. if (strlen(device) >= sizeof(ifr.ifr_name)) {
  1368. status = PCAP_ERROR_NO_SUCH_DEVICE;
  1369. goto fail;
  1370. }
  1371. /*
  1372. * Turn a negative snapshot value (invalid), a snapshot value of
  1373. * 0 (unspecified), or a value bigger than the normal maximum
  1374. * value, into the maximum allowed value.
  1375. *
  1376. * If some application really *needs* a bigger snapshot
  1377. * length, we should just increase MAXIMUM_SNAPLEN.
  1378. */
  1379. if (handle->snapshot <= 0 || handle->snapshot > MAXIMUM_SNAPLEN)
  1380. handle->snapshot = MAXIMUM_SNAPLEN;
  1381. handle->inject_op = pcap_inject_linux;
  1382. handle->setfilter_op = pcap_setfilter_linux;
  1383. handle->setdirection_op = pcap_setdirection_linux;
  1384. handle->set_datalink_op = pcap_set_datalink_linux;
  1385. handle->getnonblock_op = pcap_getnonblock_fd;
  1386. handle->setnonblock_op = pcap_setnonblock_fd;
  1387. handle->cleanup_op = pcap_cleanup_linux;
  1388. handle->read_op = pcap_read_linux;
  1389. handle->stats_op = pcap_stats_linux;
  1390. /*
  1391. * The "any" device is a special device which causes us not
  1392. * to bind to a particular device and thus to look at all
  1393. * devices.
  1394. */
  1395. if (strcmp(device, "any") == 0) {
  1396. if (handle->opt.promisc) {
  1397. handle->opt.promisc = 0;
  1398. /* Just a warning. */
  1399. pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  1400. "Promiscuous mode not supported on the \"any\" device");
  1401. status = PCAP_WARNING_PROMISC_NOTSUP;
  1402. }
  1403. }
  1404. handlep->device = strdup(device);
  1405. if (handlep->device == NULL) {
  1406. pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
  1407. errno, "strdup");
  1408. return PCAP_ERROR;
  1409. }
  1410. /* copy timeout value */
  1411. handlep->timeout = handle->opt.timeout;
  1412. /*
  1413. * If we're in promiscuous mode, then we probably want
  1414. * to see when the interface drops packets too, so get an
  1415. * initial count from /proc/net/dev
  1416. */
  1417. if (handle->opt.promisc)
  1418. handlep->proc_dropped = linux_if_drops(handlep->device);
  1419. /*
  1420. * Current Linux kernels use the protocol family PF_PACKET to
  1421. * allow direct access to all packets on the network while
  1422. * older kernels had a special socket type SOCK_PACKET to
  1423. * implement this feature.
  1424. * While this old implementation is kind of obsolete we need
  1425. * to be compatible with older kernels for a while so we are
  1426. * trying both methods with the newer method preferred.
  1427. */
  1428. ret = activate_new(handle);
  1429. if (ret < 0) {
  1430. /*
  1431. * Fatal error with the new way; just fail.
  1432. * ret has the error return; if it's PCAP_ERROR,
  1433. * handle->errbuf has been set appropriately.
  1434. */
  1435. status = ret;
  1436. goto fail;
  1437. }
  1438. if (ret == 1) {
  1439. /*
  1440. * Success.
  1441. * Try to use memory-mapped access.
  1442. */
  1443. switch (activate_mmap(handle, &status)) {
  1444. case 1:
  1445. /*
  1446. * We succeeded. status has been
  1447. * set to the status to return,
  1448. * which might be 0, or might be
  1449. * a PCAP_WARNING_ value.
  1450. *
  1451. * Set the timeout to use in poll() before
  1452. * returning.
  1453. */
  1454. set_poll_timeout(handlep);
  1455. return status;
  1456. case 0:
  1457. /*
  1458. * Kernel doesn't support it - just continue
  1459. * with non-memory-mapped access.
  1460. */
  1461. break;
  1462. case -1:
  1463. /*
  1464. * We failed to set up to use it, or the kernel
  1465. * supports it, but we failed to enable it.
  1466. * ret has been set to the error status to
  1467. * return and, if it's PCAP_ERROR, handle->errbuf
  1468. * contains the error message.
  1469. */
  1470. status = ret;
  1471. goto fail;
  1472. }
  1473. }
  1474. else if (ret == 0) {
  1475. /* Non-fatal error; try old way */
  1476. if ((ret = activate_old(handle)) != 1) {
  1477. /*
  1478. * Both methods to open the packet socket failed.
  1479. * Tidy up and report our failure (handle->errbuf
  1480. * is expected to be set by the functions above).
  1481. */
  1482. status = ret;
  1483. goto fail;
  1484. }
  1485. }
  1486. /*
  1487. * We set up the socket, but not with memory-mapped access.
  1488. */
  1489. if (handle->opt.buffer_size != 0) {
  1490. /*
  1491. * Set the socket buffer size to the specified value.
  1492. */
  1493. if (setsockopt(handle->fd, SOL_SOCKET, SO_RCVBUF,
  1494. &handle->opt.buffer_size,
  1495. sizeof(handle->opt.buffer_size)) == -1) {
  1496. pcap_fmt_errmsg_for_errno(handle->errbuf,
  1497. PCAP_ERRBUF_SIZE, errno, "SO_RCVBUF");
  1498. status = PCAP_ERROR;
  1499. goto fail;
  1500. }
  1501. }
  1502. /* Allocate the buffer */
  1503. handle->buffer = malloc(handle->bufsize + handle->offset);
  1504. if (!handle->buffer) {
  1505. pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
  1506. errno, "malloc");
  1507. status = PCAP_ERROR;
  1508. goto fail;
  1509. }
  1510. /*
  1511. * "handle->fd" is a socket, so "select()" and "poll()"
  1512. * should work on it.
  1513. */
  1514. handle->selectable_fd = handle->fd;
  1515. return status;
  1516. fail:
  1517. pcap_cleanup_linux(handle);
  1518. return status;
  1519. }
  1520. /*
  1521. * Read at most max_packets from the capture stream and call the callback
  1522. * for each of them. Returns the number of packets handled or -1 if an
  1523. * error occured.
  1524. */
  1525. static int
  1526. pcap_read_linux(pcap_t *handle, int max_packets _U_, pcap_handler callback, u_char *user)
  1527. {
  1528. /*
  1529. * Currently, on Linux only one packet is delivered per read,
  1530. * so we don't loop.
  1531. */
  1532. return pcap_read_packet(handle, callback, user);
  1533. }
  1534. static int
  1535. pcap_set_datalink_linux(pcap_t *handle, int dlt)
  1536. {
  1537. handle->linktype = dlt;
  1538. return 0;
  1539. }
  1540. /*
  1541. * linux_check_direction()
  1542. *
  1543. * Do checks based on packet direction.
  1544. */
  1545. static inline int
  1546. linux_check_direction(const pcap_t *handle, const struct sockaddr_ll *sll)
  1547. {
  1548. struct pcap_linux *handlep = handle->priv;
  1549. if (sll->sll_pkttype == PACKET_OUTGOING) {
  1550. /*
  1551. * Outgoing packet.
  1552. * If this is from the loopback device, reject it;
  1553. * we'll see the packet as an incoming packet as well,
  1554. * and we don't want to see it twice.
  1555. */
  1556. if (sll->sll_ifindex == handlep->lo_ifindex)
  1557. return 0;
  1558. /*
  1559. * If this is an outgoing CAN or CAN FD frame, and
  1560. * the user doesn't only want outgoing packets,
  1561. * reject it; CAN devices and drivers, and the CAN
  1562. * stack, always arrange to loop back transmitted
  1563. * packets, so they also appear as incoming packets.
  1564. * We don't want duplicate packets, and we can't
  1565. * easily distinguish packets looped back by the CAN
  1566. * layer than those received by the CAN layer, so we
  1567. * eliminate this packet instead.
  1568. */
  1569. if ((sll->sll_protocol == LINUX_SLL_P_CAN ||
  1570. sll->sll_protocol == LINUX_SLL_P_CANFD) &&
  1571. handle->direction != PCAP_D_OUT)
  1572. return 0;
  1573. /*
  1574. * If the user only wants incoming packets, reject it.
  1575. */
  1576. if (handle->direction == PCAP_D_IN)
  1577. return 0;
  1578. } else {
  1579. /*
  1580. * Incoming packet.
  1581. * If the user only wants outgoing packets, reject it.
  1582. */
  1583. if (handle->direction == PCAP_D_OUT)
  1584. return 0;
  1585. }
  1586. return 1;
  1587. }
  1588. /*
  1589. * Read a packet from the socket calling the handler provided by
  1590. * the user. Returns the number of packets received or -1 if an
  1591. * error occured.
  1592. */
  1593. static int
  1594. pcap_read_packet(pcap_t *handle, pcap_handler callback, u_char *userdata)
  1595. {
  1596. struct pcap_linux *handlep = handle->priv;
  1597. u_char *bp;
  1598. int offset;
  1599. #ifdef HAVE_PF_PACKET_SOCKETS
  1600. struct sockaddr_ll from;
  1601. struct sll_header *hdrp;
  1602. #else
  1603. struct sockaddr from;
  1604. #endif
  1605. #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI)
  1606. struct iovec iov;
  1607. struct msghdr msg;
  1608. struct cmsghdr *cmsg;
  1609. union {
  1610. struct cmsghdr cmsg;
  1611. char buf[CMSG_SPACE(sizeof(struct tpacket_auxdata))];
  1612. } cmsg_buf;
  1613. #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI) */
  1614. socklen_t fromlen;
  1615. #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI) */
  1616. int packet_len, caplen;
  1617. struct pcap_pkthdr pcap_header;
  1618. struct bpf_aux_data aux_data;
  1619. #ifdef HAVE_PF_PACKET_SOCKETS
  1620. /*
  1621. * If this is a cooked device, leave extra room for a
  1622. * fake packet header.
  1623. */
  1624. if (handlep->cooked)
  1625. offset = SLL_HDR_LEN;
  1626. else
  1627. offset = 0;
  1628. #else
  1629. /*
  1630. * This system doesn't have PF_PACKET sockets, so it doesn't
  1631. * support cooked devices.
  1632. */
  1633. offset = 0;
  1634. #endif
  1635. /*
  1636. * Receive a single packet from the kernel.
  1637. * We ignore EINTR, as that might just be due to a signal
  1638. * being delivered - if the signal should interrupt the
  1639. * loop, the signal handler should call pcap_breakloop()
  1640. * to set handle->break_loop (we ignore it on other
  1641. * platforms as well).
  1642. * We also ignore ENETDOWN, so that we can continue to
  1643. * capture traffic if the interface goes down and comes
  1644. * back up again; comments in the kernel indicate that
  1645. * we'll just block waiting for packets if we try to
  1646. * receive from a socket that delivered ENETDOWN, and,
  1647. * if we're using a memory-mapped buffer, we won't even
  1648. * get notified of "network down" events.
  1649. */
  1650. bp = (u_char *)handle->buffer + handle->offset;
  1651. #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI)
  1652. msg.msg_name = &from;
  1653. msg.msg_namelen = sizeof(from);
  1654. msg.msg_iov = &iov;
  1655. msg.msg_iovlen = 1;
  1656. msg.msg_control = &cmsg_buf;
  1657. msg.msg_controllen = sizeof(cmsg_buf);
  1658. msg.msg_flags = 0;
  1659. iov.iov_len = handle->bufsize - offset;
  1660. iov.iov_base = bp + offset;
  1661. #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI) */
  1662. do {
  1663. /*
  1664. * Has "pcap_breakloop()" been called?
  1665. */
  1666. if (handle->break_loop) {
  1667. /*
  1668. * Yes - clear the flag that indicates that it has,
  1669. * and return PCAP_ERROR_BREAK as an indication that
  1670. * we were told to break out of the loop.
  1671. */
  1672. handle->break_loop = 0;
  1673. return PCAP_ERROR_BREAK;
  1674. }
  1675. #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI)
  1676. packet_len = recvmsg(handle->fd, &msg, MSG_TRUNC);
  1677. #else /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI) */
  1678. fromlen = sizeof(from);
  1679. packet_len = recvfrom(
  1680. handle->fd, bp + offset,
  1681. handle->bufsize - offset, MSG_TRUNC,
  1682. (struct sockaddr *) &from, &fromlen);
  1683. #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI) */
  1684. } while (packet_len == -1 && errno == EINTR);
  1685. /* Check if an error occured */
  1686. if (packet_len == -1) {
  1687. switch (errno) {
  1688. case EAGAIN:
  1689. return 0; /* no packet there */
  1690. case ENETDOWN:
  1691. /*
  1692. * The device on which we're capturing went away.
  1693. *
  1694. * XXX - we should really return
  1695. * PCAP_ERROR_IFACE_NOT_UP, but pcap_dispatch()
  1696. * etc. aren't defined to return that.
  1697. */
  1698. pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  1699. "The interface went down");
  1700. return PCAP_ERROR;
  1701. default:
  1702. pcap_fmt_errmsg_for_errno(handle->errbuf,
  1703. PCAP_ERRBUF_SIZE, errno, "recvfrom");
  1704. return PCAP_ERROR;
  1705. }
  1706. }
  1707. #ifdef HAVE_PF_PACKET_SOCKETS
  1708. if (!handlep->sock_packet) {
  1709. /*
  1710. * Unfortunately, there is a window between socket() and
  1711. * bind() where the kernel may queue packets from any
  1712. * interface. If we're bound to a particular interface,
  1713. * discard packets not from that interface.
  1714. *
  1715. * (If socket filters are supported, we could do the
  1716. * same thing we do when changing the filter; however,
  1717. * that won't handle packet sockets without socket
  1718. * filter support, and it's a bit more complicated.
  1719. * It would save some instructions per packet, however.)
  1720. */
  1721. if (handlep->ifindex != -1 &&
  1722. from.sll_ifindex != handlep->ifindex)
  1723. return 0;
  1724. /*
  1725. * Do checks based on packet direction.
  1726. * We can only do this if we're using PF_PACKET; the
  1727. * address returned for SOCK_PACKET is a "sockaddr_pkt"
  1728. * which lacks the relevant packet type information.
  1729. */
  1730. if (!linux_check_direction(handle, &from))
  1731. return 0;
  1732. }
  1733. #endif
  1734. #ifdef HAVE_PF_PACKET_SOCKETS
  1735. /*
  1736. * If this is a cooked device, fill in the fake packet header.
  1737. */
  1738. if (handlep->cooked) {
  1739. /*
  1740. * Add the length of the fake header to the length
  1741. * of packet data we read.
  1742. */
  1743. packet_len += SLL_HDR_LEN;
  1744. hdrp = (struct sll_header *)bp;
  1745. hdrp->sll_pkttype = map_packet_type_to_sll_type(from.sll_pkttype);
  1746. hdrp->sll_hatype = htons(from.sll_hatype);
  1747. hdrp->sll_halen = htons(from.sll_halen);
  1748. memcpy(hdrp->sll_addr, from.sll_addr,
  1749. (from.sll_halen > SLL_ADDRLEN) ?
  1750. SLL_ADDRLEN :
  1751. from.sll_halen);
  1752. hdrp->sll_protocol = from.sll_protocol;
  1753. }
  1754. /*
  1755. * Start out with no VLAN information.
  1756. */
  1757. aux_data.vlan_tag_present = 0;
  1758. aux_data.vlan_tag = 0;
  1759. #if defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI)
  1760. if (handlep->vlan_offset != -1) {
  1761. for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
  1762. struct tpacket_auxdata *aux;
  1763. unsigned int len;
  1764. struct vlan_tag *tag;
  1765. if (cmsg->cmsg_len < CMSG_LEN(sizeof(struct tpacket_auxdata)) ||
  1766. cmsg->cmsg_level != SOL_PACKET ||
  1767. cmsg->cmsg_type != PACKET_AUXDATA) {
  1768. /*
  1769. * This isn't a PACKET_AUXDATA auxiliary
  1770. * data item.
  1771. */
  1772. continue;
  1773. }
  1774. aux = (struct tpacket_auxdata *)CMSG_DATA(cmsg);
  1775. if (!VLAN_VALID(aux, aux)) {
  1776. /*
  1777. * There is no VLAN information in the
  1778. * auxiliary data.
  1779. */
  1780. continue;
  1781. }
  1782. len = (u_int)packet_len > iov.iov_len ? iov.iov_len : (u_int)packet_len;
  1783. if (len < (u_int)handlep->vlan_offset)
  1784. break;
  1785. /*
  1786. * Move everything in the header, except the
  1787. * type field, down VLAN_TAG_LEN bytes, to
  1788. * allow us to insert the VLAN tag between
  1789. * that stuff and the type field.
  1790. */
  1791. bp -= VLAN_TAG_LEN;
  1792. memmove(bp, bp + VLAN_TAG_LEN, handlep->vlan_offset);
  1793. /*
  1794. * Now insert the tag.
  1795. */
  1796. tag = (struct vlan_tag *)(bp + handlep->vlan_offset);
  1797. tag->vlan_tpid = htons(VLAN_TPID(aux, aux));
  1798. tag->vlan_tci = htons(aux->tp_vlan_tci);
  1799. /*
  1800. * Save a flag indicating that we have a VLAN tag,
  1801. * and the VLAN TCI, to bpf_aux_data struct for
  1802. * use by the BPF filter if we're doing the
  1803. * filtering in userland.
  1804. */
  1805. aux_data.vlan_tag_present = 1;
  1806. aux_data.vlan_tag = htons(aux->tp_vlan_tci) & 0x0fff;
  1807. /*
  1808. * Add the tag to the packet lengths.
  1809. */
  1810. packet_len += VLAN_TAG_LEN;
  1811. }
  1812. }
  1813. #endif /* defined(HAVE_PACKET_AUXDATA) && defined(HAVE_STRUCT_TPACKET_AUXDATA_TP_VLAN_TCI) */
  1814. #endif /* HAVE_PF_PACKET_SOCKETS */
  1815. /*
  1816. * XXX: According to the kernel source we should get the real
  1817. * packet len if calling recvfrom with MSG_TRUNC set. It does
  1818. * not seem to work here :(, but it is supported by this code
  1819. * anyway.
  1820. * To be honest the code RELIES on that feature so this is really
  1821. * broken with 2.2.x kernels.
  1822. * I spend a day to figure out what's going on and I found out
  1823. * that the following is happening:
  1824. *
  1825. * The packet comes from a random interface and the packet_rcv
  1826. * hook is called with a clone of the packet. That code inserts
  1827. * the packet into the receive queue of the packet socket.
  1828. * If a filter is attached to that socket that filter is run
  1829. * first - and there lies the problem. The default filter always
  1830. * cuts the packet at the snaplen:
  1831. *
  1832. * # tcpdump -d
  1833. * (000) ret #68
  1834. *
  1835. * So the packet filter cuts down the packet. The recvfrom call
  1836. * says "hey, it's only 68 bytes, it fits into the buffer" with
  1837. * the result that we don't get the real packet length. This
  1838. * is valid at least until kernel 2.2.17pre6.
  1839. *
  1840. * We currently handle this by making a copy of the filter
  1841. * program, fixing all "ret" instructions with non-zero
  1842. * operands to have an operand of MAXIMUM_SNAPLEN so that the
  1843. * filter doesn't truncate the packet, and supplying that modified
  1844. * filter to the kernel.
  1845. */
  1846. caplen = packet_len;
  1847. if (caplen > handle->snapshot)
  1848. caplen = handle->snapshot;
  1849. /* Run the packet filter if not using kernel filter */
  1850. if (handlep->filter_in_userland && handle->fcode.bf_insns) {
  1851. if (bpf_filter_with_aux_data(handle->fcode.bf_insns, bp,
  1852. packet_len, caplen, &aux_data) == 0) {
  1853. /* rejected by filter */
  1854. return 0;
  1855. }
  1856. }
  1857. /* Fill in our own header data */
  1858. /* get timestamp for this packet */
  1859. #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
  1860. if (handle->opt.tstamp_precision == PCAP_TSTAMP_PRECISION_NANO) {
  1861. if (ioctl(handle->fd, SIOCGSTAMPNS, &pcap_header.ts) == -1) {
  1862. pcap_fmt_errmsg_for_errno(handle->errbuf,
  1863. PCAP_ERRBUF_SIZE, errno, "SIOCGSTAMPNS");
  1864. return PCAP_ERROR;
  1865. }
  1866. } else
  1867. #endif
  1868. {
  1869. if (ioctl(handle->fd, SIOCGSTAMP, &pcap_header.ts) == -1) {
  1870. pcap_fmt_errmsg_for_errno(handle->errbuf,
  1871. PCAP_ERRBUF_SIZE, errno, "SIOCGSTAMP");
  1872. return PCAP_ERROR;
  1873. }
  1874. }
  1875. pcap_header.caplen = caplen;
  1876. pcap_header.len = packet_len;
  1877. /*
  1878. * Count the packet.
  1879. *
  1880. * Arguably, we should count them before we check the filter,
  1881. * as on many other platforms "ps_recv" counts packets
  1882. * handed to the filter rather than packets that passed
  1883. * the filter, but if filtering is done in the kernel, we
  1884. * can't get a count of packets that passed the filter,
  1885. * and that would mean the meaning of "ps_recv" wouldn't
  1886. * be the same on all Linux systems.
  1887. *
  1888. * XXX - it's not the same on all systems in any case;
  1889. * ideally, we should have a "get the statistics" call
  1890. * that supplies more counts and indicates which of them
  1891. * it supplies, so that we supply a count of packets
  1892. * handed to the filter only on platforms where that
  1893. * information is available.
  1894. *
  1895. * We count them here even if we can get the packet count
  1896. * from the kernel, as we can only determine at run time
  1897. * whether we'll be able to get it from the kernel (if
  1898. * HAVE_STRUCT_TPACKET_STATS isn't defined, we can't get it from
  1899. * the kernel, but if it is defined, the library might
  1900. * have been built with a 2.4 or later kernel, but we
  1901. * might be running on a 2.2[.x] kernel without Alexey
  1902. * Kuznetzov's turbopacket patches, and thus the kernel
  1903. * might not be able to supply those statistics). We
  1904. * could, I guess, try, when opening the socket, to get
  1905. * the statistics, and if we can not increment the count
  1906. * here, but it's not clear that always incrementing
  1907. * the count is more expensive than always testing a flag
  1908. * in memory.
  1909. *
  1910. * We keep the count in "handlep->packets_read", and use that
  1911. * for "ps_recv" if we can't get the statistics from the kernel.
  1912. * We do that because, if we *can* get the statistics from
  1913. * the kernel, we use "handlep->stat.ps_recv" and
  1914. * "handlep->stat.ps_drop" as running counts, as reading the
  1915. * statistics from the kernel resets the kernel statistics,
  1916. * and if we directly increment "handlep->stat.ps_recv" here,
  1917. * that means it will count packets *twice* on systems where
  1918. * we can get kernel statistics - once here, and once in
  1919. * pcap_stats_linux().
  1920. */
  1921. handlep->packets_read++;
  1922. /* Call the user supplied callback function */
  1923. callback(userdata, &pcap_header, bp);
  1924. return 1;
  1925. }
  1926. static int
  1927. pcap_inject_linux(pcap_t *handle, const void *buf, size_t size)
  1928. {
  1929. struct pcap_linux *handlep = handle->priv;
  1930. int ret;
  1931. #ifdef HAVE_PF_PACKET_SOCKETS
  1932. if (!handlep->sock_packet) {
  1933. /* PF_PACKET socket */
  1934. if (handlep->ifindex == -1) {
  1935. /*
  1936. * We don't support sending on the "any" device.
  1937. */
  1938. strlcpy(handle->errbuf,
  1939. "Sending packets isn't supported on the \"any\" device",
  1940. PCAP_ERRBUF_SIZE);
  1941. return (-1);
  1942. }
  1943. if (handlep->cooked) {
  1944. /*
  1945. * We don't support sending on the "any" device.
  1946. *
  1947. * XXX - how do you send on a bound cooked-mode
  1948. * socket?
  1949. * Is a "sendto()" required there?
  1950. */
  1951. strlcpy(handle->errbuf,
  1952. "Sending packets isn't supported in cooked mode",
  1953. PCAP_ERRBUF_SIZE);
  1954. return (-1);
  1955. }
  1956. }
  1957. #endif
  1958. ret = send(handle->fd, buf, size, 0);
  1959. if (ret == -1) {
  1960. pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
  1961. errno, "send");
  1962. return (-1);
  1963. }
  1964. return (ret);
  1965. }
  1966. /*
  1967. * Get the statistics for the given packet capture handle.
  1968. * Reports the number of dropped packets iff the kernel supports
  1969. * the PACKET_STATISTICS "getsockopt()" argument (2.4 and later
  1970. * kernels, and 2.2[.x] kernels with Alexey Kuznetzov's turbopacket
  1971. * patches); otherwise, that information isn't available, and we lie
  1972. * and report 0 as the count of dropped packets.
  1973. */
  1974. static int
  1975. pcap_stats_linux(pcap_t *handle, struct pcap_stat *stats)
  1976. {
  1977. struct pcap_linux *handlep = handle->priv;
  1978. #ifdef HAVE_STRUCT_TPACKET_STATS
  1979. #ifdef HAVE_TPACKET3
  1980. /*
  1981. * For sockets using TPACKET_V1 or TPACKET_V2, the extra
  1982. * stuff at the end of a struct tpacket_stats_v3 will not
  1983. * be filled in, and we don't look at it so this is OK even
  1984. * for those sockets. In addition, the PF_PACKET socket
  1985. * code in the kernel only uses the length parameter to
  1986. * compute how much data to copy out and to indicate how
  1987. * much data was copied out, so it's OK to base it on the
  1988. * size of a struct tpacket_stats.
  1989. *
  1990. * XXX - it's probably OK, in fact, to just use a
  1991. * struct tpacket_stats for V3 sockets, as we don't
  1992. * care about the tp_freeze_q_cnt stat.
  1993. */
  1994. struct tpacket_stats_v3 kstats;
  1995. #else /* HAVE_TPACKET3 */
  1996. struct tpacket_stats kstats;
  1997. #endif /* HAVE_TPACKET3 */
  1998. socklen_t len = sizeof (struct tpacket_stats);
  1999. #endif /* HAVE_STRUCT_TPACKET_STATS */
  2000. long if_dropped = 0;
  2001. /*
  2002. * To fill in ps_ifdrop, we parse /proc/net/dev for the number
  2003. */
  2004. if (handle->opt.promisc)
  2005. {
  2006. if_dropped = handlep->proc_dropped;
  2007. handlep->proc_dropped = linux_if_drops(handlep->device);
  2008. handlep->stat.ps_ifdrop += (handlep->proc_dropped - if_dropped);
  2009. }
  2010. #ifdef HAVE_STRUCT_TPACKET_STATS
  2011. /*
  2012. * Try to get the packet counts from the kernel.
  2013. */
  2014. if (getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS,
  2015. &kstats, &len) > -1) {
  2016. /*
  2017. * On systems where the PACKET_STATISTICS "getsockopt()"
  2018. * argument is supported on PF_PACKET sockets:
  2019. *
  2020. * "ps_recv" counts only packets that *passed* the
  2021. * filter, not packets that didn't pass the filter.
  2022. * This includes packets later dropped because we
  2023. * ran out of buffer space.
  2024. *
  2025. * "ps_drop" counts packets dropped because we ran
  2026. * out of buffer space. It doesn't count packets
  2027. * dropped by the interface driver. It counts only
  2028. * packets that passed the filter.
  2029. *
  2030. * See above for ps_ifdrop.
  2031. *
  2032. * Both statistics include packets not yet read from
  2033. * the kernel by libpcap, and thus not yet seen by
  2034. * the application.
  2035. *
  2036. * In "linux/net/packet/af_packet.c", at least in the
  2037. * 2.4.9 kernel, "tp_packets" is incremented for every
  2038. * packet that passes the packet filter *and* is
  2039. * successfully queued on the socket; "tp_drops" is
  2040. * incremented for every packet dropped because there's
  2041. * not enough free space in the socket buffer.
  2042. *
  2043. * When the statistics are returned for a PACKET_STATISTICS
  2044. * "getsockopt()" call, "tp_drops" is added to "tp_packets",
  2045. * so that "tp_packets" counts all packets handed to
  2046. * the PF_PACKET socket, including packets dropped because
  2047. * there wasn't room on the socket buffer - but not
  2048. * including packets that didn't pass the filter.
  2049. *
  2050. * In the BSD BPF, the count of received packets is
  2051. * incremented for every packet handed to BPF, regardless
  2052. * of whether it passed the filter.
  2053. *
  2054. * We can't make "pcap_stats()" work the same on both
  2055. * platforms, but the best approximation is to return
  2056. * "tp_packets" as the count of packets and "tp_drops"
  2057. * as the count of drops.
  2058. *
  2059. * Keep a running total because each call to
  2060. * getsockopt(handle->fd, SOL_PACKET, PACKET_STATISTICS, ....
  2061. * resets the counters to zero.
  2062. */
  2063. handlep->stat.ps_recv += kstats.tp_packets;
  2064. handlep->stat.ps_drop += kstats.tp_drops;
  2065. *stats = handlep->stat;
  2066. return 0;
  2067. }
  2068. else
  2069. {
  2070. /*
  2071. * If the error was EOPNOTSUPP, fall through, so that
  2072. * if you build the library on a system with
  2073. * "struct tpacket_stats" and run it on a system
  2074. * that doesn't, it works as it does if the library
  2075. * is built on a system without "struct tpacket_stats".
  2076. */
  2077. if (errno != EOPNOTSUPP) {
  2078. pcap_fmt_errmsg_for_errno(handle->errbuf,
  2079. PCAP_ERRBUF_SIZE, errno, "pcap_stats");
  2080. return -1;
  2081. }
  2082. }
  2083. #endif
  2084. /*
  2085. * On systems where the PACKET_STATISTICS "getsockopt()" argument
  2086. * is not supported on PF_PACKET sockets:
  2087. *
  2088. * "ps_recv" counts only packets that *passed* the filter,
  2089. * not packets that didn't pass the filter. It does not
  2090. * count packets dropped because we ran out of buffer
  2091. * space.
  2092. *
  2093. * "ps_drop" is not supported.
  2094. *
  2095. * "ps_ifdrop" is supported. It will return the number
  2096. * of drops the interface reports in /proc/net/dev,
  2097. * if that is available.
  2098. *
  2099. * "ps_recv" doesn't include packets not yet read from
  2100. * the kernel by libpcap.
  2101. *
  2102. * We maintain the count of packets processed by libpcap in
  2103. * "handlep->packets_read", for reasons described in the comment
  2104. * at the end of pcap_read_packet(). We have no idea how many
  2105. * packets were dropped by the kernel buffers -- but we know
  2106. * how many the interface dropped, so we can return that.
  2107. */
  2108. stats->ps_recv = handlep->packets_read;
  2109. stats->ps_drop = 0;
  2110. stats->ps_ifdrop = handlep->stat.ps_ifdrop;
  2111. return 0;
  2112. }
  2113. static int
  2114. add_linux_if(pcap_if_list_t *devlistp, const char *ifname, int fd, char *errbuf)
  2115. {
  2116. const char *p;
  2117. char name[512]; /* XXX - pick a size */
  2118. char *q, *saveq;
  2119. struct ifreq ifrflags;
  2120. /*
  2121. * Get the interface name.
  2122. */
  2123. p = ifname;
  2124. q = &name[0];
  2125. while (*p != '\0' && isascii(*p) && !isspace(*p)) {
  2126. if (*p == ':') {
  2127. /*
  2128. * This could be the separator between a
  2129. * name and an alias number, or it could be
  2130. * the separator between a name with no
  2131. * alias number and the next field.
  2132. *
  2133. * If there's a colon after digits, it
  2134. * separates the name and the alias number,
  2135. * otherwise it separates the name and the
  2136. * next field.
  2137. */
  2138. saveq = q;
  2139. while (isascii(*p) && isdigit(*p))
  2140. *q++ = *p++;
  2141. if (*p != ':') {
  2142. /*
  2143. * That was the next field,
  2144. * not the alias number.
  2145. */
  2146. q = saveq;
  2147. }
  2148. break;
  2149. } else
  2150. *q++ = *p++;
  2151. }
  2152. *q = '\0';
  2153. /*
  2154. * Get the flags for this interface.
  2155. */
  2156. strlcpy(ifrflags.ifr_name, name, sizeof(ifrflags.ifr_name));
  2157. if (ioctl(fd, SIOCGIFFLAGS, (char *)&ifrflags) < 0) {
  2158. if (errno == ENXIO || errno == ENODEV)
  2159. return (0); /* device doesn't actually exist - ignore it */
  2160. pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
  2161. errno, "SIOCGIFFLAGS: %.*s",
  2162. (int)sizeof(ifrflags.ifr_name),
  2163. ifrflags.ifr_name);
  2164. return (-1);
  2165. }
  2166. /*
  2167. * Add an entry for this interface, with no addresses, if it's
  2168. * not already in the list.
  2169. */
  2170. if (find_or_add_if(devlistp, name, ifrflags.ifr_flags,
  2171. get_if_flags, errbuf) == NULL) {
  2172. /*
  2173. * Failure.
  2174. */
  2175. return (-1);
  2176. }
  2177. return (0);
  2178. }
  2179. /*
  2180. * Get from "/sys/class/net" all interfaces listed there; if they're
  2181. * already in the list of interfaces we have, that won't add another
  2182. * instance, but if they're not, that'll add them.
  2183. *
  2184. * We don't bother getting any addresses for them; it appears you can't
  2185. * use SIOCGIFADDR on Linux to get IPv6 addresses for interfaces, and,
  2186. * although some other types of addresses can be fetched with SIOCGIFADDR,
  2187. * we don't bother with them for now.
  2188. *
  2189. * We also don't fail if we couldn't open "/sys/class/net"; we just leave
  2190. * the list of interfaces as is, and return 0, so that we can try
  2191. * scanning /proc/net/dev.
  2192. *
  2193. * Otherwise, we return 1 if we don't get an error and -1 if we do.
  2194. */
  2195. static int
  2196. scan_sys_class_net(pcap_if_list_t *devlistp, char *errbuf)
  2197. {
  2198. DIR *sys_class_net_d;
  2199. int fd;
  2200. struct dirent *ent;
  2201. char subsystem_path[PATH_MAX+1];
  2202. struct stat statb;
  2203. int ret = 1;
  2204. sys_class_net_d = opendir("/sys/class/net");
  2205. if (sys_class_net_d == NULL) {
  2206. /*
  2207. * Don't fail if it doesn't exist at all.
  2208. */
  2209. if (errno == ENOENT)
  2210. return (0);
  2211. /*
  2212. * Fail if we got some other error.
  2213. */
  2214. pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
  2215. errno, "Can't open /sys/class/net");
  2216. return (-1);
  2217. }
  2218. /*
  2219. * Create a socket from which to fetch interface information.
  2220. */
  2221. fd = socket(PF_UNIX, SOCK_RAW, 0);
  2222. if (fd < 0) {
  2223. pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
  2224. errno, "socket");
  2225. (void)closedir(sys_class_net_d);
  2226. return (-1);
  2227. }
  2228. for (;;) {
  2229. errno = 0;
  2230. ent = readdir(sys_class_net_d);
  2231. if (ent == NULL) {
  2232. /*
  2233. * Error or EOF; if errno != 0, it's an error.
  2234. */
  2235. break;
  2236. }
  2237. /*
  2238. * Ignore "." and "..".
  2239. */
  2240. if (strcmp(ent->d_name, ".") == 0 ||
  2241. strcmp(ent->d_name, "..") == 0)
  2242. continue;
  2243. /*
  2244. * Ignore plain files; they do not have subdirectories
  2245. * and thus have no attributes.
  2246. */
  2247. if (ent->d_type == DT_REG)
  2248. continue;
  2249. /*
  2250. * Is there an "ifindex" file under that name?
  2251. * (We don't care whether it's a directory or
  2252. * a symlink; older kernels have directories
  2253. * for devices, newer kernels have symlinks to
  2254. * directories.)
  2255. */
  2256. pcap_snprintf(subsystem_path, sizeof subsystem_path,
  2257. "/sys/class/net/%s/ifindex", ent->d_name);
  2258. if (lstat(subsystem_path, &statb) != 0) {
  2259. /*
  2260. * Stat failed. Either there was an error
  2261. * other than ENOENT, and we don't know if
  2262. * this is an interface, or it's ENOENT,
  2263. * and either some part of "/sys/class/net/{if}"
  2264. * disappeared, in which case it probably means
  2265. * the interface disappeared, or there's no
  2266. * "ifindex" file, which means it's not a
  2267. * network interface.
  2268. */
  2269. continue;
  2270. }
  2271. /*
  2272. * Attempt to add the interface.
  2273. */
  2274. if (add_linux_if(devlistp, &ent->d_name[0], fd, errbuf) == -1) {
  2275. /* Fail. */
  2276. ret = -1;
  2277. break;
  2278. }
  2279. }
  2280. if (ret != -1) {
  2281. /*
  2282. * Well, we didn't fail for any other reason; did we
  2283. * fail due to an error reading the directory?
  2284. */
  2285. if (errno != 0) {
  2286. pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
  2287. errno, "Error reading /sys/class/net");
  2288. ret = -1;
  2289. }
  2290. }
  2291. (void)close(fd);
  2292. (void)closedir(sys_class_net_d);
  2293. return (ret);
  2294. }
  2295. /*
  2296. * Get from "/proc/net/dev" all interfaces listed there; if they're
  2297. * already in the list of interfaces we have, that won't add another
  2298. * instance, but if they're not, that'll add them.
  2299. *
  2300. * See comments from scan_sys_class_net().
  2301. */
  2302. static int
  2303. scan_proc_net_dev(pcap_if_list_t *devlistp, char *errbuf)
  2304. {
  2305. FILE *proc_net_f;
  2306. int fd;
  2307. char linebuf[512];
  2308. int linenum;
  2309. char *p;
  2310. int ret = 0;
  2311. proc_net_f = fopen("/proc/net/dev", "r");
  2312. if (proc_net_f == NULL) {
  2313. /*
  2314. * Don't fail if it doesn't exist at all.
  2315. */
  2316. if (errno == ENOENT)
  2317. return (0);
  2318. /*
  2319. * Fail if we got some other error.
  2320. */
  2321. pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
  2322. errno, "Can't open /proc/net/dev");
  2323. return (-1);
  2324. }
  2325. /*
  2326. * Create a socket from which to fetch interface information.
  2327. */
  2328. fd = socket(PF_UNIX, SOCK_RAW, 0);
  2329. if (fd < 0) {
  2330. pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
  2331. errno, "socket");
  2332. (void)fclose(proc_net_f);
  2333. return (-1);
  2334. }
  2335. for (linenum = 1;
  2336. fgets(linebuf, sizeof linebuf, proc_net_f) != NULL; linenum++) {
  2337. /*
  2338. * Skip the first two lines - they're headers.
  2339. */
  2340. if (linenum <= 2)
  2341. continue;
  2342. p = &linebuf[0];
  2343. /*
  2344. * Skip leading white space.
  2345. */
  2346. while (*p != '\0' && isascii(*p) && isspace(*p))
  2347. p++;
  2348. if (*p == '\0' || *p == '\n')
  2349. continue; /* blank line */
  2350. /*
  2351. * Attempt to add the interface.
  2352. */
  2353. if (add_linux_if(devlistp, p, fd, errbuf) == -1) {
  2354. /* Fail. */
  2355. ret = -1;
  2356. break;
  2357. }
  2358. }
  2359. if (ret != -1) {
  2360. /*
  2361. * Well, we didn't fail for any other reason; did we
  2362. * fail due to an error reading the file?
  2363. */
  2364. if (ferror(proc_net_f)) {
  2365. pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
  2366. errno, "Error reading /proc/net/dev");
  2367. ret = -1;
  2368. }
  2369. }
  2370. (void)close(fd);
  2371. (void)fclose(proc_net_f);
  2372. return (ret);
  2373. }
  2374. /*
  2375. * Description string for the "any" device.
  2376. */
  2377. static const char any_descr[] = "Pseudo-device that captures on all interfaces";
  2378. /*
  2379. * A SOCK_PACKET or PF_PACKET socket can be bound to any network interface.
  2380. */
  2381. static int
  2382. can_be_bound(const char *name _U_)
  2383. {
  2384. return (1);
  2385. }
  2386. /*
  2387. * Get additional flags for a device, using SIOCGIFMEDIA.
  2388. */
  2389. static int
  2390. get_if_flags(const char *name, bpf_u_int32 *flags, char *errbuf)
  2391. {
  2392. int sock;
  2393. FILE *fh;
  2394. unsigned int arptype;
  2395. struct ifreq ifr;
  2396. struct ethtool_value info;
  2397. if (*flags & PCAP_IF_LOOPBACK) {
  2398. /*
  2399. * Loopback devices aren't wireless, and "connected"/
  2400. * "disconnected" doesn't apply to them.
  2401. */
  2402. *flags |= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE;
  2403. return 0;
  2404. }
  2405. sock = socket(AF_INET, SOCK_DGRAM, 0);
  2406. if (sock == -1) {
  2407. pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE, errno,
  2408. "Can't create socket to get ethtool information for %s",
  2409. name);
  2410. return -1;
  2411. }
  2412. /*
  2413. * OK, what type of network is this?
  2414. * In particular, is it wired or wireless?
  2415. */
  2416. if (is_wifi(sock, name)) {
  2417. /*
  2418. * Wi-Fi, hence wireless.
  2419. */
  2420. *flags |= PCAP_IF_WIRELESS;
  2421. } else {
  2422. /*
  2423. * OK, what does /sys/class/net/{if}/type contain?
  2424. * (We don't use that for Wi-Fi, as it'll report
  2425. * "Ethernet", i.e. ARPHRD_ETHER, for non-monitor-
  2426. * mode devices.)
  2427. */
  2428. char *pathstr;
  2429. if (asprintf(&pathstr, "/sys/class/net/%s/type", name) == -1) {
  2430. pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
  2431. "%s: Can't generate path name string for /sys/class/net device",
  2432. name);
  2433. close(sock);
  2434. return -1;
  2435. }
  2436. fh = fopen(pathstr, "r");
  2437. if (fh != NULL) {
  2438. if (fscanf(fh, "%u", &arptype) == 1) {
  2439. /*
  2440. * OK, we got an ARPHRD_ type; what is it?
  2441. */
  2442. switch (arptype) {
  2443. #ifdef ARPHRD_LOOPBACK
  2444. case ARPHRD_LOOPBACK:
  2445. /*
  2446. * These are types to which
  2447. * "connected" and "disconnected"
  2448. * don't apply, so don't bother
  2449. * asking about it.
  2450. *
  2451. * XXX - add other types?
  2452. */
  2453. close(sock);
  2454. fclose(fh);
  2455. free(pathstr);
  2456. return 0;
  2457. #endif
  2458. case ARPHRD_IRDA:
  2459. case ARPHRD_IEEE80211:
  2460. case ARPHRD_IEEE80211_PRISM:
  2461. case ARPHRD_IEEE80211_RADIOTAP:
  2462. #ifdef ARPHRD_IEEE802154
  2463. case ARPHRD_IEEE802154:
  2464. #endif
  2465. #ifdef ARPHRD_IEEE802154_MONITOR
  2466. case ARPHRD_IEEE802154_MONITOR:
  2467. #endif
  2468. #ifdef ARPHRD_6LOWPAN
  2469. case ARPHRD_6LOWPAN:
  2470. #endif
  2471. /*
  2472. * Various wireless types.
  2473. */
  2474. *flags |= PCAP_IF_WIRELESS;
  2475. break;
  2476. }
  2477. }
  2478. fclose(fh);
  2479. free(pathstr);
  2480. }
  2481. }
  2482. #ifdef ETHTOOL_GLINK
  2483. memset(&ifr, 0, sizeof(ifr));
  2484. strlcpy(ifr.ifr_name, name, sizeof(ifr.ifr_name));
  2485. info.cmd = ETHTOOL_GLINK;
  2486. ifr.ifr_data = (caddr_t)&info;
  2487. if (ioctl(sock, SIOCETHTOOL, &ifr) == -1) {
  2488. int save_errno = errno;
  2489. switch (save_errno) {
  2490. case EOPNOTSUPP:
  2491. case EINVAL:
  2492. /*
  2493. * OK, this OS version or driver doesn't support
  2494. * asking for this information.
  2495. * XXX - distinguish between "this doesn't
  2496. * support ethtool at all because it's not
  2497. * that type of device" vs. "this doesn't
  2498. * support ethtool even though it's that
  2499. * type of device", and return "unknown".
  2500. */
  2501. *flags |= PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE;
  2502. close(sock);
  2503. return 0;
  2504. case ENODEV:
  2505. /*
  2506. * OK, no such device.
  2507. * The user will find that out when they try to
  2508. * activate the device; just say "OK" and
  2509. * don't set anything.
  2510. */
  2511. close(sock);
  2512. return 0;
  2513. default:
  2514. /*
  2515. * Other error.
  2516. */
  2517. pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
  2518. save_errno,
  2519. "%s: SIOCETHTOOL(ETHTOOL_GLINK) ioctl failed",
  2520. name);
  2521. close(sock);
  2522. return -1;
  2523. }
  2524. }
  2525. /*
  2526. * Is it connected?
  2527. */
  2528. if (info.data) {
  2529. /*
  2530. * It's connected.
  2531. */
  2532. *flags |= PCAP_IF_CONNECTION_STATUS_CONNECTED;
  2533. } else {
  2534. /*
  2535. * It's disconnected.
  2536. */
  2537. *flags |= PCAP_IF_CONNECTION_STATUS_DISCONNECTED;
  2538. }
  2539. #endif
  2540. close(sock);
  2541. return 0;
  2542. }
  2543. int
  2544. pcap_platform_finddevs(pcap_if_list_t *devlistp, char *errbuf)
  2545. {
  2546. int ret;
  2547. /*
  2548. * Get the list of regular interfaces first.
  2549. */
  2550. if (pcap_findalldevs_interfaces(devlistp, errbuf, can_be_bound,
  2551. get_if_flags) == -1)
  2552. return (-1); /* failure */
  2553. /*
  2554. * Read "/sys/class/net", and add to the list of interfaces all
  2555. * interfaces listed there that we don't already have, because,
  2556. * on Linux, SIOCGIFCONF reports only interfaces with IPv4 addresses,
  2557. * and even getifaddrs() won't return information about
  2558. * interfaces with no addresses, so you need to read "/sys/class/net"
  2559. * to get the names of the rest of the interfaces.
  2560. */
  2561. ret = scan_sys_class_net(devlistp, errbuf);
  2562. if (ret == -1)
  2563. return (-1); /* failed */
  2564. if (ret == 0) {
  2565. /*
  2566. * No /sys/class/net; try reading /proc/net/dev instead.
  2567. */
  2568. if (scan_proc_net_dev(devlistp, errbuf) == -1)
  2569. return (-1);
  2570. }
  2571. /*
  2572. * Add the "any" device.
  2573. * As it refers to all network devices, not to any particular
  2574. * network device, the notion of "connected" vs. "disconnected"
  2575. * doesn't apply.
  2576. */
  2577. if (add_dev(devlistp, "any",
  2578. PCAP_IF_UP|PCAP_IF_RUNNING|PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE,
  2579. any_descr, errbuf) == NULL)
  2580. return (-1);
  2581. return (0);
  2582. }
  2583. /*
  2584. * Attach the given BPF code to the packet capture device.
  2585. */
  2586. static int
  2587. pcap_setfilter_linux_common(pcap_t *handle, struct bpf_program *filter,
  2588. int is_mmapped)
  2589. {
  2590. struct pcap_linux *handlep;
  2591. #ifdef SO_ATTACH_FILTER
  2592. struct sock_fprog fcode;
  2593. int can_filter_in_kernel;
  2594. int err = 0;
  2595. #endif
  2596. if (!handle)
  2597. return -1;
  2598. if (!filter) {
  2599. strlcpy(handle->errbuf, "setfilter: No filter specified",
  2600. PCAP_ERRBUF_SIZE);
  2601. return -1;
  2602. }
  2603. handlep = handle->priv;
  2604. /* Make our private copy of the filter */
  2605. if (install_bpf_program(handle, filter) < 0)
  2606. /* install_bpf_program() filled in errbuf */
  2607. return -1;
  2608. /*
  2609. * Run user level packet filter by default. Will be overriden if
  2610. * installing a kernel filter succeeds.
  2611. */
  2612. handlep->filter_in_userland = 1;
  2613. /* Install kernel level filter if possible */
  2614. #ifdef SO_ATTACH_FILTER
  2615. #ifdef USHRT_MAX
  2616. if (handle->fcode.bf_len > USHRT_MAX) {
  2617. /*
  2618. * fcode.len is an unsigned short for current kernel.
  2619. * I have yet to see BPF-Code with that much
  2620. * instructions but still it is possible. So for the
  2621. * sake of correctness I added this check.
  2622. */
  2623. fprintf(stderr, "Warning: Filter too complex for kernel\n");
  2624. fcode.len = 0;
  2625. fcode.filter = NULL;
  2626. can_filter_in_kernel = 0;
  2627. } else
  2628. #endif /* USHRT_MAX */
  2629. {
  2630. /*
  2631. * Oh joy, the Linux kernel uses struct sock_fprog instead
  2632. * of struct bpf_program and of course the length field is
  2633. * of different size. Pointed out by Sebastian
  2634. *
  2635. * Oh, and we also need to fix it up so that all "ret"
  2636. * instructions with non-zero operands have MAXIMUM_SNAPLEN
  2637. * as the operand if we're not capturing in memory-mapped
  2638. * mode, and so that, if we're in cooked mode, all memory-
  2639. * reference instructions use special magic offsets in
  2640. * references to the link-layer header and assume that the
  2641. * link-layer payload begins at 0; "fix_program()" will do
  2642. * that.
  2643. */
  2644. switch (fix_program(handle, &fcode, is_mmapped)) {
  2645. case -1:
  2646. default:
  2647. /*
  2648. * Fatal error; just quit.
  2649. * (The "default" case shouldn't happen; we
  2650. * return -1 for that reason.)
  2651. */
  2652. return -1;
  2653. case 0:
  2654. /*
  2655. * The program performed checks that we can't make
  2656. * work in the kernel.
  2657. */
  2658. can_filter_in_kernel = 0;
  2659. break;
  2660. case 1:
  2661. /*
  2662. * We have a filter that'll work in the kernel.
  2663. */
  2664. can_filter_in_kernel = 1;
  2665. break;
  2666. }
  2667. }
  2668. /*
  2669. * NOTE: at this point, we've set both the "len" and "filter"
  2670. * fields of "fcode". As of the 2.6.32.4 kernel, at least,
  2671. * those are the only members of the "sock_fprog" structure,
  2672. * so we initialize every member of that structure.
  2673. *
  2674. * If there is anything in "fcode" that is not initialized,
  2675. * it is either a field added in a later kernel, or it's
  2676. * padding.
  2677. *
  2678. * If a new field is added, this code needs to be updated
  2679. * to set it correctly.
  2680. *
  2681. * If there are no other fields, then:
  2682. *
  2683. * if the Linux kernel looks at the padding, it's
  2684. * buggy;
  2685. *
  2686. * if the Linux kernel doesn't look at the padding,
  2687. * then if some tool complains that we're passing
  2688. * uninitialized data to the kernel, then the tool
  2689. * is buggy and needs to understand that it's just
  2690. * padding.
  2691. */
  2692. if (can_filter_in_kernel) {
  2693. if ((err = set_kernel_filter(handle, &fcode)) == 0)
  2694. {
  2695. /*
  2696. * Installation succeded - using kernel filter,
  2697. * so userland filtering not needed.
  2698. */
  2699. handlep->filter_in_userland = 0;
  2700. }
  2701. else if (err == -1) /* Non-fatal error */
  2702. {
  2703. /*
  2704. * Print a warning if we weren't able to install
  2705. * the filter for a reason other than "this kernel
  2706. * isn't configured to support socket filters.
  2707. */
  2708. if (errno != ENOPROTOOPT && errno != EOPNOTSUPP) {
  2709. fprintf(stderr,
  2710. "Warning: Kernel filter failed: %s\n",
  2711. pcap_strerror(errno));
  2712. }
  2713. }
  2714. }
  2715. /*
  2716. * If we're not using the kernel filter, get rid of any kernel
  2717. * filter that might've been there before, e.g. because the
  2718. * previous filter could work in the kernel, or because some other
  2719. * code attached a filter to the socket by some means other than
  2720. * calling "pcap_setfilter()". Otherwise, the kernel filter may
  2721. * filter out packets that would pass the new userland filter.
  2722. */
  2723. if (handlep->filter_in_userland) {
  2724. if (reset_kernel_filter(handle) == -1) {
  2725. pcap_fmt_errmsg_for_errno(handle->errbuf,
  2726. PCAP_ERRBUF_SIZE, errno,
  2727. "can't remove kernel filter");
  2728. err = -2; /* fatal error */
  2729. }
  2730. }
  2731. /*
  2732. * Free up the copy of the filter that was made by "fix_program()".
  2733. */
  2734. if (fcode.filter != NULL)
  2735. free(fcode.filter);
  2736. if (err == -2)
  2737. /* Fatal error */
  2738. return -1;
  2739. #endif /* SO_ATTACH_FILTER */
  2740. return 0;
  2741. }
  2742. static int
  2743. pcap_setfilter_linux(pcap_t *handle, struct bpf_program *filter)
  2744. {
  2745. return pcap_setfilter_linux_common(handle, filter, 0);
  2746. }
  2747. /*
  2748. * Set direction flag: Which packets do we accept on a forwarding
  2749. * single device? IN, OUT or both?
  2750. */
  2751. static int
  2752. pcap_setdirection_linux(pcap_t *handle, pcap_direction_t d)
  2753. {
  2754. #ifdef HAVE_PF_PACKET_SOCKETS
  2755. struct pcap_linux *handlep = handle->priv;
  2756. if (!handlep->sock_packet) {
  2757. handle->direction = d;
  2758. return 0;
  2759. }
  2760. #endif
  2761. /*
  2762. * We're not using PF_PACKET sockets, so we can't determine
  2763. * the direction of the packet.
  2764. */
  2765. pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  2766. "Setting direction is not supported on SOCK_PACKET sockets");
  2767. return -1;
  2768. }
  2769. #ifdef HAVE_PF_PACKET_SOCKETS
  2770. /*
  2771. * Map the PACKET_ value to a LINUX_SLL_ value; we
  2772. * want the same numerical value to be used in
  2773. * the link-layer header even if the numerical values
  2774. * for the PACKET_ #defines change, so that programs
  2775. * that look at the packet type field will always be
  2776. * able to handle DLT_LINUX_SLL captures.
  2777. */
  2778. static short int
  2779. map_packet_type_to_sll_type(short int sll_pkttype)
  2780. {
  2781. switch (sll_pkttype) {
  2782. case PACKET_HOST:
  2783. return htons(LINUX_SLL_HOST);
  2784. case PACKET_BROADCAST:
  2785. return htons(LINUX_SLL_BROADCAST);
  2786. case PACKET_MULTICAST:
  2787. return htons(LINUX_SLL_MULTICAST);
  2788. case PACKET_OTHERHOST:
  2789. return htons(LINUX_SLL_OTHERHOST);
  2790. case PACKET_OUTGOING:
  2791. return htons(LINUX_SLL_OUTGOING);
  2792. default:
  2793. return -1;
  2794. }
  2795. }
  2796. #endif
  2797. static int
  2798. is_wifi(int sock_fd
  2799. #ifndef IW_MODE_MONITOR
  2800. _U_
  2801. #endif
  2802. , const char *device)
  2803. {
  2804. char *pathstr;
  2805. struct stat statb;
  2806. #ifdef IW_MODE_MONITOR
  2807. char errbuf[PCAP_ERRBUF_SIZE];
  2808. #endif
  2809. /*
  2810. * See if there's a sysfs wireless directory for it.
  2811. * If so, it's a wireless interface.
  2812. */
  2813. if (asprintf(&pathstr, "/sys/class/net/%s/wireless", device) == -1) {
  2814. /*
  2815. * Just give up here.
  2816. */
  2817. return 0;
  2818. }
  2819. if (stat(pathstr, &statb) == 0) {
  2820. free(pathstr);
  2821. return 1;
  2822. }
  2823. free(pathstr);
  2824. #ifdef IW_MODE_MONITOR
  2825. /*
  2826. * OK, maybe it's not wireless, or maybe this kernel doesn't
  2827. * support sysfs. Try the wireless extensions.
  2828. */
  2829. if (has_wext(sock_fd, device, errbuf) == 1) {
  2830. /*
  2831. * It supports the wireless extensions, so it's a Wi-Fi
  2832. * device.
  2833. */
  2834. return 1;
  2835. }
  2836. #endif
  2837. return 0;
  2838. }
  2839. /*
  2840. * Linux uses the ARP hardware type to identify the type of an
  2841. * interface. pcap uses the DLT_xxx constants for this. This
  2842. * function takes a pointer to a "pcap_t", and an ARPHRD_xxx
  2843. * constant, as arguments, and sets "handle->linktype" to the
  2844. * appropriate DLT_XXX constant and sets "handle->offset" to
  2845. * the appropriate value (to make "handle->offset" plus link-layer
  2846. * header length be a multiple of 4, so that the link-layer payload
  2847. * will be aligned on a 4-byte boundary when capturing packets).
  2848. * (If the offset isn't set here, it'll be 0; add code as appropriate
  2849. * for cases where it shouldn't be 0.)
  2850. *
  2851. * If "cooked_ok" is non-zero, we can use DLT_LINUX_SLL and capture
  2852. * in cooked mode; otherwise, we can't use cooked mode, so we have
  2853. * to pick some type that works in raw mode, or fail.
  2854. *
  2855. * Sets the link type to -1 if unable to map the type.
  2856. */
  2857. static void map_arphrd_to_dlt(pcap_t *handle, int sock_fd, int arptype,
  2858. const char *device, int cooked_ok)
  2859. {
  2860. static const char cdma_rmnet[] = "cdma_rmnet";
  2861. switch (arptype) {
  2862. case ARPHRD_ETHER:
  2863. /*
  2864. * For various annoying reasons having to do with DHCP
  2865. * software, some versions of Android give the mobile-
  2866. * phone-network interface an ARPHRD_ value of
  2867. * ARPHRD_ETHER, even though the packets supplied by
  2868. * that interface have no link-layer header, and begin
  2869. * with an IP header, so that the ARPHRD_ value should
  2870. * be ARPHRD_NONE.
  2871. *
  2872. * Detect those devices by checking the device name, and
  2873. * use DLT_RAW for them.
  2874. */
  2875. if (strncmp(device, cdma_rmnet, sizeof cdma_rmnet - 1) == 0) {
  2876. handle->linktype = DLT_RAW;
  2877. return;
  2878. }
  2879. /*
  2880. * Is this a real Ethernet device? If so, give it a
  2881. * link-layer-type list with DLT_EN10MB and DLT_DOCSIS, so
  2882. * that an application can let you choose it, in case you're
  2883. * capturing DOCSIS traffic that a Cisco Cable Modem
  2884. * Termination System is putting out onto an Ethernet (it
  2885. * doesn't put an Ethernet header onto the wire, it puts raw
  2886. * DOCSIS frames out on the wire inside the low-level
  2887. * Ethernet framing).
  2888. *
  2889. * XXX - are there any other sorts of "fake Ethernet" that
  2890. * have ARPHRD_ETHER but that shouldn't offer DLT_DOCSIS as
  2891. * a Cisco CMTS won't put traffic onto it or get traffic
  2892. * bridged onto it? ISDN is handled in "activate_new()",
  2893. * as we fall back on cooked mode there, and we use
  2894. * is_wifi() to check for 802.11 devices; are there any
  2895. * others?
  2896. */
  2897. if (!is_wifi(sock_fd, device)) {
  2898. /*
  2899. * It's not a Wi-Fi device; offer DOCSIS.
  2900. */
  2901. handle->dlt_list = (u_int *) malloc(sizeof(u_int) * 2);
  2902. /*
  2903. * If that fails, just leave the list empty.
  2904. */
  2905. if (handle->dlt_list != NULL) {
  2906. handle->dlt_list[0] = DLT_EN10MB;
  2907. handle->dlt_list[1] = DLT_DOCSIS;
  2908. handle->dlt_count = 2;
  2909. }
  2910. }
  2911. /* FALLTHROUGH */
  2912. case ARPHRD_METRICOM:
  2913. case ARPHRD_LOOPBACK:
  2914. handle->linktype = DLT_EN10MB;
  2915. handle->offset = 2;
  2916. break;
  2917. case ARPHRD_EETHER:
  2918. handle->linktype = DLT_EN3MB;
  2919. break;
  2920. case ARPHRD_AX25:
  2921. handle->linktype = DLT_AX25_KISS;
  2922. break;
  2923. case ARPHRD_PRONET:
  2924. handle->linktype = DLT_PRONET;
  2925. break;
  2926. case ARPHRD_CHAOS:
  2927. handle->linktype = DLT_CHAOS;
  2928. break;
  2929. #ifndef ARPHRD_CAN
  2930. #define ARPHRD_CAN 280
  2931. #endif
  2932. case ARPHRD_CAN:
  2933. /*
  2934. * Map this to DLT_LINUX_SLL; that way, CAN frames will
  2935. * have ETH_P_CAN/LINUX_SLL_P_CAN as the protocol and
  2936. * CAN FD frames will have ETH_P_CANFD/LINUX_SLL_P_CANFD
  2937. * as the protocol, so they can be distinguished by the
  2938. * protocol in the SLL header.
  2939. */
  2940. handle->linktype = DLT_LINUX_SLL;
  2941. break;
  2942. #ifndef ARPHRD_IEEE802_TR
  2943. #define ARPHRD_IEEE802_TR 800 /* From Linux 2.4 */
  2944. #endif
  2945. case ARPHRD_IEEE802_TR:
  2946. case ARPHRD_IEEE802:
  2947. handle->linktype = DLT_IEEE802;
  2948. handle->offset = 2;
  2949. break;
  2950. case ARPHRD_ARCNET:
  2951. handle->linktype = DLT_ARCNET_LINUX;
  2952. break;
  2953. #ifndef ARPHRD_FDDI /* From Linux 2.2.13 */
  2954. #define ARPHRD_FDDI 774
  2955. #endif
  2956. case ARPHRD_FDDI:
  2957. handle->linktype = DLT_FDDI;
  2958. handle->offset = 3;
  2959. break;
  2960. #ifndef ARPHRD_ATM /* FIXME: How to #include this? */
  2961. #define ARPHRD_ATM 19
  2962. #endif
  2963. case ARPHRD_ATM:
  2964. /*
  2965. * The Classical IP implementation in ATM for Linux
  2966. * supports both what RFC 1483 calls "LLC Encapsulation",
  2967. * in which each packet has an LLC header, possibly
  2968. * with a SNAP header as well, prepended to it, and
  2969. * what RFC 1483 calls "VC Based Multiplexing", in which
  2970. * different virtual circuits carry different network
  2971. * layer protocols, and no header is prepended to packets.
  2972. *
  2973. * They both have an ARPHRD_ type of ARPHRD_ATM, so
  2974. * you can't use the ARPHRD_ type to find out whether
  2975. * captured packets will have an LLC header, and,
  2976. * while there's a socket ioctl to *set* the encapsulation
  2977. * type, there's no ioctl to *get* the encapsulation type.
  2978. *
  2979. * This means that
  2980. *
  2981. * programs that dissect Linux Classical IP frames
  2982. * would have to check for an LLC header and,
  2983. * depending on whether they see one or not, dissect
  2984. * the frame as LLC-encapsulated or as raw IP (I
  2985. * don't know whether there's any traffic other than
  2986. * IP that would show up on the socket, or whether
  2987. * there's any support for IPv6 in the Linux
  2988. * Classical IP code);
  2989. *
  2990. * filter expressions would have to compile into
  2991. * code that checks for an LLC header and does
  2992. * the right thing.
  2993. *
  2994. * Both of those are a nuisance - and, at least on systems
  2995. * that support PF_PACKET sockets, we don't have to put
  2996. * up with those nuisances; instead, we can just capture
  2997. * in cooked mode. That's what we'll do, if we can.
  2998. * Otherwise, we'll just fail.
  2999. */
  3000. if (cooked_ok)
  3001. handle->linktype = DLT_LINUX_SLL;
  3002. else
  3003. handle->linktype = -1;
  3004. break;
  3005. #ifndef ARPHRD_IEEE80211 /* From Linux 2.4.6 */
  3006. #define ARPHRD_IEEE80211 801
  3007. #endif
  3008. case ARPHRD_IEEE80211:
  3009. handle->linktype = DLT_IEEE802_11;
  3010. break;
  3011. #ifndef ARPHRD_IEEE80211_PRISM /* From Linux 2.4.18 */
  3012. #define ARPHRD_IEEE80211_PRISM 802
  3013. #endif
  3014. case ARPHRD_IEEE80211_PRISM:
  3015. handle->linktype = DLT_PRISM_HEADER;
  3016. break;
  3017. #ifndef ARPHRD_IEEE80211_RADIOTAP /* new */
  3018. #define ARPHRD_IEEE80211_RADIOTAP 803
  3019. #endif
  3020. case ARPHRD_IEEE80211_RADIOTAP:
  3021. handle->linktype = DLT_IEEE802_11_RADIO;
  3022. break;
  3023. case ARPHRD_PPP:
  3024. /*
  3025. * Some PPP code in the kernel supplies no link-layer
  3026. * header whatsoever to PF_PACKET sockets; other PPP
  3027. * code supplies PPP link-layer headers ("syncppp.c");
  3028. * some PPP code might supply random link-layer
  3029. * headers (PPP over ISDN - there's code in Ethereal,
  3030. * for example, to cope with PPP-over-ISDN captures
  3031. * with which the Ethereal developers have had to cope,
  3032. * heuristically trying to determine which of the
  3033. * oddball link-layer headers particular packets have).
  3034. *
  3035. * As such, we just punt, and run all PPP interfaces
  3036. * in cooked mode, if we can; otherwise, we just treat
  3037. * it as DLT_RAW, for now - if somebody needs to capture,
  3038. * on a 2.0[.x] kernel, on PPP devices that supply a
  3039. * link-layer header, they'll have to add code here to
  3040. * map to the appropriate DLT_ type (possibly adding a
  3041. * new DLT_ type, if necessary).
  3042. */
  3043. if (cooked_ok)
  3044. handle->linktype = DLT_LINUX_SLL;
  3045. else {
  3046. /*
  3047. * XXX - handle ISDN types here? We can't fall
  3048. * back on cooked sockets, so we'd have to
  3049. * figure out from the device name what type of
  3050. * link-layer encapsulation it's using, and map
  3051. * that to an appropriate DLT_ value, meaning
  3052. * we'd map "isdnN" devices to DLT_RAW (they
  3053. * supply raw IP packets with no link-layer
  3054. * header) and "isdY" devices to a new DLT_I4L_IP
  3055. * type that has only an Ethernet packet type as
  3056. * a link-layer header.
  3057. *
  3058. * But sometimes we seem to get random crap
  3059. * in the link-layer header when capturing on
  3060. * ISDN devices....
  3061. */
  3062. handle->linktype = DLT_RAW;
  3063. }
  3064. break;
  3065. #ifndef ARPHRD_CISCO
  3066. #define ARPHRD_CISCO 513 /* previously ARPHRD_HDLC */
  3067. #endif
  3068. case ARPHRD_CISCO:
  3069. handle->linktype = DLT_C_HDLC;
  3070. break;
  3071. /* Not sure if this is correct for all tunnels, but it
  3072. * works for CIPE */
  3073. case ARPHRD_TUNNEL:
  3074. #ifndef ARPHRD_SIT
  3075. #define ARPHRD_SIT 776 /* From Linux 2.2.13 */
  3076. #endif
  3077. case ARPHRD_SIT:
  3078. case ARPHRD_CSLIP:
  3079. case ARPHRD_SLIP6:
  3080. case ARPHRD_CSLIP6:
  3081. case ARPHRD_ADAPT:
  3082. case ARPHRD_SLIP:
  3083. #ifndef ARPHRD_RAWHDLC
  3084. #define ARPHRD_RAWHDLC 518
  3085. #endif
  3086. case ARPHRD_RAWHDLC:
  3087. #ifndef ARPHRD_DLCI
  3088. #define ARPHRD_DLCI 15
  3089. #endif
  3090. case ARPHRD_DLCI:
  3091. /*
  3092. * XXX - should some of those be mapped to DLT_LINUX_SLL
  3093. * instead? Should we just map all of them to DLT_LINUX_SLL?
  3094. */
  3095. handle->linktype = DLT_RAW;
  3096. break;
  3097. #ifndef ARPHRD_FRAD
  3098. #define ARPHRD_FRAD 770
  3099. #endif
  3100. case ARPHRD_FRAD:
  3101. handle->linktype = DLT_FRELAY;
  3102. break;
  3103. case ARPHRD_LOCALTLK:
  3104. handle->linktype = DLT_LTALK;
  3105. break;
  3106. case 18:
  3107. /*
  3108. * RFC 4338 defines an encapsulation for IP and ARP
  3109. * packets that's compatible with the RFC 2625
  3110. * encapsulation, but that uses a different ARP
  3111. * hardware type and hardware addresses. That
  3112. * ARP hardware type is 18; Linux doesn't define
  3113. * any ARPHRD_ value as 18, but if it ever officially
  3114. * supports RFC 4338-style IP-over-FC, it should define
  3115. * one.
  3116. *
  3117. * For now, we map it to DLT_IP_OVER_FC, in the hopes
  3118. * that this will encourage its use in the future,
  3119. * should Linux ever officially support RFC 4338-style
  3120. * IP-over-FC.
  3121. */
  3122. handle->linktype = DLT_IP_OVER_FC;
  3123. break;
  3124. #ifndef ARPHRD_FCPP
  3125. #define ARPHRD_FCPP 784
  3126. #endif
  3127. case ARPHRD_FCPP:
  3128. #ifndef ARPHRD_FCAL
  3129. #define ARPHRD_FCAL 785
  3130. #endif
  3131. case ARPHRD_FCAL:
  3132. #ifndef ARPHRD_FCPL
  3133. #define ARPHRD_FCPL 786
  3134. #endif
  3135. case ARPHRD_FCPL:
  3136. #ifndef ARPHRD_FCFABRIC
  3137. #define ARPHRD_FCFABRIC 787
  3138. #endif
  3139. case ARPHRD_FCFABRIC:
  3140. /*
  3141. * Back in 2002, Donald Lee at Cray wanted a DLT_ for
  3142. * IP-over-FC:
  3143. *
  3144. * http://www.mail-archive.com/tcpdump-workers@sandelman.ottawa.on.ca/msg01043.html
  3145. *
  3146. * and one was assigned.
  3147. *
  3148. * In a later private discussion (spun off from a message
  3149. * on the ethereal-users list) on how to get that DLT_
  3150. * value in libpcap on Linux, I ended up deciding that
  3151. * the best thing to do would be to have him tweak the
  3152. * driver to set the ARPHRD_ value to some ARPHRD_FCxx
  3153. * type, and map all those types to DLT_IP_OVER_FC:
  3154. *
  3155. * I've checked into the libpcap and tcpdump CVS tree
  3156. * support for DLT_IP_OVER_FC. In order to use that,
  3157. * you'd have to modify your modified driver to return
  3158. * one of the ARPHRD_FCxxx types, in "fcLINUXfcp.c" -
  3159. * change it to set "dev->type" to ARPHRD_FCFABRIC, for
  3160. * example (the exact value doesn't matter, it can be
  3161. * any of ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL, or
  3162. * ARPHRD_FCFABRIC).
  3163. *
  3164. * 11 years later, Christian Svensson wanted to map
  3165. * various ARPHRD_ values to DLT_FC_2 and
  3166. * DLT_FC_2_WITH_FRAME_DELIMS for raw Fibre Channel
  3167. * frames:
  3168. *
  3169. * https://github.com/mcr/libpcap/pull/29
  3170. *
  3171. * There doesn't seem to be any network drivers that uses
  3172. * any of the ARPHRD_FC* values for IP-over-FC, and
  3173. * it's not exactly clear what the "Dummy types for non
  3174. * ARP hardware" are supposed to mean (link-layer
  3175. * header type? Physical network type?), so it's
  3176. * not exactly clear why the ARPHRD_FC* types exist
  3177. * in the first place.
  3178. *
  3179. * For now, we map them to DLT_FC_2, and provide an
  3180. * option of DLT_FC_2_WITH_FRAME_DELIMS, as well as
  3181. * DLT_IP_OVER_FC just in case there's some old
  3182. * driver out there that uses one of those types for
  3183. * IP-over-FC on which somebody wants to capture
  3184. * packets.
  3185. */
  3186. handle->dlt_list = (u_int *) malloc(sizeof(u_int) * 3);
  3187. /*
  3188. * If that fails, just leave the list empty.
  3189. */
  3190. if (handle->dlt_list != NULL) {
  3191. handle->dlt_list[0] = DLT_FC_2;
  3192. handle->dlt_list[1] = DLT_FC_2_WITH_FRAME_DELIMS;
  3193. handle->dlt_list[2] = DLT_IP_OVER_FC;
  3194. handle->dlt_count = 3;
  3195. }
  3196. handle->linktype = DLT_FC_2;
  3197. break;
  3198. #ifndef ARPHRD_IRDA
  3199. #define ARPHRD_IRDA 783
  3200. #endif
  3201. case ARPHRD_IRDA:
  3202. /* Don't expect IP packet out of this interfaces... */
  3203. handle->linktype = DLT_LINUX_IRDA;
  3204. /* We need to save packet direction for IrDA decoding,
  3205. * so let's use "Linux-cooked" mode. Jean II
  3206. *
  3207. * XXX - this is handled in activate_new(). */
  3208. /* handlep->cooked = 1; */
  3209. break;
  3210. /* ARPHRD_LAPD is unofficial and randomly allocated, if reallocation
  3211. * is needed, please report it to <daniele@orlandi.com> */
  3212. #ifndef ARPHRD_LAPD
  3213. #define ARPHRD_LAPD 8445
  3214. #endif
  3215. case ARPHRD_LAPD:
  3216. /* Don't expect IP packet out of this interfaces... */
  3217. handle->linktype = DLT_LINUX_LAPD;
  3218. break;
  3219. #ifndef ARPHRD_NONE
  3220. #define ARPHRD_NONE 0xFFFE
  3221. #endif
  3222. case ARPHRD_NONE:
  3223. /*
  3224. * No link-layer header; packets are just IP
  3225. * packets, so use DLT_RAW.
  3226. */
  3227. handle->linktype = DLT_RAW;
  3228. break;
  3229. #ifndef ARPHRD_IEEE802154
  3230. #define ARPHRD_IEEE802154 804
  3231. #endif
  3232. case ARPHRD_IEEE802154:
  3233. handle->linktype = DLT_IEEE802_15_4_NOFCS;
  3234. break;
  3235. #ifndef ARPHRD_NETLINK
  3236. #define ARPHRD_NETLINK 824
  3237. #endif
  3238. case ARPHRD_NETLINK:
  3239. handle->linktype = DLT_NETLINK;
  3240. /*
  3241. * We need to use cooked mode, so that in sll_protocol we
  3242. * pick up the netlink protocol type such as NETLINK_ROUTE,
  3243. * NETLINK_GENERIC, NETLINK_FIB_LOOKUP, etc.
  3244. *
  3245. * XXX - this is handled in activate_new().
  3246. */
  3247. /* handlep->cooked = 1; */
  3248. break;
  3249. #ifndef ARPHRD_VSOCKMON
  3250. #define ARPHRD_VSOCKMON 826
  3251. #endif
  3252. case ARPHRD_VSOCKMON:
  3253. handle->linktype = DLT_VSOCK;
  3254. break;
  3255. default:
  3256. handle->linktype = -1;
  3257. break;
  3258. }
  3259. }
  3260. /* ===== Functions to interface to the newer kernels ================== */
  3261. /*
  3262. * Try to open a packet socket using the new kernel PF_PACKET interface.
  3263. * Returns 1 on success, 0 on an error that means the new interface isn't
  3264. * present (so the old SOCK_PACKET interface should be tried), and a
  3265. * PCAP_ERROR_ value on an error that means that the old mechanism won't
  3266. * work either (so it shouldn't be tried).
  3267. */
  3268. static int
  3269. activate_new(pcap_t *handle)
  3270. {
  3271. #ifdef HAVE_PF_PACKET_SOCKETS
  3272. struct pcap_linux *handlep = handle->priv;
  3273. const char *device = handle->opt.device;
  3274. int is_any_device = (strcmp(device, "any") == 0);
  3275. int protocol = pcap_protocol(handle);
  3276. int sock_fd = -1, arptype;
  3277. #ifdef HAVE_PACKET_AUXDATA
  3278. int val;
  3279. #endif
  3280. int err = 0;
  3281. struct packet_mreq mr;
  3282. #if defined(SO_BPF_EXTENSIONS) && defined(SKF_AD_VLAN_TAG_PRESENT)
  3283. int bpf_extensions;
  3284. socklen_t len = sizeof(bpf_extensions);
  3285. #endif
  3286. /*
  3287. * Open a socket with protocol family packet. If the
  3288. * "any" device was specified, we open a SOCK_DGRAM
  3289. * socket for the cooked interface, otherwise we first
  3290. * try a SOCK_RAW socket for the raw interface.
  3291. */
  3292. sock_fd = is_any_device ?
  3293. socket(PF_PACKET, SOCK_DGRAM, protocol) :
  3294. socket(PF_PACKET, SOCK_RAW, protocol);
  3295. if (sock_fd == -1) {
  3296. if (errno == EINVAL || errno == EAFNOSUPPORT) {
  3297. /*
  3298. * We don't support PF_PACKET/SOCK_whatever
  3299. * sockets; try the old mechanism.
  3300. */
  3301. return 0;
  3302. }
  3303. pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
  3304. errno, "socket");
  3305. if (errno == EPERM || errno == EACCES) {
  3306. /*
  3307. * You don't have permission to open the
  3308. * socket.
  3309. */
  3310. return PCAP_ERROR_PERM_DENIED;
  3311. } else {
  3312. /*
  3313. * Other error.
  3314. */
  3315. return PCAP_ERROR;
  3316. }
  3317. }
  3318. /* It seems the kernel supports the new interface. */
  3319. handlep->sock_packet = 0;
  3320. /*
  3321. * Get the interface index of the loopback device.
  3322. * If the attempt fails, don't fail, just set the
  3323. * "handlep->lo_ifindex" to -1.
  3324. *
  3325. * XXX - can there be more than one device that loops
  3326. * packets back, i.e. devices other than "lo"? If so,
  3327. * we'd need to find them all, and have an array of
  3328. * indices for them, and check all of them in
  3329. * "pcap_read_packet()".
  3330. */
  3331. handlep->lo_ifindex = iface_get_id(sock_fd, "lo", handle->errbuf);
  3332. /*
  3333. * Default value for offset to align link-layer payload
  3334. * on a 4-byte boundary.
  3335. */
  3336. handle->offset = 0;
  3337. /*
  3338. * What kind of frames do we have to deal with? Fall back
  3339. * to cooked mode if we have an unknown interface type
  3340. * or a type we know doesn't work well in raw mode.
  3341. */
  3342. if (!is_any_device) {
  3343. /* Assume for now we don't need cooked mode. */
  3344. handlep->cooked = 0;
  3345. if (handle->opt.rfmon) {
  3346. /*
  3347. * We were asked to turn on monitor mode.
  3348. * Do so before we get the link-layer type,
  3349. * because entering monitor mode could change
  3350. * the link-layer type.
  3351. */
  3352. err = enter_rfmon_mode(handle, sock_fd, device);
  3353. if (err < 0) {
  3354. /* Hard failure */
  3355. close(sock_fd);
  3356. return err;
  3357. }
  3358. if (err == 0) {
  3359. /*
  3360. * Nothing worked for turning monitor mode
  3361. * on.
  3362. */
  3363. close(sock_fd);
  3364. return PCAP_ERROR_RFMON_NOTSUP;
  3365. }
  3366. /*
  3367. * Either monitor mode has been turned on for
  3368. * the device, or we've been given a different
  3369. * device to open for monitor mode. If we've
  3370. * been given a different device, use it.
  3371. */
  3372. if (handlep->mondevice != NULL)
  3373. device = handlep->mondevice;
  3374. }
  3375. arptype = iface_get_arptype(sock_fd, device, handle->errbuf);
  3376. if (arptype < 0) {
  3377. close(sock_fd);
  3378. return arptype;
  3379. }
  3380. map_arphrd_to_dlt(handle, sock_fd, arptype, device, 1);
  3381. if (handle->linktype == -1 ||
  3382. handle->linktype == DLT_LINUX_SLL ||
  3383. handle->linktype == DLT_LINUX_IRDA ||
  3384. handle->linktype == DLT_LINUX_LAPD ||
  3385. handle->linktype == DLT_NETLINK ||
  3386. (handle->linktype == DLT_EN10MB &&
  3387. (strncmp("isdn", device, 4) == 0 ||
  3388. strncmp("isdY", device, 4) == 0))) {
  3389. /*
  3390. * Unknown interface type (-1), or a
  3391. * device we explicitly chose to run
  3392. * in cooked mode (e.g., PPP devices),
  3393. * or an ISDN device (whose link-layer
  3394. * type we can only determine by using
  3395. * APIs that may be different on different
  3396. * kernels) - reopen in cooked mode.
  3397. */
  3398. if (close(sock_fd) == -1) {
  3399. pcap_fmt_errmsg_for_errno(handle->errbuf,
  3400. PCAP_ERRBUF_SIZE, errno, "close");
  3401. return PCAP_ERROR;
  3402. }
  3403. sock_fd = socket(PF_PACKET, SOCK_DGRAM, protocol);
  3404. if (sock_fd == -1) {
  3405. pcap_fmt_errmsg_for_errno(handle->errbuf,
  3406. PCAP_ERRBUF_SIZE, errno, "socket");
  3407. if (errno == EPERM || errno == EACCES) {
  3408. /*
  3409. * You don't have permission to
  3410. * open the socket.
  3411. */
  3412. return PCAP_ERROR_PERM_DENIED;
  3413. } else {
  3414. /*
  3415. * Other error.
  3416. */
  3417. return PCAP_ERROR;
  3418. }
  3419. }
  3420. handlep->cooked = 1;
  3421. /*
  3422. * Get rid of any link-layer type list
  3423. * we allocated - this only supports cooked
  3424. * capture.
  3425. */
  3426. if (handle->dlt_list != NULL) {
  3427. free(handle->dlt_list);
  3428. handle->dlt_list = NULL;
  3429. handle->dlt_count = 0;
  3430. }
  3431. if (handle->linktype == -1) {
  3432. /*
  3433. * Warn that we're falling back on
  3434. * cooked mode; we may want to
  3435. * update "map_arphrd_to_dlt()"
  3436. * to handle the new type.
  3437. */
  3438. pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  3439. "arptype %d not "
  3440. "supported by libpcap - "
  3441. "falling back to cooked "
  3442. "socket",
  3443. arptype);
  3444. }
  3445. /*
  3446. * IrDA capture is not a real "cooked" capture,
  3447. * it's IrLAP frames, not IP packets. The
  3448. * same applies to LAPD capture.
  3449. */
  3450. if (handle->linktype != DLT_LINUX_IRDA &&
  3451. handle->linktype != DLT_LINUX_LAPD &&
  3452. handle->linktype != DLT_NETLINK)
  3453. handle->linktype = DLT_LINUX_SLL;
  3454. }
  3455. handlep->ifindex = iface_get_id(sock_fd, device,
  3456. handle->errbuf);
  3457. if (handlep->ifindex == -1) {
  3458. close(sock_fd);
  3459. return PCAP_ERROR;
  3460. }
  3461. if ((err = iface_bind(sock_fd, handlep->ifindex,
  3462. handle->errbuf, protocol)) != 1) {
  3463. close(sock_fd);
  3464. if (err < 0)
  3465. return err;
  3466. else
  3467. return 0; /* try old mechanism */
  3468. }
  3469. } else {
  3470. /*
  3471. * The "any" device.
  3472. */
  3473. if (handle->opt.rfmon) {
  3474. /*
  3475. * It doesn't support monitor mode.
  3476. */
  3477. close(sock_fd);
  3478. return PCAP_ERROR_RFMON_NOTSUP;
  3479. }
  3480. /*
  3481. * It uses cooked mode.
  3482. */
  3483. handlep->cooked = 1;
  3484. handle->linktype = DLT_LINUX_SLL;
  3485. /*
  3486. * We're not bound to a device.
  3487. * For now, we're using this as an indication
  3488. * that we can't transmit; stop doing that only
  3489. * if we figure out how to transmit in cooked
  3490. * mode.
  3491. */
  3492. handlep->ifindex = -1;
  3493. }
  3494. /*
  3495. * Select promiscuous mode on if "promisc" is set.
  3496. *
  3497. * Do not turn allmulti mode on if we don't select
  3498. * promiscuous mode - on some devices (e.g., Orinoco
  3499. * wireless interfaces), allmulti mode isn't supported
  3500. * and the driver implements it by turning promiscuous
  3501. * mode on, and that screws up the operation of the
  3502. * card as a normal networking interface, and on no
  3503. * other platform I know of does starting a non-
  3504. * promiscuous capture affect which multicast packets
  3505. * are received by the interface.
  3506. */
  3507. /*
  3508. * Hmm, how can we set promiscuous mode on all interfaces?
  3509. * I am not sure if that is possible at all. For now, we
  3510. * silently ignore attempts to turn promiscuous mode on
  3511. * for the "any" device (so you don't have to explicitly
  3512. * disable it in programs such as tcpdump).
  3513. */
  3514. if (!is_any_device && handle->opt.promisc) {
  3515. memset(&mr, 0, sizeof(mr));
  3516. mr.mr_ifindex = handlep->ifindex;
  3517. mr.mr_type = PACKET_MR_PROMISC;
  3518. if (setsockopt(sock_fd, SOL_PACKET, PACKET_ADD_MEMBERSHIP,
  3519. &mr, sizeof(mr)) == -1) {
  3520. pcap_fmt_errmsg_for_errno(handle->errbuf,
  3521. PCAP_ERRBUF_SIZE, errno, "setsockopt");
  3522. close(sock_fd);
  3523. return PCAP_ERROR;
  3524. }
  3525. }
  3526. /* Enable auxillary data if supported and reserve room for
  3527. * reconstructing VLAN headers. */
  3528. #ifdef HAVE_PACKET_AUXDATA
  3529. val = 1;
  3530. if (setsockopt(sock_fd, SOL_PACKET, PACKET_AUXDATA, &val,
  3531. sizeof(val)) == -1 && errno != ENOPROTOOPT) {
  3532. pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
  3533. errno, "setsockopt");
  3534. close(sock_fd);
  3535. return PCAP_ERROR;
  3536. }
  3537. handle->offset += VLAN_TAG_LEN;
  3538. #endif /* HAVE_PACKET_AUXDATA */
  3539. /*
  3540. * This is a 2.2[.x] or later kernel (we know that
  3541. * because we're not using a SOCK_PACKET socket -
  3542. * PF_PACKET is supported only in 2.2 and later
  3543. * kernels).
  3544. *
  3545. * We can safely pass "recvfrom()" a byte count
  3546. * based on the snapshot length.
  3547. *
  3548. * If we're in cooked mode, make the snapshot length
  3549. * large enough to hold a "cooked mode" header plus
  3550. * 1 byte of packet data (so we don't pass a byte
  3551. * count of 0 to "recvfrom()").
  3552. */
  3553. if (handlep->cooked) {
  3554. if (handle->snapshot < SLL_HDR_LEN + 1)
  3555. handle->snapshot = SLL_HDR_LEN + 1;
  3556. }
  3557. handle->bufsize = handle->snapshot;
  3558. /*
  3559. * Set the offset at which to insert VLAN tags.
  3560. * That should be the offset of the type field.
  3561. */
  3562. switch (handle->linktype) {
  3563. case DLT_EN10MB:
  3564. /*
  3565. * The type field is after the destination and source
  3566. * MAC address.
  3567. */
  3568. handlep->vlan_offset = 2 * ETH_ALEN;
  3569. break;
  3570. case DLT_LINUX_SLL:
  3571. /*
  3572. * The type field is in the last 2 bytes of the
  3573. * DLT_LINUX_SLL header.
  3574. */
  3575. handlep->vlan_offset = SLL_HDR_LEN - 2;
  3576. break;
  3577. default:
  3578. handlep->vlan_offset = -1; /* unknown */
  3579. break;
  3580. }
  3581. #if defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS)
  3582. if (handle->opt.tstamp_precision == PCAP_TSTAMP_PRECISION_NANO) {
  3583. int nsec_tstamps = 1;
  3584. if (setsockopt(sock_fd, SOL_SOCKET, SO_TIMESTAMPNS, &nsec_tstamps, sizeof(nsec_tstamps)) < 0) {
  3585. pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "setsockopt: unable to set SO_TIMESTAMPNS");
  3586. close(sock_fd);
  3587. return PCAP_ERROR;
  3588. }
  3589. }
  3590. #endif /* defined(SIOCGSTAMPNS) && defined(SO_TIMESTAMPNS) */
  3591. /*
  3592. * We've succeeded. Save the socket FD in the pcap structure.
  3593. */
  3594. handle->fd = sock_fd;
  3595. #if defined(SO_BPF_EXTENSIONS) && defined(SKF_AD_VLAN_TAG_PRESENT)
  3596. /*
  3597. * Can we generate special code for VLAN checks?
  3598. * (XXX - what if we need the special code but it's not supported
  3599. * by the OS? Is that possible?)
  3600. */
  3601. if (getsockopt(sock_fd, SOL_SOCKET, SO_BPF_EXTENSIONS,
  3602. &bpf_extensions, &len) == 0) {
  3603. if (bpf_extensions >= SKF_AD_VLAN_TAG_PRESENT) {
  3604. /*
  3605. * Yes, we can. Request that we do so.
  3606. */
  3607. handle->bpf_codegen_flags |= BPF_SPECIAL_VLAN_HANDLING;
  3608. }
  3609. }
  3610. #endif /* defined(SO_BPF_EXTENSIONS) && defined(SKF_AD_VLAN_TAG_PRESENT) */
  3611. return 1;
  3612. #else /* HAVE_PF_PACKET_SOCKETS */
  3613. strlcpy(ebuf,
  3614. "New packet capturing interface not supported by build "
  3615. "environment", PCAP_ERRBUF_SIZE);
  3616. return 0;
  3617. #endif /* HAVE_PF_PACKET_SOCKETS */
  3618. }
  3619. #ifdef HAVE_PACKET_RING
  3620. /*
  3621. * Attempt to activate with memory-mapped access.
  3622. *
  3623. * On success, returns 1, and sets *status to 0 if there are no warnings
  3624. * or to a PCAP_WARNING_ code if there is a warning.
  3625. *
  3626. * On failure due to lack of support for memory-mapped capture, returns
  3627. * 0.
  3628. *
  3629. * On error, returns -1, and sets *status to the appropriate error code;
  3630. * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
  3631. */
  3632. static int
  3633. activate_mmap(pcap_t *handle, int *status)
  3634. {
  3635. struct pcap_linux *handlep = handle->priv;
  3636. int ret;
  3637. /*
  3638. * Attempt to allocate a buffer to hold the contents of one
  3639. * packet, for use by the oneshot callback.
  3640. */
  3641. handlep->oneshot_buffer = malloc(handle->snapshot);
  3642. if (handlep->oneshot_buffer == NULL) {
  3643. pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
  3644. errno, "can't allocate oneshot buffer");
  3645. *status = PCAP_ERROR;
  3646. return -1;
  3647. }
  3648. if (handle->opt.buffer_size == 0) {
  3649. /* by default request 2M for the ring buffer */
  3650. handle->opt.buffer_size = 2*1024*1024;
  3651. }
  3652. ret = prepare_tpacket_socket(handle);
  3653. if (ret == -1) {
  3654. free(handlep->oneshot_buffer);
  3655. *status = PCAP_ERROR;
  3656. return ret;
  3657. }
  3658. ret = create_ring(handle, status);
  3659. if (ret == 0) {
  3660. /*
  3661. * We don't support memory-mapped capture; our caller
  3662. * will fall back on reading from the socket.
  3663. */
  3664. free(handlep->oneshot_buffer);
  3665. return 0;
  3666. }
  3667. if (ret == -1) {
  3668. /*
  3669. * Error attempting to enable memory-mapped capture;
  3670. * fail. create_ring() has set *status.
  3671. */
  3672. free(handlep->oneshot_buffer);
  3673. return -1;
  3674. }
  3675. /*
  3676. * Success. *status has been set either to 0 if there are no
  3677. * warnings or to a PCAP_WARNING_ value if there is a warning.
  3678. *
  3679. * Override some defaults and inherit the other fields from
  3680. * activate_new.
  3681. * handle->offset is used to get the current position into the rx ring.
  3682. * handle->cc is used to store the ring size.
  3683. */
  3684. switch (handlep->tp_version) {
  3685. case TPACKET_V1:
  3686. handle->read_op = pcap_read_linux_mmap_v1;
  3687. break;
  3688. case TPACKET_V1_64:
  3689. handle->read_op = pcap_read_linux_mmap_v1_64;
  3690. break;
  3691. #ifdef HAVE_TPACKET2
  3692. case TPACKET_V2:
  3693. handle->read_op = pcap_read_linux_mmap_v2;
  3694. break;
  3695. #endif
  3696. #ifdef HAVE_TPACKET3
  3697. case TPACKET_V3:
  3698. handle->read_op = pcap_read_linux_mmap_v3;
  3699. break;
  3700. #endif
  3701. }
  3702. handle->cleanup_op = pcap_cleanup_linux_mmap;
  3703. handle->setfilter_op = pcap_setfilter_linux_mmap;
  3704. handle->setnonblock_op = pcap_setnonblock_mmap;
  3705. handle->getnonblock_op = pcap_getnonblock_mmap;
  3706. handle->oneshot_callback = pcap_oneshot_mmap;
  3707. handle->selectable_fd = handle->fd;
  3708. return 1;
  3709. }
  3710. #else /* HAVE_PACKET_RING */
  3711. static int
  3712. activate_mmap(pcap_t *handle _U_, int *status _U_)
  3713. {
  3714. return 0;
  3715. }
  3716. #endif /* HAVE_PACKET_RING */
  3717. #ifdef HAVE_PACKET_RING
  3718. #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
  3719. /*
  3720. * Attempt to set the socket to the specified version of the memory-mapped
  3721. * header.
  3722. *
  3723. * Return 0 if we succeed; return 1 if we fail because that version isn't
  3724. * supported; return -1 on any other error, and set handle->errbuf.
  3725. */
  3726. static int
  3727. init_tpacket(pcap_t *handle, int version, const char *version_str)
  3728. {
  3729. struct pcap_linux *handlep = handle->priv;
  3730. int val = version;
  3731. socklen_t len = sizeof(val);
  3732. /*
  3733. * Probe whether kernel supports the specified TPACKET version;
  3734. * this also gets the length of the header for that version.
  3735. */
  3736. if (getsockopt(handle->fd, SOL_PACKET, PACKET_HDRLEN, &val, &len) < 0) {
  3737. if (errno == ENOPROTOOPT || errno == EINVAL)
  3738. return 1; /* no */
  3739. /* Failed to even find out; this is a fatal error. */
  3740. pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
  3741. errno, "can't get %s header len on packet socket",
  3742. version_str);
  3743. return -1;
  3744. }
  3745. handlep->tp_hdrlen = val;
  3746. val = version;
  3747. if (setsockopt(handle->fd, SOL_PACKET, PACKET_VERSION, &val,
  3748. sizeof(val)) < 0) {
  3749. pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
  3750. errno, "can't activate %s on packet socket", version_str);
  3751. return -1;
  3752. }
  3753. handlep->tp_version = version;
  3754. /* Reserve space for VLAN tag reconstruction */
  3755. val = VLAN_TAG_LEN;
  3756. if (setsockopt(handle->fd, SOL_PACKET, PACKET_RESERVE, &val,
  3757. sizeof(val)) < 0) {
  3758. pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
  3759. errno, "can't set up reserve on packet socket");
  3760. return -1;
  3761. }
  3762. return 0;
  3763. }
  3764. #endif /* defined HAVE_TPACKET2 || defined HAVE_TPACKET3 */
  3765. /*
  3766. * If the instruction set for which we're compiling has both 32-bit
  3767. * and 64-bit versions, and Linux support for the 64-bit version
  3768. * predates TPACKET_V2, define ISA_64_BIT as the .machine value
  3769. * you get from uname() for the 64-bit version. Otherwise, leave
  3770. * it undefined. (This includes ARM, which has a 64-bit version,
  3771. * but Linux support for it appeared well after TPACKET_V2 support
  3772. * did, so there should never be a case where 32-bit ARM code is
  3773. * running o a 64-bit kernel that only supports TPACKET_V1.)
  3774. *
  3775. * If we've omitted your favorite such architecture, please contribute
  3776. * a patch. (No patch is needed for architectures that are 32-bit-only
  3777. * or for which Linux has no support for 32-bit userland - or for which,
  3778. * as noted, 64-bit support appeared in Linux after TPACKET_V2 support
  3779. * did.)
  3780. */
  3781. #if defined(__i386__)
  3782. #define ISA_64_BIT "x86_64"
  3783. #elif defined(__ppc__)
  3784. #define ISA_64_BIT "ppc64"
  3785. #elif defined(__sparc__)
  3786. #define ISA_64_BIT "sparc64"
  3787. #elif defined(__s390__)
  3788. #define ISA_64_BIT "s390x"
  3789. #elif defined(__mips__)
  3790. #define ISA_64_BIT "mips64"
  3791. #elif defined(__hppa__)
  3792. #define ISA_64_BIT "parisc64"
  3793. #endif
  3794. /*
  3795. * Attempt to set the socket to version 3 of the memory-mapped header and,
  3796. * if that fails because version 3 isn't supported, attempt to fall
  3797. * back to version 2. If version 2 isn't supported, just leave it at
  3798. * version 1.
  3799. *
  3800. * Return 1 if we succeed or if we fail because neither version 2 nor 3 is
  3801. * supported; return -1 on any other error, and set handle->errbuf.
  3802. */
  3803. static int
  3804. prepare_tpacket_socket(pcap_t *handle)
  3805. {
  3806. struct pcap_linux *handlep = handle->priv;
  3807. #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
  3808. int ret;
  3809. #endif
  3810. #ifdef HAVE_TPACKET3
  3811. /*
  3812. * Try setting the version to TPACKET_V3.
  3813. *
  3814. * The only mode in which buffering is done on PF_PACKET
  3815. * sockets, so that packets might not be delivered
  3816. * immediately, is TPACKET_V3 mode.
  3817. *
  3818. * The buffering cannot be disabled in that mode, so
  3819. * if the user has requested immediate mode, we don't
  3820. * use TPACKET_V3.
  3821. */
  3822. if (!handle->opt.immediate) {
  3823. ret = init_tpacket(handle, TPACKET_V3, "TPACKET_V3");
  3824. if (ret == 0) {
  3825. /*
  3826. * Success.
  3827. */
  3828. return 1;
  3829. }
  3830. if (ret == -1) {
  3831. /*
  3832. * We failed for some reason other than "the
  3833. * kernel doesn't support TPACKET_V3".
  3834. */
  3835. return -1;
  3836. }
  3837. }
  3838. #endif /* HAVE_TPACKET3 */
  3839. #ifdef HAVE_TPACKET2
  3840. /*
  3841. * Try setting the version to TPACKET_V2.
  3842. */
  3843. ret = init_tpacket(handle, TPACKET_V2, "TPACKET_V2");
  3844. if (ret == 0) {
  3845. /*
  3846. * Success.
  3847. */
  3848. return 1;
  3849. }
  3850. if (ret == -1) {
  3851. /*
  3852. * We failed for some reason other than "the
  3853. * kernel doesn't support TPACKET_V2".
  3854. */
  3855. return -1;
  3856. }
  3857. #endif /* HAVE_TPACKET2 */
  3858. /*
  3859. * OK, we're using TPACKET_V1, as that's all the kernel supports.
  3860. */
  3861. handlep->tp_version = TPACKET_V1;
  3862. handlep->tp_hdrlen = sizeof(struct tpacket_hdr);
  3863. #ifdef ISA_64_BIT
  3864. /*
  3865. * 32-bit userspace + 64-bit kernel + TPACKET_V1 are not compatible with
  3866. * each other due to platform-dependent data type size differences.
  3867. *
  3868. * If we have a 32-bit userland and a 64-bit kernel, use an
  3869. * internally-defined TPACKET_V1_64, with which we use a 64-bit
  3870. * version of the data structures.
  3871. */
  3872. if (sizeof(long) == 4) {
  3873. /*
  3874. * This is 32-bit code.
  3875. */
  3876. struct utsname utsname;
  3877. if (uname(&utsname) == -1) {
  3878. /*
  3879. * Failed.
  3880. */
  3881. pcap_fmt_errmsg_for_errno(handle->errbuf,
  3882. PCAP_ERRBUF_SIZE, errno, "uname failed");
  3883. return -1;
  3884. }
  3885. if (strcmp(utsname.machine, ISA_64_BIT) == 0) {
  3886. /*
  3887. * uname() tells us the machine is 64-bit,
  3888. * so we presumably have a 64-bit kernel.
  3889. *
  3890. * XXX - this presumes that uname() won't lie
  3891. * in 32-bit code and claim that the machine
  3892. * has the 32-bit version of the ISA.
  3893. */
  3894. handlep->tp_version = TPACKET_V1_64;
  3895. handlep->tp_hdrlen = sizeof(struct tpacket_hdr_64);
  3896. }
  3897. }
  3898. #endif
  3899. return 1;
  3900. }
  3901. #define MAX(a,b) ((a)>(b)?(a):(b))
  3902. /*
  3903. * Attempt to set up memory-mapped access.
  3904. *
  3905. * On success, returns 1, and sets *status to 0 if there are no warnings
  3906. * or to a PCAP_WARNING_ code if there is a warning.
  3907. *
  3908. * On failure due to lack of support for memory-mapped capture, returns
  3909. * 0.
  3910. *
  3911. * On error, returns -1, and sets *status to the appropriate error code;
  3912. * if that is PCAP_ERROR, sets handle->errbuf to the appropriate message.
  3913. */
  3914. static int
  3915. create_ring(pcap_t *handle, int *status)
  3916. {
  3917. struct pcap_linux *handlep = handle->priv;
  3918. unsigned i, j, frames_per_block;
  3919. #ifdef HAVE_TPACKET3
  3920. /*
  3921. * For sockets using TPACKET_V1 or TPACKET_V2, the extra
  3922. * stuff at the end of a struct tpacket_req3 will be
  3923. * ignored, so this is OK even for those sockets.
  3924. */
  3925. struct tpacket_req3 req;
  3926. #else
  3927. struct tpacket_req req;
  3928. #endif
  3929. socklen_t len;
  3930. unsigned int sk_type, tp_reserve, maclen, tp_hdrlen, netoff, macoff;
  3931. unsigned int frame_size;
  3932. /*
  3933. * Start out assuming no warnings or errors.
  3934. */
  3935. *status = 0;
  3936. switch (handlep->tp_version) {
  3937. case TPACKET_V1:
  3938. case TPACKET_V1_64:
  3939. #ifdef HAVE_TPACKET2
  3940. case TPACKET_V2:
  3941. #endif
  3942. /* Note that with large snapshot length (say 256K, which is
  3943. * the default for recent versions of tcpdump, Wireshark,
  3944. * TShark, dumpcap or 64K, the value that "-s 0" has given for
  3945. * a long time with tcpdump), if we use the snapshot
  3946. * length to calculate the frame length, only a few frames
  3947. * will be available in the ring even with pretty
  3948. * large ring size (and a lot of memory will be unused).
  3949. *
  3950. * Ideally, we should choose a frame length based on the
  3951. * minimum of the specified snapshot length and the maximum
  3952. * packet size. That's not as easy as it sounds; consider,
  3953. * for example, an 802.11 interface in monitor mode, where
  3954. * the frame would include a radiotap header, where the
  3955. * maximum radiotap header length is device-dependent.
  3956. *
  3957. * So, for now, we just do this for Ethernet devices, where
  3958. * there's no metadata header, and the link-layer header is
  3959. * fixed length. We can get the maximum packet size by
  3960. * adding 18, the Ethernet header length plus the CRC length
  3961. * (just in case we happen to get the CRC in the packet), to
  3962. * the MTU of the interface; we fetch the MTU in the hopes
  3963. * that it reflects support for jumbo frames. (Even if the
  3964. * interface is just being used for passive snooping, the
  3965. * driver might set the size of buffers in the receive ring
  3966. * based on the MTU, so that the MTU limits the maximum size
  3967. * of packets that we can receive.)
  3968. *
  3969. * If segmentation/fragmentation or receive offload are
  3970. * enabled, we can get reassembled/aggregated packets larger
  3971. * than MTU, but bounded to 65535 plus the Ethernet overhead,
  3972. * due to kernel and protocol constraints */
  3973. frame_size = handle->snapshot;
  3974. if (handle->linktype == DLT_EN10MB) {
  3975. unsigned int max_frame_len;
  3976. int mtu;
  3977. int offload;
  3978. mtu = iface_get_mtu(handle->fd, handle->opt.device,
  3979. handle->errbuf);
  3980. if (mtu == -1) {
  3981. *status = PCAP_ERROR;
  3982. return -1;
  3983. }
  3984. offload = iface_get_offload(handle);
  3985. if (offload == -1) {
  3986. *status = PCAP_ERROR;
  3987. return -1;
  3988. }
  3989. if (offload)
  3990. max_frame_len = MAX(mtu, 65535);
  3991. else
  3992. max_frame_len = mtu;
  3993. max_frame_len += 18;
  3994. if (frame_size > max_frame_len)
  3995. frame_size = max_frame_len;
  3996. }
  3997. /* NOTE: calculus matching those in tpacket_rcv()
  3998. * in linux-2.6/net/packet/af_packet.c
  3999. */
  4000. len = sizeof(sk_type);
  4001. if (getsockopt(handle->fd, SOL_SOCKET, SO_TYPE, &sk_type,
  4002. &len) < 0) {
  4003. pcap_fmt_errmsg_for_errno(handle->errbuf,
  4004. PCAP_ERRBUF_SIZE, errno, "getsockopt");
  4005. *status = PCAP_ERROR;
  4006. return -1;
  4007. }
  4008. #ifdef PACKET_RESERVE
  4009. len = sizeof(tp_reserve);
  4010. if (getsockopt(handle->fd, SOL_PACKET, PACKET_RESERVE,
  4011. &tp_reserve, &len) < 0) {
  4012. if (errno != ENOPROTOOPT) {
  4013. /*
  4014. * ENOPROTOOPT means "kernel doesn't support
  4015. * PACKET_RESERVE", in which case we fall back
  4016. * as best we can.
  4017. */
  4018. pcap_fmt_errmsg_for_errno(handle->errbuf,
  4019. PCAP_ERRBUF_SIZE, errno, "getsockopt");
  4020. *status = PCAP_ERROR;
  4021. return -1;
  4022. }
  4023. tp_reserve = 0; /* older kernel, reserve not supported */
  4024. }
  4025. #else
  4026. tp_reserve = 0; /* older kernel, reserve not supported */
  4027. #endif
  4028. maclen = (sk_type == SOCK_DGRAM) ? 0 : MAX_LINKHEADER_SIZE;
  4029. /* XXX: in the kernel maclen is calculated from
  4030. * LL_ALLOCATED_SPACE(dev) and vnet_hdr.hdr_len
  4031. * in: packet_snd() in linux-2.6/net/packet/af_packet.c
  4032. * then packet_alloc_skb() in linux-2.6/net/packet/af_packet.c
  4033. * then sock_alloc_send_pskb() in linux-2.6/net/core/sock.c
  4034. * but I see no way to get those sizes in userspace,
  4035. * like for instance with an ifreq ioctl();
  4036. * the best thing I've found so far is MAX_HEADER in
  4037. * the kernel part of linux-2.6/include/linux/netdevice.h
  4038. * which goes up to 128+48=176; since pcap-linux.c
  4039. * defines a MAX_LINKHEADER_SIZE of 256 which is
  4040. * greater than that, let's use it.. maybe is it even
  4041. * large enough to directly replace macoff..
  4042. */
  4043. tp_hdrlen = TPACKET_ALIGN(handlep->tp_hdrlen) + sizeof(struct sockaddr_ll) ;
  4044. netoff = TPACKET_ALIGN(tp_hdrlen + (maclen < 16 ? 16 : maclen)) + tp_reserve;
  4045. /* NOTE: AFAICS tp_reserve may break the TPACKET_ALIGN
  4046. * of netoff, which contradicts
  4047. * linux-2.6/Documentation/networking/packet_mmap.txt
  4048. * documenting that:
  4049. * "- Gap, chosen so that packet data (Start+tp_net)
  4050. * aligns to TPACKET_ALIGNMENT=16"
  4051. */
  4052. /* NOTE: in linux-2.6/include/linux/skbuff.h:
  4053. * "CPUs often take a performance hit
  4054. * when accessing unaligned memory locations"
  4055. */
  4056. macoff = netoff - maclen;
  4057. req.tp_frame_size = TPACKET_ALIGN(macoff + frame_size);
  4058. /*
  4059. * Round the buffer size up to a multiple of the
  4060. * frame size (rather than rounding down, which
  4061. * would give a buffer smaller than our caller asked
  4062. * for, and possibly give zero frames if the requested
  4063. * buffer size is too small for one frame).
  4064. */
  4065. req.tp_frame_nr = (handle->opt.buffer_size + req.tp_frame_size - 1)/req.tp_frame_size;
  4066. break;
  4067. #ifdef HAVE_TPACKET3
  4068. case TPACKET_V3:
  4069. /* The "frames" for this are actually buffers that
  4070. * contain multiple variable-sized frames.
  4071. *
  4072. * We pick a "frame" size of MAXIMUM_SNAPLEN to leave
  4073. * enough room for at least one reasonably-sized packet
  4074. * in the "frame". */
  4075. req.tp_frame_size = MAXIMUM_SNAPLEN;
  4076. /*
  4077. * Round the buffer size up to a multiple of the
  4078. * "frame" size (rather than rounding down, which
  4079. * would give a buffer smaller than our caller asked
  4080. * for, and possibly give zero "frames" if the requested
  4081. * buffer size is too small for one "frame").
  4082. */
  4083. req.tp_frame_nr = (handle->opt.buffer_size + req.tp_frame_size - 1)/req.tp_frame_size;
  4084. break;
  4085. #endif
  4086. default:
  4087. pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  4088. "Internal error: unknown TPACKET_ value %u",
  4089. handlep->tp_version);
  4090. *status = PCAP_ERROR;
  4091. return -1;
  4092. }
  4093. /* compute the minumum block size that will handle this frame.
  4094. * The block has to be page size aligned.
  4095. * The max block size allowed by the kernel is arch-dependent and
  4096. * it's not explicitly checked here. */
  4097. req.tp_block_size = getpagesize();
  4098. while (req.tp_block_size < req.tp_frame_size)
  4099. req.tp_block_size <<= 1;
  4100. frames_per_block = req.tp_block_size/req.tp_frame_size;
  4101. /*
  4102. * PACKET_TIMESTAMP was added after linux/net_tstamp.h was,
  4103. * so we check for PACKET_TIMESTAMP. We check for
  4104. * linux/net_tstamp.h just in case a system somehow has
  4105. * PACKET_TIMESTAMP but not linux/net_tstamp.h; that might
  4106. * be unnecessary.
  4107. *
  4108. * SIOCSHWTSTAMP was introduced in the patch that introduced
  4109. * linux/net_tstamp.h, so we don't bother checking whether
  4110. * SIOCSHWTSTAMP is defined (if your Linux system has
  4111. * linux/net_tstamp.h but doesn't define SIOCSHWTSTAMP, your
  4112. * Linux system is badly broken).
  4113. */
  4114. #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
  4115. /*
  4116. * If we were told to do so, ask the kernel and the driver
  4117. * to use hardware timestamps.
  4118. *
  4119. * Hardware timestamps are only supported with mmapped
  4120. * captures.
  4121. */
  4122. if (handle->opt.tstamp_type == PCAP_TSTAMP_ADAPTER ||
  4123. handle->opt.tstamp_type == PCAP_TSTAMP_ADAPTER_UNSYNCED) {
  4124. struct hwtstamp_config hwconfig;
  4125. struct ifreq ifr;
  4126. int timesource;
  4127. /*
  4128. * Ask for hardware time stamps on all packets,
  4129. * including transmitted packets.
  4130. */
  4131. memset(&hwconfig, 0, sizeof(hwconfig));
  4132. hwconfig.tx_type = HWTSTAMP_TX_ON;
  4133. hwconfig.rx_filter = HWTSTAMP_FILTER_ALL;
  4134. memset(&ifr, 0, sizeof(ifr));
  4135. strlcpy(ifr.ifr_name, handle->opt.device, sizeof(ifr.ifr_name));
  4136. ifr.ifr_data = (void *)&hwconfig;
  4137. if (ioctl(handle->fd, SIOCSHWTSTAMP, &ifr) < 0) {
  4138. switch (errno) {
  4139. case EPERM:
  4140. /*
  4141. * Treat this as an error, as the
  4142. * user should try to run this
  4143. * with the appropriate privileges -
  4144. * and, if they can't, shouldn't
  4145. * try requesting hardware time stamps.
  4146. */
  4147. *status = PCAP_ERROR_PERM_DENIED;
  4148. return -1;
  4149. case EOPNOTSUPP:
  4150. case ERANGE:
  4151. /*
  4152. * Treat this as a warning, as the
  4153. * only way to fix the warning is to
  4154. * get an adapter that supports hardware
  4155. * time stamps for *all* packets.
  4156. * (ERANGE means "we support hardware
  4157. * time stamps, but for packets matching
  4158. * that particular filter", so it means
  4159. * "we don't support hardware time stamps
  4160. * for all incoming packets" here.)
  4161. *
  4162. * We'll just fall back on the standard
  4163. * host time stamps.
  4164. */
  4165. *status = PCAP_WARNING_TSTAMP_TYPE_NOTSUP;
  4166. break;
  4167. default:
  4168. pcap_fmt_errmsg_for_errno(handle->errbuf,
  4169. PCAP_ERRBUF_SIZE, errno,
  4170. "SIOCSHWTSTAMP failed");
  4171. *status = PCAP_ERROR;
  4172. return -1;
  4173. }
  4174. } else {
  4175. /*
  4176. * Well, that worked. Now specify the type of
  4177. * hardware time stamp we want for this
  4178. * socket.
  4179. */
  4180. if (handle->opt.tstamp_type == PCAP_TSTAMP_ADAPTER) {
  4181. /*
  4182. * Hardware timestamp, synchronized
  4183. * with the system clock.
  4184. */
  4185. timesource = SOF_TIMESTAMPING_SYS_HARDWARE;
  4186. } else {
  4187. /*
  4188. * PCAP_TSTAMP_ADAPTER_UNSYNCED - hardware
  4189. * timestamp, not synchronized with the
  4190. * system clock.
  4191. */
  4192. timesource = SOF_TIMESTAMPING_RAW_HARDWARE;
  4193. }
  4194. if (setsockopt(handle->fd, SOL_PACKET, PACKET_TIMESTAMP,
  4195. (void *)&timesource, sizeof(timesource))) {
  4196. pcap_fmt_errmsg_for_errno(handle->errbuf,
  4197. PCAP_ERRBUF_SIZE, errno,
  4198. "can't set PACKET_TIMESTAMP");
  4199. *status = PCAP_ERROR;
  4200. return -1;
  4201. }
  4202. }
  4203. }
  4204. #endif /* HAVE_LINUX_NET_TSTAMP_H && PACKET_TIMESTAMP */
  4205. /* ask the kernel to create the ring */
  4206. retry:
  4207. req.tp_block_nr = req.tp_frame_nr / frames_per_block;
  4208. /* req.tp_frame_nr is requested to match frames_per_block*req.tp_block_nr */
  4209. req.tp_frame_nr = req.tp_block_nr * frames_per_block;
  4210. #ifdef HAVE_TPACKET3
  4211. /* timeout value to retire block - use the configured buffering timeout, or default if <0. */
  4212. req.tp_retire_blk_tov = (handlep->timeout>=0)?handlep->timeout:0;
  4213. /* private data not used */
  4214. req.tp_sizeof_priv = 0;
  4215. /* Rx ring - feature request bits - none (rxhash will not be filled) */
  4216. req.tp_feature_req_word = 0;
  4217. #endif
  4218. if (setsockopt(handle->fd, SOL_PACKET, PACKET_RX_RING,
  4219. (void *) &req, sizeof(req))) {
  4220. if ((errno == ENOMEM) && (req.tp_block_nr > 1)) {
  4221. /*
  4222. * Memory failure; try to reduce the requested ring
  4223. * size.
  4224. *
  4225. * We used to reduce this by half -- do 5% instead.
  4226. * That may result in more iterations and a longer
  4227. * startup, but the user will be much happier with
  4228. * the resulting buffer size.
  4229. */
  4230. if (req.tp_frame_nr < 20)
  4231. req.tp_frame_nr -= 1;
  4232. else
  4233. req.tp_frame_nr -= req.tp_frame_nr/20;
  4234. goto retry;
  4235. }
  4236. if (errno == ENOPROTOOPT) {
  4237. /*
  4238. * We don't have ring buffer support in this kernel.
  4239. */
  4240. return 0;
  4241. }
  4242. pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
  4243. errno, "can't create rx ring on packet socket");
  4244. *status = PCAP_ERROR;
  4245. return -1;
  4246. }
  4247. /* memory map the rx ring */
  4248. handlep->mmapbuflen = req.tp_block_nr * req.tp_block_size;
  4249. handlep->mmapbuf = mmap(0, handlep->mmapbuflen,
  4250. PROT_READ|PROT_WRITE, MAP_SHARED, handle->fd, 0);
  4251. if (handlep->mmapbuf == MAP_FAILED) {
  4252. pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
  4253. errno, "can't mmap rx ring");
  4254. /* clear the allocated ring on error*/
  4255. destroy_ring(handle);
  4256. *status = PCAP_ERROR;
  4257. return -1;
  4258. }
  4259. /* allocate a ring for each frame header pointer*/
  4260. handle->cc = req.tp_frame_nr;
  4261. handle->buffer = malloc(handle->cc * sizeof(union thdr *));
  4262. if (!handle->buffer) {
  4263. pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
  4264. errno, "can't allocate ring of frame headers");
  4265. destroy_ring(handle);
  4266. *status = PCAP_ERROR;
  4267. return -1;
  4268. }
  4269. /* fill the header ring with proper frame ptr*/
  4270. handle->offset = 0;
  4271. for (i=0; i<req.tp_block_nr; ++i) {
  4272. void *base = &handlep->mmapbuf[i*req.tp_block_size];
  4273. for (j=0; j<frames_per_block; ++j, ++handle->offset) {
  4274. RING_GET_CURRENT_FRAME(handle) = base;
  4275. base += req.tp_frame_size;
  4276. }
  4277. }
  4278. handle->bufsize = req.tp_frame_size;
  4279. handle->offset = 0;
  4280. return 1;
  4281. }
  4282. /* free all ring related resources*/
  4283. static void
  4284. destroy_ring(pcap_t *handle)
  4285. {
  4286. struct pcap_linux *handlep = handle->priv;
  4287. /* tell the kernel to destroy the ring*/
  4288. struct tpacket_req req;
  4289. memset(&req, 0, sizeof(req));
  4290. /* do not test for setsockopt failure, as we can't recover from any error */
  4291. (void)setsockopt(handle->fd, SOL_PACKET, PACKET_RX_RING,
  4292. (void *) &req, sizeof(req));
  4293. /* if ring is mapped, unmap it*/
  4294. if (handlep->mmapbuf) {
  4295. /* do not test for mmap failure, as we can't recover from any error */
  4296. (void)munmap(handlep->mmapbuf, handlep->mmapbuflen);
  4297. handlep->mmapbuf = NULL;
  4298. }
  4299. }
  4300. /*
  4301. * Special one-shot callback, used for pcap_next() and pcap_next_ex(),
  4302. * for Linux mmapped capture.
  4303. *
  4304. * The problem is that pcap_next() and pcap_next_ex() expect the packet
  4305. * data handed to the callback to be valid after the callback returns,
  4306. * but pcap_read_linux_mmap() has to release that packet as soon as
  4307. * the callback returns (otherwise, the kernel thinks there's still
  4308. * at least one unprocessed packet available in the ring, so a select()
  4309. * will immediately return indicating that there's data to process), so,
  4310. * in the callback, we have to make a copy of the packet.
  4311. *
  4312. * Yes, this means that, if the capture is using the ring buffer, using
  4313. * pcap_next() or pcap_next_ex() requires more copies than using
  4314. * pcap_loop() or pcap_dispatch(). If that bothers you, don't use
  4315. * pcap_next() or pcap_next_ex().
  4316. */
  4317. static void
  4318. pcap_oneshot_mmap(u_char *user, const struct pcap_pkthdr *h,
  4319. const u_char *bytes)
  4320. {
  4321. struct oneshot_userdata *sp = (struct oneshot_userdata *)user;
  4322. pcap_t *handle = sp->pd;
  4323. struct pcap_linux *handlep = handle->priv;
  4324. *sp->hdr = *h;
  4325. memcpy(handlep->oneshot_buffer, bytes, h->caplen);
  4326. *sp->pkt = handlep->oneshot_buffer;
  4327. }
  4328. static void
  4329. pcap_cleanup_linux_mmap( pcap_t *handle )
  4330. {
  4331. struct pcap_linux *handlep = handle->priv;
  4332. destroy_ring(handle);
  4333. if (handlep->oneshot_buffer != NULL) {
  4334. free(handlep->oneshot_buffer);
  4335. handlep->oneshot_buffer = NULL;
  4336. }
  4337. pcap_cleanup_linux(handle);
  4338. }
  4339. static int
  4340. pcap_getnonblock_mmap(pcap_t *handle)
  4341. {
  4342. struct pcap_linux *handlep = handle->priv;
  4343. /* use negative value of timeout to indicate non blocking ops */
  4344. return (handlep->timeout<0);
  4345. }
  4346. static int
  4347. pcap_setnonblock_mmap(pcap_t *handle, int nonblock)
  4348. {
  4349. struct pcap_linux *handlep = handle->priv;
  4350. /*
  4351. * Set the file descriptor to non-blocking mode, as we use
  4352. * it for sending packets.
  4353. */
  4354. if (pcap_setnonblock_fd(handle, nonblock) == -1)
  4355. return -1;
  4356. /*
  4357. * Map each value to their corresponding negation to
  4358. * preserve the timeout value provided with pcap_set_timeout.
  4359. */
  4360. if (nonblock) {
  4361. if (handlep->timeout >= 0) {
  4362. /*
  4363. * Indicate that we're switching to
  4364. * non-blocking mode.
  4365. */
  4366. handlep->timeout = ~handlep->timeout;
  4367. }
  4368. } else {
  4369. if (handlep->timeout < 0) {
  4370. handlep->timeout = ~handlep->timeout;
  4371. }
  4372. }
  4373. /* Update the timeout to use in poll(). */
  4374. set_poll_timeout(handlep);
  4375. return 0;
  4376. }
  4377. /*
  4378. * Get the status field of the ring buffer frame at a specified offset.
  4379. */
  4380. static inline int
  4381. pcap_get_ring_frame_status(pcap_t *handle, int offset)
  4382. {
  4383. struct pcap_linux *handlep = handle->priv;
  4384. union thdr h;
  4385. h.raw = RING_GET_FRAME_AT(handle, offset);
  4386. switch (handlep->tp_version) {
  4387. case TPACKET_V1:
  4388. return (h.h1->tp_status);
  4389. break;
  4390. case TPACKET_V1_64:
  4391. return (h.h1_64->tp_status);
  4392. break;
  4393. #ifdef HAVE_TPACKET2
  4394. case TPACKET_V2:
  4395. return (h.h2->tp_status);
  4396. break;
  4397. #endif
  4398. #ifdef HAVE_TPACKET3
  4399. case TPACKET_V3:
  4400. return (h.h3->hdr.bh1.block_status);
  4401. break;
  4402. #endif
  4403. }
  4404. /* This should not happen. */
  4405. return 0;
  4406. }
  4407. #ifndef POLLRDHUP
  4408. #define POLLRDHUP 0
  4409. #endif
  4410. /*
  4411. * Block waiting for frames to be available.
  4412. */
  4413. static int pcap_wait_for_frames_mmap(pcap_t *handle)
  4414. {
  4415. struct pcap_linux *handlep = handle->priv;
  4416. char c;
  4417. struct pollfd pollinfo;
  4418. int ret;
  4419. pollinfo.fd = handle->fd;
  4420. pollinfo.events = POLLIN;
  4421. do {
  4422. /*
  4423. * Yes, we do this even in non-blocking mode, as it's
  4424. * the only way to get error indications from a
  4425. * tpacket socket.
  4426. *
  4427. * The timeout is 0 in non-blocking mode, so poll()
  4428. * returns immediately.
  4429. */
  4430. ret = poll(&pollinfo, 1, handlep->poll_timeout);
  4431. if (ret < 0 && errno != EINTR) {
  4432. pcap_fmt_errmsg_for_errno(handle->errbuf,
  4433. PCAP_ERRBUF_SIZE, errno,
  4434. "can't poll on packet socket");
  4435. return PCAP_ERROR;
  4436. } else if (ret > 0 &&
  4437. (pollinfo.revents & (POLLHUP|POLLRDHUP|POLLERR|POLLNVAL))) {
  4438. /*
  4439. * There's some indication other than
  4440. * "you can read on this descriptor" on
  4441. * the descriptor.
  4442. */
  4443. if (pollinfo.revents & (POLLHUP | POLLRDHUP)) {
  4444. pcap_snprintf(handle->errbuf,
  4445. PCAP_ERRBUF_SIZE,
  4446. "Hangup on packet socket");
  4447. return PCAP_ERROR;
  4448. }
  4449. if (pollinfo.revents & POLLERR) {
  4450. /*
  4451. * A recv() will give us the actual error code.
  4452. *
  4453. * XXX - make the socket non-blocking?
  4454. */
  4455. if (recv(handle->fd, &c, sizeof c,
  4456. MSG_PEEK) != -1)
  4457. continue; /* what, no error? */
  4458. if (errno == ENETDOWN) {
  4459. /*
  4460. * The device on which we're
  4461. * capturing went away.
  4462. *
  4463. * XXX - we should really return
  4464. * PCAP_ERROR_IFACE_NOT_UP, but
  4465. * pcap_dispatch() etc. aren't
  4466. * defined to return that.
  4467. */
  4468. pcap_snprintf(handle->errbuf,
  4469. PCAP_ERRBUF_SIZE,
  4470. "The interface went down");
  4471. } else {
  4472. pcap_fmt_errmsg_for_errno(handle->errbuf,
  4473. PCAP_ERRBUF_SIZE, errno,
  4474. "Error condition on packet socket");
  4475. }
  4476. return PCAP_ERROR;
  4477. }
  4478. if (pollinfo.revents & POLLNVAL) {
  4479. pcap_snprintf(handle->errbuf,
  4480. PCAP_ERRBUF_SIZE,
  4481. "Invalid polling request on packet socket");
  4482. return PCAP_ERROR;
  4483. }
  4484. }
  4485. /* check for break loop condition on interrupted syscall*/
  4486. if (handle->break_loop) {
  4487. handle->break_loop = 0;
  4488. return PCAP_ERROR_BREAK;
  4489. }
  4490. } while (ret < 0);
  4491. return 0;
  4492. }
  4493. /* handle a single memory mapped packet */
  4494. static int pcap_handle_packet_mmap(
  4495. pcap_t *handle,
  4496. pcap_handler callback,
  4497. u_char *user,
  4498. unsigned char *frame,
  4499. unsigned int tp_len,
  4500. unsigned int tp_mac,
  4501. unsigned int tp_snaplen,
  4502. unsigned int tp_sec,
  4503. unsigned int tp_usec,
  4504. int tp_vlan_tci_valid,
  4505. __u16 tp_vlan_tci,
  4506. __u16 tp_vlan_tpid)
  4507. {
  4508. struct pcap_linux *handlep = handle->priv;
  4509. unsigned char *bp;
  4510. struct sockaddr_ll *sll;
  4511. struct pcap_pkthdr pcaphdr;
  4512. unsigned int snaplen = tp_snaplen;
  4513. /* perform sanity check on internal offset. */
  4514. if (tp_mac + tp_snaplen > handle->bufsize) {
  4515. pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  4516. "corrupted frame on kernel ring mac "
  4517. "offset %u + caplen %u > frame len %d",
  4518. tp_mac, tp_snaplen, handle->bufsize);
  4519. return -1;
  4520. }
  4521. /* run filter on received packet
  4522. * If the kernel filtering is enabled we need to run the
  4523. * filter until all the frames present into the ring
  4524. * at filter creation time are processed.
  4525. * In this case, blocks_to_filter_in_userland is used
  4526. * as a counter for the packet we need to filter.
  4527. * Note: alternatively it could be possible to stop applying
  4528. * the filter when the ring became empty, but it can possibly
  4529. * happen a lot later... */
  4530. bp = frame + tp_mac;
  4531. /* if required build in place the sll header*/
  4532. sll = (void *)frame + TPACKET_ALIGN(handlep->tp_hdrlen);
  4533. if (handlep->cooked) {
  4534. struct sll_header *hdrp;
  4535. /*
  4536. * The kernel should have left us with enough
  4537. * space for an sll header; back up the packet
  4538. * data pointer into that space, as that'll be
  4539. * the beginning of the packet we pass to the
  4540. * callback.
  4541. */
  4542. bp -= SLL_HDR_LEN;
  4543. /*
  4544. * Let's make sure that's past the end of
  4545. * the tpacket header, i.e. >=
  4546. * ((u_char *)thdr + TPACKET_HDRLEN), so we
  4547. * don't step on the header when we construct
  4548. * the sll header.
  4549. */
  4550. if (bp < (u_char *)frame +
  4551. TPACKET_ALIGN(handlep->tp_hdrlen) +
  4552. sizeof(struct sockaddr_ll)) {
  4553. pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  4554. "cooked-mode frame doesn't have room for sll header");
  4555. return -1;
  4556. }
  4557. /*
  4558. * OK, that worked; construct the sll header.
  4559. */
  4560. hdrp = (struct sll_header *)bp;
  4561. hdrp->sll_pkttype = map_packet_type_to_sll_type(
  4562. sll->sll_pkttype);
  4563. hdrp->sll_hatype = htons(sll->sll_hatype);
  4564. hdrp->sll_halen = htons(sll->sll_halen);
  4565. memcpy(hdrp->sll_addr, sll->sll_addr, SLL_ADDRLEN);
  4566. hdrp->sll_protocol = sll->sll_protocol;
  4567. snaplen += sizeof(struct sll_header);
  4568. }
  4569. if (handlep->filter_in_userland && handle->fcode.bf_insns) {
  4570. struct bpf_aux_data aux_data;
  4571. aux_data.vlan_tag_present = tp_vlan_tci_valid;
  4572. aux_data.vlan_tag = tp_vlan_tci & 0x0fff;
  4573. if (bpf_filter_with_aux_data(handle->fcode.bf_insns,
  4574. bp,
  4575. tp_len,
  4576. snaplen,
  4577. &aux_data) == 0)
  4578. return 0;
  4579. }
  4580. if (!linux_check_direction(handle, sll))
  4581. return 0;
  4582. /* get required packet info from ring header */
  4583. pcaphdr.ts.tv_sec = tp_sec;
  4584. pcaphdr.ts.tv_usec = tp_usec;
  4585. pcaphdr.caplen = tp_snaplen;
  4586. pcaphdr.len = tp_len;
  4587. /* if required build in place the sll header*/
  4588. if (handlep->cooked) {
  4589. /* update packet len */
  4590. pcaphdr.caplen += SLL_HDR_LEN;
  4591. pcaphdr.len += SLL_HDR_LEN;
  4592. }
  4593. #if defined(HAVE_TPACKET2) || defined(HAVE_TPACKET3)
  4594. if (tp_vlan_tci_valid &&
  4595. handlep->vlan_offset != -1 &&
  4596. tp_snaplen >= (unsigned int) handlep->vlan_offset)
  4597. {
  4598. struct vlan_tag *tag;
  4599. /*
  4600. * Move everything in the header, except the type field,
  4601. * down VLAN_TAG_LEN bytes, to allow us to insert the
  4602. * VLAN tag between that stuff and the type field.
  4603. */
  4604. bp -= VLAN_TAG_LEN;
  4605. memmove(bp, bp + VLAN_TAG_LEN, handlep->vlan_offset);
  4606. /*
  4607. * Now insert the tag.
  4608. */
  4609. tag = (struct vlan_tag *)(bp + handlep->vlan_offset);
  4610. tag->vlan_tpid = htons(tp_vlan_tpid);
  4611. tag->vlan_tci = htons(tp_vlan_tci);
  4612. /*
  4613. * Add the tag to the packet lengths.
  4614. */
  4615. pcaphdr.caplen += VLAN_TAG_LEN;
  4616. pcaphdr.len += VLAN_TAG_LEN;
  4617. }
  4618. #endif
  4619. /*
  4620. * The only way to tell the kernel to cut off the
  4621. * packet at a snapshot length is with a filter program;
  4622. * if there's no filter program, the kernel won't cut
  4623. * the packet off.
  4624. *
  4625. * Trim the snapshot length to be no longer than the
  4626. * specified snapshot length.
  4627. */
  4628. if (pcaphdr.caplen > (bpf_u_int32)handle->snapshot)
  4629. pcaphdr.caplen = handle->snapshot;
  4630. /* pass the packet to the user */
  4631. callback(user, &pcaphdr, bp);
  4632. return 1;
  4633. }
  4634. static int
  4635. pcap_read_linux_mmap_v1(pcap_t *handle, int max_packets, pcap_handler callback,
  4636. u_char *user)
  4637. {
  4638. struct pcap_linux *handlep = handle->priv;
  4639. union thdr h;
  4640. int pkts = 0;
  4641. int ret;
  4642. /* wait for frames availability.*/
  4643. h.raw = RING_GET_CURRENT_FRAME(handle);
  4644. if (h.h1->tp_status == TP_STATUS_KERNEL) {
  4645. /*
  4646. * The current frame is owned by the kernel; wait for
  4647. * a frame to be handed to us.
  4648. */
  4649. ret = pcap_wait_for_frames_mmap(handle);
  4650. if (ret) {
  4651. return ret;
  4652. }
  4653. }
  4654. /* non-positive values of max_packets are used to require all
  4655. * packets currently available in the ring */
  4656. while ((pkts < max_packets) || PACKET_COUNT_IS_UNLIMITED(max_packets)) {
  4657. /*
  4658. * Get the current ring buffer frame, and break if
  4659. * it's still owned by the kernel.
  4660. */
  4661. h.raw = RING_GET_CURRENT_FRAME(handle);
  4662. if (h.h1->tp_status == TP_STATUS_KERNEL)
  4663. break;
  4664. ret = pcap_handle_packet_mmap(
  4665. handle,
  4666. callback,
  4667. user,
  4668. h.raw,
  4669. h.h1->tp_len,
  4670. h.h1->tp_mac,
  4671. h.h1->tp_snaplen,
  4672. h.h1->tp_sec,
  4673. h.h1->tp_usec,
  4674. 0,
  4675. 0,
  4676. 0);
  4677. if (ret == 1) {
  4678. pkts++;
  4679. handlep->packets_read++;
  4680. } else if (ret < 0) {
  4681. return ret;
  4682. }
  4683. /*
  4684. * Hand this block back to the kernel, and, if we're
  4685. * counting blocks that need to be filtered in userland
  4686. * after having been filtered by the kernel, count
  4687. * the one we've just processed.
  4688. */
  4689. h.h1->tp_status = TP_STATUS_KERNEL;
  4690. if (handlep->blocks_to_filter_in_userland > 0) {
  4691. handlep->blocks_to_filter_in_userland--;
  4692. if (handlep->blocks_to_filter_in_userland == 0) {
  4693. /*
  4694. * No more blocks need to be filtered
  4695. * in userland.
  4696. */
  4697. handlep->filter_in_userland = 0;
  4698. }
  4699. }
  4700. /* next block */
  4701. if (++handle->offset >= handle->cc)
  4702. handle->offset = 0;
  4703. /* check for break loop condition*/
  4704. if (handle->break_loop) {
  4705. handle->break_loop = 0;
  4706. return PCAP_ERROR_BREAK;
  4707. }
  4708. }
  4709. return pkts;
  4710. }
  4711. static int
  4712. pcap_read_linux_mmap_v1_64(pcap_t *handle, int max_packets, pcap_handler callback,
  4713. u_char *user)
  4714. {
  4715. struct pcap_linux *handlep = handle->priv;
  4716. union thdr h;
  4717. int pkts = 0;
  4718. int ret;
  4719. /* wait for frames availability.*/
  4720. h.raw = RING_GET_CURRENT_FRAME(handle);
  4721. if (h.h1_64->tp_status == TP_STATUS_KERNEL) {
  4722. /*
  4723. * The current frame is owned by the kernel; wait for
  4724. * a frame to be handed to us.
  4725. */
  4726. ret = pcap_wait_for_frames_mmap(handle);
  4727. if (ret) {
  4728. return ret;
  4729. }
  4730. }
  4731. /* non-positive values of max_packets are used to require all
  4732. * packets currently available in the ring */
  4733. while ((pkts < max_packets) || PACKET_COUNT_IS_UNLIMITED(max_packets)) {
  4734. /*
  4735. * Get the current ring buffer frame, and break if
  4736. * it's still owned by the kernel.
  4737. */
  4738. h.raw = RING_GET_CURRENT_FRAME(handle);
  4739. if (h.h1_64->tp_status == TP_STATUS_KERNEL)
  4740. break;
  4741. ret = pcap_handle_packet_mmap(
  4742. handle,
  4743. callback,
  4744. user,
  4745. h.raw,
  4746. h.h1_64->tp_len,
  4747. h.h1_64->tp_mac,
  4748. h.h1_64->tp_snaplen,
  4749. h.h1_64->tp_sec,
  4750. h.h1_64->tp_usec,
  4751. 0,
  4752. 0,
  4753. 0);
  4754. if (ret == 1) {
  4755. pkts++;
  4756. handlep->packets_read++;
  4757. } else if (ret < 0) {
  4758. return ret;
  4759. }
  4760. /*
  4761. * Hand this block back to the kernel, and, if we're
  4762. * counting blocks that need to be filtered in userland
  4763. * after having been filtered by the kernel, count
  4764. * the one we've just processed.
  4765. */
  4766. h.h1_64->tp_status = TP_STATUS_KERNEL;
  4767. if (handlep->blocks_to_filter_in_userland > 0) {
  4768. handlep->blocks_to_filter_in_userland--;
  4769. if (handlep->blocks_to_filter_in_userland == 0) {
  4770. /*
  4771. * No more blocks need to be filtered
  4772. * in userland.
  4773. */
  4774. handlep->filter_in_userland = 0;
  4775. }
  4776. }
  4777. /* next block */
  4778. if (++handle->offset >= handle->cc)
  4779. handle->offset = 0;
  4780. /* check for break loop condition*/
  4781. if (handle->break_loop) {
  4782. handle->break_loop = 0;
  4783. return PCAP_ERROR_BREAK;
  4784. }
  4785. }
  4786. return pkts;
  4787. }
  4788. #ifdef HAVE_TPACKET2
  4789. static int
  4790. pcap_read_linux_mmap_v2(pcap_t *handle, int max_packets, pcap_handler callback,
  4791. u_char *user)
  4792. {
  4793. struct pcap_linux *handlep = handle->priv;
  4794. union thdr h;
  4795. int pkts = 0;
  4796. int ret;
  4797. /* wait for frames availability.*/
  4798. h.raw = RING_GET_CURRENT_FRAME(handle);
  4799. if (h.h2->tp_status == TP_STATUS_KERNEL) {
  4800. /*
  4801. * The current frame is owned by the kernel; wait for
  4802. * a frame to be handed to us.
  4803. */
  4804. ret = pcap_wait_for_frames_mmap(handle);
  4805. if (ret) {
  4806. return ret;
  4807. }
  4808. }
  4809. /* non-positive values of max_packets are used to require all
  4810. * packets currently available in the ring */
  4811. while ((pkts < max_packets) || PACKET_COUNT_IS_UNLIMITED(max_packets)) {
  4812. /*
  4813. * Get the current ring buffer frame, and break if
  4814. * it's still owned by the kernel.
  4815. */
  4816. h.raw = RING_GET_CURRENT_FRAME(handle);
  4817. if (h.h2->tp_status == TP_STATUS_KERNEL)
  4818. break;
  4819. ret = pcap_handle_packet_mmap(
  4820. handle,
  4821. callback,
  4822. user,
  4823. h.raw,
  4824. h.h2->tp_len,
  4825. h.h2->tp_mac,
  4826. h.h2->tp_snaplen,
  4827. h.h2->tp_sec,
  4828. handle->opt.tstamp_precision == PCAP_TSTAMP_PRECISION_NANO ? h.h2->tp_nsec : h.h2->tp_nsec / 1000,
  4829. VLAN_VALID(h.h2, h.h2),
  4830. h.h2->tp_vlan_tci,
  4831. VLAN_TPID(h.h2, h.h2));
  4832. if (ret == 1) {
  4833. pkts++;
  4834. handlep->packets_read++;
  4835. } else if (ret < 0) {
  4836. return ret;
  4837. }
  4838. /*
  4839. * Hand this block back to the kernel, and, if we're
  4840. * counting blocks that need to be filtered in userland
  4841. * after having been filtered by the kernel, count
  4842. * the one we've just processed.
  4843. */
  4844. h.h2->tp_status = TP_STATUS_KERNEL;
  4845. if (handlep->blocks_to_filter_in_userland > 0) {
  4846. handlep->blocks_to_filter_in_userland--;
  4847. if (handlep->blocks_to_filter_in_userland == 0) {
  4848. /*
  4849. * No more blocks need to be filtered
  4850. * in userland.
  4851. */
  4852. handlep->filter_in_userland = 0;
  4853. }
  4854. }
  4855. /* next block */
  4856. if (++handle->offset >= handle->cc)
  4857. handle->offset = 0;
  4858. /* check for break loop condition*/
  4859. if (handle->break_loop) {
  4860. handle->break_loop = 0;
  4861. return PCAP_ERROR_BREAK;
  4862. }
  4863. }
  4864. return pkts;
  4865. }
  4866. #endif /* HAVE_TPACKET2 */
  4867. #ifdef HAVE_TPACKET3
  4868. static int
  4869. pcap_read_linux_mmap_v3(pcap_t *handle, int max_packets, pcap_handler callback,
  4870. u_char *user)
  4871. {
  4872. struct pcap_linux *handlep = handle->priv;
  4873. union thdr h;
  4874. int pkts = 0;
  4875. int ret;
  4876. again:
  4877. if (handlep->current_packet == NULL) {
  4878. /* wait for frames availability.*/
  4879. h.raw = RING_GET_CURRENT_FRAME(handle);
  4880. if (h.h3->hdr.bh1.block_status == TP_STATUS_KERNEL) {
  4881. /*
  4882. * The current frame is owned by the kernel; wait
  4883. * for a frame to be handed to us.
  4884. */
  4885. ret = pcap_wait_for_frames_mmap(handle);
  4886. if (ret) {
  4887. return ret;
  4888. }
  4889. }
  4890. }
  4891. h.raw = RING_GET_CURRENT_FRAME(handle);
  4892. if (h.h3->hdr.bh1.block_status == TP_STATUS_KERNEL) {
  4893. if (pkts == 0 && handlep->timeout == 0) {
  4894. /* Block until we see a packet. */
  4895. goto again;
  4896. }
  4897. return pkts;
  4898. }
  4899. /* non-positive values of max_packets are used to require all
  4900. * packets currently available in the ring */
  4901. while ((pkts < max_packets) || PACKET_COUNT_IS_UNLIMITED(max_packets)) {
  4902. int packets_to_read;
  4903. if (handlep->current_packet == NULL) {
  4904. h.raw = RING_GET_CURRENT_FRAME(handle);
  4905. if (h.h3->hdr.bh1.block_status == TP_STATUS_KERNEL)
  4906. break;
  4907. handlep->current_packet = h.raw + h.h3->hdr.bh1.offset_to_first_pkt;
  4908. handlep->packets_left = h.h3->hdr.bh1.num_pkts;
  4909. }
  4910. packets_to_read = handlep->packets_left;
  4911. if (!PACKET_COUNT_IS_UNLIMITED(max_packets) &&
  4912. packets_to_read > (max_packets - pkts)) {
  4913. /*
  4914. * We've been given a maximum number of packets
  4915. * to process, and there are more packets in
  4916. * this buffer than that. Only process enough
  4917. * of them to get us up to that maximum.
  4918. */
  4919. packets_to_read = max_packets - pkts;
  4920. }
  4921. while (packets_to_read-- && !handle->break_loop) {
  4922. struct tpacket3_hdr* tp3_hdr = (struct tpacket3_hdr*) handlep->current_packet;
  4923. ret = pcap_handle_packet_mmap(
  4924. handle,
  4925. callback,
  4926. user,
  4927. handlep->current_packet,
  4928. tp3_hdr->tp_len,
  4929. tp3_hdr->tp_mac,
  4930. tp3_hdr->tp_snaplen,
  4931. tp3_hdr->tp_sec,
  4932. handle->opt.tstamp_precision == PCAP_TSTAMP_PRECISION_NANO ? tp3_hdr->tp_nsec : tp3_hdr->tp_nsec / 1000,
  4933. VLAN_VALID(tp3_hdr, &tp3_hdr->hv1),
  4934. tp3_hdr->hv1.tp_vlan_tci,
  4935. VLAN_TPID(tp3_hdr, &tp3_hdr->hv1));
  4936. if (ret == 1) {
  4937. pkts++;
  4938. handlep->packets_read++;
  4939. } else if (ret < 0) {
  4940. handlep->current_packet = NULL;
  4941. return ret;
  4942. }
  4943. handlep->current_packet += tp3_hdr->tp_next_offset;
  4944. handlep->packets_left--;
  4945. }
  4946. if (handlep->packets_left <= 0) {
  4947. /*
  4948. * Hand this block back to the kernel, and, if
  4949. * we're counting blocks that need to be
  4950. * filtered in userland after having been
  4951. * filtered by the kernel, count the one we've
  4952. * just processed.
  4953. */
  4954. h.h3->hdr.bh1.block_status = TP_STATUS_KERNEL;
  4955. if (handlep->blocks_to_filter_in_userland > 0) {
  4956. handlep->blocks_to_filter_in_userland--;
  4957. if (handlep->blocks_to_filter_in_userland == 0) {
  4958. /*
  4959. * No more blocks need to be filtered
  4960. * in userland.
  4961. */
  4962. handlep->filter_in_userland = 0;
  4963. }
  4964. }
  4965. /* next block */
  4966. if (++handle->offset >= handle->cc)
  4967. handle->offset = 0;
  4968. handlep->current_packet = NULL;
  4969. }
  4970. /* check for break loop condition*/
  4971. if (handle->break_loop) {
  4972. handle->break_loop = 0;
  4973. return PCAP_ERROR_BREAK;
  4974. }
  4975. }
  4976. if (pkts == 0 && handlep->timeout == 0) {
  4977. /* Block until we see a packet. */
  4978. goto again;
  4979. }
  4980. return pkts;
  4981. }
  4982. #endif /* HAVE_TPACKET3 */
  4983. static int
  4984. pcap_setfilter_linux_mmap(pcap_t *handle, struct bpf_program *filter)
  4985. {
  4986. struct pcap_linux *handlep = handle->priv;
  4987. int n, offset;
  4988. int ret;
  4989. /*
  4990. * Don't rewrite "ret" instructions; we don't need to, as
  4991. * we're not reading packets with recvmsg(), and we don't
  4992. * want to, as, by not rewriting them, the kernel can avoid
  4993. * copying extra data.
  4994. */
  4995. ret = pcap_setfilter_linux_common(handle, filter, 1);
  4996. if (ret < 0)
  4997. return ret;
  4998. /*
  4999. * If we're filtering in userland, there's nothing to do;
  5000. * the new filter will be used for the next packet.
  5001. */
  5002. if (handlep->filter_in_userland)
  5003. return ret;
  5004. /*
  5005. * We're filtering in the kernel; the packets present in
  5006. * all blocks currently in the ring were already filtered
  5007. * by the old filter, and so will need to be filtered in
  5008. * userland by the new filter.
  5009. *
  5010. * Get an upper bound for the number of such blocks; first,
  5011. * walk the ring backward and count the free blocks.
  5012. */
  5013. offset = handle->offset;
  5014. if (--offset < 0)
  5015. offset = handle->cc - 1;
  5016. for (n=0; n < handle->cc; ++n) {
  5017. if (--offset < 0)
  5018. offset = handle->cc - 1;
  5019. if (pcap_get_ring_frame_status(handle, offset) != TP_STATUS_KERNEL)
  5020. break;
  5021. }
  5022. /*
  5023. * If we found free blocks, decrement the count of free
  5024. * blocks by 1, just in case we lost a race with another
  5025. * thread of control that was adding a packet while
  5026. * we were counting and that had run the filter before
  5027. * we changed it.
  5028. *
  5029. * XXX - could there be more than one block added in
  5030. * this fashion?
  5031. *
  5032. * XXX - is there a way to avoid that race, e.g. somehow
  5033. * wait for all packets that passed the old filter to
  5034. * be added to the ring?
  5035. */
  5036. if (n != 0)
  5037. n--;
  5038. /*
  5039. * Set the count of blocks worth of packets to filter
  5040. * in userland to the total number of blocks in the
  5041. * ring minus the number of free blocks we found, and
  5042. * turn on userland filtering. (The count of blocks
  5043. * worth of packets to filter in userland is guaranteed
  5044. * not to be zero - n, above, couldn't be set to a
  5045. * value > handle->cc, and if it were equal to
  5046. * handle->cc, it wouldn't be zero, and thus would
  5047. * be decremented to handle->cc - 1.)
  5048. */
  5049. handlep->blocks_to_filter_in_userland = handle->cc - n;
  5050. handlep->filter_in_userland = 1;
  5051. return ret;
  5052. }
  5053. #endif /* HAVE_PACKET_RING */
  5054. #ifdef HAVE_PF_PACKET_SOCKETS
  5055. /*
  5056. * Return the index of the given device name. Fill ebuf and return
  5057. * -1 on failure.
  5058. */
  5059. static int
  5060. iface_get_id(int fd, const char *device, char *ebuf)
  5061. {
  5062. struct ifreq ifr;
  5063. memset(&ifr, 0, sizeof(ifr));
  5064. strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
  5065. if (ioctl(fd, SIOCGIFINDEX, &ifr) == -1) {
  5066. pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
  5067. errno, "SIOCGIFINDEX");
  5068. return -1;
  5069. }
  5070. return ifr.ifr_ifindex;
  5071. }
  5072. /*
  5073. * Bind the socket associated with FD to the given device.
  5074. * Return 1 on success, 0 if we should try a SOCK_PACKET socket,
  5075. * or a PCAP_ERROR_ value on a hard error.
  5076. */
  5077. static int
  5078. iface_bind(int fd, int ifindex, char *ebuf, int protocol)
  5079. {
  5080. struct sockaddr_ll sll;
  5081. int err;
  5082. socklen_t errlen = sizeof(err);
  5083. memset(&sll, 0, sizeof(sll));
  5084. sll.sll_family = AF_PACKET;
  5085. sll.sll_ifindex = ifindex;
  5086. sll.sll_protocol = protocol;
  5087. if (bind(fd, (struct sockaddr *) &sll, sizeof(sll)) == -1) {
  5088. if (errno == ENETDOWN) {
  5089. /*
  5090. * Return a "network down" indication, so that
  5091. * the application can report that rather than
  5092. * saying we had a mysterious failure and
  5093. * suggest that they report a problem to the
  5094. * libpcap developers.
  5095. */
  5096. return PCAP_ERROR_IFACE_NOT_UP;
  5097. } else {
  5098. pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
  5099. errno, "bind");
  5100. return PCAP_ERROR;
  5101. }
  5102. }
  5103. /* Any pending errors, e.g., network is down? */
  5104. if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &errlen) == -1) {
  5105. pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
  5106. errno, "getsockopt");
  5107. return 0;
  5108. }
  5109. if (err == ENETDOWN) {
  5110. /*
  5111. * Return a "network down" indication, so that
  5112. * the application can report that rather than
  5113. * saying we had a mysterious failure and
  5114. * suggest that they report a problem to the
  5115. * libpcap developers.
  5116. */
  5117. return PCAP_ERROR_IFACE_NOT_UP;
  5118. } else if (err > 0) {
  5119. pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
  5120. err, "bind");
  5121. return 0;
  5122. }
  5123. return 1;
  5124. }
  5125. #ifdef IW_MODE_MONITOR
  5126. /*
  5127. * Check whether the device supports the Wireless Extensions.
  5128. * Returns 1 if it does, 0 if it doesn't, PCAP_ERROR_NO_SUCH_DEVICE
  5129. * if the device doesn't even exist.
  5130. */
  5131. static int
  5132. has_wext(int sock_fd, const char *device, char *ebuf)
  5133. {
  5134. struct iwreq ireq;
  5135. if (is_bonding_device(sock_fd, device))
  5136. return 0; /* bonding device, so don't even try */
  5137. strlcpy(ireq.ifr_ifrn.ifrn_name, device,
  5138. sizeof ireq.ifr_ifrn.ifrn_name);
  5139. if (ioctl(sock_fd, SIOCGIWNAME, &ireq) >= 0)
  5140. return 1; /* yes */
  5141. pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE, errno,
  5142. "%s: SIOCGIWNAME", device);
  5143. if (errno == ENODEV)
  5144. return PCAP_ERROR_NO_SUCH_DEVICE;
  5145. return 0;
  5146. }
  5147. /*
  5148. * Per me si va ne la citta dolente,
  5149. * Per me si va ne l'etterno dolore,
  5150. * ...
  5151. * Lasciate ogne speranza, voi ch'intrate.
  5152. *
  5153. * XXX - airmon-ng does special stuff with the Orinoco driver and the
  5154. * wlan-ng driver.
  5155. */
  5156. typedef enum {
  5157. MONITOR_WEXT,
  5158. MONITOR_HOSTAP,
  5159. MONITOR_PRISM,
  5160. MONITOR_PRISM54,
  5161. MONITOR_ACX100,
  5162. MONITOR_RT2500,
  5163. MONITOR_RT2570,
  5164. MONITOR_RT73,
  5165. MONITOR_RTL8XXX
  5166. } monitor_type;
  5167. /*
  5168. * Use the Wireless Extensions, if we have them, to try to turn monitor mode
  5169. * on if it's not already on.
  5170. *
  5171. * Returns 1 on success, 0 if we don't support the Wireless Extensions
  5172. * on this device, or a PCAP_ERROR_ value if we do support them but
  5173. * we weren't able to turn monitor mode on.
  5174. */
  5175. static int
  5176. enter_rfmon_mode_wext(pcap_t *handle, int sock_fd, const char *device)
  5177. {
  5178. /*
  5179. * XXX - at least some adapters require non-Wireless Extensions
  5180. * mechanisms to turn monitor mode on.
  5181. *
  5182. * Atheros cards might require that a separate "monitor virtual access
  5183. * point" be created, with later versions of the madwifi driver.
  5184. * airmon-ng does "wlanconfig ath create wlandev {if} wlanmode
  5185. * monitor -bssid", which apparently spits out a line "athN"
  5186. * where "athN" is the monitor mode device. To leave monitor
  5187. * mode, it destroys the monitor mode device.
  5188. *
  5189. * Some Intel Centrino adapters might require private ioctls to get
  5190. * radio headers; the ipw2200 and ipw3945 drivers allow you to
  5191. * configure a separate "rtapN" interface to capture in monitor
  5192. * mode without preventing the adapter from operating normally.
  5193. * (airmon-ng doesn't appear to use that, though.)
  5194. *
  5195. * It would be Truly Wonderful if mac80211 and nl80211 cleaned this
  5196. * up, and if all drivers were converted to mac80211 drivers.
  5197. *
  5198. * If interface {if} is a mac80211 driver, the file
  5199. * /sys/class/net/{if}/phy80211 is a symlink to
  5200. * /sys/class/ieee80211/{phydev}, for some {phydev}.
  5201. *
  5202. * On Fedora 9, with a 2.6.26.3-29 kernel, my Zydas stick, at
  5203. * least, has a "wmaster0" device and a "wlan0" device; the
  5204. * latter is the one with the IP address. Both show up in
  5205. * "tcpdump -D" output. Capturing on the wmaster0 device
  5206. * captures with 802.11 headers.
  5207. *
  5208. * airmon-ng searches through /sys/class/net for devices named
  5209. * monN, starting with mon0; as soon as one *doesn't* exist,
  5210. * it chooses that as the monitor device name. If the "iw"
  5211. * command exists, it does "iw dev {if} interface add {monif}
  5212. * type monitor", where {monif} is the monitor device. It
  5213. * then (sigh) sleeps .1 second, and then configures the
  5214. * device up. Otherwise, if /sys/class/ieee80211/{phydev}/add_iface
  5215. * is a file, it writes {mondev}, without a newline, to that file,
  5216. * and again (sigh) sleeps .1 second, and then iwconfig's that
  5217. * device into monitor mode and configures it up. Otherwise,
  5218. * you can't do monitor mode.
  5219. *
  5220. * All these devices are "glued" together by having the
  5221. * /sys/class/net/{device}/phy80211 links pointing to the same
  5222. * place, so, given a wmaster, wlan, or mon device, you can
  5223. * find the other devices by looking for devices with
  5224. * the same phy80211 link.
  5225. *
  5226. * To turn monitor mode off, delete the monitor interface,
  5227. * either with "iw dev {monif} interface del" or by sending
  5228. * {monif}, with no NL, down /sys/class/ieee80211/{phydev}/remove_iface
  5229. *
  5230. * Note: if you try to create a monitor device named "monN", and
  5231. * there's already a "monN" device, it fails, as least with
  5232. * the netlink interface (which is what iw uses), with a return
  5233. * value of -ENFILE. (Return values are negative errnos.) We
  5234. * could probably use that to find an unused device.
  5235. */
  5236. struct pcap_linux *handlep = handle->priv;
  5237. int err;
  5238. struct iwreq ireq;
  5239. struct iw_priv_args *priv;
  5240. monitor_type montype;
  5241. int i;
  5242. __u32 cmd;
  5243. struct ifreq ifr;
  5244. int oldflags;
  5245. int args[2];
  5246. int channel;
  5247. /*
  5248. * Does this device *support* the Wireless Extensions?
  5249. */
  5250. err = has_wext(sock_fd, device, handle->errbuf);
  5251. if (err <= 0)
  5252. return err; /* either it doesn't or the device doesn't even exist */
  5253. /*
  5254. * Start out assuming we have no private extensions to control
  5255. * radio metadata.
  5256. */
  5257. montype = MONITOR_WEXT;
  5258. cmd = 0;
  5259. /*
  5260. * Try to get all the Wireless Extensions private ioctls
  5261. * supported by this device.
  5262. *
  5263. * First, get the size of the buffer we need, by supplying no
  5264. * buffer and a length of 0. If the device supports private
  5265. * ioctls, it should return E2BIG, with ireq.u.data.length set
  5266. * to the length we need. If it doesn't support them, it should
  5267. * return EOPNOTSUPP.
  5268. */
  5269. memset(&ireq, 0, sizeof ireq);
  5270. strlcpy(ireq.ifr_ifrn.ifrn_name, device,
  5271. sizeof ireq.ifr_ifrn.ifrn_name);
  5272. ireq.u.data.pointer = (void *)args;
  5273. ireq.u.data.length = 0;
  5274. ireq.u.data.flags = 0;
  5275. if (ioctl(sock_fd, SIOCGIWPRIV, &ireq) != -1) {
  5276. pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  5277. "%s: SIOCGIWPRIV with a zero-length buffer didn't fail!",
  5278. device);
  5279. return PCAP_ERROR;
  5280. }
  5281. if (errno != EOPNOTSUPP) {
  5282. /*
  5283. * OK, it's not as if there are no private ioctls.
  5284. */
  5285. if (errno != E2BIG) {
  5286. /*
  5287. * Failed.
  5288. */
  5289. pcap_fmt_errmsg_for_errno(handle->errbuf,
  5290. PCAP_ERRBUF_SIZE, errno, "%s: SIOCGIWPRIV", device);
  5291. return PCAP_ERROR;
  5292. }
  5293. /*
  5294. * OK, try to get the list of private ioctls.
  5295. */
  5296. priv = malloc(ireq.u.data.length * sizeof (struct iw_priv_args));
  5297. if (priv == NULL) {
  5298. pcap_fmt_errmsg_for_errno(handle->errbuf,
  5299. PCAP_ERRBUF_SIZE, errno, "malloc");
  5300. return PCAP_ERROR;
  5301. }
  5302. ireq.u.data.pointer = (void *)priv;
  5303. if (ioctl(sock_fd, SIOCGIWPRIV, &ireq) == -1) {
  5304. pcap_fmt_errmsg_for_errno(handle->errbuf,
  5305. PCAP_ERRBUF_SIZE, errno, "%s: SIOCGIWPRIV", device);
  5306. free(priv);
  5307. return PCAP_ERROR;
  5308. }
  5309. /*
  5310. * Look for private ioctls to turn monitor mode on or, if
  5311. * monitor mode is on, to set the header type.
  5312. */
  5313. for (i = 0; i < ireq.u.data.length; i++) {
  5314. if (strcmp(priv[i].name, "monitor_type") == 0) {
  5315. /*
  5316. * Hostap driver, use this one.
  5317. * Set monitor mode first.
  5318. * You can set it to 0 to get DLT_IEEE80211,
  5319. * 1 to get DLT_PRISM, 2 to get
  5320. * DLT_IEEE80211_RADIO_AVS, and, with more
  5321. * recent versions of the driver, 3 to get
  5322. * DLT_IEEE80211_RADIO.
  5323. */
  5324. if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
  5325. break;
  5326. if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
  5327. break;
  5328. if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
  5329. break;
  5330. montype = MONITOR_HOSTAP;
  5331. cmd = priv[i].cmd;
  5332. break;
  5333. }
  5334. if (strcmp(priv[i].name, "set_prismhdr") == 0) {
  5335. /*
  5336. * Prism54 driver, use this one.
  5337. * Set monitor mode first.
  5338. * You can set it to 2 to get DLT_IEEE80211
  5339. * or 3 or get DLT_PRISM.
  5340. */
  5341. if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
  5342. break;
  5343. if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
  5344. break;
  5345. if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
  5346. break;
  5347. montype = MONITOR_PRISM54;
  5348. cmd = priv[i].cmd;
  5349. break;
  5350. }
  5351. if (strcmp(priv[i].name, "forceprismheader") == 0) {
  5352. /*
  5353. * RT2570 driver, use this one.
  5354. * Do this after turning monitor mode on.
  5355. * You can set it to 1 to get DLT_PRISM or 2
  5356. * to get DLT_IEEE80211.
  5357. */
  5358. if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
  5359. break;
  5360. if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
  5361. break;
  5362. if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
  5363. break;
  5364. montype = MONITOR_RT2570;
  5365. cmd = priv[i].cmd;
  5366. break;
  5367. }
  5368. if (strcmp(priv[i].name, "forceprism") == 0) {
  5369. /*
  5370. * RT73 driver, use this one.
  5371. * Do this after turning monitor mode on.
  5372. * Its argument is a *string*; you can
  5373. * set it to "1" to get DLT_PRISM or "2"
  5374. * to get DLT_IEEE80211.
  5375. */
  5376. if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_CHAR)
  5377. break;
  5378. if (priv[i].set_args & IW_PRIV_SIZE_FIXED)
  5379. break;
  5380. montype = MONITOR_RT73;
  5381. cmd = priv[i].cmd;
  5382. break;
  5383. }
  5384. if (strcmp(priv[i].name, "prismhdr") == 0) {
  5385. /*
  5386. * One of the RTL8xxx drivers, use this one.
  5387. * It can only be done after monitor mode
  5388. * has been turned on. You can set it to 1
  5389. * to get DLT_PRISM or 0 to get DLT_IEEE80211.
  5390. */
  5391. if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
  5392. break;
  5393. if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
  5394. break;
  5395. if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 1)
  5396. break;
  5397. montype = MONITOR_RTL8XXX;
  5398. cmd = priv[i].cmd;
  5399. break;
  5400. }
  5401. if (strcmp(priv[i].name, "rfmontx") == 0) {
  5402. /*
  5403. * RT2500 or RT61 driver, use this one.
  5404. * It has one one-byte parameter; set
  5405. * u.data.length to 1 and u.data.pointer to
  5406. * point to the parameter.
  5407. * It doesn't itself turn monitor mode on.
  5408. * You can set it to 1 to allow transmitting
  5409. * in monitor mode(?) and get DLT_IEEE80211,
  5410. * or set it to 0 to disallow transmitting in
  5411. * monitor mode(?) and get DLT_PRISM.
  5412. */
  5413. if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
  5414. break;
  5415. if ((priv[i].set_args & IW_PRIV_SIZE_MASK) != 2)
  5416. break;
  5417. montype = MONITOR_RT2500;
  5418. cmd = priv[i].cmd;
  5419. break;
  5420. }
  5421. if (strcmp(priv[i].name, "monitor") == 0) {
  5422. /*
  5423. * Either ACX100 or hostap, use this one.
  5424. * It turns monitor mode on.
  5425. * If it takes two arguments, it's ACX100;
  5426. * the first argument is 1 for DLT_PRISM
  5427. * or 2 for DLT_IEEE80211, and the second
  5428. * argument is the channel on which to
  5429. * run. If it takes one argument, it's
  5430. * HostAP, and the argument is 2 for
  5431. * DLT_IEEE80211 and 3 for DLT_PRISM.
  5432. *
  5433. * If we see this, we don't quit, as this
  5434. * might be a version of the hostap driver
  5435. * that also supports "monitor_type".
  5436. */
  5437. if ((priv[i].set_args & IW_PRIV_TYPE_MASK) != IW_PRIV_TYPE_INT)
  5438. break;
  5439. if (!(priv[i].set_args & IW_PRIV_SIZE_FIXED))
  5440. break;
  5441. switch (priv[i].set_args & IW_PRIV_SIZE_MASK) {
  5442. case 1:
  5443. montype = MONITOR_PRISM;
  5444. cmd = priv[i].cmd;
  5445. break;
  5446. case 2:
  5447. montype = MONITOR_ACX100;
  5448. cmd = priv[i].cmd;
  5449. break;
  5450. default:
  5451. break;
  5452. }
  5453. }
  5454. }
  5455. free(priv);
  5456. }
  5457. /*
  5458. * XXX - ipw3945? islism?
  5459. */
  5460. /*
  5461. * Get the old mode.
  5462. */
  5463. strlcpy(ireq.ifr_ifrn.ifrn_name, device,
  5464. sizeof ireq.ifr_ifrn.ifrn_name);
  5465. if (ioctl(sock_fd, SIOCGIWMODE, &ireq) == -1) {
  5466. /*
  5467. * We probably won't be able to set the mode, either.
  5468. */
  5469. return PCAP_ERROR_RFMON_NOTSUP;
  5470. }
  5471. /*
  5472. * Is it currently in monitor mode?
  5473. */
  5474. if (ireq.u.mode == IW_MODE_MONITOR) {
  5475. /*
  5476. * Yes. Just leave things as they are.
  5477. * We don't offer multiple link-layer types, as
  5478. * changing the link-layer type out from under
  5479. * somebody else capturing in monitor mode would
  5480. * be considered rude.
  5481. */
  5482. return 1;
  5483. }
  5484. /*
  5485. * No. We have to put the adapter into rfmon mode.
  5486. */
  5487. /*
  5488. * If we haven't already done so, arrange to have
  5489. * "pcap_close_all()" called when we exit.
  5490. */
  5491. if (!pcap_do_addexit(handle)) {
  5492. /*
  5493. * "atexit()" failed; don't put the interface
  5494. * in rfmon mode, just give up.
  5495. */
  5496. return PCAP_ERROR_RFMON_NOTSUP;
  5497. }
  5498. /*
  5499. * Save the old mode.
  5500. */
  5501. handlep->oldmode = ireq.u.mode;
  5502. /*
  5503. * Put the adapter in rfmon mode. How we do this depends
  5504. * on whether we have a special private ioctl or not.
  5505. */
  5506. if (montype == MONITOR_PRISM) {
  5507. /*
  5508. * We have the "monitor" private ioctl, but none of
  5509. * the other private ioctls. Use this, and select
  5510. * the Prism header.
  5511. *
  5512. * If it fails, just fall back on SIOCSIWMODE.
  5513. */
  5514. memset(&ireq, 0, sizeof ireq);
  5515. strlcpy(ireq.ifr_ifrn.ifrn_name, device,
  5516. sizeof ireq.ifr_ifrn.ifrn_name);
  5517. ireq.u.data.length = 1; /* 1 argument */
  5518. args[0] = 3; /* request Prism header */
  5519. memcpy(ireq.u.name, args, sizeof (int));
  5520. if (ioctl(sock_fd, cmd, &ireq) != -1) {
  5521. /*
  5522. * Success.
  5523. * Note that we have to put the old mode back
  5524. * when we close the device.
  5525. */
  5526. handlep->must_do_on_close |= MUST_CLEAR_RFMON;
  5527. /*
  5528. * Add this to the list of pcaps to close
  5529. * when we exit.
  5530. */
  5531. pcap_add_to_pcaps_to_close(handle);
  5532. return 1;
  5533. }
  5534. /*
  5535. * Failure. Fall back on SIOCSIWMODE.
  5536. */
  5537. }
  5538. /*
  5539. * First, take the interface down if it's up; otherwise, we
  5540. * might get EBUSY.
  5541. */
  5542. memset(&ifr, 0, sizeof(ifr));
  5543. strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
  5544. if (ioctl(sock_fd, SIOCGIFFLAGS, &ifr) == -1) {
  5545. pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
  5546. errno, "%s: Can't get flags", device);
  5547. return PCAP_ERROR;
  5548. }
  5549. oldflags = 0;
  5550. if (ifr.ifr_flags & IFF_UP) {
  5551. oldflags = ifr.ifr_flags;
  5552. ifr.ifr_flags &= ~IFF_UP;
  5553. if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
  5554. pcap_fmt_errmsg_for_errno(handle->errbuf,
  5555. PCAP_ERRBUF_SIZE, errno, "%s: Can't set flags",
  5556. device);
  5557. return PCAP_ERROR;
  5558. }
  5559. }
  5560. /*
  5561. * Then turn monitor mode on.
  5562. */
  5563. strlcpy(ireq.ifr_ifrn.ifrn_name, device,
  5564. sizeof ireq.ifr_ifrn.ifrn_name);
  5565. ireq.u.mode = IW_MODE_MONITOR;
  5566. if (ioctl(sock_fd, SIOCSIWMODE, &ireq) == -1) {
  5567. /*
  5568. * Scientist, you've failed.
  5569. * Bring the interface back up if we shut it down.
  5570. */
  5571. ifr.ifr_flags = oldflags;
  5572. if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
  5573. pcap_fmt_errmsg_for_errno(handle->errbuf,
  5574. PCAP_ERRBUF_SIZE, errno, "%s: Can't set flags",
  5575. device);
  5576. return PCAP_ERROR;
  5577. }
  5578. return PCAP_ERROR_RFMON_NOTSUP;
  5579. }
  5580. /*
  5581. * XXX - airmon-ng does "iwconfig {if} key off" after setting
  5582. * monitor mode and setting the channel, and then does
  5583. * "iwconfig up".
  5584. */
  5585. /*
  5586. * Now select the appropriate radio header.
  5587. */
  5588. switch (montype) {
  5589. case MONITOR_WEXT:
  5590. /*
  5591. * We don't have any private ioctl to set the header.
  5592. */
  5593. break;
  5594. case MONITOR_HOSTAP:
  5595. /*
  5596. * Try to select the radiotap header.
  5597. */
  5598. memset(&ireq, 0, sizeof ireq);
  5599. strlcpy(ireq.ifr_ifrn.ifrn_name, device,
  5600. sizeof ireq.ifr_ifrn.ifrn_name);
  5601. args[0] = 3; /* request radiotap header */
  5602. memcpy(ireq.u.name, args, sizeof (int));
  5603. if (ioctl(sock_fd, cmd, &ireq) != -1)
  5604. break; /* success */
  5605. /*
  5606. * That failed. Try to select the AVS header.
  5607. */
  5608. memset(&ireq, 0, sizeof ireq);
  5609. strlcpy(ireq.ifr_ifrn.ifrn_name, device,
  5610. sizeof ireq.ifr_ifrn.ifrn_name);
  5611. args[0] = 2; /* request AVS header */
  5612. memcpy(ireq.u.name, args, sizeof (int));
  5613. if (ioctl(sock_fd, cmd, &ireq) != -1)
  5614. break; /* success */
  5615. /*
  5616. * That failed. Try to select the Prism header.
  5617. */
  5618. memset(&ireq, 0, sizeof ireq);
  5619. strlcpy(ireq.ifr_ifrn.ifrn_name, device,
  5620. sizeof ireq.ifr_ifrn.ifrn_name);
  5621. args[0] = 1; /* request Prism header */
  5622. memcpy(ireq.u.name, args, sizeof (int));
  5623. ioctl(sock_fd, cmd, &ireq);
  5624. break;
  5625. case MONITOR_PRISM:
  5626. /*
  5627. * The private ioctl failed.
  5628. */
  5629. break;
  5630. case MONITOR_PRISM54:
  5631. /*
  5632. * Select the Prism header.
  5633. */
  5634. memset(&ireq, 0, sizeof ireq);
  5635. strlcpy(ireq.ifr_ifrn.ifrn_name, device,
  5636. sizeof ireq.ifr_ifrn.ifrn_name);
  5637. args[0] = 3; /* request Prism header */
  5638. memcpy(ireq.u.name, args, sizeof (int));
  5639. ioctl(sock_fd, cmd, &ireq);
  5640. break;
  5641. case MONITOR_ACX100:
  5642. /*
  5643. * Get the current channel.
  5644. */
  5645. memset(&ireq, 0, sizeof ireq);
  5646. strlcpy(ireq.ifr_ifrn.ifrn_name, device,
  5647. sizeof ireq.ifr_ifrn.ifrn_name);
  5648. if (ioctl(sock_fd, SIOCGIWFREQ, &ireq) == -1) {
  5649. pcap_fmt_errmsg_for_errno(handle->errbuf,
  5650. PCAP_ERRBUF_SIZE, errno, "%s: SIOCGIWFREQ", device);
  5651. return PCAP_ERROR;
  5652. }
  5653. channel = ireq.u.freq.m;
  5654. /*
  5655. * Select the Prism header, and set the channel to the
  5656. * current value.
  5657. */
  5658. memset(&ireq, 0, sizeof ireq);
  5659. strlcpy(ireq.ifr_ifrn.ifrn_name, device,
  5660. sizeof ireq.ifr_ifrn.ifrn_name);
  5661. args[0] = 1; /* request Prism header */
  5662. args[1] = channel; /* set channel */
  5663. memcpy(ireq.u.name, args, 2*sizeof (int));
  5664. ioctl(sock_fd, cmd, &ireq);
  5665. break;
  5666. case MONITOR_RT2500:
  5667. /*
  5668. * Disallow transmission - that turns on the
  5669. * Prism header.
  5670. */
  5671. memset(&ireq, 0, sizeof ireq);
  5672. strlcpy(ireq.ifr_ifrn.ifrn_name, device,
  5673. sizeof ireq.ifr_ifrn.ifrn_name);
  5674. args[0] = 0; /* disallow transmitting */
  5675. memcpy(ireq.u.name, args, sizeof (int));
  5676. ioctl(sock_fd, cmd, &ireq);
  5677. break;
  5678. case MONITOR_RT2570:
  5679. /*
  5680. * Force the Prism header.
  5681. */
  5682. memset(&ireq, 0, sizeof ireq);
  5683. strlcpy(ireq.ifr_ifrn.ifrn_name, device,
  5684. sizeof ireq.ifr_ifrn.ifrn_name);
  5685. args[0] = 1; /* request Prism header */
  5686. memcpy(ireq.u.name, args, sizeof (int));
  5687. ioctl(sock_fd, cmd, &ireq);
  5688. break;
  5689. case MONITOR_RT73:
  5690. /*
  5691. * Force the Prism header.
  5692. */
  5693. memset(&ireq, 0, sizeof ireq);
  5694. strlcpy(ireq.ifr_ifrn.ifrn_name, device,
  5695. sizeof ireq.ifr_ifrn.ifrn_name);
  5696. ireq.u.data.length = 1; /* 1 argument */
  5697. ireq.u.data.pointer = "1";
  5698. ireq.u.data.flags = 0;
  5699. ioctl(sock_fd, cmd, &ireq);
  5700. break;
  5701. case MONITOR_RTL8XXX:
  5702. /*
  5703. * Force the Prism header.
  5704. */
  5705. memset(&ireq, 0, sizeof ireq);
  5706. strlcpy(ireq.ifr_ifrn.ifrn_name, device,
  5707. sizeof ireq.ifr_ifrn.ifrn_name);
  5708. args[0] = 1; /* request Prism header */
  5709. memcpy(ireq.u.name, args, sizeof (int));
  5710. ioctl(sock_fd, cmd, &ireq);
  5711. break;
  5712. }
  5713. /*
  5714. * Now bring the interface back up if we brought it down.
  5715. */
  5716. if (oldflags != 0) {
  5717. ifr.ifr_flags = oldflags;
  5718. if (ioctl(sock_fd, SIOCSIFFLAGS, &ifr) == -1) {
  5719. pcap_fmt_errmsg_for_errno(handle->errbuf,
  5720. PCAP_ERRBUF_SIZE, errno, "%s: Can't set flags",
  5721. device);
  5722. /*
  5723. * At least try to restore the old mode on the
  5724. * interface.
  5725. */
  5726. if (ioctl(handle->fd, SIOCSIWMODE, &ireq) == -1) {
  5727. /*
  5728. * Scientist, you've failed.
  5729. */
  5730. fprintf(stderr,
  5731. "Can't restore interface wireless mode (SIOCSIWMODE failed: %s).\n"
  5732. "Please adjust manually.\n",
  5733. strerror(errno));
  5734. }
  5735. return PCAP_ERROR;
  5736. }
  5737. }
  5738. /*
  5739. * Note that we have to put the old mode back when we
  5740. * close the device.
  5741. */
  5742. handlep->must_do_on_close |= MUST_CLEAR_RFMON;
  5743. /*
  5744. * Add this to the list of pcaps to close when we exit.
  5745. */
  5746. pcap_add_to_pcaps_to_close(handle);
  5747. return 1;
  5748. }
  5749. #endif /* IW_MODE_MONITOR */
  5750. /*
  5751. * Try various mechanisms to enter monitor mode.
  5752. */
  5753. static int
  5754. enter_rfmon_mode(pcap_t *handle, int sock_fd, const char *device)
  5755. {
  5756. #if defined(HAVE_LIBNL) || defined(IW_MODE_MONITOR)
  5757. int ret;
  5758. #endif
  5759. #ifdef HAVE_LIBNL
  5760. ret = enter_rfmon_mode_mac80211(handle, sock_fd, device);
  5761. if (ret < 0)
  5762. return ret; /* error attempting to do so */
  5763. if (ret == 1)
  5764. return 1; /* success */
  5765. #endif /* HAVE_LIBNL */
  5766. #ifdef IW_MODE_MONITOR
  5767. ret = enter_rfmon_mode_wext(handle, sock_fd, device);
  5768. if (ret < 0)
  5769. return ret; /* error attempting to do so */
  5770. if (ret == 1)
  5771. return 1; /* success */
  5772. #endif /* IW_MODE_MONITOR */
  5773. /*
  5774. * Either none of the mechanisms we know about work or none
  5775. * of those mechanisms are available, so we can't do monitor
  5776. * mode.
  5777. */
  5778. return 0;
  5779. }
  5780. #if defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP)
  5781. /*
  5782. * Map SOF_TIMESTAMPING_ values to PCAP_TSTAMP_ values.
  5783. */
  5784. static const struct {
  5785. int soft_timestamping_val;
  5786. int pcap_tstamp_val;
  5787. } sof_ts_type_map[3] = {
  5788. { SOF_TIMESTAMPING_SOFTWARE, PCAP_TSTAMP_HOST },
  5789. { SOF_TIMESTAMPING_SYS_HARDWARE, PCAP_TSTAMP_ADAPTER },
  5790. { SOF_TIMESTAMPING_RAW_HARDWARE, PCAP_TSTAMP_ADAPTER_UNSYNCED }
  5791. };
  5792. #define NUM_SOF_TIMESTAMPING_TYPES (sizeof sof_ts_type_map / sizeof sof_ts_type_map[0])
  5793. /*
  5794. * Set the list of time stamping types to include all types.
  5795. */
  5796. static void
  5797. iface_set_all_ts_types(pcap_t *handle)
  5798. {
  5799. u_int i;
  5800. handle->tstamp_type_count = NUM_SOF_TIMESTAMPING_TYPES;
  5801. handle->tstamp_type_list = malloc(NUM_SOF_TIMESTAMPING_TYPES * sizeof(u_int));
  5802. for (i = 0; i < NUM_SOF_TIMESTAMPING_TYPES; i++)
  5803. handle->tstamp_type_list[i] = sof_ts_type_map[i].pcap_tstamp_val;
  5804. }
  5805. #ifdef ETHTOOL_GET_TS_INFO
  5806. /*
  5807. * Get a list of time stamping capabilities.
  5808. */
  5809. static int
  5810. iface_ethtool_get_ts_info(const char *device, pcap_t *handle, char *ebuf)
  5811. {
  5812. int fd;
  5813. struct ifreq ifr;
  5814. struct ethtool_ts_info info;
  5815. int num_ts_types;
  5816. u_int i, j;
  5817. /*
  5818. * This doesn't apply to the "any" device; you can't say "turn on
  5819. * hardware time stamping for all devices that exist now and arrange
  5820. * that it be turned on for any device that appears in the future",
  5821. * and not all devices even necessarily *support* hardware time
  5822. * stamping, so don't report any time stamp types.
  5823. */
  5824. if (strcmp(device, "any") == 0) {
  5825. handle->tstamp_type_list = NULL;
  5826. return 0;
  5827. }
  5828. /*
  5829. * Create a socket from which to fetch time stamping capabilities.
  5830. */
  5831. fd = socket(PF_UNIX, SOCK_RAW, 0);
  5832. if (fd < 0) {
  5833. pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
  5834. errno, "socket for SIOCETHTOOL(ETHTOOL_GET_TS_INFO)");
  5835. return -1;
  5836. }
  5837. memset(&ifr, 0, sizeof(ifr));
  5838. strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
  5839. memset(&info, 0, sizeof(info));
  5840. info.cmd = ETHTOOL_GET_TS_INFO;
  5841. ifr.ifr_data = (caddr_t)&info;
  5842. if (ioctl(fd, SIOCETHTOOL, &ifr) == -1) {
  5843. int save_errno = errno;
  5844. close(fd);
  5845. switch (save_errno) {
  5846. case EOPNOTSUPP:
  5847. case EINVAL:
  5848. /*
  5849. * OK, this OS version or driver doesn't support
  5850. * asking for the time stamping types, so let's
  5851. * just return all the possible types.
  5852. */
  5853. iface_set_all_ts_types(handle);
  5854. return 0;
  5855. case ENODEV:
  5856. /*
  5857. * OK, no such device.
  5858. * The user will find that out when they try to
  5859. * activate the device; just return an empty
  5860. * list of time stamp types.
  5861. */
  5862. handle->tstamp_type_list = NULL;
  5863. return 0;
  5864. default:
  5865. /*
  5866. * Other error.
  5867. */
  5868. pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
  5869. save_errno,
  5870. "%s: SIOCETHTOOL(ETHTOOL_GET_TS_INFO) ioctl failed",
  5871. device);
  5872. return -1;
  5873. }
  5874. }
  5875. close(fd);
  5876. /*
  5877. * Do we support hardware time stamping of *all* packets?
  5878. */
  5879. if (!(info.rx_filters & (1 << HWTSTAMP_FILTER_ALL))) {
  5880. /*
  5881. * No, so don't report any time stamp types.
  5882. *
  5883. * XXX - some devices either don't report
  5884. * HWTSTAMP_FILTER_ALL when they do support it, or
  5885. * report HWTSTAMP_FILTER_ALL but map it to only
  5886. * time stamping a few PTP packets. See
  5887. * http://marc.info/?l=linux-netdev&m=146318183529571&w=2
  5888. */
  5889. handle->tstamp_type_list = NULL;
  5890. return 0;
  5891. }
  5892. num_ts_types = 0;
  5893. for (i = 0; i < NUM_SOF_TIMESTAMPING_TYPES; i++) {
  5894. if (info.so_timestamping & sof_ts_type_map[i].soft_timestamping_val)
  5895. num_ts_types++;
  5896. }
  5897. handle->tstamp_type_count = num_ts_types;
  5898. if (num_ts_types != 0) {
  5899. handle->tstamp_type_list = malloc(num_ts_types * sizeof(u_int));
  5900. for (i = 0, j = 0; i < NUM_SOF_TIMESTAMPING_TYPES; i++) {
  5901. if (info.so_timestamping & sof_ts_type_map[i].soft_timestamping_val) {
  5902. handle->tstamp_type_list[j] = sof_ts_type_map[i].pcap_tstamp_val;
  5903. j++;
  5904. }
  5905. }
  5906. } else
  5907. handle->tstamp_type_list = NULL;
  5908. return 0;
  5909. }
  5910. #else /* ETHTOOL_GET_TS_INFO */
  5911. static int
  5912. iface_ethtool_get_ts_info(const char *device, pcap_t *handle, char *ebuf _U_)
  5913. {
  5914. /*
  5915. * This doesn't apply to the "any" device; you can't say "turn on
  5916. * hardware time stamping for all devices that exist now and arrange
  5917. * that it be turned on for any device that appears in the future",
  5918. * and not all devices even necessarily *support* hardware time
  5919. * stamping, so don't report any time stamp types.
  5920. */
  5921. if (strcmp(device, "any") == 0) {
  5922. handle->tstamp_type_list = NULL;
  5923. return 0;
  5924. }
  5925. /*
  5926. * We don't have an ioctl to use to ask what's supported,
  5927. * so say we support everything.
  5928. */
  5929. iface_set_all_ts_types(handle);
  5930. return 0;
  5931. }
  5932. #endif /* ETHTOOL_GET_TS_INFO */
  5933. #endif /* defined(HAVE_LINUX_NET_TSTAMP_H) && defined(PACKET_TIMESTAMP) */
  5934. #ifdef HAVE_PACKET_RING
  5935. /*
  5936. * Find out if we have any form of fragmentation/reassembly offloading.
  5937. *
  5938. * We do so using SIOCETHTOOL checking for various types of offloading;
  5939. * if SIOCETHTOOL isn't defined, or we don't have any #defines for any
  5940. * of the types of offloading, there's nothing we can do to check, so
  5941. * we just say "no, we don't".
  5942. */
  5943. #if defined(SIOCETHTOOL) && (defined(ETHTOOL_GTSO) || defined(ETHTOOL_GUFO) || defined(ETHTOOL_GGSO) || defined(ETHTOOL_GFLAGS) || defined(ETHTOOL_GGRO))
  5944. static int
  5945. iface_ethtool_flag_ioctl(pcap_t *handle, int cmd, const char *cmdname)
  5946. {
  5947. struct ifreq ifr;
  5948. struct ethtool_value eval;
  5949. memset(&ifr, 0, sizeof(ifr));
  5950. strlcpy(ifr.ifr_name, handle->opt.device, sizeof(ifr.ifr_name));
  5951. eval.cmd = cmd;
  5952. eval.data = 0;
  5953. ifr.ifr_data = (caddr_t)&eval;
  5954. if (ioctl(handle->fd, SIOCETHTOOL, &ifr) == -1) {
  5955. if (errno == EOPNOTSUPP || errno == EINVAL) {
  5956. /*
  5957. * OK, let's just return 0, which, in our
  5958. * case, either means "no, what we're asking
  5959. * about is not enabled" or "all the flags
  5960. * are clear (i.e., nothing is enabled)".
  5961. */
  5962. return 0;
  5963. }
  5964. pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
  5965. errno, "%s: SIOCETHTOOL(%s) ioctl failed",
  5966. handle->opt.device, cmdname);
  5967. return -1;
  5968. }
  5969. return eval.data;
  5970. }
  5971. static int
  5972. iface_get_offload(pcap_t *handle)
  5973. {
  5974. int ret;
  5975. #ifdef ETHTOOL_GTSO
  5976. ret = iface_ethtool_flag_ioctl(handle, ETHTOOL_GTSO, "ETHTOOL_GTSO");
  5977. if (ret == -1)
  5978. return -1;
  5979. if (ret)
  5980. return 1; /* TCP segmentation offloading on */
  5981. #endif
  5982. #ifdef ETHTOOL_GUFO
  5983. ret = iface_ethtool_flag_ioctl(handle, ETHTOOL_GUFO, "ETHTOOL_GUFO");
  5984. if (ret == -1)
  5985. return -1;
  5986. if (ret)
  5987. return 1; /* UDP fragmentation offloading on */
  5988. #endif
  5989. #ifdef ETHTOOL_GGSO
  5990. /*
  5991. * XXX - will this cause large unsegmented packets to be
  5992. * handed to PF_PACKET sockets on transmission? If not,
  5993. * this need not be checked.
  5994. */
  5995. ret = iface_ethtool_flag_ioctl(handle, ETHTOOL_GGSO, "ETHTOOL_GGSO");
  5996. if (ret == -1)
  5997. return -1;
  5998. if (ret)
  5999. return 1; /* generic segmentation offloading on */
  6000. #endif
  6001. #ifdef ETHTOOL_GFLAGS
  6002. ret = iface_ethtool_flag_ioctl(handle, ETHTOOL_GFLAGS, "ETHTOOL_GFLAGS");
  6003. if (ret == -1)
  6004. return -1;
  6005. if (ret & ETH_FLAG_LRO)
  6006. return 1; /* large receive offloading on */
  6007. #endif
  6008. #ifdef ETHTOOL_GGRO
  6009. /*
  6010. * XXX - will this cause large reassembled packets to be
  6011. * handed to PF_PACKET sockets on receipt? If not,
  6012. * this need not be checked.
  6013. */
  6014. ret = iface_ethtool_flag_ioctl(handle, ETHTOOL_GGRO, "ETHTOOL_GGRO");
  6015. if (ret == -1)
  6016. return -1;
  6017. if (ret)
  6018. return 1; /* generic (large) receive offloading on */
  6019. #endif
  6020. return 0;
  6021. }
  6022. #else /* SIOCETHTOOL */
  6023. static int
  6024. iface_get_offload(pcap_t *handle _U_)
  6025. {
  6026. /*
  6027. * XXX - do we need to get this information if we don't
  6028. * have the ethtool ioctls? If so, how do we do that?
  6029. */
  6030. return 0;
  6031. }
  6032. #endif /* SIOCETHTOOL */
  6033. #endif /* HAVE_PACKET_RING */
  6034. #endif /* HAVE_PF_PACKET_SOCKETS */
  6035. /* ===== Functions to interface to the older kernels ================== */
  6036. /*
  6037. * Try to open a packet socket using the old kernel interface.
  6038. * Returns 1 on success and a PCAP_ERROR_ value on an error.
  6039. */
  6040. static int
  6041. activate_old(pcap_t *handle)
  6042. {
  6043. struct pcap_linux *handlep = handle->priv;
  6044. int err;
  6045. int arptype;
  6046. struct ifreq ifr;
  6047. const char *device = handle->opt.device;
  6048. struct utsname utsname;
  6049. int mtu;
  6050. /* Open the socket */
  6051. handle->fd = socket(PF_INET, SOCK_PACKET, htons(ETH_P_ALL));
  6052. if (handle->fd == -1) {
  6053. err = errno;
  6054. pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
  6055. err, "socket");
  6056. if (err == EPERM || err == EACCES) {
  6057. /*
  6058. * You don't have permission to open the
  6059. * socket.
  6060. */
  6061. return PCAP_ERROR_PERM_DENIED;
  6062. } else {
  6063. /*
  6064. * Other error.
  6065. */
  6066. return PCAP_ERROR;
  6067. }
  6068. }
  6069. /* It worked - we are using the old interface */
  6070. handlep->sock_packet = 1;
  6071. /* ...which means we get the link-layer header. */
  6072. handlep->cooked = 0;
  6073. /* Bind to the given device */
  6074. if (strcmp(device, "any") == 0) {
  6075. strlcpy(handle->errbuf, "pcap_activate: The \"any\" device isn't supported on 2.0[.x]-kernel systems",
  6076. PCAP_ERRBUF_SIZE);
  6077. return PCAP_ERROR;
  6078. }
  6079. if (iface_bind_old(handle->fd, device, handle->errbuf) == -1)
  6080. return PCAP_ERROR;
  6081. /*
  6082. * Try to get the link-layer type.
  6083. */
  6084. arptype = iface_get_arptype(handle->fd, device, handle->errbuf);
  6085. if (arptype < 0)
  6086. return PCAP_ERROR;
  6087. /*
  6088. * Try to find the DLT_ type corresponding to that
  6089. * link-layer type.
  6090. */
  6091. map_arphrd_to_dlt(handle, handle->fd, arptype, device, 0);
  6092. if (handle->linktype == -1) {
  6093. pcap_snprintf(handle->errbuf, PCAP_ERRBUF_SIZE,
  6094. "unknown arptype %d", arptype);
  6095. return PCAP_ERROR;
  6096. }
  6097. /* Go to promisc mode if requested */
  6098. if (handle->opt.promisc) {
  6099. memset(&ifr, 0, sizeof(ifr));
  6100. strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
  6101. if (ioctl(handle->fd, SIOCGIFFLAGS, &ifr) == -1) {
  6102. pcap_fmt_errmsg_for_errno(handle->errbuf,
  6103. PCAP_ERRBUF_SIZE, errno, "SIOCGIFFLAGS");
  6104. return PCAP_ERROR;
  6105. }
  6106. if ((ifr.ifr_flags & IFF_PROMISC) == 0) {
  6107. /*
  6108. * Promiscuous mode isn't currently on,
  6109. * so turn it on, and remember that
  6110. * we should turn it off when the
  6111. * pcap_t is closed.
  6112. */
  6113. /*
  6114. * If we haven't already done so, arrange
  6115. * to have "pcap_close_all()" called when
  6116. * we exit.
  6117. */
  6118. if (!pcap_do_addexit(handle)) {
  6119. /*
  6120. * "atexit()" failed; don't put
  6121. * the interface in promiscuous
  6122. * mode, just give up.
  6123. */
  6124. return PCAP_ERROR;
  6125. }
  6126. ifr.ifr_flags |= IFF_PROMISC;
  6127. if (ioctl(handle->fd, SIOCSIFFLAGS, &ifr) == -1) {
  6128. pcap_fmt_errmsg_for_errno(handle->errbuf,
  6129. PCAP_ERRBUF_SIZE, errno, "SIOCSIFFLAGS");
  6130. return PCAP_ERROR;
  6131. }
  6132. handlep->must_do_on_close |= MUST_CLEAR_PROMISC;
  6133. /*
  6134. * Add this to the list of pcaps
  6135. * to close when we exit.
  6136. */
  6137. pcap_add_to_pcaps_to_close(handle);
  6138. }
  6139. }
  6140. /*
  6141. * Compute the buffer size.
  6142. *
  6143. * We're using SOCK_PACKET, so this might be a 2.0[.x]
  6144. * kernel, and might require special handling - check.
  6145. */
  6146. if (uname(&utsname) < 0 ||
  6147. strncmp(utsname.release, "2.0", 3) == 0) {
  6148. /*
  6149. * Either we couldn't find out what kernel release
  6150. * this is, or it's a 2.0[.x] kernel.
  6151. *
  6152. * In the 2.0[.x] kernel, a "recvfrom()" on
  6153. * a SOCK_PACKET socket, with MSG_TRUNC set, will
  6154. * return the number of bytes read, so if we pass
  6155. * a length based on the snapshot length, it'll
  6156. * return the number of bytes from the packet
  6157. * copied to userland, not the actual length
  6158. * of the packet.
  6159. *
  6160. * This means that, for example, the IP dissector
  6161. * in tcpdump will get handed a packet length less
  6162. * than the length in the IP header, and will
  6163. * complain about "truncated-ip".
  6164. *
  6165. * So we don't bother trying to copy from the
  6166. * kernel only the bytes in which we're interested,
  6167. * but instead copy them all, just as the older
  6168. * versions of libpcap for Linux did.
  6169. *
  6170. * The buffer therefore needs to be big enough to
  6171. * hold the largest packet we can get from this
  6172. * device. Unfortunately, we can't get the MRU
  6173. * of the network; we can only get the MTU. The
  6174. * MTU may be too small, in which case a packet larger
  6175. * than the buffer size will be truncated *and* we
  6176. * won't get the actual packet size.
  6177. *
  6178. * However, if the snapshot length is larger than
  6179. * the buffer size based on the MTU, we use the
  6180. * snapshot length as the buffer size, instead;
  6181. * this means that with a sufficiently large snapshot
  6182. * length we won't artificially truncate packets
  6183. * to the MTU-based size.
  6184. *
  6185. * This mess just one of many problems with packet
  6186. * capture on 2.0[.x] kernels; you really want a
  6187. * 2.2[.x] or later kernel if you want packet capture
  6188. * to work well.
  6189. */
  6190. mtu = iface_get_mtu(handle->fd, device, handle->errbuf);
  6191. if (mtu == -1)
  6192. return PCAP_ERROR;
  6193. handle->bufsize = MAX_LINKHEADER_SIZE + mtu;
  6194. if (handle->bufsize < (u_int)handle->snapshot)
  6195. handle->bufsize = (u_int)handle->snapshot;
  6196. } else {
  6197. /*
  6198. * This is a 2.2[.x] or later kernel.
  6199. *
  6200. * We can safely pass "recvfrom()" a byte count
  6201. * based on the snapshot length.
  6202. */
  6203. handle->bufsize = (u_int)handle->snapshot;
  6204. }
  6205. /*
  6206. * Default value for offset to align link-layer payload
  6207. * on a 4-byte boundary.
  6208. */
  6209. handle->offset = 0;
  6210. /*
  6211. * SOCK_PACKET sockets don't supply information from
  6212. * stripped VLAN tags.
  6213. */
  6214. handlep->vlan_offset = -1; /* unknown */
  6215. return 1;
  6216. }
  6217. /*
  6218. * Bind the socket associated with FD to the given device using the
  6219. * interface of the old kernels.
  6220. */
  6221. static int
  6222. iface_bind_old(int fd, const char *device, char *ebuf)
  6223. {
  6224. struct sockaddr saddr;
  6225. int err;
  6226. socklen_t errlen = sizeof(err);
  6227. memset(&saddr, 0, sizeof(saddr));
  6228. strlcpy(saddr.sa_data, device, sizeof(saddr.sa_data));
  6229. if (bind(fd, &saddr, sizeof(saddr)) == -1) {
  6230. pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
  6231. errno, "bind");
  6232. return -1;
  6233. }
  6234. /* Any pending errors, e.g., network is down? */
  6235. if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &errlen) == -1) {
  6236. pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
  6237. errno, "getsockopt");
  6238. return -1;
  6239. }
  6240. if (err > 0) {
  6241. pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
  6242. err, "bind");
  6243. return -1;
  6244. }
  6245. return 0;
  6246. }
  6247. /* ===== System calls available on all supported kernels ============== */
  6248. /*
  6249. * Query the kernel for the MTU of the given interface.
  6250. */
  6251. static int
  6252. iface_get_mtu(int fd, const char *device, char *ebuf)
  6253. {
  6254. struct ifreq ifr;
  6255. if (!device)
  6256. return BIGGER_THAN_ALL_MTUS;
  6257. memset(&ifr, 0, sizeof(ifr));
  6258. strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
  6259. if (ioctl(fd, SIOCGIFMTU, &ifr) == -1) {
  6260. pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
  6261. errno, "SIOCGIFMTU");
  6262. return -1;
  6263. }
  6264. return ifr.ifr_mtu;
  6265. }
  6266. /*
  6267. * Get the hardware type of the given interface as ARPHRD_xxx constant.
  6268. */
  6269. static int
  6270. iface_get_arptype(int fd, const char *device, char *ebuf)
  6271. {
  6272. struct ifreq ifr;
  6273. memset(&ifr, 0, sizeof(ifr));
  6274. strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
  6275. if (ioctl(fd, SIOCGIFHWADDR, &ifr) == -1) {
  6276. pcap_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
  6277. errno, "SIOCGIFHWADDR");
  6278. if (errno == ENODEV) {
  6279. /*
  6280. * No such device.
  6281. */
  6282. return PCAP_ERROR_NO_SUCH_DEVICE;
  6283. }
  6284. return PCAP_ERROR;
  6285. }
  6286. return ifr.ifr_hwaddr.sa_family;
  6287. }
  6288. #ifdef SO_ATTACH_FILTER
  6289. static int
  6290. fix_program(pcap_t *handle, struct sock_fprog *fcode, int is_mmapped)
  6291. {
  6292. struct pcap_linux *handlep = handle->priv;
  6293. size_t prog_size;
  6294. register int i;
  6295. register struct bpf_insn *p;
  6296. struct bpf_insn *f;
  6297. int len;
  6298. /*
  6299. * Make a copy of the filter, and modify that copy if
  6300. * necessary.
  6301. */
  6302. prog_size = sizeof(*handle->fcode.bf_insns) * handle->fcode.bf_len;
  6303. len = handle->fcode.bf_len;
  6304. f = (struct bpf_insn *)malloc(prog_size);
  6305. if (f == NULL) {
  6306. pcap_fmt_errmsg_for_errno(handle->errbuf, PCAP_ERRBUF_SIZE,
  6307. errno, "malloc");
  6308. return -1;
  6309. }
  6310. memcpy(f, handle->fcode.bf_insns, prog_size);
  6311. fcode->len = len;
  6312. fcode->filter = (struct sock_filter *) f;
  6313. for (i = 0; i < len; ++i) {
  6314. p = &f[i];
  6315. /*
  6316. * What type of instruction is this?
  6317. */
  6318. switch (BPF_CLASS(p->code)) {
  6319. case BPF_RET:
  6320. /*
  6321. * It's a return instruction; are we capturing
  6322. * in memory-mapped mode?
  6323. */
  6324. if (!is_mmapped) {
  6325. /*
  6326. * No; is the snapshot length a constant,
  6327. * rather than the contents of the
  6328. * accumulator?
  6329. */
  6330. if (BPF_MODE(p->code) == BPF_K) {
  6331. /*
  6332. * Yes - if the value to be returned,
  6333. * i.e. the snapshot length, is
  6334. * anything other than 0, make it
  6335. * MAXIMUM_SNAPLEN, so that the packet
  6336. * is truncated by "recvfrom()",
  6337. * not by the filter.
  6338. *
  6339. * XXX - there's nothing we can
  6340. * easily do if it's getting the
  6341. * value from the accumulator; we'd
  6342. * have to insert code to force
  6343. * non-zero values to be
  6344. * MAXIMUM_SNAPLEN.
  6345. */
  6346. if (p->k != 0)
  6347. p->k = MAXIMUM_SNAPLEN;
  6348. }
  6349. }
  6350. break;
  6351. case BPF_LD:
  6352. case BPF_LDX:
  6353. /*
  6354. * It's a load instruction; is it loading
  6355. * from the packet?
  6356. */
  6357. switch (BPF_MODE(p->code)) {
  6358. case BPF_ABS:
  6359. case BPF_IND:
  6360. case BPF_MSH:
  6361. /*
  6362. * Yes; are we in cooked mode?
  6363. */
  6364. if (handlep->cooked) {
  6365. /*
  6366. * Yes, so we need to fix this
  6367. * instruction.
  6368. */
  6369. if (fix_offset(p) < 0) {
  6370. /*
  6371. * We failed to do so.
  6372. * Return 0, so our caller
  6373. * knows to punt to userland.
  6374. */
  6375. return 0;
  6376. }
  6377. }
  6378. break;
  6379. }
  6380. break;
  6381. }
  6382. }
  6383. return 1; /* we succeeded */
  6384. }
  6385. static int
  6386. fix_offset(struct bpf_insn *p)
  6387. {
  6388. /*
  6389. * What's the offset?
  6390. */
  6391. if (p->k >= SLL_HDR_LEN) {
  6392. /*
  6393. * It's within the link-layer payload; that starts at an
  6394. * offset of 0, as far as the kernel packet filter is
  6395. * concerned, so subtract the length of the link-layer
  6396. * header.
  6397. */
  6398. p->k -= SLL_HDR_LEN;
  6399. } else if (p->k == 0) {
  6400. /*
  6401. * It's the packet type field; map it to the special magic
  6402. * kernel offset for that field.
  6403. */
  6404. p->k = SKF_AD_OFF + SKF_AD_PKTTYPE;
  6405. } else if (p->k == 14) {
  6406. /*
  6407. * It's the protocol field; map it to the special magic
  6408. * kernel offset for that field.
  6409. */
  6410. p->k = SKF_AD_OFF + SKF_AD_PROTOCOL;
  6411. } else if ((bpf_int32)(p->k) > 0) {
  6412. /*
  6413. * It's within the header, but it's not one of those
  6414. * fields; we can't do that in the kernel, so punt
  6415. * to userland.
  6416. */
  6417. return -1;
  6418. }
  6419. return 0;
  6420. }
  6421. static int
  6422. set_kernel_filter(pcap_t *handle, struct sock_fprog *fcode)
  6423. {
  6424. int total_filter_on = 0;
  6425. int save_mode;
  6426. int ret;
  6427. int save_errno;
  6428. /*
  6429. * The socket filter code doesn't discard all packets queued
  6430. * up on the socket when the filter is changed; this means
  6431. * that packets that don't match the new filter may show up
  6432. * after the new filter is put onto the socket, if those
  6433. * packets haven't yet been read.
  6434. *
  6435. * This means, for example, that if you do a tcpdump capture
  6436. * with a filter, the first few packets in the capture might
  6437. * be packets that wouldn't have passed the filter.
  6438. *
  6439. * We therefore discard all packets queued up on the socket
  6440. * when setting a kernel filter. (This isn't an issue for
  6441. * userland filters, as the userland filtering is done after
  6442. * packets are queued up.)
  6443. *
  6444. * To flush those packets, we put the socket in read-only mode,
  6445. * and read packets from the socket until there are no more to
  6446. * read.
  6447. *
  6448. * In order to keep that from being an infinite loop - i.e.,
  6449. * to keep more packets from arriving while we're draining
  6450. * the queue - we put the "total filter", which is a filter
  6451. * that rejects all packets, onto the socket before draining
  6452. * the queue.
  6453. *
  6454. * This code deliberately ignores any errors, so that you may
  6455. * get bogus packets if an error occurs, rather than having
  6456. * the filtering done in userland even if it could have been
  6457. * done in the kernel.
  6458. */
  6459. if (setsockopt(handle->fd, SOL_SOCKET, SO_ATTACH_FILTER,
  6460. &total_fcode, sizeof(total_fcode)) == 0) {
  6461. char drain[1];
  6462. /*
  6463. * Note that we've put the total filter onto the socket.
  6464. */
  6465. total_filter_on = 1;
  6466. /*
  6467. * Save the socket's current mode, and put it in
  6468. * non-blocking mode; we drain it by reading packets
  6469. * until we get an error (which is normally a
  6470. * "nothing more to be read" error).
  6471. */
  6472. save_mode = fcntl(handle->fd, F_GETFL, 0);
  6473. if (save_mode == -1) {
  6474. pcap_fmt_errmsg_for_errno(handle->errbuf,
  6475. PCAP_ERRBUF_SIZE, errno,
  6476. "can't get FD flags when changing filter");
  6477. return -2;
  6478. }
  6479. if (fcntl(handle->fd, F_SETFL, save_mode | O_NONBLOCK) < 0) {
  6480. pcap_fmt_errmsg_for_errno(handle->errbuf,
  6481. PCAP_ERRBUF_SIZE, errno,
  6482. "can't set nonblocking mode when changing filter");
  6483. return -2;
  6484. }
  6485. while (recv(handle->fd, &drain, sizeof drain, MSG_TRUNC) >= 0)
  6486. ;
  6487. save_errno = errno;
  6488. if (save_errno != EAGAIN) {
  6489. /*
  6490. * Fatal error.
  6491. *
  6492. * If we can't restore the mode or reset the
  6493. * kernel filter, there's nothing we can do.
  6494. */
  6495. (void)fcntl(handle->fd, F_SETFL, save_mode);
  6496. (void)reset_kernel_filter(handle);
  6497. pcap_fmt_errmsg_for_errno(handle->errbuf,
  6498. PCAP_ERRBUF_SIZE, save_errno,
  6499. "recv failed when changing filter");
  6500. return -2;
  6501. }
  6502. if (fcntl(handle->fd, F_SETFL, save_mode) == -1) {
  6503. pcap_fmt_errmsg_for_errno(handle->errbuf,
  6504. PCAP_ERRBUF_SIZE, errno,
  6505. "can't restore FD flags when changing filter");
  6506. return -2;
  6507. }
  6508. }
  6509. /*
  6510. * Now attach the new filter.
  6511. */
  6512. ret = setsockopt(handle->fd, SOL_SOCKET, SO_ATTACH_FILTER,
  6513. fcode, sizeof(*fcode));
  6514. if (ret == -1 && total_filter_on) {
  6515. /*
  6516. * Well, we couldn't set that filter on the socket,
  6517. * but we could set the total filter on the socket.
  6518. *
  6519. * This could, for example, mean that the filter was
  6520. * too big to put into the kernel, so we'll have to
  6521. * filter in userland; in any case, we'll be doing
  6522. * filtering in userland, so we need to remove the
  6523. * total filter so we see packets.
  6524. */
  6525. save_errno = errno;
  6526. /*
  6527. * If this fails, we're really screwed; we have the
  6528. * total filter on the socket, and it won't come off.
  6529. * Report it as a fatal error.
  6530. */
  6531. if (reset_kernel_filter(handle) == -1) {
  6532. pcap_fmt_errmsg_for_errno(handle->errbuf,
  6533. PCAP_ERRBUF_SIZE, errno,
  6534. "can't remove kernel total filter");
  6535. return -2; /* fatal error */
  6536. }
  6537. errno = save_errno;
  6538. }
  6539. return ret;
  6540. }
  6541. static int
  6542. reset_kernel_filter(pcap_t *handle)
  6543. {
  6544. int ret;
  6545. /*
  6546. * setsockopt() barfs unless it get a dummy parameter.
  6547. * valgrind whines unless the value is initialized,
  6548. * as it has no idea that setsockopt() ignores its
  6549. * parameter.
  6550. */
  6551. int dummy = 0;
  6552. ret = setsockopt(handle->fd, SOL_SOCKET, SO_DETACH_FILTER,
  6553. &dummy, sizeof(dummy));
  6554. /*
  6555. * Ignore ENOENT - it means "we don't have a filter", so there
  6556. * was no filter to remove, and there's still no filter.
  6557. *
  6558. * Also ignore ENONET, as a lot of kernel versions had a
  6559. * typo where ENONET, rather than ENOENT, was returned.
  6560. */
  6561. if (ret == -1 && errno != ENOENT && errno != ENONET)
  6562. return -1;
  6563. return 0;
  6564. }
  6565. #endif
  6566. int
  6567. pcap_set_protocol_linux(pcap_t *p, int protocol)
  6568. {
  6569. if (pcap_check_activated(p))
  6570. return (PCAP_ERROR_ACTIVATED);
  6571. p->opt.protocol = protocol;
  6572. return (0);
  6573. }
  6574. /*
  6575. * Libpcap version string.
  6576. */
  6577. const char *
  6578. pcap_lib_version(void)
  6579. {
  6580. #ifdef HAVE_PACKET_RING
  6581. #if defined(HAVE_TPACKET3)
  6582. return (PCAP_VERSION_STRING " (with TPACKET_V3)");
  6583. #elif defined(HAVE_TPACKET2)
  6584. return (PCAP_VERSION_STRING " (with TPACKET_V2)");
  6585. #else
  6586. return (PCAP_VERSION_STRING " (with TPACKET_V1)");
  6587. #endif
  6588. #else
  6589. return (PCAP_VERSION_STRING " (without TPACKET)");
  6590. #endif
  6591. }