1 /*
2  * $smu-mark$
3  * $name: listen.c$
4  * $author: Salvatore Sanfilippo <antirez@invece.org>$
5  * $copyright: Copyright (C) 1999 by Salvatore Sanfilippo$
6  * $license: This software is under GPL version 2 of license$
7  * $date: Fri Nov  5 11:55:48 MET 1999$
8  * $rev: 8$
9  */
10 
11 /* $Id: listen.c,v 1.2 2003/09/01 00:22:06 antirez Exp $ */
12 
13 #include <stdlib.h>
14 #include <stdio.h>
15 #include <string.h>
16 #include <unistd.h>
17 #include <sys/types.h>
18 #include <sys/socket.h>
19 #include <netinet/in.h>
20 
21 #include "hping2.h" /* hping2.h includes hcmp.h */
22 #include "globals.h"
23 
listenmain(void)24 void listenmain(void)
25 {
26 	int size, ip_size;
27 	int stdoutFD = fileno(stdout);
28 	char packet[IP_MAX_SIZE+linkhdr_size];
29 	char *p, *ip_packet;
30 	struct myiphdr ip;
31 	__u16 id;
32 	static __u16 exp_id; /* expected id */
33 
34 	exp_id = 1;
35 
36 	while(1) {
37 		size = read_packet(packet, IP_MAX_SIZE+linkhdr_size);
38 		switch(size) {
39 		case 0:
40 			continue;
41 		case -1:
42 			exit(1);
43 		}
44 
45 		/* Skip truncated packets */
46 		if (size < linkhdr_size+IPHDR_SIZE)
47 			continue;
48 		ip_packet = packet + linkhdr_size;
49 
50 		/* copy the ip header so it will be aligned */
51 		memcpy(&ip, ip_packet, sizeof(ip));
52 		id = ntohs(ip.id);
53 		ip_size = ntohs(ip.tot_len);
54 		if (size-linkhdr_size > ip_size)
55 			size = ip_size;
56 		else
57 			size -= linkhdr_size;
58 
59 		if ((p = memstr(ip_packet, sign, size))) {
60 			if (opt_verbose)
61 				fprintf(stderr, "packet %d received\n", id);
62 
63 			if (opt_safe) {
64 				if (id == exp_id)
65 					exp_id++;
66 				else {
67 					if (opt_verbose)
68 						fprintf(stderr, "packet not in sequence (id %d) received\n", id);
69 					send_hcmp(HCMP_RESTART, exp_id);
70 					if (opt_verbose)
71 						fprintf(stderr, "HCMP restart from %d sent\n", exp_id);
72 					continue; /* discard this packet */
73 				}
74 			}
75 
76 			p+=strlen(sign);
77 			write(stdoutFD, p, size-(p-ip_packet));
78 		}
79 	}
80 }
81