Coverage Report

Created: 2026-10-17 07:12

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