1 /*
2  * $smu-mark$
3  * $name: datafiller.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:47 MET 1999$
8  * $rev: 8$
9  */
10 
11 /* $Id: datafiller.c,v 1.2 2003/09/01 00:22:06 antirez Exp $ */
12 
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <unistd.h>
16 #include <sys/types.h>
17 #include <sys/stat.h>
18 #include <fcntl.h>
19 #include <string.h> /* memset */
20 
21 #include "hping2.h"
22 #include "globals.h"
23 
datafiller(char * p,int size)24 void datafiller(char *p, int size)
25 {
26 	static int fd = 0;
27 	int readed, diff;
28 
29 	if (!fd) {
30 		fd = open(datafilename, O_RDONLY);
31 		if (fd == -1) {
32 			perror("[datafiller] open()");
33 			fd = 0; /* will retry to open the file for
34 				 * the next packet */
35 			memset(p, 'X', size);
36 			return;
37 		}
38 	}
39 
40 	if (p == NULL && fd != -1) { /* seek operation */
41 		/* size-1 because packet with id 1 start from 0 */
42 		lseek(fd, (data_size-signlen)*(size-1), SEEK_SET);
43 		return;
44 	}
45 
46 restart: /* if EOF occurs, after rewind, restart */
47 
48 	readed = read(fd, p, size);
49 	if (readed == size)
50 		return;
51 	else if (readed == -1) {
52 		perror("[datafiller] read()");
53 		close(fd);
54 		fd = 0; /* will retry to open the file for the next packet */
55 		memset(p, 'X', size);
56 		return;
57 	}
58 	else if (readed < size && opt_end == FALSE) {
59 		lseek(fd, 0, SEEK_SET);
60 		if (readed == 0)
61 			goto restart;
62 	}
63 	else if (readed < size && opt_end == TRUE) {
64 		fprintf(stderr, "EOF reached, wait some second than press "
65 				"ctrl+c\n");
66 		eof_reached = TRUE;
67 	} else {
68 		printf("[datafiller.c INTERNAL ERROR] readed = %d - "
69 			"opt_end == %d\n", readed, opt_end);
70 		exit(1);
71 	}
72 	diff = size - readed;
73 	memset(p+readed, '\0', diff); /* padding */
74 	lseek(fd, 0, SEEK_SET);
75 	return;
76 }
77