Coverage Report

Created: 2026-03-12 06:16

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libpcap/pcap.c
Line
Count
Source
1
/*
2
 * Copyright (c) 1993, 1994, 1995, 1996, 1997, 1998
3
 *  The Regents of the University of California.  All rights reserved.
4
 *
5
 * Redistribution and use in source and binary forms, with or without
6
 * modification, are permitted provided that the following conditions
7
 * are met:
8
 * 1. Redistributions of source code must retain the above copyright
9
 *    notice, this list of conditions and the following disclaimer.
10
 * 2. Redistributions in binary form must reproduce the above copyright
11
 *    notice, this list of conditions and the following disclaimer in the
12
 *    documentation and/or other materials provided with the distribution.
13
 * 3. All advertising materials mentioning features or use of this software
14
 *    must display the following acknowledgement:
15
 *  This product includes software developed by the Computer Systems
16
 *  Engineering Group at Lawrence Berkeley Laboratory.
17
 * 4. Neither the name of the University nor of the Laboratory may be used
18
 *    to endorse or promote products derived from this software without
19
 *    specific prior written permission.
20
 *
21
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31
 * SUCH DAMAGE.
32
 */
33
34
#include <config.h>
35
36
/*
37
 * Include this before including any system header files, as it
38
 * may do some #defines that cause those headers to declare
39
 * more functions than they do by default.
40
 */
41
#include "ftmacros.h"
42
43
#include <pcap-types.h>
44
#ifndef _WIN32
45
#include <sys/param.h>
46
#include <sys/file.h>
47
#include <sys/ioctl.h>
48
#include <sys/socket.h>
49
50
/*
51
 * On most supported platforms <sys/ioctl.h> also defines the SIOCGIF* macros.
52
 * However, on Haiku, illumos and Solaris the macros need <sys/sockio.h>,
53
 * which does not exist in AIX 7, HP-UX 11, GNU/Hurd and Linux (both GNU and
54
 * musl libc).
55
 */
56
#if defined(HAVE_SOLARIS) || defined(__HAIKU__)
57
#include <sys/sockio.h>
58
#endif
59
60
#include <net/if.h>
61
#include <netinet/in.h>
62
#endif /* _WIN32 */
63
64
#include <stdio.h>
65
#include <stdlib.h>
66
#include <string.h>
67
#include <ctype.h>
68
#if !defined(_MSC_VER) && !defined(__BORLANDC__) && !defined(__MINGW32__)
69
#include <unistd.h>
70
#endif
71
#include <fcntl.h>
72
#include <errno.h>
73
#include <limits.h>
74
75
#include "diag-control.h"
76
77
#include "thread-local.h"
78
79
#ifdef HAVE_OS_PROTO_H
80
#include "os-proto.h"
81
#endif
82
83
#include "pcap-int.h"
84
85
#include "optimize.h"
86
87
#ifdef HAVE_DAG_API
88
#include "pcap-dag.h"
89
#endif /* HAVE_DAG_API */
90
91
#ifdef HAVE_SNF_API
92
#include "pcap-snf.h"
93
#endif /* HAVE_SNF_API */
94
95
#ifdef PCAP_SUPPORT_LINUX_USBMON
96
#include "pcap-usb-linux.h"
97
#endif
98
99
#ifdef PCAP_SUPPORT_BT
100
#include "pcap-bt-linux.h"
101
#endif
102
103
#ifdef PCAP_SUPPORT_BT_MONITOR
104
#include "pcap-bt-monitor-linux.h"
105
#endif
106
107
#ifdef PCAP_SUPPORT_NETFILTER
108
#include "pcap-netfilter-linux.h"
109
#endif
110
111
#ifdef PCAP_SUPPORT_NETMAP
112
#include "pcap-netmap.h"
113
#endif
114
115
#ifdef PCAP_SUPPORT_DBUS
116
#include "pcap-dbus.h"
117
#endif
118
119
#ifdef PCAP_SUPPORT_RDMASNIFF
120
#include "pcap-rdmasniff.h"
121
#endif
122
123
#ifdef PCAP_SUPPORT_DPDK
124
#include "pcap-dpdk.h"
125
#endif
126
127
#ifdef ENABLE_REMOTE
128
#include "pcap-rpcap.h"
129
#endif
130
131
#ifdef _WIN32
132
/*
133
 * To quote the WSAStartup() documentation:
134
 *
135
 *   The WSAStartup function typically leads to protocol-specific helper
136
 *   DLLs being loaded. As a result, the WSAStartup function should not
137
 *   be called from the DllMain function in a application DLL. This can
138
 *   potentially cause deadlocks.
139
 *
140
 * and the WSACleanup() documentation:
141
 *
142
 *   The WSACleanup function typically leads to protocol-specific helper
143
 *   DLLs being unloaded. As a result, the WSACleanup function should not
144
 *   be called from the DllMain function in a application DLL. This can
145
 *   potentially cause deadlocks.
146
 *
147
 * So we don't initialize Winsock in a DllMain() routine.
148
 *
149
 * Similarly, we cannot register an atexit() handler to call WSACleanup()
150
 * because that handler will be run in the context of DllMain. Therefore, we
151
 * call WSAStartup each time Winsock is needed and WSACleanup as soon as it is
152
 * no longer needed.
153
 */
154
155
/*
156
 * Shut down Winsock.
157
 *
158
 * Ignores the return value of WSACleanup(); given that this is
159
 * an atexit() routine, there's nothing much we can do about
160
 * a failure.
161
 */
162
static void
163
internal_wsockfini(void)
164
{
165
  WSACleanup();
166
}
167
168
/*
169
 * Start Winsock.
170
 * Internal routine.
171
 */
172
static int
173
internal_wsockinit(char *errbuf)
174
{
175
  return 0;
176
}
177
178
/*
179
 * Exported in case some applications using WinPcap/Npcap called it,
180
 * even though it wasn't exported.
181
 */
182
int
183
wsockinit(void)
184
{
185
  return (internal_wsockinit(NULL));
186
}
187
188
/*
189
 * This is the exported function; new programs should call this.
190
 * *Newer* programs should call pcap_init().
191
 */
192
int
193
pcap_wsockinit(void)
194
{
195
  return (internal_wsockinit(NULL));
196
}
197
#endif /* _WIN32 */
198
199
/*
200
 * Do whatever initialization is needed for libpcap.
201
 *
202
 * The argument specifies whether we use the local code page or UTF-8
203
 * for strings; on UN*X, we just assume UTF-8 in places where the encoding
204
 * would matter, whereas, on Windows, we use the local code page for
205
 * PCAP_CHAR_ENC_LOCAL and UTF-8 for PCAP_CHAR_ENC_UTF_8.
206
 *
207
 * On Windows, we also disable the hack in pcap_create() to deal with
208
 * being handed UTF-16 strings, because if the user calls this they're
209
 * explicitly declaring that they will either be passing local code
210
 * page strings or UTF-8 strings, so we don't need to allow UTF-16LE
211
 * strings to be passed.  For good measure, on Windows *and* UN*X,
212
 * we disable pcap_lookupdev(), to prevent anybody from even
213
 * *trying* to pass the result of pcap_lookupdev() - which might be
214
 * UTF-16LE on Windows, for ugly compatibility reasons - to pcap_create()
215
 * or pcap_open_live() or pcap_open().
216
 *
217
 * Returns 0 on success, -1 on error.
218
 */
219
int pcapint_new_api;    /* pcap_lookupdev() always fails */
220
int pcapint_utf_8_mode;   /* Strings should be in UTF-8. */
221
int pcapint_mmap_32bit;   /* Map packet buffers with 32-bit addresses. */
222
223
int
224
pcap_init(unsigned int opts, char *errbuf)
225
0
{
226
0
  static int initialized;
227
228
  /*
229
   * Don't allow multiple calls that set different modes; that
230
   * may mean a library is initializing pcap in one mode and
231
   * a program using that library, or another library used by
232
   * that program, is initializing it in another mode.
233
   */
234
0
  switch (opts) {
235
236
0
  case PCAP_CHAR_ENC_LOCAL:
237
    /* Leave "UTF-8 mode" off. */
238
0
    if (initialized) {
239
0
      if (pcapint_utf_8_mode) {
240
0
        snprintf(errbuf, PCAP_ERRBUF_SIZE,
241
0
            "Multiple pcap_init calls with different character encodings");
242
0
        return (PCAP_ERROR);
243
0
      }
244
0
    }
245
0
    break;
246
247
0
  case PCAP_CHAR_ENC_UTF_8:
248
    /* Turn on "UTF-8 mode". */
249
0
    if (initialized) {
250
0
      if (!pcapint_utf_8_mode) {
251
0
        snprintf(errbuf, PCAP_ERRBUF_SIZE,
252
0
            "Multiple pcap_init calls with different character encodings");
253
0
        return (PCAP_ERROR);
254
0
      }
255
0
    }
256
0
    pcapint_utf_8_mode = 1;
257
0
    break;
258
259
0
  case PCAP_MMAP_32BIT:
260
0
    pcapint_mmap_32bit = 1;
261
0
    break;
262
263
0
  default:
264
0
    snprintf(errbuf, PCAP_ERRBUF_SIZE, "Unknown options specified");
265
0
    return (PCAP_ERROR);
266
0
  }
267
268
  /*
269
   * Turn the appropriate mode on for error messages; those routines
270
   * are also used in rpcapd, which has no access to pcap's internal
271
   * UTF-8 mode flag, so we have to call a routine to set its
272
   * UTF-8 mode flag.
273
   */
274
0
  pcapint_fmt_set_encoding(opts);
275
276
0
  if (initialized) {
277
    /*
278
     * Nothing more to do; for example, on Windows, we've
279
     * already initialized Winsock.
280
     */
281
0
    return (0);
282
0
  }
283
284
  /*
285
   * We're done.
286
   */
287
0
  initialized = 1;
288
0
  pcapint_new_api = 1;
289
0
  return (0);
290
0
}
291
292
/*
293
 * String containing the library version.
294
 * Not explicitly exported via a header file - the right API to use
295
 * is pcap_lib_version() - but some programs included it, so we
296
 * provide it.
297
 *
298
 * We declare it here, right before defining it, to squelch any
299
 * warnings we might get from compilers about the lack of a
300
 * declaration.
301
 */
302
PCAP_API char pcap_version[];
303
PCAP_API_DEF char pcap_version[] = PACKAGE_VERSION;
304
305
static void
306
pcap_set_not_initialized_message(pcap_t *pcap)
307
0
{
308
0
  if (pcap->activated) {
309
    /* A module probably forgot to set the function pointer */
310
0
    (void)snprintf(pcap->errbuf, sizeof(pcap->errbuf),
311
0
        "This operation isn't properly handled by that device");
312
0
    return;
313
0
  }
314
  /* in case the caller doesn't check for PCAP_ERROR_NOT_ACTIVATED */
315
0
  (void)snprintf(pcap->errbuf, sizeof(pcap->errbuf),
316
0
      "This handle hasn't been activated yet");
317
0
}
318
319
static int
320
pcap_read_not_initialized(pcap_t *pcap, int cnt _U_, pcap_handler callback _U_,
321
    u_char *user _U_)
322
0
{
323
0
  pcap_set_not_initialized_message(pcap);
324
  /* this means 'not initialized' */
325
0
  return (PCAP_ERROR_NOT_ACTIVATED);
326
0
}
327
328
static int
329
pcap_inject_not_initialized(pcap_t *pcap, const void * buf _U_, int size _U_)
330
0
{
331
0
  pcap_set_not_initialized_message(pcap);
332
  /* this means 'not initialized' */
333
0
  return (PCAP_ERROR_NOT_ACTIVATED);
334
0
}
335
336
static int
337
pcap_setfilter_not_initialized(pcap_t *pcap, struct bpf_program *fp _U_)
338
0
{
339
0
  pcap_set_not_initialized_message(pcap);
340
  /* this means 'not initialized' */
341
0
  return (PCAP_ERROR_NOT_ACTIVATED);
342
0
}
343
344
static int
345
pcap_setdirection_not_initialized(pcap_t *pcap, pcap_direction_t d _U_)
346
0
{
347
0
  pcap_set_not_initialized_message(pcap);
348
  /* this means 'not initialized' */
349
0
  return (PCAP_ERROR_NOT_ACTIVATED);
350
0
}
351
352
static int
353
pcap_set_datalink_not_initialized(pcap_t *pcap, int dlt _U_)
354
0
{
355
0
  pcap_set_not_initialized_message(pcap);
356
  /* this means 'not initialized' */
357
0
  return (PCAP_ERROR_NOT_ACTIVATED);
358
0
}
359
360
static int
361
pcap_getnonblock_not_initialized(pcap_t *pcap)
362
0
{
363
0
  pcap_set_not_initialized_message(pcap);
364
  /* this means 'not initialized' */
365
0
  return (PCAP_ERROR_NOT_ACTIVATED);
366
0
}
367
368
static int
369
pcap_stats_not_initialized(pcap_t *pcap, struct pcap_stat *ps _U_)
370
0
{
371
0
  pcap_set_not_initialized_message(pcap);
372
  /* this means 'not initialized' */
373
0
  return (PCAP_ERROR_NOT_ACTIVATED);
374
0
}
375
376
#ifdef _WIN32
377
static struct pcap_stat *
378
pcap_stats_ex_not_initialized(pcap_t *pcap, int *pcap_stat_size _U_)
379
{
380
  pcap_set_not_initialized_message(pcap);
381
  return (NULL);
382
}
383
384
static int
385
pcap_setbuff_not_initialized(pcap_t *pcap, int dim _U_)
386
{
387
  pcap_set_not_initialized_message(pcap);
388
  /* this means 'not initialized' */
389
  return (PCAP_ERROR_NOT_ACTIVATED);
390
}
391
392
static int
393
pcap_setmode_not_initialized(pcap_t *pcap, int mode _U_)
394
{
395
  pcap_set_not_initialized_message(pcap);
396
  /* this means 'not initialized' */
397
  return (PCAP_ERROR_NOT_ACTIVATED);
398
}
399
400
static int
401
pcap_setmintocopy_not_initialized(pcap_t *pcap, int size _U_)
402
{
403
  pcap_set_not_initialized_message(pcap);
404
  /* this means 'not initialized' */
405
  return (PCAP_ERROR_NOT_ACTIVATED);
406
}
407
408
static HANDLE
409
pcap_getevent_not_initialized(pcap_t *pcap)
410
{
411
  pcap_set_not_initialized_message(pcap);
412
  return (INVALID_HANDLE_VALUE);
413
}
414
415
static int
416
pcap_oid_get_request_not_initialized(pcap_t *pcap, bpf_u_int32 oid _U_,
417
    void *data _U_, size_t *lenp _U_)
418
{
419
  pcap_set_not_initialized_message(pcap);
420
  return (PCAP_ERROR_NOT_ACTIVATED);
421
}
422
423
static int
424
pcap_oid_set_request_not_initialized(pcap_t *pcap, bpf_u_int32 oid _U_,
425
    const void *data _U_, size_t *lenp _U_)
426
{
427
  pcap_set_not_initialized_message(pcap);
428
  return (PCAP_ERROR_NOT_ACTIVATED);
429
}
430
431
static u_int
432
pcap_sendqueue_transmit_not_initialized(pcap_t *pcap, pcap_send_queue* queue _U_,
433
    int sync _U_)
434
{
435
  pcap_set_not_initialized_message(pcap);
436
  return (0);
437
}
438
439
static int
440
pcap_setuserbuffer_not_initialized(pcap_t *pcap, int size _U_)
441
{
442
  pcap_set_not_initialized_message(pcap);
443
  return (PCAP_ERROR_NOT_ACTIVATED);
444
}
445
446
static int
447
pcap_live_dump_not_initialized(pcap_t *pcap, char *filename _U_, int maxsize _U_,
448
    int maxpacks _U_)
449
{
450
  pcap_set_not_initialized_message(pcap);
451
  return (PCAP_ERROR_NOT_ACTIVATED);
452
}
453
454
static int
455
pcap_live_dump_ended_not_initialized(pcap_t *pcap, int sync _U_)
456
{
457
  pcap_set_not_initialized_message(pcap);
458
  return (PCAP_ERROR_NOT_ACTIVATED);
459
}
460
#endif
461
462
/*
463
 * Returns 1 if rfmon mode can be set on the pcap_t, 0 if it can't,
464
 * a PCAP_ERROR value on an error.
465
 */
466
int
467
pcap_can_set_rfmon(pcap_t *p)
468
0
{
469
0
  return (p->can_set_rfmon_op(p));
470
0
}
471
472
/*
473
 * For systems where rfmon mode is never supported.
474
 */
475
static int
476
pcap_cant_set_rfmon(pcap_t *p _U_)
477
0
{
478
0
  return (0);
479
0
}
480
481
/*
482
 * Sets *tstamp_typesp to point to an array 1 or more supported time stamp
483
 * types; the return value is the number of supported time stamp types.
484
 * The list should be freed by a call to pcap_free_tstamp_types() when
485
 * you're done with it.
486
 *
487
 * A return value of 0 means "you don't get a choice of time stamp type",
488
 * in which case *tstamp_typesp is set to null.
489
 *
490
 * PCAP_ERROR is returned on error.
491
 */
492
int
493
pcap_list_tstamp_types(pcap_t *p, int **tstamp_typesp)
494
0
{
495
0
  if (p->tstamp_type_count == 0) {
496
    /*
497
     * We don't support multiple time stamp types.
498
     * That means the only type we support is PCAP_TSTAMP_HOST;
499
     * set up a list containing only that type.
500
     */
501
0
    *tstamp_typesp = (int*)malloc(sizeof(**tstamp_typesp));
502
0
    if (*tstamp_typesp == NULL) {
503
0
      pcapint_fmt_errmsg_for_errno(p->errbuf, sizeof(p->errbuf),
504
0
          errno, "malloc");
505
0
      return (PCAP_ERROR);
506
0
    }
507
0
    **tstamp_typesp = PCAP_TSTAMP_HOST;
508
0
    return (1);
509
0
  } else {
510
0
    *tstamp_typesp = (int*)calloc(p->tstamp_type_count,
511
0
                sizeof(**tstamp_typesp));
512
0
    if (*tstamp_typesp == NULL) {
513
0
      pcapint_fmt_errmsg_for_errno(p->errbuf, sizeof(p->errbuf),
514
0
          errno, "malloc");
515
0
      return (PCAP_ERROR);
516
0
    }
517
0
    (void)memcpy(*tstamp_typesp, p->tstamp_type_list,
518
0
        sizeof(**tstamp_typesp) * p->tstamp_type_count);
519
0
    return (p->tstamp_type_count);
520
0
  }
521
0
}
522
523
/*
524
 * In Windows, you might have a library built with one version of the
525
 * C runtime library and an application built with another version of
526
 * the C runtime library, which means that the library might use one
527
 * version of malloc() and free() and the application might use another
528
 * version of malloc() and free().  If so, that means something
529
 * allocated by the library cannot be freed by the application, so we
530
 * need to have a pcap_free_tstamp_types() routine to free up the list
531
 * allocated by pcap_list_tstamp_types(), even though it's just a wrapper
532
 * around free().
533
 */
534
void
535
pcap_free_tstamp_types(int *tstamp_type_list)
536
0
{
537
0
  free(tstamp_type_list);
538
0
}
539
540
/*
541
 * Default one-shot callback; overridden for capture types where the
542
 * packet data cannot be guaranteed to be available after the callback
543
 * returns, so that a copy must be made.
544
 */
545
void
546
pcapint_oneshot(u_char *user, const struct pcap_pkthdr *h, const u_char *pkt)
547
55.5k
{
548
55.5k
  struct oneshot_userdata *sp = (struct oneshot_userdata *)user;
549
550
55.5k
  *sp->hdr = *h;
551
55.5k
  *sp->pkt = pkt;
552
55.5k
}
553
554
const u_char *
555
pcap_next(pcap_t *p, struct pcap_pkthdr *h)
556
0
{
557
0
  struct oneshot_userdata s;
558
0
  const u_char *pkt;
559
560
0
  s.hdr = h;
561
0
  s.pkt = &pkt;
562
0
  s.pd = p;
563
0
  if (pcap_dispatch(p, 1, p->oneshot_callback, (u_char *)&s) <= 0)
564
0
    return (0);
565
0
  return (pkt);
566
0
}
567
568
int
569
pcap_next_ex(pcap_t *p, struct pcap_pkthdr **pkt_header,
570
    const u_char **pkt_data)
571
66.1k
{
572
66.1k
  struct oneshot_userdata s;
573
574
66.1k
  s.hdr = &p->pcap_header;
575
66.1k
  s.pkt = pkt_data;
576
66.1k
  s.pd = p;
577
578
  /* Saves a pointer to the packet headers */
579
66.1k
  *pkt_header= &p->pcap_header;
580
581
66.1k
  if (p->rfile != NULL) {
582
66.1k
    int status;
583
584
    /* We are on an offline capture */
585
66.1k
    status = pcapint_offline_read(p, 1, p->oneshot_callback,
586
66.1k
        (u_char *)&s);
587
588
    /*
589
     * Return codes for pcapint_offline_read() are:
590
     *   -  0: EOF
591
     *   - -1: error
592
     *   - >0: OK - result is number of packets read, so
593
     *         it will be 1 in this case, as we've passed
594
     *         a maximum packet count of 1
595
     * The first one ('0') conflicts with the return code of
596
     * 0 from pcap_read() meaning "no packets arrived before
597
     * the timeout expired", so we map it to -2 so you can
598
     * distinguish between an EOF from a savefile and a
599
     * "no packets arrived before the timeout expired, try
600
     * again" from a live capture.
601
     */
602
66.1k
    if (status == 0)
603
7.66k
      return (-2);
604
58.5k
    else
605
58.5k
      return (status);
606
66.1k
  }
607
608
  /*
609
   * Return codes for pcap_read() are:
610
   *   -  0: timeout
611
   *   - -1: error
612
   *   - -2: loop was broken out of with pcap_breakloop()
613
   *   - >0: OK, result is number of packets captured, so
614
   *         it will be 1 in this case, as we've passed
615
   *         a maximum packet count of 1
616
   * The first one ('0') conflicts with the return code of 0 from
617
   * pcapint_offline_read() meaning "end of file".
618
  */
619
0
  return (p->read_op(p, 1, p->oneshot_callback, (u_char *)&s));
620
66.1k
}
621
622
/*
623
 * Implementation of a pcap_if_list_t.
624
 */
625
struct pcap_if_list {
626
  pcap_if_t *beginning;
627
};
628
629
static struct capture_source_type {
630
  int (*findalldevs_op)(pcap_if_list_t *, char *);
631
  pcap_t *(*create_op)(const char *, char *, int *);
632
} capture_source_types[] = {
633
#ifdef HAVE_DAG_API
634
  { dag_findalldevs, dag_create },
635
#endif
636
#ifdef HAVE_SNF_API
637
  { snf_findalldevs, snf_create },
638
#endif
639
#ifdef PCAP_SUPPORT_BT
640
  { bt_findalldevs, bt_create },
641
#endif
642
#ifdef PCAP_SUPPORT_BT_MONITOR
643
  { bt_monitor_findalldevs, bt_monitor_create },
644
#endif
645
#ifdef PCAP_SUPPORT_LINUX_USBMON
646
  { usb_findalldevs, usb_create },
647
#endif
648
#ifdef PCAP_SUPPORT_NETFILTER
649
  { netfilter_findalldevs, netfilter_create },
650
#endif
651
#ifdef PCAP_SUPPORT_NETMAP
652
  { pcap_netmap_findalldevs, pcap_netmap_create },
653
#endif
654
#ifdef PCAP_SUPPORT_DBUS
655
  { dbus_findalldevs, dbus_create },
656
#endif
657
#ifdef PCAP_SUPPORT_RDMASNIFF
658
  { rdmasniff_findalldevs, rdmasniff_create },
659
#endif
660
#ifdef PCAP_SUPPORT_DPDK
661
  { pcap_dpdk_findalldevs, pcap_dpdk_create },
662
#endif
663
  { NULL, NULL }
664
};
665
666
/*
667
 * Get a list of all capture sources that are up and that we can open.
668
 * Returns -1 on error, 0 otherwise.
669
 * The list, as returned through "alldevsp", may be null if no interfaces
670
 * were up and could be opened.
671
 */
