コード例 #1
0
ファイル: sipsak.c プロジェクト: BackupTheBerlios/sipsak-svn
int main(int argc, char *argv[])
{
	FILE	*pf;
	char	buff[BUFSIZE];
	int		c, i, port;
	unsigned int tsp;
	char	*scheme, *user, *host, *backup;
	pid_t 	pid;
	struct 	timespec ts;
	int 	upp;

#ifdef HAVE_GETOPT_LONG
	int option_index = 0;
	static struct option l_opts[] = {
		{"help", 0, 0, 'X'},
		{"version", 0, 0, 'V'},
		{"filename", 1, 0, 'f'},
		{"sip-uri", 1, 0, 's'},
		{"traceroute-mode", 0, 0, 'T'},
		{"usrloc-mode", 0, 0, 'U'},
		{"invite-mode", 0, 0, 'I'},
		{"message-mode", 0, 0, 'M'},
		{"contact", 1, 0, 'C'},
		{"appendix-begin", 1, 0, 'b'},
		{"appendix-end", 1, 0, 'e'},
		{"sleep", 1, 0, 'o'},
		{"expires", 1, 0, 'x'},
		{"remove-bindings", 1, 0, 'z'},
		{"flood-mode", 0, 0, 'F'},
		{"random-mode", 0, 0, 'R'},
		{"trash-chars", 1, 0, 't'},
		{"local-port", 1, 0, 'l'},
		{"remote-port", 1, 0, 'r'},
		{"outbound-proxy", 1, 0, 'p'},
		{"hostname", 1, 0, 'H'},
		{"max-fowards", 1, 0, 'm'},
		{"numeric", 0, 0, 'n'},
		{"no-via", 0, 0, 'i'},
		{"password", 1, 0, 'a'},
		{"ignore-redirects", 0, 0, 'd'},
		{"verbose", 0, 0, 'v'},
		{"extract-ip", 0, 0, 'w'},
		{"replace-string", 0, 0, 'g'},
		{"replace", 0, 0, 'G'},
		{"nagios-code", 0, 0, 'N'},
		{"nagios-warn", 1, 0, 'W'},
		{"search", 1, 0, 'q'},
		{"message-body", 1, 0, 'B'},
		{"disposition", 1, 0, 'O'},
		{"processes", 1, 0, 'P'},
		{"auth-username", 1, 0, 'u'},
		{"no-crlf", 0, 0, 'L'},
		{"timing", 1, 0, 'A'},
		{"symmetric", 0, 0, 'S'},
		{"from", 1, 0, 'c'},
		{"timeout-factor", 1, 0, 'D'},
		{"transport", 1, 0, 'E'},
		{"headers", 1, 0, 'j'},
		{0, 0, 0, 0}
	};
#endif
	/* some initialisation to be shure */
	file_b=uri_b=trace=lport=usrloc=flood=verbose=randtrash=trashchar = 0;
	warning_ext=rand_rem=nonce_count=replace_b=invite=message = 0;
	sleep_ms=empty_contact=nagios_warn=timing=outbound_proxy=symmetric = 0;
	namebeg=nameend=maxforw= -1;
	numeric=via_ins=redirects=fix_crlf=processes = 1;
	username=password=replace_str=hostname=contact_uri=mes_body = NULL;
	con_dis=auth_username=from_uri=headers = NULL;
	scheme = user = host = backup = req = rep = rec = NULL;
	re = NULL;
	address= 0;
	transport=tsp = 0;
	rport = port = 0;
	expires_t = USRLOC_EXP_DEF;
	inv_final = 64 * SIP_T1;
	memset(buff, 0, BUFSIZE);
	memset(fqdn, 0, FQDN_SIZE);

	if (argc==1) {
		print_help();
	}

	/* lots of command line switches to handle*/
#ifdef HAVE_GETOPT_LONG
	while ((c=getopt_long(argc, argv, "a:A:b:B:c:C:dD:e:E:f:Fg:GhH:iIj:l:Lm:MnNo:O:p:P:q:r:Rs:St:Tu:UvVwW:x:Xz:", l_opts, &option_index)) != EOF){
#else
	while ((c=getopt(argc, argv, "a:A:b:B:c:C:dD:e:E:f:Fg:GhH:iIj:l:Lm:MnNo:O:p:P:q:r:Rs:St:Tu:UvVwW:x:z:")) != EOF){
#endif
		switch(c){
			case 'a':
				if (strlen(optarg) == 1 && STRNCASECMP(optarg, "-", 1) == 0) {
					password = str_alloc(SIPSAK_MAX_PASSWD_LEN);
					printf("Please enter the password (max. length %i): ", SIPSAK_MAX_PASSWD_LEN);
					if (read_stdin(password, SIPSAK_MAX_PASSWD_LEN, 1) == 0) {
						exit_code(0);
					}
				}
				else {
					password=str_alloc(strlen(optarg) + 1);
					strncpy(password, optarg, strlen(optarg));
				}
				break;
			case 'A':
				timing=str_to_int(optarg);
				break;
			case 'b':
				namebeg=str_to_int(optarg);
				break;
			case 'B':
				mes_body=str_alloc(strlen(optarg) + 1);
				strncpy(mes_body, optarg, strlen(optarg));
				break;
			case 'c':
				backup=str_alloc(strlen(optarg)+1);
				strncpy(backup, optarg, strlen(optarg));
				parse_uri(backup, &scheme, &user, &host, &port);
				if (scheme  == NULL) {
					fprintf(stderr, "error: missing scheme in From URI\n");
					exit_code(2);
				}
				else if (user == NULL) {
					fprintf(stderr, "error: missing username in From URI\n");
					exit_code(2);
				}
				else if (host == NULL) {
					fprintf(stderr, "error: missing host in From URI\n");
					exit_code(2);
				}
				else {
					from_uri=str_alloc(strlen(optarg)+1);
					strncpy(from_uri, optarg, strlen(optarg));
				}
				free(backup);
				break;
			case 'C':
				if ((strlen(optarg) == 5 && STRNCASECMP(optarg, "empty", 5) == 0) || 
					(strlen(optarg) == 4 && STRNCASECMP(optarg, "none", 4) == 0)) {
					empty_contact = 1;
				}
				else if (strlen(optarg) == 1 && STRNCASECMP(optarg, "*", 1) == 0) {
					contact_uri=str_alloc(strlen(optarg)+1);
					strncpy(contact_uri, optarg, strlen(optarg));
				}
				else {
					backup=str_alloc(strlen(optarg)+1);
					strncpy(backup, optarg, strlen(optarg));
					parse_uri(backup, &scheme, &user, &host, &port);
					if (scheme == NULL) {
					    fprintf(stderr, "error: REGISTER Contact uri doesn't not contain "
						   "sip:, sips:, *, or is not empty\n");
				    	exit_code(2);
					}
					else if (user == NULL) {
						fprintf(stderr, "error: missing username in Contact uri\n");
						exit_code(2);
					}
					else if (host == NULL) {
						fprintf(stderr, "error: missing host in Contact uri\n");
						exit_code(2);
					}
					else {
						contact_uri=str_alloc(strlen(optarg)+1);
						strncpy(contact_uri, optarg, strlen(optarg));
					}
					free(backup);
				}
				break;
			case 'd':
				redirects=0;
				break;
			case 'D':
				inv_final = str_to_int(optarg) * SIP_T1;
				break;
			case 'e':
				nameend=str_to_int(optarg);
				break;
			case 'E':
				if (strlen(optarg) == 3 && 
					STRNCASECMP(optarg, "udp", 3) == 0) {
					transport = SIP_UDP_TRANSPORT;
				}
				else if (strlen(optarg) == 3 &&
						STRNCASECMP(optarg, "tcp", 3) == 0) {
					transport = SIP_TCP_TRANSPORT;
				}
				else if (strlen(optarg) == 3 &&
						STRNCASECMP(optarg, "tls", 3) == 0) {
					fprintf(stderr, "error: TLS is not supported yet, supported values: udp, tcp\n");
					exit_code(2);
					transport = SIP_TLS_TRANSPORT;
				}
				else {
					fprintf(stderr, "error: unsupported transport '%s', supported values: udp, tcp\n", optarg);
					exit_code(2);
				}
				break;
			case 'F':
				flood=1;
				break;
			case 'f':
				if (strlen(optarg) != 1 && STRNCASECMP(optarg, "-", 1) != 0) {
					/* file is opened in binary mode so that the cr-lf is 
					   preserved */
					pf = fopen(optarg, "rb");
					if (!pf){
						fprintf(stderr, "error: unable to open the file '%s'.\n", optarg);
						exit_code(2);
					}
					if (fread(buff, 1, sizeof(buff), pf) >= sizeof(buff)){
						fprintf(stderr, "error:the file is too big. try files of less "
							"than %i bytes.\n", BUFSIZE);
						fprintf(stderr, "      or recompile the program with bigger "
							"BUFSIZE defined.\n");
						exit_code(2);
					}
					fclose(pf);
				}
				else if (strlen(optarg) == 1 && STRNCASECMP(optarg, "-", 1) == 0) {
					if (read_stdin(&buff[0], sizeof(buff), 0) == 0) {
						exit_code(0);
					}
				}
				else {
					fprintf(stderr, "error: unable to handle input file name: %s\n", optarg);
					exit_code(2);
				}
				file_b=1;
				break;
			case 'g':
				replace_str=optarg;
				break;
			case 'G':
				replace_b=1;
				break;
			case 'h':
				print_help();
				break;
			case 'H':
				hostname=optarg;
				break;
			case 'i':
				via_ins=0;
				break;
			case 'I':
				invite=1;
				break;
			case 'j':
				headers=optarg;
				break;
			case 'l':
				lport=str_to_int(optarg);
				break;
			case 'L':
				fix_crlf=0;
				break;
			case 'm':
				maxforw=str_to_int(optarg);
				break;
			case 'M':
				message=1;
				break;
			case 'n':
				numeric = 0;
				break;
			case 'N':
				exit_mode=EM_NAGIOS;
				break;
			case 'o':
				sleep_ms = 0;
				if (strlen(optarg) == 4 && STRNCASECMP(optarg, "rand", 4) == 0) {
					sleep_ms = -2;
				}
				else {
					sleep_ms = str_to_int(optarg);
				}
				break;
			case 'O':
				con_dis=str_alloc(strlen(optarg) + 1);
				strncpy(con_dis, optarg, strlen(optarg));
				break;
			case 'p':
				parse_uri(optarg, &scheme, &user, &host, &rport);
				if (host == NULL) {
					fprintf(stderr, "error: missing in host in outbound proxy\n");
					exit_code(2);
				}
				if (is_ip(host)) {
					address = getaddress(host);
					if (transport == 0)
						transport = SIP_UDP_TRANSPORT;
				}
				else {
					if (!rport) {
						address = getsrvadr(host, &rport, &tsp);
						if (tsp != 0)
							transport = tsp;
					}
					if (!address) {
						address = getaddress(host);
						if (address && verbose > 1)
							printf("using A record: %s\n", host);
					}
					if (!address){
						fprintf(stderr, "error:unable to determine the outbound proxy "
							"address\n");
						exit_code(2);
					}
				}
				outbound_proxy=1;
				break;
			case 'P':
				processes=str_to_int(optarg);
				break;
			case 'q':
				if (re) {
					/* previously allocated -- free */
					regfree(re);
				} else {
					/* never tried -- allocate */
					re=malloc(sizeof(regex_t));
				};
				if (!re) {
					fprintf(stderr, "Error: can't allocate RE\n");
					exit_code(2);
				};
				if (regcomp(re, optarg, REG_EXTENDED|REG_ICASE|REG_NEWLINE )!=0) {
					fprintf(stderr, "Error: compiling RE: %s\n", optarg );
					exit_code(2);
				};
				break;
			case 'r':
				port = 0;
				port=str_to_int(optarg);
				if (rport) {
					fprintf(stderr, "warning: you are overwritting the destination port with the r argument\n");
				}
				rport = port;
				break;
			case 'R':
				randtrash=1;
				break;
			case 's':
				parse_uri(optarg, &scheme, &user, &host, &port);
				if (scheme == NULL) {
					fprintf(stderr, "error: missing scheme in sip uri\n");
					exit_code(2);
				}
				if (strlen(optarg) == 4 && STRNCASECMP(optarg,"sips",4) == 0){
					fprintf(stderr, "error: sips is not supported yet\n");
					exit_code(2);
				}
				else if (strlen(optarg) != 3 || STRNCASECMP(optarg,"sip",3) != 0){
					fprintf(stderr, "error: scheme of sip uri has to be sip\n");
					exit_code(2);
				}
				if (user != NULL) {
					username = user;
				}
				if (host != NULL) {
					domainname = host;
				}
				else {
					fprintf(stderr, "error: missing hostname in sip uri\n");
					exit_code(2);
				}
				if (port && !rport) {
					rport = port;
				}
				if (is_ip(domainname)) {
					address = getaddress(domainname);
					if (transport == 0)
						transport = SIP_UDP_TRANSPORT;
				}
				else {
					if (!rport && !address) {
						address = getsrvadr(domainname, &rport, &tsp);
						if (tsp != 0)
							transport = tsp;
					}
					if (!address) {
						address = getaddress(domainname);
						if (address && verbose > 1)
							printf("using A record: %s\n", domainname);
					}
					if (!address){
						fprintf(stderr, "error:unable to determine the IP address for: %s\n", domainname);
						exit_code(2);
					}
				}
				if (port != 0) {
					backup = str_alloc(strlen(domainname)+1+6);
					snprintf(backup, strlen(domainname)+6, "%s:%i", domainname, port);
					domainname = backup;
				}
				uri_b=1;
				break;
			case 'S':
				fprintf(stderr, "warning: symmetric does not work with a-symmetric servers\n");
				symmetric=1;
				break;
			case 't':
				trashchar=str_to_int(optarg);
				break;
			case 'T':
				trace=1;
				break;
			case 'U':
				usrloc=1;
				break;
			case 'u':
				auth_username=str_alloc(strlen(optarg) + 1);
				strncpy(auth_username, optarg, strlen(optarg));
				break;
			case 'v':
				verbose++;
				break;
			case 'V':
				printf("sipsak %s  by Nils Ohlmeier\n Copyright (C) 2002-2004"
						" FhG Fokus\n Copyright (C) 2004-2005 Nils Ohlmeier\n", 
						SIPSAK_VERSION);
				printf(" compiled with DEFAULT_TIMEOUT=%i, FQDN_SIZE=%i",
						DEFAULT_TIMEOUT, FQDN_SIZE);
#ifdef RAW_SUPPORT
				printf(", RAW_SUPPORT");
#endif
#ifdef HAVE_GETOPT_LONG
				printf(", LONG_OPTS");
#endif
#ifdef HAVE_GNUTLS
				printf(", GNUTLS_MD5");
#else
# ifdef HAVE_FULL_OPENSSL
				printf(", OPENSSL_MD5");
# else
				printf(", INTERNAL_MD5");
# endif
#endif
#ifdef HAVE_OPENSSL_SHA1
				printf(", OPENSSL_SHA1");
#endif
#ifdef HAVE_CARES_H
				printf(", SRV_SUPPORT(ARES)");
#else
# ifdef HAVE_RULI_H
				printf(", SRV_SUPPORT(RULI)");
# endif
#endif
#ifdef HAVE_STRCASESTR
				printf(", STR_CASE_INSENSITIVE");
#endif
#ifdef HAVE_STRNCASECMP
				printf(", CMP_CASE_INSENSITIVE");
#endif
				printf("\n");
				exit_code(0);
				break;
			case 'w':
				warning_ext=1;
				break;
			case 'W':
				nagios_warn = str_to_int(optarg);
				break;
			case 'x':
				expires_t=str_to_int(optarg);
				break;
#ifdef HAVE_GETOPT_LONG
			case 'X':
				print_long_help();
				break;
#endif
			case 'z':
				rand_rem=str_to_int(optarg);
				if (rand_rem < 0 || rand_rem > 100) {
					fprintf(stderr, "error: z option must between 0 and 100\n");
					exit_code(2);
				}
				break;
			default:
				fprintf(stderr, "error: unknown parameter %c\n", c);
				exit_code(2);
				break;
		}
	}

	if (rport == 0) {
		rport =  5060;
	}
	if (rport > 65535 || rport <= 0) {
		fprintf(stderr, "error: invalid remote port: %i\n", rport);
		exit_code(2);
	}
	if (transport == 0) {
		transport = SIP_UDP_TRANSPORT;
	}

	/* replace LF with CRLF if we read from a file */
	if ((file_b) && (fix_crlf)) {
		insert_cr(buff);
	}
	if (headers) {
		backup = str_alloc(strlen(headers) + 30); // FIXME
		strcpy(backup, headers);
		headers = backup;
		replace_string(headers, "\\n", "\r\n");
		backup = headers + strlen(headers) - 1;
		if (*backup != '\n') {
			strcpy(backup + 1, "\r\n");
		}
		if (file_b)
			insert_header(buff, headers, 1);
	}
	/* lots of conditions to check */
	if (trace) {
		if (usrloc || flood || randtrash) {
			fprintf(stderr, "error: trace can't be combined with usrloc, random or "
				"flood\n");
			exit_code(2);
		}
		if (!uri_b) {
			fprintf(stderr, "error: for trace mode a SIPURI is realy needed\n");
			exit_code(2);
		}
		if (file_b) {
			fprintf(stderr, "warning: file will be ignored for tracing.");
		}
		if (!username) {
			fprintf(stderr, "error: for trace mode without a file the SIPURI have to "
				"contain a username\n");
			exit_code(2);
		}
		if (!via_ins){
			fprintf(stderr, "warning: Via-Line is needed for tracing. Ignoring -i\n");
			via_ins=1;
		}
		if (!warning_ext) {
			fprintf(stderr, "warning: IP extract from warning activated to be more "
				"informational\n");
			warning_ext=1;
		}
		if (maxforw==-1) maxforw=255;
	}
	else if (usrloc || invite || message) {
		if (trace || flood || randtrash) {
			fprintf(stderr, "error: usrloc can't be combined with trace, random or "
				"flood\n");
			exit_code(2);
		}
		if (!username || !uri_b) {
			fprintf(stderr, "error: for the USRLOC mode you have to give a SIPURI with "
				"a username\n       at least\n");
			exit_code(2);
		}
		if (namebeg>0 && nameend==-1) {
			fprintf(stderr, "error: if a starting numbers is given also an ending "
				"number have to be specified\n");
			exit_code(2);
		}
		if (invite && message) {
			fprintf(stderr, "error: invite and message tests are XOR\n");
			exit_code(2);
		}
		if (!usrloc && invite && !lport) {
			fprintf(stderr, "warning: Do NOT use the usrloc invite mode without "
				"registering sipsak before.\n         See man page for "
				"details.\n");
			exit_code(2);
		}
		if (contact_uri!=NULL) {
			if (invite || message) {
				fprintf(stderr, "error: Contact uri is not support for invites or "
					"messages\n");
				exit_code(2);
			}
			if (nameend!=-1 || namebeg!=-1) {
				fprintf(stderr, "warning: ignoring starting or ending number if Contact"
					" is given\n");
				nameend=namebeg=0;
			}
			if (rand_rem) {
				fprintf(stderr, "warning: ignoring -z option when Contact is given\n");
				rand_rem=0;
			}
		}
		if (via_ins) {
			fprintf(stderr, "warning: ignoring -i option when in usrloc mode\n");
			via_ins=0;
		}
		if (nameend==-1)
			nameend=0;
		if (namebeg==-1)
			namebeg=0;
	}
	else if (flood) {
		if (trace || usrloc || randtrash) {
			fprintf(stderr, "error: flood can't be combined with trace, random or "
				"usrloc\n");
			exit_code(2);
		}
		if (!uri_b) {
			fprintf(stderr, "error: we need at least a sip uri for flood\n");
			exit_code(2);
		}
		if (redirects) {
			fprintf(stderr, "warning: redirects are not expected in flood. "
				"disableing\n");
			redirects=0;
		}
	}
	else if (randtrash) {
		if (trace || usrloc || flood) {
			fprintf(stderr, "error: random can't be combined with trace, flood or "
				"usrloc\n");
			exit_code(2);
		}
		if (!uri_b) {
			fprintf(stderr, "error: need at least a sip uri for random\n");
			exit_code(2);
		}
		if (redirects) {
			fprintf(stderr, "warning: redirects are not expected in random. "
				"disableing\n");
			redirects=0;
		}
		if (verbose) {
			fprintf(stderr, "warning: random characters may destroy your terminal "
				"output\n");
		}
	}
	else if (mes_body) {
		if (!message) {
			fprintf(stderr, "warning: to send a message mode (-M) is required. activating\n");
			message=1;
		}
		if (!uri_b) {
			fprintf(stderr, "error: need at least a sip uri to send a meesage\n");
			exit_code(2);
		}
		if (nameend==-1)
			nameend=0;
		if (namebeg==-1)
			namebeg=0;
	}
	else {
		if (!uri_b) {
			fprintf(stderr, "error: a spi uri is needed at least\n");
			exit_code(2);
		}
	}

	switch (transport) {
		case SIP_TLS_TRANSPORT:
			transport_str = TRANSPORT_TLS_STR;
			break;
		case SIP_TCP_TRANSPORT:
			transport_str = TRANSPORT_TCP_STR;
			break;
		case SIP_UDP_TRANSPORT:
			transport_str = TRANSPORT_UDP_STR;
			break;
		default:
			fprintf(stderr, "unknown transport: %i\n", transport);
			exit_code(2);
	}

	/* determine our hostname */
	get_fqdn();
	
	/* this is not a cryptographic random number generator,
	   but hey this is only a test-tool => should be satisfying*/
	srand(time(0) ^ getpid());
	
	if (processes > 1) {
		if (signal(SIGCHLD , sigchld_handler)  == SIG_ERR ) {
			fprintf(stderr, "error: Could not install SIGCHLD handler\n");
			exit_code(2);
		}
	}

	for(i = 0; i < processes - 1; i++) {
		if ((pid = fork()) < 0) {
			fprintf(stderr, "error: Cannot fork\n");
			exit_code(2);
		}
		
		if (pid == 0){
	    	/* child */
			upp = (nameend - namebeg + 1) / processes;
			namebeg = namebeg + upp * i;
			nameend = namebeg + upp;
			shoot(&buff[0], sizeof(buff));
		} else {
			if (lport) {
				lport++;
			}
		}
		
		/* Delay execution of children so that the
		 * time of the first transmission gets spread over
		 * the retransmission interval evenly
		 */
		ts.tv_sec = 0;
		ts.tv_nsec = (float)DEFAULT_TIMEOUT / (float)processes * (float)1000 * (float)1000;
		nanosleep(&ts, 0);
	}

	/* here we go...*/
	if (processes > 1) {
		upp = (nameend - namebeg + 1) / processes;
		namebeg = namebeg + upp * i;
		nameend = namebeg + upp;
	}
	shoot(&buff[0], sizeof(buff));

	/* normaly we won't come back here, but to satisfy the compiler */
	return 0;
}
コード例 #2
0
ファイル: main.c プロジェクト: f4exb/tnc1101
// ------------------------------------------------------------------------------------------------
int main (int argc, char **argv)
// ------------------------------------------------------------------------------------------------
{
    int i, nbytes;

    // unsolicited termination handling
    struct sigaction sa;
    // Catch all signals possible on process exit!
    for (i = 1; i < 64; i++) 
    {
        // skip SIGUSR2 for Wiring Pi
        if (i == 17)
            continue; 

        // These are uncatchable or harmless or we want a core dump (SEGV) 
        if (i != SIGKILL
            && i != SIGSEGV
            && i != SIGSTOP
            && i != SIGVTALRM
            && i != SIGWINCH
            && i != SIGPROF) 
        {
            memset(&sa, 0, sizeof(sa));
            sa.sa_handler = terminate;
            sigaction(i, &sa, NULL);
        }
    }

    // Set argument defaults
    init_args(&arguments); 

    // Parse arguments 
    argp_parse (&argp, argc, argv, 0, 0, &arguments);

    if (arguments.print_long_help)
    {
        print_long_help();
        return 0;
    }
    
    if (!arguments.usbacm_device)
    {
        arguments.usbacm_device = strdup("/dev/ttyACM2");
    }
    
    if (!arguments.serial_device)
    {
        arguments.serial_device = strdup("/var/ax25/axp2");
    }
    
    if (!arguments.bulk_filename)
    {
        arguments.bulk_filename = strdup("-");
    }

    set_serial_parameters(&serial_parms_ax25, arguments.serial_device, get_serial_speed(arguments.serial_speed, &arguments.serial_speed_n));
    set_serial_parameters(&serial_parms_usb,  arguments.usbacm_device, get_serial_speed(115200, &arguments.usb_speed_n));
    init_radio_parms(&radio_parms, &arguments);

    if (arguments.verbose_level > 0)
    {
        print_args(&arguments);
        print_radio_parms(&radio_parms);
        fprintf(stderr, "\n");
    }

    if (arguments.tnc_mode == TNC_KISS)
    {
        kiss_init(&arguments);
        kiss_run(&serial_parms_ax25, &serial_parms_usb, &radio_parms, &arguments);
    }
    else if (arguments.tnc_mode == TNC_SLIP)
    {
        arguments.slip = 1;
        kiss_init(&arguments);
        kiss_run(&serial_parms_ax25, &serial_parms_usb, &radio_parms, &arguments);
    }
    else if (arguments.tnc_mode == TNC_TEST_USB_ECHO) // This one does not need any access to the radio
    {
        usb_test_echo(&serial_parms_usb, &arguments);
    }
    else if (arguments.tnc_mode == TNC_RADIO_STATUS) 
    {
        print_radio_status(&serial_parms_usb, &arguments);
    }
    else if (arguments.tnc_mode == TNC_RADIO_INIT)
    {
        init_radio(&serial_parms_usb, &radio_parms, &arguments);

        if (nbytes < 0)
        {
            fprintf(stderr, "Error\n");
        }
    }
    else if (arguments.tnc_mode == TNC_TEST_TX)
    {
        radio_transmit_test(&serial_parms_usb, &radio_parms, &arguments);
    }
    else if (arguments.tnc_mode == TNC_TEST_RX)
    {
        radio_receive_test(&serial_parms_usb, &radio_parms, &arguments);
    }
    else if (arguments.tnc_mode == TNC_TEST_ECHO_TX)
    {
        radio_echo_test(&serial_parms_usb, &radio_parms, &arguments, 1);
    } 
    else if (arguments.tnc_mode == TNC_TEST_ECHO_RX)
    {
        radio_echo_test(&serial_parms_usb, &radio_parms, &arguments, 0);
    }
    else if (arguments.tnc_mode == TNC_TEST_TX_PACKET)
    {
        radio_packet_transmit_test(&serial_parms_usb, &radio_parms, &arguments);
    }
    else if (arguments.tnc_mode == TNC_TEST_RX_PACKET)
    {
        radio_packet_receive_test(&serial_parms_usb, &radio_parms, &arguments);
    }
    else if (arguments.tnc_mode == TNC_TEST_RX_PACKET_NON_BLOCKING)
    {
        radio_packet_receive_nb_test(&serial_parms_usb, &radio_parms, &arguments);
    }
    else if (arguments.tnc_mode == TNC_BULK_TX)
    {
        file_bulk_transmit(&serial_parms_usb, &radio_parms, &arguments);
    }
    else if (arguments.tnc_mode == TNC_BULK_RX)
    {
        file_bulk_receive(&serial_parms_usb, &radio_parms, &arguments);
    }

    close_serial(&serial_parms_usb);
    close_serial(&serial_parms_ax25);
    delete_args(&arguments);
    return 0;
}
コード例 #3
0
ファイル: sipsak.c プロジェクト: BackupTheBerlios/sipsak-svn
int main(int argc, char *argv[])
{
	FILE	*pf;
	char	buff[BUFSIZE];
	int	length, c, i, j;
	char	*delim, *delim2;
	pid_t 	pid;
	struct timespec ts;
	int 	upp;

#ifdef HAVE_GETOPT_LONG
	int option_index = 0;
	static struct option l_opts[] = {
		{"help", 0, 0, 'X'},
		{"version", 0, 0, 'V'},
		{"filename", 1, 0, 'f'},
		{"sip-uri", 1, 0, 's'},
		{"traceroute-mode", 0, 0, 'T'},
		{"usrloc-mode", 0, 0, 'U'},
		{"invite-mode", 0, 0, 'I'},
		{"message-mode", 0, 0, 'M'},
		{"contact", 1, 0, 'C'},
		{"appendix-begin", 1, 0, 'b'},
		{"appendix-end", 1, 0, 'e'},
		{"sleep", 1, 0, 'o'},
		{"expires", 1, 0, 'x'},
		{"remove-bindings", 0, 0, 'z'},
		{"flood-mode", 0, 0, 'F'},
		{"cseq-max", 1, 0, 'c'},
		{"random-mode", 0, 0, 'R'},
		{"trash-chars", 1, 0, 't'},
		{"local-port", 1, 0, 'l'},
		{"remote-port", 1, 0, 'r'},
		{"outbound-proxy", 1, 0, 'p'},
		{"hostname", 1, 0, 'H'},
		{"max-fowards", 1, 0, 'm'},
		{"numeric", 0, 0, 'n'},
		{"no-via", 0, 0, 'i'},
		{"password", 1, 0, 'a'},
		{"ignore-redirects", 0, 0, 'd'},
		{"verbose", 0, 0, 'v'},
		{"extract-ip", 0, 0, 'w'},
		{"replace-string", 0, 0, 'g'},
		{"replace", 0, 0, 'G'},
		{"nagios-code", 0, 0, 'N'},
		{"nagios-warn", 1, 0, 'W'},
		{"search", 1, 0, 'q'},
		{"message-body", 1, 0, 'B'},
		{"disposition", 1, 0, 'O'},
		{"processes", 1, 0, 'P'},
		{"auth-username", 1, 0, 'u'},
		{"no-crlf", 0, 0, 'L'},
		{"timing", 0, 0, 'A'},
		{0, 0, 0, 0}
	};
#endif
	/* some initialisation to be shure */
	file_b=uri_b=trace=lport=usrloc=flood=verbose=randtrash=trashchar = 0;
	warning_ext=rand_rem=nonce_count=replace_b=invite=message = 0;
	sleep_ms=empty_contact=nagios_warn=timing = 0;
	namebeg=nameend=maxforw= -1;
	numeric=via_ins=redirects=fix_crlf=processes  = 1;
	username=password=replace_str=hostname=contact_uri=mes_body = NULL;
	con_dis=auth_username = NULL;
	re = NULL;
	address = 0;
	rport = 5060;
	expires_t = USRLOC_EXP_DEF;
	memset(buff, 0, BUFSIZE);
	memset(confirm, 0, BUFSIZE);
	memset(ack, 0, BUFSIZE);
	memset(fqdn, 0, FQDN_SIZE);
	memset(messusern, 0, FQDN_SIZE);

	if (argc==1) print_help();

	/* lots of command line switches to handle*/
#ifdef HAVE_GETOPT_LONG
	while ((c=getopt_long(argc, argv, "a:AB:b:c:C:de:f:Fg:GhH:iIl:Lm:MnNo:O:p:P:q:r:Rs:t:Tu:UvVwW:x:z", l_opts, &option_index)) != EOF){
#else
	while ((c=getopt(argc,argv,"a:AB:b:c:C:de:f:Fg:GhH:iIl:Lm:MnNo:O:p:P:q:r:Rs:t:Tu:UvVwW:x:z")) != EOF){
#endif
		switch(c){
			case 'a':
				password=malloc(strlen(optarg));
				strncpy(password, optarg, strlen(optarg));
				*(password+strlen(optarg)) = '\0';
				break;
			case 'A':
				timing=1;
				break;
			case 'b':
				if ((namebeg=atoi(optarg))==-1) {
					printf("error: non-numerical appendix begin for the "
						"username\n");
					exit_code(2);
				}
				break;
			case 'B':
				mes_body=malloc(strlen(optarg));
				strncpy(mes_body, optarg, strlen(optarg));
				*(mes_body+strlen(optarg)) = '\0';
				break;
			case 'C':
				if (!strncmp(optarg, "empty", 5) || !strncmp(optarg, "none", 4)) {
					empty_contact = 1;
				}
				else if (((delim=STRSTR(optarg,"sip:"))!=NULL) ||
					((delim=STRSTR(optarg,"sips:"))!=NULL)) {
			 		if (strchr(optarg,'@')<delim) {
						printf("error: missing '@' in Contact uri\n");
						exit_code(2);
					}
					else {
						contact_uri=malloc(strlen(optarg)+1);
						memset(contact_uri, 0, strlen(optarg)+1);
						strncpy(contact_uri, optarg, strlen(optarg));
					}
				}
				else if ((strlen(optarg)==1) && (!strncmp(optarg, "*", 1))) {
					contact_uri=malloc(strlen(optarg)+1);
					memset(contact_uri, 0, strlen(optarg)+1);
					strncpy(contact_uri, optarg, strlen(optarg));
				}
				else{
				    printf("error: REGISTER Contact uri doesn't not contain "
					   "sip:, *, or is not empty\n");
				    exit_code(2);
				}
				break;
			case 'c':
				if ((namebeg=atoi(optarg))==-1) {
					printf("error: non-numerical CSeq maximum\n");
					exit_code(2);
				}
				break;
			case 'd':
				redirects=0;
				break;
			case 'e':
				if ((nameend=atoi(optarg))==-1) {
					printf("error: non-numerical appendix end for the "
						"username\n");
					exit_code(2);
				}
				break;
			case 'F':
				flood=1;
				break;
			case 'f':
				if (strncmp(optarg, "-", 1)) {
					/* file is opened in binary mode so that the cr-lf is 
					   preserved */
					pf = fopen(optarg, "rb");
					if (!pf){
						printf("error: unable to open the file '%s'.\n", optarg);
						exit_code(2);
					}
					length  = fread(buff, 1, sizeof(buff), pf);
					if (length >= sizeof(buff)){
						printf("error:the file is too big. try files of less "
							"than %i bytes.\n", BUFSIZE);
						printf("      or recompile the program with bigger "
							"BUFSIZE defined.\n");
						exit_code(2);
					}
					fclose(pf);
				}
				else {
					for(i = 0; i < BUFSIZE - 1; i++) {
						j = getchar();
						if (j == EOF)
							break;
						else
							buff[i] = j;
					}
					length = i;
				}
				buff[length] = '\0';
				file_b=1;
				break;
			case 'g':
				replace_str=optarg;
				break;
			case 'G':
				replace_b=1;
				break;
			case 'h':
				print_help();
				break;
			case 'H':
				hostname=optarg;
				break;
			case 'i':
				via_ins=0;
				break;
			case 'I':
				invite=1;
				break;
			case 'l':
				lport=atoi(optarg);
				if (!lport) {
					printf("error: non-numerical local port number");
					exit_code(2);
				}
				break;
			case 'L':
				fix_crlf=0;
				break;
			case 'm':
				maxforw=atoi(optarg);
				if (maxforw==-1) {
					printf("error: non-numerical number of max-forwards\n");
					exit_code(2);
				}
				break;
			case 'M':
				message=1;
				break;
			case 'n':
				numeric = 0;
				break;
			case 'N':
				exit_mode=EM_NAGIOS;
				break;
			case 'o':
				sleep_ms = 0;
				if (strncmp(optarg, "rand", 4)==0) {
					sleep_ms = -2;
				}
				else {
					sleep_ms = atoi(optarg);
					if (!sleep_ms) {
						printf("error: non-numerical sleep value\n");
						exit_code(2);
					}
				}
				break;
			case 'O':
				con_dis=malloc(strlen(optarg));
				strncpy(con_dis, optarg, strlen(optarg));
				*(con_dis+strlen(optarg)) = '\0';
				break;
			case 'p':
				address = getaddress(optarg);
				break;
		        case 'P':
				processes=atoi(optarg);
				if (!processes) {
					printf("error: non-numerical number of processes\n");
					exit_code(2);
				}
				break;
			case 'q':
				if (re) {
					/* previously allocated -- free */
					regfree(re);
				} else {
					/* never tried -- allocate */
					re=malloc(sizeof(regex_t));
				};
				if (!re) {
					fprintf(stderr, "Error: can't allocate RE\n");
					exit_code(2);
				};
				if (regcomp(re, optarg, REG_EXTENDED|REG_ICASE|REG_NEWLINE )!=0) {
					fprintf(stderr, "Error: compiling RE: %s\n", optarg );
					exit_code(2);
				};
				break;
			case 'r':
				rport=atoi(optarg);
				if (!rport) {
					printf("error: non-numerical remote port number\n");
					exit_code(2);
				}
				break;
			case 'R':
				randtrash=1;
				break;
			case 's':
				/* we try to extract as much informationas we can from the uri*/
				if (!strncmp(optarg,"sip",3)){
					if ((delim=strchr(optarg,':'))!=NULL){
						delim++;
						if ((delim2=strchr(delim,'@'))!=NULL){
							username=malloc(delim2-delim+1);
							strncpy(username, delim, delim2-delim);
							*(username+(delim2-delim)) = '\0';
							delim2++;
							delim=delim2;
						}
						if ((delim2=strchr(delim,':'))!=NULL){
							domainname=malloc(strlen(delim)+1);
							strncpy(domainname, delim, strlen(delim));
							*(domainname+strlen(delim)) = '\0';
							*delim2 = '\0';
							delim2++;
							rport = atoi(delim2);
							if (!rport) {
								printf("error: non-numerical remote port "
									"number\n");
								exit_code(2);
							}
						}
						else {
							domainname=malloc(strlen(delim)+1);
							strncpy(domainname, delim, strlen(delim));
							*(domainname+strlen(delim)) = '\0';
						}
						if (!address)
							address = getaddress(delim);
						if (!address){
							printf("error:unable to determine the remote host "
								"address\n");
							exit_code(2);
						}
					}
					else{
						printf("error: SIPURI doesn't contain a : ?!\n");
						exit_code(2);
					}
				}
				else{
					printf("error: SIPURI doesn't not begin with sip\n");
					exit_code(2);
				}
				uri_b=1;
				break;			break;
			case 't':
				trashchar=atoi(optarg);
				if (!trashchar) {
					printf("error: non-numerical number of trashed "
						"character\n");
					exit_code(2);
				}
				break;
			case 'T':
				trace=1;
				break;
			case 'U':
				usrloc=1;
				break;
			case 'u':
				auth_username=malloc(strlen(optarg));
				strncpy(auth_username, optarg, strlen(optarg));
				*(auth_username+strlen(optarg)) = '\0';
				break;
			case 'v':
				verbose++;
				break;
			case 'V':
				printf("sipsak %s  by Nils Ohlmeier\n Copyright (C) 2002-2004"
						" FhG Fokus\n Copyright (C) 2004-2005 Nils Ohlmeier\n", 
						SIPSAK_VERSION);
				printf(" compiled with DEFAULT_RETRYS=%i, DEFAULT_TIMEOUT=%i, FQDN_SIZE=%i",
						DEFAULT_RETRYS, DEFAULT_TIMEOUT, FQDN_SIZE);
#ifdef RAW_SUPPORT
				printf(", RAW_SUPPORT");
#endif
#ifdef HAVE_GETOPT_LONG
				printf(", LONG_OPTS");
#endif
				printf("\n");
				exit_code(0);
				break;
			case 'w':
				warning_ext=1;
				break;
			case 'W':
				nagios_warn = atoi(optarg);
				break;
			case 'x':
				expires_t=atoi(optarg);
				break;
#ifdef HAVE_GETOPT_LONG
			case 'X':
				print_long_help();
				break;
#endif
			case 'z':
				rand_rem=1;
				break;
			default:
				printf("error: unknown parameter %c\n", c);
				exit_code(2);
				break;
		}
	}

	/* replace LF with CRLF if we read from a file */
	if ((file_b) && (fix_crlf)) {
		insert_cr(buff);
	}
	/* lots of conditions to check */
	if (trace) {
		if (usrloc || flood || randtrash) {
			printf("error: trace can't be combined with usrloc, random or "
				"flood\n");
			exit_code(2);
		}
		if (!uri_b) {
			printf("error: for trace mode a SIPURI is realy needed\n");
			exit_code(2);
		}
		if (file_b) {
			printf("warning: file will be ignored for tracing.");
		}
		if (!username) {
			printf("error: for trace mode without a file the SIPURI have to "
				"contain a username\n");
			exit_code(2);
		}
		if (!via_ins){
			printf("warning: Via-Line is needed for tracing. Ignoring -i\n");
			via_ins=1;
		}
		if (!warning_ext) {
			printf("warning: IP extract from warning activated to be more "
				"informational\n");
			warning_ext=1;
		}
		if (maxforw==-1) maxforw=255;
	}
	else if (usrloc || invite || message) {
		if (trace || flood || randtrash) {
			printf("error: usrloc can't be combined with trace, random or "
				"flood\n");
			exit_code(2);
		}
		if (!username || !uri_b) {
			printf("error: for the USRLOC mode you have to give a SIPURI with "
				"a username\n       at least\n");
			exit_code(2);
		}
		if (namebeg>0 && nameend==-1) {
			printf("error: if a starting numbers is given also an ending "
				"number have to be specified\n");
			exit_code(2);
		}
		if (invite && message) {
			printf("error: invite and message tests are XOR\n");
			exit_code(2);
		}
		if (!usrloc && invite && !lport) {
			printf("WARNING: Do NOT use the usrloc invite mode without "
				"registering sipsak before.\n         See man page for "
				"details.\n");
			exit_code(2);
		}
		if (contact_uri!=NULL) {
			if (invite || message) {
				printf("error: Contact uri is not support for invites or "
					"messages\n");
				exit_code(2);
			}
			if (nameend!=-1 || namebeg!=-1) {
				printf("warning: ignoring starting or ending number if Contact"
					" is given\n");
				nameend=namebeg=0;
			}
			if (rand_rem) {
				printf("warning: ignoring -z option when Contact is given\n");
				rand_rem=0;
			}
		}
		if (via_ins) {
			printf("warning: ignoring -i option when in usrloc mode\n");
			via_ins=0;
		}
		if (nameend==-1)
			nameend=0;
		if (namebeg==-1)
			namebeg=0;
	}
	else if (flood) {
		if (trace || usrloc || randtrash) {
			printf("error: flood can't be combined with trace, random or "
				"usrloc\n");
			exit_code(2);
		}
		if (!uri_b) {
			printf("error: we need at least a sip uri for flood\n");
			exit_code(2);
		}
		if (redirects) {
			printf("warning: redirects are not expected in flood. "
				"disableing\n");
			redirects=0;
		}
	}
	else if (randtrash) {
		if (trace || usrloc || flood) {
			printf("error: random can't be combined with trace, flood or "
				"usrloc\n");
			exit_code(2);
		}
		if (!uri_b) {
			printf("error: need at least a sip uri for random\n");
			exit_code(2);
		}
		if (redirects) {
			printf("warning: redirects are not expected in random. "
				"disableing\n");
			redirects=0;
		}
		if (verbose) {
			printf("warning: random characters may destroy your terminal "
				"output\n");
		}
	}
	else if (mes_body) {
		if (!message) {
			printf("warning: to send a message mode (-M) is required. activating\n");
			message=1;
		}
		if (!uri_b) {
			printf("error: need at least a sip uri to send a meesage\n");
			exit_code(2);
		}
		if (nameend==-1)
			nameend=0;
		if (namebeg==-1)
			namebeg=0;
	}
	else {
		if (!uri_b) {
			printf("error: a spi uri is needed at least\n");
			exit_code(2);
		}
	}
	/* determine our hostname */
	get_fqdn();
	
	/* this is not a cryptographic random number generator,
	   but hey this is only a test-tool => should be satisfying*/
	srand(time(0));
	
	if (processes > 1) {
		if (signal(SIGCHLD , sigchld_handler)  == SIG_ERR ) {
			printf("error: Could not install SIGCHLD handler\n");
			exit_code(2);
		}
	}

	for(i = 0; i < processes - 1; i++) {
		if ((pid = fork()) < 0) {
			printf("error: Cannot fork\n");
			exit_code(2);
		}
		
		if (pid == 0){
	    	/* child */
			upp = (nameend - namebeg + 1) / processes;
			namebeg = namebeg + upp * i;
			nameend = namebeg + upp;
			shoot(buff);
		} else {
			if (lport) {
				lport++;
			}
		}
		
		/* Delay execution of children so that the
		 * time of the first transmission gets spread over
		 * the retransmission interval evenly
		 */
		ts.tv_sec = 0;
		ts.tv_nsec = (float)DEFAULT_TIMEOUT / (float)processes * (float)1000 * (float)1000;
		nanosleep(&ts, 0);
	}

	/* here we go...*/
	if (processes > 1) {
		upp = (nameend - namebeg + 1) / processes;
		namebeg = namebeg + upp * i;
		nameend = namebeg + upp;
	}
	shoot(buff);

	/* normaly we won't come back here, but to satisfy the compiler */
	return 0;
}
コード例 #4
0
ファイル: aften.c プロジェクト: 9060/wavtoac3encoder
int
main(int argc, char **argv)
{
    void (*aften_remap)(void *samples, int n, int ch,
                        A52SampleFormat fmt, int acmod) = NULL;
    uint8_t *frame = NULL;
    FLOAT *fwav = NULL;
    int nr, fs, err;
    FILE *ifp[A52_NUM_SPEAKERS];
    FILE *ofp = NULL;
    PcmContext pf;
    CommandOptions opts;
    AftenContext s;
    uint32_t samplecount, bytecount, t0, t1, percent;
    FLOAT kbps, qual, bw;
    int frame_cnt;
    int input_file_format;
    enum PcmSampleFormat read_format;
    /* update output every 200ms */
    clock_t update_clock_span = (clock_t)(0.2f * CLOCKS_PER_SEC);
    clock_t current_clock;
    clock_t last_update_clock = clock() - update_clock_span;
    int ret_val = 0;
    int i;

    opts.s = &s;
    aften_set_defaults(&s);
    err = parse_commandline(argc, argv, &opts);
    if (err) {
        if (err == 1) {
            print_intro(stderr);
            print_usage(stderr);
            return 1;
        } else {
            print_intro(stdout);
            if (err == 2) {
                print_help(stdout);
            } else if (err == 3) {
                print_long_help(stdout);
            }
            return 0;
        }
    }

    if (s.verbose > 0) {
        print_intro(stderr);
    }

    memset(ifp, 0, A52_NUM_SPEAKERS * sizeof(FILE *));
    for (i = 0; i < opts.num_input_files; i++) {
        if (!strncmp(opts.infile[i], "-", 2)) {
#ifdef _WIN32
            _setmode(_fileno(stdin), _O_BINARY);
#endif
            ifp[i] = stdin;
        } else {
            ifp[i] = fopen(opts.infile[i], "rb");
            if (!ifp[i]) {
                fprintf(stderr, "error opening input file: %s\n", opts.infile[i]);
                goto error_end;
            }
        }
    }

#ifdef CONFIG_DOUBLE
    read_format = PCM_SAMPLE_FMT_DBL;
#else
    read_format = PCM_SAMPLE_FMT_FLT;
#endif

    // initialize pcmfile using input
    input_file_format = PCM_FORMAT_UNKNOWN;
    if (opts.raw_input)
        input_file_format = PCM_FORMAT_RAW;
    if (pcm_init(&pf, opts.num_input_files, ifp, read_format, input_file_format)) {
        fprintf(stderr, "invalid input file(s)\n");
        goto error_end;
    }
    if (opts.read_to_eof)
        pcm_set_read_to_eof(&pf, 1);
    if (opts.raw_input) {
        pcm_set_source_params(&pf, opts.raw_ch, opts.raw_fmt,
                                  opts.raw_order, opts.raw_sr);
    }

    // print wav info to console
    if (s.verbose > 0) {
        fprintf(stderr, "input format: ");
        if (opts.num_input_files > 1)
            fprintf(stderr, "\n");
        pcm_print(&pf, stderr);
    }

    // if acmod is given on commandline, determine lfe from number of channels
    if (s.acmod >= 0) {
        int ch = acmod_to_ch[s.acmod];
        if (ch == pf.channels) {
            if (s.lfe < 0) {
                s.lfe = 0;
            } else {
                if (s.lfe != 0) {
                    fprintf(stderr, "acmod and lfe do not match number of channels\n");
                    goto error_end;
                }
            }
        } else if (ch == (pf.channels - 1)) {
            if (s.lfe < 0) {
                s.lfe = 1;
            } else {
                if (s.lfe != 1) {
                    fprintf(stderr, "acmod and lfe do not match number of channels\n");
                    goto error_end;
                }
            }
        } else {
            fprintf(stderr, "acmod does not match number of channels\n");
            goto error_end;
        }
    } else {
        // if acmod is not given on commandline, determine from WAVE file
        int ch = pf.channels;
        if (s.lfe >= 0) {
            if (s.lfe == 0 && ch == 6) {
                fprintf(stderr, "cannot encode 6 channels w/o LFE\n");
                goto error_end;
            } else if (s.lfe == 1 && ch == 1) {
                fprintf(stderr, "cannot encode LFE channel only\n");
                goto error_end;
            }
            if (s.lfe) {
                pf.ch_mask |= 0x08;
            }
        }
        if (aften_wav_channels_to_acmod(ch, pf.ch_mask, &s.acmod, &s.lfe)) {
            fprintf(stderr, "mismatch in channels, acmod, and lfe params\n");
            goto error_end;
        }
    }
    // set some encoding parameters using wav info
    s.channels = pf.channels;
    s.samplerate = pf.sample_rate;
#ifdef CONFIG_DOUBLE
    s.sample_format = A52_SAMPLE_FMT_DBL;
#else
    s.sample_format = A52_SAMPLE_FMT_FLT;
#endif

    // open output file
    if (!strncmp(opts.outfile, "-", 2)) {
#ifdef _WIN32
        _setmode(_fileno(stdout), _O_BINARY);
#endif
        ofp = stdout;
    } else {
        ofp = fopen(opts.outfile, "wb");
        if (!ofp) {
            fprintf(stderr, "error opening output file: %s\n", opts.outfile);
            goto error_end;
        }
    }

    // print ac3 info to console
    if (s.verbose > 0) {
        fprintf(stderr, "output format: %d Hz %s", s.samplerate,
                acmod_str[s.acmod]);
        if (s.lfe) {
            fprintf(stderr, " + LFE");
        }
        fprintf(stderr, "\n\n");
    }

    // allocate memory for coded frame and sample buffer
    frame = calloc(A52_MAX_CODED_FRAME_SIZE, 1);
    fwav = calloc(A52_SAMPLES_PER_FRAME * s.channels, sizeof(FLOAT));
    if (frame == NULL || fwav == NULL)
        goto error_end;

    samplecount = bytecount = t0 = t1 = percent = 0;
    qual = bw = 0.0;
    frame_cnt = 0;
    fs = 0;
    nr = 0;

    if (opts.chmap == 0)
        aften_remap = aften_remap_wav_to_a52;
    else if (opts.chmap == 2)
        aften_remap = aften_remap_mpeg_to_a52;

    // Don't pad start with zero samples, use input audio instead.
    if (!opts.pad_start) {
        int diff;
        nr = pcm_read_samples(&pf, fwav, 256);
        diff = 256 - nr;
        if (diff > 0) {
            memmove(fwav + diff * s.channels, fwav, nr);
            memset(fwav, 0, diff * s.channels * sizeof(FLOAT));
        }
        if (aften_remap)
            aften_remap(fwav + diff, nr, s.channels, s.sample_format, s.acmod);

        s.initial_samples = fwav;
    }
    // initialize encoder
    if (aften_encode_init(&s)) {
        fprintf(stderr, "error initializing encoder\n");
        goto error_end;
    }
    // print SIMD instructions used
    print_simd_in_use(stderr, &s.system.wanted_simd_instructions);

    // print number of threads used
    fprintf(stderr, "Threads: %i\n\n", s.system.n_threads);

    do {
        nr = pcm_read_samples(&pf, fwav, A52_SAMPLES_PER_FRAME);
        if (aften_remap)
            aften_remap(fwav, nr, s.channels, s.sample_format, s.acmod);

        fs = aften_encode_frame(&s, frame, fwav, nr);

        if (fs < 0) {
            fprintf(stderr, "Error encoding frame %d\n", frame_cnt);
            break;
        } else if (fs > 0) {
            if (s.verbose > 0) {
                samplecount += A52_SAMPLES_PER_FRAME;
                bytecount += fs;
                qual += s.status.quality;
                bw += s.status.bwcode;
                if (s.verbose == 1) {
                    current_clock = clock();
                    if (current_clock - last_update_clock >= update_clock_span) {
                        t1 = samplecount / pf.sample_rate;
                        if (frame_cnt > 0 && (t1 > t0 || samplecount >= pf.samples)) {
                            kbps = (bytecount * FCONST(8.0) * pf.sample_rate) /
                                (FCONST(1000.0) * samplecount);
                            percent = 0;
                            if (pf.samples > 0) {
                                percent = (uint32_t)((samplecount * FCONST(100.0)) /
                                                        pf.samples);
                                percent = CLIP(percent, 0, 100);
                            }
                            fprintf(stderr, "\rprogress: %3u%% | q: %4.1f | "
                                    "bw: %2.1f | bitrate: %4.1f kbps ",
                                    percent, (qual / (frame_cnt+1)),
                                    (bw / (frame_cnt+1)), kbps);
                        }
                        t0 = t1;
                        last_update_clock = current_clock;
                    }
                } else if (s.verbose == 2) {
                    fprintf(stderr, "frame: %7d | q: %4d | bw: %2d | bitrate: %3d kbps\n",
                            frame_cnt, s.status.quality, s.status.bwcode,
                            s.status.bit_rate);
                }
            }
            fwrite(frame, 1, fs, ofp);
            frame_cnt++;
        }
    } while (nr > 0 || fs > 0 || !frame_cnt);

    if (s.verbose >= 1) {
        if (samplecount > 0) {
            kbps = (bytecount * FCONST(8.0) * pf.sample_rate) / (FCONST(1000.0) * samplecount);
        } else {
            kbps = 0;
        }
        frame_cnt = MAX(frame_cnt, 1);
        if (s.verbose == 1) {
            fprintf(stderr, "\rprogress: 100%% | q: %4.1f | bw: %2.1f | bitrate: %4.1f kbps\n\n",
                    (qual / frame_cnt), (bw / frame_cnt), kbps);
        } else if (s.verbose == 2) {
            fprintf(stderr, "\n");
            fprintf(stderr, "average quality:   %4.1f\n", (qual / frame_cnt));
            fprintf(stderr, "average bandwidth: %2.1f\n", (bw / frame_cnt));
            fprintf(stderr, "average bitrate:   %4.1f kbps\n\n", kbps);
        }
    }
    goto end;
error_end:
    ret_val = 1;
end:
    if (fwav)
        free(fwav);

    if (frame)
        free(frame);

        pcm_close(&pf);
    for (i = 0; i < opts.num_input_files; i++) {
        if (ifp[i])
            fclose(ifp[i]);
    }
    if (ofp)
        fclose(ofp);

    if (aften_encode_close(&s))
        return 1;

    return ret_val;
}
コード例 #5
0
ファイル: isl_arg.c プロジェクト: VanirLLVM/toolchain_isl
static void print_help(struct isl_arg *arg,
	struct isl_prefixes *prefixes, void *opt)
{
	int i;
	int any = 0;

	for (i = 0; arg[i].type != isl_arg_end; ++i) {
		if (arg[i].flags & ISL_ARG_HIDDEN)
			continue;
		switch (arg[i].type) {
		case isl_arg_flags:
			print_flags_help(&arg[i], prefixes, opt);
			any = 1;
			break;
		case isl_arg_choice:
			print_choice_help(&arg[i], prefixes, opt);
			any = 1;
			break;
		case isl_arg_bool:
			print_bool_help(&arg[i], prefixes, opt);
			any = 1;
			break;
		case isl_arg_int:
			print_int_help(&arg[i], prefixes, opt);
			any = 1;
			break;
		case isl_arg_long:
			print_long_help(&arg[i], prefixes, opt);
			any = 1;
			break;
		case isl_arg_ulong:
			print_ulong_help(&arg[i], prefixes);
			any = 1;
			break;
		case isl_arg_str:
			print_str_help(&arg[i], prefixes, opt);
			any = 1;
			break;
		case isl_arg_str_list:
			print_str_list_help(&arg[i], prefixes);
			any = 1;
			break;
		case isl_arg_alias:
		case isl_arg_version:
		case isl_arg_arg:
		case isl_arg_footer:
		case isl_arg_child:
		case isl_arg_user:
		case isl_arg_end:
			break;
		}
	}

	for (i = 0; arg[i].type != isl_arg_end; ++i) {
		void *child;
		int first;

		if (arg[i].type != isl_arg_child)
			continue;
		if (arg[i].flags & ISL_ARG_HIDDEN)
			continue;

		if (any)
			printf("\n");
		if (arg[i].help_msg)
			printf(" %s\n", arg[i].help_msg);
		if (arg[i].offset == (size_t) -1)
			child = opt;
		else
			child = *(void **)(((char *) opt) + arg[i].offset);
		first = add_prefix(prefixes, arg[i].long_name);
		print_help(arg[i].u.child.child->args, prefixes, child);
		drop_prefix(prefixes, first);
		any = 1;
	}
}
コード例 #6
0
ファイル: main.c プロジェクト: rickwangtw/lm-sensors
int main(int argc, char *argv[])
{
    int c, i, err, do_bus_list;
    const char *config_file_name = NULL;

    struct option long_opts[] =  {
        { "help", no_argument, NULL, 'h' },
        { "set", no_argument, NULL, 's' },
        { "version", no_argument, NULL, 'v'},
        { "fahrenheit", no_argument, NULL, 'f' },
        { "no-adapter", no_argument, NULL, 'A' },
        { "config-file", required_argument, NULL, 'c' },
        { "bus-list", no_argument, NULL, 'B' },
        { 0, 0, 0, 0 }
    };

    setlocale(LC_CTYPE, "");

    do_raw = 0;
    do_sets = 0;
    do_bus_list = 0;
    hide_adapter = 0;
    while (1) {
        c = getopt_long(argc, argv, "hsvfAc:u", long_opts, NULL);
        if (c == EOF)
            break;
        switch(c) {
        case ':':
        case '?':
            print_short_help();
            exit(1);
        case 'h':
            print_long_help();
            exit(0);
        case 'v':
            print_version();
            exit(0);
        case 'c':
            config_file_name = optarg;
            break;
        case 's':
            do_sets = 1;
            break;
        case 'f':
            fahrenheit = 1;
            break;
        case 'A':
            hide_adapter = 1;
            break;
        case 'u':
            do_raw = 1;
            break;
        case 'B':
            do_bus_list = 1;
            break;
        default:
            fprintf(stderr,
                    "Internal error while parsing options!\n");
            exit(1);
        }
    }

    err = read_config_file(config_file_name);
    if (err)
        exit(err);

    /* build the degrees string */
    set_degstr();

    if (do_bus_list) {
        print_bus_list();
    } else if (optind == argc) { /* No chip name on command line */
        if (!do_the_real_work(NULL, &err)) {
            fprintf(stderr,
                    "No sensors found!\n"
                    "Make sure you loaded all the kernel drivers you need.\n"
                    "Try sensors-detect to find out which these are.\n");
            err = 1;
        }
    } else {
        int cnt = 0;
        sensors_chip_name chip;

        for (i = optind; i < argc; i++) {
            if (sensors_parse_chip_name(argv[i], &chip)) {
                fprintf(stderr,
                        "Parse error in chip name `%s'\n",
                        argv[i]);
                print_short_help();
                err = 1;
                goto exit;
            }
            cnt += do_the_real_work(&chip, &err);
            sensors_free_chip_name(&chip);
        }

        if (!cnt) {
            fprintf(stderr, "Specified sensor(s) not found!\n");
            err = 1;
        }
    }

exit:
    sensors_cleanup();
    exit(err);
}