1/*	$NetBSD: bootptest.c,v 1.19 2011/08/16 08:02:18 christos Exp $	*/
2
3/*
4 * bootptest.c - Test out a bootp server.
5 *
6 * This simple program was put together from pieces taken from
7 * various places, including the CMU BOOTP client and server.
8 * The packet printing routine is from the Berkeley "tcpdump"
9 * program with some enhancements I added.  The print-bootp.c
10 * file was shared with my copy of "tcpdump" and therefore uses
11 * some unusual utility routines that would normally be provided
12 * by various parts of the tcpdump program.  Gordon W. Ross
13 *
14 * Boilerplate:
15 *
16 * This program includes software developed by the University of
17 * California, Lawrence Berkeley Laboratory and its contributors.
18 * (See the copyright notice in print-bootp.c)
19 *
20 * The remainder of this program is public domain.  You may do
21 * whatever you like with it except claim that you wrote it.
22 *
23 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
24 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
25 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
26 *
27 * HISTORY:
28 *
29 * 12/02/93 Released version 1.4 (with bootp-2.3.2)
30 * 11/05/93 Released version 1.3
31 * 10/14/93 Released version 1.2
32 * 10/11/93 Released version 1.1
33 * 09/28/93 Released version 1.0
34 * 09/93 Original developed by Gordon W. Ross <gwr@mc.com>
35 */
36
37#include <sys/cdefs.h>
38#ifndef lint
39__RCSID("$NetBSD: bootptest.c,v 1.19 2011/08/16 08:02:18 christos Exp $");
40#endif
41
42static const char usage[] =
43    "Usage: %s [-f bootfile] [-h] [-m magic_number] server-name\n"
44    "\t[vendor-data-template-file]\n";
45
46#include <sys/param.h>
47#include <sys/socket.h>
48#include <sys/ioctl.h>
49#include <sys/file.h>
50#include <sys/time.h>
51#include <sys/stat.h>
52#include <sys/poll.h>
53
54#include <net/if.h>
55#include <netinet/in.h>
56#include <arpa/inet.h>			/* inet_ntoa */
57
58#include <stdlib.h>
59#include <signal.h>
60#include <stdio.h>
61#include <string.h>
62#include <strings.h>
63#include <errno.h>
64#include <ctype.h>
65#include <netdb.h>
66#include <assert.h>
67#include <unistd.h>
68
69#include "bootp.h"
70#include "bootptest.h"
71#include "getif.h"
72#include "report.h"
73#include "patchlevel.h"
74
75#define LOG_ERR 1
76#define BUFLEN 1024
77#define WAITSECS 1
78#define MAXWAIT  10
79
80int vflag = 1;
81int tflag = 0;
82int thiszone;
83char *progname;
84unsigned char *packetp;
85unsigned char *snapend;
86int snaplen;
87
88
89/*
90 * IP port numbers for client and server obtained from /etc/services
91 */
92
93u_short bootps_port, bootpc_port;
94
95
96/*
97 * Internet socket and interface config structures
98 */
99
100struct sockaddr_in sin_server;	/* where to send requests */
101struct sockaddr_in sin_client;	/* for bind and listen */
102struct sockaddr_in sin_from;	/* Packet source */
103u_char eaddr[16];				/* Ethernet address */
104
105/*
106 * General
107 */
108
109int debug = 1;					/* Debugging flag (level) */
110char hostname[MAXHOSTNAMELEN + 1];
111char *sndbuf;					/* Send packet buffer */
112char *rcvbuf;					/* Receive packet buffer */
113
114/*
115 * Vendor magic cookies for CMU and RFC1048
116 */
117
118unsigned char vm_cmu[4] = VM_CMU;
119unsigned char vm_rfc1048[4] = VM_RFC1048;
120short secs;						/* How long client has waited */
121
122
123extern int getether(char *, char *);
124int main(int, char **);
125void send_request(int);
126
127/*
128 * Initialization such as command-line processing is done, then
129 * the receiver loop is started.  Die when interrupted.
130 */
131
132int
133main(int argc, char **argv)
134{
135	struct bootp *bp;
136	struct servent *sep;
137	struct hostent *hep;
138
139	char *servername = NULL;
140	char *vendor_file = NULL;
141	char *bp_file = NULL;
142	socklen_t fromlen;
143	int s;				/* Socket file descriptor */
144	int n, recvcnt;
145	int use_hwa = 0;
146	int32 vend_magic;
147	int32 xid;
148	struct pollfd set[1];
149
150	progname = strrchr(argv[0], '/');
151	if (progname)
152		progname++;
153	else
154		progname = argv[0];
155	argc--;
156	argv++;
157
158	if (debug)
159		printf("%s: version %s.%d\n", progname, VERSION, PATCHLEVEL);
160
161	/*
162	 * Verify that "struct bootp" has the correct official size.
163	 * (Catch evil compilers that do struct padding.)
164	 */
165	assert(sizeof(struct bootp) == BP_MINPKTSZ);
166
167	sndbuf = malloc(BUFLEN);
168	rcvbuf = malloc(BUFLEN);
169	if (!sndbuf || !rcvbuf) {
170		printf("malloc failed\n");
171		exit(1);
172	}
173
174	/* default magic number */
175	bcopy(vm_rfc1048, (char*)&vend_magic, 4);
176
177	/* Handle option switches. */
178	while (argc > 0) {
179		if (argv[0][0] != '-')
180			break;
181		switch (argv[0][1]) {
182
183		case 'f':				/* File name to reqest. */
184			if (argc < 2)
185				goto error;
186			argc--; argv++;
187			bp_file = *argv;
188			break;
189
190		case 'h':				/* Use hardware address. */
191			use_hwa = 1;
192			break;
193
194		case 'm':				/* Magic number value. */
195			if (argc < 2)
196				goto error;
197			argc--; argv++;
198			vend_magic = inet_addr(*argv);
199			break;
200
201		error:
202		default:
203			(void)fprintf(stderr, usage, getprogname());
204			exit(1);
205
206		}
207		argc--;
208		argv++;
209	}
210
211	/* Get server name (or address) for query. */
212	if (argc > 0) {
213		servername = *argv;
214		argc--;
215		argv++;
216	}
217	/* Get optional vendor-data-template-file. */
218	if (argc > 0) {
219		vendor_file = *argv;
220		argc--;
221		argv++;
222	}
223	if (!servername) {
224		printf("missing server name.\n");
225		(void)fprintf(stderr, usage, getprogname());
226		exit(1);
227	}
228	/*
229	 * Create a socket.
230	 */
231	if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
232		perror("socket");
233		exit(1);
234	}
235	/*
236	 * Get server's listening port number
237	 */
238	sep = getservbyname("bootps", "udp");
239	if (sep) {
240		bootps_port = ntohs((u_short) sep->s_port);
241	} else {
242		fprintf(stderr, "udp/bootps: unknown service -- using port %d\n",
243				IPPORT_BOOTPS);
244		bootps_port = (u_short) IPPORT_BOOTPS;
245	}
246
247	/*
248	 * Set up server socket address (for send)
249	 */
250	if (servername) {
251		if (inet_aton(servername, &sin_server.sin_addr) == 0) {
252			hep = gethostbyname(servername);
253			if (!hep) {
254				fprintf(stderr, "%s: unknown host\n", servername);
255				exit(1);
256			}
257			memcpy(&sin_server.sin_addr, hep->h_addr,
258			    sizeof(sin_server.sin_addr));
259		}
260	} else {
261		/* Get broadcast address */
262		/* XXX - not yet */
263		sin_server.sin_addr.s_addr = INADDR_ANY;
264	}
265	sin_server.sin_family = AF_INET;
266	sin_server.sin_port = htons(bootps_port);
267
268	/*
269	 * Get client's listening port number
270	 */
271	sep = getservbyname("bootpc", "udp");
272	if (sep) {
273		bootpc_port = ntohs(sep->s_port);
274	} else {
275		fprintf(stderr, "udp/bootpc: unknown service -- using port %d\n",
276				IPPORT_BOOTPC);
277		bootpc_port = (u_short) IPPORT_BOOTPC;
278	}
279
280	/*
281	 * Set up client socket address (for listen)
282	 */
283	sin_client.sin_family = AF_INET;
284	sin_client.sin_port = htons(bootpc_port);
285	sin_client.sin_addr.s_addr = INADDR_ANY;
286
287	/*
288	 * Bind client socket to BOOTPC port.
289	 */
290	if (bind(s, (struct sockaddr *) &sin_client, sizeof(sin_client)) < 0) {
291		perror("bind BOOTPC port");
292		if (errno == EACCES)
293			fprintf(stderr, "You need to run this as root\n");
294		exit(1);
295	}
296	/*
297	 * Build a request.
298	 */
299	bp = (struct bootp *) sndbuf;
300	bzero(bp, sizeof(*bp));
301	bp->bp_op = BOOTREQUEST;
302	xid = (int32) getpid();
303	bp->bp_xid = (u_int32) htonl(xid);
304	if (bp_file)
305		strlcpy(bp->bp_file, bp_file, sizeof(bp->bp_file));
306
307	/*
308	 * Fill in the hardware address (or client IP address)
309	 */
310	if (use_hwa) {
311		struct ifreq *ifr;
312
313		ifr = getif(s, &sin_server.sin_addr);
314		if (!ifr) {
315			printf("No interface for %s\n", servername);
316			exit(1);
317		}
318		if (getether(ifr->ifr_name, (char *)eaddr)) {
319			printf("Can not get ether addr for %s\n", ifr->ifr_name);
320			exit(1);
321		}
322		/* Copy Ethernet address into request packet. */
323		bp->bp_htype = 1;
324		bp->bp_hlen = 6;
325		bcopy(eaddr, bp->bp_chaddr, bp->bp_hlen);
326	} else {
327		/* Fill in the client IP address. */
328		gethostname(hostname, sizeof(hostname));
329		hostname[sizeof(hostname) - 1] = '\0';
330		hep = gethostbyname(hostname);
331		if (!hep) {
332			printf("Can not get my IP address\n");
333			exit(1);
334		}
335		bcopy(hep->h_addr, &bp->bp_ciaddr, hep->h_length);
336	}
337
338	/*
339	 * Copy in the default vendor data.
340	 */
341	bcopy((char*)&vend_magic, bp->bp_vend, 4);
342	if (vend_magic)
343		bp->bp_vend[4] = TAG_END;
344
345	/*
346	 * Read in the "options" part of the request.
347	 * This also determines the size of the packet.
348	 */
349	snaplen = sizeof(*bp);
350	if (vendor_file) {
351		int fd = open(vendor_file, 0);
352		if (fd < 0) {
353			perror(vendor_file);
354			exit(1);
355		}
356		/* Compute actual space for options. */
357		n = BUFLEN - sizeof(*bp) + BP_VEND_LEN;
358		n = read(fd, bp->bp_vend, n);
359		close(fd);
360		if (n < 0) {
361			perror(vendor_file);
362			exit(1);
363		}
364		printf("read %d bytes of vendor template\n", n);
365		if (n > BP_VEND_LEN) {
366			printf("warning: extended options in use (len > %d)\n",
367				   BP_VEND_LEN);
368			snaplen += (n - BP_VEND_LEN);
369		}
370	}
371	/*
372	 * Set globals needed by print_bootp
373	 * (called by send_request)
374	 */
375	packetp = (unsigned char *) eaddr;
376	snapend = (unsigned char *) sndbuf + snaplen;
377
378	/* Send a request once per second while waiting for replies. */
379	recvcnt = 0;
380	bp->bp_secs = secs = 0;
381	send_request(s);
382	set[0].fd = s;
383	set[0].events = POLLIN;
384	while (1) {
385		n = poll(set, 1, WAITSECS * 1000);
386		if (n < 0) {
387			perror("poll");
388			break;
389		}
390		if (n == 0) {
391			/*
392			 * We have not received a response in the last second.
393			 * If we have ever received any responses, exit now.
394			 * Otherwise, bump the "wait time" field and re-send.
395			 */
396			if (recvcnt > 0)
397				exit(0);
398			secs += WAITSECS;
399			if (secs > MAXWAIT)
400				break;
401			bp->bp_secs = htons(secs);
402			send_request(s);
403			continue;
404		}
405		fromlen = sizeof(sin_from);
406		n = recvfrom(s, rcvbuf, BUFLEN, 0,
407					 (struct sockaddr *) &sin_from, &fromlen);
408		if (n <= 0) {
409			continue;
410		}
411		if (n < (int)sizeof(struct bootp)) {
412			printf("received short packet\n");
413			continue;
414		}
415		recvcnt++;
416
417		/* Print the received packet. */
418		printf("Recvd from %s", inet_ntoa(sin_from.sin_addr));
419		/* set globals needed by bootp_print() */
420		snaplen = n;
421		snapend = (unsigned char *) rcvbuf + snaplen;
422		bootp_print((struct bootp *)rcvbuf, n, sin_from.sin_port, 0);
423		putchar('\n');
424		/*
425		 * This no longer exits immediately after receiving
426		 * one response because it is useful to know if the
427		 * client might get multiple responses.  This code
428		 * will now listen for one second after a response.
429		 */
430	}
431	fprintf(stderr, "no response from %s\n", servername);
432	exit(1);
433}
434
435void
436send_request(int s)
437{
438	/* Print the request packet. */
439	printf("Sending to %s", inet_ntoa(sin_server.sin_addr));
440	bootp_print((struct bootp *)sndbuf, snaplen, sin_from.sin_port, 0);
441	putchar('\n');
442
443	/* Send the request packet. */
444	if (sendto(s, sndbuf, snaplen, 0,
445			   (struct sockaddr *) &sin_server,
446			   sizeof(sin_server)) < 0)
447	{
448		perror("sendto server");
449		exit(1);
450	}
451}
452
453/*
454 * Print out a filename (or other ascii string).
455 * Return true if truncated.
456 */
457int
458printfn(u_char *s, u_char *ep)
459{
460	u_char c;
461
462	putchar('"');
463	while ((c = *s++) != 0) {
464		if (s > ep) {
465			putchar('"');
466			return (1);
467		}
468		if (!isascii(c)) {
469			c = toascii(c);
470			putchar('M');
471			putchar('-');
472		}
473		if (!isprint(c)) {
474			c ^= 0x40;			/* DEL to ?, others to alpha */
475			putchar('^');
476		}
477		putchar(c);
478	}
479	putchar('"');
480	return (0);
481}
482
483/*
484 * Convert an IP addr to a string.
485 * (like inet_ntoa, but ina is a pointer)
486 */
487char *
488ipaddr_string(struct in_addr *ina)
489{
490	static char b[24];
491	u_char *p;
492
493	p = (u_char *) ina;
494	snprintf(b, sizeof(b), "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
495	return (b);
496}
497
498/*
499 * Local Variables:
500 * tab-width: 4
501 * c-indent-level: 4
502 * c-argdecl-indent: 4
503 * c-continued-statement-offset: 4
504 * c-continued-brace-offset: -4
505 * c-label-offset: -4
506 * c-brace-offset: 0
507 * End:
508 */
509