672
int
673
pcap_findalldevs(pcap_if_t **alldevsp, char *errbuf)
674
0
{
675
0
  size_t i;
676
0
  pcap_if_list_t devlist;
677
678
  /*
679
   * Find all the local network interfaces on which we
680
   * can capture.
681
   */
682
0
  devlist.beginning = NULL;
683
0
  if (pcapint_platform_finddevs(&devlist, errbuf) == -1) {
684
    /*
685
     * Failed - free all of the entries we were given
686
     * before we failed.
687
     */
688
0
    if (devlist.beginning != NULL)
689
0
      pcap_freealldevs(devlist.beginning);
690
0
    *alldevsp = NULL;
691
0
    return (-1);
692
0
  }
693
694
  /*
695
   * Ask each of the non-local-network-interface capture
696
   * source types what interfaces they have.
697
   */
698
0
  for (i = 0; capture_source_types[i].findalldevs_op != NULL; i++) {
699
0
    if (capture_source_types[i].findalldevs_op(&devlist, errbuf) == -1) {
700
      /*
701
       * We had an error; free the list we've been
702
       * constructing.
703
       */
704
0
      if (devlist.beginning != NULL)
705
0
        pcap_freealldevs(devlist.beginning);
706
0
      *alldevsp = NULL;
707
0
      return (-1);
708
0
    }
709
0
  }
710
711
  /*
712
   * Return the first entry of the list of all devices.
713
   */
714
0
  *alldevsp = devlist.beginning;
715
0
  return (0);
716
0
}
717
718
static struct sockaddr *
719
dup_sockaddr(struct sockaddr *sa, size_t sa_length)
720
0
{
721
0
  struct sockaddr *newsa;
722
723
0
  if ((newsa = malloc(sa_length)) == NULL)
724
0
    return (NULL);
725
0
  return (memcpy(newsa, sa, sa_length));
726
0
}
727
728
/*
729
 * Construct a "figure of merit" for an interface, for use when sorting
730
 * the list of interfaces, in which interfaces that are up are superior
731
 * to interfaces that aren't up, interfaces that are up and running are
732
 * superior to interfaces that are up but not running, and non-loopback
733
 * interfaces that are up and running are superior to loopback interfaces,
734
 * and interfaces with the same flags have a figure of merit that's higher
735
 * the lower the instance number.
736
 *
737
 * The goal is to try to put the interfaces most likely to be useful for
738
 * capture at the beginning of the list.
739
 *
740
 * The figure of merit, which is lower the "better" the interface is,
741
 * has the uppermost bit set if the interface isn't running, the bit
742
 * below that set if the interface isn't up, the bit below that
743
 * set if the interface is a loopback interface, and the bit below
744
 * that set if it's the "any" interface.
745
 *
746
 * Note: we don't sort by unit number because 1) not all interfaces have
747
 * a unit number (systemd, for example, might assign interface names
748
 * based on the interface's MAC address or on the physical location of
749
 * the adapter's connector), and 2) if the name does end with a simple
750
 * unit number, it's not a global property of the interface, it's only
751
 * useful as a sort key for device names with the same prefix, so xyz0
752
 * shouldn't necessarily sort before abc2.  This means that interfaces
753
 * with the same figure of merit will be sorted by the order in which
754
 * the mechanism from which we're getting the interfaces supplies them.
755
 */
756
static u_int
757
get_figure_of_merit(pcap_if_t *dev)
758
0
{
759
0
  u_int n;
760
761
0
  n = 0;
762
0
  if (!(dev->flags & PCAP_IF_RUNNING))
763
0
    n |= 0x80000000;
764
0
  if (!(dev->flags & PCAP_IF_UP))
765
0
    n |= 0x40000000;
766
767
  /*
768
   * Give non-wireless interfaces that aren't disconnected a better
769
   * figure of merit than interfaces that are disconnected, as
770
   * "disconnected" should indicate that the interface isn't
771
   * plugged into a network and thus won't give you any traffic.
772
   *
773
   * For wireless interfaces, it means "associated with a network",
774
   * which we presume not to necessarily prevent capture, as you
775
   * might run the adapter in some flavor of monitor mode.
776
   */
777
0
  if (!(dev->flags & PCAP_IF_WIRELESS) &&
778
0
      (dev->flags & PCAP_IF_CONNECTION_STATUS) == PCAP_IF_CONNECTION_STATUS_DISCONNECTED)
779
0
    n |= 0x20000000;
780
781
  /*
782
   * Sort loopback devices after non-loopback devices, *except* for
783
   * disconnected devices.
784
   */
785
0
  if (dev->flags & PCAP_IF_LOOPBACK)
786
0
    n |= 0x10000000;
787
788
  /*
789
   * Sort the "any" device before loopback and disconnected devices,
790
   * but after all other devices.
791
   */
792
0
  if (strcmp(dev->name, "any") == 0)
793
0
    n |= 0x08000000;
794
795
0
  return (n);
796
0
}
797
798
#ifndef _WIN32
799
/*
800
 * Try to get a description for a given device.
801
 * Returns a malloced description if it could and NULL if it couldn't.
802
 *
803
 * XXX - on FreeBSDs that support it, should it get the sysctl named
804
 * "dev.{adapter family name}.{adapter unit}.%desc" to get a description
805
 * of the adapter?  Note that "dev.an.0.%desc" is "Aironet PC4500/PC4800"
806
 * with my Cisco 350 card, so the name isn't entirely descriptive.  The
807
 * "dev.an.0.%pnpinfo" has a better description, although one might argue
808
 * that the problem is really a driver bug - if it can find out that it's
809
 * a Cisco 340 or 350, rather than an old Aironet card, it should use
810
 * that in the description.
811
 *
812
 * Do NetBSD, DragonflyBSD, or OpenBSD support this as well?  FreeBSD
813
 * and OpenBSD let you get a description, but it's not generated by the OS,
814
 * it's set with another ioctl that ifconfig supports; we use that to get
815
 * a description in FreeBSD and OpenBSD, but if there is no such
816
 * description available, it still might be nice to get some description
817
 * string based on the device type or something such as that.
818
 *
819
 * In macOS, the System Configuration framework can apparently return
820
 * names in 10.4 and later.
821
 *
822
 * It also appears that freedesktop.org's HAL offers an "info.product"
823
 * string, but the HAL specification says it "should not be used in any
824
 * UI" and "subsystem/capability specific properties" should be used
825
 * instead and, in any case, I think HAL is being deprecated in
826
 * favor of other stuff such as DeviceKit.  DeviceKit doesn't appear
827
 * to have any obvious product information for devices, but maybe
828
 * I haven't looked hard enough.
829
 *
830
 * Using the System Configuration framework, or HAL, or DeviceKit, or
831
 * whatever, would require that libpcap applications be linked with
832
 * the frameworks/libraries in question.  That shouldn't be a problem
833
 * for programs linking with the shared version of libpcap (unless
834
 * you're running on AIX - which I think is the only UN*X that doesn't
835
 * support linking a shared library with other libraries on which it
836
 * depends, and having an executable linked only with the first shared
837
 * library automatically pick up the other libraries when started -
838
 * and using HAL or whatever).  Programs linked with the static
839
 * version of libpcap would have to use pcap-config with the --static
840
 * flag in order to get the right linker flags in order to pick up
841
 * the additional libraries/frameworks; those programs need that anyway
842
 * for libpcap 1.1 and beyond on Linux, as, by default, it requires
843
 * -lnl.
844
 *
845
 * Do any other UN*Xes, or desktop environments support getting a
846
 * description?
847
 */
848
static char *
849
#ifdef SIOCGIFDESCR
850
get_if_description(const char *name)
851
{
852
  char *description = NULL;
853
  int s;
854
  struct ifreq ifrdesc;
855
#ifndef IFDESCRSIZE
856
  size_t descrlen = 64;
857
#else
858
  size_t descrlen = IFDESCRSIZE;
859
#endif /* IFDESCRSIZE */
860
861
  /*
862
   * Get the description for the interface.
863
   */
864
  memset(&ifrdesc, 0, sizeof ifrdesc);
865
  pcapint_strlcpy(ifrdesc.ifr_name, name, sizeof ifrdesc.ifr_name);
866
  s = socket(AF_INET, SOCK_DGRAM, 0);
867
  if (s >= 0) {
868
#ifdef __FreeBSD__
869
    /*
870
     * On FreeBSD, if the buffer isn't big enough for the
871
     * description, the ioctl succeeds, but the description
872
     * isn't copied, ifr_buffer.length is set to the description
873
     * length, and ifr_buffer.buffer is set to NULL.
874
     */
875
    for (;;) {
876
      free(description);
877
      if ((description = malloc(descrlen)) != NULL) {
878
        ifrdesc.ifr_buffer.buffer = description;
879
        ifrdesc.ifr_buffer.length = descrlen;
880
        if (ioctl(s, SIOCGIFDESCR, &ifrdesc) == 0) {
881
          if (ifrdesc.ifr_buffer.buffer ==
882
              description)
883
            break;
884
          else
885
            descrlen = ifrdesc.ifr_buffer.length;
886
        } else {
887
          /*
888
           * Failed to get interface description.
889
           */
890
          free(description);
891
          description = NULL;
892
          break;
893
        }
894
      } else
895
        break;
896
    }
897
#else /* __FreeBSD__ */
898
    /*
899
     * The only other OS that currently supports
900
     * SIOCGIFDESCR is OpenBSD, and it has no way
901
     * to get the description length - it's clamped
902
     * to a maximum of IFDESCRSIZE.
903
     */
904
    if ((description = malloc(descrlen)) != NULL) {
905
      ifrdesc.ifr_data = (caddr_t)description;
906
      if (ioctl(s, SIOCGIFDESCR, &ifrdesc) != 0) {
907
        /*
908
         * Failed to get interface description.
909
         */
910
        free(description);
911
        description = NULL;
912
      }
913
    }
914
#endif /* __FreeBSD__ */
915
    close(s);
916
    if (description != NULL && description[0] == '\0') {
917
      /*
918
       * Description is empty, so discard it.
919
       */
920
      free(description);
921
      description = NULL;
922
    }
923
  }
924
925
#ifdef __FreeBSD__
926
  /*
927
   * For FreeBSD, if we didn't get a description, and this is
928
   * a device with a name of the form usbusN, label it as a USB
929
   * bus.
930
   */
931
  if (description == NULL) {
932
    if (strncmp(name, "usbus", 5) == 0) {
933
      /*
934
       * OK, it begins with "usbus".
935
       */
936
      long busnum;
937
      char *p;
938
939
      errno = 0;
940
      busnum = strtol(name + 5, &p, 10);
941
      if (errno == 0 && p != name + 5 && *p == '\0' &&
942
          busnum >= 0 && busnum <= INT_MAX) {
943
        /*
944
         * OK, it's a valid number that's not
945
         * bigger than INT_MAX.  Construct
946
         * a description from it.
947
         * (If that fails, we don't worry about
948
         * it, we just return NULL.)
949
         */
950
        if (pcapint_asprintf(&description,
951
            "USB bus number %ld", busnum) == -1) {
952
          /* Failed. */
953
          description = NULL;
954
        }
955
      }
956
    }
957
  }
958
#endif
959
  return (description);
960
#else /* SIOCGIFDESCR */
961
get_if_description(const char *name _U_)
962
0
{
963
0
  return (NULL);
964
0
#endif /* SIOCGIFDESCR */
965
0
}
966
967
/*
968
 * Look for a given device in the specified list of devices.
969
 *
970
 * If we find it, return a pointer to its entry.
971
 *
972
 * If we don't find it, attempt to add an entry for it, with the specified
973
 * IFF_ flags and description, and, if that succeeds, return a pointer to
974
 * the new entry, otherwise return NULL and set errbuf to an error message.
975
 */
976
pcap_if_t *
977
pcapint_find_or_add_if(pcap_if_list_t *devlistp, const char *name,
978
    uint64_t if_flags, get_if_flags_func get_flags_func, char *errbuf)
979
0
{
980
0
  bpf_u_int32 pcap_flags;
981
982
  /*
983
   * Convert IFF_ flags to pcap flags.
984
   */
985
0
  pcap_flags = 0;
986
0
#ifdef IFF_LOOPBACK
987
0
  if (if_flags & IFF_LOOPBACK)
988
0
    pcap_flags |= PCAP_IF_LOOPBACK;
989
#else
990
  /*
991
   * We don't have IFF_LOOPBACK, so look at the device name to
992
   * see if it looks like a loopback device.
993
   */
994
  if (name[0] == 'l' && name[1] == 'o' &&
995
      (PCAP_ISDIGIT(name[2]) || name[2] == '\0'))
996
    pcap_flags |= PCAP_IF_LOOPBACK;
997
#endif
998
0
#ifdef IFF_UP
999
0
  if (if_flags & IFF_UP)
1000
0
    pcap_flags |= PCAP_IF_UP;
1001
0
#endif
1002
0
#ifdef IFF_RUNNING
1003
0
  if (if_flags & IFF_RUNNING)
1004
0
    pcap_flags |= PCAP_IF_RUNNING;
1005
0
#endif
1006
1007
  /*
1008
   * Attempt to find an entry for this device; if we don't find one,
1009
   * attempt to add one.
1010
   */
1011
0
  return (pcapint_find_or_add_dev(devlistp, name, pcap_flags,
1012
0
      get_flags_func, get_if_description(name), errbuf));
1013
0
}
1014
1015
/*
1016
 * Look for a given device in the specified list of devices.
1017
 *
1018
 * If we find it, then, if the specified address isn't null, add it to
1019
 * the list of addresses for the device and return 0.
1020
 *
1021
 * If we don't find it, attempt to add an entry for it, with the specified
1022
 * IFF_ flags and description, and, if that succeeds, add the specified
1023
 * address to its list of addresses if that address is non-null, and
1024
 * return 0, otherwise return -1 and set errbuf to an error message.
1025
 *
1026
 * (We can get called with a null address because we might get a list
1027
 * of interface name/address combinations from the underlying OS, with
1028
 * the address being absent in some cases, rather than a list of
1029
 * interfaces with each interface having a list of addresses, so this
1030
 * call may be the only call made to add to the list, and we want to
1031
 * add interfaces even if they have no addresses.)
1032
 */
1033
int
1034
pcapint_add_addr_to_if(pcap_if_list_t *devlistp, const char *name,
1035
    uint64_t if_flags, get_if_flags_func get_flags_func,
1036
    struct sockaddr *addr, size_t addr_size,
1037
    struct sockaddr *netmask, size_t netmask_size,
1038
    struct sockaddr *broadaddr, size_t broadaddr_size,
1039
    struct sockaddr *dstaddr, size_t dstaddr_size,
1040
    char *errbuf)
1041
0
{
1042
0
  pcap_if_t *curdev;
1043
1044
  /*
1045
   * Check whether the device exists and, if not, add it.
1046
   */
1047
0
  curdev = pcapint_find_or_add_if(devlistp, name, if_flags, get_flags_func,
1048
0
      errbuf);
1049
0
  if (curdev == NULL) {
1050
    /*
1051
     * Error - give up.
1052
     */
1053
0
    return (-1);
1054
0
  }
1055
1056
0
  if (addr == NULL) {
1057
    /*
1058
     * There's no address to add; this entry just meant
1059
     * "here's a new interface".
1060
     */
1061
0
    return (0);
1062
0
  }
1063
1064
  /*
1065
   * "curdev" is an entry for this interface, and we have an
1066
   * address for it; add an entry for that address to the
1067
   * interface's list of addresses.
1068
   */
1069
0
  return (pcapint_add_addr_to_dev(curdev, addr, addr_size, netmask,
1070
0
      netmask_size, broadaddr, broadaddr_size, dstaddr,
1071
0
      dstaddr_size, errbuf));
1072
0
}
1073
#endif /* _WIN32 */
1074
1075
/*
1076
 * Add an entry to the list of addresses for an interface.
1077
 * "curdev" is the entry for that interface.
1078
 */
1079
int
1080
pcapint_add_addr_to_dev(pcap_if_t *curdev,
1081
    struct sockaddr *addr, size_t addr_size,
1082
    struct sockaddr *netmask, size_t netmask_size,
1083
    struct sockaddr *broadaddr, size_t broadaddr_size,
1084
    struct sockaddr *dstaddr, size_t dstaddr_size,
1085
    char *errbuf)
1086
0
{
1087
0
  pcap_addr_t *curaddr, *prevaddr, *nextaddr;
1088
1089
  /*
1090
   * Allocate the new entry and fill it in.
1091
   */
1092
0
  curaddr = (pcap_addr_t *)malloc(sizeof(pcap_addr_t));
1093
0
  if (curaddr == NULL) {
1094
0
    pcapint_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1095
0
        errno, "malloc");
1096
0
    return (-1);
1097
0
  }
1098
1099
0
  curaddr->next = NULL;
1100
0
  if (addr != NULL && addr_size != 0) {
1101
0
    curaddr->addr = (struct sockaddr *)dup_sockaddr(addr, addr_size);
1102
0
    if (curaddr->addr == NULL) {
1103
0
      pcapint_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1104
0
          errno, "malloc");
1105
0
      free(curaddr);
1106
0
      return (-1);
1107
0
    }
1108
0
  } else
1109
0
    curaddr->addr = NULL;
1110
1111
0
  if (netmask != NULL && netmask_size != 0) {
1112
0
    curaddr->netmask = (struct sockaddr *)dup_sockaddr(netmask, netmask_size);
1113
0
    if (curaddr->netmask == NULL) {
1114
0
      pcapint_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1115
0
          errno, "malloc");
1116
0
      if (curaddr->addr != NULL)
1117
0
        free(curaddr->addr);
1118
0
      free(curaddr);
1119
0
      return (-1);
1120
0
    }
1121
0
  } else
1122
0
    curaddr->netmask = NULL;
1123
1124
0
  if (broadaddr != NULL && broadaddr_size != 0) {
1125
0
    curaddr->broadaddr = (struct sockaddr *)dup_sockaddr(broadaddr, broadaddr_size);
1126
0
    if (curaddr->broadaddr == NULL) {
1127
0
      pcapint_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1128
0
          errno, "malloc");
1129
0
      if (curaddr->netmask != NULL)
1130
0
        free(curaddr->netmask);
1131
0
      if (curaddr->addr != NULL)
1132
0
        free(curaddr->addr);
1133
0
      free(curaddr);
1134
0
      return (-1);
1135
0
    }
1136
0
  } else
1137
0
    curaddr->broadaddr = NULL;
1138
1139
0
  if (dstaddr != NULL && dstaddr_size != 0) {
1140
0
    curaddr->dstaddr = (struct sockaddr *)dup_sockaddr(dstaddr, dstaddr_size);
1141
0
    if (curaddr->dstaddr == NULL) {
1142
0
      pcapint_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1143
0
          errno, "malloc");
1144
0
      if (curaddr->broadaddr != NULL)
1145
0
        free(curaddr->broadaddr);
1146
0
      if (curaddr->netmask != NULL)
1147
0
        free(curaddr->netmask);
1148
0
      if (curaddr->addr != NULL)
1149
0
        free(curaddr->addr);
1150
0
      free(curaddr);
1151
0
      return (-1);
1152
0
    }
1153
0
  } else
1154
0
    curaddr->dstaddr = NULL;
1155
1156
  /*
1157
   * Find the end of the list of addresses.
1158
   */
1159
0
  for (prevaddr = curdev->addresses; prevaddr != NULL; prevaddr = nextaddr) {
1160
0
    nextaddr = prevaddr->next;
1161
0
    if (nextaddr == NULL) {
1162
      /*
1163
       * This is the end of the list.
1164
       */
1165
0
      break;
1166
0
    }
1167
0
  }
1168
1169
0
  if (prevaddr == NULL) {
1170
    /*
1171
     * The list was empty; this is the first member.
1172
     */
1173
0
    curdev->addresses = curaddr;
1174
0
  } else {
1175
    /*
1176
     * "prevaddr" is the last member of the list; append
1177
     * this member to it.
1178
     */
1179
0
    prevaddr->next = curaddr;
1180
0
  }
1181
1182
0
  return (0);
1183
0
}
1184
1185
/*
1186
 * Look for a given device in the specified list of devices.
1187
 *
1188
 * If we find it, return 0 and set *curdev_ret to point to it.
1189
 *
1190
 * If we don't find it, attempt to add an entry for it, with the specified
1191
 * flags and description, and, if that succeeds, return 0, otherwise
1192
 * return -1 and set errbuf to an error message.
1193
 */
1194
pcap_if_t *
1195
pcapint_find_or_add_dev(pcap_if_list_t *devlistp, const char *name, bpf_u_int32 flags,
1196
    get_if_flags_func get_flags_func, const char *description, char *errbuf)
1197
0
{
1198
0
  pcap_if_t *curdev;
1199
1200
  /*
1201
   * Is there already an entry in the list for this device?
1202
   */
1203
0
  curdev = pcapint_find_dev(devlistp, name);
1204
0
  if (curdev != NULL) {
1205
    /*
1206
     * Yes, return it.
1207
     */
1208
0
    return (curdev);
1209
0
  }
1210
1211
  /*
1212
   * No, we didn't find it.
1213
   */
1214
1215
  /*
1216
   * Try to get additional flags for the device.
1217
   */
1218
0
  if ((*get_flags_func)(name, &flags, errbuf) == -1) {
1219
    /*
1220
     * Failed.
1221
     */
1222
0
    return (NULL);
1223
0
  }
1224
1225
  /*
1226
   * Now, try to add it to the list of devices.
1227
   */
1228
0
  return (pcapint_add_dev(devlistp, name, flags, description, errbuf));
1229
0
}
1230
1231
/*
1232
 * Look for a given device in the specified list of devices, and return
1233
 * the entry for it if we find it or NULL if we don't.
1234
 */
1235
pcap_if_t *
1236
pcapint_find_dev(pcap_if_list_t *devlistp, const char *name)
1237
0
{
1238
0
  pcap_if_t *curdev;
1239
1240
  /*
1241
   * Is there an entry in the list for this device?
1242
   */
1243
0
  for (curdev = devlistp->beginning; curdev != NULL;
1244
0
      curdev = curdev->next) {
1245
0
    if (strcmp(name, curdev->name) == 0) {
1246
      /*
1247
       * We found it, so, yes, there is.  No need to
1248
       * add it.  Provide the entry we found to our
1249
       * caller.
1250
       */
1251
0
      return (curdev);
1252
0
    }
1253
0
  }
1254
1255
  /*
1256
   * No.
1257
   */
1258
0
  return (NULL);
1259
0
}
1260
1261
/*
1262
 * Attempt to add an entry for a device, with the specified flags
1263
 * and description, and, if that succeeds, return 0 and return a pointer
1264
 * to the new entry, otherwise return NULL and set errbuf to an error
1265
 * message.
1266
 *
1267
 * If we weren't given a description, try to get one.
1268
 */
1269
pcap_if_t *
1270
pcapint_add_dev(pcap_if_list_t *devlistp, const char *name, bpf_u_int32 flags,
1271
    const char *description, char *errbuf)
1272
0
{
1273
0
  pcap_if_t *curdev, *prevdev, *nextdev;
1274
0
  u_int this_figure_of_merit, nextdev_figure_of_merit;
1275
1276
0
  curdev = malloc(sizeof(pcap_if_t));
1277
0
  if (curdev == NULL) {
1278
0
    pcapint_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1279
0
        errno, "malloc");
1280
0
    return (NULL);
1281
0
  }
