Home | History | Annotate | Download | only in ns-tools
      1 /******************************************************************************/
      2 /*                                                                            */
      3 /*   Copyright (c) International Business Machines  Corp., 2006               */
      4 /*                                                                            */
      5 /*   This program is free software;  you can redistribute it and/or modify    */
      6 /*   it under the terms of the GNU General Public License as published by     */
      7 /*   the Free Software Foundation; either version 2 of the License, or        */
      8 /*   (at your option) any later version.                                      */
      9 /*                                                                            */
     10 /*   This program is distributed in the hope that it will be useful,          */
     11 /*   but WITHOUT ANY WARRANTY;  without even the implied warranty of          */
     12 /*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See                */
     13 /*   the GNU General Public License for more details.                         */
     14 /*                                                                            */
     15 /*   You should have received a copy of the GNU General Public License        */
     16 /*   along with this program;  if not, write to the Free Software             */
     17 /*   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA  */
     18 /*                                                                            */
     19 /******************************************************************************/
     20 
     21 /*
     22  * File:
     23  *	ns-udpsender.c
     24  *
     25  * Description:
     26  *	This is UDP datagram sender (not only unicast but also multicast)
     27  *
     28  * Author:
     29  *	Mitsuru Chinen <mitch (at) jp.ibm.com>
     30  *
     31  * History:
     32  *	Mar 17 2006 - Created (Mitsuru Chinen)
     33  *---------------------------------------------------------------------------*/
     34 
     35 /*
     36  * Header Files
     37  */
     38 #include <stdio.h>
     39 #include <stdlib.h>
     40 #include <string.h>
     41 #include <errno.h>
     42 #include <netdb.h>
     43 #include <signal.h>
     44 #include <time.h>
     45 #include <unistd.h>
     46 #include <sys/ioctl.h>
     47 #include <sys/socket.h>
     48 #include <sys/types.h>
     49 
     50 #include "ns-traffic.h"
     51 
     52 /*
     53  * Structure Definitions
     54  */
     55 
     56 struct udp_info {
     57 	int sd;
     58 	int is_multicast;
     59 	sa_family_t family;
     60 	char *ifname;
     61 	char *dst_name;
     62 	char *dst_port;
     63 	struct addrinfo addr_info;
     64 	unsigned char *msg;
     65 	size_t msgsize;
     66 	double timeout;
     67 };
     68 
     69 /*
     70  * Gloval variables
     71  */
     72 char *program_name;		/* program name */
     73 struct sigaction handler;	/* Behavior for a signal */
     74 int catch_sighup;		/* When catch the SIGHUP, set to non-zero */
     75 
     76 /*
     77  * Function: usage()
     78  *
     79  * Descripton:
     80  *  Print the usage of this program. Then, terminate this program with
     81  *  the specified exit value.
     82  *
     83  * Argument:
     84  *  exit_value:	exit value
     85  *
     86  * Return value:
     87  *  This function does not return.
     88  */
     89 void usage(char *program_name, int exit_value)
     90 {
     91 	FILE *stream = stdout;	/* stream where the usage is output */
     92 
     93 	if (exit_value == EXIT_FAILURE)
     94 		stream = stderr;
     95 
     96 	fprintf(stream, "%s [OPTION]\n"
     97 		"\t-f num\ttprotocol family\n"
     98 		"\t\t  4 : IPv4\n"
     99 		"\t\t  6 : IPv6\n"
    100 		"\t-D addr\tIP address of the destination host\n"
    101 		"\t-p num\tport number of the destination host\n"
    102 		"\t-s size\tdata size of UDP payload\n"
    103 		"\t-t value\ttimeout [sec]\n"
    104 		"\t-o\t\tsend only one UDP datagram\n"
    105 		"\t-b\t\twork in the background\n"
    106 		"\t-d\t\tdisplay debug informations\n"
    107 		"\t-h\t\tdisplay this usage\n"
    108 		"\n"
    109 		"\t[options for multicast]\n"
    110 		"\t  -m\t\tsend multicast datagrams\n"
    111 		"\t  -I if_name\tinterface name of the source host\n",
    112 		program_name);
    113 	exit(exit_value);
    114 }
    115 
    116 /*
    117  * Function: set_signal_flag()
    118  *
    119  * Description:
    120  *  This function sets global variables accordig to signal
    121  *
    122  * Argument:
    123  *  type: type of signal
    124  *
    125  * Return value:
    126  *  None
    127  */
    128 void set_signal_flag(int type)
    129 {
    130 	if (debug)
    131 		fprintf(stderr, "Catch signal. type is %d\n", type);
    132 
    133 	switch (type) {
    134 	case SIGHUP:
    135 		catch_sighup = 1;
    136 		handler.sa_handler = SIG_IGN;
    137 		if (sigaction(type, &handler, NULL) < 0)
    138 			fatal_error("sigaction()");
    139 		break;
    140 
    141 	default:
    142 		fprintf(stderr, "Unexpected signal (%d) is caught\n", type);
    143 		exit(EXIT_FAILURE);
    144 	}
    145 }
    146 
    147 /*
    148  * Function: parse_options()
    149  *
    150  * Description:
    151  *  This function parse the options
    152  *
    153  * Argument:
    154  *   argc:  the number of argument
    155  *   argv:  arguments
    156  *  udp_p: pointer to the data of udp datagram
    157  *   bg_p: pointer to the flag of working in backgrond
    158  *
    159  * Return value:
    160  *  None
    161  */
    162 void parse_options(int argc, char *argv[], struct udp_info *udp_p, int *bg_p)
    163 {
    164 	int optc;		/* option */
    165 	unsigned long opt_ul;	/* option value in unsigned long */
    166 	double opt_d;		/* option value in double */
    167 	int is_specified_family = 0;
    168 	int is_specified_daddr = 0;
    169 	int is_specified_port = 0;
    170 
    171 	while ((optc = getopt(argc, argv, "f:D:p:s:t:obdhmI:")) != EOF) {
    172 		switch (optc) {
    173 		case 'f':
    174 			if (optarg[0] == '4')
    175 				udp_p->family = PF_INET;	/* IPv4 */
    176 			else if (optarg[0] == '6')
    177 				udp_p->family = PF_INET6;	/* IPv6 */
    178 			else {
    179 				fprintf(stderr,
    180 					"protocol family should be 4 or 6.\n");
    181 				usage(program_name, EXIT_FAILURE);
    182 			}
    183 			is_specified_family = 1;
    184 			break;
    185 
    186 		case 'D':
    187 			udp_p->dst_name = strdup(optarg);
    188 			if (udp_p->dst_name == NULL)
    189 				fatal_error("strdup() failed.");
    190 			is_specified_daddr = 1;
    191 			break;
    192 
    193 		case 'p':
    194 			opt_ul = strtoul(optarg, NULL, 0);
    195 			if (opt_ul < 1 || PORTNUMMAX < opt_ul) {
    196 				fprintf(stderr,
    197 					"The range of port is from %u to %u\n",
    198 					1, PORTNUMMAX);
    199 				usage(program_name, EXIT_FAILURE);
    200 			}
    201 			udp_p->dst_port = strdup(optarg);
    202 			is_specified_port = 1;
    203 			break;
    204 
    205 		case 's':
    206 			opt_ul = strtoul(optarg, NULL, 0);
    207 			udp_p->msgsize = opt_ul;
    208 			break;
    209 
    210 		case 't':
    211 			opt_d = strtod(optarg, NULL);
    212 			if (opt_d < 0.0) {
    213 				fprintf(stderr,
    214 					"Timeout should be positive value\n");
    215 				usage(program_name, EXIT_FAILURE);
    216 			}
    217 			udp_p->timeout = opt_d;
    218 			break;
    219 
    220 		case 'o':
    221 			udp_p->timeout = -1.0;
    222 			break;
    223 
    224 		case 'b':
    225 			*bg_p = 1;
    226 			break;
    227 
    228 		case 'd':
    229 			debug = 1;
    230 			break;
    231 
    232 		case 'h':
    233 			usage(program_name, EXIT_SUCCESS);
    234 			break;
    235 
    236 			/* Options for multicast */
    237 		case 'm':
    238 			udp_p->is_multicast = 1;
    239 			break;
    240 
    241 		case 'I':
    242 			udp_p->ifname = strdup(optarg);
    243 			if (udp_p->dst_name == NULL)
    244 				fatal_error("strdup() failed.");
    245 			break;
    246 
    247 		default:
    248 			usage(program_name, EXIT_FAILURE);
    249 		}
    250 	}
    251 
    252 	if (!is_specified_family) {
    253 		fprintf(stderr, "protocol family is not specified\n");
    254 		usage(program_name, EXIT_FAILURE);
    255 	}
    256 
    257 	if (!is_specified_daddr) {
    258 		fprintf(stderr, "desttinaion IP address is not specified\n");
    259 		usage(program_name, EXIT_FAILURE);
    260 	}
    261 
    262 	if (!is_specified_port) {
    263 		fprintf(stderr, "destination port is not specified\n");
    264 		usage(program_name, EXIT_FAILURE);
    265 	}
    266 
    267 	if (udp_p->is_multicast) {
    268 		if (udp_p->ifname == NULL) {
    269 			fprintf(stderr,
    270 				"interface name is not specified with multicast\n");
    271 			usage(program_name, EXIT_FAILURE);
    272 		}
    273 	}
    274 }
    275 
    276 /*
    277  * Function: create_udp_datagram()
    278  *
    279  * Description:
    280  *  This function creates udp datagram
    281  *
    282  * Argument:
    283  *  udp_p: pointer to data of udp data structure
    284  *
    285  * Return value:
    286  *  None
    287  */
    288 void create_udp_datagram(struct udp_info *udp_p)
    289 {
    290 	struct addrinfo hints;	/* hints for getaddrinfo() */
    291 	struct addrinfo *res;	/* pointer to addrinfo structure */
    292 	struct ifreq ifinfo;	/* Interface information */
    293 	int err;		/* return value of getaddrinfo */
    294 	int on;			/* variable for socket option */
    295 
    296 	/* Set the hints to addrinfo() */
    297 	memset(&hints, '\0', sizeof(struct addrinfo));
    298 	hints.ai_family = udp_p->family;
    299 	hints.ai_socktype = SOCK_DGRAM;
    300 	hints.ai_protocol = IPPROTO_UDP;
    301 
    302 	/* Get the address information */
    303 	err = getaddrinfo(udp_p->dst_name, udp_p->dst_port, &hints, &res);
    304 	if (err) {
    305 		fprintf(stderr, "getaddrinfo(): %s\n", gai_strerror(err));
    306 		exit(EXIT_FAILURE);
    307 	}
    308 	if (res->ai_next) {
    309 		fprintf(stderr, "getaddrinfo(): multiple address is found.");
    310 		exit(EXIT_FAILURE);
    311 	}
    312 
    313 	/* Create a socket */
    314 	udp_p->sd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    315 	if (udp_p->sd < 0)
    316 		fatal_error("socket()");
    317 
    318 	/* Enable to reuse the socket */
    319 	on = 1;
    320 	if (setsockopt(udp_p->sd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(int)))
    321 		fatal_error("setsockopt()");
    322 
    323 	/* In multicast case, specify the interface for outgoing datagrams */
    324 	if (udp_p->is_multicast) {
    325 		struct ip_mreqn mcast_req, *req_p = &mcast_req;
    326 		int ifindex, *id_p = &ifindex;
    327 
    328 		get_ifinfo(&ifinfo, udp_p->sd, udp_p->ifname, SIOCGIFINDEX);
    329 		ifindex = ifinfo.ifr_ifindex;
    330 
    331 		switch (udp_p->family) {
    332 		case PF_INET:	/* IPv4 */
    333 			req_p->imr_multiaddr =
    334 			    ((struct sockaddr_in *)(res->ai_addr))->sin_addr;
    335 			req_p->imr_address.s_addr = htonl(INADDR_ANY);
    336 			req_p->imr_ifindex = ifindex;
    337 			if (setsockopt(udp_p->sd, IPPROTO_IP, IP_MULTICAST_IF,
    338 				       req_p, sizeof(struct ip_mreqn))) {
    339 				fatal_error("setsockopt()");
    340 			}
    341 			break;
    342 
    343 		case PF_INET6:	/* IPv6 */
    344 			if (setsockopt
    345 			    (udp_p->sd, IPPROTO_IPV6, IPV6_MULTICAST_IF, id_p,
    346 			     sizeof(int))) {
    347 				fatal_error("setsockopt()");
    348 			}
    349 			break;
    350 		}
    351 	}
    352 
    353 	/* Make the payload */
    354 	udp_p->msg = malloc(udp_p->msgsize);
    355 	if (udp_p->msg == NULL) {
    356 		fatal_error("malloc()");
    357 		exit(EXIT_FAILURE);
    358 	}
    359 	fill_payload(udp_p->msg, udp_p->msgsize);
    360 
    361 	/* Store addrinfo */
    362 	memcpy(&(udp_p->addr_info), res, sizeof(struct addrinfo));
    363 	freeaddrinfo(res);
    364 }
    365 
    366 /*
    367  * Function: send_udp_datagram()
    368  *
    369  * Description:
    370  *  This function sends udp datagram
    371  *
    372  * Argument:
    373  *  udp_p: pointer to the udp data structure
    374  *
    375  * Return value:
    376  *  None
    377  */
    378 void send_udp_datagram(struct udp_info *udp_p)
    379 {
    380 	int retval;
    381 	double start_time;
    382 
    383 	/* Set singal hander for SIGHUP */
    384 	handler.sa_handler = set_signal_flag;
    385 	handler.sa_flags = 0;
    386 	if (sigfillset(&handler.sa_mask) < 0)
    387 		fatal_error("sigfillset()");
    388 	if (sigaction(SIGHUP, &handler, NULL) < 0)
    389 		fatal_error("sigaction()");
    390 
    391 	/*
    392 	 * loop for sending packets
    393 	 */
    394 	start_time = time(NULL);
    395 
    396 	for (;;) {
    397 		retval = sendto(udp_p->sd, udp_p->msg, udp_p->msgsize, 0,
    398 				udp_p->addr_info.ai_addr,
    399 				udp_p->addr_info.ai_addrlen);
    400 		if (retval != udp_p->msgsize) {
    401 			if (catch_sighup)
    402 				break;
    403 			else
    404 				fatal_error("sendto()");
    405 		}
    406 
    407 		/* Check timeout:
    408 		   If timeout value is negative only send one datagram */
    409 		if (udp_p->timeout)
    410 			if (udp_p->timeout < difftime(time(NULL), start_time))
    411 				break;
    412 
    413 		if (catch_sighup)	/* catch SIGHUP */
    414 			break;
    415 	}
    416 
    417 	/* Close the socket */
    418 	close(udp_p->sd);
    419 }
    420 
    421 /*
    422  *
    423  *  Function: main()
    424  *
    425  */
    426 int main(int argc, char *argv[])
    427 {
    428 	struct udp_info udp_data;
    429 	int background = 0;
    430 
    431 	debug = 0;
    432 	program_name = strdup(argv[0]);
    433 
    434 	memset(&udp_data, '\0', sizeof(struct udp_info));
    435 	parse_options(argc, argv, &udp_data, &background);
    436 
    437 	create_udp_datagram(&udp_data);
    438 
    439 	if (background)		/* Work in the background */
    440 		if (daemon(0, 0) < 0)
    441 			fatal_error("daemon()");
    442 
    443 	send_udp_datagram(&udp_data);
    444 
    445 	exit(EXIT_SUCCESS);
    446 }
    447