Coverage Report

Created: 2024-02-25 06:24

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