1282
1283
  /*
1284
   * Fill in the entry.
1285
   */
1286
0
  curdev->next = NULL;
1287
0
  curdev->name = strdup(name);
1288
0
  if (curdev->name == NULL) {
1289
0
    pcapint_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1290
0
        errno, "malloc");
1291
0
    free(curdev);
1292
0
    return (NULL);
1293
0
  }
1294
0
  if (description == NULL) {
1295
    /*
1296
     * We weren't handed a description for the interface.
1297
     */
1298
0
    curdev->description = NULL;
1299
0
  } else {
1300
    /*
1301
     * We were handed a description; make a copy.
1302
     */
1303
0
    curdev->description = strdup(description);
1304
0
    if (curdev->description == NULL) {
1305
0
      pcapint_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1306
0
          errno, "malloc");
1307
0
      free(curdev->name);
1308
0
      free(curdev);
1309
0
      return (NULL);
1310
0
    }
1311
0
  }
1312
0
  curdev->addresses = NULL; /* list starts out as empty */
1313
0
  curdev->flags = flags;
1314
1315
  /*
1316
   * Add it to the list, in the appropriate location.
1317
   * First, get the "figure of merit" for this interface.
1318
   *
1319
   * To have the list of devices ordered correctly, after adding a
1320
   * device to the list the device flags value must not change (i.e. it
1321
   * should be set correctly beforehand).
1322
   */
1323
0
  this_figure_of_merit = get_figure_of_merit(curdev);
1324
1325
  /*
1326
   * Now look for the last interface with an figure of merit
1327
   * less than or equal to the new interface's figure of merit.
1328
   *
1329
   * We start with "prevdev" being NULL, meaning we're before
1330
   * the first element in the list.
1331
   */
1332
0
  prevdev = NULL;
1333
0
  for (;;) {
1334
    /*
1335
     * Get the interface after this one.
1336
     */
1337
0
    if (prevdev == NULL) {
1338
      /*
1339
       * The next element is the first element.
1340
       */
1341
0
      nextdev = devlistp->beginning;
1342
0
    } else
1343
0
      nextdev = prevdev->next;
1344
1345
    /*
1346
     * Are we at the end of the list?
1347
     */
1348
0
    if (nextdev == NULL) {
1349
      /*
1350
       * Yes - we have to put the new entry after "prevdev".
1351
       */
1352
0
      break;
1353
0
    }
1354
1355
    /*
1356
     * Is the new interface's figure of merit less
1357
     * than the next interface's figure of merit,
1358
     * meaning that the new interface is better
1359
     * than the next interface?
1360
     */
1361
0
    nextdev_figure_of_merit = get_figure_of_merit(nextdev);
1362
0
    if (this_figure_of_merit < nextdev_figure_of_merit) {
1363
      /*
1364
       * Yes - we should put the new entry
1365
       * before "nextdev", i.e. after "prevdev".
1366
       */
1367
0
      break;
1368
0
    }
1369
1370
0
    prevdev = nextdev;
1371
0
  }
1372
1373
  /*
1374
   * Insert before "nextdev".
1375
   */
1376
0
  curdev->next = nextdev;
1377
1378
  /*
1379
   * Insert after "prevdev" - unless "prevdev" is null,
1380
   * in which case this is the first interface.
1381
   */
1382
0
  if (prevdev == NULL) {
1383
    /*
1384
     * This is the first interface.  Make it
1385
     * the first element in the list of devices.
1386
     */
1387
0
    devlistp->beginning = curdev;
1388
0
  } else
1389
0
    prevdev->next = curdev;
1390
0
  return (curdev);
1391
0
}
1392
1393
/*
1394
 * Add an entry for the "any" device.
1395
 */
1396
pcap_if_t *
1397
pcapint_add_any_dev(pcap_if_list_t *devlistp, char *errbuf)
1398
0
{
1399
0
  static const char any_descr[] = "Pseudo-device that captures on all interfaces";
1400
1401
  /*
1402
   * As it refers to all network devices, not to any particular
1403
   * network device, the notion of "connected" vs. "disconnected"
1404
   * doesn't apply to the "any" device.
1405
   */
1406
0
  return pcapint_add_dev(devlistp, "any",
1407
0
      PCAP_IF_UP|PCAP_IF_RUNNING|PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE,
1408
0
      any_descr, errbuf);
1409
0
}
1410
1411
/*
1412
 * Free a list of interfaces.
1413
 */
1414
void
1415
pcap_freealldevs(pcap_if_t *alldevs)
1416
0
{
1417
0
  pcap_if_t *curdev, *nextdev;
1418
0
  pcap_addr_t *curaddr, *nextaddr;
1419
1420
0
  for (curdev = alldevs; curdev != NULL; curdev = nextdev) {
1421
0
    nextdev = curdev->next;
1422
1423
    /*
1424
     * Free all addresses.
1425
     */
1426
0
    for (curaddr = curdev->addresses; curaddr != NULL; curaddr = nextaddr) {
1427
0
      nextaddr = curaddr->next;
1428
0
      if (curaddr->addr)
1429
0
        free(curaddr->addr);
1430
0
      if (curaddr->netmask)
1431
0
        free(curaddr->netmask);
1432
0
      if (curaddr->broadaddr)
1433
0
        free(curaddr->broadaddr);
1434
0
      if (curaddr->dstaddr)
1435
0
        free(curaddr->dstaddr);
1436
0
      free(curaddr);
1437
0
    }
1438
1439
    /*
1440
     * Free the name string.
1441
     */
1442
0
    free(curdev->name);
1443
1444
    /*
1445
     * Free the description string, if any.
1446
     */
1447
0
    if (curdev->description != NULL)
1448
0
      free(curdev->description);
1449
1450
    /*
1451
     * Free the interface.
1452
     */
1453
0
    free(curdev);
1454
0
  }
1455
0
}
1456
1457
/*
1458
 * pcap-npf.c has its own pcap_lookupdev(), for compatibility reasons, as
1459
 * it actually returns the names of all interfaces, with a NUL separator
1460
 * between them; some callers may depend on that.
1461
 *
1462
 * In all other cases, we just use pcap_findalldevs() to get a list of
1463
 * devices, and pick from that list.
1464
 */
1465
#if !defined(HAVE_PACKET32)
1466
/*
1467
 * Return the name of a network interface attached to the system, or NULL
1468
 * if none can be found.  The interface must be configured up; the
1469
 * lowest unit number is preferred; loopback is ignored.
1470
 */
1471
char *
1472
pcap_lookupdev(char *errbuf)
1473
0
{
1474
0
  pcap_if_t *alldevs;
1475
#ifdef _WIN32
1476
  /*
1477
   * Windows - use the same size as the old WinPcap 3.1 code.
1478
   * XXX - this is probably bigger than it needs to be.
1479
   */
1480
  #define IF_NAMESIZE 8192
1481
#else
1482
  /*
1483
   * UN*X - use the system's interface name size.
1484
   * XXX - that might not be large enough for capture devices
1485
   * that aren't regular network interfaces.
1486
   */
1487
0
#endif
1488
0
  static char device[IF_NAMESIZE + 1];
1489
0
  char *ret;
1490
1491
  /*
1492
   * We disable this in "new API" mode, because 1) in WinPcap/Npcap,
1493
   * it may return UTF-16 strings, for backwards-compatibility
1494
   * reasons, and we're also disabling the hack to make that work,
1495
   * for not-going-past-the-end-of-a-string reasons, and 2) we
1496
   * want its behavior to be consistent.
1497
   *
1498
   * In addition, it's not thread-safe, so we've marked it as
1499
   * deprecated.
1500
   */
1501
0
  if (pcapint_new_api) {
1502
0
    snprintf(errbuf, PCAP_ERRBUF_SIZE,
1503
0
        "pcap_lookupdev() is deprecated and is not supported in programs calling pcap_init()");
1504
0
    return (NULL);
1505
0
  }
1506
1507
0
  if (pcap_findalldevs(&alldevs, errbuf) == -1)
1508
0
    return (NULL);
1509
1510
0
  if (alldevs == NULL || (alldevs->flags & PCAP_IF_LOOPBACK)) {
1511
    /*
1512
     * There are no devices on the list, or the first device
1513
     * on the list is a loopback device, which means there
1514
     * are no non-loopback devices on the list.  This means
1515
     * we can't return any device.
1516
     *
1517
     * XXX - why not return a loopback device?  If we can't
1518
     * capture on it, it won't be on the list, and if it's
1519
     * on the list, there aren't any non-loopback devices,
1520
     * so why not just supply it as the default device?
1521
     */
1522
0
    (void)pcapint_strlcpy(errbuf, "no suitable device found",
1523
0
        PCAP_ERRBUF_SIZE);
1524
0
    ret = NULL;
1525
0
  } else {
1526
    /*
1527
     * Return the name of the first device on the list.
1528
     */
1529
0
    (void)pcapint_strlcpy(device, alldevs->name, sizeof(device));
1530
0
    ret = device;
1531
0
  }
1532
1533
0
  pcap_freealldevs(alldevs);
1534
0
  return (ret);
1535
0
}
1536
#endif /* !defined(HAVE_PACKET32) */
1537
1538
#if !defined(_WIN32)
1539
/*
1540
 * We don't just fetch the entire list of devices, search for the
1541
 * particular device, and use its first IPv4 address, as that's too
1542
 * much work to get just one device's netmask.
1543
 *
1544
 * If we had an API to get attributes for a given device, we could
1545
 * use that.
1546
 */
1547
int
1548
pcap_lookupnet(const char *device, bpf_u_int32 *netp, bpf_u_int32 *maskp,
1549
    char *errbuf)
1550
0
{
1551
0
  int fd;
1552
0
  struct sockaddr_in *sin4;
1553
0
  struct ifreq ifr;
1554
1555
  /*
1556
   * The pseudo-device "any" listens on all interfaces and therefore
1557
   * has the network address and -mask "0.0.0.0" therefore catching
1558
   * all traffic. Using NULL for the interface is the same as "any".
1559
   */
1560
0
  if (!device || strcmp(device, "any") == 0
1561
#ifdef HAVE_DAG_API
1562
      || strstr(device, "dag") != NULL
1563
#endif
1564
#ifdef PCAP_SUPPORT_BT
1565
      || strstr(device, "bluetooth") != NULL
1566
#endif
1567
0
#ifdef PCAP_SUPPORT_LINUX_USBMON
1568
0
      || strstr(device, "usbmon") != NULL
1569
0
#endif
1570
#ifdef HAVE_SNF_API
1571
      || strstr(device, "snf") != NULL
1572
#endif
1573
#ifdef PCAP_SUPPORT_NETMAP
1574
      || strncmp(device, "netmap:", 7) == 0
1575
      || strncmp(device, "vale", 4) == 0
1576
#endif
1577
#ifdef PCAP_SUPPORT_DPDK
1578
      || strncmp(device, "dpdk:", 5) == 0
1579
#endif
1580
0
      ) {
1581
0
    *netp = *maskp = 0;
1582
0
    return (0);
1583
0
  }
1584
1585
0
  fd = socket(AF_INET, SOCK_DGRAM, 0);
1586
0
  if (fd < 0) {
1587
0
    pcapint_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1588
0
        errno, "socket");
1589
0
    return (-1);
1590
0
  }
1591
0
  memset(&ifr, 0, sizeof(ifr));
1592
0
#ifdef __linux__
1593
  /* XXX Work around Linux kernel bug */
1594
0
  ifr.ifr_addr.sa_family = AF_INET;
1595
0
#endif
1596
0
  (void)pcapint_strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
1597
#if defined(__HAIKU__) && defined(__clang__)
1598
  /*
1599
   * In Haiku R1/beta4 <unistd.h> ioctl() is a macro that needs to take 4
1600
   * arguments to initialize its intermediate 2-member structure fully so
1601
   * that Clang does not generate a -Wmissing-field-initializers warning
1602
   * (which manifests only when it runs with -Werror).  This workaround
1603
   * can be removed as soon as there is a Haiku release that fixes the
1604
   * problem.  See also https://review.haiku-os.org/c/haiku/+/6369
1605
   */
1606
  if (ioctl(fd, SIOCGIFADDR, (char *)&ifr, sizeof(ifr)) < 0) {
1607
#else
1608
0
  if (ioctl(fd, SIOCGIFADDR, (char *)&ifr) < 0) {
1609
0
#endif /* __HAIKU__ && __clang__ */
1610
0
    if (errno == EADDRNOTAVAIL) {
1611
0
      (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
1612
0
          "%s: no IPv4 address assigned", device);
1613
0
    } else {
1614
0
      pcapint_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1615
0
          errno, "SIOCGIFADDR: %s", device);
1616
0
    }
1617
0
    (void)close(fd);
1618
0
    return (-1);
1619
0
  }
1620
0
  sin4 = (struct sockaddr_in *)&ifr.ifr_addr;
1621
0
  *netp = sin4->sin_addr.s_addr;
1622
0
  memset(&ifr, 0, sizeof(ifr));
1623
0
#ifdef __linux__
1624
  /* XXX Work around Linux kernel bug */
1625
0
  ifr.ifr_addr.sa_family = AF_INET;
1626
0
#endif
1627
0
  (void)pcapint_strlcpy(ifr.ifr_name, device, sizeof(ifr.ifr_name));
1628
#if defined(__HAIKU__) && defined(__clang__)
1629
  /* Same as above. */
1630
  if (ioctl(fd, SIOCGIFNETMASK, (char *)&ifr, sizeof(ifr)) < 0) {
1631
#else
1632
0
  if (ioctl(fd, SIOCGIFNETMASK, (char *)&ifr) < 0) {
1633
0
#endif /* __HAIKU__ && __clang__ */
1634
0
    pcapint_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
1635
0
        errno, "SIOCGIFNETMASK: %s", device);
1636
0
    (void)close(fd);
1637
0
    return (-1);
1638
0
  }
1639
0
  (void)close(fd);
1640
0
  *maskp = sin4->sin_addr.s_addr;
1641
0
  if (*maskp == 0) {
1642
0
    if (IN_CLASSA(*netp))
1643
0
      *maskp = IN_CLASSA_NET;
1644
0
    else if (IN_CLASSB(*netp))
1645
0
      *maskp = IN_CLASSB_NET;
1646
0
    else if (IN_CLASSC(*netp))
1647
0
      *maskp = IN_CLASSC_NET;
1648
0
    else {
1649
0
      (void)snprintf(errbuf, PCAP_ERRBUF_SIZE,
1650
0
          "inet class for 0x%x unknown", *netp);
1651
0
      return (-1);
1652
0
    }
1653
0
  }
1654
0
  *netp &= *maskp;
1655
0
  return (0);
1656
0
}
1657
#endif /* !defined(_WIN32) */
1658
1659
#ifdef ENABLE_REMOTE
1660
1661
/*
1662
 * Extract a substring from a string.
1663
 */
1664
static char *
1665
get_substring(const char *p, size_t len, char *ebuf)
1666
{
1667
  char *token;
1668
1669
  token = malloc(len + 1);
1670
  if (token == NULL) {
1671
    pcapint_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
1672
        errno, "malloc");
1673
    return (NULL);
1674
  }
1675
  memcpy(token, p, len);
1676
  token[len] = '\0';
1677
  return (token);
1678
}
1679
1680
/*
1681
 * Parse a capture source that might be a URL.
1682
 *
1683
 * If the source is not a URL, *schemep, *userinfop, *hostp, and *portp
1684
 * are set to NULL, *pathp is set to point to the source, and 0 is
1685
 * returned.
1686
 *
1687
 * If source is a URL, and the URL refers to a local device (a special
1688
 * case of rpcap:), *schemep, *userinfop, *hostp, and *portp are set
1689
 * to NULL, *pathp is set to point to the device name, and 0 is returned.
1690
 *
1691
 * If source is a URL, and it's not a special case that refers to a local
1692
 * device, and the parse succeeds:
1693
 *
1694
 *    *schemep is set to point to an allocated string containing the scheme;
1695
 *
1696
 *    if user information is present in the URL, *userinfop is set to point
1697
 *    to an allocated string containing the user information, otherwise
1698
 *    it's set to NULL;
1699
 *
1700
 *    if host information is present in the URL, *hostp is set to point
1701
 *    to an allocated string containing the host information, otherwise
1702
 *    it's set to NULL;
1703
 *
1704
 *    if a port number is present in the URL, *portp is set to point
1705
 *    to an allocated string containing the port number, otherwise
1706
 *    it's set to NULL;
1707
 *
1708
 *    *pathp is set to point to an allocated string containing the
1709
 *    path;
1710
 *
1711
 * and 0 is returned.
1712
 *
1713
 * If the parse fails, ebuf is set to an error string, and -1 is returned.
1714
 */
1715
static int
1716
pcap_parse_source(const char *source, char **schemep, char **userinfop,
1717
    char **hostp, char **portp, char **pathp, char *ebuf)
1718
{
1719
  char *colonp;
1720
  size_t scheme_len;
1721
  char *scheme;
1722
  const char *endp;
1723
  size_t authority_len;
1724
  char *authority;
1725
  char *parsep, *atsignp, *bracketp;
1726
  char *userinfo, *host, *port, *path;
1727
1728
  if (source == NULL) {
1729
    snprintf(ebuf, PCAP_ERRBUF_SIZE,
1730
        "The source string must not be NULL.");
1731
    return (-1);
1732
  }
1733
  if (! strcmp(source, "")) {
1734
    snprintf(ebuf, PCAP_ERRBUF_SIZE,
1735
        "The source string must not be empty.");
1736
    return (-1);
1737
  }
1738
1739
  /*
1740
   * Start out returning nothing.
1741
   */
1742
  *schemep = NULL;
1743
  *userinfop = NULL;
1744
  *hostp = NULL;
1745
  *portp = NULL;
1746
  *pathp = NULL;
1747
1748
  /*
1749
   * RFC 3986 says:
1750
   *
1751
   *   URI         = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
1752
   *
1753
   *   hier-part   = "//" authority path-abempty
1754
   *               / path-absolute
1755
   *               / path-rootless
1756
   *               / path-empty
1757
   *
1758
   *   authority   = [ userinfo "@" ] host [ ":" port ]
1759
   *
1760
   *   userinfo    = *( unreserved / pct-encoded / sub-delims / ":" )
1761
         *
1762
         * Step 1: look for the ":" at the end of the scheme.
1763
   * A colon in the source is *NOT* sufficient to indicate that
1764
   * this is a URL, as interface names on some platforms might
1765
   * include colons (e.g., I think some Solaris interfaces
1766
   * might).
1767
   */
1768
  colonp = strchr(source, ':');
1769
  if (colonp == NULL) {
1770
    /*
1771
     * The source is the device to open.
1772
     * Return a NULL pointer for the scheme, user information,
1773
     * host, and port, and return the device as the path.
1774
     */
1775
    *pathp = strdup(source);
1776
    if (*pathp == NULL) {
1777
      pcapint_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
1778
          errno, "malloc");
1779
      return (-1);
1780
    }
1781
    return (0);
1782
  }
1783
1784
  /*
1785
   * All schemes must have "//" after them, i.e. we only support
1786
   * hier-part   = "//" authority path-abempty, not
1787
   * hier-part   = path-absolute
1788
   * hier-part   = path-rootless
1789
   * hier-part   = path-empty
1790
   *
1791
   * We need that in order to distinguish between a local device
1792
   * name that happens to contain a colon and a URI.
1793
   */
1794
  if (strncmp(colonp + 1, "//", 2) != 0) {
1795
    /*
1796
     * The source is the device to open.
1797
     * Return a NULL pointer for the scheme, user information,
1798
     * host, and port, and return the device as the path.
1799
     */
1800
    *pathp = strdup(source);
1801
    if (*pathp == NULL) {
1802
      pcapint_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
1803
          errno, "malloc");
1804
      return (-1);
1805
    }
1806
    return (0);
1807
  }
1808
1809
  /*
1810
   * XXX - check whether the purported scheme could be a scheme?
1811
   */
1812
1813
  /*
1814
   * OK, this looks like a URL.
1815
   * Get the scheme.
1816
   */
1817
  scheme_len = colonp - source;
1818
  scheme = malloc(scheme_len + 1);
1819
  if (scheme == NULL) {
1820
    pcapint_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
1821
        errno, "malloc");
1822
    return (-1);
1823
  }
1824
  memcpy(scheme, source, scheme_len);
1825
  scheme[scheme_len] = '\0';
1826
1827
  /*
1828
   * Treat file: specially - take everything after file:// as
1829
   * the pathname.
1830
   *
1831
   * That doesn't conform to RFC 8089 "The "file" URI Scheme",
1832
   * but it does conform to the way WinPcap's pcap_open() handles
1833
   * the file scheme.
1834
   *
1835
   * XXX - however, it *also* means that
1836
   *
1837
   *    file://localhost/this/is/a/capture.pcap
1838
   *
1839
   * will be interpreted as a path, relative to the current
1840
   * directory, of "localhost/this/is/a/capture.pcap", not
1841
   * as an absolute path of "/this/is/a/capture.pcap".
1842
   */
1843
  if (pcapint_strcasecmp(scheme, "file") == 0) {
1844
    *pathp = strdup(colonp + 3);
1845
    if (*pathp == NULL) {
1846
      pcapint_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
1847
          errno, "malloc");
1848
      free(scheme);
1849
      return (-1);
1850
    }
1851
    *schemep = scheme;
1852
    return (0);
1853
  }
1854
1855
  /*
1856
   * The WinPcap documentation says you can specify a local
1857
   * interface with "rpcap://{device}"; we special-case
1858
   * that here.  If the scheme is "rpcap", and there are
1859
   * no slashes past the "//", we just return the device.
1860
   *
1861
   * XXX - %-escaping?
1862
   */
1863
  if ((pcapint_strcasecmp(scheme, "rpcap") == 0 ||
1864
      pcapint_strcasecmp(scheme, "rpcaps") == 0) &&
1865
      strchr(colonp + 3, '/') == NULL) {
1866
    /*
1867
     * Local device.
1868
     *
1869
     * Return a NULL pointer for the scheme, user information,
1870
     * host, and port, and return the device as the path.
1871
     */
1872
    free(scheme);
1873
    *pathp = strdup(colonp + 3);
1874
    if (*pathp == NULL) {
1875
      pcapint_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
1876
          errno, "malloc");
1877
      return (-1);
1878
    }
1879
    return (0);
1880
  }
1881
1882
  /*
1883
   * OK, now start parsing the authority.
1884
   * Get token, terminated with / or terminated at the end of
1885
   * the string.
1886
   */
1887
  authority_len = strcspn(colonp + 3, "/");
1888
  authority = get_substring(colonp + 3, authority_len, ebuf);
1889
  if (authority == NULL) {
1890
    /*
1891
     * Error.
1892
     */
1893
    free(scheme);
1894
    return (-1);
1895
  }
1896
  endp = colonp + 3 + authority_len;
1897
1898
  /*
1899
   * Now carve the authority field into its components.
1900
   */
1901
  parsep = authority;
1902
1903
  /*
1904
   * Is there a userinfo field?
1905
   */
1906
  atsignp = strchr(parsep, '@');
1907
  if (atsignp != NULL) {
1908
    /*
1909
     * Yes.
1910
     */
1911
    size_t userinfo_len;
1912
1913
    userinfo_len = atsignp - parsep;
1914
    userinfo = get_substring(parsep, userinfo_len, ebuf);
1915
    if (userinfo == NULL) {
1916
      /*
1917
       * Error.
1918
       */
1919
      free(authority);
1920
      free(scheme);
1921
      return (-1);
1922
    }
1923
    parsep = atsignp + 1;
1924
  } else {
1925
    /*
1926
     * No.
1927
     */
1928
    userinfo = NULL;
1929
  }
