xref: /openbsd-src/lib/libpcap/pcap.c (revision 4c1e55dc91edd6e69ccc60ce855900fbc12cf34f)
1 /*	$OpenBSD: pcap.c,v 1.13 2012/05/25 01:58:08 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 = (int*)calloc(sizeof(**dlt_buffer), p->dlt_count);
269 		if (*dlt_buffer == NULL) {
270 			(void)snprintf(p->errbuf, sizeof(p->errbuf),
271 			    "malloc: %s", pcap_strerror(errno));
272 			return (-1);
273 		}
274 		(void)memcpy(*dlt_buffer, p->dlt_list,
275 		    sizeof(**dlt_buffer) * p->dlt_count);
276 		return (p->dlt_count);
277 	}
278 }
279 
280 struct dlt_choice {
281 	const char *name;
282 	const char *description;
283 	int	dlt;
284 };
285 
286 static struct dlt_choice dlts[] = {
287 #define DLT_CHOICE(code, description) { #code, description, code }
288 DLT_CHOICE(DLT_NULL, "no link-layer encapsulation"),
289 DLT_CHOICE(DLT_EN10MB, "Ethernet (10Mb)"),
290 DLT_CHOICE(DLT_EN3MB, "Experimental Ethernet (3Mb)"),
291 DLT_CHOICE(DLT_AX25, "Amateur Radio AX.25"),
292 DLT_CHOICE(DLT_PRONET, "Proteon ProNET Token Ring"),
293 DLT_CHOICE(DLT_CHAOS, "Chaos"),
294 DLT_CHOICE(DLT_IEEE802, "IEEE 802 Networks"),
295 DLT_CHOICE(DLT_ARCNET, "ARCNET"),
296 DLT_CHOICE(DLT_SLIP, "Serial Line IP"),
297 DLT_CHOICE(DLT_PPP, "Point-to-point Protocol"),
298 DLT_CHOICE(DLT_FDDI, "FDDI"),
299 DLT_CHOICE(DLT_ATM_RFC1483, "LLC/SNAP encapsulated atm"),
300 DLT_CHOICE(DLT_LOOP, "loopback type (af header)"),
301 DLT_CHOICE(DLT_ENC, "IPSEC enc type (af header, spi, flags)"),
302 DLT_CHOICE(DLT_RAW, "raw IP"),
303 DLT_CHOICE(DLT_SLIP_BSDOS, "BSD/OS Serial Line IP"),
304 DLT_CHOICE(DLT_PPP_BSDOS, "BSD/OS Point-to-point Protocol"),
305 DLT_CHOICE(DLT_PFSYNC, "Packet filter state syncing"),
306 DLT_CHOICE(DLT_PPP_ETHER, "PPP over Ethernet; session only w/o ether header"),
307 DLT_CHOICE(DLT_IEEE802_11, "IEEE 802.11 wireless"),
308 DLT_CHOICE(DLT_PFLOG, "Packet filter logging, by pcap people"),
309 DLT_CHOICE(DLT_IEEE802_11_RADIO, "IEEE 802.11 plus WLAN header"),
310 #undef DLT_CHOICE
311 	{ NULL, NULL, -1}
312 };
313 
314 int
315 pcap_datalink_name_to_val(const char *name)
316 {
317 	int i;
318 
319 	for (i = 0; dlts[i].name != NULL; i++) {
320 		/* Skip leading "DLT_" */
321 		if (strcasecmp(dlts[i].name + 4, name) == 0)
322 			return (dlts[i].dlt);
323 	}
324 	return (-1);
325 }
326 
327 const char *
328 pcap_datalink_val_to_name(int dlt)
329 {
330 	int i;
331 
332 	for (i = 0; dlts[i].name != NULL; i++) {
333 		if (dlts[i].dlt == dlt)
334 			return (dlts[i].name + 4); /* Skip leading "DLT_" */
335 	}
336 	return (NULL);
337 }
338 
339 const char *
340 pcap_datalink_val_to_description(int dlt)
341 {
342 	int i;
343 
344 	for (i = 0; dlts[i].name != NULL; i++) {
345 		if (dlts[i].dlt == dlt)
346 			return (dlts[i].description);
347 	}
348 	return (NULL);
349 }
350 
351 int
352 pcap_snapshot(pcap_t *p)
353 {
354 	return (p->snapshot);
355 }
356 
357 int
358 pcap_is_swapped(pcap_t *p)
359 {
360 	return (p->sf.swapped);
361 }
362 
363 int
364 pcap_major_version(pcap_t *p)
365 {
366 	return (p->sf.version_major);
367 }
368 
369 int
370 pcap_minor_version(pcap_t *p)
371 {
372 	return (p->sf.version_minor);
373 }
374 
375 FILE *
376 pcap_file(pcap_t *p)
377 {
378 	return (p->sf.rfile);
379 }
380 
381 int
382 pcap_fileno(pcap_t *p)
383 {
384 	return (p->fd);
385 }
386 
387 void
388 pcap_perror(pcap_t *p, char *prefix)
389 {
390 	fprintf(stderr, "%s: %s\n", prefix, p->errbuf);
391 }
392 
393 int
394 pcap_get_selectable_fd(pcap_t *p)
395 {
396 	return (p->fd);
397 }
398 
399 char *
400 pcap_geterr(pcap_t *p)
401 {
402 	return (p->errbuf);
403 }
404 
405 int
406 pcap_getnonblock(pcap_t *p, char *errbuf)
407 {
408 	int fdflags;
409 
410 	fdflags = fcntl(p->fd, F_GETFL, 0);
411 	if (fdflags == -1) {
412 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "F_GETFL: %s",
413 		    pcap_strerror(errno));
414 		return (-1);
415 	}
416 	if (fdflags & O_NONBLOCK)
417 		return (1);
418 	else
419 		return (0);
420 }
421 
422 int
423 pcap_setnonblock(pcap_t *p, int nonblock, char *errbuf)
424 {
425 	int fdflags;
426 
427 	fdflags = fcntl(p->fd, F_GETFL, 0);
428 	if (fdflags == -1) {
429 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "F_GETFL: %s",
430 		    pcap_strerror(errno));
431 		return (-1);
432 	}
433 	if (nonblock)
434 		fdflags |= O_NONBLOCK;
435 	else
436 		fdflags &= ~O_NONBLOCK;
437 	if (fcntl(p->fd, F_SETFL, fdflags) == -1) {
438 		snprintf(p->errbuf, PCAP_ERRBUF_SIZE, "F_SETFL: %s",
439 		    pcap_strerror(errno));
440 		return (-1);
441 	}
442 	return (0);
443 }
444 
445 /*
446  * Generate error strings for PCAP_ERROR_ and PCAP_WARNING_ values.
447  */
448 const char *
449 pcap_statustostr(int errnum)
450 {
451 	static char ebuf[15+10+1];
452 
453 	switch (errnum) {
454 
455 	case PCAP_WARNING:
456 		return("Generic warning");
457 
458 	case PCAP_WARNING_TSTAMP_TYPE_NOTSUP:
459 		return ("That type of time stamp is not supported by that device");
460 
461 	case PCAP_WARNING_PROMISC_NOTSUP:
462 		return ("That device doesn't support promiscuous mode");
463 
464 	case PCAP_ERROR:
465 		return("Generic error");
466 
467 	case PCAP_ERROR_BREAK:
468 		return("Loop terminated by pcap_breakloop");
469 
470 	case PCAP_ERROR_NOT_ACTIVATED:
471 		return("The pcap_t has not been activated");
472 
473 	case PCAP_ERROR_ACTIVATED:
474 		return ("The setting can't be changed after the pcap_t is activated");
475 
476 	case PCAP_ERROR_NO_SUCH_DEVICE:
477 		return ("No such device exists");
478 
479 	case PCAP_ERROR_RFMON_NOTSUP:
480 		return ("That device doesn't support monitor mode");
481 
482 	case PCAP_ERROR_NOT_RFMON:
483 		return ("That operation is supported only in monitor mode");
484 
485 	case PCAP_ERROR_PERM_DENIED:
486 		return ("You don't have permission to capture on that device");
487 
488 	case PCAP_ERROR_IFACE_NOT_UP:
489 		return ("That device is not up");
490 
491 	case PCAP_ERROR_CANTSET_TSTAMP_TYPE:
492 		return ("That device doesn't support setting the time stamp type");
493 
494 	case PCAP_ERROR_PROMISC_PERM_DENIED:
495 		return ("You don't have permission to capture in promiscuous mode on that device");
496 	}
497 	(void)snprintf(ebuf, sizeof ebuf, "Unknown error: %d", errnum);
498 	return(ebuf);
499 }
500 
501 /*
502  * Not all systems have strerror().
503  */
504 char *
505 pcap_strerror(int errnum)
506 {
507 #ifdef HAVE_STRERROR
508 	return (strerror(errnum));
509 #else
510 	extern int sys_nerr;
511 	extern const char *const sys_errlist[];
512 	static char ebuf[20];
513 
514 	if ((unsigned int)errnum < sys_nerr)
515 		return ((char *)sys_errlist[errnum]);
516 	(void)snprintf(ebuf, sizeof ebuf, "Unknown error: %d", errnum);
517 	return(ebuf);
518 #endif
519 }
520 
521 /*
522  * On some platforms, we need to clean up promiscuous or monitor mode
523  * when we close a device - and we want that to happen even if the
524  * application just exits without explicitl closing devices.
525  * On those platforms, we need to register a "close all the pcaps"
526  * routine to be called when we exit, and need to maintain a list of
527  * pcaps that need to be closed to clean up modes.
528  *
529  * XXX - not thread-safe.
530  */
531 
532 /*
533  * List of pcaps on which we've done something that needs to be
534  * cleaned up.
535  * If there are any such pcaps, we arrange to call "pcap_close_all()"
536  * when we exit, and have it close all of them.
537  */
538 static struct pcap *pcaps_to_close;
539 
540 /*
541  * TRUE if we've already called "atexit()" to cause "pcap_close_all()" to
542  * be called on exit.
543  */
544 static int did_atexit;
545 
546 static void
547 pcap_close_all(void)
548 {
549 	struct pcap *handle;
550 
551 	while ((handle = pcaps_to_close) != NULL)
552 		pcap_close(handle);
553 }
554 
555 int
556 pcap_do_addexit(pcap_t *p)
557 {
558 	/*
559 	 * If we haven't already done so, arrange to have
560 	 * "pcap_close_all()" called when we exit.
561 	 */
562 	if (!did_atexit) {
563 		if (atexit(pcap_close_all) == -1) {
564 			/*
565 			 * "atexit()" failed; let our caller know.
566 			 */
567 			(void)strlcpy(p->errbuf, "atexit failed",
568 			    PCAP_ERRBUF_SIZE);
569 			return (0);
570 		}
571 		did_atexit = 1;
572 	}
573 	return (1);
574 }
575 
576 void
577 pcap_add_to_pcaps_to_close(pcap_t *p)
578 {
579 	p->md.next = pcaps_to_close;
580 	pcaps_to_close = p;
581 }
582 
583 void
584 pcap_remove_from_pcaps_to_close(pcap_t *p)
585 {
586 	pcap_t *pc, *prevpc;
587 
588 	for (pc = pcaps_to_close, prevpc = NULL; pc != NULL;
589 	    prevpc = pc, pc = pc->md.next) {
590 		if (pc == p) {
591 			/*
592 			 * Found it.  Remove it from the list.
593 			 */
594 			if (prevpc == NULL) {
595 				/*
596 				 * It was at the head of the list.
597 				 */
598 				pcaps_to_close = pc->md.next;
599 			} else {
600 				/*
601 				 * It was in the middle of the list.
602 				 */
603 				prevpc->md.next = pc->md.next;
604 			}
605 			break;
606 		}
607 	}
608 }
609 
610 pcap_t *
611 pcap_open_dead(int linktype, int snaplen)
612 {
613 	pcap_t *p;
614 
615 	p = malloc(sizeof(*p));
616 	if (p == NULL)
617 		return NULL;
618 	memset (p, 0, sizeof(*p));
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