Fix document creation under Windows, add ethereal-filter.html to the NSIS
[obnox/wireshark/wip.git] / pcap-util.c
1 /* pcap-util.c
2  * Utility routines for packet capture
3  *
4  * $Id: pcap-util.c,v 1.17 2003/09/10 06:47:04 guy Exp $
5  *
6  * Ethereal - Network traffic analyzer
7  * By Gerald Combs <gerald@ethereal.com>
8  * Copyright 1998 Gerald Combs
9  *
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 2
13  * of the License, or (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
23  */
24
25 #ifdef HAVE_CONFIG_H
26 # include "config.h"
27 #endif
28
29 #ifdef HAVE_LIBPCAP
30
31 #include <glib.h>
32
33 #include <stdlib.h>
34 #include <string.h>
35 #include <stdio.h>
36 #include <errno.h>
37
38 #ifdef HAVE_UNISTD_H
39 #include <unistd.h>
40 #endif
41
42 #ifdef HAVE_SYS_SOCKET_H
43 #include <sys/socket.h>
44 #endif
45
46 #ifdef HAVE_SYS_IOCTL_H
47 #include <sys/ioctl.h>
48 #endif
49
50 #include <pcap.h>
51
52 #ifndef WIN32
53 /*
54  * Keep Digital UNIX happy when including <net/if.h>.
55  */
56 struct mbuf;
57 struct rtentry;
58 #include <net/if.h>
59 #endif
60
61 #ifdef HAVE_SYS_SOCKIO_H
62 # include <sys/sockio.h>
63 #endif
64
65 #include "globals.h"
66
67 #ifdef WIN32
68 #include "capture-wpcap.h"
69 #endif
70
71 #include "pcap-util.h"
72
73 /*
74  * Get the data-link type for a libpcap device.
75  * This works around AIX 5.x's non-standard and incompatible-with-the-
76  * rest-of-the-universe libpcap.
77  */
78 int
79 get_pcap_linktype(pcap_t *pch, char *devname
80 #ifndef AIX
81         _U_
82 #endif
83 )
84 {
85         int linktype;
86 #ifdef AIX
87         char *ifacename;
88 #endif
89
90         linktype = pcap_datalink(pch);
91 #ifdef AIX
92
93         /*
94          * The libpcap that comes with AIX 5.x uses RFC 1573 ifType values
95          * rather than DLT_ values for link-layer types; the ifType values
96          * for LAN devices are:
97          *
98          *      Ethernet        6
99          *      802.3           7
100          *      Token Ring      9
101          *      FDDI            15
102          *
103          * and the ifType value for a loopback device is 24.
104          *
105          * The AIX names for LAN devices begin with:
106          *
107          *      Ethernet                en
108          *      802.3                   et
109          *      Token Ring              tr
110          *      FDDI                    fi
111          *
112          * and the AIX names for loopback devices begin with "lo".
113          *
114          * (The difference between "Ethernet" and "802.3" is presumably
115          * whether packets have an Ethernet header, with a packet type,
116          * or an 802.3 header, with a packet length, followed by an 802.2
117          * header and possibly a SNAP header.)
118          *
119          * If the device name matches "linktype" interpreted as an ifType
120          * value, rather than as a DLT_ value, we will assume this is AIX's
121          * non-standard, incompatible libpcap, rather than a standard libpcap,
122          * and will map the link-layer type to the standard DLT_ value for
123          * that link-layer type, as that's what the rest of Ethereal expects.
124          *
125          * (This means the capture files won't be readable by a tcpdump
126          * linked with AIX's non-standard libpcap, but so it goes.  They
127          * *will* be readable by standard versions of tcpdump, Ethereal,
128          * and so on.)
129          *
130          * XXX - if we conclude we're using AIX libpcap, should we also
131          * set a flag to cause us to assume the time stamps are in
132          * seconds-and-nanoseconds form, and to convert them to
133          * seconds-and-microseconds form before processing them and
134          * writing them out?
135          */
136
137         /*
138          * Find the last component of the device name, which is the
139          * interface name.
140          */
141         ifacename = strchr(devname, '/');
142         if (ifacename == NULL)
143                 ifacename = devnames;
144
145         /* See if it matches any of the LAN device names. */
146         if (strncmp(ifacename, "en", 2) == 0) {
147                 if (linktype == 6) {
148                         /*
149                          * That's the RFC 1573 value for Ethernet; map it
150                          * to DLT_EN10MB.
151                          */
152                         linktype = 1;
153                 }
154         } else if (strncmp(ifacename, "et", 2) == 0) {
155                 if (linktype == 7) {
156                         /*
157                          * That's the RFC 1573 value for 802.3; map it to
158                          * DLT_EN10MB.
159                          * (libpcap, tcpdump, Ethereal, etc. don't care if
160                          * it's Ethernet or 802.3.)
161                          */
162                         linktype = 1;
163                 }
164         } else if (strncmp(ifacename, "tr") == 0) {
165                 if (linktype == 9) {
166                         /*
167                          * That's the RFC 1573 value for 802.5 (Token Ring);
168                          * map it to DLT_IEEE802, which is what's used for
169                          * Token Ring.
170                          */
171                         linktype = 6;
172                 }
173         } else if (strncmp(ifacename, "fi") == 0) {
174                 if (linktype == 15) {
175                         /*
176                          * That's the RFC 1573 value for FDDI; map it to
177                          * DLT_FDDI.
178                          */
179                         linktype = 10;
180                 }
181         } else if (strncmp(ifacename, "lo") == 0) {
182                 if (linktype == 24) {
183                         /*
184                          * That's the RFC 1573 value for "software loopback"
185                          * devices; map it to DLT_NULL, which is what's used
186                          * for loopback devices on BSD.
187                          */
188                         linktype = 0;
189                 }
190         }
191 #endif
192
193         return linktype;
194 }
195
196 /*
197  * If the ability to capture packets is added to Wiretap, these
198  * routines should be moved to the Wiretap source (with
199  * "get_interface_list()" and "free_interface_list()" renamed to
200  * "wtap_get_interface_list()" and "wtap_free_interface_list()",
201  * and modified to use Wiretap routines to attempt to open the
202  * interface.
203  */
204
205 struct search_user_data {
206         char    *name;
207         int     found;
208 };
209
210 static void
211 search_for_if_cb(gpointer data, gpointer user_data);
212
213 static void
214 free_if_cb(gpointer data, gpointer user_data);
215
216 static if_info_t *
217 if_info_new(char *name, char *description)
218 {
219         if_info_t *if_info;
220
221         if_info = g_malloc(sizeof (if_info_t));
222         if_info->name = g_strdup(name);
223         if (description == NULL)
224                 if_info->description = NULL;
225         else
226                 if_info->description = g_strdup(description);
227         return if_info;
228 }
229
230 #ifndef WIN32
231 GList *
232 get_interface_list(int *err, char *err_str)
233 {
234         GList  *il = NULL;
235         gint    nonloopback_pos = 0;
236         struct  ifreq *ifr, *last;
237         struct  ifconf ifc;
238         struct  ifreq ifrflags;
239         int     sock = socket(AF_INET, SOCK_DGRAM, 0);
240         struct search_user_data user_data;
241         pcap_t *pch;
242         int len, lastlen;
243         char *buf;
244         if_info_t *if_info;
245
246         if (sock < 0) {
247                 sprintf(err_str, "Error opening socket: %s",
248                     strerror(errno));
249                 return NULL;
250         }
251
252         /*
253          * This code came from: W. Richard Stevens: "UNIX Network Programming",
254          * Networking APIs: Sockets and XTI, Vol 1, page 434.
255          */
256         lastlen = 0;
257         len = 100 * sizeof(struct ifreq);
258         for ( ; ; ) {
259                 buf = g_malloc(len);
260                 ifc.ifc_len = len;
261                 ifc.ifc_buf = buf;
262                 memset (buf, 0, len);
263                 if (ioctl(sock, SIOCGIFCONF, &ifc) < 0) {
264                         if (errno != EINVAL || lastlen != 0) {
265                                 sprintf(err_str,
266                                         "SIOCGIFCONF ioctl error getting list of interfaces: %s",
267                                         strerror(errno));
268                                 goto fail;
269                         }
270                 } else {
271                         if ((unsigned) ifc.ifc_len < sizeof(struct ifreq)) {
272                                 sprintf(err_str,
273                                         "SIOCGIFCONF ioctl gave too small return buffer");
274                                 goto fail;
275                         }
276                         if (ifc.ifc_len == lastlen)
277                                 break;                  /* success, len has not changed */
278                         lastlen = ifc.ifc_len;
279                 }
280                 len += 10 * sizeof(struct ifreq);       /* increment */
281                 g_free(buf);
282         }
283         ifr = (struct ifreq *) ifc.ifc_req;
284         last = (struct ifreq *) ((char *) ifr + ifc.ifc_len);
285         while (ifr < last) {
286                 /*
287                  * Skip addresses that begin with "dummy", or that include
288                  * a ":" (the latter are Solaris virtuals).
289                  */
290                 if (strncmp(ifr->ifr_name, "dummy", 5) == 0 ||
291                     strchr(ifr->ifr_name, ':') != NULL)
292                         goto next;
293
294                 /*
295                  * If we already have this interface name on the list,
296                  * don't add it (SIOCGIFCONF returns, at least on
297                  * BSD-flavored systems, one entry per interface *address*;
298                  * if an interface has multiple addresses, we get multiple
299                  * entries for it).
300                  */
301                 user_data.name = ifr->ifr_name;
302                 user_data.found = FALSE;
303                 g_list_foreach(il, search_for_if_cb, &user_data);
304                 if (user_data.found)
305                         goto next;
306
307                 /*
308                  * Get the interface flags.
309                  */
310                 memset(&ifrflags, 0, sizeof ifrflags);
311                 strncpy(ifrflags.ifr_name, ifr->ifr_name,
312                     sizeof ifrflags.ifr_name);
313                 if (ioctl(sock, SIOCGIFFLAGS, (char *)&ifrflags) < 0) {
314                         if (errno == ENXIO)
315                                 goto next;
316                         sprintf(err_str, "SIOCGIFFLAGS error getting flags for interface %s: %s",
317                             ifr->ifr_name, strerror(errno));
318                         goto fail;
319                 }
320
321                 /*
322                  * Skip interfaces that aren't up.
323                  */
324                 if (!(ifrflags.ifr_flags & IFF_UP))
325                         goto next;
326
327                 /*
328                  * Skip interfaces that we can't open with "libpcap".
329                  * Open with the minimum packet size - it appears that the
330                  * IRIX SIOCSNOOPLEN "ioctl" may fail if the capture length
331                  * supplied is too large, rather than just truncating it.
332                  */
333                 pch = pcap_open_live(ifr->ifr_name, MIN_PACKET_SIZE, 0, 0,
334                     err_str);
335                 if (pch == NULL)
336                         goto next;
337                 pcap_close(pch);
338
339                 /*
340                  * If it's a loopback interface, add it at the end of the
341                  * list, otherwise add it after the last non-loopback
342                  * interface, so all loopback interfaces go at the end - we
343                  * don't want a loopback interface to be the default capture
344                  * device unless there are no non-loopback devices.
345                  */
346                 if_info = if_info_new(ifr->ifr_name, NULL);
347                 if ((ifrflags.ifr_flags & IFF_LOOPBACK) ||
348                     strncmp(ifr->ifr_name, "lo", 2) == 0)
349                         il = g_list_insert(il, if_info, -1);
350                 else {
351                         il = g_list_insert(il, if_info, nonloopback_pos);
352                         /*
353                          * Insert the next non-loopback interface after this
354                          * one.
355                          */
356                         nonloopback_pos++;
357                 }
358
359         next:
360 #ifdef HAVE_SA_LEN
361                 ifr = (struct ifreq *) ((char *) ifr +
362                     (ifr->ifr_addr.sa_len > sizeof(ifr->ifr_addr) ?
363                         ifr->ifr_addr.sa_len : sizeof(ifr->ifr_addr)) +
364                     IFNAMSIZ);
365 #else
366                 ifr = (struct ifreq *) ((char *) ifr + sizeof(struct ifreq));
367 #endif
368         }
369
370 #ifdef linux
371         /*
372          * OK, maybe we have support for the "any" device, to do a cooked
373          * capture on all interfaces at once.
374          * Try opening it and, if that succeeds, add it to the end of
375          * the list of interfaces.
376          */
377         pch = pcap_open_live("any", MIN_PACKET_SIZE, 0, 0, err_str);
378         if (pch != NULL) {
379                 /*
380                  * It worked; we can use the "any" device.
381                  */
382                 if_info = if_info_new("any",
383                     "Pseudo-device that captures on all interfaces");
384                 il = g_list_insert(il, if_info, -1);
385                 pcap_close(pch);
386         }
387 #endif
388
389         g_free(ifc.ifc_buf);
390         close(sock);
391
392         if (il == NULL) {
393                 /*
394                  * No interfaces found.
395                  */
396                 *err = NO_INTERFACES_FOUND;
397         }
398         return il;
399
400 fail:
401         if (il != NULL)
402                 free_interface_list(il);
403         g_free(ifc.ifc_buf);
404         close(sock);
405         *err = CANT_GET_INTERFACE_LIST;
406         return NULL;
407 }
408
409 static void
410 search_for_if_cb(gpointer data, gpointer user_data)
411 {
412         struct search_user_data *search_user_data = user_data;
413         if_info_t *if_info = data;
414
415         if (strcmp(if_info->name, search_user_data->name) == 0)
416                 search_user_data->found = TRUE;
417 }
418 #else /* Windows */
419 GList *
420 get_interface_list(int *err, char *err_str) {
421   GList  *il = NULL;
422   wchar_t *names;
423   char *win95names;
424   char ascii_name[MAX_WIN_IF_NAME_LEN + 1];
425   char ascii_desc[MAX_WIN_IF_NAME_LEN + 1];
426   int i, j;
427
428   /* On Windows pcap_lookupdev is implemented by calling
429    * PacketGetAdapterNames.  According to the documentation I can find
430    * (http://winpcap.polito.it/docs/dll.htm#PacketGetAdapterNames)
431    * this means that:
432    *
433    * On Windows OT (95, 98, Me), pcap_lookupdev returns a sequence of bytes
434    * consisting of:
435    *
436    *    a sequence of null-terminated ASCII strings (i.e., each one is
437    *    terminated by a single 0 byte), giving the names of the interfaces;
438    *
439    *    an empty ASCII string (i.e., a single 0 byte);
440    *
441    *    a sequence of null-terminated ASCII strings, giving the
442    *    descriptions of the interfaces;
443    *
444    *    an empty ASCII string.
445    *
446    * On Windows NT (NT 4.0, W2K, WXP, W2K3, etc.), pcap_lookupdev returns
447    * a sequence of bytes consisting of:
448    *
449    *    a sequence of null-terminated double-byte Unicode strings (i.e.,
450    *    each one consits of a sequence of double-byte characters,
451    *    terminated by a double-byte 0), giving the names of the interfaces;
452    *
453    *    an empty Unicode string (i.e., a double 0 byte);
454    *
455    *    a sequence of null-terminated ASCII strings, giving the
456    *    descriptions of the interfaces;
457    *
458    *    an empty ASCII string.
459    *
460    * The Nth string in the first sequence is the name of the Nth adapter;
461    * the Nth string in the second sequence is the descriptio of the Nth
462    * adapter.
463    */
464
465   names = (wchar_t *)pcap_lookupdev(err_str);
466   i = 0;
467
468   if (names) {
469           char* desc = 0;
470           int desc_pos = 0;
471
472           if (names[0]<256) {
473                   /* If names[0] is less than 256 it means the first byte is 0
474                      This implies that we are using unicode characters */
475                   while(*(names+desc_pos) || *(names+desc_pos-1))
476                         desc_pos++;
477                   desc_pos++;   /* Step over the extra '\0' */
478                   desc = (char*)(names + desc_pos); /* cast *after* addition */
479
480                   while (names[i] != 0)
481                   {
482                         /*
483                          * Copy the Unicode description to an ASCII
484                          * string.
485                          */
486                         j = 0;
487                         while (*desc != 0) {
488                             if (j < MAX_WIN_IF_NAME_LEN)
489                                 ascii_desc[j++] = *desc;
490                                 desc++;
491                         }
492                         ascii_desc[j] = '\0';
493                         desc++;
494
495                         /*
496                          * Copy the Unicode name to an ASCII string.
497                          */
498                         j = 0;
499                         while (names[i] != 0) {
500                             if (j < MAX_WIN_IF_NAME_LEN)
501                                 ascii_name[j++] = names[i++];
502                         }
503                         ascii_name[j] = '\0';
504                         i++;
505                         il = g_list_append(il,
506                             if_info_new(ascii_name, ascii_desc));
507                   }
508           }
509           else {
510                   /* Otherwise we are in Windows 95/98 and using ASCII
511                      (8 bit) characters */
512                   win95names=(char *)names;
513                   while(*(win95names+desc_pos) || *(win95names+desc_pos-1))
514                         desc_pos++;
515                   desc_pos++;   /* Step over the extra '\0' */
516                   desc = win95names + desc_pos;
517
518                   while (win95names[i] != '\0')
519                   {
520                         /*
521                          * "&win95names[i]" points to the current interface
522                          * name, and "desc" points to that interface's
523                          * description.
524                          */
525                         il = g_list_append(il,
526                             if_info_new(&win95names[i], desc));
527
528                         /*
529                          * Skip to the next description.
530                          */
531                         while (*desc != 0)
532                                 desc++;
533                         desc++;
534
535                         /*
536                          * Skip to the next name.
537                          */
538                         while (win95names[i] != 0)
539                             i++;
540                         i++;
541                   }
542           }
543   }
544
545   if (il == NULL) {
546     /*
547      * No interfaces found.
548      */
549     *err = NO_INTERFACES_FOUND;
550   }
551   return(il);
552 }
553 #endif
554
555 static void
556 free_if_cb(gpointer data, gpointer user_data _U_)
557 {
558         if_info_t *if_info = data;
559
560         g_free(if_info->name);
561         if (if_info->description != NULL)
562                 g_free(if_info->description);
563 }
564
565 void
566 free_interface_list(GList *if_list)
567 {
568         g_list_foreach(if_list, free_if_cb, NULL);
569         g_list_free(if_list);
570 }
571
572 #endif /* HAVE_LIBPCAP */