1930
1931
  /*
1932
   * Is there a host field?
1933
   */
1934
  if (*parsep == '\0') {
1935
    /*
1936
     * No; there's no host field or port field.
1937
     */
1938
    host = NULL;
1939
    port = NULL;
1940
  } else {
1941
    /*
1942
     * Yes.
1943
     */
1944
    size_t host_len;
1945
1946
    /*
1947
     * Is it an IP-literal?
1948
     */
1949
    if (*parsep == '[') {
1950
      /*
1951
       * Yes.
1952
       * Treat everything up to the closing square
1953
       * bracket as the IP-Literal; we don't worry
1954
       * about whether it's a valid IPv6address or
1955
       * IPvFuture (or an IPv4address, for that
1956
       * matter, just in case we get handed a
1957
       * URL with an IPv4 IP-Literal, of the sort
1958
       * that pcap_createsrcstr() used to generate,
1959
       * and that pcap_parsesrcstr(), in the original
1960
       * WinPcap code, accepted).
1961
       */
1962
      bracketp = strchr(parsep, ']');
1963
      if (bracketp == NULL) {
1964
        /*
1965
         * There's no closing square bracket.
1966
         */
1967
        snprintf(ebuf, PCAP_ERRBUF_SIZE,
1968
            "IP-literal in URL doesn't end with ]");
1969
        free(userinfo);
1970
        free(authority);
1971
        free(scheme);
1972
        return (-1);
1973
      }
1974
      if (*(bracketp + 1) != '\0' &&
1975
          *(bracketp + 1) != ':') {
1976
        /*
1977
         * There's extra crud after the
1978
         * closing square bracket.
1979
         */
1980
        snprintf(ebuf, PCAP_ERRBUF_SIZE,
1981
            "Extra text after IP-literal in URL");
1982
        free(userinfo);
1983
        free(authority);
1984
        free(scheme);
1985
        return (-1);
1986
      }
1987
      host_len = (bracketp - 1) - parsep;
1988
      host = get_substring(parsep + 1, host_len, ebuf);
1989
      if (host == NULL) {
1990
        /*
1991
         * Error.
1992
         */
1993
        free(userinfo);
1994
        free(authority);
1995
        free(scheme);
1996
        return (-1);
1997
      }
1998
      parsep = bracketp + 1;
1999
    } else {
2000
      /*
2001
       * No.
2002
       * Treat everything up to a : or the end of
2003
       * the string as the host.
2004
       */
2005
      host_len = strcspn(parsep, ":");
2006
      host = get_substring(parsep, host_len, ebuf);
2007
      if (host == NULL) {
2008
        /*
2009
         * Error.
2010
         */
2011
        free(userinfo);
2012
        free(authority);
2013
        free(scheme);
2014
        return (-1);
2015
      }
2016
      parsep = parsep + host_len;
2017
    }
2018
2019
    /*
2020
     * Is there a port field?
2021
     */
2022
    if (*parsep == ':') {
2023
      /*
2024
       * Yes.  It's the rest of the authority field.
2025
       */
2026
      size_t port_len;
2027
2028
      parsep++;
2029
      port_len = strlen(parsep);
2030
      port = get_substring(parsep, port_len, ebuf);
2031
      if (port == NULL) {
2032
        /*
2033
         * Error.
2034
         */
2035
        free(host);
2036
        free(userinfo);
2037
        free(authority);
2038
        free(scheme);
2039
        return (-1);
2040
      }
2041
    } else {
2042
      /*
2043
       * No.
2044
       */
2045
      port = NULL;
2046
    }
2047
  }
2048
  free(authority);
2049
2050
  /*
2051
   * Everything else is the path.  Strip off the leading /.
2052
   */
2053
  if (*endp == '\0')
2054
    path = strdup("");
2055
  else
2056
    path = strdup(endp + 1);
2057
  if (path == NULL) {
2058
    pcapint_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
2059
        errno, "malloc");
2060
    free(port);
2061
    free(host);
2062
    free(userinfo);
2063
    free(scheme);
2064
    return (-1);
2065
  }
2066
  *schemep = scheme;
2067
  *userinfop = userinfo;
2068
  *hostp = host;
2069
  *portp = port;
2070
  *pathp = path;
2071
  return (0);
2072
}
2073
2074
int
2075
pcapint_createsrcstr_ex(char *source, int type, const char *userinfo, const char *host,
2076
    const char *port, const char *name, unsigned char uses_ssl, char *errbuf)
2077
{
2078
  switch (type) {
2079
2080
  case PCAP_SRC_FILE:
2081
    pcapint_strlcpy(source, PCAP_SRC_FILE_STRING, PCAP_BUF_SIZE);
2082
    if (name != NULL && *name != '\0') {
2083
      pcapint_strlcat(source, name, PCAP_BUF_SIZE);
2084
      return (0);
2085
    } else {
2086
      snprintf(errbuf, PCAP_ERRBUF_SIZE,
2087
          "The file name cannot be NULL.");
2088
      return (-1);
2089
    }
2090
2091
  case PCAP_SRC_IFREMOTE:
2092
    pcapint_strlcpy(source,
2093
        (uses_ssl ? "rpcaps://" : PCAP_SRC_IF_STRING),
2094
        PCAP_BUF_SIZE);
2095
    if (host != NULL && *host != '\0') {
2096
      if (userinfo != NULL && *userinfo != '\0') {
2097
        pcapint_strlcat(source, userinfo, PCAP_BUF_SIZE);
2098
        pcapint_strlcat(source, "@", PCAP_BUF_SIZE);
2099
      }
2100
2101
      if (strchr(host, ':') != NULL) {
2102
        /*
2103
         * The host name contains a colon, so it's
2104
         * probably an IPv6 address, and needs to
2105
         * be included in square brackets.
2106
         */
2107
        pcapint_strlcat(source, "[", PCAP_BUF_SIZE);
2108
        pcapint_strlcat(source, host, PCAP_BUF_SIZE);
2109
        pcapint_strlcat(source, "]", PCAP_BUF_SIZE);
2110
      } else
2111
        pcapint_strlcat(source, host, PCAP_BUF_SIZE);
2112
2113
      if (port != NULL && *port != '\0') {
2114
        pcapint_strlcat(source, ":", PCAP_BUF_SIZE);
2115
        pcapint_strlcat(source, port, PCAP_BUF_SIZE);
2116
      }
2117
2118
      pcapint_strlcat(source, "/", PCAP_BUF_SIZE);
2119
    } else {
2120
      snprintf(errbuf, PCAP_ERRBUF_SIZE,
2121
          "The host name cannot be NULL.");
2122
      return (-1);
2123
    }
2124
2125
    if (name != NULL && *name != '\0')
2126
      pcapint_strlcat(source, name, PCAP_BUF_SIZE);
2127
2128
    return (0);
2129
2130
  case PCAP_SRC_IFLOCAL:
2131
    pcapint_strlcpy(source, PCAP_SRC_IF_STRING, PCAP_BUF_SIZE);
2132
2133
    if (name != NULL && *name != '\0')
2134
      pcapint_strlcat(source, name, PCAP_BUF_SIZE);
2135
2136
    return (0);
2137
2138
  default:
2139
    snprintf(errbuf, PCAP_ERRBUF_SIZE,
2140
        "The interface type is not valid.");
2141
    return (-1);
2142
  }
2143
}
2144
2145
2146
int
2147
pcap_createsrcstr(char *source, int type, const char *host, const char *port,
2148
    const char *name, char *errbuf)
2149
{
2150
  return (pcapint_createsrcstr_ex(source, type, NULL, host, port, name, 0, errbuf));
2151
}
2152
2153
int
2154
pcapint_parsesrcstr_ex(const char *source, int *type, char *userinfo, char *host,
2155
    char *port, char *name, unsigned char *uses_ssl, char *errbuf)
2156
{
2157
  char *scheme, *tmpuserinfo, *tmphost, *tmpport, *tmppath;
2158
2159
  /* Initialization stuff */
2160
  if (userinfo)
2161
    *userinfo = '\0';
2162
  if (host)
2163
    *host = '\0';
2164
  if (port)
2165
    *port = '\0';
2166
  if (name)
2167
    *name = '\0';
2168
  if (uses_ssl)
2169
    *uses_ssl = 0;
2170
2171
  /* Parse the source string */
2172
  if (pcap_parse_source(source, &scheme, &tmpuserinfo, &tmphost,
2173
      &tmpport, &tmppath, errbuf) == -1) {
2174
    /*
2175
     * Fail.
2176
     */
2177
    return (-1);
2178
  }
2179
2180
  if (scheme == NULL) {
2181
    /*
2182
     * Local device.
2183
     */
2184
    if (name && tmppath)
2185
      pcapint_strlcpy(name, tmppath, PCAP_BUF_SIZE);
2186
    if (type)
2187
      *type = PCAP_SRC_IFLOCAL;
2188
    free(tmppath);
2189
    free(tmpport);
2190
    free(tmphost);
2191
    free(tmpuserinfo);
2192
    return (0);
2193
  }
2194
2195
  int is_rpcap = 0;
2196
  if (strcmp(scheme, "rpcaps") == 0) {
2197
    is_rpcap = 1;
2198
    if (uses_ssl) *uses_ssl = 1;
2199
  } else if (strcmp(scheme, "rpcap") == 0) {
2200
    is_rpcap = 1;
2201
  }
2202
2203
  if (is_rpcap) {
2204
    /*
2205
     * rpcap[s]://
2206
     *
2207
     * pcap_parse_source() has already handled the case of
2208
     * rpcap[s]://device
2209
     */
2210
    if (userinfo && tmpuserinfo)
2211
      pcapint_strlcpy(userinfo, tmpuserinfo, PCAP_BUF_SIZE);
2212
    if (host && tmphost)
2213
      pcapint_strlcpy(host, tmphost, PCAP_BUF_SIZE);
2214
    if (port && tmpport)
2215
      pcapint_strlcpy(port, tmpport, PCAP_BUF_SIZE);
2216
    if (name && tmppath)
2217
      pcapint_strlcpy(name, tmppath, PCAP_BUF_SIZE);
2218
    if (type)
2219
      *type = PCAP_SRC_IFREMOTE;
2220
    free(tmppath);
2221
    free(tmpport);
2222
    free(tmphost);
2223
    free(tmpuserinfo);
2224
    free(scheme);
2225
    return (0);
2226
  }
2227
2228
  if (strcmp(scheme, "file") == 0) {
2229
    /*
2230
     * file://
2231
     */
2232
    if (name && tmppath)
2233
      pcapint_strlcpy(name, tmppath, PCAP_BUF_SIZE);
2234
    if (type)
2235
      *type = PCAP_SRC_FILE;
2236
    free(tmppath);
2237
    free(tmpport);
2238
    free(tmphost);
2239
    free(tmpuserinfo);
2240
    free(scheme);
2241
    return (0);
2242
  }
2243
2244
  /*
2245
   * The code above has already completely handled the case of no scheme,
2246
   * as well as each case of a valid scheme.
2247
   */
2248
  snprintf(errbuf, PCAP_ERRBUF_SIZE, "The source string URL scheme is not supported.");
2249
  free(tmppath);
2250
  free(tmpport);
2251
  free(tmphost);
2252
  free(tmpuserinfo);
2253
  free(scheme);
2254
  return (-1);
2255
}
2256
2257
int
2258
pcap_parsesrcstr(const char *source, int *type, char *host, char *port,
2259
    char *name, char *errbuf)
2260
{
2261
  return (pcapint_parsesrcstr_ex(source, type, NULL, host, port, name, NULL, errbuf));
2262
}
2263
2264
#else /* ENABLE_REMOTE */
2265
2266
int
2267
pcapint_createsrcstr_ex(char *source _U_, int type _U_, const char *userinfo _U_,
2268
   const char *host _U_, const char *port _U_, const char *name _U_,
2269
   unsigned char uses_ssl _U_, char *errbuf)
2270
0
{
2271
0
  pcapint_strlcpy(errbuf, "pcapint_createsrcstr_ex() is not supported",
2272
0
      PCAP_ERRBUF_SIZE);
2273
0
  return (-1);
2274
0
}
2275
2276
int
2277
pcap_createsrcstr(char *source _U_, int type _U_, const char *host _U_,
2278
    const char *port _U_, const char *name _U_, char *errbuf)
2279
0
{
2280
0
  pcapint_strlcpy(errbuf, "pcapint_createsrcstr() is not supported",
2281
0
      PCAP_ERRBUF_SIZE);
2282
0
  return (-1);
2283
0
}
2284
2285
int
2286
pcapint_parsesrcstr_ex(const char *source _U_, int *type _U_,
2287
    char *userinfo _U_, char *host _U_, char *port _U_, char *name _U_,
2288
    unsigned char *uses_ssl _U_, char *errbuf)
2289
0
{
2290
0
  pcapint_strlcpy(errbuf, "pcapint_parsesrcstr_ex() is not supported",
2291
0
      PCAP_ERRBUF_SIZE);
2292
0
  return (-1);
2293
0
}
2294
2295
int
2296
pcap_parsesrcstr(const char *source _U_, int *type _U_, char *host _U_,
2297
    char *port _U_, char *name _U_, char *errbuf)
2298
0
{
2299
0
  pcapint_strlcpy(errbuf, "pcapint_parsesrcstr() is not supported",
2300
0
      PCAP_ERRBUF_SIZE);
2301
0
  return (-1);
2302
0
}
2303
2304
#endif /* ENABLE_REMOTE */
2305
2306
pcap_t *
2307
pcap_create(const char *device, char *errbuf)
2308
0
{
2309
0
  size_t i;
2310
0
  int is_theirs;
2311
0
  pcap_t *p;
2312
0
  char *device_str;
2313
2314
  /*
2315
   * A null device name is equivalent to the "any" device -
2316
   * which might not be supported on this platform, but
2317
   * this means that you'll get a "not supported" error
2318
   * rather than, say, a crash when we try to dereference
2319
   * the null pointer.
2320
   */
2321
0
  if (device == NULL)
2322
0
    device_str = strdup("any");
2323
0
  else {
2324
#ifdef _WIN32
2325
    /*
2326
     * On Windows, for backwards compatibility reasons,
2327
     * pcap_lookupdev() returns a pointer to a sequence of
2328
     * pairs of UTF-16LE device names and local code page
2329
     * description strings.
2330
     *
2331
     * This means that if a program uses pcap_lookupdev()
2332
     * to get a default device, and hands that to an API
2333
     * that opens devices, we'll get handed a UTF-16LE
2334
     * string, not a string in the local code page.
2335
     *
2336
     * To work around that, we check whether the string
2337
     * looks as if it might be a UTF-16LE string and, if
2338
     * so, convert it back to the local code page's
2339
     * extended ASCII.
2340
     *
2341
     * We disable that check in "new API" mode, because:
2342
     *
2343
     *   1) You *cannot* reliably detect whether a
2344
     *   string is UTF-16LE or not; "a" could either
2345
     *   be a one-character ASCII string or the first
2346
     *   character of a UTF-16LE string.
2347
     *
2348
     *   2) Doing that test can run past the end of
2349
     *   the string, if it's a 1-character ASCII
2350
     *   string
2351
     *
2352
     * This particular version of this heuristic dates
2353
     * back to WinPcap 4.1.1; PacketOpenAdapter() does
2354
     * uses the same heuristic, with the exact same
2355
     * vulnerability.
2356
     *
2357
     * That's why we disable this in "new API" mode.
2358
     * We keep it around in legacy mode for backwards
2359
     * compatibility.
2360
     */
2361
    if (!pcapint_new_api && device[0] != '\0' && device[1] == '\0') {
2362
      size_t length;
2363
2364
      length = wcslen((wchar_t *)device);
2365
      device_str = (char *)malloc(length + 1);
2366
      if (device_str == NULL) {
2367
        pcapint_fmt_errmsg_for_errno(errbuf,
2368
            PCAP_ERRBUF_SIZE, errno,
2369
            "malloc");
2370
        return (NULL);
2371
      }
2372
2373
      snprintf(device_str, length + 1, "%ws",
2374
          (const wchar_t *)device);
2375
    } else
2376
#endif
2377
0
      device_str = strdup(device);
2378
0
  }
2379
0
  if (device_str == NULL) {
2380
0
    pcapint_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
2381
0
        errno, "malloc");
2382
0
    return (NULL);
2383
0
  }
2384
2385
  /*
2386
   * Try each of the non-local-network-interface capture
2387
   * source types until we find one that works for this
2388
   * device or run out of types.
2389
   */
2390
0
  for (i = 0; capture_source_types[i].create_op != NULL; i++) {
2391
0
    is_theirs = 0;
2392
0
    p = capture_source_types[i].create_op(device_str, errbuf,
2393
0
        &is_theirs);
2394
0
    if (is_theirs) {
2395
      /*
2396
       * The device name refers to a device of the
2397
       * type in question; either it succeeded,
2398
       * in which case p refers to a pcap_t to
2399
       * later activate for the device, or it
2400
       * failed, in which case p is null and we
2401
       * should return that to report the failure
2402
       * to create.
2403
       */
2404
0
      if (p == NULL) {
2405
        /*
2406
         * We assume the caller filled in errbuf.
2407
         */
2408
0
        free(device_str);
2409
0
        return (NULL);
2410
0
      }
2411
0
      p->opt.device = device_str;
2412
0
      return (p);
2413
0
    }
2414
0
  }
2415
2416
  /*
2417
   * OK, try it as a regular network interface.
2418
   */
2419
0
  p = pcapint_create_interface(device_str, errbuf);
2420
0
  if (p == NULL) {
2421
    /*
2422
     * We assume the caller filled in errbuf.
2423
     */
2424
0
    free(device_str);
2425
0
    return (NULL);
2426
0
  }
2427
0
  p->opt.device = device_str;
2428
0
  return (p);
2429
0
}
2430
2431
/*
2432
 * Set nonblocking mode on an unactivated pcap_t; this sets a flag
2433
 * checked by pcap_activate(), which sets the mode after calling
2434
 * the activate routine.
2435
 */
2436
static int
2437
pcap_setnonblock_unactivated(pcap_t *p, int nonblock)
2438
0
{
2439
0
  p->opt.nonblock = nonblock;
2440
0
  return (0);
2441
0
}
2442
2443
static void
2444
initialize_ops(pcap_t *p)
2445
0
{
2446
  /*
2447
   * Set operation pointers for operations that only work on
2448
   * an activated pcap_t to point to a routine that returns
2449
   * a "this isn't activated" error.
2450
   */
2451
0
  p->read_op = pcap_read_not_initialized;
2452
0
  p->inject_op = pcap_inject_not_initialized;
2453
0
  p->setfilter_op = pcap_setfilter_not_initialized;
2454
0
  p->setdirection_op = pcap_setdirection_not_initialized;
2455
0
  p->set_datalink_op = pcap_set_datalink_not_initialized;
2456
0
  p->getnonblock_op = pcap_getnonblock_not_initialized;
2457
0
  p->stats_op = pcap_stats_not_initialized;
2458
#ifdef _WIN32
2459
  p->stats_ex_op = pcap_stats_ex_not_initialized;
2460
  p->setbuff_op = pcap_setbuff_not_initialized;
2461
  p->setmode_op = pcap_setmode_not_initialized;
2462
  p->setmintocopy_op = pcap_setmintocopy_not_initialized;
2463
  p->getevent_op = pcap_getevent_not_initialized;
2464
  p->oid_get_request_op = pcap_oid_get_request_not_initialized;
2465
  p->oid_set_request_op = pcap_oid_set_request_not_initialized;
2466
  p->sendqueue_transmit_op = pcap_sendqueue_transmit_not_initialized;
2467
  p->setuserbuffer_op = pcap_setuserbuffer_not_initialized;
2468
  p->live_dump_op = pcap_live_dump_not_initialized;
2469
  p->live_dump_ended_op = pcap_live_dump_ended_not_initialized;
2470
#endif
2471
2472
  /*
2473
   * Default cleanup operation - implementations can override
2474
   * this, but should call pcapint_cleanup_live_common() after
2475
   * doing their own additional cleanup.
2476
   */
2477
0
  p->cleanup_op = pcapint_cleanup_live_common;
2478
2479
  /*
2480
   * In most cases, the standard one-shot callback can
2481
   * be used for pcap_next()/pcap_next_ex().
2482
   */
2483
0
  p->oneshot_callback = pcapint_oneshot;
2484
2485
  /*
2486
   * Default breakloop operation - implementations can override
2487
   * this, but should call pcapint_breakloop_common() before doing
2488
   * their own logic.
2489
   */
2490
0
  p->breakloop_op = pcapint_breakloop_common;
2491
0
}
2492
2493
static pcap_t *
2494
pcap_alloc_pcap_t(char *ebuf, size_t total_size, size_t private_offset)
2495
17.0k
{
2496
17.0k
  char *chunk;
2497
17.0k
  pcap_t *p;
2498
2499
  /*
2500
   * total_size is the size of a structure containing a pcap_t
2501
   * followed by a private structure.
2502
   */
2503
17.0k
  chunk = calloc(total_size, 1);
2504
17.0k
  if (chunk == NULL) {
2505
0
    pcapint_fmt_errmsg_for_errno(ebuf, PCAP_ERRBUF_SIZE,
2506
0
        errno, "malloc");
2507
0
    return (NULL);
2508
0
  }
2509
2510
  /*
2511
   * Get a pointer to the pcap_t at the beginning.
2512
   */
2513
17.0k
  p = (pcap_t *)chunk;
2514
2515
#ifdef _WIN32
2516
  p->handle = INVALID_HANDLE_VALUE; /* not opened yet */
2517
#else /* _WIN32 */
2518
17.0k
  p->fd = -1; /* not opened yet */
2519
17.0k
  p->selectable_fd = -1;
2520
17.0k
  p->required_select_timeout = NULL;
2521
17.0k
#endif /* _WIN32 */
2522
2523
  /*
2524
   * private_offset is the offset, in bytes, of the private
2525
   * data from the beginning of the structure.
2526
   *
2527
   * Set the pointer to the private data; that's private_offset
2528
   * bytes past the pcap_t.
2529
   */
2530
17.0k
  p->priv = (void *)(chunk + private_offset);
2531
2532
17.0k
  return (p);
2533
17.0k
}
2534
2535
pcap_t *
2536
pcapint_create_common(char *ebuf, size_t total_size, size_t private_offset)
2537
0
{
2538
0
  pcap_t *p;
2539
2540
0
  p = pcap_alloc_pcap_t(ebuf, total_size, private_offset);
2541
0
  if (p == NULL)
2542
0
    return (NULL);
2543
2544
  /*
2545
   * Default to "can't set rfmon mode"; if it's supported by
2546
   * a platform, the create routine that called us can set
2547
   * the op to its routine to check whether a particular
2548
   * device supports it.
2549
   */
2550
0
  p->can_set_rfmon_op = pcap_cant_set_rfmon;
2551
2552
  /*
2553
   * If pcap_setnonblock() is called on a not-yet-activated
2554
   * pcap_t, default to setting a flag and turning
2555
   * on non-blocking mode when activated.
2556
   */
2557
0
  p->setnonblock_op = pcap_setnonblock_unactivated;
2558
2559
0
  initialize_ops(p);
2560
2561
  /* put in some defaults*/
2562
0
  p->snapshot = 0;    /* max packet size unspecified */
2563
0
  p->opt.timeout = 0;   /* no timeout specified */
2564
0
  p->opt.buffer_size = 0;   /* use the platform's default */
2565
0
  p->opt.promisc = 0;
2566
0
  p->opt.rfmon = 0;
2567
0
  p->opt.immediate = 0;
2568
0
  p->opt.tstamp_type = -1;  /* default to not setting time stamp type */
2569
0
  p->opt.tstamp_precision = PCAP_TSTAMP_PRECISION_MICRO;
2570
  /*
2571
   * Platform-dependent options.
2572
   */
2573
0
#ifdef __linux__
2574
0
  p->opt.protocol = 0;
2575
0
#endif
2576
#ifdef _WIN32
2577
  p->opt.nocapture_local = 0;
2578
#endif
2579
2580
  /*
2581
   * Start out with no BPF code generation flags set.
2582
   */
2583
0
  p->bpf_codegen_flags = 0;
2584
2585
0
  return (p);
2586
0
}
2587
2588
int
2589
pcapint_check_activated(pcap_t *p)
2590
0
{
2591
0
  if (p->activated) {
2592
0
    snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "can't perform "
2593
0
      " operation on activated capture");
2594
0
    return (-1);
2595
0
  }
