Coverage Report

Created: 2026-04-12 06:38

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