xref: /openbsd-src/lib/libpcap/pcap.c (revision 50b7afb2c2c0993b0894d4e34bf857cb13ed9c80)
1 /*	$OpenBSD: pcap.c,v 1.15 2014/06/26 04:03:33 lteo Exp $	*/
2 
3 /*
4  * Copyright (c) 1993, 1994, 1995, 1996, 1997, 1998
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *	This product includes software developed by the Computer Systems
18  *	Engineering Group at Lawrence Berkeley Laboratory.
19  * 4. Neither the name of the University nor of the Laboratory may be used
20  *    to endorse or promote products derived from this software without
21  *    specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  */
35 
36 #include <sys/types.h>
37 
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <unistd.h>
42 #include <errno.h>
43 #include <fcntl.h>
44 
45 #ifdef HAVE_OS_PROTO_H
46 #include "os-proto.h"
47 #endif
48 
49 #include "pcap-int.h"
50 
51 static const char pcap_version_string[] = "OpenBSD libpcap";
52 
53 int
54 pcap_dispatch(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
55 {
56 
57 	if (p->sf.rfile != NULL)
58 		return (pcap_offline_read(p, cnt, callback, user));
59 	return (pcap_read(p, cnt, callback, user));
60 }
61 
62 int
63 pcap_loop(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
64 {
65 	register int n;
66 
67 	for (;;) {
68 		if (p->sf.rfile != NULL)
69 			n = pcap_offline_read(p, cnt, callback, user);
70 		else {
71 			/*
72 			 * XXX keep reading until we get something
73 			 * (or an error occurs)
74 			 */
75 			do {
76 				n = pcap_read(p, cnt, callback, user);
77 			} while (n == 0);
78 		}
79 		if (n <= 0)
80 			return (n);
81 		if (cnt > 0) {
82 			cnt -= n;
83 			if (cnt <= 0)
84 				return (0);
85 		}
86 	}
87 }
88 
89 struct singleton {
90 	struct pcap_pkthdr *hdr;
91 	const u_char *pkt;
92 };
93 
94 
95 static void
96 pcap_oneshot(u_char *userData, const struct pcap_pkthdr *h, const u_char *pkt)
97 {
98 	struct singleton *sp = (struct singleton *)userData;
99 	*sp->hdr = *h;
100 	sp->pkt = pkt;
101 }
102 
103 const u_char *
104 pcap_next(pcap_t *p, struct pcap_pkthdr *h)
105 {
106 	struct singleton s;
107 
108 	s.hdr = h;
109 	if (pcap_dispatch(p, 1, pcap_oneshot, (u_char*)&s) <= 0)
110 		return (0);
111 	return (s.pkt);
112 }
113 
114 struct pkt_for_fakecallback {
115 	struct pcap_pkthdr *hdr;
116 	const u_char **pkt;
117 };
118 
119 static void
120 pcap_fakecallback(u_char *userData, const struct pcap_pkthdr *h,
121     const u_char *pkt)
122 {
123 	struct pkt_for_fakecallback *sp = (struct pkt_for_fakecallback *)userData;
124 
125 	*sp->hdr = *h;
126 	*sp->pkt = pkt;
127 }
128 
129 int
130 pcap_next_ex(pcap_t *p, struct pcap_pkthdr **pkt_header,
131     const u_char **pkt_data)
132 {
133 	struct pkt_for_fakecallback s;
134 
135 	s.hdr = &p->pcap_header;
136 	s.pkt = pkt_data;
137 
138 	/* Saves a pointer to the packet headers */
139 	*pkt_header= &p->pcap_header;
140 
141 	if (p->sf.rfile != NULL) {
142 		int status;
143 
144 		/* We are on an offline capture */
145 		status = pcap_offline_read(p, 1, pcap_fakecallback,
146 		    (u_char *)&s);
147 
148 		/*
149 		 * Return codes for pcap_offline_read() are:
150 		 *   -  0: EOF
151 		 *   - -1: error
152 		 *   - >1: OK
153 		 * The first one ('0') conflicts with the return code of
154 		 * 0 from pcap_read() meaning "no packets arrived before
155 		 * the timeout expired", so we map it to -2 so you can
156 		 * distinguish between an EOF from a savefile and a
157 		 * "no packets arrived before the timeout expired, try
158 		 * again" from a live capture.
159 		 */
160 		if (status == 0)
161 			return (-2);
162 		else
163 			return (status);
164 	}
165 
166 	/*
167 	 * Return codes for pcap_read() are:
168 	 *   -  0: timeout
169 	 *   - -1: error
170 	 *   - -2: loop was broken out of with pcap_breakloop()
171 	 *   - >1: OK
172 	 * The first one ('0') conflicts with the return code of 0 from
173 	 * pcap_offline_read() meaning "end of file".
174 	*/
175 	return (pcap_read(p, 1, pcap_fakecallback, (u_char *)&s));
176 }
177 
178 int
179 pcap_check_activated(pcap_t *p)
180 {
181 	if (p->activated) {
182 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "can't perform "
183 			" operation on activated capture");
184 		return -1;
185 	}
186 	return 0;
187 }
188 
189 int
190 pcap_set_snaplen(pcap_t *p, int snaplen)
191 {
192 	if (pcap_check_activated(p))
193 		return PCAP_ERROR_ACTIVATED;
194 	p->snapshot = snaplen;
195 	return 0;
196 }
197 
198 int
199 pcap_set_promisc(pcap_t *p, int promisc)
200 {
201 	if (pcap_check_activated(p))
202 		return PCAP_ERROR_ACTIVATED;
203 	p->opt.promisc = promisc;
204 	return 0;
205 }
206 
207 int
208 pcap_set_rfmon(pcap_t *p, int rfmon)
209 {
210 	if (pcap_check_activated(p))
211 		return PCAP_ERROR_ACTIVATED;
212 	p->opt.rfmon = rfmon;
213 	return 0;
214 }
215 
216 int
217 pcap_set_timeout(pcap_t *p, int timeout_ms)
218 {
219 	if (pcap_check_activated(p))
220 		return PCAP_ERROR_ACTIVATED;
221 	p->md.timeout = timeout_ms;
222 	return 0;
223 }
224 
225 int
226 pcap_set_buffer_size(pcap_t *p, int buffer_size)
227 {
228 	if (pcap_check_activated(p))
229 		return PCAP_ERROR_ACTIVATED;
230 	p->opt.buffer_size = buffer_size;
231 	return 0;
232 }
233 
234 /*
235  * Force the loop in "pcap_read()" or "pcap_read_offline()" to terminate.
236  */
237 void
238 pcap_breakloop(pcap_t *p)
239 {
240 	p->break_loop = 1;
241 }
242 
243 int
244 pcap_datalink(pcap_t *p)
245 {
246 	return (p->linktype);
247 }
248 
249 int
250 pcap_list_datalinks(pcap_t *p, int **dlt_buffer)
251 {
252 	if (p->dlt_count == 0) {
253 		/*
254 		 * We couldn't fetch the list of DLTs, which means
255 		 * this platform doesn't support changing the
256 		 * DLT for an interface.  Return a list of DLTs
257 		 * containing only the DLT this device supports.
258 		 */
259 		*dlt_buffer = (int*)malloc(sizeof(**dlt_buffer));
260 		if (*dlt_buffer == NULL) {
261 			(void)snprintf(p->errbuf, sizeof(p->errbuf),
262 			    "malloc: %s", pcap_strerror(errno));
263 			return (-1);
264 		}
265 		**dlt_buffer = p->linktype;
266 		return (1);
267 	} else {
268 		*dlt_buffer = reallocarray(NULL, sizeof(**dlt_buffer),
269 		    p->dlt_count);
270 		if (*dlt_buffer == NULL) {
271 			(void)snprintf(p->errbuf, sizeof(p->errbuf),
272 			    "malloc: %s", pcap_strerror(errno));
273 			return (-1);
274 		}
275 		(void)memcpy(*dlt_buffer, p->dlt_list,
276 		    sizeof(**dlt_buffer) * p->dlt_count);
277 		return (p->dlt_count);
278 	}
279 }
280 
281 struct dlt_choice {
282 	const char *name;
283 	const char *description;
284 	int	dlt;
285 };
286 
287 static struct dlt_choice dlts[] = {
288 #define DLT_CHOICE(code, description) { #code, description, code }
289 DLT_CHOICE(DLT_NULL, "no link-layer encapsulation"),
290 DLT_CHOICE(DLT_EN10MB, "Ethernet (10Mb)"),
291 DLT_CHOICE(DLT_EN3MB, "Experimental Ethernet (3Mb)"),
292 DLT_CHOICE(DLT_AX25, "Amateur Radio AX.25"),
293 DLT_CHOICE(DLT_PRONET, "Proteon ProNET Token Ring"),
294 DLT_CHOICE(DLT_CHAOS, "Chaos"),
295 DLT_CHOICE(DLT_IEEE802, "IEEE 802 Networks"),
296 DLT_CHOICE(DLT_ARCNET, "ARCNET"),
297 DLT_CHOICE(DLT_SLIP, "Serial Line IP"),
298 DLT_CHOICE(DLT_PPP, "Point-to-point Protocol"),
299 DLT_CHOICE(DLT_FDDI, "FDDI"),
300 DLT_CHOICE(DLT_ATM_RFC1483, "LLC/SNAP encapsulated atm"),
301 DLT_CHOICE(DLT_LOOP, "loopback type (af header)"),
302 DLT_CHOICE(DLT_ENC, "IPSEC enc type (af header, spi, flags)"),
303 DLT_CHOICE(DLT_RAW, "raw IP"),
304 DLT_CHOICE(DLT_SLIP_BSDOS, "BSD/OS Serial Line IP"),
305 DLT_CHOICE(DLT_PPP_BSDOS, "BSD/OS Point-to-point Protocol"),
306 DLT_CHOICE(DLT_PFSYNC, "Packet filter state syncing"),
307 DLT_CHOICE(DLT_PPP_ETHER, "PPP over Ethernet; session only w/o ether header"),
308 DLT_CHOICE(DLT_IEEE802_11, "IEEE 802.11 wireless"),
309 DLT_CHOICE(DLT_PFLOG, "Packet filter logging, by pcap people"),
310 DLT_CHOICE(DLT_IEEE802_11_RADIO, "IEEE 802.11 plus WLAN header"),
311 #undef DLT_CHOICE
312 	{ NULL, NULL, -1}
313 };
314 
315 int
316 pcap_datalink_name_to_val(const char *name)
317 {
318 	int i;
319 
320 	for (i = 0; dlts[i].name != NULL; i++) {
321 		/* Skip leading "DLT_" */
322 		if (strcasecmp(dlts[i].name + 4, name) == 0)
323 			return (dlts[i].dlt);
324 	}
325 	return (-1);
326 }
327 
328 const char *
329 pcap_datalink_val_to_name(int dlt)
330 {
331 	int i;
332 
333 	for (i = 0; dlts[i].name != NULL; i++) {
334 		if (dlts[i].dlt == dlt)
335 			return (dlts[i].name + 4); /* Skip leading "DLT_" */
336 	}
337 	return (NULL);
338 }
339 
340 const char *
341 pcap_datalink_val_to_description(int dlt)
342 {
343 	int i;
344 
345 	for (i = 0; dlts[i].name != NULL; i++) {
346 		if (dlts[i].dlt == dlt)
347 			return (dlts[i].description);
348 	}
349 	return (NULL);
350 }
351 
352 int
353 pcap_snapshot(pcap_t *p)
354 {
355 	return (p->snapshot);
356 }
357 
358 int
359 pcap_is_swapped(pcap_t *p)
360 {
361 	return (p->sf.swapped);
362 }
363 
364 int
365 pcap_major_version(pcap_t *p)
366 {
367 	return (p->sf.version_major);
368 }
369 
370 int
371 pcap_minor_version(pcap_t *p)
372 {
373 	return (p->sf.version_minor);
374 }
375 
376 FILE *
377 pcap_file(pcap_t *p)
378 {
379 	return (p->sf.rfile);
380 }
381 
382 int
383 pcap_fileno(pcap_t *p)
384 {
385 	return (p->fd);
386 }
387 
388 void
389 pcap_perror(pcap_t *p, char *prefix)
390 {
391 	fprintf(stderr, "%s: %s\n", prefix, p->errbuf);
392 }
393 
394 int
395 pcap_get_selectable_fd(pcap_t *p)
396 {
397 	return (p->fd);
398 }
399 
400 char *
401 pcap_geterr(pcap_t *p)
402 {
403 	return (p->errbuf);
404 }
405 
406 int
407 pcap_getnonblock(pcap_t *p, char *errbuf)
408 {
409 	int fdflags;
410 
411 	fdflags = fcntl(p->fd, F_GETFL, 0);
412 	if (fdflags == -1) {
413 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "F_GETFL: %s",
414 		    pcap_strerror(errno));
415 		return (-1);
416 	}
417 	if (fdflags & O_NONBLOCK)
418 		return (1);
419 	else
420 		return (0);
421 }
422 
423 int
424 pcap_setnonblock(pcap_t *p, int nonblock, char *errbuf)
425 {
426 	int fdflags;
427 
428 	fdflags = fcntl(p->fd, F_GETFL, 0);
429 	if (fdflags == -1) {
430 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "F_GETFL: %s",
431 		    pcap_strerror(errno));
432 		return (-1);
433 	}
434 	if (nonblock)
435 		fdflags |= O_NONBLOCK;
436 	else
437 		fdflags &= ~O_NONBLOCK;
438 	if (fcntl(p->fd, F_SETFL, fdflags) == -1) {
439 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "F_SETFL: %s",
440 		    pcap_strerror(errno));
441 		return (-1);
442 	}
443 	return (0);
444 }
445 
446 /*
447  * Generate error strings for PCAP_ERROR_ and PCAP_WARNING_ values.
448  */
449 const char *
450 pcap_statustostr(int errnum)
451 {
452 	static char ebuf[15+10+1];
453 
454 	switch (errnum) {
455 
456 	case PCAP_WARNING:
457 		return("Generic warning");
458 
459 	case PCAP_WARNING_TSTAMP_TYPE_NOTSUP:
460 		return ("That type of time stamp is not supported by that device");
461 
462 	case PCAP_WARNING_PROMISC_NOTSUP:
463 		return ("That device doesn't support promiscuous mode");
464 
465 	case PCAP_ERROR:
466 		return("Generic error");
467 
468 	case PCAP_ERROR_BREAK:
469 		return("Loop terminated by pcap_breakloop");
470 
471 	case PCAP_ERROR_NOT_ACTIVATED:
472 		return("The pcap_t has not been activated");
473 
474 	case PCAP_ERROR_ACTIVATED:
475 		return ("The setting can't be changed after the pcap_t is activated");
476 
477 	case PCAP_ERROR_NO_SUCH_DEVICE:
478 		return ("No such device exists");
479 
480 	case PCAP_ERROR_RFMON_NOTSUP:
481 		return ("That device doesn't support monitor mode");
482 
483 	case PCAP_ERROR_NOT_RFMON:
484 		return ("That operation is supported only in monitor mode");
485 
486 	case PCAP_ERROR_PERM_DENIED:
487 		return ("You don't have permission to capture on that device");
488 
489 	case PCAP_ERROR_IFACE_NOT_UP:
490 		return ("That device is not up");
491 
492 	case PCAP_ERROR_CANTSET_TSTAMP_TYPE:
493 		return ("That device doesn't support setting the time stamp type");
494 
495 	case PCAP_ERROR_PROMISC_PERM_DENIED:
496 		return ("You don't have permission to capture in promiscuous mode on that device");
497 	}
498 	(void)snprintf(ebuf, sizeof ebuf, "Unknown error: %d", errnum);
499 	return(ebuf);
500 }
501 
502 /*
503  * Not all systems have strerror().
504  */
505 char *
506 pcap_strerror(int errnum)
507 {
508 #ifdef HAVE_STRERROR
509 	return (strerror(errnum));
510 #else
511 	extern int sys_nerr;
512 	extern const char *const sys_errlist[];
513 	static char ebuf[20];
514 
515 	if ((unsigned int)errnum < sys_nerr)
516 		return ((char *)sys_errlist[errnum]);
517 	(void)snprintf(ebuf, sizeof ebuf, "Unknown error: %d", errnum);
518 	return(ebuf);
519 #endif
520 }
521 
522 /*
523  * On some platforms, we need to clean up promiscuous or monitor mode
524  * when we close a device - and we want that to happen even if the
525  * application just exits without explicitl closing devices.
526  * On those platforms, we need to register a "close all the pcaps"
527  * routine to be called when we exit, and need to maintain a list of
528  * pcaps that need to be closed to clean up modes.
529  *
530  * XXX - not thread-safe.
531  */
532 
533 /*
534  * List of pcaps on which we've done something that needs to be
535  * cleaned up.
536  * If there are any such pcaps, we arrange to call "pcap_close_all()"
537  * when we exit, and have it close all of them.
538  */
539 static struct pcap *pcaps_to_close;
540 
541 /*
542  * TRUE if we've already called "atexit()" to cause "pcap_close_all()" to
543  * be called on exit.
544  */
545 static int did_atexit;
546 
547 static void
548 pcap_close_all(void)
549 {
550 	struct pcap *handle;
551 
552 	while ((handle = pcaps_to_close) != NULL)
553 		pcap_close(handle);
554 }
555 
556 int
557 pcap_do_addexit(pcap_t *p)
558 {
559 	/*
560 	 * If we haven't already done so, arrange to have
561 	 * "pcap_close_all()" called when we exit.
562 	 */
563 	if (!did_atexit) {
564 		if (atexit(pcap_close_all) == -1) {
565 			/*
566 			 * "atexit()" failed; let our caller know.
567 			 */
568 			(void)strlcpy(p->errbuf, "atexit failed",
569 			    PCAP_ERRBUF_SIZE);
570 			return (0);
571 		}
572 		did_atexit = 1;
573 	}
574 	return (1);
575 }
576 
577 void
578 pcap_add_to_pcaps_to_close(pcap_t *p)
579 {
580 	p->md.next = pcaps_to_close;
581 	pcaps_to_close = p;
582 }
583 
584 void
585 pcap_remove_from_pcaps_to_close(pcap_t *p)
586 {
587 	pcap_t *pc, *prevpc;
588 
589 	for (pc = pcaps_to_close, prevpc = NULL; pc != NULL;
590 	    prevpc = pc, pc = pc->md.next) {
591 		if (pc == p) {
592 			/*
593 			 * Found it.  Remove it from the list.
594 			 */
595 			if (prevpc == NULL) {
596 				/*
597 				 * It was at the head of the list.
598 				 */
599 				pcaps_to_close = pc->md.next;
600 			} else {
601 				/*
602 				 * It was in the middle of the list.
603 				 */
604 				prevpc->md.next = pc->md.next;
605 			}
606 			break;
607 		}
608 	}
609 }
610 
611 pcap_t *
612 pcap_open_dead(int linktype, int snaplen)
613 {
614 	pcap_t *p;
615 
616 	p = calloc(1, sizeof(*p));
617 	if (p == NULL)
618 		return NULL;
619 	p->snapshot = snaplen;
620 	p->linktype = linktype;
621 	p->fd = -1;
622 	return p;
623 }
624 
625 const char *
626 pcap_lib_version(void)
627 {
628 	return (pcap_version_string);
629 }
630 
631