2596
0
  return (0);
2597
0
}
2598
2599
int
2600
pcap_set_snaplen(pcap_t *p, int snaplen)
2601
0
{
2602
0
  if (pcapint_check_activated(p))
2603
0
    return (PCAP_ERROR_ACTIVATED);
2604
0
  p->snapshot = snaplen;
2605
0
  return (0);
2606
0
}
2607
2608
int
2609
pcap_set_promisc(pcap_t *p, int promisc)
2610
0
{
2611
0
  if (pcapint_check_activated(p))
2612
0
    return (PCAP_ERROR_ACTIVATED);
2613
0
  p->opt.promisc = promisc;
2614
0
  return (0);
2615
0
}
2616
2617
int
2618
pcap_set_rfmon(pcap_t *p, int rfmon)
2619
0
{
2620
0
  if (pcapint_check_activated(p))
2621
0
    return (PCAP_ERROR_ACTIVATED);
2622
0
  p->opt.rfmon = rfmon;
2623
0
  return (0);
2624
0
}
2625
2626
int
2627
pcap_set_timeout(pcap_t *p, int timeout_ms)
2628
0
{
2629
0
  if (pcapint_check_activated(p))
2630
0
    return (PCAP_ERROR_ACTIVATED);
2631
0
  p->opt.timeout = timeout_ms;
2632
0
  return (0);
2633
0
}
2634
2635
int
2636
pcap_set_tstamp_type(pcap_t *p, int tstamp_type)
2637
0
{
2638
0
  int i;
2639
2640
0
  if (pcapint_check_activated(p))
2641
0
    return (PCAP_ERROR_ACTIVATED);
2642
2643
  /*
2644
   * The argument should have been u_int, but that's too late
2645
   * to change now - it's an API.
2646
   */
2647
0
  if (tstamp_type < 0)
2648
0
    return (PCAP_WARNING_TSTAMP_TYPE_NOTSUP);
2649
2650
  /*
2651
   * If p->tstamp_type_count is 0, we only support PCAP_TSTAMP_HOST;
2652
   * the default time stamp type is PCAP_TSTAMP_HOST.
2653
   */
2654
0
  if (p->tstamp_type_count == 0) {
2655
0
    if (tstamp_type == PCAP_TSTAMP_HOST) {
2656
0
      p->opt.tstamp_type = tstamp_type;
2657
0
      return (0);
2658
0
    }
2659
0
  } else {
2660
    /*
2661
     * Check whether we claim to support this type of time stamp.
2662
     */
2663
0
    for (i = 0; i < p->tstamp_type_count; i++) {
2664
0
      if (p->tstamp_type_list[i] == (u_int)tstamp_type) {
2665
        /*
2666
         * Yes.
2667
         */
2668
0
        p->opt.tstamp_type = tstamp_type;
2669
0
        return (0);
2670
0
      }
2671
0
    }
2672
0
  }
2673
2674
  /*
2675
   * We don't support this type of time stamp.
2676
   */
2677
0
  return (PCAP_WARNING_TSTAMP_TYPE_NOTSUP);
2678
0
}
2679
2680
int
2681
pcap_set_immediate_mode(pcap_t *p, int immediate)
2682
0
{
2683
0
  if (pcapint_check_activated(p))
2684
0
    return (PCAP_ERROR_ACTIVATED);
2685
0
  p->opt.immediate = immediate;
2686
0
  return (0);
2687
0
}
2688
2689
int
2690
pcap_set_buffer_size(pcap_t *p, int buffer_size)
2691
0
{
2692
0
  if (pcapint_check_activated(p))
2693
0
    return (PCAP_ERROR_ACTIVATED);
2694
0
  if (buffer_size <= 0) {
2695
    /*
2696
     * Silently ignore invalid values.
2697
     */
2698
0
    return (0);
2699
0
  }
2700
0
  p->opt.buffer_size = buffer_size;
2701
0
  return (0);
2702
0
}
2703
2704
int
2705
pcap_set_tstamp_precision(pcap_t *p, int tstamp_precision)
2706
0
{
2707
0
  int i;
2708
2709
0
  if (pcapint_check_activated(p))
2710
0
    return (PCAP_ERROR_ACTIVATED);
2711
2712
  /*
2713
   * The argument should have been u_int, but that's too late
2714
   * to change now - it's an API.
2715
   */
2716
0
  if (tstamp_precision < 0)
2717
0
    return (PCAP_ERROR_TSTAMP_PRECISION_NOTSUP);
2718
2719
  /*
2720
   * If p->tstamp_precision_count is 0, we only support setting
2721
   * the time stamp precision to microsecond precision; every
2722
   * pcap module *MUST* support microsecond precision, even if
2723
   * it does so by converting the native precision to
2724
   * microseconds.
2725
   */
2726
0
  if (p->tstamp_precision_count == 0) {
2727
0
    if (tstamp_precision == PCAP_TSTAMP_PRECISION_MICRO) {
2728
0
      p->opt.tstamp_precision = tstamp_precision;
2729
0
      return (0);
2730
0
    }
2731
0
  } else {
2732
    /*
2733
     * Check whether we claim to support this precision of
2734
     * time stamp.
2735
     */
2736
0
    for (i = 0; i < p->tstamp_precision_count; i++) {
2737
0
      if (p->tstamp_precision_list[i] == (u_int)tstamp_precision) {
2738
        /*
2739
         * Yes.
2740
         */
2741
0
        p->opt.tstamp_precision = tstamp_precision;
2742
0
        return (0);
2743
0
      }
2744
0
    }
2745
0
  }
2746
2747
  /*
2748
   * We don't support this time stamp precision.
2749
   */
2750
0
  return (PCAP_ERROR_TSTAMP_PRECISION_NOTSUP);
2751
0
}
2752
2753
int
2754
pcap_get_tstamp_precision(pcap_t *p)
2755
0
{
2756
0
        return (p->opt.tstamp_precision);
2757
0
}
2758
2759
int
2760
pcap_activate(pcap_t *p)
2761
0
{
2762
0
  int status;
2763
2764
  /*
2765
   * Catch attempts to re-activate an already-activated
2766
   * pcap_t; this should, for example, catch code that
2767
   * calls pcap_open_live() followed by pcap_activate(),
2768
   * as some code that showed up in a Stack Exchange
2769
   * question did.
2770
   */
2771
0
  if (pcapint_check_activated(p))
2772
0
    return (PCAP_ERROR_ACTIVATED);
2773
0
  status = p->activate_op(p);
2774
0
  if (status >= 0) {
2775
    /*
2776
     * If somebody requested non-blocking mode before
2777
     * calling pcap_activate(), turn it on now.
2778
     */
2779
0
    if (p->opt.nonblock) {
2780
0
      status = p->setnonblock_op(p, 1);
2781
0
      if (status < 0) {
2782
        /*
2783
         * Failed.  Undo everything done by
2784
         * the activate operation.
2785
         */
2786
0
        p->cleanup_op(p);
2787
0
        initialize_ops(p);
2788
0
        return (status);
2789
0
      }
2790
0
    }
2791
0
    p->activated = 1;
2792
0
  } else {
2793
0
    if (p->errbuf[0] == '\0') {
2794
      /*
2795
       * No error message supplied by the activate routine;
2796
       * for the benefit of programs that don't specially
2797
       * handle errors other than PCAP_ERROR, return the
2798
       * error message corresponding to the status.
2799
       */
2800
0
      snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "%s",
2801
0
          pcap_statustostr(status));
2802
0
    }
2803
2804
    /*
2805
     * Undo any operation pointer setting, etc. done by
2806
     * the activate operation.
2807
     */
2808
0
    initialize_ops(p);
2809
0
  }
2810
0
  return (status);
