12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617 |
- /*++
- Copyright (c) 2015 Minoca Corp.
- This file is licensed under the terms of the GNU General Public License
- version 3. Alternative licensing terms are available. Contact
- info@minocacorp.com for details. See the LICENSE file at the root of this
- project for complete licensing information.
- Module Name:
- resolv.c
- Abstract:
- This module implements the standard DNS resolver functions.
- Author:
- Evan Green 23-Jan-2015
- Environment:
- User Mode C Library
- --*/
- //
- // ------------------------------------------------------------------- Includes
- //
- #include "libcp.h"
- #include <minoca/devinfo/net.h>
- #include <arpa/inet.h>
- #include <assert.h>
- #include <errno.h>
- #include <fcntl.h>
- #include <limits.h>
- #include <netdb.h>
- #include <poll.h>
- #include <resolv.h>
- #include <stdlib.h>
- #include "net.h"
- //
- // --------------------------------------------------------------------- Macros
- //
- //
- // This macro evaluates to non-zero if the given character is a special
- // character (per the DNS spec).
- //
- #define DNS_SPECIAL_CHARACTER(_Character) \
- (((_Character) == '"') || ((_Character) == '.') || \
- ((_Character) == ';') || ((_Character) == '\\') || \
- ((_Character) == '@') || ((_Character) == '$'))
- //
- // This macro evaluates to non-zero if the given character is printable
- // according to the DNS spec.
- //
- #define DNS_PRINTABLE_CHARACTER(_Character) \
- (((_Character) > ' ') && ((_Character) < 0x7F))
- //
- // ---------------------------------------------------------------- Definitions
- //
- //
- // Define the name of an environment variable to use as a DNS server address,
- // overriding the configuration.
- //
- #define DNS_DNSCACHEIP_VARIABLE "DNSCACHEIP"
- //
- // Define the maximum size of the resolver configuration file.
- //
- #define DNS_RESOLVER_CONFIGURATION_MAX 4096
- //
- // Define the maximum number of supported local domains.
- //
- #define DNS_DOMAIN_COUNT 8
- //
- // Define the maximum size of a DNS query.
- //
- #define DNS_QUERY_MAX 512
- //
- // Define the maximum size of a DNS name component.
- //
- #define DNS_COMPONENT_MAX 63
- //
- // Define the maximum number of times in a row to call a hook.
- //
- #define DNS_MAX_HOOK_CALLS 50
- //
- // ------------------------------------------------------ Data Type Definitions
- //
- //
- // ----------------------------------------------- Internal Function Prototypes
- //
- INT
- ClpDnsReadStartFiles (
- res_state State
- );
- int
- ClpDnsParseSocketAddress (
- PSTR Address,
- PVOID SocketAddress
- );
- INT
- ClpDnsAddConfiguredServers (
- res_state State,
- NET_DOMAIN_TYPE Domain
- );
- INT
- ClpDnsMatchQueries (
- PUCHAR Buffer1,
- PUCHAR Buffer1End,
- PUCHAR Buffer2,
- PUCHAR Buffer2End
- );
- INT
- ClpDnsIsNameInQuery (
- PUCHAR Name,
- INT Type,
- INT Class,
- PUCHAR Buffer,
- PUCHAR BufferEnd
- );
- INT
- ClpDnsIsSameName (
- PCHAR Name1,
- PCHAR Name2
- );
- INT
- ClpDnsMakeNameCanonical (
- PCHAR Source,
- PCHAR Destination,
- UINTN DestinationSize
- );
- INT
- ClpDnsIsNameServer (
- res_state State,
- struct sockaddr_in6 *Address
- );
- INT
- ClpDnsCompressName (
- PUCHAR Source,
- PUCHAR Destination,
- UINTN DestinationSize,
- PUCHAR *DomainNames,
- PUCHAR *LastDomainName
- );
- INT
- ClpDnsDecompressName (
- PUCHAR Message,
- PUCHAR MessageEnd,
- PUCHAR Source,
- PUCHAR Destination,
- UINTN DestinationSize
- );
- INT
- ClpDnsPackName (
- PUCHAR Source,
- PUCHAR Destination,
- UINTN DestinationSize,
- PUCHAR *DomainNames,
- PUCHAR *LastDomainName
- );
- INT
- ClpDnsUnpackName (
- PUCHAR Message,
- PUCHAR MessageEnd,
- PUCHAR Source,
- PUCHAR Destination,
- UINTN DestinationSize
- );
- INT
- ClpDnsEncodeName (
- PUCHAR Source,
- PUCHAR Destination,
- UINTN DestinationSize
- );
- INT
- ClpDnsDecodeName (
- PUCHAR Source,
- PUCHAR Destination,
- UINTN DestinationSize
- );
- INT
- ClpDnsFindName (
- PUCHAR Domain,
- PUCHAR Message,
- PUCHAR *DomainNames,
- PUCHAR *LastDomainName
- );
- INT
- ClpDnsSkipName (
- PUCHAR *Name,
- PUCHAR MessageEnd
- );
- INT
- ClpCompareIp4Addresses (
- struct sockaddr_in *Address1,
- struct sockaddr_in *Address2
- );
- //
- // -------------------------------------------------------------------- Globals
- //
- //
- // Store the resolver state, somewhat accessible by applications.
- //
- LIBC_API struct __res_state _res;
- //
- // Store the local domains.
- //
- int ClDnsSearch;
- PSTR ClDnsDomains[DNS_DOMAIN_COUNT];
- //
- // ------------------------------------------------------------------ Functions
- //
- //
- // TODO: Handle locking on resolver functions when threading is implemented.
- //
- LIBC_API
- int
- res_init (
- void
- )
- /*++
- Routine Description:
- This routine initializes the global resolver state.
- Arguments:
- None.
- Return Value:
- 0 on success.
- -1 on error, and errno will be set to contain more information.
- --*/
- {
- return res_ninit(&_res);
- }
- LIBC_API
- int
- res_search (
- const char *DomainName,
- int Class,
- int Type,
- u_char *Answer,
- int AnswerLength
- )
- /*++
- Routine Description:
- This routine constructs a query, sends it to the DNS server, awaits a
- response, and performs preliminary checks on the reply. It is the same as
- res_nquery, except that it also implements the default and search rules
- controlled by the RES_DEFNAMES and RES_DNSRCH options. It returns the first
- successful reply.
- Arguments:
- DomainName - Supplies the domain name to query for.
- Class - Supplies the class to put in the query.
- Type - Supplies the type to put in the query.
- Answer - Supplies a pointer where the answer will be returned.
- AnswerLength - Supplies the length of the answer buffer.
- Return Value:
- Returns the size of the response on success.
- -1 on failure.
- --*/
- {
- return res_nsearch(&_res, DomainName, Class, Type, Answer, AnswerLength);
- }
- LIBC_API
- int
- res_query (
- const char *DomainName,
- int Class,
- int Type,
- u_char *Answer,
- int AnswerLength
- )
- /*++
- Routine Description:
- This routine constructs a query, sends it to the DNS server, awaits a
- response, and performs preliminary checks on the reply.
- Arguments:
- DomainName - Supplies the domain name to query for.
- Class - Supplies the class to put in the query.
- Type - Supplies the type to put in the query.
- Answer - Supplies a pointer where the answer will be returned.
- AnswerLength - Supplies the length of the answer buffer.
- Return Value:
- Returns the size of the response on success.
- -1 on failure.
- --*/
- {
- return res_nquery(&_res, DomainName, Class, Type, Answer, AnswerLength);
- }
- LIBC_API
- int
- res_mkquery (
- int Op,
- const char *DomainName,
- int Class,
- int Type,
- u_char *Data,
- int DataLength,
- struct rrec *NewRecord,
- u_char *Buffer,
- int BufferLength
- )
- /*++
- Routine Description:
- This routine constructs a DNS query from the given parameters.
- Arguments:
- Op - Supplies the operation to perform. This is usually QUERY but can be
- any op from nameser.h.
- DomainName - Supplies the domain name to query for.
- Class - Supplies the class to put in the query.
- Type - Supplies the type to put in the query.
- Data - Supplies an unused data pointer.
- DataLength - Supplies the length of the data.
- NewRecord - Supplies a new record pointer, currently unused.
- Buffer - Supplies a pointer where the DNS query will be returned.
- BufferLength - Supplies the length of the return buffer in bytes.
- Return Value:
- Returns the size of the query created, or -1 on failure.
- --*/
- {
- int Result;
- Result = res_nmkquery(&_res,
- Op,
- DomainName,
- Class,
- Type,
- Data,
- DataLength,
- NewRecord,
- Buffer,
- BufferLength);
- return Result;
- }
- LIBC_API
- int
- res_send (
- const u_char *Message,
- int MessageLength,
- u_char *Answer,
- int AnswerLength
- )
- /*++
- Routine Description:
- This routine sends a message to the currently configured DNS server and
- returns the reply.
- Arguments:
- Message - Supplies a pointer to the message to send.
- MessageLength - Supplies the length of the message in bytes.
- Answer - Supplies a pointer where the answer will be returned.
- AnswerLength - Supplies the length of the answer buffer in bytes.
- Return Value:
- Returns the length of the reply message on success.
- -1 on failure.
- --*/
- {
- return res_nsend(&_res, Message, MessageLength, Answer, AnswerLength);
- }
- LIBC_API
- void
- res_close (
- void
- )
- /*++
- Routine Description:
- This routine closes the socket for the global resolver state.
- Arguments:
- None.
- Return Value:
- None.
- --*/
- {
- return res_nclose(&_res);
- }
- //
- // These resolver interface functions operate on a state pointer passed in,
- // rather than a global object.
- //
- LIBC_API
- int
- res_ninit (
- res_state State
- )
- /*++
- Routine Description:
- This routine initializes the resolver state.
- Arguments:
- State - Supplies the state to initialize, a pointer type.
- Return Value:
- 0 on success.
- -1 on error, and errno will be set to contain more information.
- --*/
- {
- int Result;
- State->nscount = 0;
- Result = ClpDnsReadStartFiles(State);
- if (Result < 0) {
- return -1;
- }
- if ((State->options & RES_INIT) == 0) {
- State->retry = 1;
- State->retrans = RES_TIMEOUT;
- State->options |= RES_INIT;
- State->_sock = -1;
- }
- return Result;
- }
- LIBC_API
- int
- res_nsearch (
- res_state State,
- const char *DomainName,
- int Class,
- int Type,
- u_char *Answer,
- int AnswerLength
- )
- /*++
- Routine Description:
- This routine constructs a query, sends it to the DNS server, awaits a
- response, and performs preliminary checks on the reply. It is the same as
- res_nquery, except that it also implements the default and search rules
- controlled by the RES_DEFNAMES and RES_DNSRCH options. It returns the first
- successful reply.
- Arguments:
- State - Supplies the state, a pointer type.
- DomainName - Supplies the domain name to query for.
- Class - Supplies the class to put in the query.
- Type - Supplies the type to put in the query.
- Answer - Supplies a pointer where the answer will be returned.
- AnswerLength - Supplies the length of the answer buffer.
- Return Value:
- Returns the size of the response on success.
- -1 on failure.
- --*/
- {
- //
- // For now, this is the same as res_nquery.
- //
- return res_nquery(State, DomainName, Class, Type, Answer, AnswerLength);
- }
- LIBC_API
- int
- res_nquery (
- res_state State,
- const char *DomainName,
- int Class,
- int Type,
- u_char *Answer,
- int AnswerLength
- )
- /*++
- Routine Description:
- This routine constructs a query, sends it to the DNS server, awaits a
- response, and performs preliminary checks on the reply.
- Arguments:
- State - Supplies the state, a pointer type.
- DomainName - Supplies the domain name to query for.
- Class - Supplies the class to put in the query.
- Type - Supplies the type to put in the query.
- Answer - Supplies a pointer where the answer will be returned.
- AnswerLength - Supplies the length of the answer buffer.
- Return Value:
- Returns the size of the response on success.
- -1 on failure.
- --*/
- {
- UCHAR Buffer[DNS_QUERY_MAX];
- PDNS_HEADER Header;
- UINT ResponseCode;
- int Result;
- UINT Size;
- Header = (PDNS_HEADER)Answer;
- Header->Flags = 0;
- Result = res_nmkquery(State,
- QUERY,
- DomainName,
- Class,
- Type,
- NULL,
- 0,
- NULL,
- Buffer,
- sizeof(Buffer));
- if (Result < 0) {
- return Result;
- }
- Size = Result;
- Result = res_nsend(State, Buffer, Size, Answer, AnswerLength);
- if (Result < 0) {
- return Result;
- }
- ResponseCode = (Header->Flags >> DNS_HEADER_RESPONSE_SHIFT) &
- DNS_HEADER_RESPONSE_MASK;
- if ((ResponseCode != DNS_HEADER_RESPONSE_SUCCESS) ||
- (ntohs(Header->AnswerCount) == 0)) {
- if (ResponseCode == DNS_HEADER_RESPONSE_NAME_ERROR) {
- errno = ENOENT;
- return -1;
- } else if (ResponseCode == DNS_HEADER_RESPONSE_SERVER_FAILURE) {
- errno = EAGAIN;
- return -1;
- } else if (ResponseCode == DNS_HEADER_RESPONSE_SUCCESS) {
- errno = ENODATA;
- return -1;
- } else {
- errno = ENOTRECOVERABLE;
- return -1;
- }
- }
- Size = Result;
- return Size;
- }
- LIBC_API
- int
- res_nmkquery (
- res_state State,
- int Op,
- const char *DomainName,
- int Class,
- int Type,
- u_char *Data,
- int DataLength,
- struct rrec *NewRecord,
- u_char *Buffer,
- int BufferLength
- )
- /*++
- Routine Description:
- This routine constructs a DNS query from the given parameters.
- Arguments:
- State - Supplies the state, a pointer type.
- Op - Supplies the operation to perform. This is usually QUERY but can be
- any op from nameser.h.
- DomainName - Supplies the domain name to query for.
- Class - Supplies the class to put in the query.
- Type - Supplies the type to put in the query.
- Data - Supplies an unused data pointer.
- DataLength - Supplies the length of the data.
- NewRecord - Supplies a new record pointer, currently unused.
- Buffer - Supplies a pointer where the DNS query will be returned.
- BufferLength - Supplies the length of the return buffer in bytes.
- Return Value:
- Returns the size of the query created, or -1 on failure.
- --*/
- {
- PUCHAR CurrentByte;
- DNS_HEADER DnsHeader;
- UINTN NameLength;
- UCHAR Packet[DNS_QUERY_MAX];
- PSTR Search;
- UINTN Size;
- if ((State->options & RES_INIT) == 0) {
- if (res_ninit(State) < 0) {
- return -1;
- }
- }
- memset(&DnsHeader, 0, sizeof(DNS_HEADER));
- DnsHeader.Identifier = time(NULL) ^ rand() ^ getpid();
- DnsHeader.Flags = (Op << DNS_HEADER_OPCODE_SHIFT);
- if ((State->options & RES_RECURSE) != 0) {
- DnsHeader.Flags |= DNS_HEADER_FLAG_RECURSION_DESIRED;
- }
- DnsHeader.QuestionCount = htons(1);
- memcpy(Packet, &DnsHeader, sizeof(DNS_HEADER));
- CurrentByte = Packet + sizeof(DNS_HEADER);
- NameLength = 0;
- while (*DomainName != '\0') {
- //
- // Skip dots.
- //
- while (*DomainName == '.') {
- DomainName += 1;
- }
- //
- // Find the next dot.
- //
- Search = (PSTR)DomainName;
- while ((*Search != '\0') && (*Search != '.')) {
- Search += 1;
- }
- if (Search - DomainName > DNS_COMPONENT_MAX) {
- return -1;
- }
- Size = (UINTN)(Search - DomainName);
- *CurrentByte = Size;
- if (Size == 0) {
- break;
- }
- NameLength += *CurrentByte + 1;
- if (NameLength >= DNS_MAX_NAME) {
- return -1;
- }
- CurrentByte += 1;
- memcpy(CurrentByte, DomainName, Size);
- CurrentByte += Size;
- if (*Search == '\0') {
- *CurrentByte = '\0';
- break;
- }
- DomainName = Search;
- }
- //
- // Terminate the name.
- //
- CurrentByte += 1;
- *CurrentByte = '\0';
- //
- // Add the type and class.
- //
- CurrentByte += 1;
- *CurrentByte = Type;
- CurrentByte += 1;
- *CurrentByte = 0;
- CurrentByte += 1;
- *CurrentByte = Class;
- CurrentByte += 1;
- //
- // If the generated packet is too big, fail.
- //
- Size = (UINTN)(CurrentByte - Packet);
- if (Size > BufferLength) {
- return -1;
- }
- //
- // Copy the packet over and return.
- //
- memcpy(Buffer, Packet, Size);
- return Size;
- }
- LIBC_API
- int
- res_nsend (
- res_state State,
- const u_char *Message,
- int MessageLength,
- u_char *Answer,
- int AnswerLength
- )
- /*++
- Routine Description:
- This routine sends a message to the currently configured DNS server and
- returns the reply.
- Arguments:
- State - Supplies the resolver state, a pointer type.
- Message - Supplies a pointer to the message to send.
- MessageLength - Supplies the length of the message in bytes.
- Answer - Supplies a pointer where the answer will be returned.
- AnswerLength - Supplies the length of the answer buffer in bytes.
- Return Value:
- Returns the length of the reply message on success.
- -1 on failure.
- --*/
- {
- res_sendhookact Action;
- PDNS_HEADER AnswerHeader;
- UINTN BadNameServer;
- ssize_t BytesSent;
- BOOL ConnectionReset;
- PVOID CurrentBuffer;
- time_t CurrentTime;
- fd_set DescriptorMask;
- BOOL Done;
- INT Error;
- time_t Finish;
- struct sockaddr_in From;
- socklen_t FromLength;
- BOOL GotSomewhere;
- int HighestDescriptor;
- struct iovec IoVector[2];
- struct sockaddr_in Ip4Address;
- CHAR Junk[DNS_QUERY_MAX];
- ssize_t Length;
- INT Loops;
- int NewSocket;
- PDNS_HEADER QueryHeader;
- UCHAR ResponseCode;
- int ResponseLength;
- int Result;
- INT Seconds;
- struct sockaddr_in *ServerAddress;
- INTN ServerIndex;
- socklen_t SocketSize;
- time_t Start;
- UINTN Timeout;
- struct timeval TimeValue;
- BOOL Truncated;
- UINTN Try;
- BOOL VirtualCircuit;
- if ((State->options & RES_INIT) == 0) {
- if (res_ninit(State) < 0) {
- return -1;
- }
- }
- if (AnswerLength < sizeof(DNS_HEADER)) {
- errno = EINVAL;
- return -1;
- }
- VirtualCircuit = FALSE;
- if (((State->options & RES_USEVC) != 0) ||
- (MessageLength > DNS_QUERY_MAX)) {
- VirtualCircuit = TRUE;
- }
- AnswerHeader = (PDNS_HEADER)Answer;
- BadNameServer = 0;
- ConnectionReset = FALSE;
- Error = ETIMEDOUT;
- GotSomewhere = FALSE;
- HighestDescriptor = FD_SETSIZE - 1;
- QueryHeader = (PDNS_HEADER)Message;
- ResponseLength = 0;
- //
- // Rotate through name servers if desired.
- //
- if ((State->nscount > 0) && ((State->options & RES_ROTATE) != 0)) {
- Ip4Address = State->nsaddr_list[0];
- for (ServerIndex = 0;
- ServerIndex < State->nscount - 1;
- ServerIndex += 1) {
- State->nsaddr_list[ServerIndex] =
- State->nsaddr_list[ServerIndex + 1];
- }
- State->nsaddr_list[ServerIndex] = Ip4Address;
- }
- //
- // Loop trying to send a request and get a response.
- //
- for (Try = 0; Try < State->retry; Try += 1) {
- //
- // Loop over each name server in the list.
- //
- for (ServerIndex = 0; ServerIndex < State->nscount; ServerIndex += 1) {
- ServerAddress = &(State->nsaddr_list[ServerIndex]);
- if ((BadNameServer & (1L << ServerIndex)) != 0) {
- res_nclose(State);
- continue;
- }
- //
- // Call the query hook if it's set.
- //
- if (State->qhook != NULL) {
- Done = FALSE;
- Loops = 0;
- do {
- Action = State->qhook(&ServerAddress,
- &Message,
- &MessageLength,
- Answer,
- AnswerLength,
- &ResponseLength);
- switch (Action) {
- case res_goahead:
- Done = TRUE;
- break;
- case res_nextns:
- res_nclose(State);
- Done = TRUE;
- break;
- case res_done:
- return ResponseLength;
- case res_modified:
- if (Loops < DNS_MAX_HOOK_CALLS) {
- break;
- }
- //
- // Fall through.
- //
- case res_error:
- default:
- return -EINVAL;
- }
- } while (Done == FALSE);
- if (Action == res_nextns) {
- continue;
- }
- }
- if ((State->options & RES_DEBUG) != 0) {
- fprintf(stderr,
- "res_send: Querying server %d, try %d.\n",
- ServerIndex,
- Try);
- }
- if (VirtualCircuit != FALSE) {
- //
- // Only try once on a virtual circuit.
- //
- Try = State->retry;
- Truncated = FALSE;
- //
- // Ensure this is still the expected connection.
- //
- if ((State->_sock >= 0) &&
- ((State->_flags & RES_F_VC) != 0)) {
- SocketSize = sizeof(Ip4Address);
- Result = getpeername(State->_sock,
- (struct sockaddr *)&Ip4Address,
- &SocketSize);
- if ((Result != 0) ||
- (ClpCompareIp4Addresses(&Ip4Address,
- ServerAddress) == 0)) {
- res_nclose(State);
- State->_flags &= ~RES_F_VC;
- }
- }
- //
- // Fire up a connection.
- //
- if ((State->_sock < 0) ||
- ((State->_flags & RES_F_VC) == 0)) {
- if (State->_sock >= 0) {
- res_nclose(State);
- }
- State->_sock = socket(PF_INET, SOCK_STREAM, 0);
- if ((State->_sock < 0) ||
- (State->_sock > HighestDescriptor)) {
- Error = errno;
- if ((State->options & RES_DEBUG) != 0) {
- perror("res_send: Failed to open socket");
- }
- return -Error;
- }
- errno = 0;
- Result = connect(State->_sock,
- (struct sockaddr *)ServerAddress,
- sizeof(*ServerAddress));
- if (Result < 0) {
- Error = errno;
- if ((State->options & RES_DEBUG) != 0) {
- perror("res_send: Failed to connect");
- }
- BadNameServer |= (1L << ServerIndex);
- res_nclose(State);
- continue;
- }
- State->_flags |= RES_F_VC;
- }
- //
- // Write out the request.
- //
- IoVector[0].iov_base = &MessageLength;
- IoVector[0].iov_len = INT16SZ;
- IoVector[1].iov_base = (void *)Message;
- IoVector[1].iov_len = MessageLength;
- if (writev(State->_sock, IoVector, 2) !=
- (MessageLength + INT16SZ)) {
- Error = errno;
- if ((State->options & RES_DEBUG) != 0) {
- perror("res_send: Failed to writev");
- }
- BadNameServer |= 1L << ServerIndex;
- res_nclose(State);
- continue;
- }
- //
- // Read the length and response.
- //
- Length = INT16SZ;
- ResponseLength = 0;
- CurrentBuffer = &ResponseLength;
- BytesSent = 0;
- while (Length != 0) {
- do {
- BytesSent = read(State->_sock, CurrentBuffer, Length);
- } while ((BytesSent < 0) && (errno == EINTR));
- if (BytesSent <= 0) {
- break;
- }
- CurrentBuffer += BytesSent;
- Length -= BytesSent;
- }
- if (BytesSent <= 0) {
- Error = errno;
- if ((State->options & RES_DEBUG) != 0) {
- perror("res_send: Failed to read");
- }
- res_nclose(State);
- //
- // Give one retry a shot.
- //
- if ((errno == ECONNREFUSED) && (ConnectionReset == FALSE)) {
- ConnectionReset = TRUE;
- res_nclose(State);
- ServerIndex -= 1;
- continue;
- }
- }
- Length = ResponseLength;
- if (ResponseLength > AnswerLength) {
- if ((State->options & RES_DEBUG) != 0) {
- fprintf(stderr, "res_send: Response truncated.\n");
- }
- Truncated = TRUE;
- Length = AnswerLength;
- }
- //
- // Handle an undersized message.
- //
- if (Length < sizeof(DNS_HEADER)) {
- if ((State->options & RES_DEBUG) != 0) {
- fprintf(stderr, "res_send: Undersized response.\n");
- }
- Error = ENOSPC;
- BadNameServer |= (1L << ServerIndex);
- res_nclose(State);
- continue;
- }
- CurrentBuffer = Answer;
- while (Length != 0) {
- do {
- BytesSent = read(State->_sock, CurrentBuffer, Length);
- } while ((BytesSent < 0) && (errno == EINTR));
- if (BytesSent <= 0) {
- break;
- }
- CurrentBuffer += BytesSent;
- Length -= BytesSent;
- }
- if (BytesSent <= 0) {
- Error = errno;
- if ((State->options & RES_DEBUG) != 0) {
- perror("res_send: Failed to read");
- }
- res_nclose(State);
- continue;
- }
- //
- // Flush out the rest of the answer if the response was
- // truncated so things don't get out of sync.
- //
- if (Truncated != FALSE) {
- AnswerHeader->Flags |= DNS_HEADER_FLAG_TRUNCATION;
- Length = ResponseLength - AnswerLength;
- while (Length != 0) {
- BytesSent = Length;
- if (BytesSent > sizeof(Junk)) {
- BytesSent = sizeof(Junk);
- }
- do {
- BytesSent = read(State->_sock, Junk, BytesSent);
- } while ((BytesSent < 0) && (errno == EINTR));
- if (BytesSent > 0) {
- Length -= BytesSent;
- } else {
- break;
- }
- }
- }
- //
- // Validate the response ID.
- //
- if (AnswerHeader->Identifier != QueryHeader->Identifier) {
- if ((State->options & RES_DEBUG) != 0) {
- fprintf(stderr, "res_send: Unexpected response.\n");
- }
- continue;
- }
- //
- // This is not a virtual circuit, use datagrams.
- //
- } else {
- //
- // Create a socket if there is none.
- //
- if ((State->_sock < 0) ||
- ((State->_flags & RES_F_VC) != 0)) {
- if ((State->_flags & RES_F_VC) != 0) {
- res_nclose(State);
- }
- State->_sock = socket(PF_INET, SOCK_DGRAM, 0);
- if ((State->_sock < 0) ||
- (State->_sock > HighestDescriptor)) {
- Error = errno;
- if ((State->options & RES_DEBUG) != 0) {
- perror("res_send: Failed to create socket");
- }
- return -Error;
- }
- State->_flags &= ~RES_F_CONN;
- }
- if ((State->nscount == 1) ||
- ((Try == 0) && (ServerIndex == 0))) {
- //
- // Only connect if there's no possibility of receiving a
- // response from another server.
- //
- if ((State->_flags & RES_F_CONN) == 0) {
- Result = connect(State->_sock,
- (struct sockaddr *)ServerAddress,
- sizeof(*ServerAddress));
- if (Result != 0) {
- if ((State->options & RES_DEBUG) != 0) {
- perror("res_send: Failed to connect");
- }
- BadNameServer |= 1L << ServerIndex;
- res_nclose(State);
- continue;
- }
- State->_flags |= RES_F_CONN;
- }
- //
- // Fire off the request.
- //
- BytesSent = send(State->_sock,
- (const char *)Message,
- MessageLength,
- 0);
- if (BytesSent != MessageLength) {
- if ((State->options & RES_DEBUG) != 0) {
- perror("res_send: Failed to send");
- }
- BadNameServer |= 1L << ServerIndex;
- res_nclose(State);
- continue;
- }
- } else {
- //
- // Disconnect if trying to receive to responses from
- // multiple servers.
- //
- if ((State->_flags & RES_F_CONN) != 0) {
- SocketSize = sizeof(Ip4Address);
- NewSocket = socket(PF_INET, SOCK_DGRAM, 0);
- Result = getsockname(State->_sock,
- (struct sockaddr *)&Ip4Address,
- &SocketSize);
- if (NewSocket < 0) {
- Error = errno;
- if ((State->options & RES_DEBUG) != 0) {
- perror("res_send: Failed to create socket");
- }
- return -Error;
- }
- dup2(NewSocket, State->_sock);
- close(NewSocket);
- if (Result == 0) {
- //
- // Re-bind to the original port.
- //
- Ip4Address.sin_addr.s_addr = htonl(0);
- bind(State->_sock,
- (struct sockaddr *)&Ip4Address,
- SocketSize);
- }
- State->_flags &= ~RES_F_CONN;
- errno = 0;
- }
- //
- // Fire off the request.
- //
- Result = sendto(State->_sock,
- Message,
- MessageLength,
- 0,
- (struct sockaddr *)ServerAddress,
- sizeof(*ServerAddress));
- if (Result != MessageLength) {
- if ((State->options & RES_DEBUG) != 0) {
- perror("res_send: Failed to send");
- }
- BadNameServer |= 1L << ServerIndex;
- res_nclose(State);
- continue;
- }
- }
- if ((State->_sock < 0) || (State->_sock > HighestDescriptor)) {
- if ((State->options & RES_DEBUG) != 0) {
- perror("res_send: Invalid socket");
- }
- res_nclose(State);
- continue;
- }
- //
- // Wait for a reply.
- //
- Seconds = State->retry << Try;
- if (Try > 0) {
- Seconds /= State->nscount;
- }
- if (Seconds == 0) {
- Seconds = 1;
- }
- time(&CurrentTime);
- Start = CurrentTime;
- Timeout = Seconds;
- Finish = Start + Timeout;
- while (TRUE) {
- FD_ZERO(&DescriptorMask);
- FD_SET(State->_sock, &DescriptorMask);
- TimeValue.tv_sec = Timeout;
- TimeValue.tv_usec = 0;
- Result = select(State->_sock + 1,
- &DescriptorMask,
- NULL,
- NULL,
- &TimeValue);
- if (Result == 0) {
- if ((State->options & RES_DEBUG) != 0) {
- fprintf(stderr, "res_send: DNS Server Timeout\n");
- }
- GotSomewhere = TRUE;
- break;
- }
- if (Result < 0) {
- if (errno == EINTR) {
- time(&CurrentTime);
- if (Finish >= CurrentTime) {
- Timeout = Finish - CurrentTime;
- continue;
- }
- }
- if ((State->options & RES_DEBUG) != 0) {
- perror("res_send: select failed");
- }
- res_nclose(State);
- break;
- }
- errno = 0;
- //
- // Grab that response.
- //
- FromLength = sizeof(struct sockaddr_in);
- ResponseLength = recvfrom(State->_sock,
- Answer,
- AnswerLength,
- 0,
- (struct sockaddr *)&From,
- &FromLength);
- if (ResponseLength <= 0) {
- if ((State->options & RES_DEBUG) != 0) {
- perror("res_send: select failed");
- }
- res_nclose(State);
- Result = -1;
- break;
- }
- GotSomewhere = TRUE;
- if (ResponseLength < sizeof(DNS_HEADER)) {
- if ((State->options & RES_DEBUG) != 0) {
- fprintf(stderr, "res_send: Undersized packet.\n");
- }
- Error = ENOSPC;
- BadNameServer |= 1L << ServerIndex;
- res_nclose(State);
- Result = -1;
- break;
- }
- //
- // Ignore any answers whose IDs don't match.
- //
- if (QueryHeader->Identifier != AnswerHeader->Identifier) {
- if ((State->options & RES_DEBUG) != 0) {
- fprintf(stderr, "res_send: Ignoring packet.\n");
- }
- continue;
- }
- //
- // Ensure the response came from the server.
- //
- if ((State->options & RES_INSECURE1) == 0) {
- Result = ClpDnsIsNameServer(
- State,
- (struct sockaddr_in6 *)&From);
- if (Result == 0) {
- if ((State->options & RES_DEBUG) != 0) {
- fprintf(stderr,
- "res_send: Ignoring packet from "
- "unknown server.\n");
- }
- continue;
- }
- }
- //
- // Ensure the response matches the query.
- //
- if ((State->options & RES_INSECURE2) == 0) {
- Result = ClpDnsMatchQueries(
- (PUCHAR)Message,
- (PUCHAR)Message + MessageLength,
- Answer,
- Answer + AnswerLength);
- if (Result == 0) {
- if ((State->options & RES_DEBUG) != 0) {
- fprintf(stderr,
- "res_send: Ignoring packet from "
- "mismatched query.\n");
- }
- continue;
- }
- }
- break;
- }
- //
- // If a response failed to come in, go to the next name server.
- //
- if (Result <= 0) {
- continue;
- }
- //
- // See if the server rejected the query.
- //
- ResponseCode = (AnswerHeader->Flags >>
- DNS_HEADER_RESPONSE_SHIFT) &
- DNS_HEADER_RESPONSE_MASK;
- if ((ResponseCode == DNS_HEADER_RESPONSE_SERVER_FAILURE) ||
- (ResponseCode ==
- DNS_HEADER_RESPONSE_NOT_IMPLEMENTED) ||
- (ResponseCode == DNS_HEADER_RESPONSE_REFUSED)) {
- if ((State->options & RES_DEBUG) != 0) {
- fprintf(stderr,
- "res_send: Server rejected query: %d.\n",
- ResponseCode);
- }
- BadNameServer |= 1L << ServerIndex;
- res_nclose(State);
- if (State->pfcode == 0) {
- continue;
- }
- }
- //
- // Handle truncation.
- //
- if (((State->options & RES_IGNTC) == 0) &&
- ((AnswerHeader->Flags & DNS_HEADER_FLAG_TRUNCATION) != 0)) {
- if ((State->options & RES_DEBUG) != 0) {
- fprintf(stderr,
- "res_send: Response truncated.\n");
- }
- //
- // Get the rest of the answer using TCP on the same server.
- //
- VirtualCircuit = TRUE;
- res_nclose(State);
- ServerIndex -= 1;
- continue;
- }
- }
- if ((State->options & RES_DEBUG) != 0) {
- fprintf(stderr, "res_send: Got answer.\n");
- }
- //
- // Potentially close the socket.
- //
- if (((VirtualCircuit != FALSE) &&
- (((State->options & RES_USEVC) == 0) || (ServerIndex != 0))) ||
- ((State->options & RES_STAYOPEN) == 0)) {
- res_nclose(State);
- }
- //
- // Call the response hook.
- //
- if (State->rhook != NULL) {
- Done = FALSE;
- Loops = 0;
- do {
- Action = State->rhook(ServerAddress,
- Message,
- MessageLength,
- Answer,
- AnswerLength,
- &ResponseLength);
- switch (Action) {
- case res_goahead:
- case res_done:
- Done = TRUE;
- break;
- case res_nextns:
- res_nclose(State);
- break;
- case res_modified:
- if (Loops < DNS_MAX_HOOK_CALLS) {
- break;
- }
- //
- // Fall through.
- //
- case res_error:
- default:
- return -EINVAL;
- }
- } while (Done == FALSE);
- if (Action == res_nextns) {
- continue;
- }
- }
- return AnswerLength;
- }
- }
- res_nclose(State);
- if (VirtualCircuit == FALSE) {
- if (GotSomewhere == FALSE) {
- Error = ECONNREFUSED;
- } else {
- errno = ETIMEDOUT;
- }
- }
- assert(Error > 0);
- return -Error;
- }
- LIBC_API
- void
- res_nclose (
- res_state State
- )
- /*++
- Routine Description:
- This routine closes the socket for the given resolver state.
- Arguments:
- State - Supplies a pointer to the state to close.
- Return Value:
- None.
- --*/
- {
- if (State->_sock >= 0) {
- close(State->_sock);
- State->_sock = -1;
- State->_flags &= ~(RES_F_VC | RES_F_CONN);
- }
- return;
- }
- LIBC_API
- int
- dn_expand (
- const u_char *Message,
- const u_char *MessageEnd,
- const u_char *Source,
- u_char *Destination,
- unsigned int DestinationSize
- )
- /*++
- Routine Description:
- This routine expands a DNS name in compressed format.
- Arguments:
- Message - Supplies a pointer to the DNS query or result.
- MessageEnd - Supplies one beyond the last valid byte in the message.
- Source - Supplies a pointer to the compressed name to decompress.
- Destination - Supplies a pointer where the decompressed name will be
- returned on success.
- DestinationSize - Supplies the size of the decompressed name buffer in
- bytes.
- Return Value:
- Returns the size of the compressed name.
- -1 on error.
- --*/
- {
- int NameSize;
- NameSize = ClpDnsDecompressName((PUCHAR)Message,
- (PUCHAR)MessageEnd,
- (PUCHAR)Source,
- Destination,
- DestinationSize);
- if ((NameSize > 0) && (Destination[0] == '.')) {
- Destination[0] = '\0';
- }
- return NameSize;
- }
- LIBC_API
- int
- dn_comp (
- const char *Source,
- u_char *Destination,
- unsigned int DestinationSize,
- u_char **DomainNames,
- u_char **LastDomainName
- )
- /*++
- Routine Description:
- This routine compresses a name for a format suitable for DNS queries and
- responses.
- Arguments:
- Source - Supplies the source name to compress.
- Destination - Supplies a pointer where the compressed name will be returned
- on success.
- DestinationSize - Supplies the size of the destination buffer on success.
- DomainNames - Supplies an array of previously compressed names in the
- message. The first pointer must point to the beginning of the message.
- The list ends with NULL.
- LastDomainName - Supplies one beyond the end of the array of domain name
- pointers.
- Return Value:
- Returns the size of the compressed name.
- -1 on error.
- --*/
- {
- int NameSize;
- NameSize = ClpDnsCompressName((PUCHAR)Source,
- Destination,
- DestinationSize,
- DomainNames,
- LastDomainName);
- return NameSize;
- }
- LIBC_API
- int
- dn_skipname (
- const u_char *Name,
- const u_char *MessageEnd
- )
- /*++
- Routine Description:
- This routine skips over a compressed DNS name.
- Arguments:
- Name - Supplies a pointer to the compressed name.
- MessageEnd - Supplies a pointer one byte beyond the last valid byte in the
- query or response.
- Return Value:
- Returns the size of the compressed name.
- -1 on error.
- --*/
- {
- PUCHAR NameEnd;
- NameEnd = (PUCHAR)Name;
- if (ClpDnsSkipName(&NameEnd, (PUCHAR)MessageEnd) < 0) {
- return -1;
- }
- return NameEnd - Name;
- }
- //
- // --------------------------------------------------------- Internal Functions
- //
- INT
- ClpDnsReadStartFiles (
- res_state State
- )
- /*++
- Routine Description:
- This routine reads the resolver configuration file and sets up the global
- resolver state.
- Arguments:
- State - Supplies a pointer to the state to initialize.
- Return Value:
- 0 on success.
- -1 on failure.
- --*/
- {
- CHAR Buffer[DNS_RESOLVER_CONFIGURATION_MAX];
- PSTR CacheIpAddress;
- PSTR CurrentBuffer;
- int DnsDomainCount;
- PSTR End;
- int File;
- ssize_t Length;
- char OriginalCharacter;
- int Result;
- PSTR Search;
- //
- // If there are already name servers set up, then don't do anything.
- //
- if (State->nscount > 0) {
- return 0;
- }
- CacheIpAddress = getenv(DNS_DNSCACHEIP_VARIABLE);
- ClDnsSearch = 0;
- if (CacheIpAddress != NULL) {
- if (ClpDnsParseSocketAddress(CacheIpAddress, State->nsaddr_list) != 0) {
- State->nscount += 1;
- }
- }
- State->options = RES_RECURSE;
- File = open(_PATH_RESCONF, O_RDONLY);
- if (File < 0) {
- goto DnsReadStartFilesEnd;
- }
- do {
- Length = read(File, Buffer, DNS_RESOLVER_CONFIGURATION_MAX);
- } while ((Length < 0) && (errno == EINTR));
- close(File);
- DnsDomainCount = sizeof(ClDnsDomains) / sizeof(ClDnsDomains[0]);
- CurrentBuffer = Buffer;
- End = Buffer + Length;
- while (CurrentBuffer < End) {
- if (strncmp(CurrentBuffer, "nameserver", 10) == 0) {
- CurrentBuffer += 10;
- //
- // Loop through every name server listed on the line.
- //
- while ((CurrentBuffer < End) && (*CurrentBuffer != '\n')) {
- //
- // Get past blank space.
- //
- while ((CurrentBuffer < End) &&
- (isblank(*CurrentBuffer) != 0)) {
- CurrentBuffer += 1;
- }
- Search = CurrentBuffer;
- while ((Search < End) && (isspace(*Search) == 0)) {
- Search += 1;
- }
- if (Search >= End) {
- break;
- }
- OriginalCharacter = *Search;
- *Search = '\0';
- Result = ClpDnsParseSocketAddress(
- CurrentBuffer,
- &(State->nsaddr_list[State->nscount]));
- if (Result != 0) {
- if (State->nscount < MAXNS) {
- State->nscount += 1;
- }
- }
- *Search = OriginalCharacter;
- CurrentBuffer = Search;
- }
- } else if (((strncmp(CurrentBuffer, "search", 6) == 0) ||
- (strncmp(CurrentBuffer, "domain", 6) == 0)) &&
- (ClDnsSearch < DnsDomainCount)) {
- CurrentBuffer += 6;
- //
- // Loop through all search or domain entries on this line.
- //
- while ((CurrentBuffer < End) && (*CurrentBuffer != '\n')) {
- //
- // Get past blank space or commas.
- //
- while ((CurrentBuffer < End) &&
- ((*CurrentBuffer == ',') ||
- (isblank(*CurrentBuffer) != 0))) {
- CurrentBuffer += 1;
- }
- ClDnsDomains[ClDnsSearch] = CurrentBuffer;
- while ((CurrentBuffer < End) &&
- ((*CurrentBuffer == '.') ||
- (*CurrentBuffer == '-') ||
- (isalnum(*CurrentBuffer) != 0))) {
- CurrentBuffer += 1;
- }
- OriginalCharacter = *CurrentBuffer;
- if (CurrentBuffer < End) {
- *CurrentBuffer = '\0';
- }
- if (ClDnsDomains[ClDnsSearch] < CurrentBuffer) {
- ClDnsDomains[ClDnsSearch] =
- strdup(ClDnsDomains[ClDnsSearch]);
- if (ClDnsDomains[ClDnsSearch] != NULL) {
- ClDnsSearch += 1;
- }
- }
- if (CurrentBuffer < End) {
- *CurrentBuffer = OriginalCharacter;
- }
- }
- continue;
- }
- //
- // Scan past the rest of the line, and any newlines.
- //
- while ((CurrentBuffer < End) && (*CurrentBuffer != '\n')) {
- CurrentBuffer += 1;
- }
- while ((CurrentBuffer < End) && (*CurrentBuffer == '\n')) {
- CurrentBuffer += 1;
- }
- }
- DnsReadStartFilesEnd:
- //
- // Add DNS servers from the network link configuration itself.
- //
- Result = ClpDnsAddConfiguredServers(State, NetDomainIp4);
- if (Result != 0) {
- errno = Result;
- return -1;
- }
- return 0;
- }
- int
- ClpDnsParseSocketAddress (
- PSTR Address,
- PVOID SocketAddress
- )
- /*++
- Routine Description:
- This routine attempts to convert an address string into a socket address.
- Arguments:
- Address - Supplies the address string to convert.
- SocketAddress - Supplies a pointer where the socket address will be
- returned on success (either sockaddr_in or sockaddr_in6).
- Return Value:
- Non-zero on success.
- Zero on failure.
- --*/
- {
- struct sockaddr_in Ip4Address;
- struct sockaddr_in6 Ip6Address;
- int Result;
- Result = 0;
- memset(&Ip4Address, 0, sizeof(Ip4Address));
- if (inet_pton(AF_INET, Address, &(Ip4Address.sin_addr)) != 0) {
- Ip4Address.sin_port = htons(DNS_PORT_NUMBER);
- Ip4Address.sin_family = AF_INET;
- memcpy(SocketAddress, &Ip4Address, sizeof(struct sockaddr_in));
- Result = 1;
- } else {
- memset(&Ip6Address, 0, sizeof(Ip6Address));
- Result = inet_pton(AF_INET6, Address, &Ip6Address);
- if (Result != 0) {
- Ip6Address.sin6_port = htons(DNS_PORT_NUMBER);
- Ip6Address.sin6_family = AF_INET6;
- memcpy(SocketAddress, &Ip6Address, sizeof(struct sockaddr_in6));
- }
- }
- return Result;
- }
- INT
- ClpDnsAddConfiguredServers (
- res_state State,
- NET_DOMAIN_TYPE Domain
- )
- /*++
- Routine Description:
- This routine gets the known DNS server addresses from the system.
- Arguments:
- State - Supplies the state pointer to add the servers to.
- Domain - Supplies the network domain to get DNS servers for.
- Return Value:
- 0 on success.
- Returns an error code on failure.
- --*/
- {
- BOOL AddedOne;
- socklen_t AddressLength;
- ULONG DeviceCount;
- ULONG DeviceIndex;
- DEVICE_INFORMATION_RESULT *Devices;
- NETWORK_DEVICE_INFORMATION Information;
- PVOID NewBuffer;
- INT Result;
- NET_DOMAIN_TYPE ServerDomain;
- ULONG ServerIndex;
- UINTN Size;
- KSTATUS Status;
- Devices = NULL;
- if (State->nscount == MAXNS) {
- Status = STATUS_SUCCESS;
- goto DnsAddConfiguredServersEnd;
- }
- //
- // Get the array of devices that return network device information.
- //
- DeviceCount = NETWORK_DEVICE_COUNT_ESTIMATE;
- Devices = malloc(sizeof(DEVICE_INFORMATION_RESULT) * DeviceCount);
- if (Devices == NULL) {
- Status = STATUS_INSUFFICIENT_RESOURCES;
- goto DnsAddConfiguredServersEnd;
- }
- Status = OsLocateDeviceInformation(&ClNetworkDeviceInformationUuid,
- NULL,
- Devices,
- &DeviceCount);
- if (!KSUCCESS(Status)) {
- if (Status == STATUS_BUFFER_TOO_SMALL) {
- DeviceCount += NETWORK_DEVICE_COUNT_ESTIMATE;
- NewBuffer = realloc(
- Devices,
- sizeof(DEVICE_INFORMATION_RESULT) * DeviceCount);
- if (NewBuffer == NULL) {
- Status = STATUS_INSUFFICIENT_RESOURCES;
- goto DnsAddConfiguredServersEnd;
- }
- NewBuffer = Devices;
- Status = OsLocateDeviceInformation(&ClNetworkDeviceInformationUuid,
- NULL,
- Devices,
- &DeviceCount);
- if (!KSUCCESS(Status)) {
- goto DnsAddConfiguredServersEnd;
- }
- } else {
- goto DnsAddConfiguredServersEnd;
- }
- }
- if (DeviceCount == 0) {
- Status = STATUS_NO_NETWORK_CONNECTION;
- goto DnsAddConfiguredServersEnd;
- }
- //
- // Loop through all the network devices.
- //
- AddedOne = FALSE;
- memset(&Information, 0, sizeof(NETWORK_DEVICE_INFORMATION));
- Information.Version = NETWORK_DEVICE_INFORMATION_VERSION;
- Information.Domain = Domain;
- for (DeviceIndex = 0; DeviceIndex < DeviceCount; DeviceIndex += 1) {
- Size = sizeof(NETWORK_DEVICE_INFORMATION);
- Status = OsGetSetDeviceInformation(Devices[DeviceIndex].DeviceId,
- &ClNetworkDeviceInformationUuid,
- &Information,
- &Size,
- FALSE);
- if (!KSUCCESS(Status)) {
- continue;
- }
- if (((Information.Flags & NETWORK_DEVICE_FLAG_MEDIA_CONNECTED) == 0) ||
- ((Information.Flags & NETWORK_DEVICE_FLAG_CONFIGURED) == 0)) {
- continue;
- }
- //
- // Loop through every listed server.
- //
- for (ServerIndex = 0;
- ServerIndex < Information.DnsServerCount;
- ServerIndex += 1) {
- Information.DnsServers[ServerIndex].Port = DNS_PORT_NUMBER;
- ServerDomain = Information.DnsServers[ServerIndex].Domain;
- //
- // TODO: Support IPv6 address in __res_state._u._ext.nsaddrs.
- //
- if ((State->nscount < MAXNS) &&
- (ServerDomain == NetDomainIp4)) {
- AddressLength = sizeof(struct sockaddr_in);
- Status = ClConvertFromNetworkAddress(
- &(Information.DnsServers[ServerIndex]),
- (struct sockaddr *)&(State->nsaddr_list[State->nscount]),
- &AddressLength,
- NULL,
- 0);
- if (KSUCCESS(Status)) {
- AddedOne = TRUE;
- State->nscount += 1;
- }
- continue;
- }
- }
- }
- if (AddedOne == FALSE) {
- Status = STATUS_NOT_FOUND;
- goto DnsAddConfiguredServersEnd;
- }
- Status = STATUS_SUCCESS;
- DnsAddConfiguredServersEnd:
- if (Devices != NULL) {
- free(Devices);
- }
- Result = 0;
- if (!KSUCCESS(Status)) {
- Result = ClConvertKstatusToErrorNumber(Status);
- }
- return Result;
- }
- INT
- ClpDnsMatchQueries (
- PUCHAR Buffer1,
- PUCHAR Buffer1End,
- PUCHAR Buffer2,
- PUCHAR Buffer2End
- )
- /*++
- Routine Description:
- This routine determines if two DNS queries match each other.
- Arguments:
- Buffer1 - Supplies a pointer to the first DNS query.
- Buffer1End - Supplies one beyond the last valid byte of the first DNS query.
- Buffer2 - Supplies a pointer to the second DNS query.
- Buffer2End - Supplies one beyond the last valid byte of the second DNS
- query.
- Return Value:
- -1 on error.
- 0 if the queries do not match.
- 1 if the queries match.
- --*/
- {
- INT Class;
- PUCHAR CurrentPointer;
- PDNS_HEADER Header1;
- PDNS_HEADER Header2;
- UCHAR Name[DNS_MAX_NAME];
- int NameSize;
- UINT Op1;
- UINT Op2;
- INT QuestionCount;
- INT Type;
- Header1 = (PDNS_HEADER)Buffer1;
- Header2 = (PDNS_HEADER)Buffer2;
- CurrentPointer = Buffer1 + sizeof(DNS_HEADER);
- if ((Buffer1 + sizeof(DNS_HEADER) > Buffer1End) ||
- (Buffer2 + sizeof(DNS_HEADER) > Buffer2End)) {
- return -1;
- }
- QuestionCount = ntohs(Header1->QuestionCount);
- Op1 = (Header1->Flags >> DNS_HEADER_OPCODE_SHIFT) & DNS_HEADER_OPCODE_MASK;
- Op2 = (Header2->Flags >> DNS_HEADER_OPCODE_SHIFT) & DNS_HEADER_OPCODE_MASK;
- if ((Op1 == DNS_HEADER_OPCODE_UPDATE) &&
- (Op2 == DNS_HEADER_OPCODE_UPDATE)) {
- return 1;
- }
- if (ntohs(Header2->QuestionCount) != QuestionCount) {
- return 0;
- }
- while (QuestionCount > 0) {
- QuestionCount -= 1;
- NameSize = dn_expand(Buffer1,
- Buffer1End,
- CurrentPointer,
- Name,
- sizeof(Name));
- if (NameSize < 0) {
- return -1;
- }
- CurrentPointer += NameSize;
- if (CurrentPointer + (2 * INT16SZ) > Buffer1End) {
- return -1;
- }
- Type = READ_UNALIGNED16(CurrentPointer);
- CurrentPointer += INT16SZ;
- Class = READ_UNALIGNED16(CurrentPointer);
- CurrentPointer += INT16SZ;
- if (ClpDnsIsNameInQuery(Name, Type, Class, Buffer2, Buffer2End) == 0) {
- return 0;
- }
- }
- return 1;
- }
- INT
- ClpDnsIsNameInQuery (
- PUCHAR Name,
- INT Type,
- INT Class,
- PUCHAR Buffer,
- PUCHAR BufferEnd
- )
- /*++
- Routine Description:
- This routine determines if the given name, type, and class are located in
- the query section of the given packet.
- Arguments:
- Name - Supplies a pointer to the name to look for.
- Type - Supplies the type to look for.
- Class - Supplies the class to look for.
- Buffer - Supplies a pointer to the DNS query.
- BufferEnd - Supplies one beyond the last valid byte of the DNS query.
- Return Value:
- -1 on error.
- 0 if the name was not found.
- 1 if the name was found.
- --*/
- {
- PUCHAR CurrentPointer;
- PDNS_HEADER Header;
- INT PacketClass;
- UCHAR PacketName[DNS_MAX_NAME];
- INT PacketNameSize;
- INT PacketType;
- INT QuestionCount;
- Header = (PDNS_HEADER)Buffer;
- CurrentPointer = Buffer + sizeof(DNS_HEADER);
- QuestionCount = ntohs(Header->QuestionCount);
- while (QuestionCount > 0) {
- QuestionCount -= 1;
- PacketNameSize = dn_expand(Buffer,
- BufferEnd,
- CurrentPointer,
- PacketName,
- sizeof(PacketName));
- if (PacketNameSize < 0) {
- return -1;
- }
- CurrentPointer += PacketNameSize;
- if (CurrentPointer + (2 * INT16SZ) > BufferEnd) {
- return -1;
- }
- PacketType = READ_UNALIGNED16(CurrentPointer);
- CurrentPointer += INT16SZ;
- PacketClass = READ_UNALIGNED16(CurrentPointer);
- CurrentPointer += INT16SZ;
- if ((PacketType == Type) && (PacketClass == Class) &&
- (ClpDnsIsSameName((PSTR)PacketName, (PSTR)Name) == 1)) {
- return 1;
- }
- }
- return 0;
- }
- INT
- ClpDnsIsSameName (
- PCHAR Name1,
- PCHAR Name2
- )
- /*++
- Routine Description:
- This routine determines if the two domain names are the same.
- Arguments:
- Name1 - Supplies a pointer to the first name.
- Name2 - Supplies a pointer to the second name.
- Return Value:
- -1 on error.
- 0 if the names are not the same.
- 1 if the names are the same.
- --*/
- {
- CHAR CanonicalName1[DNS_MAX_NAME];
- CHAR CanonicalName2[DNS_MAX_NAME];
- INT Result;
- Result = ClpDnsMakeNameCanonical(Name1,
- CanonicalName1,
- sizeof(CanonicalName1));
- if (Result < 0) {
- return Result;
- }
- Result = ClpDnsMakeNameCanonical(Name2,
- CanonicalName2,
- sizeof(CanonicalName2));
- if (Result < 0) {
- return Result;
- }
- if (strcasecmp(CanonicalName1, CanonicalName2) == 0) {
- return 1;
- }
- return 0;
- }
- INT
- ClpDnsMakeNameCanonical (
- PCHAR Source,
- PCHAR Destination,
- UINTN DestinationSize
- )
- /*++
- Routine Description:
- This routine makes a canonical copy of the given domain name, removing
- extra dots but making sure a dot is at the end.
- Arguments:
- Source - Supplies a pointer to the name to canonicalize.
- Destination - Supplies a pointer where the canonicalized name will be
- returned.
- DestinationSize - Supplies the number of bytes in the destination buffer.
- Return Value:
- -1 on error.
- 0 on success.
- --*/
- {
- size_t Length;
- Length = strlen(Source);
- if (Length + sizeof(".") > DestinationSize) {
- return -1;
- }
- strcpy(Destination, Source);
- while ((Length > 0) && (Destination[Length - 1] == '.')) {
- if ((Length > 1) && (Destination[Length - 2] == '\\') &&
- ((Length < 2) || (Destination[Length - 3] != '\\'))) {
- break;
- }
- Length -= 1;
- Destination[Length] = '\0';
- }
- Destination[Length] = '.';
- Length += 1;
- Destination[Length] = '\0';
- return 0;
- }
- INT
- ClpDnsIsNameServer (
- res_state State,
- struct sockaddr_in6 *Address
- )
- /*++
- Routine Description:
- This routine determines if the given address is in the list of name servers.
- Arguments:
- State - Supplies the state (pointer) containing the acceptable name
- servers.
- Address - Supplies a pointer to the address to check.
- Return Value:
- -1 on error.
- 0 on success.
- --*/
- {
- struct sockaddr_in *Ip4Address;
- struct sockaddr_in *Ip4ServerAddress;
- struct sockaddr_in6 *Ip6ServerAddress;
- int Result;
- UINTN ServerIndex;
- if (Address->sin6_family == AF_INET) {
- Ip4Address = (struct sockaddr_in *)Address;
- for (ServerIndex = 0; ServerIndex < State->nscount; ServerIndex += 1) {
- Ip4ServerAddress = &(State->nsaddr_list[ServerIndex]);
- if ((Ip4ServerAddress->sin_family == Ip4Address->sin_family) &&
- (Ip4ServerAddress->sin_port = Ip4Address->sin_port) &&
- (Ip4ServerAddress->sin_addr.s_addr ==
- Ip4Address->sin_addr.s_addr)) {
- return 1;
- }
- }
- } else if (Address->sin6_family == AF_INET6) {
- for (ServerIndex = 0; ServerIndex < MAXNS; ServerIndex += 1) {
- Ip6ServerAddress = State->_u._ext.nsaddrs[ServerIndex];
- if ((Ip6ServerAddress != NULL) &&
- (Ip6ServerAddress->sin6_family == AF_INET6) &&
- (Ip6ServerAddress->sin6_port == Address->sin6_port)) {
- //
- // It matches if it's not the ANY address and it matches the
- // server.
- //
- Result = memcmp(&(Ip6ServerAddress->sin6_addr),
- &in6addr_any,
- sizeof(struct in6_addr));
- if (Result == 0) {
- Result = memcmp(&(Ip6ServerAddress->sin6_addr),
- &(Address->sin6_addr),
- sizeof(struct in6_addr));
- if (Result != 0) {
- return 1;
- }
- }
- }
- }
- }
- return 0;
- }
- INT
- ClpDnsCompressName (
- PUCHAR Source,
- PUCHAR Destination,
- UINTN DestinationSize,
- PUCHAR *DomainNames,
- PUCHAR *LastDomainName
- )
- /*++
- Routine Description:
- This routine compresses a name for a format suitable for DNS queries and
- responses.
- Arguments:
- Source - Supplies the source name to compress.
- Destination - Supplies a pointer where the compressed name will be returned
- on success.
- DestinationSize - Supplies the size of the destination buffer on success.
- DomainNames - Supplies an array of previously compressed names in the
- message. The first pointer must point to the beginning of the message.
- The list ends with NULL.
- LastDomainName - Supplies one beyond the end of the array of domain name
- pointers.
- Return Value:
- Returns the size of the compressed name.
- -1 on error.
- --*/
- {
- UCHAR Name[DNS_MAX_NAME];
- INT Result;
- if (ClpDnsEncodeName(Source, Name, DNS_MAX_NAME) == -1) {
- return -1;
- }
- Result = ClpDnsPackName(Name,
- Destination,
- DestinationSize,
- DomainNames,
- LastDomainName);
- return Result;
- }
- INT
- ClpDnsDecompressName (
- PUCHAR Message,
- PUCHAR MessageEnd,
- PUCHAR Source,
- PUCHAR Destination,
- UINTN DestinationSize
- )
- /*++
- Routine Description:
- This routine expands a compressed name to presentation format.
- Arguments:
- Message - Supplies a pointer to the beginning of the DNS query or response.
- MessageEnd - Supplies a pointer one beyond the last valid byte in the DNS
- query or response.
- Source - Supplies a pointer within the message to the name to expand.
- Destination - Supplies a pointer where the decompressed name will be
- returned on success.
- DestinationSize - Supplies the size of the destination buffer in bytes.
- Return Value:
- Returns the number of bytes read out of the source buffer, or -1 on error.
- --*/
- {
- UCHAR Name[DNS_MAX_NAME];
- INT NameSize;
- INT Result;
- NameSize = ClpDnsUnpackName(Message,
- MessageEnd,
- Source,
- Name,
- sizeof(Name));
- if (NameSize < 0) {
- return -1;
- }
- Result = ClpDnsDecodeName(Name, Destination, DestinationSize);
- if (Result < 0) {
- return -1;
- }
- return NameSize;
- }
- INT
- ClpDnsPackName (
- PUCHAR Source,
- PUCHAR Destination,
- UINTN DestinationSize,
- PUCHAR *DomainNames,
- PUCHAR *LastDomainName
- )
- /*++
- Routine Description:
- This routine compresses a name for a format suitable for DNS queries and
- responses.
- Arguments:
- Source - Supplies the source name to compress.
- Destination - Supplies a pointer where the compressed name will be returned
- on success.
- DestinationSize - Supplies the size of the destination buffer on success.
- DomainNames - Supplies an array of previously compressed names in the
- message. The first pointer must point to the beginning of the message.
- The list ends with NULL.
- LastDomainName - Supplies one beyond the end of the array of domain name
- pointers.
- Return Value:
- Returns the size of the compressed name.
- -1 on error.
- --*/
- {
- PUCHAR *CurrentDomain;
- PUCHAR DestinationPointer;
- PUCHAR End;
- PUCHAR *LastDomain;
- INT Length;
- PUCHAR Message;
- INT Result;
- UINT Size;
- PUCHAR SourcePointer;
- CurrentDomain = NULL;
- DestinationPointer = Destination;
- End = Destination + DestinationSize;
- LastDomain = NULL;
- Message = NULL;
- Result = -1;
- SourcePointer = Source;
- if (DomainNames != NULL) {
- Message = DomainNames[0];
- DomainNames += 1;
- if (Message != NULL) {
- CurrentDomain = DomainNames;
- while (*CurrentDomain != NULL) {
- CurrentDomain += 1;
- }
- LastDomain = CurrentDomain;
- }
- }
- //
- // Make sure the domain looks good.
- //
- Length = 0;
- do {
- Size = *SourcePointer;
- if ((Size & DNS_COMPRESSION_MASK) != 0) {
- goto DnsPackNameEnd;
- }
- Length += Size + 1;
- if (Length > MAXCDNAME) {
- goto DnsPackNameEnd;
- }
- SourcePointer += Size + 1;
- } while (Size != 0);
- SourcePointer = Source;
- do {
- Size = *SourcePointer;
- if ((Size != 0) && (Message != NULL)) {
- Length = ClpDnsFindName(SourcePointer,
- Message,
- DomainNames,
- LastDomain);
- if (Length >= 0) {
- if (DestinationPointer + 1 >= End) {
- goto DnsPackNameEnd;
- }
- *DestinationPointer = (Length >> 8) | DNS_COMPRESSION_VALUE;
- DestinationPointer += 1;
- *DestinationPointer = (Length & 0xFF);
- return DestinationPointer - Destination;
- }
- if ((LastDomainName != NULL) &&
- (CurrentDomain < (LastDomainName - 1))) {
- *CurrentDomain = DestinationPointer;
- CurrentDomain += 1;
- *CurrentDomain = NULL;
- }
- }
- //
- // Copy the label.
- //
- if ((Size & DNS_COMPRESSION_MASK) != 0) {
- goto DnsPackNameEnd;
- }
- if (DestinationPointer + 1 + Size >= End) {
- goto DnsPackNameEnd;
- }
- memcpy(DestinationPointer, SourcePointer, Size + 1);
- SourcePointer += Size + 1;
- DestinationPointer += Size + 1;
- } while (Size != 0);
- if (DestinationPointer > End) {
- if (Message != NULL) {
- *LastDomain = NULL;
- goto DnsPackNameEnd;
- }
- }
- Result = 0;
- DnsPackNameEnd:
- if (Result != 0) {
- errno = EMSGSIZE;
- }
- return Result;
- }
- INT
- ClpDnsUnpackName (
- PUCHAR Message,
- PUCHAR MessageEnd,
- PUCHAR Source,
- PUCHAR Destination,
- UINTN DestinationSize
- )
- /*++
- Routine Description:
- This routine unpacks a name from a source that might be compressed.
- Arguments:
- Message - Supplies a pointer to the beginning of the DNS query or response.
- MessageEnd - Supplies a pointer one beyond the last valid byte in the DNS
- query or response.
- Source - Supplies a pointer within the message to the name to expand.
- Destination - Supplies a pointer where the decompressed name will be
- returned on success.
- DestinationSize - Supplies the size of the destination buffer in bytes.
- Return Value:
- Returns the number of bytes read out of the source buffer, or -1 on error.
- --*/
- {
- UINT Byte;
- INT Checked;
- PUCHAR DestinationLimit;
- PUCHAR DestinationPointer;
- INT Length;
- PUCHAR SourcePointer;
- Checked = 0;
- DestinationLimit = Destination + DestinationSize;
- DestinationPointer = Destination;
- Length = -1;
- SourcePointer = Source;
- if ((SourcePointer < Message) || (SourcePointer >= MessageEnd)) {
- errno = EMSGSIZE;
- return -1;
- }
- //
- // Loop getting labels in the domain name.
- //
- while (TRUE) {
- Byte = *SourcePointer;
- SourcePointer += 1;
- if (Byte == '\0') {
- break;
- }
- switch (Byte & DNS_COMPRESSION_MASK) {
- case 0:
- if (((DestinationPointer + Byte + 1) >= DestinationLimit) ||
- (SourcePointer + Byte >= MessageEnd)) {
- errno = EMSGSIZE;
- return -1;
- }
- Checked += Byte + 1;
- *DestinationPointer = Byte;
- DestinationPointer += 1;
- memcpy(DestinationPointer, SourcePointer, Byte);
- DestinationPointer += Byte;
- SourcePointer += Byte;
- break;
- case DNS_COMPRESSION_VALUE:
- if (SourcePointer >= MessageEnd) {
- errno = EMSGSIZE;
- return -1;
- }
- if (Length < 0) {
- Length = SourcePointer - Source + 1;
- }
- SourcePointer = Message +
- (((Byte & (~DNS_COMPRESSION_MASK)) <<
- BITS_PER_BYTE) |
- (*SourcePointer & 0xFF));
- if ((SourcePointer < Message) || (SourcePointer >= MessageEnd)) {
- errno = EMSGSIZE;
- return -1;
- }
- Checked += 2;
- //
- // Check for loops in the compressed name.
- //
- if (Checked >= MessageEnd - Message) {
- errno = EMSGSIZE;
- return -1;
- }
- break;
- default:
- errno = EMSGSIZE;
- return -1;
- }
- }
- *DestinationPointer = '\0';
- if (Length < 0) {
- Length = SourcePointer - Source;
- }
- return Length;
- }
- INT
- ClpDnsEncodeName (
- PUCHAR Source,
- PUCHAR Destination,
- UINTN DestinationSize
- )
- /*++
- Routine Description:
- This routine converts an ASCII string into an encoded name.
- Arguments:
- Source - Supplies a pointer to the name to encode.
- Destination - Supplies a pointer where the encoded name will be returned on
- success.
- DestinationSize - Supplies the size of the destination buffer in bytes.
- Return Value:
- 0 if the string was not fully qualified.
- 1 if the string was fully qualified.
- -1 on failure, and errno will be set to contain more information.
- --*/
- {
- INT Character;
- PUCHAR Current;
- PUCHAR End;
- BOOL Escaped;
- PUCHAR Label;
- INT Value;
- Current = Destination;
- Escaped = FALSE;
- End = Destination + DestinationSize;
- Label = Destination + 1;
- while (TRUE) {
- Character = *Source;
- Source += 1;
- if (Character == '\0') {
- break;
- }
- if (Escaped != FALSE) {
- if (isdigit(Character)) {
- Value = (Character - '0') * 100;
- Character = *Source;
- Source += 1;
- if ((Character == '\0') || (!isdigit(Character))) {
- errno = EMSGSIZE;
- return -1;
- }
- Value += (Character - '0') * 10;
- Character = *Source;
- Source += 1;
- if ((Character == '\0') || (!isdigit(Character))) {
- errno = EMSGSIZE;
- return -1;
- }
- Value += Character - '0';
- if (Value > 0xFF) {
- errno = EMSGSIZE;
- return -1;
- }
- Character = Value;
- }
- Escaped = FALSE;
- } else if (Character == '\\') {
- Escaped = TRUE;
- continue;
- } else if (Character == '.') {
- Character = Current - Label - 1;
- //
- // Watch out for the leg being too big (or off the end).
- //
- if (((Character & DNS_COMPRESSION_MASK) != 0) ||
- (Label >= End)) {
- errno = EMSGSIZE;
- return -1;
- }
- *Label = Character;
- //
- // Handle a fully qualified name.
- //
- if (*Source == '\0') {
- if (Character != 0) {
- if (Current >= End) {
- errno = EMSGSIZE;
- return -1;
- }
- *Current = '\0';
- Current += 1;
- }
- if ((Current - Destination) > MAXCDNAME) {
- errno = EMSGSIZE;
- return -1;
- }
- return 1;
- }
- if ((Character == 0) || (*Source == '.')) {
- errno = EMSGSIZE;
- return -1;
- }
- Label = Current;
- Current += 1;
- continue;
- }
- if (Current >= End) {
- errno = EMSGSIZE;
- return -1;
- }
- *Current = Character;
- Current += 1;
- }
- Character = Current - Label - 1;
- if (((Character & DNS_COMPRESSION_MASK) != 0) ||
- (Label >= End)) {
- errno = EMSGSIZE;
- return -1;
- }
- if (Label >= End) {
- errno = EMSGSIZE;
- return -1;
- }
- *Label = Character;
- if (Character != 0) {
- if (Current >= End) {
- errno = EMSGSIZE;
- return -1;
- }
- *Current = '\0';
- Current += 1;
- }
- if ((Current - Destination) > MAXCDNAME) {
- errno = EMSGSIZE;
- return -1;
- }
- return 0;
- }
- INT
- ClpDnsDecodeName (
- PUCHAR Source,
- PUCHAR Destination,
- UINTN DestinationSize
- )
- /*++
- Routine Description:
- This routine converts an encoded name to a printable ASCII name.
- Arguments:
- Source - Supplies a pointer to the name to decode.
- Destination - Supplies a pointer where the decoded name will be returned on
- success.
- DestinationSize - Supplies the size of the destination buffer in bytes.
- Return Value:
- Returns the number of bytes written to the buffer, or -1 on error.
- --*/
- {
- UCHAR Character;
- PUCHAR CurrentPointer;
- PUCHAR DestinationPointer;
- PUCHAR End;
- UINT Size;
- CurrentPointer = Source;
- DestinationPointer = Destination;
- End = Destination + DestinationSize;
- while (TRUE) {
- Size = *CurrentPointer;
- CurrentPointer += 1;
- if (Size == 0) {
- break;
- }
- //
- // The name is supposed to already be decompressed.
- //
- if ((Size & DNS_COMPRESSION_MASK) != 0) {
- errno = EMSGSIZE;
- return -1;
- }
- if (DestinationPointer != Destination) {
- if (DestinationPointer >= End) {
- errno = EMSGSIZE;
- return -1;
- }
- *DestinationPointer = '.';
- DestinationPointer += 1;
- }
- if (DestinationPointer + Size >= End) {
- errno = EMSGSIZE;
- return -1;
- }
- while (Size > 0) {
- Character = *CurrentPointer;
- CurrentPointer += 1;
- if (DNS_SPECIAL_CHARACTER(Character)) {
- if (DestinationPointer + 1 >= End) {
- errno = EMSGSIZE;
- return -1;
- }
- *DestinationPointer = '\\';
- DestinationPointer += 1;
- *DestinationPointer = Character;
- DestinationPointer += 1;
- } else if (!DNS_PRINTABLE_CHARACTER(Character)) {
- if (DestinationPointer + 3 >= End) {
- errno = EMSGSIZE;
- return -1;
- }
- *DestinationPointer = '\\';
- DestinationPointer += 1;
- *DestinationPointer = '0' + (Character / 100);
- DestinationPointer += 1;
- *DestinationPointer = '0' + ((Character % 100) / 10);
- DestinationPointer += 1;
- *DestinationPointer = '0' + (Character % 10);
- DestinationPointer += 1;
- } else {
- if (DestinationPointer >= End) {
- errno = EMSGSIZE;
- return -1;
- }
- *DestinationPointer = Character;
- DestinationPointer += 1;
- }
- Size -= 1;
- }
- }
- if (DestinationPointer == Destination) {
- if (DestinationPointer >= End) {
- errno = EMSGSIZE;
- return -1;
- }
- *DestinationPointer = '.';
- DestinationPointer += 1;
- }
- if (DestinationPointer >= End) {
- errno = EMSGSIZE;
- return -1;
- }
- *DestinationPointer = '\0';
- DestinationPointer += 1;
- return (DestinationPointer - Destination);
- }
- INT
- ClpDnsFindName (
- PUCHAR Domain,
- PUCHAR Message,
- PUCHAR *DomainNames,
- PUCHAR *LastDomainName
- )
- /*++
- Routine Description:
- This routine attempts to find the counted label name in an array of
- compressed names.
- Arguments:
- Domain - Supplies the domain to search for.
- Message - Supplies a pointer to the start of the query or response.
- DomainNames - Supplies an array of compressed names to search.
- LastDomainName - Supplies one beyond the last element in the domain names
- array.
- Return Value:
- Returns the offset from the start of the message if found.
- -1 if not found.
- --*/
- {
- PUCHAR *CurrentDomain;
- PUCHAR CurrentPointer;
- PUCHAR DomainName;
- UINT Size;
- PUCHAR Start;
- CurrentDomain = DomainNames;
- while (CurrentDomain < LastDomainName) {
- DomainName = Domain;
- CurrentPointer = *CurrentDomain;
- Start = *CurrentDomain;
- Size = *CurrentPointer;
- CurrentPointer += 1;
- while (Size != 0) {
- if ((Size & DNS_COMPRESSION_MASK) == 0) {
- if (*DomainName != Size) {
- break;
- }
- DomainName += 1;
- while (Size > 0) {
- if (tolower(*DomainName) != tolower(*CurrentPointer)) {
- break;
- }
- DomainName += 1;
- CurrentPointer += 1;
- Size -= 1;
- }
- if (Size != 0) {
- break;
- }
- if ((*DomainName == '\0') && (*CurrentPointer == '\0')) {
- return Start - Message;
- }
- if (*DomainName == '\0') {
- break;
- }
- } else if ((Size & DNS_COMPRESSION_MASK) == DNS_COMPRESSION_VALUE) {
- CurrentPointer = Message +
- (((Size & (~DNS_COMPRESSION_MASK)) <<
- BITS_PER_BYTE) |
- *CurrentPointer);
- } else {
- errno = EMSGSIZE;
- return -1;
- }
- }
- CurrentDomain += 1;
- }
- errno = ENOENT;
- return -1;
- }
- INT
- ClpDnsSkipName (
- PUCHAR *Name,
- PUCHAR MessageEnd
- )
- /*++
- Routine Description:
- This routine skips a compressed DNS name.
- Arguments:
- Name - Supplies a pointer that on input points to the name to skip. On
- successful output, this will point after the compressed name.
- MessageEnd - Supplies a pointer to the end of the DNS query or response,
- to avoid buffer overruns.
- Return Value:
- 0 on success.
- -1 on failure, an errno will be set to contain more information.
- --*/
- {
- PUCHAR Current;
- UINT Size;
- Current = *Name;
- while (Current <= MessageEnd) {
- Size = *Current;
- Current += 1;
- if (Size == 0) {
- break;
- }
- switch (Size & DNS_COMPRESSION_MASK) {
- case 0:
- Current += Size;
- continue;
- case DNS_COMPRESSION_VALUE:
- Current += 1;
- break;
- default:
- errno = EMSGSIZE;
- return -1;
- }
- break;
- }
- if (Current > MessageEnd) {
- errno = EMSGSIZE;
- return -1;
- }
- *Name = Current;
- return 0;
- }
- INT
- ClpCompareIp4Addresses (
- struct sockaddr_in *Address1,
- struct sockaddr_in *Address2
- )
- /*++
- Routine Description:
- This routine compares two IPv4 addresses.
- Arguments:
- Address1 - Supplies a pointer to the first address.
- Address2 - Supplies a pointer to the second address.
- Return Value:
- TRUE if the addresses are the same.
- FALSE if the addresses are different.
- --*/
- {
- if ((Address1->sin_family == Address2->sin_family) &&
- (Address1->sin_port == Address2->sin_port) &&
- (Address1->sin_addr.s_addr == Address2->sin_addr.s_addr)) {
- return TRUE;
- }
- return FALSE;
- }
|