pcap-rpcap.c 99 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311
  1. /*
  2. * Copyright (c) 2002 - 2005 NetGroup, Politecnico di Torino (Italy)
  3. * Copyright (c) 2005 - 2008 CACE Technologies, Davis (California)
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions
  8. * are met:
  9. *
  10. * 1. Redistributions of source code must retain the above copyright
  11. * notice, this list of conditions and the following disclaimer.
  12. * 2. Redistributions in binary form must reproduce the above copyright
  13. * notice, this list of conditions and the following disclaimer in the
  14. * documentation and/or other materials provided with the distribution.
  15. * 3. Neither the name of the Politecnico di Torino, CACE Technologies
  16. * nor the names of its contributors may be used to endorse or promote
  17. * products derived from this software without specific prior written
  18. * permission.
  19. *
  20. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. *
  32. */
  33. #ifdef HAVE_CONFIG_H
  34. #include <config.h>
  35. #endif
  36. #include "ftmacros.h"
  37. #include <string.h> /* for strlen(), ... */
  38. #include <stdlib.h> /* for malloc(), free(), ... */
  39. #include <stdarg.h> /* for functions with variable number of arguments */
  40. #include <errno.h> /* for the errno variable */
  41. #include "sockutils.h"
  42. #include "pcap-int.h"
  43. #include "rpcap-protocol.h"
  44. #include "pcap-rpcap.h"
  45. /*
  46. * This file contains the pcap module for capturing from a remote machine's
  47. * interfaces using the RPCAP protocol.
  48. *
  49. * WARNING: All the RPCAP functions that are allowed to return a buffer
  50. * containing the error description can return max PCAP_ERRBUF_SIZE characters.
  51. * However there is no guarantees that the string will be zero-terminated.
  52. * Best practice is to define the errbuf variable as a char of size
  53. * 'PCAP_ERRBUF_SIZE+1' and to insert manually a NULL character at the end
  54. * of the buffer. This will guarantee that no buffer overflows occur even
  55. * if we use the printf() to show the error on the screen.
  56. *
  57. * XXX - actually, null-terminating the error string is part of the
  58. * contract for the pcap API; if there's any place in the pcap code
  59. * that doesn't guarantee null-termination, even at the expense of
  60. * cutting the message short, that's a bug and needs to be fixed.
  61. */
  62. #define PCAP_STATS_STANDARD 0 /* Used by pcap_stats_rpcap to see if we want standard or extended statistics */
  63. #ifdef _WIN32
  64. #define PCAP_STATS_EX 1 /* Used by pcap_stats_rpcap to see if we want standard or extended statistics */
  65. #endif
  66. /*
  67. * \brief Keeps a list of all the opened connections in the active mode.
  68. *
  69. * This structure defines a linked list of items that are needed to keep the info required to
  70. * manage the active mode.
  71. * In other words, when a new connection in active mode starts, this structure is updated so that
  72. * it reflects the list of active mode connections currently opened.
  73. * This structure is required by findalldevs() and open_remote() to see if they have to open a new
  74. * control connection toward the host, or they already have a control connection in place.
  75. */
  76. struct activehosts
  77. {
  78. struct sockaddr_storage host;
  79. SOCKET sockctrl;
  80. uint8 protocol_version;
  81. struct activehosts *next;
  82. };
  83. /* Keeps a list of all the opened connections in the active mode. */
  84. static struct activehosts *activeHosts;
  85. /*
  86. * Keeps the main socket identifier when we want to accept a new remote
  87. * connection (active mode only).
  88. * See the documentation of pcap_remoteact_accept() and
  89. * pcap_remoteact_cleanup() for more details.
  90. */
  91. static SOCKET sockmain;
  92. /*
  93. * Private data for capturing remotely using the rpcap protocol.
  94. */
  95. struct pcap_rpcap {
  96. /*
  97. * This is '1' if we're the network client; it is needed by several
  98. * functions (such as pcap_setfilter()) to know whether they have
  99. * to use the socket or have to open the local adapter.
  100. */
  101. int rmt_clientside;
  102. SOCKET rmt_sockctrl; /* socket ID of the socket used for the control connection */
  103. SOCKET rmt_sockdata; /* socket ID of the socket used for the data connection */
  104. int rmt_flags; /* we have to save flags, since they are passed by the pcap_open_live(), but they are used by the pcap_startcapture() */
  105. int rmt_capstarted; /* 'true' if the capture is already started (needed to knoe if we have to call the pcap_startcapture() */
  106. char *currentfilter; /* Pointer to a buffer (allocated at run-time) that stores the current filter. Needed when flag PCAP_OPENFLAG_NOCAPTURE_RPCAP is turned on. */
  107. uint8 protocol_version; /* negotiated protocol version */
  108. unsigned int TotNetDrops; /* keeps the number of packets that have been dropped by the network */
  109. /*
  110. * This keeps the number of packets that have been received by the
  111. * application.
  112. *
  113. * Packets dropped by the kernel buffer are not counted in this
  114. * variable. It is always equal to (TotAccepted - TotDrops),
  115. * except for the case of remote capture, in which we have also
  116. * packets in flight, i.e. that have been transmitted by the remote
  117. * host, but that have not been received (yet) from the client.
  118. * In this case, (TotAccepted - TotDrops - TotNetDrops) gives a
  119. * wrong result, since this number does not corresponds always to
  120. * the number of packet received by the application. For this reason,
  121. * in the remote capture we need another variable that takes into
  122. * account of the number of packets actually received by the
  123. * application.
  124. */
  125. unsigned int TotCapt;
  126. struct pcap_stat stat;
  127. /* XXX */
  128. struct pcap *next; /* list of open pcaps that need stuff cleared on close */
  129. };
  130. /****************************************************
  131. * *
  132. * Locally defined functions *
  133. * *
  134. ****************************************************/
  135. static struct pcap_stat *rpcap_stats_rpcap(pcap_t *p, struct pcap_stat *ps, int mode);
  136. static int pcap_pack_bpffilter(pcap_t *fp, char *sendbuf, int *sendbufidx, struct bpf_program *prog);
  137. static int pcap_createfilter_norpcappkt(pcap_t *fp, struct bpf_program *prog);
  138. static int pcap_updatefilter_remote(pcap_t *fp, struct bpf_program *prog);
  139. static void pcap_save_current_filter_rpcap(pcap_t *fp, const char *filter);
  140. static int pcap_setfilter_rpcap(pcap_t *fp, struct bpf_program *prog);
  141. static int pcap_setsampling_remote(pcap_t *fp);
  142. static int pcap_startcapture_remote(pcap_t *fp);
  143. static int rpcap_sendauth(SOCKET sock, uint8 *ver, struct pcap_rmtauth *auth, char *errbuf);
  144. static int rpcap_recv_msg_header(SOCKET sock, struct rpcap_header *header, char *errbuf);
  145. static int rpcap_check_msg_ver(SOCKET sock, uint8 expected_ver, struct rpcap_header *header, char *errbuf);
  146. static int rpcap_check_msg_type(SOCKET sock, uint8 request_type, struct rpcap_header *header, uint16 *errcode, char *errbuf);
  147. static int rpcap_process_msg_header(SOCKET sock, uint8 ver, uint8 request_type, struct rpcap_header *header, char *errbuf);
  148. static int rpcap_recv(SOCKET sock, void *buffer, size_t toread, uint32 *plen, char *errbuf);
  149. static void rpcap_msg_err(SOCKET sockctrl, uint32 plen, char *remote_errbuf);
  150. static int rpcap_discard(SOCKET sock, uint32 len, char *errbuf);
  151. static int rpcap_read_packet_msg(SOCKET sock, pcap_t *p, size_t size);
  152. /****************************************************
  153. * *
  154. * Function bodies *
  155. * *
  156. ****************************************************/
  157. /*
  158. * This function translates (i.e. de-serializes) a 'rpcap_sockaddr'
  159. * structure from the network byte order to a 'sockaddr_in" or
  160. * 'sockaddr_in6' structure in the host byte order.
  161. *
  162. * It accepts an 'rpcap_sockaddr' structure as it is received from the
  163. * network, and checks the address family field against various values
  164. * to see whether it looks like an IPv4 address, an IPv6 address, or
  165. * neither of those. It checks for multiple values in order to try
  166. * to handle older rpcap daemons that sent the native OS's 'sockaddr_in'
  167. * or 'sockaddr_in6' structures over the wire with some members
  168. * byte-swapped, and to handle the fact that AF_INET6 has different
  169. * values on different OSes.
  170. *
  171. * For IPv4 addresses, it converts the address family to host byte
  172. * order from network byte order and puts it into the structure,
  173. * sets the length if a sockaddr structure has a length, converts the
  174. * port number to host byte order from network byte order and puts
  175. * it into the structure, copies over the IPv4 address, and zeroes
  176. * out the zero padding.
  177. *
  178. * For IPv6 addresses, it converts the address family to host byte
  179. * order from network byte order and puts it into the structure,
  180. * sets the length if a sockaddr structure has a length, converts the
  181. * port number and flow information to host byte order from network
  182. * byte order and puts them into the structure, copies over the IPv6
  183. * address, and converts the scope ID to host byte order from network
  184. * byte order and puts it into the structure.
  185. *
  186. * The function will allocate the 'sockaddrout' variable according to the
  187. * address family in use. In case the address does not belong to the
  188. * AF_INET nor AF_INET6 families, 'sockaddrout' is not allocated and a
  189. * NULL pointer is returned. This usually happens because that address
  190. * does not exist on the other host, or is of an address family other
  191. * than AF_INET or AF_INET6, so the RPCAP daemon sent a 'sockaddr_storage'
  192. * structure containing all 'zero' values.
  193. *
  194. * Older RPCAPDs sent the addresses over the wire in the OS's native
  195. * structure format. For most OSes, this looks like the over-the-wire
  196. * format, but might have a different value for AF_INET6 than the value
  197. * on the machine receiving the reply. For OSes with the newer BSD-style
  198. * sockaddr structures, this has, instead of a 2-byte address family,
  199. * a 1-byte structure length followed by a 1-byte address family. The
  200. * RPCAPD code would put the address family in network byte order before
  201. * sending it; that would set it to 0 on a little-endian machine, as
  202. * htons() of any value between 1 and 255 would result in a value > 255,
  203. * with its lower 8 bits zero, so putting that back into a 1-byte field
  204. * would set it to 0.
  205. *
  206. * Therefore, for older RPCAPDs running on an OS with newer BSD-style
  207. * sockaddr structures, the family field, if treated as a big-endian
  208. * (network byte order) 16-bit field, would be:
  209. *
  210. * (length << 8) | family if sent by a big-endian machine
  211. * (length << 8) if sent by a little-endian machine
  212. *
  213. * For current RPCAPDs, and for older RPCAPDs running on an OS with
  214. * older BSD-style sockaddr structures, the family field, if treated
  215. * as a big-endian 16-bit field, would just contain the family.
  216. *
  217. * \param sockaddrin: a 'rpcap_sockaddr' pointer to the variable that has
  218. * to be de-serialized.
  219. *
  220. * \param sockaddrout: a 'sockaddr_storage' pointer to the variable that will contain
  221. * the de-serialized data. The structure returned can be either a 'sockaddr_in' or 'sockaddr_in6'.
  222. * This variable will be allocated automatically inside this function.
  223. *
  224. * \param errbuf: a pointer to a user-allocated buffer (of size PCAP_ERRBUF_SIZE)
  225. * that will contain the error message (in case there is one).
  226. *
  227. * \return '0' if everything is fine, '-1' if some errors occurred. Basically, the error
  228. * can be only the fact that the malloc() failed to allocate memory.
  229. * The error message is returned in the 'errbuf' variable, while the deserialized address
  230. * is returned into the 'sockaddrout' variable.
  231. *
  232. * \warning This function supports only AF_INET and AF_INET6 address families.
  233. *
  234. * \warning The sockaddrout (if not NULL) must be deallocated by the user.
  235. */
  236. /*
  237. * Possible IPv4 family values other than the designated over-the-wire value,
  238. * which is 2 (because everybody uses 2 for AF_INET4).
  239. */
  240. #define SOCKADDR_IN_LEN 16 /* length of struct sockaddr_in */
  241. #define SOCKADDR_IN6_LEN 28 /* length of struct sockaddr_in6 */
  242. #define NEW_BSD_AF_INET_BE ((SOCKADDR_IN_LEN << 8) | 2)
  243. #define NEW_BSD_AF_INET_LE (SOCKADDR_IN_LEN << 8)
  244. /*
  245. * Possible IPv6 family values other than the designated over-the-wire value,
  246. * which is 23 (because that's what Windows uses, and most RPCAP servers
  247. * out there are probably running Windows, as WinPcap includes the server
  248. * but few if any UN*Xes build and ship it).
  249. *
  250. * The new BSD sockaddr structure format was in place before 4.4-Lite, so
  251. * all the free-software BSDs use it.
  252. */
  253. #define NEW_BSD_AF_INET6_BSD_BE ((SOCKADDR_IN6_LEN << 8) | 24) /* NetBSD, OpenBSD, BSD/OS */
  254. #define NEW_BSD_AF_INET6_FREEBSD_BE ((SOCKADDR_IN6_LEN << 8) | 28) /* FreeBSD, DragonFly BSD */
  255. #define NEW_BSD_AF_INET6_DARWIN_BE ((SOCKADDR_IN6_LEN << 8) | 30) /* macOS, iOS, anything else Darwin-based */
  256. #define NEW_BSD_AF_INET6_LE (SOCKADDR_IN6_LEN << 8)
  257. #define LINUX_AF_INET6 10
  258. #define HPUX_AF_INET6 22
  259. #define AIX_AF_INET6 24
  260. #define SOLARIS_AF_INET6 26
  261. static int
  262. rpcap_deseraddr(struct rpcap_sockaddr *sockaddrin, struct sockaddr_storage **sockaddrout, char *errbuf)
  263. {
  264. /* Warning: we support only AF_INET and AF_INET6 */
  265. switch (ntohs(sockaddrin->family))
  266. {
  267. case RPCAP_AF_INET:
  268. case NEW_BSD_AF_INET_BE:
  269. case NEW_BSD_AF_INET_LE:
  270. {
  271. struct rpcap_sockaddr_in *sockaddrin_ipv4;
  272. struct sockaddr_in *sockaddrout_ipv4;
  273. (*sockaddrout) = (struct sockaddr_storage *) malloc(sizeof(struct sockaddr_in));
  274. if ((*sockaddrout) == NULL)
  275. {
  276. pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
  277. errno, "malloc() failed");
  278. return -1;
  279. }
  280. sockaddrin_ipv4 = (struct rpcap_sockaddr_in *) sockaddrin;
  281. sockaddrout_ipv4 = (struct sockaddr_in *) (*sockaddrout);
  282. sockaddrout_ipv4->sin_family = AF_INET;
  283. sockaddrout_ipv4->sin_port = ntohs(sockaddrin_ipv4->port);
  284. memcpy(&sockaddrout_ipv4->sin_addr, &sockaddrin_ipv4->addr, sizeof(sockaddrout_ipv4->sin_addr));
  285. memset(sockaddrout_ipv4->sin_zero, 0, sizeof(sockaddrout_ipv4->sin_zero));
  286. break;
  287. }
  288. #ifdef AF_INET6
  289. case RPCAP_AF_INET6:
  290. case NEW_BSD_AF_INET6_BSD_BE:
  291. case NEW_BSD_AF_INET6_FREEBSD_BE:
  292. case NEW_BSD_AF_INET6_DARWIN_BE:
  293. case NEW_BSD_AF_INET6_LE:
  294. case LINUX_AF_INET6:
  295. case HPUX_AF_INET6:
  296. case AIX_AF_INET6:
  297. case SOLARIS_AF_INET6:
  298. {
  299. struct rpcap_sockaddr_in6 *sockaddrin_ipv6;
  300. struct sockaddr_in6 *sockaddrout_ipv6;
  301. (*sockaddrout) = (struct sockaddr_storage *) malloc(sizeof(struct sockaddr_in6));
  302. if ((*sockaddrout) == NULL)
  303. {
  304. pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
  305. errno, "malloc() failed");
  306. return -1;
  307. }
  308. sockaddrin_ipv6 = (struct rpcap_sockaddr_in6 *) sockaddrin;
  309. sockaddrout_ipv6 = (struct sockaddr_in6 *) (*sockaddrout);
  310. sockaddrout_ipv6->sin6_family = AF_INET6;
  311. sockaddrout_ipv6->sin6_port = ntohs(sockaddrin_ipv6->port);
  312. sockaddrout_ipv6->sin6_flowinfo = ntohl(sockaddrin_ipv6->flowinfo);
  313. memcpy(&sockaddrout_ipv6->sin6_addr, &sockaddrin_ipv6->addr, sizeof(sockaddrout_ipv6->sin6_addr));
  314. sockaddrout_ipv6->sin6_scope_id = ntohl(sockaddrin_ipv6->scope_id);
  315. break;
  316. }
  317. #endif
  318. default:
  319. /*
  320. * It is neither AF_INET nor AF_INET6 (or, if the OS doesn't
  321. * support AF_INET6, it's not AF_INET).
  322. */
  323. *sockaddrout = NULL;
  324. break;
  325. }
  326. return 0;
  327. }
  328. /*
  329. * This function reads a packet from the network socket. It does not
  330. * deliver the packet to a pcap_dispatch()/pcap_loop() callback (hence
  331. * the "nocb" string into its name).
  332. *
  333. * This function is called by pcap_read_rpcap().
  334. *
  335. * WARNING: By choice, this function does not make use of semaphores. A smarter
  336. * implementation should put a semaphore into the data thread, and a signal will
  337. * be raised as soon as there is data into the socket buffer.
  338. * However this is complicated and it does not bring any advantages when reading
  339. * from the network, in which network delays can be much more important than
  340. * these optimizations. Therefore, we chose the following approach:
  341. * - the 'timeout' chosen by the user is split in two (half on the server side,
  342. * with the usual meaning, and half on the client side)
  343. * - this function checks for packets; if there are no packets, it waits for
  344. * timeout/2 and then it checks again. If packets are still missing, it returns,
  345. * otherwise it reads packets.
  346. */
  347. static int pcap_read_nocb_remote(pcap_t *p, struct pcap_pkthdr *pkt_header, u_char **pkt_data)
  348. {
  349. struct pcap_rpcap *pr = p->priv; /* structure used when doing a remote live capture */
  350. struct rpcap_header *header; /* general header according to the RPCAP format */
  351. struct rpcap_pkthdr *net_pkt_header; /* header of the packet, from the message */
  352. u_char *net_pkt_data; /* packet data from the message */
  353. uint32 plen;
  354. int retval; /* generic return value */
  355. int msglen;
  356. /* Structures needed for the select() call */
  357. struct timeval tv; /* maximum time the select() can block waiting for data */
  358. fd_set rfds; /* set of socket descriptors we have to check */
  359. /*
  360. * Define the packet buffer timeout, to be used in the select()
  361. * 'timeout', in pcap_t, is in milliseconds; we have to convert it into sec and microsec
  362. */
  363. tv.tv_sec = p->opt.timeout / 1000;
  364. tv.tv_usec = (p->opt.timeout - tv.tv_sec * 1000) * 1000;
  365. /* Watch out sockdata to see if it has input */
  366. FD_ZERO(&rfds);
  367. /*
  368. * 'fp->rmt_sockdata' has always to be set before calling the select(),
  369. * since it is cleared by the select()
  370. */
  371. FD_SET(pr->rmt_sockdata, &rfds);
  372. retval = select((int) pr->rmt_sockdata + 1, &rfds, NULL, NULL, &tv);
  373. if (retval == -1)
  374. {
  375. #ifndef _WIN32
  376. if (errno == EINTR)
  377. {
  378. /* Interrupted. */
  379. return 0;
  380. }
  381. #endif
  382. sock_geterror("select(): ", p->errbuf, PCAP_ERRBUF_SIZE);
  383. return -1;
  384. }
  385. /* There is no data waiting, so return '0' */
  386. if (retval == 0)
  387. return 0;
  388. /*
  389. * We have to define 'header' as a pointer to a larger buffer,
  390. * because in case of UDP we have to read all the message within a single call
  391. */
  392. header = (struct rpcap_header *) p->buffer;
  393. net_pkt_header = (struct rpcap_pkthdr *) ((char *)p->buffer + sizeof(struct rpcap_header));
  394. net_pkt_data = (u_char *)p->buffer + sizeof(struct rpcap_header) + sizeof(struct rpcap_pkthdr);
  395. if (pr->rmt_flags & PCAP_OPENFLAG_DATATX_UDP)
  396. {
  397. /* Read the entire message from the network */
  398. msglen = sock_recv_dgram(pr->rmt_sockdata, p->buffer,
  399. p->bufsize, p->errbuf, PCAP_ERRBUF_SIZE);
  400. if (msglen == -1)
  401. {
  402. /* Network error. */
  403. return -1;
  404. }
  405. if (msglen == -3)
  406. {
  407. /* Interrupted receive. */
  408. return 0;
  409. }
  410. if ((size_t)msglen < sizeof(struct rpcap_header))
  411. {
  412. /*
  413. * Message is shorter than an rpcap header.
  414. */
  415. pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
  416. "UDP packet message is shorter than an rpcap header");
  417. return -1;
  418. }
  419. plen = ntohl(header->plen);
  420. if ((size_t)msglen < sizeof(struct rpcap_header) + plen)
  421. {
  422. /*
  423. * Message is shorter than the header claims it
  424. * is.
  425. */
  426. pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
  427. "UDP packet message is shorter than its rpcap header claims");
  428. return -1;
  429. }
  430. }
  431. else
  432. {
  433. int status;
  434. if ((size_t)p->cc < sizeof(struct rpcap_header))
  435. {
  436. /*
  437. * We haven't read any of the packet header yet.
  438. * The size we should get is the size of the
  439. * packet header.
  440. */
  441. status = rpcap_read_packet_msg(pr->rmt_sockdata, p,
  442. sizeof(struct rpcap_header));
  443. if (status == -1)
  444. {
  445. /* Network error. */
  446. return -1;
  447. }
  448. if (status == -3)
  449. {
  450. /* Interrupted receive. */
  451. return 0;
  452. }
  453. }
  454. /*
  455. * We have the header, so we know how long the
  456. * message payload is. The size we should get
  457. * is the size of the packet header plus the
  458. * size of the payload.
  459. */
  460. plen = ntohl(header->plen);
  461. if (plen > p->bufsize - sizeof(struct rpcap_header))
  462. {
  463. /*
  464. * This is bigger than the largest
  465. * record we'd expect. (We do it by
  466. * subtracting in order to avoid an
  467. * overflow.)
  468. */
  469. pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
  470. "Server sent us a message larger than the largest expected packet message");
  471. return -1;
  472. }
  473. status = rpcap_read_packet_msg(pr->rmt_sockdata, p,
  474. sizeof(struct rpcap_header) + plen);
  475. if (status == -1)
  476. {
  477. /* Network error. */
  478. return -1;
  479. }
  480. if (status == -3)
  481. {
  482. /* Interrupted receive. */
  483. return 0;
  484. }
  485. /*
  486. * We have the entire message; reset the buffer pointer
  487. * and count, as the next read should start a new
  488. * message.
  489. */
  490. p->bp = p->buffer;
  491. p->cc = 0;
  492. }
  493. /*
  494. * We have the entire message.
  495. */
  496. header->plen = plen;
  497. /*
  498. * Did the server specify the version we negotiated?
  499. */
  500. if (rpcap_check_msg_ver(pr->rmt_sockdata, pr->protocol_version,
  501. header, p->errbuf) == -1)
  502. {
  503. return 0; /* Return 'no packets received' */
  504. }
  505. /*
  506. * Is this a RPCAP_MSG_PACKET message?
  507. */
  508. if (header->type != RPCAP_MSG_PACKET)
  509. {
  510. return 0; /* Return 'no packets received' */
  511. }
  512. if (ntohl(net_pkt_header->caplen) > plen)
  513. {
  514. pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
  515. "Packet's captured data goes past the end of the received packet message.");
  516. return -1;
  517. }
  518. /* Fill in packet header */
  519. pkt_header->caplen = ntohl(net_pkt_header->caplen);
  520. pkt_header->len = ntohl(net_pkt_header->len);
  521. pkt_header->ts.tv_sec = ntohl(net_pkt_header->timestamp_sec);
  522. pkt_header->ts.tv_usec = ntohl(net_pkt_header->timestamp_usec);
  523. /* Supply a pointer to the beginning of the packet data */
  524. *pkt_data = net_pkt_data;
  525. /*
  526. * I don't update the counter of the packets dropped by the network since we're using TCP,
  527. * therefore no packets are dropped. Just update the number of packets received correctly
  528. */
  529. pr->TotCapt++;
  530. if (pr->rmt_flags & PCAP_OPENFLAG_DATATX_UDP)
  531. {
  532. unsigned int npkt;
  533. /* We're using UDP, so we need to update the counter of the packets dropped by the network */
  534. npkt = ntohl(net_pkt_header->npkt);
  535. if (pr->TotCapt != npkt)
  536. {
  537. pr->TotNetDrops += (npkt - pr->TotCapt);
  538. pr->TotCapt = npkt;
  539. }
  540. }
  541. /* Packet read successfully */
  542. return 1;
  543. }
  544. /*
  545. * This function reads a packet from the network socket.
  546. *
  547. * This function relies on the pcap_read_nocb_remote to deliver packets. The
  548. * difference, here, is that as soon as a packet is read, it is delivered
  549. * to the application by means of a callback function.
  550. */
  551. static int pcap_read_rpcap(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
  552. {
  553. struct pcap_rpcap *pr = p->priv; /* structure used when doing a remote live capture */
  554. struct pcap_pkthdr pkt_header;
  555. u_char *pkt_data;
  556. int n = 0;
  557. int ret;
  558. /*
  559. * If this is client-side, and we haven't already started
  560. * the capture, start it now.
  561. */
  562. if (pr->rmt_clientside)
  563. {
  564. /* We are on an remote capture */
  565. if (!pr->rmt_capstarted)
  566. {
  567. /*
  568. * The capture isn't started yet, so try to
  569. * start it.
  570. */
  571. if (pcap_startcapture_remote(p))
  572. return -1;
  573. }
  574. }
  575. while (n < cnt || PACKET_COUNT_IS_UNLIMITED(cnt))
  576. {
  577. /*
  578. * Has "pcap_breakloop()" been called?
  579. */
  580. if (p->break_loop) {
  581. /*
  582. * Yes - clear the flag that indicates that it
  583. * has, and return PCAP_ERROR_BREAK to indicate
  584. * that we were told to break out of the loop.
  585. */
  586. p->break_loop = 0;
  587. return (PCAP_ERROR_BREAK);
  588. }
  589. /*
  590. * Read some packets.
  591. */
  592. ret = pcap_read_nocb_remote(p, &pkt_header, &pkt_data);
  593. if (ret == 1)
  594. {
  595. /*
  596. * We got a packet. Hand it to the callback
  597. * and count it so we can return the count.
  598. */
  599. (*callback)(user, &pkt_header, pkt_data);
  600. n++;
  601. }
  602. else if (ret == -1)
  603. {
  604. /* Error. */
  605. return ret;
  606. }
  607. else
  608. {
  609. /*
  610. * No packet; this could mean that we timed
  611. * out, or that we got interrupted, or that
  612. * we got a bad packet.
  613. *
  614. * Were we told to break out of the loop?
  615. */
  616. if (p->break_loop) {
  617. /*
  618. * Yes.
  619. */
  620. p->break_loop = 0;
  621. return (PCAP_ERROR_BREAK);
  622. }
  623. /* No - return the number of packets we've processed. */
  624. return n;
  625. }
  626. }
  627. return n;
  628. }
  629. /*
  630. * This function sends a CLOSE command to the capture server.
  631. *
  632. * It is called when the user calls pcap_close(). It sends a command
  633. * to our peer that says 'ok, let's stop capturing'.
  634. *
  635. * WARNING: Since we're closing the connection, we do not check for errors.
  636. */
  637. static void pcap_cleanup_rpcap(pcap_t *fp)
  638. {
  639. struct pcap_rpcap *pr = fp->priv; /* structure used when doing a remote live capture */
  640. struct rpcap_header header; /* header of the RPCAP packet */
  641. struct activehosts *temp; /* temp var needed to scan the host list chain, to detect if we're in active mode */
  642. int active = 0; /* active mode or not? */
  643. /* detect if we're in active mode */
  644. temp = activeHosts;
  645. while (temp)
  646. {
  647. if (temp->sockctrl == pr->rmt_sockctrl)
  648. {
  649. active = 1;
  650. break;
  651. }
  652. temp = temp->next;
  653. }
  654. if (!active)
  655. {
  656. rpcap_createhdr(&header, pr->protocol_version,
  657. RPCAP_MSG_CLOSE, 0, 0);
  658. /*
  659. * Send the close request; don't report any errors, as
  660. * we're closing this pcap_t, and have no place to report
  661. * the error. No reply is sent to this message.
  662. */
  663. (void)sock_send(pr->rmt_sockctrl, (char *)&header,
  664. sizeof(struct rpcap_header), NULL, 0);
  665. }
  666. else
  667. {
  668. rpcap_createhdr(&header, pr->protocol_version,
  669. RPCAP_MSG_ENDCAP_REQ, 0, 0);
  670. /*
  671. * Send the end capture request; don't report any errors,
  672. * as we're closing this pcap_t, and have no place to
  673. * report the error.
  674. */
  675. if (sock_send(pr->rmt_sockctrl, (char *)&header,
  676. sizeof(struct rpcap_header), NULL, 0) == 0)
  677. {
  678. /*
  679. * Wait for the answer; don't report any errors,
  680. * as we're closing this pcap_t, and have no
  681. * place to report the error.
  682. */
  683. if (rpcap_process_msg_header(pr->rmt_sockctrl,
  684. pr->protocol_version, RPCAP_MSG_ENDCAP_REQ,
  685. &header, NULL) == 0)
  686. {
  687. (void)rpcap_discard(pr->rmt_sockctrl,
  688. header.plen, NULL);
  689. }
  690. }
  691. }
  692. if (pr->rmt_sockdata)
  693. {
  694. sock_close(pr->rmt_sockdata, NULL, 0);
  695. pr->rmt_sockdata = 0;
  696. }
  697. if ((!active) && (pr->rmt_sockctrl))
  698. sock_close(pr->rmt_sockctrl, NULL, 0);
  699. pr->rmt_sockctrl = 0;
  700. if (pr->currentfilter)
  701. {
  702. free(pr->currentfilter);
  703. pr->currentfilter = NULL;
  704. }
  705. /* To avoid inconsistencies in the number of sock_init() */
  706. sock_cleanup();
  707. }
  708. /*
  709. * This function retrieves network statistics from our peer;
  710. * it provides only the standard statistics.
  711. */
  712. static int pcap_stats_rpcap(pcap_t *p, struct pcap_stat *ps)
  713. {
  714. struct pcap_stat *retval;
  715. retval = rpcap_stats_rpcap(p, ps, PCAP_STATS_STANDARD);
  716. if (retval)
  717. return 0;
  718. else
  719. return -1;
  720. }
  721. #ifdef _WIN32
  722. /*
  723. * This function retrieves network statistics from our peer;
  724. * it provides the additional statistics supported by pcap_stats_ex().
  725. */
  726. static struct pcap_stat *pcap_stats_ex_rpcap(pcap_t *p, int *pcap_stat_size)
  727. {
  728. *pcap_stat_size = sizeof (p->stat);
  729. /* PCAP_STATS_EX (third param) means 'extended pcap_stats()' */
  730. return (rpcap_stats_rpcap(p, &(p->stat), PCAP_STATS_EX));
  731. }
  732. #endif
  733. /*
  734. * This function retrieves network statistics from our peer. It
  735. * is used by the two previous functions.
  736. *
  737. * It can be called in two modes:
  738. * - PCAP_STATS_STANDARD: if we want just standard statistics (i.e.,
  739. * for pcap_stats())
  740. * - PCAP_STATS_EX: if we want extended statistics (i.e., for
  741. * pcap_stats_ex())
  742. *
  743. * This 'mode' parameter is needed because in pcap_stats() the variable that
  744. * keeps the statistics is allocated by the user. On Windows, this structure
  745. * has been extended in order to keep new stats. However, if the user has a
  746. * smaller structure and it passes it to pcap_stats(), this function will
  747. * try to fill in more data than the size of the structure, so that memory
  748. * after the structure will be overwritten.
  749. *
  750. * So, we need to know it we have to copy just the standard fields, or the
  751. * extended fields as well.
  752. *
  753. * In case we want to copy the extended fields as well, the problem of
  754. * memory overflow no longer exists because the structure that's filled
  755. * in is part of the pcap_t, so that it can be guaranteed to be large
  756. * enough for the additional statistics.
  757. *
  758. * \param p: the pcap_t structure related to the current instance.
  759. *
  760. * \param ps: a pointer to a 'pcap_stat' structure, needed for compatibility
  761. * with pcap_stat(), where the structure is allocated by the user. In case
  762. * of pcap_stats_ex(), this structure and the function return value point
  763. * to the same variable.
  764. *
  765. * \param mode: one of PCAP_STATS_STANDARD or PCAP_STATS_EX.
  766. *
  767. * \return The structure that keeps the statistics, or NULL in case of error.
  768. * The error string is placed in the pcap_t structure.
  769. */
  770. static struct pcap_stat *rpcap_stats_rpcap(pcap_t *p, struct pcap_stat *ps, int mode)
  771. {
  772. struct pcap_rpcap *pr = p->priv; /* structure used when doing a remote live capture */
  773. struct rpcap_header header; /* header of the RPCAP packet */
  774. struct rpcap_stats netstats; /* statistics sent on the network */
  775. uint32 plen; /* data remaining in the message */
  776. #ifdef _WIN32
  777. if (mode != PCAP_STATS_STANDARD && mode != PCAP_STATS_EX)
  778. #else
  779. if (mode != PCAP_STATS_STANDARD)
  780. #endif
  781. {
  782. pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
  783. "Invalid stats mode %d", mode);
  784. return NULL;
  785. }
  786. /*
  787. * If the capture has not yet started, we cannot request statistics
  788. * for the capture from our peer, so we return 0 for all statistics,
  789. * as nothing's been seen yet.
  790. */
  791. if (!pr->rmt_capstarted)
  792. {
  793. ps->ps_drop = 0;
  794. ps->ps_ifdrop = 0;
  795. ps->ps_recv = 0;
  796. #ifdef _WIN32
  797. if (mode == PCAP_STATS_EX)
  798. {
  799. ps->ps_capt = 0;
  800. ps->ps_sent = 0;
  801. ps->ps_netdrop = 0;
  802. }
  803. #endif /* _WIN32 */
  804. return ps;
  805. }
  806. rpcap_createhdr(&header, pr->protocol_version,
  807. RPCAP_MSG_STATS_REQ, 0, 0);
  808. /* Send the PCAP_STATS command */
  809. if (sock_send(pr->rmt_sockctrl, (char *)&header,
  810. sizeof(struct rpcap_header), p->errbuf, PCAP_ERRBUF_SIZE) < 0)
  811. return NULL; /* Unrecoverable network error */
  812. /* Receive and process the reply message header. */
  813. if (rpcap_process_msg_header(pr->rmt_sockctrl, pr->protocol_version,
  814. RPCAP_MSG_STATS_REQ, &header, p->errbuf) == -1)
  815. return NULL; /* Error */
  816. plen = header.plen;
  817. /* Read the reply body */
  818. if (rpcap_recv(pr->rmt_sockctrl, (char *)&netstats,
  819. sizeof(struct rpcap_stats), &plen, p->errbuf) == -1)
  820. goto error;
  821. ps->ps_drop = ntohl(netstats.krnldrop);
  822. ps->ps_ifdrop = ntohl(netstats.ifdrop);
  823. ps->ps_recv = ntohl(netstats.ifrecv);
  824. #ifdef _WIN32
  825. if (mode == PCAP_STATS_EX)
  826. {
  827. ps->ps_capt = pr->TotCapt;
  828. ps->ps_netdrop = pr->TotNetDrops;
  829. ps->ps_sent = ntohl(netstats.svrcapt);
  830. }
  831. #endif /* _WIN32 */
  832. /* Discard the rest of the message. */
  833. if (rpcap_discard(pr->rmt_sockctrl, plen, p->errbuf) == -1)
  834. goto error_nodiscard;
  835. return ps;
  836. error:
  837. /*
  838. * Discard the rest of the message.
  839. * We already reported an error; if this gets an error, just
  840. * drive on.
  841. */
  842. (void)rpcap_discard(pr->rmt_sockctrl, plen, NULL);
  843. error_nodiscard:
  844. return NULL;
  845. }
  846. /*
  847. * This function returns the entry in the list of active hosts for this
  848. * active connection (active mode only), or NULL if there is no
  849. * active connection or an error occurred. It is just for internal
  850. * use.
  851. *
  852. * \param host: a string that keeps the host name of the host for which we
  853. * want to get the socket ID for that active connection.
  854. *
  855. * \param error: a pointer to an int that is set to 1 if an error occurred
  856. * and 0 otherwise.
  857. *
  858. * \param errbuf: a pointer to a user-allocated buffer (of size
  859. * PCAP_ERRBUF_SIZE) that will contain the error message (in case
  860. * there is one).
  861. *
  862. * \return the entry for this host in the list of active connections
  863. * if found, NULL if it's not found or there's an error.
  864. */
  865. static struct activehosts *
  866. rpcap_remoteact_getsock(const char *host, int *error, char *errbuf)
  867. {
  868. struct activehosts *temp; /* temp var needed to scan the host list chain */
  869. struct addrinfo hints, *addrinfo, *ai_next; /* temp var needed to translate between hostname to its address */
  870. int retval;
  871. /* retrieve the network address corresponding to 'host' */
  872. addrinfo = NULL;
  873. memset(&hints, 0, sizeof(struct addrinfo));
  874. hints.ai_family = PF_UNSPEC;
  875. hints.ai_socktype = SOCK_STREAM;
  876. retval = getaddrinfo(host, "0", &hints, &addrinfo);
  877. if (retval != 0)
  878. {
  879. pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "getaddrinfo() %s",
  880. gai_strerror(retval));
  881. *error = 1;
  882. return NULL;
  883. }
  884. temp = activeHosts;
  885. while (temp)
  886. {
  887. ai_next = addrinfo;
  888. while (ai_next)
  889. {
  890. if (sock_cmpaddr(&temp->host, (struct sockaddr_storage *) ai_next->ai_addr) == 0)
  891. {
  892. *error = 0;
  893. freeaddrinfo(addrinfo);
  894. return temp;
  895. }
  896. ai_next = ai_next->ai_next;
  897. }
  898. temp = temp->next;
  899. }
  900. if (addrinfo)
  901. freeaddrinfo(addrinfo);
  902. /*
  903. * The host for which you want to get the socket ID does not have an
  904. * active connection.
  905. */
  906. *error = 0;
  907. return NULL;
  908. }
  909. /*
  910. * This function starts a remote capture.
  911. *
  912. * This function is required since the RPCAP protocol decouples the 'open'
  913. * from the 'start capture' functions.
  914. * This function takes all the parameters needed (which have been stored
  915. * into the pcap_t structure) and sends them to the server.
  916. *
  917. * \param fp: the pcap_t descriptor of the device currently open.
  918. *
  919. * \return '0' if everything is fine, '-1' otherwise. The error message
  920. * (if one) is returned into the 'errbuf' field of the pcap_t structure.
  921. */
  922. static int pcap_startcapture_remote(pcap_t *fp)
  923. {
  924. struct pcap_rpcap *pr = fp->priv; /* structure used when doing a remote live capture */
  925. char sendbuf[RPCAP_NETBUF_SIZE]; /* temporary buffer in which data to be sent is buffered */
  926. int sendbufidx = 0; /* index which keeps the number of bytes currently buffered */
  927. char portdata[PCAP_BUF_SIZE]; /* temp variable needed to keep the network port for the data connection */
  928. uint32 plen;
  929. int active = 0; /* '1' if we're in active mode */
  930. struct activehosts *temp; /* temp var needed to scan the host list chain, to detect if we're in active mode */
  931. char host[INET6_ADDRSTRLEN + 1]; /* numeric name of the other host */
  932. /* socket-related variables*/
  933. struct addrinfo hints; /* temp, needed to open a socket connection */
  934. struct addrinfo *addrinfo; /* temp, needed to open a socket connection */
  935. SOCKET sockdata = 0; /* socket descriptor of the data connection */
  936. struct sockaddr_storage saddr; /* temp, needed to retrieve the network data port chosen on the local machine */
  937. socklen_t saddrlen; /* temp, needed to retrieve the network data port chosen on the local machine */
  938. int ai_family; /* temp, keeps the address family used by the control connection */
  939. /* RPCAP-related variables*/
  940. struct rpcap_header header; /* header of the RPCAP packet */
  941. struct rpcap_startcapreq *startcapreq; /* start capture request message */
  942. struct rpcap_startcapreply startcapreply; /* start capture reply message */
  943. /* Variables related to the buffer setting */
  944. int res;
  945. socklen_t itemp;
  946. int sockbufsize = 0;
  947. uint32 server_sockbufsize;
  948. /*
  949. * Let's check if sampling has been required.
  950. * If so, let's set it first
  951. */
  952. if (pcap_setsampling_remote(fp) != 0)
  953. return -1;
  954. /* detect if we're in active mode */
  955. temp = activeHosts;
  956. while (temp)
  957. {
  958. if (temp->sockctrl == pr->rmt_sockctrl)
  959. {
  960. active = 1;
  961. break;
  962. }
  963. temp = temp->next;
  964. }
  965. addrinfo = NULL;
  966. /*
  967. * Gets the complete sockaddr structure used in the ctrl connection
  968. * This is needed to get the address family of the control socket
  969. * Tip: I cannot save the ai_family of the ctrl sock in the pcap_t struct,
  970. * since the ctrl socket can already be open in case of active mode;
  971. * so I would have to call getpeername() anyway
  972. */
  973. saddrlen = sizeof(struct sockaddr_storage);
  974. if (getpeername(pr->rmt_sockctrl, (struct sockaddr *) &saddr, &saddrlen) == -1)
  975. {
  976. sock_geterror("getsockname(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
  977. goto error_nodiscard;
  978. }
  979. ai_family = ((struct sockaddr_storage *) &saddr)->ss_family;
  980. /* Get the numeric address of the remote host we are connected to */
  981. if (getnameinfo((struct sockaddr *) &saddr, saddrlen, host,
  982. sizeof(host), NULL, 0, NI_NUMERICHOST))
  983. {
  984. sock_geterror("getnameinfo(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
  985. goto error_nodiscard;
  986. }
  987. /*
  988. * Data connection is opened by the server toward the client if:
  989. * - we're using TCP, and the user wants us to be in active mode
  990. * - we're using UDP
  991. */
  992. if ((active) || (pr->rmt_flags & PCAP_OPENFLAG_DATATX_UDP))
  993. {
  994. /*
  995. * We have to create a new socket to receive packets
  996. * We have to do that immediately, since we have to tell the other
  997. * end which network port we picked up
  998. */
  999. memset(&hints, 0, sizeof(struct addrinfo));
  1000. /* TEMP addrinfo is NULL in case of active */
  1001. hints.ai_family = ai_family; /* Use the same address family of the control socket */
  1002. hints.ai_socktype = (pr->rmt_flags & PCAP_OPENFLAG_DATATX_UDP) ? SOCK_DGRAM : SOCK_STREAM;
  1003. hints.ai_flags = AI_PASSIVE; /* Data connection is opened by the server toward the client */
  1004. /* Let's the server pick up a free network port for us */
  1005. if (sock_initaddress(NULL, "0", &hints, &addrinfo, fp->errbuf, PCAP_ERRBUF_SIZE) == -1)
  1006. goto error_nodiscard;
  1007. if ((sockdata = sock_open(addrinfo, SOCKOPEN_SERVER,
  1008. 1 /* max 1 connection in queue */, fp->errbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET)
  1009. goto error_nodiscard;
  1010. /* addrinfo is no longer used */
  1011. freeaddrinfo(addrinfo);
  1012. addrinfo = NULL;
  1013. /* get the complete sockaddr structure used in the data connection */
  1014. saddrlen = sizeof(struct sockaddr_storage);
  1015. if (getsockname(sockdata, (struct sockaddr *) &saddr, &saddrlen) == -1)
  1016. {
  1017. sock_geterror("getsockname(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
  1018. goto error_nodiscard;
  1019. }
  1020. /* Get the local port the system picked up */
  1021. if (getnameinfo((struct sockaddr *) &saddr, saddrlen, NULL,
  1022. 0, portdata, sizeof(portdata), NI_NUMERICSERV))
  1023. {
  1024. sock_geterror("getnameinfo(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
  1025. goto error_nodiscard;
  1026. }
  1027. }
  1028. /*
  1029. * Now it's time to start playing with the RPCAP protocol
  1030. * RPCAP start capture command: create the request message
  1031. */
  1032. if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
  1033. &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, fp->errbuf, PCAP_ERRBUF_SIZE))
  1034. goto error_nodiscard;
  1035. rpcap_createhdr((struct rpcap_header *) sendbuf,
  1036. pr->protocol_version, RPCAP_MSG_STARTCAP_REQ, 0,
  1037. sizeof(struct rpcap_startcapreq) + sizeof(struct rpcap_filter) + fp->fcode.bf_len * sizeof(struct rpcap_filterbpf_insn));
  1038. /* Fill the structure needed to open an adapter remotely */
  1039. startcapreq = (struct rpcap_startcapreq *) &sendbuf[sendbufidx];
  1040. if (sock_bufferize(NULL, sizeof(struct rpcap_startcapreq), NULL,
  1041. &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, fp->errbuf, PCAP_ERRBUF_SIZE))
  1042. goto error_nodiscard;
  1043. memset(startcapreq, 0, sizeof(struct rpcap_startcapreq));
  1044. /* By default, apply half the timeout on one side, half of the other */
  1045. fp->opt.timeout = fp->opt.timeout / 2;
  1046. startcapreq->read_timeout = htonl(fp->opt.timeout);
  1047. /* portdata on the openreq is meaningful only if we're in active mode */
  1048. if ((active) || (pr->rmt_flags & PCAP_OPENFLAG_DATATX_UDP))
  1049. {
  1050. sscanf(portdata, "%d", (int *)&(startcapreq->portdata)); /* cast to avoid a compiler warning */
  1051. startcapreq->portdata = htons(startcapreq->portdata);
  1052. }
  1053. startcapreq->snaplen = htonl(fp->snapshot);
  1054. startcapreq->flags = 0;
  1055. if (pr->rmt_flags & PCAP_OPENFLAG_PROMISCUOUS)
  1056. startcapreq->flags |= RPCAP_STARTCAPREQ_FLAG_PROMISC;
  1057. if (pr->rmt_flags & PCAP_OPENFLAG_DATATX_UDP)
  1058. startcapreq->flags |= RPCAP_STARTCAPREQ_FLAG_DGRAM;
  1059. if (active)
  1060. startcapreq->flags |= RPCAP_STARTCAPREQ_FLAG_SERVEROPEN;
  1061. startcapreq->flags = htons(startcapreq->flags);
  1062. /* Pack the capture filter */
  1063. if (pcap_pack_bpffilter(fp, &sendbuf[sendbufidx], &sendbufidx, &fp->fcode))
  1064. goto error_nodiscard;
  1065. if (sock_send(pr->rmt_sockctrl, sendbuf, sendbufidx, fp->errbuf,
  1066. PCAP_ERRBUF_SIZE) < 0)
  1067. goto error_nodiscard;
  1068. /* Receive and process the reply message header. */
  1069. if (rpcap_process_msg_header(pr->rmt_sockctrl, pr->protocol_version,
  1070. RPCAP_MSG_STARTCAP_REQ, &header, fp->errbuf) == -1)
  1071. goto error_nodiscard;
  1072. plen = header.plen;
  1073. if (rpcap_recv(pr->rmt_sockctrl, (char *)&startcapreply,
  1074. sizeof(struct rpcap_startcapreply), &plen, fp->errbuf) == -1)
  1075. goto error;
  1076. /*
  1077. * In case of UDP data stream, the connection is always opened by the daemon
  1078. * So, this case is already covered by the code above.
  1079. * Now, we have still to handle TCP connections, because:
  1080. * - if we're in active mode, we have to wait for a remote connection
  1081. * - if we're in passive more, we have to start a connection
  1082. *
  1083. * We have to do he job in two steps because in case we're opening a TCP connection, we have
  1084. * to tell the port we're using to the remote side; in case we're accepting a TCP
  1085. * connection, we have to wait this info from the remote side.
  1086. */
  1087. if (!(pr->rmt_flags & PCAP_OPENFLAG_DATATX_UDP))
  1088. {
  1089. if (!active)
  1090. {
  1091. memset(&hints, 0, sizeof(struct addrinfo));
  1092. hints.ai_family = ai_family; /* Use the same address family of the control socket */
  1093. hints.ai_socktype = (pr->rmt_flags & PCAP_OPENFLAG_DATATX_UDP) ? SOCK_DGRAM : SOCK_STREAM;
  1094. pcap_snprintf(portdata, PCAP_BUF_SIZE, "%d", ntohs(startcapreply.portdata));
  1095. /* Let's the server pick up a free network port for us */
  1096. if (sock_initaddress(host, portdata, &hints, &addrinfo, fp->errbuf, PCAP_ERRBUF_SIZE) == -1)
  1097. goto error;
  1098. if ((sockdata = sock_open(addrinfo, SOCKOPEN_CLIENT, 0, fp->errbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET)
  1099. goto error;
  1100. /* addrinfo is no longer used */
  1101. freeaddrinfo(addrinfo);
  1102. addrinfo = NULL;
  1103. }
  1104. else
  1105. {
  1106. SOCKET socktemp; /* We need another socket, since we're going to accept() a connection */
  1107. /* Connection creation */
  1108. saddrlen = sizeof(struct sockaddr_storage);
  1109. socktemp = accept(sockdata, (struct sockaddr *) &saddr, &saddrlen);
  1110. if (socktemp == INVALID_SOCKET)
  1111. {
  1112. sock_geterror("accept(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
  1113. goto error;
  1114. }
  1115. /* Now that I accepted the connection, the server socket is no longer needed */
  1116. sock_close(sockdata, fp->errbuf, PCAP_ERRBUF_SIZE);
  1117. sockdata = socktemp;
  1118. }
  1119. }
  1120. /* Let's save the socket of the data connection */
  1121. pr->rmt_sockdata = sockdata;
  1122. /*
  1123. * Set the size of the socket buffer for the data socket.
  1124. * It has the same size as the local capture buffer used
  1125. * on the other side of the connection.
  1126. */
  1127. server_sockbufsize = ntohl(startcapreply.bufsize);
  1128. /* Let's get the actual size of the socket buffer */
  1129. itemp = sizeof(sockbufsize);
  1130. res = getsockopt(sockdata, SOL_SOCKET, SO_RCVBUF, (char *)&sockbufsize, &itemp);
  1131. if (res == -1)
  1132. {
  1133. sock_geterror("pcap_startcapture_remote()", fp->errbuf, PCAP_ERRBUF_SIZE);
  1134. SOCK_DEBUG_MESSAGE(fp->errbuf);
  1135. }
  1136. /*
  1137. * Warning: on some kernels (e.g. Linux), the size of the user
  1138. * buffer does not take into account the pcap_header and such,
  1139. * and it is set equal to the snaplen.
  1140. *
  1141. * In my view, this is wrong (the meaning of the bufsize became
  1142. * a bit strange). So, here bufsize is the whole size of the
  1143. * user buffer. In case the bufsize returned is too small,
  1144. * let's adjust it accordingly.
  1145. */
  1146. if (server_sockbufsize <= (u_int) fp->snapshot)
  1147. server_sockbufsize += sizeof(struct pcap_pkthdr);
  1148. /* if the current socket buffer is smaller than the desired one */
  1149. if ((u_int) sockbufsize < server_sockbufsize)
  1150. {
  1151. /*
  1152. * Loop until the buffer size is OK or the original
  1153. * socket buffer size is larger than this one.
  1154. */
  1155. for (;;)
  1156. {
  1157. res = setsockopt(sockdata, SOL_SOCKET, SO_RCVBUF,
  1158. (char *)&(server_sockbufsize),
  1159. sizeof(server_sockbufsize));
  1160. if (res == 0)
  1161. break;
  1162. /*
  1163. * If something goes wrong, halve the buffer size
  1164. * (checking that it does not become smaller than
  1165. * the current one).
  1166. */
  1167. server_sockbufsize /= 2;
  1168. if ((u_int) sockbufsize >= server_sockbufsize)
  1169. {
  1170. server_sockbufsize = sockbufsize;
  1171. break;
  1172. }
  1173. }
  1174. }
  1175. /*
  1176. * Let's allocate the packet; this is required in order to put
  1177. * the packet somewhere when extracting data from the socket.
  1178. * Since buffering has already been done in the socket buffer,
  1179. * here we need just a buffer whose size is equal to the
  1180. * largest possible packet message for the snapshot size,
  1181. * namely the length of the message header plus the length
  1182. * of the packet header plus the snapshot length.
  1183. */
  1184. fp->bufsize = sizeof(struct rpcap_header) + sizeof(struct rpcap_pkthdr) + fp->snapshot;
  1185. fp->buffer = (u_char *)malloc(fp->bufsize);
  1186. if (fp->buffer == NULL)
  1187. {
  1188. pcap_fmt_errmsg_for_errno(fp->errbuf, PCAP_ERRBUF_SIZE,
  1189. errno, "malloc");
  1190. goto error;
  1191. }
  1192. /*
  1193. * The buffer is currently empty.
  1194. */
  1195. fp->bp = fp->buffer;
  1196. fp->cc = 0;
  1197. /* Discard the rest of the message. */
  1198. if (rpcap_discard(pr->rmt_sockctrl, plen, fp->errbuf) == -1)
  1199. goto error_nodiscard;
  1200. /*
  1201. * In case the user does not want to capture RPCAP packets, let's update the filter
  1202. * We have to update it here (instead of sending it into the 'StartCapture' message
  1203. * because when we generate the 'start capture' we do not know (yet) all the ports
  1204. * we're currently using.
  1205. */
  1206. if (pr->rmt_flags & PCAP_OPENFLAG_NOCAPTURE_RPCAP)
  1207. {
  1208. struct bpf_program fcode;
  1209. if (pcap_createfilter_norpcappkt(fp, &fcode) == -1)
  1210. goto error;
  1211. /* We cannot use 'pcap_setfilter_rpcap' because formally the capture has not been started yet */
  1212. /* (the 'pr->rmt_capstarted' variable will be updated some lines below) */
  1213. if (pcap_updatefilter_remote(fp, &fcode) == -1)
  1214. goto error;
  1215. pcap_freecode(&fcode);
  1216. }
  1217. pr->rmt_capstarted = 1;
  1218. return 0;
  1219. error:
  1220. /*
  1221. * When the connection has been established, we have to close it. So, at the
  1222. * beginning of this function, if an error occur we return immediately with
  1223. * a return NULL; when the connection is established, we have to come here
  1224. * ('goto error;') in order to close everything properly.
  1225. */
  1226. /*
  1227. * Discard the rest of the message.
  1228. * We already reported an error; if this gets an error, just
  1229. * drive on.
  1230. */
  1231. (void)rpcap_discard(pr->rmt_sockctrl, plen, NULL);
  1232. error_nodiscard:
  1233. if ((sockdata) && (sockdata != -1)) /* we can be here because sockdata said 'error' */
  1234. sock_close(sockdata, NULL, 0);
  1235. if (!active)
  1236. sock_close(pr->rmt_sockctrl, NULL, 0);
  1237. if (addrinfo != NULL)
  1238. freeaddrinfo(addrinfo);
  1239. /*
  1240. * We do not have to call pcap_close() here, because this function is always called
  1241. * by the user in case something bad happens
  1242. */
  1243. #if 0
  1244. if (fp)
  1245. {
  1246. pcap_close(fp);
  1247. fp= NULL;
  1248. }
  1249. #endif
  1250. return -1;
  1251. }
  1252. /*
  1253. * This function takes a bpf program and sends it to the other host.
  1254. *
  1255. * This function can be called in two cases:
  1256. * - pcap_startcapture_remote() is called (we have to send the filter
  1257. * along with the 'start capture' command)
  1258. * - we want to udpate the filter during a capture (i.e. pcap_setfilter()
  1259. * after the capture has been started)
  1260. *
  1261. * This function serializes the filter into the sending buffer ('sendbuf',
  1262. * passed as a parameter) and return back. It does not send anything on
  1263. * the network.
  1264. *
  1265. * \param fp: the pcap_t descriptor of the device currently opened.
  1266. *
  1267. * \param sendbuf: the buffer on which the serialized data has to copied.
  1268. *
  1269. * \param sendbufidx: it is used to return the abounf of bytes copied into the buffer.
  1270. *
  1271. * \param prog: the bpf program we have to copy.
  1272. *
  1273. * \return '0' if everything is fine, '-1' otherwise. The error message (if one)
  1274. * is returned into the 'errbuf' field of the pcap_t structure.
  1275. */
  1276. static int pcap_pack_bpffilter(pcap_t *fp, char *sendbuf, int *sendbufidx, struct bpf_program *prog)
  1277. {
  1278. struct rpcap_filter *filter;
  1279. struct rpcap_filterbpf_insn *insn;
  1280. struct bpf_insn *bf_insn;
  1281. struct bpf_program fake_prog; /* To be used just in case the user forgot to set a filter */
  1282. unsigned int i;
  1283. if (prog->bf_len == 0) /* No filters have been specified; so, let's apply a "fake" filter */
  1284. {
  1285. if (pcap_compile(fp, &fake_prog, NULL /* buffer */, 1, 0) == -1)
  1286. return -1;
  1287. prog = &fake_prog;
  1288. }
  1289. filter = (struct rpcap_filter *) sendbuf;
  1290. if (sock_bufferize(NULL, sizeof(struct rpcap_filter), NULL, sendbufidx,
  1291. RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, fp->errbuf, PCAP_ERRBUF_SIZE))
  1292. return -1;
  1293. filter->filtertype = htons(RPCAP_UPDATEFILTER_BPF);
  1294. filter->nitems = htonl((int32)prog->bf_len);
  1295. if (sock_bufferize(NULL, prog->bf_len * sizeof(struct rpcap_filterbpf_insn),
  1296. NULL, sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, fp->errbuf, PCAP_ERRBUF_SIZE))
  1297. return -1;
  1298. insn = (struct rpcap_filterbpf_insn *) (filter + 1);
  1299. bf_insn = prog->bf_insns;
  1300. for (i = 0; i < prog->bf_len; i++)
  1301. {
  1302. insn->code = htons(bf_insn->code);
  1303. insn->jf = bf_insn->jf;
  1304. insn->jt = bf_insn->jt;
  1305. insn->k = htonl(bf_insn->k);
  1306. insn++;
  1307. bf_insn++;
  1308. }
  1309. return 0;
  1310. }
  1311. /*
  1312. * This function updates a filter on a remote host.
  1313. *
  1314. * It is called when the user wants to update a filter.
  1315. * In case we're capturing from the network, it sends the filter to our
  1316. * peer.
  1317. * This function is *not* called automatically when the user calls
  1318. * pcap_setfilter().
  1319. * There will be two cases:
  1320. * - the capture has been started: in this case, pcap_setfilter_rpcap()
  1321. * calls pcap_updatefilter_remote()
  1322. * - the capture has not started yet: in this case, pcap_setfilter_rpcap()
  1323. * stores the filter into the pcap_t structure, and then the filter is
  1324. * sent with pcap_startcap().
  1325. *
  1326. * WARNING This function *does not* clear the packet currently into the
  1327. * buffers. Therefore, the user has to expect to receive some packets
  1328. * that are related to the previous filter. If you want to discard all
  1329. * the packets before applying a new filter, you have to close the
  1330. * current capture session and start a new one.
  1331. *
  1332. * XXX - we really should have pcap_setfilter() always discard packets
  1333. * received with the old filter, and have a separate pcap_setfilter_noflush()
  1334. * function that doesn't discard any packets.
  1335. */
  1336. static int pcap_updatefilter_remote(pcap_t *fp, struct bpf_program *prog)
  1337. {
  1338. struct pcap_rpcap *pr = fp->priv; /* structure used when doing a remote live capture */
  1339. char sendbuf[RPCAP_NETBUF_SIZE]; /* temporary buffer in which data to be sent is buffered */
  1340. int sendbufidx = 0; /* index which keeps the number of bytes currently buffered */
  1341. struct rpcap_header header; /* To keep the reply message */
  1342. if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL, &sendbufidx,
  1343. RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, fp->errbuf, PCAP_ERRBUF_SIZE))
  1344. return -1;
  1345. rpcap_createhdr((struct rpcap_header *) sendbuf,
  1346. pr->protocol_version, RPCAP_MSG_UPDATEFILTER_REQ, 0,
  1347. sizeof(struct rpcap_filter) + prog->bf_len * sizeof(struct rpcap_filterbpf_insn));
  1348. if (pcap_pack_bpffilter(fp, &sendbuf[sendbufidx], &sendbufidx, prog))
  1349. return -1;
  1350. if (sock_send(pr->rmt_sockctrl, sendbuf, sendbufidx, fp->errbuf,
  1351. PCAP_ERRBUF_SIZE) < 0)
  1352. return -1;
  1353. /* Receive and process the reply message header. */
  1354. if (rpcap_process_msg_header(pr->rmt_sockctrl, pr->protocol_version,
  1355. RPCAP_MSG_UPDATEFILTER_REQ, &header, fp->errbuf) == -1)
  1356. return -1;
  1357. /*
  1358. * It shouldn't have any contents; discard it if it does.
  1359. */
  1360. if (rpcap_discard(pr->rmt_sockctrl, header.plen, fp->errbuf) == -1)
  1361. return -1;
  1362. return 0;
  1363. }
  1364. static void
  1365. pcap_save_current_filter_rpcap(pcap_t *fp, const char *filter)
  1366. {
  1367. struct pcap_rpcap *pr = fp->priv; /* structure used when doing a remote live capture */
  1368. /*
  1369. * Check if:
  1370. * - We are on an remote capture
  1371. * - we do not want to capture RPCAP traffic
  1372. *
  1373. * If so, we have to save the current filter, because we have to
  1374. * add some piece of stuff later
  1375. */
  1376. if (pr->rmt_clientside &&
  1377. (pr->rmt_flags & PCAP_OPENFLAG_NOCAPTURE_RPCAP))
  1378. {
  1379. if (pr->currentfilter)
  1380. free(pr->currentfilter);
  1381. if (filter == NULL)
  1382. filter = "";
  1383. pr->currentfilter = strdup(filter);
  1384. }
  1385. }
  1386. /*
  1387. * This function sends a filter to a remote host.
  1388. *
  1389. * This function is called when the user wants to set a filter.
  1390. * It sends the filter to our peer.
  1391. * This function is called automatically when the user calls pcap_setfilter().
  1392. *
  1393. * Parameters and return values are exactly the same of pcap_setfilter().
  1394. */
  1395. static int pcap_setfilter_rpcap(pcap_t *fp, struct bpf_program *prog)
  1396. {
  1397. struct pcap_rpcap *pr = fp->priv; /* structure used when doing a remote live capture */
  1398. if (!pr->rmt_capstarted)
  1399. {
  1400. /* copy filter into the pcap_t structure */
  1401. if (install_bpf_program(fp, prog) == -1)
  1402. return -1;
  1403. return 0;
  1404. }
  1405. /* we have to update a filter during run-time */
  1406. if (pcap_updatefilter_remote(fp, prog))
  1407. return -1;
  1408. return 0;
  1409. }
  1410. /*
  1411. * This function updates the current filter in order not to capture rpcap
  1412. * packets.
  1413. *
  1414. * This function is called *only* when the user wants exclude RPCAP packets
  1415. * related to the current session from the captured packets.
  1416. *
  1417. * \return '0' if everything is fine, '-1' otherwise. The error message (if one)
  1418. * is returned into the 'errbuf' field of the pcap_t structure.
  1419. */
  1420. static int pcap_createfilter_norpcappkt(pcap_t *fp, struct bpf_program *prog)
  1421. {
  1422. struct pcap_rpcap *pr = fp->priv; /* structure used when doing a remote live capture */
  1423. int RetVal = 0;
  1424. /* We do not want to capture our RPCAP traffic. So, let's update the filter */
  1425. if (pr->rmt_flags & PCAP_OPENFLAG_NOCAPTURE_RPCAP)
  1426. {
  1427. struct sockaddr_storage saddr; /* temp, needed to retrieve the network data port chosen on the local machine */
  1428. socklen_t saddrlen; /* temp, needed to retrieve the network data port chosen on the local machine */
  1429. char myaddress[128];
  1430. char myctrlport[128];
  1431. char mydataport[128];
  1432. char peeraddress[128];
  1433. char peerctrlport[128];
  1434. char *newfilter;
  1435. const int newstringsize = 1024;
  1436. size_t currentfiltersize;
  1437. /* Get the name/port of our peer */
  1438. saddrlen = sizeof(struct sockaddr_storage);
  1439. if (getpeername(pr->rmt_sockctrl, (struct sockaddr *) &saddr, &saddrlen) == -1)
  1440. {
  1441. sock_geterror("getpeername(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
  1442. return -1;
  1443. }
  1444. if (getnameinfo((struct sockaddr *) &saddr, saddrlen, peeraddress,
  1445. sizeof(peeraddress), peerctrlport, sizeof(peerctrlport), NI_NUMERICHOST | NI_NUMERICSERV))
  1446. {
  1447. sock_geterror("getnameinfo(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
  1448. return -1;
  1449. }
  1450. /* We cannot check the data port, because this is available only in case of TCP sockets */
  1451. /* Get the name/port of the current host */
  1452. if (getsockname(pr->rmt_sockctrl, (struct sockaddr *) &saddr, &saddrlen) == -1)
  1453. {
  1454. sock_geterror("getsockname(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
  1455. return -1;
  1456. }
  1457. /* Get the local port the system picked up */
  1458. if (getnameinfo((struct sockaddr *) &saddr, saddrlen, myaddress,
  1459. sizeof(myaddress), myctrlport, sizeof(myctrlport), NI_NUMERICHOST | NI_NUMERICSERV))
  1460. {
  1461. sock_geterror("getnameinfo(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
  1462. return -1;
  1463. }
  1464. /* Let's now check the data port */
  1465. if (getsockname(pr->rmt_sockdata, (struct sockaddr *) &saddr, &saddrlen) == -1)
  1466. {
  1467. sock_geterror("getsockname(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
  1468. return -1;
  1469. }
  1470. /* Get the local port the system picked up */
  1471. if (getnameinfo((struct sockaddr *) &saddr, saddrlen, NULL, 0, mydataport, sizeof(mydataport), NI_NUMERICSERV))
  1472. {
  1473. sock_geterror("getnameinfo(): ", fp->errbuf, PCAP_ERRBUF_SIZE);
  1474. return -1;
  1475. }
  1476. currentfiltersize = pr->currentfilter ? strlen(pr->currentfilter) : 0;
  1477. newfilter = (char *)malloc(currentfiltersize + newstringsize + 1);
  1478. if (currentfiltersize)
  1479. {
  1480. pcap_snprintf(newfilter, currentfiltersize + newstringsize,
  1481. "(%s) and not (host %s and host %s and port %s and port %s) and not (host %s and host %s and port %s)",
  1482. pr->currentfilter, myaddress, peeraddress, myctrlport, peerctrlport, myaddress, peeraddress, mydataport);
  1483. }
  1484. else
  1485. {
  1486. pcap_snprintf(newfilter, currentfiltersize + newstringsize,
  1487. "not (host %s and host %s and port %s and port %s) and not (host %s and host %s and port %s)",
  1488. myaddress, peeraddress, myctrlport, peerctrlport, myaddress, peeraddress, mydataport);
  1489. }
  1490. newfilter[currentfiltersize + newstringsize] = 0;
  1491. /*
  1492. * This is only an hack to prevent the save_current_filter
  1493. * routine, which will be called when we call pcap_compile(),
  1494. * from saving the modified filter.
  1495. */
  1496. pr->rmt_clientside = 0;
  1497. if (pcap_compile(fp, prog, newfilter, 1, 0) == -1)
  1498. RetVal = -1;
  1499. /* Undo the hack. */
  1500. pr->rmt_clientside = 1;
  1501. free(newfilter);
  1502. }
  1503. return RetVal;
  1504. }
  1505. /*
  1506. * This function sets sampling parameters in the remote host.
  1507. *
  1508. * It is called when the user wants to set activate sampling on the
  1509. * remote host.
  1510. *
  1511. * Sampling parameters are defined into the 'pcap_t' structure.
  1512. *
  1513. * \param p: the pcap_t descriptor of the device currently opened.
  1514. *
  1515. * \return '0' if everything is OK, '-1' is something goes wrong. The
  1516. * error message is returned in the 'errbuf' member of the pcap_t structure.
  1517. */
  1518. static int pcap_setsampling_remote(pcap_t *fp)
  1519. {
  1520. struct pcap_rpcap *pr = fp->priv; /* structure used when doing a remote live capture */
  1521. char sendbuf[RPCAP_NETBUF_SIZE];/* temporary buffer in which data to be sent is buffered */
  1522. int sendbufidx = 0; /* index which keeps the number of bytes currently buffered */
  1523. struct rpcap_header header; /* To keep the reply message */
  1524. struct rpcap_sampling *sampling_pars; /* Structure that is needed to send sampling parameters to the remote host */
  1525. /* If no samping is requested, return 'ok' */
  1526. if (fp->rmt_samp.method == PCAP_SAMP_NOSAMP)
  1527. return 0;
  1528. /*
  1529. * Check for sampling parameters that don't fit in a message.
  1530. * We'll let the server complain about invalid parameters
  1531. * that do fit into the message.
  1532. */
  1533. if (fp->rmt_samp.method < 0 || fp->rmt_samp.method > 255) {
  1534. pcap_snprintf(fp->errbuf, PCAP_ERRBUF_SIZE,
  1535. "Invalid sampling method %d", fp->rmt_samp.method);
  1536. return -1;
  1537. }
  1538. if (fp->rmt_samp.value < 0 || fp->rmt_samp.value > 65535) {
  1539. pcap_snprintf(fp->errbuf, PCAP_ERRBUF_SIZE,
  1540. "Invalid sampling value %d", fp->rmt_samp.value);
  1541. return -1;
  1542. }
  1543. if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
  1544. &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, fp->errbuf, PCAP_ERRBUF_SIZE))
  1545. return -1;
  1546. rpcap_createhdr((struct rpcap_header *) sendbuf,
  1547. pr->protocol_version, RPCAP_MSG_SETSAMPLING_REQ, 0,
  1548. sizeof(struct rpcap_sampling));
  1549. /* Fill the structure needed to open an adapter remotely */
  1550. sampling_pars = (struct rpcap_sampling *) &sendbuf[sendbufidx];
  1551. if (sock_bufferize(NULL, sizeof(struct rpcap_sampling), NULL,
  1552. &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, fp->errbuf, PCAP_ERRBUF_SIZE))
  1553. return -1;
  1554. memset(sampling_pars, 0, sizeof(struct rpcap_sampling));
  1555. sampling_pars->method = (uint8)fp->rmt_samp.method;
  1556. sampling_pars->value = (uint16)htonl(fp->rmt_samp.value);
  1557. if (sock_send(pr->rmt_sockctrl, sendbuf, sendbufidx, fp->errbuf,
  1558. PCAP_ERRBUF_SIZE) < 0)
  1559. return -1;
  1560. /* Receive and process the reply message header. */
  1561. if (rpcap_process_msg_header(pr->rmt_sockctrl, pr->protocol_version,
  1562. RPCAP_MSG_SETSAMPLING_REQ, &header, fp->errbuf) == -1)
  1563. return -1;
  1564. /*
  1565. * It shouldn't have any contents; discard it if it does.
  1566. */
  1567. if (rpcap_discard(pr->rmt_sockctrl, header.plen, fp->errbuf) == -1)
  1568. return -1;
  1569. return 0;
  1570. }
  1571. /*********************************************************
  1572. * *
  1573. * Miscellaneous functions *
  1574. * *
  1575. *********************************************************/
  1576. /*
  1577. * This function performs authentication and protocol version
  1578. * negotiation. It first tries to authenticate with the maximum
  1579. * version we support and, if that fails with an "I don't support
  1580. * that version" error from the server, and the version number in
  1581. * the reply from the server is one we support, tries again with
  1582. * that version.
  1583. *
  1584. * \param sock: the socket we are currently using.
  1585. *
  1586. * \param ver: pointer to variable holding protocol version number to send
  1587. * and to set to the protocol version number in the reply.
  1588. *
  1589. * \param auth: authentication parameters that have to be sent.
  1590. *
  1591. * \param errbuf: a pointer to a user-allocated buffer (of size
  1592. * PCAP_ERRBUF_SIZE) that will contain the error message (in case there
  1593. * is one). It could be a network problem or the fact that the authorization
  1594. * failed.
  1595. *
  1596. * \return '0' if everything is fine, '-1' for an error. For errors,
  1597. * an error message string is returned in the 'errbuf' variable.
  1598. */
  1599. static int rpcap_doauth(SOCKET sockctrl, uint8 *ver, struct pcap_rmtauth *auth, char *errbuf)
  1600. {
  1601. int status;
  1602. /*
  1603. * Send authentication to the remote machine.
  1604. *
  1605. * First try with the maximum version number we support.
  1606. */
  1607. *ver = RPCAP_MAX_VERSION;
  1608. status = rpcap_sendauth(sockctrl, ver, auth, errbuf);
  1609. if (status == 0)
  1610. {
  1611. //
  1612. // Success.
  1613. //
  1614. return 0;
  1615. }
  1616. if (status == -1)
  1617. {
  1618. /* Unrecoverable error. */
  1619. return -1;
  1620. }
  1621. /*
  1622. * The server doesn't support the version we used in the initial
  1623. * message, and it sent us back a reply either with the maximum
  1624. * version they do support, or with the version we sent, and we
  1625. * support that version. *ver has been set to that version; try
  1626. * authenticating again with that version.
  1627. */
  1628. status = rpcap_sendauth(sockctrl, ver, auth, errbuf);
  1629. if (status == 0)
  1630. {
  1631. //
  1632. // Success.
  1633. //
  1634. return 0;
  1635. }
  1636. if (status == -1)
  1637. {
  1638. /* Unrecoverable error. */
  1639. return -1;
  1640. }
  1641. if (status == -2)
  1642. {
  1643. /*
  1644. * The server doesn't support that version, which
  1645. * means there is no version we both support, so
  1646. * this is a fatal error.
  1647. */
  1648. pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "The server doesn't support any protocol version that we support");
  1649. return -1;
  1650. }
  1651. pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "rpcap_sendauth() returned %d", status);
  1652. return -1;
  1653. }
  1654. /*
  1655. * This function sends the authentication message.
  1656. *
  1657. * It sends the authentication parameters on the control socket.
  1658. * It is required in order to open the connection with the other end party.
  1659. *
  1660. * \param sock: the socket we are currently using.
  1661. *
  1662. * \param ver: pointer to variable holding protocol version number to send
  1663. * and to set to the protocol version number in the reply.
  1664. *
  1665. * \param auth: authentication parameters that have to be sent.
  1666. *
  1667. * \param errbuf: a pointer to a user-allocated buffer (of size
  1668. * PCAP_ERRBUF_SIZE) that will contain the error message (in case there
  1669. * is one). It could be a network problem or the fact that the authorization
  1670. * failed.
  1671. *
  1672. * \return '0' if everything is fine, '-2' if the server didn't reply with
  1673. * the protocol version we requested but replied with a version we do
  1674. * support, or '-1' for other errors. For errors, an error message string
  1675. * is returned in the 'errbuf' variable.
  1676. */
  1677. static int rpcap_sendauth(SOCKET sock, uint8 *ver, struct pcap_rmtauth *auth, char *errbuf)
  1678. {
  1679. char sendbuf[RPCAP_NETBUF_SIZE]; /* temporary buffer in which data that has to be sent is buffered */
  1680. int sendbufidx = 0; /* index which keeps the number of bytes currently buffered */
  1681. uint16 length; /* length of the payload of this message */
  1682. uint16 errcode;
  1683. struct rpcap_auth *rpauth;
  1684. uint16 auth_type;
  1685. struct rpcap_header header;
  1686. size_t str_length;
  1687. if (auth)
  1688. {
  1689. switch (auth->type)
  1690. {
  1691. case RPCAP_RMTAUTH_NULL:
  1692. length = sizeof(struct rpcap_auth);
  1693. break;
  1694. case RPCAP_RMTAUTH_PWD:
  1695. length = sizeof(struct rpcap_auth);
  1696. if (auth->username)
  1697. {
  1698. str_length = strlen(auth->username);
  1699. if (str_length > 65535)
  1700. {
  1701. pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "User name is too long (> 65535 bytes)");
  1702. return -1;
  1703. }
  1704. length += (uint16)str_length;
  1705. }
  1706. if (auth->password)
  1707. {
  1708. str_length = strlen(auth->password);
  1709. if (str_length > 65535)
  1710. {
  1711. pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Password is too long (> 65535 bytes)");
  1712. return -1;
  1713. }
  1714. length += (uint16)str_length;
  1715. }
  1716. break;
  1717. default:
  1718. pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication type not recognized.");
  1719. return -1;
  1720. }
  1721. auth_type = (uint16)auth->type;
  1722. }
  1723. else
  1724. {
  1725. auth_type = RPCAP_RMTAUTH_NULL;
  1726. length = sizeof(struct rpcap_auth);
  1727. }
  1728. if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
  1729. &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errbuf, PCAP_ERRBUF_SIZE))
  1730. return -1;
  1731. rpcap_createhdr((struct rpcap_header *) sendbuf, *ver,
  1732. RPCAP_MSG_AUTH_REQ, 0, length);
  1733. rpauth = (struct rpcap_auth *) &sendbuf[sendbufidx];
  1734. if (sock_bufferize(NULL, sizeof(struct rpcap_auth), NULL,
  1735. &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errbuf, PCAP_ERRBUF_SIZE))
  1736. return -1;
  1737. memset(rpauth, 0, sizeof(struct rpcap_auth));
  1738. rpauth->type = htons(auth_type);
  1739. if (auth_type == RPCAP_RMTAUTH_PWD)
  1740. {
  1741. if (auth->username)
  1742. rpauth->slen1 = (uint16)strlen(auth->username);
  1743. else
  1744. rpauth->slen1 = 0;
  1745. if (sock_bufferize(auth->username, rpauth->slen1, sendbuf,
  1746. &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errbuf, PCAP_ERRBUF_SIZE))
  1747. return -1;
  1748. if (auth->password)
  1749. rpauth->slen2 = (uint16)strlen(auth->password);
  1750. else
  1751. rpauth->slen2 = 0;
  1752. if (sock_bufferize(auth->password, rpauth->slen2, sendbuf,
  1753. &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errbuf, PCAP_ERRBUF_SIZE))
  1754. return -1;
  1755. rpauth->slen1 = htons(rpauth->slen1);
  1756. rpauth->slen2 = htons(rpauth->slen2);
  1757. }
  1758. if (sock_send(sock, sendbuf, sendbufidx, errbuf, PCAP_ERRBUF_SIZE) < 0)
  1759. return -1;
  1760. /* Receive the reply */
  1761. if (rpcap_recv_msg_header(sock, &header, errbuf) == -1)
  1762. return -1;
  1763. if (rpcap_check_msg_type(sock, RPCAP_MSG_AUTH_REQ, &header,
  1764. &errcode, errbuf) == -1)
  1765. {
  1766. /* Error message - or something else, which is a protocol error. */
  1767. if (header.type == RPCAP_MSG_ERROR &&
  1768. errcode == PCAP_ERR_WRONGVER)
  1769. {
  1770. /*
  1771. * The server didn't support the version we sent,
  1772. * and replied with the maximum version it supports
  1773. * if our version was too big or with the version
  1774. * we sent if out version was too small.
  1775. *
  1776. * Do we also support it?
  1777. */
  1778. if (!RPCAP_VERSION_IS_SUPPORTED(header.ver))
  1779. {
  1780. /*
  1781. * No, so there's no version we both support.
  1782. * This is an unrecoverable error.
  1783. */
  1784. pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "The server doesn't support any protocol version that we support");
  1785. return -1;
  1786. }
  1787. /*
  1788. * OK, use that version, and tell our caller to
  1789. * try again.
  1790. */
  1791. *ver = header.ver;
  1792. return -2;
  1793. }
  1794. /*
  1795. * Other error - unrecoverable.
  1796. */
  1797. return -1;
  1798. }
  1799. /*
  1800. * OK, it's an authentication reply, so they're OK with the
  1801. * protocol version we sent.
  1802. *
  1803. * Discard the rest of it.
  1804. */
  1805. if (rpcap_discard(sock, header.plen, errbuf) == -1)
  1806. return -1;
  1807. return 0;
  1808. }
  1809. /* We don't currently support non-blocking mode. */
  1810. static int
  1811. pcap_getnonblock_rpcap(pcap_t *p)
  1812. {
  1813. pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
  1814. "Non-blocking mode isn't supported for capturing remotely with rpcap");
  1815. return (-1);
  1816. }
  1817. static int
  1818. pcap_setnonblock_rpcap(pcap_t *p, int nonblock _U_)
  1819. {
  1820. pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
  1821. "Non-blocking mode isn't supported for capturing remotely with rpcap");
  1822. return (-1);
  1823. }
  1824. /*
  1825. * This function opens a remote adapter by opening an RPCAP connection and
  1826. * so on.
  1827. *
  1828. * It does the job of pcap_open_live() for a remote interface; it's called
  1829. * by pcap_open() for remote interfaces.
  1830. *
  1831. * We do not start the capture until pcap_startcapture_remote() is called.
  1832. *
  1833. * This is because, when doing a remote capture, we cannot start capturing
  1834. * data as soon as the 'open adapter' command is sent. Suppose the remote
  1835. * adapter is already overloaded; if we start a capture (which, by default,
  1836. * has a NULL filter) the new traffic can saturate the network.
  1837. *
  1838. * Instead, we want to "open" the adapter, then send a "start capture"
  1839. * command only when we're ready to start the capture.
  1840. * This function does this job: it sends an "open adapter" command
  1841. * (according to the RPCAP protocol), but it does not start the capture.
  1842. *
  1843. * Since the other libpcap functions do not share this way of life, we
  1844. * have to do some dirty things in order to make everything work.
  1845. *
  1846. * \param source: see pcap_open().
  1847. * \param snaplen: see pcap_open().
  1848. * \param flags: see pcap_open().
  1849. * \param read_timeout: see pcap_open().
  1850. * \param auth: see pcap_open().
  1851. * \param errbuf: see pcap_open().
  1852. *
  1853. * \return a pcap_t pointer in case of success, NULL otherwise. In case of
  1854. * success, the pcap_t pointer can be used as a parameter to the following
  1855. * calls (pcap_compile() and so on). In case of problems, errbuf contains
  1856. * a text explanation of error.
  1857. *
  1858. * WARNING: In case we call pcap_compile() and the capture has not yet
  1859. * been started, the filter will be saved into the pcap_t structure,
  1860. * and it will be sent to the other host later (when
  1861. * pcap_startcapture_remote() is called).
  1862. */
  1863. pcap_t *pcap_open_rpcap(const char *source, int snaplen, int flags, int read_timeout, struct pcap_rmtauth *auth, char *errbuf)
  1864. {
  1865. pcap_t *fp;
  1866. char *source_str;
  1867. struct pcap_rpcap *pr; /* structure used when doing a remote live capture */
  1868. char host[PCAP_BUF_SIZE], ctrlport[PCAP_BUF_SIZE], iface[PCAP_BUF_SIZE];
  1869. struct activehosts *activeconn; /* active connection, if there is one */
  1870. int error; /* '1' if rpcap_remoteact_getsock returned an error */
  1871. SOCKET sockctrl;
  1872. uint8 protocol_version; /* negotiated protocol version */
  1873. int active;
  1874. uint32 plen;
  1875. char sendbuf[RPCAP_NETBUF_SIZE]; /* temporary buffer in which data to be sent is buffered */
  1876. int sendbufidx = 0; /* index which keeps the number of bytes currently buffered */
  1877. int retval; /* store the return value of the functions */
  1878. /* RPCAP-related variables */
  1879. struct rpcap_header header; /* header of the RPCAP packet */
  1880. struct rpcap_openreply openreply; /* open reply message */
  1881. fp = pcap_create_common(errbuf, sizeof (struct pcap_rpcap));
  1882. if (fp == NULL)
  1883. {
  1884. return NULL;
  1885. }
  1886. source_str = strdup(source);
  1887. if (source_str == NULL) {
  1888. pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
  1889. errno, "malloc");
  1890. return NULL;
  1891. }
  1892. /*
  1893. * Turn a negative snapshot value (invalid), a snapshot value of
  1894. * 0 (unspecified), or a value bigger than the normal maximum
  1895. * value, into the maximum allowed value.
  1896. *
  1897. * If some application really *needs* a bigger snapshot
  1898. * length, we should just increase MAXIMUM_SNAPLEN.
  1899. *
  1900. * XXX - should we leave this up to the remote server to
  1901. * do?
  1902. */
  1903. if (snaplen <= 0 || snaplen > MAXIMUM_SNAPLEN)
  1904. snaplen = MAXIMUM_SNAPLEN;
  1905. fp->opt.device = source_str;
  1906. fp->snapshot = snaplen;
  1907. fp->opt.timeout = read_timeout;
  1908. pr = fp->priv;
  1909. pr->rmt_flags = flags;
  1910. /*
  1911. * determine the type of the source (NULL, file, local, remote)
  1912. * You must have a valid source string even if we're in active mode, because otherwise
  1913. * the call to the following function will fail.
  1914. */
  1915. if (pcap_parsesrcstr(fp->opt.device, &retval, host, ctrlport, iface, errbuf) == -1)
  1916. {
  1917. pcap_close(fp);
  1918. return NULL;
  1919. }
  1920. if (retval != PCAP_SRC_IFREMOTE)
  1921. {
  1922. pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "This function is able to open only remote interfaces");
  1923. pcap_close(fp);
  1924. return NULL;
  1925. }
  1926. /*
  1927. * Warning: this call can be the first one called by the user.
  1928. * For this reason, we have to initialize the WinSock support.
  1929. */
  1930. if (sock_init(errbuf, PCAP_ERRBUF_SIZE) == -1)
  1931. {
  1932. pcap_close(fp);
  1933. return NULL;
  1934. }
  1935. /* Check for active mode */
  1936. activeconn = rpcap_remoteact_getsock(host, &error, errbuf);
  1937. if (activeconn != NULL)
  1938. {
  1939. sockctrl = activeconn->sockctrl;
  1940. protocol_version = activeconn->protocol_version;
  1941. active = 1;
  1942. }
  1943. else
  1944. {
  1945. struct addrinfo hints; /* temp, needed to open a socket connection */
  1946. struct addrinfo *addrinfo; /* temp, needed to open a socket connection */
  1947. if (error)
  1948. {
  1949. /*
  1950. * Call failed.
  1951. */
  1952. pcap_close(fp);
  1953. return NULL;
  1954. }
  1955. /*
  1956. * We're not in active mode; let's try to open a new
  1957. * control connection.
  1958. */
  1959. memset(&hints, 0, sizeof(struct addrinfo));
  1960. hints.ai_family = PF_UNSPEC;
  1961. hints.ai_socktype = SOCK_STREAM;
  1962. if (ctrlport[0] == 0)
  1963. {
  1964. /* the user chose not to specify the port */
  1965. if (sock_initaddress(host, RPCAP_DEFAULT_NETPORT, &hints, &addrinfo, errbuf, PCAP_ERRBUF_SIZE) == -1)
  1966. {
  1967. pcap_close(fp);
  1968. return NULL;
  1969. }
  1970. }
  1971. else
  1972. {
  1973. if (sock_initaddress(host, ctrlport, &hints, &addrinfo, errbuf, PCAP_ERRBUF_SIZE) == -1)
  1974. {
  1975. pcap_close(fp);
  1976. return NULL;
  1977. }
  1978. }
  1979. if ((sockctrl = sock_open(addrinfo, SOCKOPEN_CLIENT, 0, errbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET)
  1980. {
  1981. freeaddrinfo(addrinfo);
  1982. pcap_close(fp);
  1983. return NULL;
  1984. }
  1985. /* addrinfo is no longer used */
  1986. freeaddrinfo(addrinfo);
  1987. if (rpcap_doauth(sockctrl, &protocol_version, auth, errbuf) == -1)
  1988. {
  1989. sock_close(sockctrl, NULL, 0);
  1990. pcap_close(fp);
  1991. return NULL;
  1992. }
  1993. active = 0;
  1994. }
  1995. /*
  1996. * Now it's time to start playing with the RPCAP protocol
  1997. * RPCAP open command: create the request message
  1998. */
  1999. if (sock_bufferize(NULL, sizeof(struct rpcap_header), NULL,
  2000. &sendbufidx, RPCAP_NETBUF_SIZE, SOCKBUF_CHECKONLY, errbuf, PCAP_ERRBUF_SIZE))
  2001. goto error_nodiscard;
  2002. rpcap_createhdr((struct rpcap_header *) sendbuf, protocol_version,
  2003. RPCAP_MSG_OPEN_REQ, 0, (uint32) strlen(iface));
  2004. if (sock_bufferize(iface, (int) strlen(iface), sendbuf, &sendbufidx,
  2005. RPCAP_NETBUF_SIZE, SOCKBUF_BUFFERIZE, errbuf, PCAP_ERRBUF_SIZE))
  2006. goto error_nodiscard;
  2007. if (sock_send(sockctrl, sendbuf, sendbufidx, errbuf,
  2008. PCAP_ERRBUF_SIZE) < 0)
  2009. goto error_nodiscard;
  2010. /* Receive and process the reply message header. */
  2011. if (rpcap_process_msg_header(sockctrl, protocol_version,
  2012. RPCAP_MSG_OPEN_REQ, &header, errbuf) == -1)
  2013. goto error_nodiscard;
  2014. plen = header.plen;
  2015. /* Read the reply body */
  2016. if (rpcap_recv(sockctrl, (char *)&openreply,
  2017. sizeof(struct rpcap_openreply), &plen, errbuf) == -1)
  2018. goto error;
  2019. /* Discard the rest of the message, if there is any. */
  2020. if (rpcap_discard(pr->rmt_sockctrl, plen, errbuf) == -1)
  2021. goto error_nodiscard;
  2022. /* Set proper fields into the pcap_t struct */
  2023. fp->linktype = ntohl(openreply.linktype);
  2024. fp->tzoff = ntohl(openreply.tzoff);
  2025. pr->rmt_sockctrl = sockctrl;
  2026. pr->protocol_version = protocol_version;
  2027. pr->rmt_clientside = 1;
  2028. /* This code is duplicated from the end of this function */
  2029. fp->read_op = pcap_read_rpcap;
  2030. fp->save_current_filter_op = pcap_save_current_filter_rpcap;
  2031. fp->setfilter_op = pcap_setfilter_rpcap;
  2032. fp->getnonblock_op = pcap_getnonblock_rpcap;
  2033. fp->setnonblock_op = pcap_setnonblock_rpcap;
  2034. fp->stats_op = pcap_stats_rpcap;
  2035. #ifdef _WIN32
  2036. fp->stats_ex_op = pcap_stats_ex_rpcap;
  2037. #endif
  2038. fp->cleanup_op = pcap_cleanup_rpcap;
  2039. fp->activated = 1;
  2040. return fp;
  2041. error:
  2042. /*
  2043. * When the connection has been established, we have to close it. So, at the
  2044. * beginning of this function, if an error occur we return immediately with
  2045. * a return NULL; when the connection is established, we have to come here
  2046. * ('goto error;') in order to close everything properly.
  2047. */
  2048. /*
  2049. * Discard the rest of the message.
  2050. * We already reported an error; if this gets an error, just
  2051. * drive on.
  2052. */
  2053. (void)rpcap_discard(pr->rmt_sockctrl, plen, NULL);
  2054. error_nodiscard:
  2055. if (!active)
  2056. sock_close(sockctrl, NULL, 0);
  2057. pcap_close(fp);
  2058. return NULL;
  2059. }
  2060. /* String identifier to be used in the pcap_findalldevs_ex() */
  2061. #define PCAP_TEXT_SOURCE_ADAPTER "Network adapter"
  2062. /* String identifier to be used in the pcap_findalldevs_ex() */
  2063. #define PCAP_TEXT_SOURCE_ON_REMOTE_HOST "on remote node"
  2064. static void
  2065. freeaddr(struct pcap_addr *addr)
  2066. {
  2067. free(addr->addr);
  2068. free(addr->netmask);
  2069. free(addr->broadaddr);
  2070. free(addr->dstaddr);
  2071. free(addr);
  2072. }
  2073. int
  2074. pcap_findalldevs_ex_remote(char *source, struct pcap_rmtauth *auth, pcap_if_t **alldevs, char *errbuf)
  2075. {
  2076. struct activehosts *activeconn; /* active connection, if there is one */
  2077. int error; /* '1' if rpcap_remoteact_getsock returned an error */
  2078. uint8 protocol_version; /* protocol version */
  2079. SOCKET sockctrl; /* socket descriptor of the control connection */
  2080. uint32 plen;
  2081. struct rpcap_header header; /* structure that keeps the general header of the rpcap protocol */
  2082. int i, j; /* temp variables */
  2083. int nif; /* Number of interfaces listed */
  2084. int active; /* 'true' if we the other end-party is in active mode */
  2085. int type;
  2086. char host[PCAP_BUF_SIZE], port[PCAP_BUF_SIZE];
  2087. char tmpstring[PCAP_BUF_SIZE + 1]; /* Needed to convert names and descriptions from 'old' syntax to the 'new' one */
  2088. pcap_if_t *lastdev; /* Last device in the pcap_if_t list */
  2089. pcap_if_t *dev; /* Device we're adding to the pcap_if_t list */
  2090. /* List starts out empty. */
  2091. (*alldevs) = NULL;
  2092. lastdev = NULL;
  2093. /* Retrieve the needed data for getting adapter list */
  2094. if (pcap_parsesrcstr(source, &type, host, port, NULL, errbuf) == -1)
  2095. return -1;
  2096. /* Warning: this call can be the first one called by the user. */
  2097. /* For this reason, we have to initialize the WinSock support. */
  2098. if (sock_init(errbuf, PCAP_ERRBUF_SIZE) == -1)
  2099. return -1;
  2100. /* Check for active mode */
  2101. activeconn = rpcap_remoteact_getsock(host, &error, errbuf);
  2102. if (activeconn != NULL)
  2103. {
  2104. sockctrl = activeconn->sockctrl;
  2105. protocol_version = activeconn->protocol_version;
  2106. active = 1;
  2107. }
  2108. else
  2109. {
  2110. struct addrinfo hints; /* temp variable needed to resolve hostnames into to socket representation */
  2111. struct addrinfo *addrinfo; /* temp variable needed to resolve hostnames into to socket representation */
  2112. if (error)
  2113. {
  2114. /*
  2115. * Call failed.
  2116. */
  2117. return -1;
  2118. }
  2119. /*
  2120. * We're not in active mode; let's try to open a new
  2121. * control connection.
  2122. */
  2123. memset(&hints, 0, sizeof(struct addrinfo));
  2124. hints.ai_family = PF_UNSPEC;
  2125. hints.ai_socktype = SOCK_STREAM;
  2126. if (port[0] == 0)
  2127. {
  2128. /* the user chose not to specify the port */
  2129. if (sock_initaddress(host, RPCAP_DEFAULT_NETPORT, &hints, &addrinfo, errbuf, PCAP_ERRBUF_SIZE) == -1)
  2130. return -1;
  2131. }
  2132. else
  2133. {
  2134. if (sock_initaddress(host, port, &hints, &addrinfo, errbuf, PCAP_ERRBUF_SIZE) == -1)
  2135. return -1;
  2136. }
  2137. if ((sockctrl = sock_open(addrinfo, SOCKOPEN_CLIENT, 0, errbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET)
  2138. {
  2139. freeaddrinfo(addrinfo);
  2140. return -1;
  2141. }
  2142. /* addrinfo is no longer used */
  2143. freeaddrinfo(addrinfo);
  2144. addrinfo = NULL;
  2145. if (rpcap_doauth(sockctrl, &protocol_version, auth, errbuf) == -1)
  2146. {
  2147. sock_close(sockctrl, NULL, 0);
  2148. return -1;
  2149. }
  2150. active = 0;
  2151. }
  2152. /* RPCAP findalldevs command */
  2153. rpcap_createhdr(&header, protocol_version, RPCAP_MSG_FINDALLIF_REQ,
  2154. 0, 0);
  2155. if (sock_send(sockctrl, (char *)&header, sizeof(struct rpcap_header),
  2156. errbuf, PCAP_ERRBUF_SIZE) < 0)
  2157. goto error_nodiscard;
  2158. /* Receive and process the reply message header. */
  2159. if (rpcap_process_msg_header(sockctrl, protocol_version,
  2160. RPCAP_MSG_FINDALLIF_REQ, &header, errbuf) == -1)
  2161. goto error_nodiscard;
  2162. plen = header.plen;
  2163. /* read the number of interfaces */
  2164. nif = ntohs(header.value);
  2165. /* loop until all interfaces have been received */
  2166. for (i = 0; i < nif; i++)
  2167. {
  2168. struct rpcap_findalldevs_if findalldevs_if;
  2169. char tmpstring2[PCAP_BUF_SIZE + 1]; /* Needed to convert names and descriptions from 'old' syntax to the 'new' one */
  2170. size_t stringlen;
  2171. struct pcap_addr *addr, *prevaddr;
  2172. tmpstring2[PCAP_BUF_SIZE] = 0;
  2173. /* receive the findalldevs structure from remote host */
  2174. if (rpcap_recv(sockctrl, (char *)&findalldevs_if,
  2175. sizeof(struct rpcap_findalldevs_if), &plen, errbuf) == -1)
  2176. goto error;
  2177. findalldevs_if.namelen = ntohs(findalldevs_if.namelen);
  2178. findalldevs_if.desclen = ntohs(findalldevs_if.desclen);
  2179. findalldevs_if.naddr = ntohs(findalldevs_if.naddr);
  2180. /* allocate the main structure */
  2181. dev = (pcap_if_t *)malloc(sizeof(pcap_if_t));
  2182. if (dev == NULL)
  2183. {
  2184. pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
  2185. errno, "malloc() failed");
  2186. goto error;
  2187. }
  2188. /* Initialize the structure to 'zero' */
  2189. memset(dev, 0, sizeof(pcap_if_t));
  2190. /* Append it to the list. */
  2191. if (lastdev == NULL)
  2192. {
  2193. /*
  2194. * List is empty, so it's also the first device.
  2195. */
  2196. *alldevs = dev;
  2197. }
  2198. else
  2199. {
  2200. /*
  2201. * Append after the last device.
  2202. */
  2203. lastdev->next = dev;
  2204. }
  2205. /* It's now the last device. */
  2206. lastdev = dev;
  2207. /* allocate mem for name and description */
  2208. if (findalldevs_if.namelen)
  2209. {
  2210. if (findalldevs_if.namelen >= sizeof(tmpstring))
  2211. {
  2212. pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Interface name too long");
  2213. goto error;
  2214. }
  2215. /* Retrieve adapter name */
  2216. if (rpcap_recv(sockctrl, tmpstring,
  2217. findalldevs_if.namelen, &plen, errbuf) == -1)
  2218. goto error;
  2219. tmpstring[findalldevs_if.namelen] = 0;
  2220. /* Create the new device identifier */
  2221. if (pcap_createsrcstr(tmpstring2, PCAP_SRC_IFREMOTE, host, port, tmpstring, errbuf) == -1)
  2222. return -1;
  2223. stringlen = strlen(tmpstring2);
  2224. dev->name = (char *)malloc(stringlen + 1);
  2225. if (dev->name == NULL)
  2226. {
  2227. pcap_fmt_errmsg_for_errno(errbuf,
  2228. PCAP_ERRBUF_SIZE, errno, "malloc() failed");
  2229. goto error;
  2230. }
  2231. /* Copy the new device name into the correct memory location */
  2232. strlcpy(dev->name, tmpstring2, stringlen + 1);
  2233. }
  2234. if (findalldevs_if.desclen)
  2235. {
  2236. if (findalldevs_if.desclen >= sizeof(tmpstring))
  2237. {
  2238. pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Interface description too long");
  2239. goto error;
  2240. }
  2241. /* Retrieve adapter description */
  2242. if (rpcap_recv(sockctrl, tmpstring,
  2243. findalldevs_if.desclen, &plen, errbuf) == -1)
  2244. goto error;
  2245. tmpstring[findalldevs_if.desclen] = 0;
  2246. pcap_snprintf(tmpstring2, sizeof(tmpstring2) - 1, "%s '%s' %s %s", PCAP_TEXT_SOURCE_ADAPTER,
  2247. tmpstring, PCAP_TEXT_SOURCE_ON_REMOTE_HOST, host);
  2248. stringlen = strlen(tmpstring2);
  2249. dev->description = (char *)malloc(stringlen + 1);
  2250. if (dev->description == NULL)
  2251. {
  2252. pcap_fmt_errmsg_for_errno(errbuf,
  2253. PCAP_ERRBUF_SIZE, errno, "malloc() failed");
  2254. goto error;
  2255. }
  2256. /* Copy the new device description into the correct memory location */
  2257. strlcpy(dev->description, tmpstring2, stringlen + 1);
  2258. }
  2259. dev->flags = ntohl(findalldevs_if.flags);
  2260. prevaddr = NULL;
  2261. /* loop until all addresses have been received */
  2262. for (j = 0; j < findalldevs_if.naddr; j++)
  2263. {
  2264. struct rpcap_findalldevs_ifaddr ifaddr;
  2265. /* Retrieve the interface addresses */
  2266. if (rpcap_recv(sockctrl, (char *)&ifaddr,
  2267. sizeof(struct rpcap_findalldevs_ifaddr),
  2268. &plen, errbuf) == -1)
  2269. goto error;
  2270. /*
  2271. * Deserialize all the address components.
  2272. */
  2273. addr = (struct pcap_addr *) malloc(sizeof(struct pcap_addr));
  2274. if (addr == NULL)
  2275. {
  2276. pcap_fmt_errmsg_for_errno(errbuf,
  2277. PCAP_ERRBUF_SIZE, errno, "malloc() failed");
  2278. goto error;
  2279. }
  2280. addr->next = NULL;
  2281. addr->addr = NULL;
  2282. addr->netmask = NULL;
  2283. addr->broadaddr = NULL;
  2284. addr->dstaddr = NULL;
  2285. if (rpcap_deseraddr(&ifaddr.addr,
  2286. (struct sockaddr_storage **) &addr->addr, errbuf) == -1)
  2287. {
  2288. freeaddr(addr);
  2289. goto error;
  2290. }
  2291. if (rpcap_deseraddr(&ifaddr.netmask,
  2292. (struct sockaddr_storage **) &addr->netmask, errbuf) == -1)
  2293. {
  2294. freeaddr(addr);
  2295. goto error;
  2296. }
  2297. if (rpcap_deseraddr(&ifaddr.broadaddr,
  2298. (struct sockaddr_storage **) &addr->broadaddr, errbuf) == -1)
  2299. {
  2300. freeaddr(addr);
  2301. goto error;
  2302. }
  2303. if (rpcap_deseraddr(&ifaddr.dstaddr,
  2304. (struct sockaddr_storage **) &addr->dstaddr, errbuf) == -1)
  2305. {
  2306. freeaddr(addr);
  2307. goto error;
  2308. }
  2309. if ((addr->addr == NULL) && (addr->netmask == NULL) &&
  2310. (addr->broadaddr == NULL) && (addr->dstaddr == NULL))
  2311. {
  2312. /*
  2313. * None of the addresses are IPv4 or IPv6
  2314. * addresses, so throw this entry away.
  2315. */
  2316. free(addr);
  2317. }
  2318. else
  2319. {
  2320. /*
  2321. * Add this entry to the list.
  2322. */
  2323. if (prevaddr == NULL)
  2324. {
  2325. dev->addresses = addr;
  2326. }
  2327. else
  2328. {
  2329. prevaddr->next = addr;
  2330. }
  2331. prevaddr = addr;
  2332. }
  2333. }
  2334. }
  2335. /* Discard the rest of the message. */
  2336. if (rpcap_discard(sockctrl, plen, errbuf) == 1)
  2337. goto error_nodiscard;
  2338. /* Control connection has to be closed only in case the remote machine is in passive mode */
  2339. if (!active)
  2340. {
  2341. /* DO not send RPCAP_CLOSE, since we did not open a pcap_t; no need to free resources */
  2342. if (sock_close(sockctrl, errbuf, PCAP_ERRBUF_SIZE))
  2343. return -1;
  2344. }
  2345. /* To avoid inconsistencies in the number of sock_init() */
  2346. sock_cleanup();
  2347. return 0;
  2348. error:
  2349. /*
  2350. * In case there has been an error, I don't want to overwrite it with a new one
  2351. * if the following call fails. I want to return always the original error.
  2352. *
  2353. * Take care: this connection can already be closed when we try to close it.
  2354. * This happens because a previous error in the rpcapd, which requested to
  2355. * closed the connection. In that case, we already recognized that into the
  2356. * rpspck_isheaderok() and we already acknowledged the closing.
  2357. * In that sense, this call is useless here (however it is needed in case
  2358. * the client generates the error).
  2359. *
  2360. * Checks if all the data has been read; if not, discard the data in excess
  2361. */
  2362. (void) rpcap_discard(sockctrl, plen, NULL);
  2363. error_nodiscard:
  2364. /* Control connection has to be closed only in case the remote machine is in passive mode */
  2365. if (!active)
  2366. sock_close(sockctrl, NULL, 0);
  2367. /* To avoid inconsistencies in the number of sock_init() */
  2368. sock_cleanup();
  2369. /* Free whatever interfaces we've allocated. */
  2370. pcap_freealldevs(*alldevs);
  2371. return -1;
  2372. }
  2373. /*
  2374. * Active mode routines.
  2375. *
  2376. * The old libpcap API is somewhat ugly, and makes active mode difficult
  2377. * to implement; we provide some APIs for it that work only with rpcap.
  2378. */
  2379. SOCKET pcap_remoteact_accept(const char *address, const char *port, const char *hostlist, char *connectinghost, struct pcap_rmtauth *auth, char *errbuf)
  2380. {
  2381. /* socket-related variables */
  2382. struct addrinfo hints; /* temporary struct to keep settings needed to open the new socket */
  2383. struct addrinfo *addrinfo; /* keeps the addrinfo chain; required to open a new socket */
  2384. struct sockaddr_storage from; /* generic sockaddr_storage variable */
  2385. socklen_t fromlen; /* keeps the length of the sockaddr_storage variable */
  2386. SOCKET sockctrl; /* keeps the main socket identifier */
  2387. uint8 protocol_version; /* negotiated protocol version */
  2388. struct activehosts *temp, *prev; /* temp var needed to scan he host list chain */
  2389. *connectinghost = 0; /* just in case */
  2390. /* Prepare to open a new server socket */
  2391. memset(&hints, 0, sizeof(struct addrinfo));
  2392. /* WARNING Currently it supports only ONE socket family among ipv4 and IPv6 */
  2393. hints.ai_family = AF_INET; /* PF_UNSPEC to have both IPv4 and IPv6 server */
  2394. hints.ai_flags = AI_PASSIVE; /* Ready to a bind() socket */
  2395. hints.ai_socktype = SOCK_STREAM;
  2396. /* Warning: this call can be the first one called by the user. */
  2397. /* For this reason, we have to initialize the WinSock support. */
  2398. if (sock_init(errbuf, PCAP_ERRBUF_SIZE) == -1)
  2399. return (SOCKET)-1;
  2400. /* Do the work */
  2401. if ((port == NULL) || (port[0] == 0))
  2402. {
  2403. if (sock_initaddress(address, RPCAP_DEFAULT_NETPORT_ACTIVE, &hints, &addrinfo, errbuf, PCAP_ERRBUF_SIZE) == -1)
  2404. {
  2405. SOCK_DEBUG_MESSAGE(errbuf);
  2406. return (SOCKET)-2;
  2407. }
  2408. }
  2409. else
  2410. {
  2411. if (sock_initaddress(address, port, &hints, &addrinfo, errbuf, PCAP_ERRBUF_SIZE) == -1)
  2412. {
  2413. SOCK_DEBUG_MESSAGE(errbuf);
  2414. return (SOCKET)-2;
  2415. }
  2416. }
  2417. if ((sockmain = sock_open(addrinfo, SOCKOPEN_SERVER, 1, errbuf, PCAP_ERRBUF_SIZE)) == INVALID_SOCKET)
  2418. {
  2419. SOCK_DEBUG_MESSAGE(errbuf);
  2420. freeaddrinfo(addrinfo);
  2421. return (SOCKET)-2;
  2422. }
  2423. freeaddrinfo(addrinfo);
  2424. /* Connection creation */
  2425. fromlen = sizeof(struct sockaddr_storage);
  2426. sockctrl = accept(sockmain, (struct sockaddr *) &from, &fromlen);
  2427. /* We're not using sock_close, since we do not want to send a shutdown */
  2428. /* (which is not allowed on a non-connected socket) */
  2429. closesocket(sockmain);
  2430. sockmain = 0;
  2431. if (sockctrl == INVALID_SOCKET)
  2432. {
  2433. sock_geterror("accept(): ", errbuf, PCAP_ERRBUF_SIZE);
  2434. return (SOCKET)-2;
  2435. }
  2436. /* Get the numeric for of the name of the connecting host */
  2437. if (getnameinfo((struct sockaddr *) &from, fromlen, connectinghost, RPCAP_HOSTLIST_SIZE, NULL, 0, NI_NUMERICHOST))
  2438. {
  2439. sock_geterror("getnameinfo(): ", errbuf, PCAP_ERRBUF_SIZE);
  2440. rpcap_senderror(sockctrl, 0, PCAP_ERR_REMOTEACCEPT, errbuf, NULL);
  2441. sock_close(sockctrl, NULL, 0);
  2442. return (SOCKET)-1;
  2443. }
  2444. /* checks if the connecting host is among the ones allowed */
  2445. if (sock_check_hostlist((char *)hostlist, RPCAP_HOSTLIST_SEP, &from, errbuf, PCAP_ERRBUF_SIZE) < 0)
  2446. {
  2447. rpcap_senderror(sockctrl, 0, PCAP_ERR_REMOTEACCEPT, errbuf, NULL);
  2448. sock_close(sockctrl, NULL, 0);
  2449. return (SOCKET)-1;
  2450. }
  2451. /*
  2452. * Send authentication to the remote machine.
  2453. */
  2454. if (rpcap_doauth(sockctrl, &protocol_version, auth, errbuf) == -1)
  2455. {
  2456. /* Unrecoverable error. */
  2457. rpcap_senderror(sockctrl, 0, PCAP_ERR_REMOTEACCEPT, errbuf, NULL);
  2458. sock_close(sockctrl, NULL, 0);
  2459. return (SOCKET)-3;
  2460. }
  2461. /* Checks that this host does not already have a cntrl connection in place */
  2462. /* Initialize pointers */
  2463. temp = activeHosts;
  2464. prev = NULL;
  2465. while (temp)
  2466. {
  2467. /* This host already has an active connection in place, so I don't have to update the host list */
  2468. if (sock_cmpaddr(&temp->host, &from) == 0)
  2469. return sockctrl;
  2470. prev = temp;
  2471. temp = temp->next;
  2472. }
  2473. /* The host does not exist in the list; so I have to update the list */
  2474. if (prev)
  2475. {
  2476. prev->next = (struct activehosts *) malloc(sizeof(struct activehosts));
  2477. temp = prev->next;
  2478. }
  2479. else
  2480. {
  2481. activeHosts = (struct activehosts *) malloc(sizeof(struct activehosts));
  2482. temp = activeHosts;
  2483. }
  2484. if (temp == NULL)
  2485. {
  2486. pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
  2487. errno, "malloc() failed");
  2488. rpcap_senderror(sockctrl, protocol_version, PCAP_ERR_REMOTEACCEPT, errbuf, NULL);
  2489. sock_close(sockctrl, NULL, 0);
  2490. return (SOCKET)-1;
  2491. }
  2492. memcpy(&temp->host, &from, fromlen);
  2493. temp->sockctrl = sockctrl;
  2494. temp->protocol_version = protocol_version;
  2495. temp->next = NULL;
  2496. return sockctrl;
  2497. }
  2498. int pcap_remoteact_close(const char *host, char *errbuf)
  2499. {
  2500. struct activehosts *temp, *prev; /* temp var needed to scan the host list chain */
  2501. struct addrinfo hints, *addrinfo, *ai_next; /* temp var needed to translate between hostname to its address */
  2502. int retval;
  2503. temp = activeHosts;
  2504. prev = NULL;
  2505. /* retrieve the network address corresponding to 'host' */
  2506. addrinfo = NULL;
  2507. memset(&hints, 0, sizeof(struct addrinfo));
  2508. hints.ai_family = PF_UNSPEC;
  2509. hints.ai_socktype = SOCK_STREAM;
  2510. retval = getaddrinfo(host, "0", &hints, &addrinfo);
  2511. if (retval != 0)
  2512. {
  2513. pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "getaddrinfo() %s", gai_strerror(retval));
  2514. return -1;
  2515. }
  2516. while (temp)
  2517. {
  2518. ai_next = addrinfo;
  2519. while (ai_next)
  2520. {
  2521. if (sock_cmpaddr(&temp->host, (struct sockaddr_storage *) ai_next->ai_addr) == 0)
  2522. {
  2523. struct rpcap_header header;
  2524. int status = 0;
  2525. /* Close this connection */
  2526. rpcap_createhdr(&header, temp->protocol_version,
  2527. RPCAP_MSG_CLOSE, 0, 0);
  2528. /*
  2529. * Don't check for errors, since we're
  2530. * just cleaning up.
  2531. */
  2532. if (sock_send(temp->sockctrl,
  2533. (char *)&header,
  2534. sizeof(struct rpcap_header), errbuf,
  2535. PCAP_ERRBUF_SIZE) < 0)
  2536. {
  2537. /*
  2538. * Let that error be the one we
  2539. * report.
  2540. */
  2541. (void)sock_close(temp->sockctrl, NULL,
  2542. 0);
  2543. status = -1;
  2544. }
  2545. else
  2546. {
  2547. if (sock_close(temp->sockctrl, errbuf,
  2548. PCAP_ERRBUF_SIZE) == -1)
  2549. status = -1;
  2550. }
  2551. /*
  2552. * Remove the host from the list of active
  2553. * hosts.
  2554. */
  2555. if (prev)
  2556. prev->next = temp->next;
  2557. else
  2558. activeHosts = temp->next;
  2559. freeaddrinfo(addrinfo);
  2560. free(temp);
  2561. /* To avoid inconsistencies in the number of sock_init() */
  2562. sock_cleanup();
  2563. return status;
  2564. }
  2565. ai_next = ai_next->ai_next;
  2566. }
  2567. prev = temp;
  2568. temp = temp->next;
  2569. }
  2570. if (addrinfo)
  2571. freeaddrinfo(addrinfo);
  2572. /* To avoid inconsistencies in the number of sock_init() */
  2573. sock_cleanup();
  2574. pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "The host you want to close the active connection is not known");
  2575. return -1;
  2576. }
  2577. void pcap_remoteact_cleanup(void)
  2578. {
  2579. /* Very dirty, but it works */
  2580. if (sockmain)
  2581. {
  2582. closesocket(sockmain);
  2583. /* To avoid inconsistencies in the number of sock_init() */
  2584. sock_cleanup();
  2585. }
  2586. }
  2587. int pcap_remoteact_list(char *hostlist, char sep, int size, char *errbuf)
  2588. {
  2589. struct activehosts *temp; /* temp var needed to scan the host list chain */
  2590. size_t len;
  2591. char hoststr[RPCAP_HOSTLIST_SIZE + 1];
  2592. temp = activeHosts;
  2593. len = 0;
  2594. *hostlist = 0;
  2595. while (temp)
  2596. {
  2597. /*int sock_getascii_addrport(const struct sockaddr_storage *sockaddr, char *address, int addrlen, char *port, int portlen, int flags, char *errbuf, int errbuflen) */
  2598. /* Get the numeric form of the name of the connecting host */
  2599. if (sock_getascii_addrport((struct sockaddr_storage *) &temp->host, hoststr,
  2600. RPCAP_HOSTLIST_SIZE, NULL, 0, NI_NUMERICHOST, errbuf, PCAP_ERRBUF_SIZE) != -1)
  2601. /* if (getnameinfo( (struct sockaddr *) &temp->host, sizeof (struct sockaddr_storage), hoststr, */
  2602. /* RPCAP_HOSTLIST_SIZE, NULL, 0, NI_NUMERICHOST) ) */
  2603. {
  2604. /* sock_geterror("getnameinfo(): ", errbuf, PCAP_ERRBUF_SIZE); */
  2605. return -1;
  2606. }
  2607. len = len + strlen(hoststr) + 1 /* the separator */;
  2608. if ((size < 0) || (len >= (size_t)size))
  2609. {
  2610. pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "The string you provided is not able to keep "
  2611. "the hostnames for all the active connections");
  2612. return -1;
  2613. }
  2614. strlcat(hostlist, hoststr, PCAP_ERRBUF_SIZE);
  2615. hostlist[len - 1] = sep;
  2616. hostlist[len] = 0;
  2617. temp = temp->next;
  2618. }
  2619. return 0;
  2620. }
  2621. /*
  2622. * Receive the header of a message.
  2623. */
  2624. static int rpcap_recv_msg_header(SOCKET sock, struct rpcap_header *header, char *errbuf)
  2625. {
  2626. int nrecv;
  2627. nrecv = sock_recv(sock, (char *) header, sizeof(struct rpcap_header),
  2628. SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf,
  2629. PCAP_ERRBUF_SIZE);
  2630. if (nrecv == -1)
  2631. {
  2632. /* Network error. */
  2633. return -1;
  2634. }
  2635. header->plen = ntohl(header->plen);
  2636. return 0;
  2637. }
  2638. /*
  2639. * Make sure the protocol version of a received message is what we were
  2640. * expecting.
  2641. */
  2642. static int rpcap_check_msg_ver(SOCKET sock, uint8 expected_ver, struct rpcap_header *header, char *errbuf)
  2643. {
  2644. /*
  2645. * Did the server specify the version we negotiated?
  2646. */
  2647. if (header->ver != expected_ver)
  2648. {
  2649. /*
  2650. * Discard the rest of the message.
  2651. */
  2652. if (rpcap_discard(sock, header->plen, errbuf) == -1)
  2653. return -1;
  2654. /*
  2655. * Tell our caller that it's not the negotiated version.
  2656. */
  2657. if (errbuf != NULL)
  2658. {
  2659. pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
  2660. "Server sent us a message with version %u when we were expecting %u",
  2661. header->ver, expected_ver);
  2662. }
  2663. return -1;
  2664. }
  2665. return 0;
  2666. }
  2667. /*
  2668. * Check the message type of a received message, which should either be
  2669. * the expected message type or RPCAP_MSG_ERROR.
  2670. */
  2671. static int rpcap_check_msg_type(SOCKET sock, uint8 request_type, struct rpcap_header *header, uint16 *errcode, char *errbuf)
  2672. {
  2673. const char *request_type_string;
  2674. const char *msg_type_string;
  2675. /*
  2676. * What type of message is it?
  2677. */
  2678. if (header->type == RPCAP_MSG_ERROR)
  2679. {
  2680. /*
  2681. * The server reported an error.
  2682. * Hand that error back to our caller.
  2683. */
  2684. *errcode = ntohs(header->value);
  2685. rpcap_msg_err(sock, header->plen, errbuf);
  2686. return -1;
  2687. }
  2688. *errcode = 0;
  2689. /*
  2690. * For a given request type value, the expected reply type value
  2691. * is the request type value with ORed with RPCAP_MSG_IS_REPLY.
  2692. */
  2693. if (header->type != (request_type | RPCAP_MSG_IS_REPLY))
  2694. {
  2695. /*
  2696. * This isn't a reply to the request we sent.
  2697. */
  2698. /*
  2699. * Discard the rest of the message.
  2700. */
  2701. if (rpcap_discard(sock, header->plen, errbuf) == -1)
  2702. return -1;
  2703. /*
  2704. * Tell our caller about it.
  2705. */
  2706. request_type_string = rpcap_msg_type_string(request_type);
  2707. msg_type_string = rpcap_msg_type_string(header->type);
  2708. if (errbuf != NULL)
  2709. {
  2710. if (request_type_string == NULL)
  2711. {
  2712. /* This should not happen. */
  2713. pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
  2714. "rpcap_check_msg_type called for request message with type %u",
  2715. request_type);
  2716. return -1;
  2717. }
  2718. if (msg_type_string != NULL)
  2719. pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
  2720. "%s message received in response to a %s message",
  2721. msg_type_string, request_type_string);
  2722. else
  2723. pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,
  2724. "Message of unknown type %u message received in response to a %s request",
  2725. header->type, request_type_string);
  2726. }
  2727. return -1;
  2728. }
  2729. return 0;
  2730. }
  2731. /*
  2732. * Receive and process the header of a message.
  2733. */
  2734. static int rpcap_process_msg_header(SOCKET sock, uint8 expected_ver, uint8 request_type, struct rpcap_header *header, char *errbuf)
  2735. {
  2736. uint16 errcode;
  2737. if (rpcap_recv_msg_header(sock, header, errbuf) == -1)
  2738. {
  2739. /* Network error. */
  2740. return -1;
  2741. }
  2742. /*
  2743. * Did the server specify the version we negotiated?
  2744. */
  2745. if (rpcap_check_msg_ver(sock, expected_ver, header, errbuf) == -1)
  2746. return -1;
  2747. /*
  2748. * Check the message type.
  2749. */
  2750. return rpcap_check_msg_type(sock, request_type, header,
  2751. &errcode, errbuf);
  2752. }
  2753. /*
  2754. * Read data from a message.
  2755. * If we're trying to read more data that remains, puts an error
  2756. * message into errmsgbuf and returns -2. Otherwise, tries to read
  2757. * the data and, if that succeeds, subtracts the amount read from
  2758. * the number of bytes of data that remains.
  2759. * Returns 0 on success, logs a message and returns -1 on a network
  2760. * error.
  2761. */
  2762. static int rpcap_recv(SOCKET sock, void *buffer, size_t toread, uint32 *plen, char *errbuf)
  2763. {
  2764. int nread;
  2765. if (toread > *plen)
  2766. {
  2767. /* The server sent us a bad message */
  2768. pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Message payload is too short");
  2769. return -1;
  2770. }
  2771. nread = sock_recv(sock, buffer, toread,
  2772. SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf, PCAP_ERRBUF_SIZE);
  2773. if (nread == -1)
  2774. {
  2775. return -1;
  2776. }
  2777. *plen -= nread;
  2778. return 0;
  2779. }
  2780. /*
  2781. * This handles the RPCAP_MSG_ERROR message.
  2782. */
  2783. static void rpcap_msg_err(SOCKET sockctrl, uint32 plen, char *remote_errbuf)
  2784. {
  2785. char errbuf[PCAP_ERRBUF_SIZE];
  2786. if (plen >= PCAP_ERRBUF_SIZE)
  2787. {
  2788. /*
  2789. * Message is too long; just read as much of it as we
  2790. * can into the buffer provided, and discard the rest.
  2791. */
  2792. if (sock_recv(sockctrl, remote_errbuf, PCAP_ERRBUF_SIZE - 1,
  2793. SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf,
  2794. PCAP_ERRBUF_SIZE) == -1)
  2795. {
  2796. // Network error.
  2797. pcap_snprintf(remote_errbuf, PCAP_ERRBUF_SIZE, "Read of error message from client failed: %s", errbuf);
  2798. return;
  2799. }
  2800. /*
  2801. * Null-terminate it.
  2802. */
  2803. remote_errbuf[PCAP_ERRBUF_SIZE - 1] = '\0';
  2804. /*
  2805. * Throw away the rest.
  2806. */
  2807. (void)rpcap_discard(sockctrl, plen - (PCAP_ERRBUF_SIZE - 1), remote_errbuf);
  2808. }
  2809. else if (plen == 0)
  2810. {
  2811. /* Empty error string. */
  2812. remote_errbuf[0] = '\0';
  2813. }
  2814. else
  2815. {
  2816. if (sock_recv(sockctrl, remote_errbuf, plen,
  2817. SOCK_RECEIVEALL_YES|SOCK_EOF_IS_ERROR, errbuf,
  2818. PCAP_ERRBUF_SIZE) == -1)
  2819. {
  2820. // Network error.
  2821. pcap_snprintf(remote_errbuf, PCAP_ERRBUF_SIZE, "Read of error message from client failed: %s", errbuf);
  2822. return;
  2823. }
  2824. /*
  2825. * Null-terminate it.
  2826. */
  2827. remote_errbuf[plen] = '\0';
  2828. }
  2829. }
  2830. /*
  2831. * Discard data from a connection.
  2832. * Mostly used to discard wrong-sized messages.
  2833. * Returns 0 on success, logs a message and returns -1 on a network
  2834. * error.
  2835. */
  2836. static int rpcap_discard(SOCKET sock, uint32 len, char *errbuf)
  2837. {
  2838. if (len != 0)
  2839. {
  2840. if (sock_discard(sock, len, errbuf, PCAP_ERRBUF_SIZE) == -1)
  2841. {
  2842. // Network error.
  2843. return -1;
  2844. }
  2845. }
  2846. return 0;
  2847. }
  2848. /*
  2849. * Read bytes into the pcap_t's buffer until we have the specified
  2850. * number of bytes read or we get an error or interrupt indication.
  2851. */
  2852. static int rpcap_read_packet_msg(SOCKET sock, pcap_t *p, size_t size)
  2853. {
  2854. u_char *bp;
  2855. int cc;
  2856. int bytes_read;
  2857. bp = p->bp;
  2858. cc = p->cc;
  2859. /*
  2860. * Loop until we have the amount of data requested or we get
  2861. * an error or interrupt.
  2862. */
  2863. while ((size_t)cc < size)
  2864. {
  2865. /*
  2866. * We haven't read all of the packet header yet.
  2867. * Read what remains, which could be all of it.
  2868. */
  2869. bytes_read = sock_recv(sock, bp, size - cc,
  2870. SOCK_RECEIVEALL_NO|SOCK_EOF_IS_ERROR, p->errbuf,
  2871. PCAP_ERRBUF_SIZE);
  2872. if (bytes_read == -1)
  2873. {
  2874. /*
  2875. * Network error. Update the read pointer and
  2876. * byte count, and return an error indication.
  2877. */
  2878. p->bp = bp;
  2879. p->cc = cc;
  2880. return -1;
  2881. }
  2882. if (bytes_read == -3)
  2883. {
  2884. /*
  2885. * Interrupted receive. Update the read
  2886. * pointer and byte count, and return
  2887. * an interrupted indication.
  2888. */
  2889. p->bp = bp;
  2890. p->cc = cc;
  2891. return -3;
  2892. }
  2893. if (bytes_read == 0)
  2894. {
  2895. /*
  2896. * EOF - server terminated the connection.
  2897. * Update the read pointer and byte count, and
  2898. * return an error indication.
  2899. */
  2900. pcap_snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
  2901. "The server terminated the connection.");
  2902. return -1;
  2903. }
  2904. bp += bytes_read;
  2905. cc += bytes_read;
  2906. }
  2907. p->bp = bp;
  2908. p->cc = cc;
  2909. return 0;
  2910. }