Coverage Report

Created: 2025-11-24 06:14

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