2811
0
}
2812
2813
pcap_t *
2814
pcap_open_live(const char *device, int snaplen, int promisc, int to_ms, char *errbuf)
2815
0
{
2816
0
  pcap_t *p;
2817
0
  int status;
2818
#ifdef ENABLE_REMOTE
2819
  char host[PCAP_BUF_SIZE + 1];
2820
  char port[PCAP_BUF_SIZE + 1];
2821
  char name[PCAP_BUF_SIZE + 1];
2822
  int srctype;
2823
2824
  /*
2825
   * A null device name is equivalent to the "any" device -
2826
   * which might not be supported on this platform, but
2827
   * this means that you'll get a "not supported" error
2828
   * rather than, say, a crash when we try to dereference
2829
   * the null pointer.
2830
   */
2831
  if (device == NULL)
2832
    device = "any";
2833
2834
  /*
2835
   * Retrofit - we have to make older applications compatible with
2836
   * remote capture.
2837
   * So we're calling pcap_open_remote() from here; this is a very
2838
   * dirty hack.
2839
   * Obviously, we cannot exploit all the new features; for instance,
2840
   * we cannot send authentication, we cannot use a UDP data connection,
2841
   * and so on.
2842
   */
2843
  if (pcap_parsesrcstr(device, &srctype, host, port, name, errbuf))
2844
    return (NULL);
2845
2846
  if (srctype == PCAP_SRC_IFREMOTE) {
2847
    /*
2848
     * Although we already have host, port and iface, we prefer
2849
     * to pass only 'device' to pcap_open_rpcap(), so that it has
2850
     * to call pcap_parsesrcstr() again.
2851
     * This is less optimized, but much clearer.
2852
     */
2853
    return (pcap_open_rpcap(device, snaplen,
2854
        promisc ? PCAP_OPENFLAG_PROMISCUOUS : 0, to_ms,
2855
        NULL, errbuf));
2856
  }
2857
  if (srctype == PCAP_SRC_FILE) {
2858
    snprintf(errbuf, PCAP_ERRBUF_SIZE, "unknown URL scheme \"file\"");
2859
    return (NULL);
2860
  }
2861
  if (srctype == PCAP_SRC_IFLOCAL) {
2862
    /*
2863
     * If it starts with rpcap://, that refers to a local device
2864
     * (no host part in the URL). Remove the rpcap://, and
2865
     * fall through to the regular open path.
2866
     */
2867
    if (strncmp(device, PCAP_SRC_IF_STRING, strlen(PCAP_SRC_IF_STRING)) == 0) {
2868
      size_t len = strlen(device) - strlen(PCAP_SRC_IF_STRING) + 1;
2869
2870
      if (len > 0)
2871
        device += strlen(PCAP_SRC_IF_STRING);
2872
    }
2873
  }
2874
#endif  /* ENABLE_REMOTE */
2875
2876
0
  p = pcap_create(device, errbuf);
2877
0
  if (p == NULL)
2878
0
    return (NULL);
2879
0
  status = pcap_set_snaplen(p, snaplen);
2880
0
  if (status < 0)
2881
0
    goto fail;
2882
0
  status = pcap_set_promisc(p, promisc);
2883
0
  if (status < 0)
2884
0
    goto fail;
2885
0
  status = pcap_set_timeout(p, to_ms);
2886
0
  if (status < 0)
2887
0
    goto fail;
2888
  /*
2889
   * Mark this as opened with pcap_open_live(), so that, for
2890
   * example, we show the full list of DLT_ values, rather
2891
   * than just the ones that are compatible with capturing
2892
   * when not in monitor mode.  That allows existing applications
2893
   * to work the way they used to work, but allows new applications
2894
   * that know about the new open API to, for example, find out the
2895
   * DLT_ values that they can select without changing whether
2896
   * the adapter is in monitor mode or not.
2897
   */
2898
0
  p->oldstyle = 1;
2899
0
  status = pcap_activate(p);
2900
0
  if (status < 0)
2901
0
    goto fail;
2902
0
  return (p);
2903
0
fail:
2904
0
  if (status == PCAP_ERROR) {
2905
    /*
2906
     * Another buffer is a bit cumbersome, but it avoids
2907
     * -Wformat-truncation.
2908
     */
2909
0
    char trimbuf[PCAP_ERRBUF_SIZE - 5]; /* 2 bytes shorter */
2910
2911
0
    pcapint_strlcpy(trimbuf, p->errbuf, sizeof(trimbuf));
2912
0
    snprintf(errbuf, PCAP_ERRBUF_SIZE, "%s: %.*s", device,
2913
0
        PCAP_ERRBUF_SIZE - 3, trimbuf);
2914
0
  } else if (status == PCAP_ERROR_NO_SUCH_DEVICE ||
2915
0
      status == PCAP_ERROR_PERM_DENIED ||
2916
0
      status == PCAP_ERROR_PROMISC_PERM_DENIED) {
2917
    /*
2918
     * Only show the additional message if it's not
2919
     * empty.
2920
     */
2921
0
    if (p->errbuf[0] != '\0') {
2922
      /*
2923
       * Idem.
2924
       */
2925
0
      char trimbuf[PCAP_ERRBUF_SIZE - 8]; /* 2 bytes shorter */
2926
2927
0
      pcapint_strlcpy(trimbuf, p->errbuf, sizeof(trimbuf));
2928
0
      snprintf(errbuf, PCAP_ERRBUF_SIZE, "%s: %s (%.*s)",
2929
0
          device, pcap_statustostr(status),
2930
0
          PCAP_ERRBUF_SIZE - 6, trimbuf);
2931
0
    } else {
2932
0
      snprintf(errbuf, PCAP_ERRBUF_SIZE, "%s: %s",
2933
0
          device, pcap_statustostr(status));
2934
0
    }
2935
0
  } else {
2936
0
    snprintf(errbuf, PCAP_ERRBUF_SIZE, "%s: %s", device,
2937
0
        pcap_statustostr(status));
2938
0
  }
2939
0
  pcap_close(p);
2940
0
  return (NULL);
2941
0
}
2942
2943
pcap_t *
2944
pcapint_open_offline_common(char *ebuf, size_t total_size, size_t private_offset)
2945
17.0k
{
2946
17.0k
  pcap_t *p;
2947
2948
17.0k
  p = pcap_alloc_pcap_t(ebuf, total_size, private_offset);
2949
17.0k
  if (p == NULL)
2950
0
    return (NULL);
2951
2952
17.0k
  p->opt.tstamp_precision = PCAP_TSTAMP_PRECISION_MICRO;
2953
2954
17.0k
  return (p);
2955
17.0k
}
2956
2957
int
2958
pcap_dispatch(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
2959
0
{
2960
0
  return (p->read_op(p, cnt, callback, user));
2961
0
}
2962
2963
int
2964
pcap_loop(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
2965
0
{
2966
0
  int n;
2967
2968
0
  for (;;) {
2969
0
    if (p->rfile != NULL) {
2970
      /*
2971
       * 0 means EOF, so don't loop if we get 0.
2972
       */
2973
0
      n = pcapint_offline_read(p, cnt, callback, user);
2974
0
    } else {
2975
      /*
2976
       * XXX keep reading until we get something
2977
       * (or an error occurs)
2978
       */
2979
0
      do {
2980
0
        n = p->read_op(p, cnt, callback, user);
2981
0
      } while (n == 0);
2982
0
    }
2983
0
    if (n <= 0)
2984
0
      return (n);
2985
0
    if (!PACKET_COUNT_IS_UNLIMITED(cnt)) {
2986
0
      cnt -= n;
2987
0
      if (cnt <= 0)
2988
0
        return (0);
2989
0
    }
2990
0
  }
2991
0
}
2992
2993
/*
2994
 * Force the loop in "pcap_read()" or "pcap_read_offline()" to terminate.
2995
 */
2996
void
2997
pcap_breakloop(pcap_t *p)
2998
0
{
2999
0
  p->breakloop_op(p);
3000
0
}
3001
3002
int
3003
pcap_datalink(pcap_t *p)
3004
12.8k
{
3005
12.8k
  if (!p->activated)
3006
0
    return (PCAP_ERROR_NOT_ACTIVATED);
3007
12.8k
  return (p->linktype);
3008
12.8k
}
3009
3010
int
3011
pcap_datalink_ext(pcap_t *p)
3012
0
{
3013
0
  if (!p->activated)
3014
0
    return (PCAP_ERROR_NOT_ACTIVATED);
3015
0
  return (p->linktype_ext);
3016
0
}
3017
3018
int
3019
pcap_list_datalinks(pcap_t *p, int **dlt_buffer)
3020
0
{
3021
0
  if (!p->activated)
3022
0
    return (PCAP_ERROR_NOT_ACTIVATED);
3023
0
  if (p->dlt_count == 0) {
3024
    /*
3025
     * We couldn't fetch the list of DLTs, which means
3026
     * this platform doesn't support changing the
3027
     * DLT for an interface.  Return a list of DLTs
3028
     * containing only the DLT this device supports.
3029
     */
3030
0
    *dlt_buffer = (int*)malloc(sizeof(**dlt_buffer));
3031
0
    if (*dlt_buffer == NULL) {
3032
0
      pcapint_fmt_errmsg_for_errno(p->errbuf, sizeof(p->errbuf),
3033
0
          errno, "malloc");
3034
0
      return (PCAP_ERROR);
3035
0
    }
3036
0
    **dlt_buffer = p->linktype;
3037
0
    return (1);
3038
0
  } else {
3039
0
    *dlt_buffer = (int*)calloc(p->dlt_count, sizeof(**dlt_buffer));
3040
0
    if (*dlt_buffer == NULL) {
3041
0
      pcapint_fmt_errmsg_for_errno(p->errbuf, sizeof(p->errbuf),
3042
0
          errno, "malloc");
3043
0
      return (PCAP_ERROR);
3044
0
    }
3045
0
    (void)memcpy(*dlt_buffer, p->dlt_list,
3046
0
        sizeof(**dlt_buffer) * p->dlt_count);
3047
0
    return (p->dlt_count);
3048
0
  }
3049
0
}
3050
3051
/*
3052
 * In Windows, you might have a library built with one version of the
3053
 * C runtime library and an application built with another version of
3054
 * the C runtime library, which means that the library might use one
3055
 * version of malloc() and free() and the application might use another
3056
 * version of malloc() and free().  If so, that means something
3057
 * allocated by the library cannot be freed by the application, so we
3058
 * need to have a pcap_free_datalinks() routine to free up the list
3059
 * allocated by pcap_list_datalinks(), even though it's just a wrapper
3060
 * around free().
3061
 */
3062
void
3063
pcap_free_datalinks(int *dlt_list)
3064
0
{
3065
0
  free(dlt_list);
3066
0
}
3067
3068
int
3069
pcap_set_datalink(pcap_t *p, int dlt)
3070
0
{
3071
0
  int i;
3072
0
  const char *dlt_name;
3073
3074
0
  if (dlt < 0)
3075
0
    goto unsupported;
3076
3077
0
  if (p->dlt_count == 0 || p->set_datalink_op == NULL) {
3078
    /*
3079
     * We couldn't fetch the list of DLTs, or we don't
3080
     * have a "set datalink" operation, which means
3081
     * this platform doesn't support changing the
3082
     * DLT for an interface.  Check whether the new
3083
     * DLT is the one this interface supports.
3084
     */
3085
0
    if (p->linktype != dlt)
3086
0
      goto unsupported;
3087
3088
    /*
3089
     * It is, so there's nothing we need to do here.
3090
     */
3091
0
    return (0);
3092
0
  }
3093
0
  for (i = 0; i < p->dlt_count; i++)
3094
0
    if (p->dlt_list[i] == (u_int)dlt)
3095
0
      break;
3096
0
  if (i >= p->dlt_count)
3097
0
    goto unsupported;
3098
0
  if (p->dlt_count == 2 && p->dlt_list[0] == DLT_EN10MB &&
3099
0
      dlt == DLT_DOCSIS) {
3100
    /*
3101
     * This is presumably an Ethernet device, as the first
3102
     * link-layer type it offers is DLT_EN10MB, and the only
3103
     * other type it offers is DLT_DOCSIS.  That means that
3104
     * we can't tell the driver to supply DOCSIS link-layer
3105
     * headers - we're just pretending that's what we're
3106
     * getting, as, presumably, we're capturing on a dedicated
3107
     * link to a Cisco Cable Modem Termination System, and
3108
     * it's putting raw DOCSIS frames on the wire inside low-level
3109
     * Ethernet framing.
3110
     */
3111
0
    p->linktype = dlt;
3112
0
    return (0);
3113
0
  }
3114
0
  if (p->set_datalink_op(p, dlt) == -1)
3115
0
    return (-1);
3116
0
  p->linktype = dlt;
3117
0
  return (0);
3118
3119
0
unsupported:
3120
0
  dlt_name = pcap_datalink_val_to_name(dlt);
3121
0
  if (dlt_name != NULL) {
3122
0
    (void) snprintf(p->errbuf, sizeof(p->errbuf),
3123
0
        "%s is not one of the DLTs supported by this device",
3124
0
        dlt_name);
3125
0
  } else {
3126
0
    (void) snprintf(p->errbuf, sizeof(p->errbuf),
3127
0
        "DLT %d is not one of the DLTs supported by this device",
3128
0
        dlt);
3129
0
  }
3130
0
  return (-1);
3131
0
}
3132
3133
/*
3134
 * This array is designed for mapping upper and lower case letter
3135
 * together for a case independent comparison.  The mappings are
3136
 * based upon ascii character sequences.
3137
 */
3138
static const u_char charmap[] = {
3139
  (u_char)'\000', (u_char)'\001', (u_char)'\002', (u_char)'\003',
3140
  (u_char)'\004', (u_char)'\005', (u_char)'\006', (u_char)'\007',
3141
  (u_char)'\010', (u_char)'\011', (u_char)'\012', (u_char)'\013',
3142
  (u_char)'\014', (u_char)'\015', (u_char)'\016', (u_char)'\017',
3143
  (u_char)'\020', (u_char)'\021', (u_char)'\022', (u_char)'\023',
3144
  (u_char)'\024', (u_char)'\025', (u_char)'\026', (u_char)'\027',
3145
  (u_char)'\030', (u_char)'\031', (u_char)'\032', (u_char)'\033',
3146
  (u_char)'\034', (u_char)'\035', (u_char)'\036', (u_char)'\037',
3147
  (u_char)'\040', (u_char)'\041', (u_char)'\042', (u_char)'\043',
3148
  (u_char)'\044', (u_char)'\045', (u_char)'\046', (u_char)'\047',
3149
  (u_char)'\050', (u_char)'\051', (u_char)'\052', (u_char)'\053',
3150
  (u_char)'\054', (u_char)'\055', (u_char)'\056', (u_char)'\057',
3151
  (u_char)'\060', (u_char)'\061', (u_char)'\062', (u_char)'\063',
3152
  (u_char)'\064', (u_char)'\065', (u_char)'\066', (u_char)'\067',
3153
  (u_char)'\070', (u_char)'\071', (u_char)'\072', (u_char)'\073',
3154
  (u_char)'\074', (u_char)'\075', (u_char)'\076', (u_char)'\077',
3155
  (u_char)'\100', (u_char)'\141', (u_char)'\142', (u_char)'\143',
3156
  (u_char)'\144', (u_char)'\145', (u_char)'\146', (u_char)'\147',
3157
  (u_char)'\150', (u_char)'\151', (u_char)'\152', (u_char)'\153',
3158
  (u_char)'\154', (u_char)'\155', (u_char)'\156', (u_char)'\157',
3159
  (u_char)'\160', (u_char)'\161', (u_char)'\162', (u_char)'\163',
3160
  (u_char)'\164', (u_char)'\165', (u_char)'\166', (u_char)'\167',
3161
  (u_char)'\170', (u_char)'\171', (u_char)'\172', (u_char)'\133',
3162
  (u_char)'\134', (u_char)'\135', (u_char)'\136', (u_char)'\137',
3163
  (u_char)'\140', (u_char)'\141', (u_char)'\142', (u_char)'\143',
3164
  (u_char)'\144', (u_char)'\145', (u_char)'\146', (u_char)'\147',
3165
  (u_char)'\150', (u_char)'\151', (u_char)'\152', (u_char)'\153',
3166
  (u_char)'\154', (u_char)'\155', (u_char)'\156', (u_char)'\157',
3167
  (u_char)'\160', (u_char)'\161', (u_char)'\162', (u_char)'\163',
3168
  (u_char)'\164', (u_char)'\165', (u_char)'\166', (u_char)'\167',
3169
  (u_char)'\170', (u_char)'\171', (u_char)'\172', (u_char)'\173',
3170
  (u_char)'\174', (u_char)'\175', (u_char)'\176', (u_char)'\177',
3171
  (u_char)'\200', (u_char)'\201', (u_char)'\202', (u_char)'\203',
3172
  (u_char)'\204', (u_char)'\205', (u_char)'\206', (u_char)'\207',
3173
  (u_char)'\210', (u_char)'\211', (u_char)'\212', (u_char)'\213',
3174
  (u_char)'\214', (u_char)'\215', (u_char)'\216', (u_char)'\217',
3175
  (u_char)'\220', (u_char)'\221', (u_char)'\222', (u_char)'\223',
3176
  (u_char)'\224', (u_char)'\225', (u_char)'\226', (u_char)'\227',
3177
  (u_char)'\230', (u_char)'\231', (u_char)'\232', (u_char)'\233',
3178
  (u_char)'\234', (u_char)'\235', (u_char)'\236', (u_char)'\237',
3179
  (u_char)'\240', (u_char)'\241', (u_char)'\242', (u_char)'\243',
3180
  (u_char)'\244', (u_char)'\245', (u_char)'\246', (u_char)'\247',
3181
  (u_char)'\250', (u_char)'\251', (u_char)'\252', (u_char)'\253',
3182
  (u_char)'\254', (u_char)'\255', (u_char)'\256', (u_char)'\257',
3183
  (u_char)'\260', (u_char)'\261', (u_char)'\262', (u_char)'\263',
3184
  (u_char)'\264', (u_char)'\265', (u_char)'\266', (u_char)'\267',
3185
  (u_char)'\270', (u_char)'\271', (u_char)'\272', (u_char)'\273',
3186
  (u_char)'\274', (u_char)'\275', (u_char)'\276', (u_char)'\277',
3187
  (u_char)'\300', (u_char)'\341', (u_char)'\342', (u_char)'\343',
3188
  (u_char)'\344', (u_char)'\345', (u_char)'\346', (u_char)'\347',
3189
  (u_char)'\350', (u_char)'\351', (u_char)'\352', (u_char)'\353',
3190
  (u_char)'\354', (u_char)'\355', (u_char)'\356', (u_char)'\357',
3191
  (u_char)'\360', (u_char)'\361', (u_char)'\362', (u_char)'\363',
3192
  (u_char)'\364', (u_char)'\365', (u_char)'\366', (u_char)'\367',
3193
  (u_char)'\370', (u_char)'\371', (u_char)'\372', (u_char)'\333',
3194
  (u_char)'\334', (u_char)'\335', (u_char)'\336', (u_char)'\337',
3195
  (u_char)'\340', (u_char)'\341', (u_char)'\342', (u_char)'\343',
3196
  (u_char)'\344', (u_char)'\345', (u_char)'\346', (u_char)'\347',
3197
  (u_char)'\350', (u_char)'\351', (u_char)'\352', (u_char)'\353',
3198
  (u_char)'\354', (u_char)'\355', (u_char)'\356', (u_char)'\357',
3199
  (u_char)'\360', (u_char)'\361', (u_char)'\362', (u_char)'\363',
3200
  (u_char)'\364', (u_char)'\365', (u_char)'\366', (u_char)'\367',
3201
  (u_char)'\370', (u_char)'\371', (u_char)'\372', (u_char)'\373',
3202
  (u_char)'\374', (u_char)'\375', (u_char)'\376', (u_char)'\377',
3203
};
3204
3205
int
3206
pcapint_strcasecmp(const char *s1, const char *s2)
3207
3.96k
{
3208
3.96k
  const u_char  *us1 = (const u_char *)s1,
3209
3.96k
      *us2 = (const u_char *)s2;
3210
3211
5.59k
  while (charmap[*us1] == charmap[*us2++])
3212
2.26k
    if (*us1++ == '\0')
3213
640
      return(0);
3214
3.32k
  return (charmap[*us1] - charmap[*--us2]);
3215
3.96k
}
3216
3217
struct dlt_choice {
3218
  const char *name;
3219
  const char *description;
3220
  int dlt;
3221
};
3222
3223
#define DLT_CHOICE(code, description) { #code, description, DLT_ ## code }
3224
#define DLT_CHOICE_SENTINEL { NULL, NULL, 0 }
3225
3226
static struct dlt_choice dlt_choices[] = {
3227
  DLT_CHOICE(NULL, "BSD loopback"),
3228
  DLT_CHOICE(EN10MB, "Ethernet"),
3229
  DLT_CHOICE(EN3MB, "experimental Ethernet (3Mb/s)"),
3230
  DLT_CHOICE(AX25, "AX.25 layer 2"),
3231
  DLT_CHOICE(PRONET, "Proteon ProNET Token Ring"),
3232
  DLT_CHOICE(CHAOS, "MIT Chaosnet"),
3233
  DLT_CHOICE(IEEE802, "802.5 Token Ring"),
3234
  DLT_CHOICE(ARCNET, "BSD ARCnet"),
3235
  DLT_CHOICE(SLIP, "Serial Line IP"),
3236
  DLT_CHOICE(PPP, "Point-to-Point Protocol"),
3237
  DLT_CHOICE(FDDI, "Fiber Distributed Data Interface"),
3238
  DLT_CHOICE(REDBACK_SMARTEDGE, "Redback SmartEdge 400/800"),
3239
  DLT_CHOICE(ATM_RFC1483, "RFC 1483 LLC-encapsulated ATM"),
3240
  DLT_CHOICE(RAW, "Raw IPv4/IPv6"),
3241
  DLT_CHOICE(SLIP_BSDOS, "BSD/OS Serial Line IP"),
3242
  DLT_CHOICE(PPP_BSDOS, "BSD/OS Point-to-Point Protocol"),
3243
  DLT_CHOICE(ATM_CLIP, "Linux Classical IP over ATM"),
3244
  DLT_CHOICE(PPP_SERIAL, "Point-to-Point Protocol over serial"),
3245
  DLT_CHOICE(PPP_ETHER, "PPPoE session packets"),
3246
  DLT_CHOICE(SYMANTEC_FIREWALL, "Symantec Firewall"),
3247
  DLT_CHOICE(C_HDLC, "Cisco HDLC"),
3248
  DLT_CHOICE(IEEE802_11, "802.11"),
3249
  DLT_CHOICE(FRELAY, "Frame Relay"),
3250
  DLT_CHOICE(LOOP, "OpenBSD loopback"),
3251
  DLT_CHOICE(ENC, "OpenBSD encapsulated IP"),
3252
  DLT_CHOICE(LINUX_SLL, "Linux cooked v1"),
3253
  DLT_CHOICE(LTALK, "LocalTalk"),
3254
  DLT_CHOICE(PFLOG, "OpenBSD pflog file"),
3255
  DLT_CHOICE(PFSYNC, "Packet filter state syncing"),
3256
  DLT_CHOICE(PRISM_HEADER, "802.11 plus Prism header"),
3257
  DLT_CHOICE(IP_OVER_FC, "RFC 2625 IP-over-Fibre Channel"),
3258
  DLT_CHOICE(SUNATM, "Sun raw ATM"),
3259
  DLT_CHOICE(IEEE802_11_RADIO, "802.11 plus radiotap header"),
3260
  DLT_CHOICE(ARCNET_LINUX, "Linux ARCnet"),
3261
  DLT_CHOICE(JUNIPER_MLPPP, "Juniper Multi-Link PPP"),
3262
  DLT_CHOICE(JUNIPER_MLFR, "Juniper Multi-Link Frame Relay"),
3263
  DLT_CHOICE(JUNIPER_ES, "Juniper Encryption Services PIC"),
3264
  DLT_CHOICE(JUNIPER_GGSN, "Juniper GGSN PIC"),
3265
  DLT_CHOICE(JUNIPER_MFR, "Juniper FRF.16 Frame Relay"),
3266
  DLT_CHOICE(JUNIPER_ATM2, "Juniper ATM2 PIC"),
3267
  DLT_CHOICE(JUNIPER_SERVICES, "Juniper Advanced Services PIC"),
3268
  DLT_CHOICE(JUNIPER_ATM1, "Juniper ATM1 PIC"),
3269
  DLT_CHOICE(APPLE_IP_OVER_IEEE1394, "Apple IP-over-IEEE 1394"),
3270
  DLT_CHOICE(MTP2_WITH_PHDR, "SS7 MTP2 with Pseudo-header"),
3271
  DLT_CHOICE(MTP2, "SS7 MTP2"),
3272
  DLT_CHOICE(MTP3, "SS7 MTP3"),
3273
  DLT_CHOICE(SCCP, "SS7 SCCP"),
3274
  DLT_CHOICE(DOCSIS, "DOCSIS"),
3275
  DLT_CHOICE(LINUX_IRDA, "Linux IrDA"),
3276
  DLT_CHOICE(IEEE802_11_RADIO_AVS, "802.11 plus AVS radio information header"),
3277
  DLT_CHOICE(JUNIPER_MONITOR, "Juniper Passive Monitor PIC"),
3278
  DLT_CHOICE(BACNET_MS_TP, "BACnet MS/TP"),
3279
  DLT_CHOICE(PPP_PPPD, "PPP for pppd, with direction flag"),
3280
  DLT_CHOICE(JUNIPER_PPPOE, "Juniper PPPoE"),
3281
  DLT_CHOICE(JUNIPER_PPPOE_ATM, "Juniper PPPoE/ATM"),
3282
  DLT_CHOICE(GPRS_LLC, "GPRS LLC"),
3283
  DLT_CHOICE(GPF_T, "GPF-T"),
3284
  DLT_CHOICE(GPF_F, "GPF-F"),
3285
  DLT_CHOICE(JUNIPER_PIC_PEER, "Juniper PIC Peer"),
3286
  DLT_CHOICE(ERF_ETH, "Ethernet with Endace ERF header"),
3287
  DLT_CHOICE(ERF_POS, "Packet-over-SONET with Endace ERF header"),
3288
  DLT_CHOICE(LINUX_LAPD, "Linux vISDN LAPD"),
3289
  DLT_CHOICE(JUNIPER_ETHER, "Juniper Ethernet"),
3290
  DLT_CHOICE(JUNIPER_PPP, "Juniper PPP"),
3291
  DLT_CHOICE(JUNIPER_FRELAY, "Juniper Frame Relay"),
3292
  DLT_CHOICE(JUNIPER_CHDLC, "Juniper C-HDLC"),
3293
  DLT_CHOICE(MFR, "FRF.16 Frame Relay"),
3294
  DLT_CHOICE(JUNIPER_VP, "Juniper Voice PIC"),
3295
  DLT_CHOICE(A429, "Arinc 429"),
3296
  DLT_CHOICE(A653_ICM, "Arinc 653 Interpartition Communication"),
3297
  DLT_CHOICE(USB_FREEBSD, "USB with FreeBSD header"),
3298
  DLT_CHOICE(BLUETOOTH_HCI_H4, "Bluetooth HCI UART transport layer"),
3299
  DLT_CHOICE(IEEE802_16_MAC_CPS, "IEEE 802.16 MAC Common Part Sublayer"),
3300
  DLT_CHOICE(USB_LINUX, "USB with Linux header"),
3301
  DLT_CHOICE(CAN20B, "Controller Area Network (CAN) v. 2.0B"),
3302
  DLT_CHOICE(IEEE802_15_4_LINUX, "IEEE 802.15.4 with Linux padding"),
3303
  DLT_CHOICE(PPI, "Per-Packet Information"),
3304
  DLT_CHOICE(IEEE802_16_MAC_CPS_RADIO, "IEEE 802.16 MAC Common Part Sublayer plus radiotap header"),
3305
  DLT_CHOICE(JUNIPER_ISM, "Juniper Integrated Service Module"),
3306
  DLT_CHOICE(IEEE802_15_4, "IEEE 802.15.4 with FCS"),
3307
  DLT_CHOICE(SITA, "SITA pseudo-header"),
3308
  DLT_CHOICE(ERF, "Endace ERF header"),
3309
  DLT_CHOICE(RAIF1, "Ethernet with u10 Networks pseudo-header"),
3310
  DLT_CHOICE(IPMB_KONTRON, "IPMB with Kontron pseudo-header"),
3311
  DLT_CHOICE(JUNIPER_ST, "Juniper Secure Tunnel"),
3312
  DLT_CHOICE(BLUETOOTH_HCI_H4_WITH_PHDR, "Bluetooth HCI UART transport layer plus pseudo-header"),
3313
  DLT_CHOICE(AX25_KISS, "AX.25 with KISS header"),
3314
  DLT_CHOICE(I2C_LINUX, "I2C with Linux/Pigeon Point pseudo-header"),
3315
  DLT_CHOICE(IEEE802_15_4_NONASK_PHY, "IEEE 802.15.4 with non-ASK PHY data"),
3316
  DLT_CHOICE(MPLS, "MPLS with label as link-layer header"),
3317
  DLT_CHOICE(LINUX_EVDEV, "Linux evdev events"),
3318
  DLT_CHOICE(USB_LINUX_MMAPPED, "USB with padded Linux header"),
3319
  DLT_CHOICE(DECT, "DECT"),
3320
  DLT_CHOICE(AOS, "AOS Space Data Link protocol"),
3321
  DLT_CHOICE(WIHART, "WirelessHART"),
3322
  DLT_CHOICE(FC_2, "Fibre Channel FC-2"),
3323
  DLT_CHOICE(FC_2_WITH_FRAME_DELIMS, "Fibre Channel FC-2 with frame delimiters"),
3324
  DLT_CHOICE(IPNET, "Solaris ipnet"),
3325
  DLT_CHOICE(CAN_SOCKETCAN, "CAN-bus with SocketCAN headers"),
3326
  DLT_CHOICE(IPV4, "Raw IPv4"),
3327
  DLT_CHOICE(IPV6, "Raw IPv6"),
3328
  DLT_CHOICE(IEEE802_15_4_NOFCS, "IEEE 802.15.4 without FCS"),
3329
  DLT_CHOICE(DBUS, "D-Bus"),
3330
  DLT_CHOICE(JUNIPER_VS, "Juniper Virtual Server"),
3331
  DLT_CHOICE(JUNIPER_SRX_E2E, "Juniper SRX E2E"),
3332
  DLT_CHOICE(JUNIPER_FIBRECHANNEL, "Juniper Fibre Channel"),
3333
  DLT_CHOICE(DVB_CI, "DVB-CI"),
3334
  DLT_CHOICE(MUX27010, "MUX27010"),
3335
  DLT_CHOICE(STANAG_5066_D_PDU, "STANAG 5066 D_PDUs"),
3336
  DLT_CHOICE(JUNIPER_ATM_CEMIC, "Juniper ATM CEMIC"),
3337
  DLT_CHOICE(NFLOG, "Linux netfilter log messages"),
3338
  DLT_CHOICE(NETANALYZER, "Ethernet with Hilscher netANALYZER pseudo-header"),
3339
  DLT_CHOICE(NETANALYZER_TRANSPARENT, "Ethernet with Hilscher netANALYZER pseudo-header and with preamble and SFD"),
3340
  DLT_CHOICE(IPOIB, "RFC 4391 IP-over-InfiniBand"),
3341
  DLT_CHOICE(MPEG_2_TS, "MPEG-2 transport stream"),
3342
  DLT_CHOICE(NG40, "ng40 protocol tester Iub/Iur"),
3343
  DLT_CHOICE(NFC_LLCP, "NFC LLCP PDUs with pseudo-header"),
3344
  DLT_CHOICE(INFINIBAND, "InfiniBand"),
3345
  DLT_CHOICE(SCTP, "SCTP"),
3346
  DLT_CHOICE(USBPCAP, "USB with USBPcap header"),
3347
  DLT_CHOICE(RTAC_SERIAL, "Schweitzer Engineering Laboratories RTAC packets"),
3348
  DLT_CHOICE(BLUETOOTH_LE_LL, "Bluetooth Low Energy air interface"),
3349
  DLT_CHOICE(NETLINK, "Linux netlink"),
3350
  DLT_CHOICE(BLUETOOTH_LINUX_MONITOR, "Bluetooth Linux Monitor"),
3351
  DLT_CHOICE(BLUETOOTH_BREDR_BB, "Bluetooth Basic Rate/Enhanced Data Rate baseband packets"),
3352
  DLT_CHOICE(BLUETOOTH_LE_LL_WITH_PHDR, "Bluetooth Low Energy air interface with pseudo-header"),
3353
  DLT_CHOICE(PROFIBUS_DL, "PROFIBUS data link layer"),
3354
  DLT_CHOICE(PKTAP, "Apple PKTAP"),
3355
  DLT_CHOICE(EPON, "Ethernet with 802.3 Clause 65 EPON preamble"),
3356
  DLT_CHOICE(IPMI_HPM_2, "IPMI trace packets"),
3357
  DLT_CHOICE(ZWAVE_R1_R2, "Z-Wave RF profile R1 and R2 packets"),
3358
  DLT_CHOICE(ZWAVE_R3, "Z-Wave RF profile R3 packets"),
3359
  DLT_CHOICE(WATTSTOPPER_DLM, "WattStopper Digital Lighting Management (DLM) and Legrand Nitoo Open protocol"),
3360
  DLT_CHOICE(ISO_14443, "ISO 14443 messages"),
3361
  DLT_CHOICE(RDS, "IEC 62106 Radio Data System groups"),
3362
  DLT_CHOICE(USB_DARWIN, "USB with Darwin header"),
3363
  DLT_CHOICE(OPENFLOW, "OpenBSD OpenFlow"),
3364
  DLT_CHOICE(SDLC, "IBM SDLC frames"),
3365
  DLT_CHOICE(TI_LLN_SNIFFER, "TI LLN sniffer frames"),
3366
  DLT_CHOICE(VSOCK, "Linux vsock"),
3367
  DLT_CHOICE(NORDIC_BLE, "Nordic Semiconductor Bluetooth LE sniffer frames"),
3368
  DLT_CHOICE(DOCSIS31_XRA31, "Excentis XRA-31 DOCSIS 3.1 RF sniffer frames"),
3369
  DLT_CHOICE(ETHERNET_MPACKET, "802.3br mPackets"),
3370
  DLT_CHOICE(DISPLAYPORT_AUX, "DisplayPort AUX channel monitoring data"),
3371
  DLT_CHOICE(LINUX_SLL2, "Linux cooked v2"),
3372
  DLT_CHOICE(OPENVIZSLA, "OpenVizsla USB"),
3373
  DLT_CHOICE(EBHSCR, "Elektrobit High Speed Capture and Replay (EBHSCR)"),
3374
  DLT_CHOICE(VPP_DISPATCH, "VPP graph dispatch tracer"),
3375
  DLT_CHOICE(DSA_TAG_BRCM, "Broadcom infix DSA tag"),
3376
  DLT_CHOICE(DSA_TAG_BRCM_PREPEND, "Broadcom prefix DSA tag"),
3377
  DLT_CHOICE(IEEE802_15_4_TAP, "IEEE 802.15.4 with pseudo-header"),
3378
  DLT_CHOICE(DSA_TAG_DSA, "Marvell infix 4-octet DSA tag"),
3379
  DLT_CHOICE(DSA_TAG_EDSA, "Marvell infix 8-octet DSA tag"),
3380
  DLT_CHOICE(ELEE, "ELEE lawful intercept packets"),
3381
  DLT_CHOICE(Z_WAVE_SERIAL, "Z-Wave serial frames between host and chip"),
3382
  DLT_CHOICE(USB_2_0, "USB 2.0/1.1/1.0 as transmitted over the cable"),
3383
  DLT_CHOICE(ATSC_ALP, "ATSC Link-Layer Protocol packets"),
3384
  DLT_CHOICE(ETW, "Event Tracing for Windows messages"),
3385
  DLT_CHOICE(NETANALYZER_NG, "Hilscher netANALYZER NG pseudo-footer"),
3386
  DLT_CHOICE(ZBOSS_NCP, "ZBOSS NCP protocol with pseudo-header"),
3387
  DLT_CHOICE(USB_2_0_LOW_SPEED, "Low-Speed USB 2.0/1.1/1.0 as transmitted over the cable"),
3388
  DLT_CHOICE(USB_2_0_FULL_SPEED, "Full-Speed USB 2.0/1.1/1.0 as transmitted over the cable"),
3389
  DLT_CHOICE(USB_2_0_HIGH_SPEED, "High-Speed USB 2.0 as transmitted over the cable"),
3390
  DLT_CHOICE(AUERSWALD_LOG, "Auerswald Logger Protocol"),
3391
  DLT_CHOICE(ZWAVE_TAP, "Z-Wave packets with a TAP meta-data header"),
3392
  DLT_CHOICE(SILABS_DEBUG_CHANNEL, "Silicon Labs debug channel protocol"),
3393
  DLT_CHOICE(FIRA_UCI, "Ultra-wideband controller interface protocol"),
3394
  DLT_CHOICE(MDB, "Multi-Drop Bus"),
3395
  DLT_CHOICE(DECT_NR, "DECT New Radio"),
3396
  DLT_CHOICE(USER0, "Private use 0"),
3397
  DLT_CHOICE(USER1, "Private use 1"),
3398
  DLT_CHOICE(USER2, "Private use 2"),
3399
  DLT_CHOICE(USER3, "Private use 3"),
3400
  DLT_CHOICE(USER4, "Private use 4"),
3401
  DLT_CHOICE(USER5, "Private use 5"),
3402
  DLT_CHOICE(USER6, "Private use 6"),
3403
  DLT_CHOICE(USER7, "Private use 7"),
3404
  DLT_CHOICE(USER8, "Private use 8"),
3405
  DLT_CHOICE(USER9, "Private use 9"),
3406
  DLT_CHOICE(USER10, "Private use 10"),
3407
  DLT_CHOICE(USER11, "Private use 11"),
3408
  DLT_CHOICE(USER12, "Private use 12"),
3409
  DLT_CHOICE(USER13, "Private use 13"),
3410
  DLT_CHOICE(USER14, "Private use 14"),
3411
  DLT_CHOICE(USER15, "Private use 15"),
3412
  DLT_CHOICE(EDK2_MM, "EDK II MM request serialization protocol"),
3413
  DLT_CHOICE(DEBUG_ONLY, "unstructured data for manual debugging only"),
3414
  DLT_CHOICE_SENTINEL
3415
};
3416
3417
int
3418
pcap_datalink_name_to_val(const char *name)
3419
0
{
3420
0
  int i;
3421
3422
0
  for (i = 0; dlt_choices[i].name != NULL; i++) {
3423
0
    if (pcapint_strcasecmp(dlt_choices[i].name, name) == 0)
3424
0
      return (dlt_choices[i].dlt);
3425
0
  }
3426
0
  return (-1);
3427
0
}
3428
3429
const char *
3430
pcap_datalink_val_to_name(int dlt)
3431
128
{
3432
128
  int i;
3433
3434
14.9k
  for (i = 0; dlt_choices[i].name != NULL; i++) {
3435
14.9k
    if (dlt_choices[i].dlt == dlt)
3436
115
      return (dlt_choices[i].name);
3437
14.9k
  }
3438
13
  return (NULL);
3439
128
}
3440
3441
const char *
3442
pcap_datalink_val_to_description(int dlt)
3443
141
{
3444
141
  int i;
3445
3446
17.3k
  for (i = 0; dlt_choices[i].name != NULL; i++) {
3447
17.3k
    if (dlt_choices[i].dlt == dlt)
3448
115
      return (dlt_choices[i].description);
3449
17.3k
  }
3450
26
  return (NULL);
3451
141
}
3452
3453
const char *
3454
pcap_datalink_val_to_description_or_dlt(int dlt)
3455
13
{
3456
13
        static thread_local char unkbuf[40];
3457
13
        const char *description;
3458
3459
13
        description = pcap_datalink_val_to_description(dlt);
3460
13
        if (description != NULL) {
3461
0
                return description;
3462
13
        } else {
3463
13
                (void)snprintf(unkbuf, sizeof(unkbuf), "DLT %d", dlt);
3464
13
                return unkbuf;
3465
13
        }
3466
13
}
3467
3468
struct tstamp_type_choice {
3469
  const char *name;
3470
  const char *description;
3471
  int type;
3472
};
3473
3474
static struct tstamp_type_choice tstamp_type_choices[] = {
3475
  { "host", "Host", PCAP_TSTAMP_HOST },
3476
  { "host_lowprec", "Host, low precision", PCAP_TSTAMP_HOST_LOWPREC },
3477
  { "host_hiprec", "Host, high precision", PCAP_TSTAMP_HOST_HIPREC },
3478
  { "adapter", "Adapter", PCAP_TSTAMP_ADAPTER },
3479
  { "adapter_unsynced", "Adapter, not synced with system time", PCAP_TSTAMP_ADAPTER_UNSYNCED },
3480
  { "host_hiprec_unsynced", "Host, high precision, not synced with system time", PCAP_TSTAMP_HOST_HIPREC_UNSYNCED },
3481
  { NULL, NULL, 0 }
3482
};
3483
3484
int
3485
pcap_tstamp_type_name_to_val(const char *name)
3486
0
{
3487
0
  int i;
3488
3489
0
  for (i = 0; tstamp_type_choices[i].name != NULL; i++) {
3490
0
    if (pcapint_strcasecmp(tstamp_type_choices[i].name, name) == 0)
3491
0
      return (tstamp_type_choices[i].type);
3492
0
  }
3493
0
  return (PCAP_ERROR);
3494
0
}
3495
3496
const char *
3497
pcap_tstamp_type_val_to_name(int tstamp_type)
3498
0
{
3499
0
  int i;
3500
3501
0
  for (i = 0; tstamp_type_choices[i].name != NULL; i++) {
3502
0
    if (tstamp_type_choices[i].type == tstamp_type)
3503
0
      return (tstamp_type_choices[i].name);
3504
0
  }
3505
0
  return (NULL);
3506
0
}
3507
3508
const char *
3509
pcap_tstamp_type_val_to_description(int tstamp_type)
3510
0
{
3511
0
  int i;
3512
3513
0
  for (i = 0; tstamp_type_choices[i].name != NULL; i++) {
3514
0
    if (tstamp_type_choices[i].type == tstamp_type)
3515
0
      return (tstamp_type_choices[i].description);
3516
0
  }
3517
0
  return (NULL);
3518
0
}
3519
3520
int
3521
pcap_snapshot(pcap_t *p)
3522
12.8k
{
3523
12.8k
  if (!p->activated)
3524
0
    return (PCAP_ERROR_NOT_ACTIVATED);
3525
12.8k
  return (p->snapshot);
3526
12.8k
}
3527
3528
int
3529
pcap_is_swapped(pcap_t *p)
3530
0
{
3531
0
  if (!p->activated)
3532
0
    return (PCAP_ERROR_NOT_ACTIVATED);
3533
0
  return (p->swapped);
3534
0
}
3535
3536
int
3537
pcap_major_version(pcap_t *p)
3538
0
{
3539
0
  if (!p->activated)
3540
0
    return (PCAP_ERROR_NOT_ACTIVATED);
3541
0
  return (p->version_major);
3542
0
}
3543
3544
int
3545
pcap_minor_version(pcap_t *p)
3546
0
{
3547
0
  if (!p->activated)
3548
0
    return (PCAP_ERROR_NOT_ACTIVATED);
3549
0
  return (p->version_minor);
3550
0
}
3551
3552
int
3553
pcap_bufsize(pcap_t *p)
3554
0
{
3555
0
  if (!p->activated)
3556
0
    return (PCAP_ERROR_NOT_ACTIVATED);
3557
0
  return (p->bufsize);
3558
0
}
3559
3560
FILE *
3561
pcap_file(pcap_t *p)
3562
0
{
3563
0
  return (p->rfile);
3564
0
}
3565
3566
#ifdef _WIN32
3567
int
3568
pcap_fileno(pcap_t *p)
3569
{
3570
  if (p->handle != INVALID_HANDLE_VALUE) {
3571
    /*
3572
     * This is a bogus and now-deprecated API; we
3573
     * squelch the narrowing warning for the cast
3574
     * from HANDLE to intptr_t.  If Windows programmers
3575
     * need to get at the HANDLE for a pcap_t, *if*
3576
     * there is one, they should request such a
3577
     * routine (and be prepared for it to return
3578
     * INVALID_HANDLE_VALUE).
3579
     */
3580
DIAG_OFF_NARROWING
3581
    return ((int)(intptr_t)p->handle);
3582
DIAG_ON_NARROWING
3583
  } else
3584
    return (PCAP_ERROR);
3585
}
3586
#else /* _WIN32 */
3587
int
3588
pcap_fileno(pcap_t *p)
3589
0
{
3590
0
  return (p->fd);
3591
0
}
3592
#endif /* _WIN32 */
3593
3594
#if !defined(_WIN32)
3595
int
3596
pcap_get_selectable_fd(pcap_t *p)
3597
0
{
3598
0
  return (p->selectable_fd);
3599
0
}
3600
3601
const struct timeval *
3602
pcap_get_required_select_timeout(pcap_t *p)
3603
0
{
3604
0
  return (p->required_select_timeout);
3605
0
}
3606
#endif
3607
3608
void
3609
pcap_perror(pcap_t *p, const char *prefix)
3610
0
{
3611
0
  fprintf(stderr, "%s: %s\n", prefix, p->errbuf);
3612
0
}
3613
3614
char *
3615
pcap_geterr(pcap_t *p)
3616
0
{
3617
0
  return (p->errbuf);
3618
0
}
3619
3620
int
3621
pcap_getnonblock(pcap_t *p, char *errbuf)
3622
0
{
3623
0
  int ret;
3624
3625
0
  ret = p->getnonblock_op(p);
3626
0
  if (ret == -1) {
3627
    /*
3628
     * The get nonblock operation sets p->errbuf; this
3629
     * function *shouldn't* have had a separate errbuf
3630
     * argument, as it didn't need one, but I goofed
3631
     * when adding it.
3632
     *
3633
     * We copy the error message to errbuf, so callers
3634
     * can find it in either place.
3635
     */
3636
0
    pcapint_strlcpy(errbuf, p->errbuf, PCAP_ERRBUF_SIZE);
3637
0
  }
3638
0
  return (ret);
3639
0
}
3640
3641
/*
3642
 * Get the current non-blocking mode setting, under the assumption that
3643
 * it's just the standard POSIX non-blocking flag.
3644
 */
3645
#if !defined(_WIN32)
3646
int
3647
pcapint_getnonblock_fd(pcap_t *p)
3648
0
{
3649
0
  int fdflags;
3650
3651
0
  fdflags = fcntl(p->fd, F_GETFL, 0);
3652
0
  if (fdflags == -1) {
3653
0
    pcapint_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
3654
0
        errno, "F_GETFL");
3655
0
    return (-1);
3656
0
  }
3657
0
  if (fdflags & O_NONBLOCK)
3658
0
    return (1);
3659
0
  else
3660
0
    return (0);
3661
0
}
3662
#endif
3663
3664
int
3665
pcap_setnonblock(pcap_t *p, int nonblock, char *errbuf)
3666
0
{
3667
0
  int ret;
3668
3669
0
  ret = p->setnonblock_op(p, nonblock);
3670
0
  if (ret == -1) {
3671
    /*
3672
     * The set nonblock operation sets p->errbuf; this
3673
     * function *shouldn't* have had a separate errbuf
3674
     * argument, as it didn't need one, but I goofed
3675
     * when adding it.
3676
     *
3677
     * We copy the error message to errbuf, so callers
3678
     * can find it in either place.
3679
     */
3680
0
    pcapint_strlcpy(errbuf, p->errbuf, PCAP_ERRBUF_SIZE);
3681
0
  }
3682
0
  return (ret);
3683
0
}
3684
3685
#if !defined(_WIN32)
3686
/*
3687
 * Set non-blocking mode, under the assumption that it's just the
3688
 * standard POSIX non-blocking flag.  (This can be called by the
3689
 * per-platform non-blocking-mode routine if that routine also
3690
 * needs to do some additional work.)
3691
 */
3692
int
3693
pcapint_setnonblock_fd(pcap_t *p, int nonblock)
3694
0
{
3695
0
  int fdflags;
3696
3697
0
  fdflags = fcntl(p->fd, F_GETFL, 0);
3698
0
  if (fdflags == -1) {
3699
0
    pcapint_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
3700
0
        errno, "F_GETFL");
3701
0
    return (-1);
3702
0
  }
3703
0
  if (nonblock)
3704
0
    fdflags |= O_NONBLOCK;
3705
0
  else
3706
0
    fdflags &= ~O_NONBLOCK;
3707
0
  if (fcntl(p->fd, F_SETFL, fdflags) == -1) {
3708
0
    pcapint_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
3709
0
        errno, "F_SETFL");
3710
0
    return (-1);
3711
0
  }
