Coverage Report

Created: 2026-10-07 06:40

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