Coverage Report

Created: 2026-09-28 08:09

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