From Jesper Peterson:
[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.14 2003/07/06 00:07:58 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 #ifndef WIN32
217 GList *
218 get_interface_list(int *err, char *err_str)
219 {
220         GList  *il = NULL;
221         gint    nonloopback_pos = 0;
222         struct  ifreq *ifr, *last;
223         struct  ifconf ifc;
224         struct  ifreq ifrflags;
225         int     sock = socket(AF_INET, SOCK_DGRAM, 0);
226         struct search_user_data user_data;
227         pcap_t *pch;
228         int len, lastlen;
229         char *buf;
230
231         if (sock < 0) {
232                 sprintf(err_str, "Error opening socket: %s",
233                     strerror(errno));
234                 return NULL;
235         }
236
237         /*
238          * This code came from: W. Richard Stevens: "UNIX Network Programming",
239          * Networking APIs: Sockets and XTI, Vol 1, page 434.
240          */
241         lastlen = 0;
242         len = 100 * sizeof(struct ifreq);
243         for ( ; ; ) {
244                 buf = g_malloc(len);
245                 ifc.ifc_len = len;
246                 ifc.ifc_buf = buf;
247                 memset (buf, 0, len);
248                 if (ioctl(sock, SIOCGIFCONF, &ifc) < 0) {
249                         if (errno != EINVAL || lastlen != 0) {
250                                 sprintf(err_str,
251                                         "SIOCGIFCONF ioctl error getting list of interfaces: %s",
252                                         strerror(errno));
253                                 goto fail;
254                         }
255                 } else {
256                         if ((unsigned) ifc.ifc_len < sizeof(struct ifreq)) {
257                                 sprintf(err_str,
258                                         "SIOCGIFCONF ioctl gave too small return buffer");
259                                 goto fail;
260                         }
261                         if (ifc.ifc_len == lastlen)
262                                 break;                  /* success, len has not changed */
263                         lastlen = ifc.ifc_len;
264                 }
265                 len += 10 * sizeof(struct ifreq);       /* increment */
266                 g_free(buf);
267         }
268         ifr = (struct ifreq *) ifc.ifc_req;
269         last = (struct ifreq *) ((char *) ifr + ifc.ifc_len);
270         while (ifr < last) {
271                 /*
272                  * Skip addresses that begin with "dummy", or that include
273                  * a ":" (the latter are Solaris virtuals).
274                  */
275                 if (strncmp(ifr->ifr_name, "dummy", 5) == 0 ||
276                     strchr(ifr->ifr_name, ':') != NULL)
277                         goto next;
278
279                 /*
280                  * If we already have this interface name on the list,
281                  * don't add it (SIOCGIFCONF returns, at least on
282                  * BSD-flavored systems, one entry per interface *address*;
283                  * if an interface has multiple addresses, we get multiple
284                  * entries for it).
285                  */
286                 user_data.name = ifr->ifr_name;
287                 user_data.found = FALSE;
288                 g_list_foreach(il, search_for_if_cb, &user_data);
289                 if (user_data.found)
290                         goto next;
291
292                 /*
293                  * Get the interface flags.
294                  */
295                 memset(&ifrflags, 0, sizeof ifrflags);
296                 strncpy(ifrflags.ifr_name, ifr->ifr_name,
297                     sizeof ifrflags.ifr_name);
298                 if (ioctl(sock, SIOCGIFFLAGS, (char *)&ifrflags) < 0) {
299                         if (errno == ENXIO)
300                                 goto next;
301                         sprintf(err_str, "SIOCGIFFLAGS error getting flags for interface %s: %s",
302                             ifr->ifr_name, strerror(errno));
303                         goto fail;
304                 }
305
306                 /*
307                  * Skip interfaces that aren't up.
308                  */
309                 if (!(ifrflags.ifr_flags & IFF_UP))
310                         goto next;
311
312                 /*
313                  * Skip interfaces that we can't open with "libpcap".
314                  * Open with the minimum packet size - it appears that the
315                  * IRIX SIOCSNOOPLEN "ioctl" may fail if the capture length
316                  * supplied is too large, rather than just truncating it.
317                  */
318                 pch = pcap_open_live(ifr->ifr_name, MIN_PACKET_SIZE, 0, 0,
319                     err_str);
320                 if (pch == NULL)
321                         goto next;
322                 pcap_close(pch);
323
324                 /*
325                  * If it's a loopback interface, add it at the end of the
326                  * list, otherwise add it after the last non-loopback
327                  * interface, so all loopback interfaces go at the end - we
328                  * don't want a loopback interface to be the default capture
329                  * device unless there are no non-loopback devices.
330                  */
331                 if ((ifrflags.ifr_flags & IFF_LOOPBACK) ||
332                     strncmp(ifr->ifr_name, "lo", 2) == 0)
333                         il = g_list_insert(il, g_strdup(ifr->ifr_name), -1);
334                 else {
335                         il = g_list_insert(il, g_strdup(ifr->ifr_name),
336                             nonloopback_pos);
337                         /*
338                          * Insert the next non-loopback interface after this
339                          * one.
340                          */
341                         nonloopback_pos++;
342                 }
343
344         next:
345 #ifdef HAVE_SA_LEN
346                 ifr = (struct ifreq *) ((char *) ifr +
347                     (ifr->ifr_addr.sa_len > sizeof(ifr->ifr_addr) ?
348                         ifr->ifr_addr.sa_len : sizeof(ifr->ifr_addr)) +
349                     IFNAMSIZ);
350 #else
351                 ifr = (struct ifreq *) ((char *) ifr + sizeof(struct ifreq));
352 #endif
353         }
354
355 #ifdef linux
356         /*
357          * OK, maybe we have support for the "any" device, to do a cooked
358          * capture on all interfaces at once.
359          * Try opening it and, if that succeeds, add it to the end of
360          * the list of interfaces.
361          */
362         pch = pcap_open_live("any", MIN_PACKET_SIZE, 0, 0, err_str);
363         if (pch != NULL) {
364                 /*
365                  * It worked; we can use the "any" device.
366                  */
367                 il = g_list_insert(il, g_strdup("any"), -1);
368                 pcap_close(pch);
369         }
370 #endif
371
372         g_free(ifc.ifc_buf);
373         close(sock);
374
375         if (il == NULL) {
376                 /*
377                  * No interfaces found.
378                  */
379                 *err = NO_INTERFACES_FOUND;
380         }
381         return il;
382
383 fail:
384         if (il != NULL)
385                 free_interface_list(il);
386         g_free(ifc.ifc_buf);
387         close(sock);
388         *err = CANT_GET_INTERFACE_LIST;
389         return NULL;
390 }
391
392 static void
393 search_for_if_cb(gpointer data, gpointer user_data)
394 {
395         struct search_user_data *search_user_data = user_data;
396
397         if (strcmp((char *)data, search_user_data->name) == 0)
398                 search_user_data->found = TRUE;
399 }
400 #else /* Windows */
401 #define MAX_WIN_IF_NAME_LEN 511
402 GList *
403 get_interface_list(int *err, char *err_str) {
404   GList  *il = NULL;
405   wchar_t *names;
406   char *win95names;
407   char newname[MAX_WIN_IF_NAME_LEN + 1];
408   int i, j;
409
410   /* On Windows pcap_lookupdev is implemented by calling
411    * PacketGetAdapterNames.  According to the documentation I can find
412    * (http://winpcap.polito.it/docs/dll.htm#PacketGetAdapterNames)
413    * this means that:
414    *
415    * On Windows 95x, pcap_lookupdev returns an ASCII string with the
416    * names of the adapters separated by a single ASCII "\0", a double
417    * "\0", followed by the descriptions of the adapters separated by a
418    * single ASCII "\0" . The string is terminated by a double "\0".
419    *
420    * On Windows NTx, pcap_lookupdev returns the names of the adapters,
421    * in UNICODE format, separated by a single UNICODE "\0" (i.e. 2
422    * ASCII "\0"), a double UNICODE "\0", followed by the descriptions
423    * of the adapters, in ASCII format, separated by a single ASCII
424    * "\0" . The string is terminated by a double ASCII "\0".
425    *
426    * We prepend the device name with a description to make it easier
427    * for users to choose the interface they want.  This requires that
428    * we split out the device name later on in tethereal.c and gtk/main.c.
429    * It might be useful to have separate structures for raw names and
430    * descriptions at some point.
431    */
432
433   names = (wchar_t *)pcap_lookupdev(err_str);
434   i = 0;
435
436   if (names) {
437           char* desc = 0;
438           int desc_pos = 0;
439
440           if (names[0]<256) {
441                   /* If names[0] is less than 256 it means the first byte is 0
442                      This implies that we are using unicode characters */
443                   while(*(names+desc_pos) || *(names+desc_pos-1))
444                         desc_pos++;
445                   desc_pos++;   /* Step over the extra '\0' */
446                   desc = (char*)(names + desc_pos); /* cast *after* addition */
447
448                   while (names[i] != 0)
449                   {
450                         j = 0;
451                         while (*desc) {
452                             if (j < MAX_WIN_IF_NAME_LEN)
453                                 newname[j++] = *desc++;
454                         }
455                         *desc++;
456                         if (j < MAX_WIN_IF_NAME_LEN - 1) {
457                             newname[j++] = ':';
458                             newname[j++] = ' ';
459                         }
460                         while (names[i] != 0) {
461                             if (j < MAX_WIN_IF_NAME_LEN)
462                                 newname[j++] = names[i++];
463                         }
464                         i++;
465                         newname[j] = 0;
466                         il = g_list_append(il, g_strdup(newname));
467                   }
468           }
469           else {
470                   /* Otherwise we are in Windows 95/98 and using ascii(8 bit)
471                      characters */
472                   win95names=(char *)names;
473                   while(*(win95names+desc_pos) || *(win95names+desc_pos-1))
474                         desc_pos++;
475                   desc_pos++;   /* Step over the extra '\0' */
476                   desc = win95names + desc_pos;
477
478                   while (win95names[i] != 0)
479                   {
480                         j = 0;
481                         while (*desc) {
482                             if (j < MAX_WIN_IF_NAME_LEN)
483                                 newname[j++] = *desc++;
484                         }
485                         *desc++;
486                         if (j < MAX_WIN_IF_NAME_LEN - 1) {
487                             newname[j++] = ':';
488                             newname[j++] = ' ';
489                         }
490                         while (win95names[i] != 0) {
491                             if (j < MAX_WIN_IF_NAME_LEN)
492                                 newname[j++] = win95names[i++];
493                         }
494                         i++;
495                         newname[j] = 0;
496                         il = g_list_append(il, g_strdup(newname));
497                   }
498           }
499   }
500
501   if (il == NULL) {
502     /*
503      * No interfaces found.
504      */
505     *err = NO_INTERFACES_FOUND;
506   }
507   return(il);
508 }
509 #endif
510
511 static void
512 free_if_cb(gpointer data, gpointer user_data _U_)
513 {
514         g_free(data);
515 }
516
517 void
518 free_interface_list(GList *if_list)
519 {
520         g_list_foreach(if_list, free_if_cb, NULL);
521         g_list_free(if_list);
522 }
523
524 #endif /* HAVE_LIBPCAP */