Coverage Report

Created: 2026-08-14 06:29

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