Coverage Report

Created: 2026-11-12 06:07

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