3712
0
  return (0);
3713
0
}
3714
#endif
3715
3716
/*
3717
 * Generate error strings for PCAP_ERROR_ and PCAP_WARNING_ values.
3718
 */
3719
const char *
3720
pcap_statustostr(int errnum)
3721
0
{
3722
0
  static thread_local char ebuf[15+10+1];
3723
3724
0
  switch (errnum) {
3725
3726
0
  case PCAP_WARNING:
3727
0
    return("Generic warning");
3728
3729
0
  case PCAP_WARNING_TSTAMP_TYPE_NOTSUP:
3730
0
    return ("That type of time stamp is not supported by that device");
3731
3732
0
  case PCAP_WARNING_PROMISC_NOTSUP:
3733
0
    return ("That device doesn't support promiscuous mode");
3734
3735
0
  case PCAP_ERROR:
3736
0
    return("Generic error");
3737
3738
0
  case PCAP_ERROR_BREAK:
3739
0
    return("Loop terminated by pcap_breakloop");
3740
3741
0
  case PCAP_ERROR_NOT_ACTIVATED:
3742
0
    return("The pcap_t has not been activated");
3743
3744
0
  case PCAP_ERROR_ACTIVATED:
3745
0
    return ("The setting can't be changed after the pcap_t is activated");
3746
3747
0
  case PCAP_ERROR_NO_SUCH_DEVICE:
3748
0
    return ("No such device exists");
3749
3750
0
  case PCAP_ERROR_RFMON_NOTSUP:
3751
0
    return ("That device doesn't support monitor mode");
3752
3753
0
  case PCAP_ERROR_NOT_RFMON:
3754
0
    return ("That operation is supported only in monitor mode");
3755
3756
0
  case PCAP_ERROR_PERM_DENIED:
3757
0
    return ("You don't have permission to perform this capture on that device");
3758
3759
0
  case PCAP_ERROR_IFACE_NOT_UP:
3760
0
    return ("That device is not up");
3761
3762
0
  case PCAP_ERROR_CANTSET_TSTAMP_TYPE:
3763
0
    return ("That device doesn't support setting the time stamp type");
3764
3765
0
  case PCAP_ERROR_PROMISC_PERM_DENIED:
3766
0
    return ("You don't have permission to capture in promiscuous mode on that device");
3767
3768
0
  case PCAP_ERROR_TSTAMP_PRECISION_NOTSUP:
3769
0
    return ("That device doesn't support that time stamp precision");
3770
3771
0
  case PCAP_ERROR_CAPTURE_NOTSUP:
3772
0
    return ("Packet capture is not supported on that device");
3773
0
  }
3774
0
  (void)snprintf(ebuf, sizeof ebuf, "Unknown error: %d", errnum);
3775
0
  return(ebuf);
3776
0
}
3777
3778
/*
3779
 * A long time ago the purpose of this function was to hide the difference
3780
 * between those Unix-like OSes that implemented strerror() and those that
3781
 * didn't.  All the currently supported OSes implement strerror(), which is in
3782
 * POSIX.1-2001, uniformly and that particular problem no longer exists.  But
3783
 * now they implement a few incompatible thread-safe variants of strerror(),
3784
 * and hiding that difference is the current purpose of this function.
3785
 */
3786
const char *
3787
pcap_strerror(int errnum)
3788
0
{
3789
#ifdef _WIN32
3790
  static thread_local char errbuf[PCAP_ERRBUF_SIZE];
3791
  errno_t err = strerror_s(errbuf, PCAP_ERRBUF_SIZE, errnum);
3792
3793
  if (err != 0) /* err = 0 if successful */
3794
    pcapint_strlcpy(errbuf, "strerror_s() error", PCAP_ERRBUF_SIZE);
3795
  return (errbuf);
3796
#elif defined(HAVE_GNU_STRERROR_R)
3797
  /*
3798
   * We have a GNU-style strerror_r(), which is *not* guaranteed to
3799
   * do anything to the buffer handed to it, and which returns a
3800
   * pointer to the error string, which may or may not be in
3801
   * the buffer.
3802
   *
3803
   * It is, however, guaranteed to succeed.
3804
   *
3805
   * At the time of this writing this applies to the following cases,
3806
   * each of which allows to use either the GNU implementation or the
3807
   * POSIX implementation, and this source tree defines _GNU_SOURCE to
3808
   * use the GNU implementation:
3809
   * - Hurd
3810
   * - Linux with GNU libc
3811
   * - Linux with uClibc-ng
3812
   */
3813
0
  static thread_local char errbuf[PCAP_ERRBUF_SIZE];
3814
0
  return strerror_r(errnum, errbuf, PCAP_ERRBUF_SIZE);
3815
#elif defined(HAVE_POSIX_STRERROR_R)
3816
  /*
3817
   * We have a POSIX-style strerror_r(), which is guaranteed to fill
3818
   * in the buffer, but is not guaranteed to succeed.
3819
   *
3820
   * At the time of this writing this applies to the following cases:
3821
   * - AIX 7
3822
   * - FreeBSD
3823
   * - Haiku
3824
   * - HP-UX 11
3825
   * - illumos
3826
   * - Linux with musl libc
3827
   * - macOS
3828
   * - NetBSD
3829
   * - OpenBSD
3830
   * - Solaris 10 & 11
3831
   */
3832
  static thread_local char errbuf[PCAP_ERRBUF_SIZE];
3833
  int err = strerror_r(errnum, errbuf, PCAP_ERRBUF_SIZE);
3834
  switch (err) {
3835
  case 0:
3836
    /* That worked. */
3837
    break;
3838
3839
  case EINVAL:
3840
    /*
3841
     * UNIX 03 says this isn't guaranteed to produce a
3842
     * fallback error message.
3843
     */
3844
    snprintf(errbuf, PCAP_ERRBUF_SIZE,
3845
             "Unknown error: %d", errnum);
3846
    break;
3847
  case ERANGE:
3848
    /*
3849
     * UNIX 03 says this isn't guaranteed to produce a
3850
     * fallback error message.
3851
     */
3852
    snprintf(errbuf, PCAP_ERRBUF_SIZE,
3853
             "Message for error %d is too long", errnum);
3854
    break;
3855
  default:
3856
    snprintf(errbuf, PCAP_ERRBUF_SIZE,
3857
             "strerror_r(%d, ...) unexpectedly returned %d",
3858
             errnum, err);
3859
  }
3860
  return errbuf;
3861
#else
3862
  /*
3863
   * At the time of this writing every supported OS implements strerror()
3864
   * and at least one thread-safe variant thereof, so this is a very
3865
   * unlikely last-resort branch.  Particular implementations of strerror()
3866
   * may be thread-safe, but this is neither required nor guaranteed.
3867
   */
3868
  return (strerror(errnum));
3869
#endif /* _WIN32 */
3870
0
}
3871
3872
/*
3873
 * Routine to parse a string containing an unsigned decimal integer,
3874
 * which catches some errors that strtoul() doesn't (strtoul() appears
3875
 * to parse numbers according to the way a C compiler does, so it skips
3876
 * leading white space and will happily allow an unsigned number with
3877
 * a negative sign), and also can treat the string not being completely
3878
 * numeric as an error and will treat values that don't fit into
3879
 * an unsigned int as an error.
3880
 *
3881
 * On success, returns 0 and sets the value pointed to by the last
3882
 * argument to the integer value; on error, returns EINVAL for an
3883
 * invalid number or ERANGE for a value that's too large to fit in
3884
 * an unsigned int.
3885
 */
3886
int
3887
pcapint_get_decuint(const char *cp, char **endptr, unsigned *nump)
3888
0
{
3889
0
  unsigned long val;
3890
0
  char *end;
3891
3892
0
  if (cp == NULL) {
3893
    /* Don't do this. */
3894
0
    return (EINVAL);
3895
0
  }
3896
3897
0
  if ((cp[0] & 0x80) != 0 || isspace((unsigned char)cp[0]) ||
3898
0
      cp[0] == '-' || cp[0] == '+') {
3899
    /*
3900
     * Numbers don't begin with non-ASCII characters or white
3901
     * space and unsigned numbers don't have a sign.
3902
     */
3903
0
    *nump = 0;
3904
0
    if (endptr != NULL)
3905
0
      *endptr = (char *)cp;
3906
0
    return (EINVAL);
3907
0
  }
3908
3909
  /*
3910
   * Clear errno, so we can check whether it was set by strtoul().
3911
   */
3912
0
  errno = 0;
3913
0
  val = strtoul(cp, &end, 10);
3914
0
  if ((val == 0 && end == cp) || (endptr == NULL && *end != '\0')) {
3915
    /*
3916
     * Parsing error, including, if endptr is NULL, the
3917
     * string ending with a non-digit character.
3918
     */
3919
0
    *nump = 0;
3920
0
    if (endptr != NULL)
3921
0
      *endptr = end;
3922
0
    return (EINVAL);
3923
0
  }
3924
0
  if (val == ULONG_MAX && errno == ERANGE) {
3925
    /* Number is bigger than ULONG_MAX */
3926
0
    *nump = 0;
3927
0
    if (endptr != NULL)
3928
0
      *endptr = end;
3929
0
    return (ERANGE);
3930
0
  }
3931
0
  if (val > UINT_MAX) {
3932
    /* Number won't fit in an unsigned int */
3933
0
    *nump = 0;
3934
0
    if (endptr != NULL)
3935
0
      *endptr = end;
3936
0
    return (ERANGE);
3937
0
  }
3938
0
  if (endptr != NULL)
3939
0
    *endptr = end;
3940
0
  *nump = (unsigned) val;
3941
0
  return (0);
3942
0
}
3943
3944
int
3945
pcap_setfilter(pcap_t *p, struct bpf_program *fp)
3946
0
{
3947
0
  return (p->setfilter_op(p, fp));
3948
0
}
3949
3950
/*
3951
 * Set direction flag, which controls whether we accept only incoming
3952
 * packets, only outgoing packets, or both.
3953
 * Note that, depending on the platform, some or all direction arguments
3954
 * might not be supported.
3955
 */
3956
int
3957
pcap_setdirection(pcap_t *p, pcap_direction_t d)
3958
0
{
3959
0
  if (p->setdirection_op == NULL) {
3960
0
    snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
3961
0
        "Setting direction is not supported on this device");
3962
0
    return (-1);
3963
0
  } else {
3964
0
    switch (d) {
3965
3966
0
    case PCAP_D_IN:
3967
0
    case PCAP_D_OUT:
3968
0
    case PCAP_D_INOUT:
3969
      /*
3970
       * Valid direction.
3971
       */
3972
0
      return (p->setdirection_op(p, d));
3973
3974
0
    default:
3975
      /*
3976
       * Invalid direction.
3977
       */
3978
0
      snprintf(p->errbuf, sizeof(p->errbuf),
3979
0
          "Invalid direction");
3980
0
      return (-1);
3981
0
    }
3982
0
  }
3983
0
}
3984
3985
int
3986
pcap_stats(pcap_t *p, struct pcap_stat *ps)
3987
3.49k
{
3988
3.49k
  return (p->stats_op(p, ps));
3989
3.49k
}
3990
3991
#ifdef _WIN32
3992
struct pcap_stat *
3993
pcap_stats_ex(pcap_t *p, int *pcap_stat_size)
3994
{
3995
  return (p->stats_ex_op(p, pcap_stat_size));
3996
}
3997
3998
int
3999
pcap_setbuff(pcap_t *p, int dim)
4000
{
4001
  return (p->setbuff_op(p, dim));
4002
}
4003
4004
int
4005
pcap_setmode(pcap_t *p, int mode)
4006
{
4007
  return (p->setmode_op(p, mode));
4008
}
4009
4010
int
4011
pcap_setmintocopy(pcap_t *p, int size)
4012
{
4013
  return (p->setmintocopy_op(p, size));
4014
}
4015
4016
HANDLE
4017
pcap_getevent(pcap_t *p)
4018
{
4019
  return (p->getevent_op(p));
4020
}
4021
4022
int
4023
pcap_oid_get_request(pcap_t *p, bpf_u_int32 oid, void *data, size_t *lenp)
4024
{
4025
  return (p->oid_get_request_op(p, oid, data, lenp));
4026
}
4027
4028
int
4029
pcap_oid_set_request(pcap_t *p, bpf_u_int32 oid, const void *data, size_t *lenp)
4030
{
4031
  return (p->oid_set_request_op(p, oid, data, lenp));
4032
}
4033
4034
pcap_send_queue *
4035
pcap_sendqueue_alloc(u_int memsize)
4036
{
4037
  pcap_send_queue *tqueue;
4038
4039
  /* Allocate the queue */
4040
  tqueue = (pcap_send_queue *)malloc(sizeof(pcap_send_queue));
4041
  if (tqueue == NULL){
4042
    return (NULL);
4043
  }
4044
4045
  /* Allocate the buffer */
4046
  tqueue->buffer = (char *)malloc(memsize);
4047
  if (tqueue->buffer == NULL) {
4048
    free(tqueue);
4049
    return (NULL);
4050
  }
4051
4052
  tqueue->maxlen = memsize;
4053
  tqueue->len = 0;
4054
4055
  return (tqueue);
4056
}
4057
4058
void
4059
pcap_sendqueue_destroy(pcap_send_queue *queue)
4060
{
4061
  free(queue->buffer);
4062
  free(queue);
4063
}
4064
4065
int
4066
pcap_sendqueue_queue(pcap_send_queue *queue, const struct pcap_pkthdr *pkt_header, const u_char *pkt_data)
4067
{
4068
  if (queue->len + sizeof(struct pcap_pkthdr) + pkt_header->caplen > queue->maxlen){
4069
    return (-1);
4070
  }
4071
4072
  /* Copy the pcap_pkthdr header*/
4073
  memcpy(queue->buffer + queue->len, pkt_header, sizeof(struct pcap_pkthdr));
4074
  queue->len += sizeof(struct pcap_pkthdr);
4075
4076
  /* copy the packet */
4077
  memcpy(queue->buffer + queue->len, pkt_data, pkt_header->caplen);
4078
  queue->len += pkt_header->caplen;
4079
4080
  return (0);
4081
}
4082
4083
u_int
4084
pcap_sendqueue_transmit(pcap_t *p, pcap_send_queue *queue, int sync)
4085
{
4086
  return (p->sendqueue_transmit_op(p, queue, sync));
4087
}
4088
4089
int
4090
pcap_setuserbuffer(pcap_t *p, int size)
4091
{
4092
  return (p->setuserbuffer_op(p, size));
4093
}
4094
4095
int
4096
pcap_live_dump(pcap_t *p, char *filename, int maxsize, int maxpacks)
4097
{
4098
  return (p->live_dump_op(p, filename, maxsize, maxpacks));
4099
}
4100
4101
int
4102
pcap_live_dump_ended(pcap_t *p, int sync)
4103
{
4104
  return (p->live_dump_ended_op(p, sync));
4105
}
4106
4107
PAirpcapHandle
4108
pcap_get_airpcap_handle(pcap_t *p)
4109
{
4110
  (void)snprintf(p->errbuf, sizeof(p->errbuf),
4111
    "AirPcap devices are no longer supported");
4112
4113
  return (NULL);
4114
}
4115
#endif
4116
4117
/*
4118
 * On some platforms, we need to clean up promiscuous or monitor mode
4119
 * when we close a device - and we want that to happen even if the
4120
 * application just exits without explicitly closing devices.
4121
 * On those platforms, we need to register a "close all the pcaps"
4122
 * routine to be called when we exit, and need to maintain a list of
4123
 * pcaps that need to be closed to clean up modes.
4124
 *
4125
 * XXX - not thread-safe.
4126
 */
4127
4128
/*
4129
 * List of pcaps on which we've done something that needs to be
4130
 * cleaned up.
4131
 * If there are any such pcaps, we arrange to call "pcap_close_all()"
4132
 * when we exit, and have it close all of them.
4133
 */
4134
static struct pcap *pcaps_to_close;
4135
4136
/*
4137
 * TRUE if we've already called "atexit()" to cause "pcap_close_all()" to
4138
 * be called on exit.
4139
 */
4140
static int did_atexit;
4141
4142
static void
4143
pcap_close_all(void)
4144
0
{
4145
0
  struct pcap *handle;
4146
4147
0
  while ((handle = pcaps_to_close) != NULL) {
4148
0
    pcap_close(handle);
4149
4150
    /*
4151
     * If a pcap module adds a pcap_t to the "close all"
4152
     * list by calling pcapint_add_to_pcaps_to_close(), it
4153
     * must have a cleanup routine that removes it from the
4154
     * list, by calling pcapint_remove_from_pcaps_to_close(),
4155
     * and must make that cleanup routine the cleanup_op
4156
     * for the pcap_t.
4157
     *
4158
     * That means that, after pcap_close() - which calls
4159
     * the cleanup_op for the pcap_t - the pcap_t must
4160
     * have been removed from the list, so pcaps_to_close
4161
     * must not be equal to handle.
4162
     *
4163
     * We check for that, and abort if handle is still
4164
     * at the head of the list, to prevent infinite loops.
4165
     */
4166
0
    if (pcaps_to_close == handle)
4167
0
      abort();
4168
0
  }
4169
0
}
4170
4171
int
4172
pcapint_do_addexit(pcap_t *p)
4173
0
{
4174
  /*
4175
   * If we haven't already done so, arrange to have
4176
   * "pcap_close_all()" called when we exit.
4177
   */
4178
0
  if (!did_atexit) {
4179
0
    if (atexit(pcap_close_all) != 0) {
4180
      /*
4181
       * "atexit()" failed; let our caller know.
4182
       */
4183
0
      pcapint_strlcpy(p->errbuf, "atexit failed", PCAP_ERRBUF_SIZE);
4184
0
      return (0);
4185
0
    }
4186
0
    did_atexit = 1;
4187
0
  }
4188
0
  return (1);
4189
0
}
4190
4191
void
4192
pcapint_add_to_pcaps_to_close(pcap_t *p)
4193
0
{
4194
0
  p->next = pcaps_to_close;
4195
0
  pcaps_to_close = p;
4196
0
}
4197
4198
void
4199
pcapint_remove_from_pcaps_to_close(pcap_t *p)
4200
0
{
4201
0
  pcap_t *pc, *prevpc;
4202
4203
0
  for (pc = pcaps_to_close, prevpc = NULL; pc != NULL;
4204
0
      prevpc = pc, pc = pc->next) {
4205
0
    if (pc == p) {
4206
      /*
4207
       * Found it.  Remove it from the list.
4208
       */
4209
0
      if (prevpc == NULL) {
4210
        /*
4211
         * It was at the head of the list.
4212
         */
4213
0
        pcaps_to_close = pc->next;
4214
0
      } else {
4215
        /*
4216
         * It was in the middle of the list.
4217
         */
4218
0
        prevpc->next = pc->next;
4219
0
      }
4220
0
      break;
4221
0
    }
4222
0
  }
4223
0
}
4224
4225
void
4226
pcapint_breakloop_common(pcap_t *p)
4227
0
{
4228
0
  p->break_loop = 1;
4229
0
}
4230
4231
4232
void
4233
pcapint_cleanup_live_common(pcap_t *p)
4234
0
{
4235
  /*
4236
   * This must not free p->opt.device; that must only be done
4237
   * in pcap_close(), as this might be cleaning up after a
4238
   * failed pcap_activate(), in which case p->opt.device must
4239
   * still be valid, in case further actions are done on the
4240
   * not-yet-activated pcap_t.
4241
   *
4242
   * See GitHub issue #1615.
4243
   */
4244
0
  if (p->buffer != NULL) {
4245
0
    free(p->buffer);
4246
0
    p->buffer = NULL;
4247
0
  }
4248
0
  if (p->dlt_list != NULL) {
4249
0
    free(p->dlt_list);
4250
0
    p->dlt_list = NULL;
4251
0
    p->dlt_count = 0;
4252
0
  }
4253
0
  if (p->tstamp_type_list != NULL) {
4254
0
    free(p->tstamp_type_list);
4255
0
    p->tstamp_type_list = NULL;
4256
0
    p->tstamp_type_count = 0;
4257
0
  }
4258
0
  if (p->tstamp_precision_list != NULL) {
4259
0
    free(p->tstamp_precision_list);
4260
0
    p->tstamp_precision_list = NULL;
4261
0
    p->tstamp_precision_count = 0;
4262
0
  }
4263
0
  pcap_freecode(&p->fcode);
4264
0
#if !defined(_WIN32)
4265
0
  if (p->fd >= 0) {
4266
0
    close(p->fd);
4267
0
    p->fd = -1;
4268
0
  }
4269
0
  p->selectable_fd = -1;
4270
0
#endif
4271
0
}
4272
4273
/*
4274
 * API compatible with WinPcap's "send a packet" routine - returns -1
4275
 * on error, 0 otherwise.
4276
 *
4277
 * XXX - what if we get a short write?
4278
 */
4279
int
4280
pcap_sendpacket(pcap_t *p, const u_char *buf, int size)
4281
0
{
4282
0
  if (size <= 0) {
4283
0
    pcapint_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
4284
0
        errno, "The number of bytes to be sent must be positive");
4285
0
    return (PCAP_ERROR);
4286
0
  }
4287
4288
0
  if (p->inject_op(p, buf, size) == -1)
4289
0
    return (-1);
4290
0
  return (0);
4291
0
}
4292
4293
/*
4294
 * API compatible with OpenBSD's "send a packet" routine - returns -1 on
4295
 * error, number of bytes written otherwise.
4296
 */
4297
int
4298
pcap_inject(pcap_t *p, const void *buf, size_t size)
4299
0
{
4300
  /*
4301
   * We return the number of bytes written, so the number of
4302
   * bytes to write must fit in an int.
4303
   */
4304
0
  if (size > INT_MAX) {
4305
0
    pcapint_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
4306
0
        errno, "More than %d bytes cannot be injected", INT_MAX);
4307
0
    return (PCAP_ERROR);
4308
0
  }
4309
4310
0
  if (size == 0) {
4311
0
    pcapint_fmt_errmsg_for_errno(p->errbuf, PCAP_ERRBUF_SIZE,
4312
0
        errno, "The number of bytes to be injected must not be zero");
4313
0
    return (PCAP_ERROR);
4314
0
  }
4315
4316
0
  return (p->inject_op(p, buf, (int)size));
4317
0
}
4318
4319
void
4320
pcap_close(pcap_t *p)
4321
16.3k
{
4322
16.3k
  p->cleanup_op(p);
4323
4324
  /*
4325
   * Free information set by pcap_create() *after* calling
4326
   * the module's cleanup routine; that routine might have
4327
   * to use p->opt.device (see commit
4328
   * e333a6044f7d2d3225a6a22205b6b7c1e389945f).
4329
   */
4330
16.3k
  if (p->opt.device != NULL) {
4331
0
    free(p->opt.device);
4332
0
    p->opt.device = NULL;
4333
0
  }
4334
16.3k
  free(p);
4335
16.3k
}
4336
4337
/*
4338
 * Helpers for safely loading code at run time.
4339
 * Currently Windows-only.
4340
 */
4341
#ifdef _WIN32
4342
//
4343
// This wrapper around loadlibrary appends the system folder (usually
4344
// C:\Windows\System32) to the relative path of the DLL, so that the DLL
4345
// is always loaded from an absolute path (it's no longer possible to
4346
// load modules from the application folder).
4347
// This solves the DLL Hijacking issue discovered in August 2010:
4348
//
4349
// https://blog.rapid7.com/2010/08/23/exploiting-dll-hijacking-flaws/
4350
// https://blog.rapid7.com/2010/08/23/application-dll-load-hijacking/
4351
// (the purported Rapid7 blog post link in the first of those two links
4352
// is broken; the second of those links works.)
4353
//
4354
// If any links there are broken from all the content shuffling Rapid&
4355
// did, see archived versions of the posts at their original homes, at
4356
//
4357
// https://web.archive.org/web/20110122175058/http://blog.metasploit.com/2010/08/exploiting-dll-hijacking-flaws.html
4358
// https://web.archive.org/web/20100828112111/http://blog.rapid7.com/?p=5325
4359
//
4360
pcap_code_handle_t
4361
pcapint_load_code(const char *name)
4362
{
4363
  /*
4364
   * XXX - should this work in UTF-16LE rather than in the local
4365
   * ANSI code page?
4366
   */
4367
  CHAR path[MAX_PATH];
4368
  CHAR fullFileName[MAX_PATH];
4369
  UINT res;
4370
  HMODULE hModule = NULL;
4371
4372
  do
4373
  {
4374
    res = GetSystemDirectoryA(path, MAX_PATH);
4375
4376
    if (res == 0) {
4377
      //
4378
      // some bad failure occurred;
4379
      //
4380
      break;
4381
    }
4382
4383
    if (res > MAX_PATH) {
4384
      //
4385
      // the buffer was not big enough
4386
      //
4387
      SetLastError(ERROR_INSUFFICIENT_BUFFER);
4388
      break;
4389
    }
4390
4391
    if (res + 1 + strlen(name) + 1 < MAX_PATH) {
4392
      memcpy(fullFileName, path, res * sizeof(TCHAR));
4393
      fullFileName[res] = '\\';
4394
      memcpy(&fullFileName[res + 1], name, (strlen(name) + 1) * sizeof(TCHAR));
4395
4396
      hModule = LoadLibraryA(fullFileName);
4397
    } else
4398
      SetLastError(ERROR_INSUFFICIENT_BUFFER);
4399
4400
  } while(FALSE);
4401
4402
  return hModule;
4403
}
4404
4405
/*
4406
 * Casting from FARPROC, which is the type of the return value of
4407
 * GetProcAddress(), to a function pointer gets a C4191 warning
4408
 * from Visual Studio 2022.
4409
 *
4410
 * Casting FARPROC to void * and returning the result, and then
4411
 * casting the void * to a function pointer, doesn't get the
4412
 * same warning.
4413
 *
4414
 * Given that, and given that the equivalent UN*X API, dlsym(),
4415
 * returns a void *, we have pcapint_find_function() return
4416
 * a void *.
4417
 */
4418
void *
4419
pcapint_find_function(pcap_code_handle_t code, const char *func)
4420
{
4421
  return ((void *)GetProcAddress(code, func));
4422
}
4423
#endif
4424
4425
/*
4426
 * Given a BPF program, a pcap_pkthdr structure for a packet, and the raw
4427
 * data for the packet, check whether the packet passes the filter.
4428
 * Returns the return value of the filter program, which will be zero if
4429
 * the packet doesn't pass and non-zero if the packet does pass.
4430
 */
4431
int
4432
pcap_offline_filter(const struct bpf_program *fp, const struct pcap_pkthdr *h,
4433
    const u_char *pkt)
4434
31.7k
{
4435
31.7k
  const struct bpf_insn *fcode = fp->bf_insns;
4436
4437
31.7k
  if (fcode != NULL)
4438
31.7k
    return (pcapint_filter(fcode, pkt, h->len, h->caplen));
4439
0
  else
4440
0
    return (0);
4441
31.7k
}
4442
4443
static int
4444
pcap_can_set_rfmon_dead(pcap_t *p)
4445
0
{
4446
0
  snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4447
0
      "Rfmon mode doesn't apply on a pcap_open_dead pcap_t");
4448
0
  return (PCAP_ERROR);
4449
0
}
4450
4451
static int
4452
pcap_read_dead(pcap_t *p, int cnt _U_, pcap_handler callback _U_,
4453
    u_char *user _U_)
4454
0
{
4455
0
  snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4456
0
      "Packets aren't available from a pcap_open_dead pcap_t");
4457
0
  return (-1);
4458
0
}
4459
4460
static void
4461
pcap_breakloop_dead(pcap_t *p _U_)
4462
0
{
4463
  /*
4464
   * A "dead" pcap_t is just a placeholder to use in order to
4465
   * compile a filter to BPF code or to open a savefile for
4466
   * writing.  It doesn't support any operations, including
4467
   * capturing or reading packets, so there will never be a
4468
   * get-packets loop in progress to break out *of*.
4469
   *
4470
   * As such, this routine doesn't need to do anything.
4471
   */
4472
0
}
4473
4474
static int
4475
pcap_inject_dead(pcap_t *p, const void *buf _U_, int size _U_)
4476
0
{
4477
0
  snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4478
0
      "Packets can't be sent on a pcap_open_dead pcap_t");
4479
0
  return (-1);
4480
0
}
4481
4482
static int
4483
pcap_setfilter_dead(pcap_t *p, struct bpf_program *fp _U_)
4484
0
{
4485
0
  snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4486
0
      "A filter cannot be set on a pcap_open_dead pcap_t");
4487
0
  return (-1);
4488
0
}
4489
4490
static int
4491
pcap_setdirection_dead(pcap_t *p, pcap_direction_t d _U_)
4492
0
{
4493
0
  snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4494
0
      "The packet direction cannot be set on a pcap_open_dead pcap_t");
4495
0
  return (-1);
4496
0
}
4497
4498
static int
4499
pcap_set_datalink_dead(pcap_t *p, int dlt _U_)
4500
0
{
4501
0
  snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4502
0
      "The link-layer header type cannot be set on a pcap_open_dead pcap_t");
4503
0
  return (-1);
4504
0
}
4505
4506
static int
4507
pcap_getnonblock_dead(pcap_t *p)
4508
0
{
4509
0
  snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4510
0
      "A pcap_open_dead pcap_t does not have a non-blocking mode setting");
4511
0
  return (-1);
4512
0
}
4513
4514
static int
4515
pcap_setnonblock_dead(pcap_t *p, int nonblock _U_)
4516
0
{
4517
0
  snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4518
0
      "A pcap_open_dead pcap_t does not have a non-blocking mode setting");
4519
0
  return (-1);
4520
0
}
4521
4522
static int
4523
pcap_stats_dead(pcap_t *p, struct pcap_stat *ps _U_)
4524
0
{
4525
0
  snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4526
0
      "Statistics aren't available from a pcap_open_dead pcap_t");
4527
0
  return (-1);
4528
0
}
4529
4530
#ifdef _WIN32
4531
static struct pcap_stat *
4532
pcap_stats_ex_dead(pcap_t *p, int *pcap_stat_size _U_)
4533
{
4534
  snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4535
      "Statistics aren't available from a pcap_open_dead pcap_t");
4536
  return (NULL);
4537
}
4538
4539
static int
4540
pcap_setbuff_dead(pcap_t *p, int dim _U_)
4541
{
4542
  snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4543
      "The kernel buffer size cannot be set on a pcap_open_dead pcap_t");
4544
  return (-1);
4545
}
4546
4547
static int
4548
pcap_setmode_dead(pcap_t *p, int mode _U_)
4549
{
4550
  snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4551
      "impossible to set mode on a pcap_open_dead pcap_t");
4552
  return (-1);
4553
}
4554
4555
static int
4556
pcap_setmintocopy_dead(pcap_t *p, int size _U_)
4557
{
4558
  snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4559
      "The mintocopy parameter cannot be set on a pcap_open_dead pcap_t");
4560
  return (-1);
4561
}
4562
4563
static HANDLE
4564
pcap_getevent_dead(pcap_t *p)
4565
{
4566
  snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4567
      "A pcap_open_dead pcap_t has no event handle");
4568
  return (INVALID_HANDLE_VALUE);
4569
}
4570
4571
static int
4572
pcap_oid_get_request_dead(pcap_t *p, bpf_u_int32 oid _U_, void *data _U_,
4573
    size_t *lenp _U_)
4574
{
4575
  snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4576
      "An OID get request cannot be performed on a pcap_open_dead pcap_t");
4577
  return (PCAP_ERROR);
4578
}
4579
4580
static int
4581
pcap_oid_set_request_dead(pcap_t *p, bpf_u_int32 oid _U_, const void *data _U_,
4582
    size_t *lenp _U_)
4583
{
4584
  snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4585
      "An OID set request cannot be performed on a pcap_open_dead pcap_t");
4586
  return (PCAP_ERROR);
4587
}
4588
4589
static u_int
4590
pcap_sendqueue_transmit_dead(pcap_t *p, pcap_send_queue *queue _U_,
4591
    int sync _U_)
4592
{
4593
  snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4594
      "Packets cannot be transmitted on a pcap_open_dead pcap_t");
4595
  return (0);
4596
}
4597
4598
static int
4599
pcap_setuserbuffer_dead(pcap_t *p, int size _U_)
4600
{
4601
  snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4602
      "The user buffer cannot be set on a pcap_open_dead pcap_t");
4603
  return (-1);
4604
}
4605
4606
static int
4607
pcap_live_dump_dead(pcap_t *p, char *filename _U_, int maxsize _U_,
4608
    int maxpacks _U_)
4609
{
4610
  snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4611
      "Live packet dumping cannot be performed on a pcap_open_dead pcap_t");
4612
  return (-1);
4613
}
4614
4615
static int
4616
pcap_live_dump_ended_dead(pcap_t *p, int sync _U_)
4617
{
4618
  snprintf(p->errbuf, PCAP_ERRBUF_SIZE,
4619
      "Live packet dumping cannot be performed on a pcap_open_dead pcap_t");
4620
  return (-1);
4621
}
4622
#endif /* _WIN32 */
4623
4624
static void
4625
pcap_cleanup_dead(pcap_t *p _U_)
4626
0
{
4627
  /* Nothing to do. */
4628
0
}
4629
4630
pcap_t *
4631
pcap_open_dead_with_tstamp_precision(int linktype, int snaplen, u_int precision)
4632
0
{
4633
0
  pcap_t *p;
4634
4635
0
  switch (precision) {
4636
4637
0
  case PCAP_TSTAMP_PRECISION_MICRO:
4638
0
  case PCAP_TSTAMP_PRECISION_NANO:
4639
0
    break;
4640
4641
0
  default:
4642
    /*
4643
     * This doesn't really matter, but we don't have any way
4644
     * to report particular errors, so the only failure we
4645
     * should have is a memory allocation failure.  Just
4646
     * pick microsecond precision.
4647
     */
4648
0
    precision = PCAP_TSTAMP_PRECISION_MICRO;
4649
0
    break;
4650
0
  }
4651
0
  p = malloc(sizeof(*p));
4652
0
  if (p == NULL)
4653
0
    return NULL;
4654
0
  memset (p, 0, sizeof(*p));
4655
0
  p->snapshot = snaplen;
4656
0
  p->linktype = linktype;
4657
0
  p->opt.tstamp_precision = precision;
4658
0
  p->can_set_rfmon_op = pcap_can_set_rfmon_dead;
4659
0
  p->read_op = pcap_read_dead;
4660
0
  p->inject_op = pcap_inject_dead;
4661
0
  p->setfilter_op = pcap_setfilter_dead;
4662
0
  p->setdirection_op = pcap_setdirection_dead;
4663
0
  p->set_datalink_op = pcap_set_datalink_dead;
4664
0
  p->getnonblock_op = pcap_getnonblock_dead;
4665
0
  p->setnonblock_op = pcap_setnonblock_dead;
4666
0
  p->stats_op = pcap_stats_dead;
4667
#ifdef _WIN32
4668
  p->stats_ex_op = pcap_stats_ex_dead;
4669
  p->setbuff_op = pcap_setbuff_dead;
4670
  p->setmode_op = pcap_setmode_dead;
4671
  p->setmintocopy_op = pcap_setmintocopy_dead;
4672
  p->getevent_op = pcap_getevent_dead;
4673
  p->oid_get_request_op = pcap_oid_get_request_dead;
4674
  p->oid_set_request_op = pcap_oid_set_request_dead;
4675
  p->sendqueue_transmit_op = pcap_sendqueue_transmit_dead;
4676
  p->setuserbuffer_op = pcap_setuserbuffer_dead;
4677
  p->live_dump_op = pcap_live_dump_dead;
4678
  p->live_dump_ended_op = pcap_live_dump_ended_dead;
4679
#endif
4680
0
  p->breakloop_op = pcap_breakloop_dead;
4681
0
  p->cleanup_op = pcap_cleanup_dead;
4682
4683
  /*
4684
   * A "dead" pcap_t never requires special BPF code generation.
4685
   */
4686
0
  p->bpf_codegen_flags = 0;
4687
4688
0
  p->activated = 1;
4689
0
  return (p);
4690
0
}
4691
4692
pcap_t *
4693
pcap_open_dead(int linktype, int snaplen)
4694
0
{
4695
0
  return (pcap_open_dead_with_tstamp_precision(linktype, snaplen,
4696
0
      PCAP_TSTAMP_PRECISION_MICRO));
4697
0
}
4698
4699
#ifdef YYDEBUG
4700
/*
4701
 * Set the internal "debug printout" flag for the filter expression parser.
4702
 * The code to print that stuff is present only if YYDEBUG is defined, so
4703
 * the flag, and the routine to set it, are defined only if YYDEBUG is
4704
 * defined.
4705
 *
4706
 * This is intended for libpcap developers, not for general use.
4707
 * If you want to set these in a program, you'll have to declare this
4708
 * routine yourself, with the appropriate DLL import attribute on Windows;
4709
 * it's not declared in any header file, and won't be declared in any
4710
 * header file provided by libpcap.
4711
 */
4712
PCAP_API void pcap_set_parser_debug(int value);
4713
4714
PCAP_API_DEF void
4715
pcap_set_parser_debug(int value)
4716
{
4717
  pcap_debug = value;
4718
}
4719
#endif