Example #1
0
static const unsigned char *parse_rr(const unsigned char *aptr, const unsigned char *abuf, int alen) {
	char *name;
	long len;
	int status, type, dnsclass, dlen;
	struct in_addr addr;

	dbg("ca_tmpname: %s\n", ca_tmpname);
	status = ares_expand_name(aptr, abuf, alen, &name, &len);
	if (status != ARES_SUCCESS) {
		printf("error: failed to expand query name\n");
		exit_code(2, __PRETTY_FUNCTION__, "failed to expand query name");
	}
	aptr += len;
	if (aptr + NS_RRFIXEDSZ > abuf + alen) {
		printf("error: not enough data in DNS answer 1\n");
		free(name);
		return NULL;
	}
	type = DNS_RR_TYPE(aptr);
	dnsclass = DNS_RR_CLASS(aptr);
	dlen = DNS_RR_LEN(aptr);
	aptr += NS_RRFIXEDSZ;
	if (aptr + dlen > abuf + alen) {
		printf("error: not enough data in DNS answer 2\n");
		free(name);
		return NULL;
	}
	if (dnsclass != CARES_CLASS_C_IN) {
		printf("error: unsupported dnsclass (%i) in DNS answer\n", dnsclass);
		free(name);
		return NULL;
	}
	if (type != CARES_TYPE_SRV && type != CARES_TYPE_A && type != CARES_TYPE_CNAME) {
		printf("error: unsupported DNS response type (%i)\n", type);
		free(name);
		return NULL;
	}
	if (type == CARES_TYPE_SRV) {
		free(name);
		caport = DNS__16BIT(aptr + 4);
		dbg("caport: %i\n", caport);
		status = ares_expand_name(aptr + 6, abuf, alen, &name, &len);
		if (status != ARES_SUCCESS) {
			printf("error: failed to expand SRV name\n");
			return NULL;
		}
		dbg("SRV name: %s\n", name);
		if (is_ip(name)) {
			caadr = inet_addr(name);
			free(name);
		}
		else {
			ca_tmpname = name;
		}
	}
	else if (type == CARES_TYPE_CNAME) {
		if ((ca_tmpname != NULL) &&
				(STRNCASECMP(ca_tmpname, name, strlen(ca_tmpname)) == 0)) {
			ca_tmpname = malloc(strlen(name));
			if (ca_tmpname == NULL) {
				printf("error: failed to allocate memory\n");
				exit_code(2, __PRETTY_FUNCTION__, "memory allocation failure");
			}
			strcpy(ca_tmpname, name);
			free(name);
		}
		else {
			free(name);
			status = ares_expand_name(aptr, abuf, alen, &name, &len);
			if (status != ARES_SUCCESS) {
				printf("error: failed to expand CNAME\n");
				return NULL;
			}
			dbg("CNAME: %s\n", name);
			if (is_ip(name)) {
				caadr = inet_addr(name);
				free(name);
			}
			else {
				ca_tmpname = name;
			}
		}
	}
	else if (type == CARES_TYPE_A) {
		if (dlen == 4 && STRNCASECMP(ca_tmpname, name, strlen(ca_tmpname)) == 0) {
			memcpy(&addr, aptr, sizeof(struct in_addr));
			caadr = addr.s_addr;
		}
		free(name);
	}
	return aptr + dlen;
}
Example #2
0
int
main(int argc, char *memin[])
{
    int         i,
                rc;
    int         irc;
    int         messages = true,
#ifdef IBMPCCHARS
                box_chars = true;

#else
                box_chars = false;

#endif
    char        indefsfnm[MAX_FILENM_SIZE],
                inloadfnm[MAX_FILENM_SIZE];


    /* set global variables */

    defssw = false;
    defsfnm = NULL;


    initmemsize = dfmemsize;
    quiet = false;
    expansion = true;
    quiet = false;
    nouserinterrupts = false;
    loadsw = false;
    triggered = true;
    debugging_on = true;
    diag_messages_on = false;
    interpreter_running = false;

#ifdef HISTORY
    lasteval = -1;
#endif

#ifdef DEBUG
    debug = false;
#endif

#ifdef PROFILE
    profile = false;
#endif

    /* Export the command line to the rest of the code */
#ifdef CMDLINE
    global_argv = memin;
    global_argc = argc;
#endif

    /* MAJ: the following code is kept in case I decide to go back
       to having the console and cgi versions the same code.
    */


    if (iscgiversion) {
        quiet = true;
        messages = false;
        box_chars = false;
        triggered = false;
        nouserinterrupts = true;
    }

#ifdef UNIXSYS
    initunixsignals();
#endif


    /* process command arguments

       the allowed syntax is:

       [(+|-)size nnnn] [-defs filenm] [-q] [-m] [-b] [-s] [-d] [workspacename] */


    if (iscgiversion)
        /*  This code will allow the cgi version to accept *.nws, *.ndf or
            *.nfm files on the command line.  No other parameters are available.
        */
    {
        if (argc >= 2)
        {   int offset = (memin[1][0] == '\"') ? -1 : 0;
            if (STRNCASECMP((strlen(memin[1]) +
                             memin[1] - 4 + offset), ".NDF", 4) == 0)
            {   /* arg is a Nial definition file name */
                defssw = true;
                strcpy(indefsfnm, memin[1]);
            }
            else if (STRNCASECMP((strlen(memin[1]) +
                                  memin[1] - 4 + offset), ".NWS", 4) == 0)
            {   /* arg is a Nial workspace file name */
                loadsw = true;
                strcpy(inloadfnm, memin[1]);
            }
        }
    }
    else
    {   i = 1;
        while (i < argc) {
            if (strcmp(memin[i], "-size") == 0) {
                /* set iniital size and allow expansion */
                initmemsize = atol(memin[i + 1]);
                if (initmemsize < minmemsize)
                    initmemsize = minmemsize;
                expansion = true;
                i += 2;
            }
            else if (strcmp(memin[i], "+size") == 0) {
                /* set iniital size and disallow expansion */
                initmemsize = atol(memin[i + 1]);
                if (initmemsize < minmemsize)
                    initmemsize = minmemsize;
                expansion = false;
                i += 2;
            }
            else if (strcmp(memin[i], "-defs") == 0) {
                if (i < argc) {
                    /* explicit defs file name given */
                    defssw = true;
                    strcpy(indefsfnm, memin[i + 1]);
                    i += 2;
                }
                else {
                    printf("missing definition file name after -defs option\n");
                    exit(1);
                }
            }
            else if (strcmp(memin[i], "-q") == 0) {
                /* inhibit all output */
                quiet = true;
                i++;
            }
            else if (strcmp(memin[i], "-m") == 0) {
                /* do not display warning messages */
                messages = false;
                i++;
            }
            else if (strcmp(memin[i], "-d") == 0) {
                /* disable Nial level debugging */
                debugging_on = false;
                i++;
            }
            else
#ifdef IBMPCCHARS
                if (strcmp(memin[i], "-b") == 0) {
                    /* do not use the IMB PC box characters */
                    box_chars = false;
                    i++;
                }
                else
#endif
                    if (strcmp(memin[i], "-s") == 0) {
                        /* suppress fault triggering */
                        triggered = false;
                        i++;
                    }
                    else if (strcmp(memin[i], "-h") == 0) {
                        /* display the help syntax and exit */
                        print_syntax();
                        exit(1);
                    }
                    else if (memin[i][0] == '-') {
                        /* invalid command line. display and exit. */
                        printf("invalid command line option: %s", memin[i]);
                        exit(1);
                    }
                    else {
                        /* assume rest of line is a workspace file name */
                        loadsw = true;
                        strcpy(inloadfnm, memin[i]);
                        i++;
                    }
        }
    }

    /* end of code to process arguments */

    /* code to check if we are running a console version under WINDOWS. If we are
       do not attempt to check for the keyboard, since it slows execution
       outrageously. This has been switched out for now. Not needed since DOS version
       no longer supported.
     */

#ifdef OMITTED
    checkkeyboard = (getenv("WINDIR") == NULL ? true : false);
    /* printf("checkkeyboard %d\n", checkkeyboard); */
#endif


    /* set the session variables */

    sessionSettings = NC_CreateSessionSettings();

    CheckErr(NC_SetSessionSetting(sessionSettings,
                                  NC_WORKSPACE_SIZE, initmemsize));
    CheckErr(NC_SetSessionSetting(sessionSettings,
                                  NC_EXPANSION, expansion));
    if (loadsw)
        CheckErr(NC_SetSessionSetting(sessionSettings,
                                      NC_INITIAL_WORKSPACE, (int) inloadfnm));
    if (defssw)
        CheckErr(NC_SetSessionSetting(sessionSettings,
                                      NC_INITIAL_DEFS, (int) indefsfnm));

    CheckErr(NC_SetSessionSetting(sessionSettings,
                                  NC_QUIET, quiet));
    CheckErr(NC_SetSessionSetting(sessionSettings, NC_DEBUGGING_ON, debugging_on));
    CheckErr(NC_SetCheckUserBreak(sessionSettings, myCheckUserBreak));

    windSettings = NC_CreateWindowSettings();

    if (iscgiversion) /* avoid output by having no prompt in CGINIAL */
        CheckErr(NC_SetWindowSetting(windSettings, NC_PROMPT, (int) ""));

    /* The CGINIAL version is given a default 0 screen width setting,
       so no lines are broken.  */

#ifdef WINDOWS_SYS
    /* The following code is added, so that we can accurately set the
       window's width.  */
    {
        CONSOLE_SCREEN_BUFFER_INFO csbi;

        GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
        CheckErr(NC_SetWindowSetting(windSettings, NC_SCREEN_WIDTH,
                                     (iscgiversion ? 0 : ((csbi.srWindow.Right - csbi.srWindow.Left)))));
    }
#else
    CheckErr(NC_SetWindowSetting(windSettings, NC_SCREEN_WIDTH, (iscgiversion ? 0 : 79)));
#endif

    CheckErr(NC_SetWindowSetting(windSettings, NC_TRIGGERED, triggered));
    CheckErr(NC_SetWindowSetting(windSettings, NC_NOUSERINTERRUPTS, nouserinterrupts));

    CheckErr(NC_SetWindowSetting(windSettings, NC_MESSAGES, messages));
    CheckErr(NC_SetWindowSetting(windSettings, NC_BOX_CHARS, box_chars));


#ifdef INTERNAL_BUF_MODE
    theContext = NC_CreateIOContext();
    CheckErr(NC_SetIOMode(theContext, NC_INTERNAL_BUFFER_MODE));
    NC_SetBufferSize(5000, 1000);
#endif


#ifdef IO_MODE
    theContext = NC_CreateIOContext();
    CheckErr(NC_SetIOMode(theContext, NC_IO_MODE));
    CheckErr(NC_SetWriteCommand(theContext, myWrite, stdout));
    CheckErr(NC_SetReadStringCommand(theContext, myReadString, stdin));
    CheckErr(NC_SetReadCharCommand(theContext, myReadChar, stdin));
#endif


    /* get nialroot path from environment on console version */

    {
        char       *nroot;

        nialrootname[0] = '\0';
        nroot = getenv("NIALROOT");
        if (nroot != NULL)
            strcpy(nialrootname, nroot);
    }

    /* initialize the user break capability */
    signal(SIGINT, controlCcatch);


    /* initialize the core routines */
    irc = NC_InitNial(sessionSettings, windSettings, theContext);
    if (NC_IsTerminate(irc))
    {   /* initialization has signalled a termination */
        exit(0);
    }
    else
    {
        CheckErr(irc);
    }



#ifdef INTERNAL_BUF_MODE
    /* display the result in the internal buffer */
    printf("%s", NC_GetBuffer());
#endif

    /* avoid the top level loop in a RUNTIME ONLY or CGINIAL version */

#ifdef RUNTIMEONLY
    goto cleanup;
#endif

#ifdef CGINIAL
    goto cleanup;
#endif


    /* the top level loop */

    do {

retry:
        /* issue the prompt to the console */
        myWrite(stdout, NC_GetPrompt(windSettings));

        userbreakrequested = false; /* could have been set during latent call in
                                 * NC_InitNial() */
        /* get the input string */
        awaitinginput = true;
        myReadInput();
        /* check if the input included a Control C press */
        if (myCheckUserBreak(NC_CS_INPUT)) {
            /* printf("myCheckUserBreak returned true\n"); */ /* remove after testing in UNIX */
            /* make sure workspace is clean */
            cleanup_ws();
#ifdef HISTORY
            if (lasteval != -1) {
                decrrefcnt(lasteval);
                freeup(lasteval);
            }
            lasteval = (-1);
#endif
#ifdef DEBUG
            printf("userbreakrequested set during input at top level loop\n");
#endif
            userbreakrequested = false;
            goto retry;            /* to go around to the prompt again */
        }
        if (EOFsignalled)
        {   /* the feof() code in Borland C returns nonzero if Ctrl-C has been
               pressed. This leads to a premature exit here. Removing the test
               causes nial.exe to loop forever if used as a filter. */
            goto cleanup;
        }

        awaitinginput = false;

        /* interpret the input */
        rc = NC_CommandInterpret(inputline, windSettings, theContext);

        /* check if there was a Control C press during CI execution */
        if (myCheckUserBreak(NC_CS_NORMAL)) {
            cleanup_ws();
#ifdef DEBUG
            printf("userbreakrequested set during input at top level loop\n");
#endif
            userbreakrequested = false;
            goto retry;            /* to go around to the prompt again */
        }

#ifdef INTERNAL_BUF_MODE
        /* display the output if buffered */
        printf("%s\n", NC_GetBuffer());
#endif

        /* check the return code from CI */

        if (!(NC_IsNoError(rc) || NC_IsWarning(rc)
                || NC_IsBreak(rc) || NC_IsTerminate(rc))) {
            /* display error information to console */
            printf("Return Code: %s ErrorTypeName : %s\n", NC_ErrorTypeName(rc),
                   NC_ErrorMessage(rc));
        }

    } while (NC_IsWarning(rc) || NC_IsNoError(rc) || NC_IsBreak(rc));

    /* end of top level loop code */

cleanup:

    /* stop the interpreter and clean up its resource usage */
    NC_StopNial();

    /* clean up the core interface resources */

    CheckErr(NC_DestroyIOContext(theContext));
    CheckErr(NC_DestroyWindowSettings(windSettings));
    CheckErr(NC_DestroySessionSettings(sessionSettings));


    /* return from the console version of Q'Nial */

    /* getchar(); */
    /* MAJ: put in the above getchar here to delay exit so that debug output can be
       seen when running from the Borland interface */
    exit(0);
    return 1;                  /* to satisfy syntax error checking */
}
Example #3
0
File: pixmap.c Project: mcgrew/lxvt
/* EXTPROTO */
Pixmap
rxvt_load_pixmap(rxvt_t *r, const char *file, long* pwidth, long* pheight)
{
    char*	    f;
    int		    flen;
#if defined(USE_JPEG) || defined(USE_PNG)
    long	    w = 0, h = 0;
#endif
    XpmAttributes   xpm_attr;
    Pixmap	    pixmap;

    UNSET_PIXMAP(pixmap);

    assert(file != NULL);
    if ((char) 0 == *file) { /* No file to load */
	return None;
    }

    xpm_attr.closeness = 30000;
    xpm_attr.colormap = XCMAP;
    xpm_attr.visual = XVISUAL;
    xpm_attr.depth = XDEPTH;
    xpm_attr.valuemask = (XpmCloseness | XpmColormap |
	    XpmVisual | XpmDepth | XpmSize | XpmReturnPixels);


    /* search environment variables here too */
    if (NULL == (f = (char*) rxvt_File_find (file, ".xpm", r->h->rs[Rs_path]))
#ifdef USE_JPEG
	&& NULL == (f = (char*) rxvt_File_find (file, ".jpg", r->h->rs[Rs_path]))
	&& NULL == (f = (char*) rxvt_File_find (file, ".jpeg", r->h->rs[Rs_path]))
#endif
#ifdef USE_PNG
	&& NULL == (f = (char*) rxvt_File_find (file, ".png", r->h->rs[Rs_path]))
#endif
	)   {
	char	       *p;
	/* semi-colon delimited */
	if (NULL == (p = STRCHR(file, ';')))
	    p = STRCHR(file, '\0');
	rxvt_msg (DBG_ERROR, DBG_PIXMAP, "couldn't load image file \"%.*s\"", (p - file), file);
	return None;
    }

    flen = STRLEN (f);
#ifdef USE_JPEG
    if ((flen >= 4 && !STRNCASECMP (f+flen-4, ".jpg", 4)) ||
	(flen >= 5 && !STRNCASECMP (f+flen-5, ".jpeg",5)))  {
	GC	gc = DefaultGC (r->Xdisplay, XSCREEN);
	if (!JpegReadFileToPixmap (r->Xdisplay, XROOT, gc, f,
	    &pixmap, &w, &h))	{
	    *pwidth = w;
	    *pheight = h;
	}
    }
    else
#endif
#ifdef USE_PNG
    if (flen >= 4 && !STRNCASECMP (f+flen-4, ".png", 4))    {
	GC	gc = DefaultGC (r->Xdisplay, XSCREEN);
	if (!PngReadFileToPixmap (r->Xdisplay, XROOT, gc, f,
	    &pixmap, &w, &h))	{
	    *pwidth = w;
	    *pheight = h;
	}
    }
    else
#endif
#ifdef HAVE_LIBXPM
    if (!XpmReadFileToPixmap(r->Xdisplay, XROOT, f,
	&pixmap, NULL, &xpm_attr))  {
	*pwidth = xpm_attr.width;
	*pheight = xpm_attr.height;
    }
#endif
    {
	/* empty to suppress compile error */
    }

    rxvt_free(f);
    if (NOT_PIXMAP(pixmap)) {
	char	       *p;
	/* semi-colon delimited */
	if ((p = STRCHR(file, ';')) == NULL)
	p = STRCHR(file, '\0');
	rxvt_msg (DBG_ERROR, DBG_PIXMAP, "couldn't load image file \"%.*s\"", (p - file), file);
    }

    return  (pixmap);
}
Example #4
0
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, 0},
		{"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'},
		{"timer-t1", 1, 0, 'Z'},
		{"transport", 1, 0, 'E'},
		{"headers", 1, 0, 'j'},
		{"authhash", 1, 0, 'J'},
		{"local-ip", 1, 0, 'k'},
		{"syslog", 1, 0, 'K'},
#ifdef WITH_TLS_TRANSP
		{"tls-ca-cert", 1, 0, 0},
		{"tls-client-cert", 1, 0, 0},
		{"tls-ignore-cert-failure", 0, 0, 0},
#endif
		{0, 0, 0, 0}
	};
#endif
	/* some initialisation to be safe */
	file_b=uri_b=trace=lport=usrloc=flood=verbose=randtrash=trashchar = 0;
	warning_ext=rand_rem=nonce_count=replace_b=invite=message=sysl = 0;
	sleep_ms=empty_contact=nagios_warn=timing=outbound_proxy=symmetric = 0;
	namebeg=nameend=maxforw= -1;
#ifdef OLDSTYLE_FQDN
	numeric = 0;
#else
	numeric = 1;
#endif
	via_ins=redirects=fix_crlf=processes = 1;
	username=password=replace_str=hostname=contact_uri=mes_body = NULL;
	con_dis=auth_username=from_uri=headers=authhash=local_ip = NULL;
	scheme = user = host = backup = request = response = received = NULL;
	regex = NULL;
	address= 0;
	transport=tsp = 0;
	rport = port = 0;
	expires_t = USRLOC_EXP_DEF;
	timer_t1 = SIP_T1;
	timer_t2 = 8;
	timer_final = 64;
	memset(buff, 0, BUFSIZE);
	memset(fqdn, 0, FQDN_SIZE);
#ifdef WITH_TLS_TRANSP
	cert_file = ca_file = NULL;
	ignore_ca_fail = 0;
# ifdef USE_GNUTLS
	tls_session = NULL;
	xcred = NULL;
# else
#  ifdef USE_OPENSSL
	ctx = NULL;
	ssl = NULL;
#  endif
#endif
#endif /* WITH_TLS_TRANSP */

	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:J:k:K:l:Lm:MnNo:O:p:P:q:r:Rs:St:Tu:UvVwW:x:z:Z:", l_opts, &option_index)) != EOF){
#else
	while ((c=getopt(argc, argv, "a:A:b:B:c:C:dD:e:E:f:Fg:GhH:iIj:J:k:K:l:Lm:MnNo:O:p:P:q:r:Rs:St:Tu:UvVwW:x:z:Z:")) != EOF){
#endif
		switch(c){
#ifdef HAVE_GETOPT_LONG
			case 0:
				printf("long option %s", l_opts[option_index].name);
				if (optarg) {
					printf(" with arg %s", optarg);
				}
				printf("\n");
				if (STRNCASECMP("help", l_opts[option_index].name, 4) == 0) {
					print_long_help();
				}
#ifdef WITH_TLS_TRANSP
				else if (STRNCASECMP("tls-ca-cert", l_opts[option_index].name, 11) == 0) {
					pf = fopen(optarg, "rb");
					if (!pf){
						fprintf(stderr, "error: unable to open the CA cert file '%s'.\n", optarg);
						exit_code(2, __PRETTY_FUNCTION__, "failed to open CA cert file");
					}
					fclose(pf);
					ca_file=optarg;
					break;
				}
				else if (STRNCASECMP("tls-ignore-cert-failure", l_opts[option_index].name, 22) == 0) {
					ignore_ca_fail = 1;
					break;
				}
				else if (STRNCASECMP("tls-client-cert", l_opts[option_index].name, 14) == 0) {
					pf = fopen(optarg, "rb");
					if (!pf){
						fprintf(stderr, "error: unable to open the client cert file '%s'.\n", optarg);
						exit_code(2, __PRETTY_FUNCTION__, "failed to open client cert file");
					}
					fclose(pf);
					cert_file=optarg;
					break;
				}
#endif
				break;
#endif
			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, __PRETTY_FUNCTION__, NULL);
					}
				}
				else {
					password=str_alloc(strlen(optarg) + 1);
					strncpy(password, optarg, strlen(optarg));
				}
				break;
			case 'A':
				timing=str_to_int(0, optarg);
				break;
			case 'b':
				namebeg=str_to_int(0, 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, __PRETTY_FUNCTION__, "missing scheme in From URI");
				}
				else if (user == NULL) {
					fprintf(stderr, "error: missing username in From URI\n");
					exit_code(2, __PRETTY_FUNCTION__, "missing username in From URI");
				}
				else if (host == NULL) {
					fprintf(stderr, "error: missing host in From URI\n");
					exit_code(2, __PRETTY_FUNCTION__, "missing host in From URI");
				}
				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) ||
						(strlen(optarg) == 4 && STRNCASECMP(optarg, "star", 4) == 0)) {
					contact_uri=str_alloc(2);
					memcpy(contact_uri, "*", 1);
				}
				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, __PRETTY_FUNCTION__, "unsupported Contact for registration");
					}
					/*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, __PRETTY_FUNCTION__, "missing host in Contact");
					}
					else {
						contact_uri=str_alloc(strlen(optarg)+1);
						strncpy(contact_uri, optarg, strlen(optarg));
					}
					free(backup);
				}
				break;
			case 'd':
				redirects=0;
				break;
			case 'D':
				timer_final = str_to_int(0, optarg);
				if (timer_final <= 0) {
					fprintf(stderr, "error: option D has to be above 0\n");
					exit_code(2, __PRETTY_FUNCTION__, "option D has to be above 0");
				}
				break;
			case 'e':
				nameend=str_to_int(0, 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;
				}
#ifdef WITH_TLS_TRANSP
				else if (strlen(optarg) == 3 &&
						STRNCASECMP(optarg, "tls", 3) == 0) {
					transport = SIP_TLS_TRANSPORT;
				}
#endif
				else {
					fprintf(stderr, "error: unsupported transport '%s', supported values: udp, tcp\n", optarg);
					exit_code(2, __PRETTY_FUNCTION__, "unsupported transport");
				}
				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, __PRETTY_FUNCTION__, "failed to open file from the f option");
					}
					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, __PRETTY_FUNCTION__, "file to big for buffer");
					}
					fclose(pf);
				}
				else if (strlen(optarg) == 1 && STRNCASECMP(optarg, "-", 1) == 0) {
					if (read_stdin(&buff[0], sizeof(buff), 0) == 0) {
						exit_code(0, __PRETTY_FUNCTION__, NULL);
					}
				}
				else {
					fprintf(stderr, "error: unable to handle input file name: %s\n", optarg);
					exit_code(2, __PRETTY_FUNCTION__, "unsupported input file name");
				}
				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 'J':
				if (strlen(optarg) < SIPSAK_HASHHEXLEN_MD5) {
					fprintf(stderr, "error: authhash string is too short\n");
					exit_code(2, __PRETTY_FUNCTION__, "authhash string is too short");
				}
				authhash=optarg;
				break;
			case 'k':
				local_ip=optarg;
				break;
			case 'K':
				sysl=str_to_int(0, optarg);
				if (sysl < LOG_ALERT || sysl > LOG_DEBUG) {
					fprintf(stderr, "error: syslog value '%s' must be between ALERT (1) and DEBUG (7)\n", optarg);
					exit_code(2, __PRETTY_FUNCTION__, "unsupported syslog value for option K");
				}
#ifdef HAVE_SYSLOG_H
				openlog(PACKAGE_NAME, LOG_CONS|LOG_NOWAIT|LOG_PID, LOG_USER);
#endif
				break;
			case 'l':
				lport=str_to_int(0, optarg);
				break;
			case 'L':
				fix_crlf=0;
				break;
			case 'm':
				maxforw=str_to_int(0, 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(0, 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, &port);
				if (host == NULL) {
					fprintf(stderr, "error: missing in host in outbound proxy\n");
					exit_code(2, __PRETTY_FUNCTION__, "missing host in outbound proxy");
				}
				if (is_ip(host)) {
					address = getaddress(host);
					if (transport == 0)
						transport = SIP_UDP_TRANSPORT;
				}
				else {
					if (!port) {
						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, __PRETTY_FUNCTION__, "failed to resolve the outbound proxy");
					}
				}
				if (port && !rport) {
					rport = port;
				}
				outbound_proxy=1;
#ifdef DEBUG
				printf("address: %lu, rport: %i\n", address, rport);
#endif
				break;
			case 'P':
				processes=str_to_int(0, optarg);
				break;
			case 'q':
				if (regex) {
					/* previously allocated -- free */
					regfree(regex);
				} else {
					/* never tried -- allocate */
					regex=malloc(sizeof(regex_t));
				};
				if (!regex) {
					fprintf(stderr, "Error: can't allocate RE\n");
					exit_code(2, __PRETTY_FUNCTION__, "failed to allocate memory for regualr expression");
				};
				if (regcomp(regex, optarg, REG_EXTENDED|REG_ICASE|REG_NEWLINE )!=0) {
					fprintf(stderr, "Error: compiling RE: %s\n", optarg );
					exit_code(2, __PRETTY_FUNCTION__, "failed to compile regular expression");
				};
				break;
			case 'r':
				port=str_to_int(0, 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, __PRETTY_FUNCTION__, "missing scheme in target SIP URI");
				}
				if (strlen(optarg) == 4 && STRNCASECMP(optarg,"sips",4) == 0){
					fprintf(stderr, "error: sips is not supported yet\n");
					exit_code(2, __PRETTY_FUNCTION__, "unsupported scheme SIPS in target URI");
				}
				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, __PRETTY_FUNCTION__, "unsupported scheme in target URI");
				}
				if (user != NULL) {
					username = user;
				}
				if (host != NULL) {
					domainname = host;
				}
				else {
					fprintf(stderr, "error: missing hostname in sip uri\n");
					exit_code(2, __PRETTY_FUNCTION__, "missing host name in target URI");
				}
				if (port && !rport) {
					rport = port;
				}
				if (is_ip(domainname) && !address) {
					address = getaddress(domainname);
					if (transport == 0)
						transport = SIP_UDP_TRANSPORT;
				}
				else {
					if (!rport && !address) {
						address = getsrvadr(domainname, &rport, &tsp);
						if (tsp != 0 && transport == 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, __PRETTY_FUNCTION__, "failed to resolve host from target URI");
					}
				}
				if (port != 0) {
					backup = str_alloc(strlen(domainname)+1+6);
					snprintf(backup, strlen(domainname)+6, "%s:%i", domainname, port);
					domainname = backup;
				}
				uri_b=1;
#ifdef DEBUG
				printf("address: %lu, rport: %i, username: '******', domain: '%s'\n", address, rport, username, domainname);
#endif
				break;
			case 'S':
				fprintf(stderr, "warning: symmetric does not work with a-symmetric servers\n");
				symmetric=1;
				break;
			case 't':
				trashchar=str_to_int(0, 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_FULL_OPENSSL
				printf(", OPENSSL_MD5");
#else
				printf(", INTERNAL_MD5");
#endif
#ifdef HAVE_OPENSSL_SHA1
				printf(", OPENSSL_SHA1");
#endif
#ifdef WITH_TLS_TRANSP
# ifdef USE_GNUTLS
				printf(", TLS_SUPPORT(GNUTLS)");
# else
#  ifdef USE_OPENSSL
				printf(", TLS_SUPPORT(OPENSSL)");
#  endif
# endif
#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
#ifdef DEBUG
				printf(", DEBUG");
#endif
				printf("\n");
				exit_code(0, __PRETTY_FUNCTION__, NULL);
				break;
			case 'w':
				warning_ext=1;
				break;
			case 'W':
				nagios_warn = str_to_int(0, optarg);
				break;
			case 'x':
				expires_t=str_to_int(0, optarg);
				break;
			case 'z':
				rand_rem=str_to_int(0, optarg);
				if (rand_rem < 0 || rand_rem > 100) {
					fprintf(stderr, "error: z option must between 0 and 100\n");
					exit_code(2, __PRETTY_FUNCTION__, "value for option z out of range");
				}
				break;
			case 'Z':
				timer_t1 = str_to_int(0, optarg);
				if (timer_t1 <= 0) {
					fprintf(stderr, "error: Z option must be above 0\n");
					exit_code(2, __PRETTY_FUNCTION__, "value for option Z must be above 0");
				}
				break;
			default:
				fprintf(stderr, "error: unknown parameter '%c'\n", c);
				exit_code(2, __PRETTY_FUNCTION__, "unknown parameter");
				break;
		}
	}

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

	timer_t2 = timer_t2 * timer_t1;
	timer_final = timer_final * timer_t1;

	/* 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, __PRETTY_FUNCTION__, "trace mode can't be combined with other modes");
		}
		if (!uri_b) {
			fprintf(stderr, "error: for trace mode a SIPURI is really needed\n");
			exit_code(2, __PRETTY_FUNCTION__, "missing URI for trace mode");
		}
		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, __PRETTY_FUNCTION__, "missing username in target URI");
		}
		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, __PRETTY_FUNCTION__, "usrloc mode can't be combined with other modes");
		}
		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, __PRETTY_FUNCTION__, "missing target URI or username in URI");
		}
		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, __PRETTY_FUNCTION__, "missing end number");
		}
		if (invite && message) {
			fprintf(stderr, "error: invite and message tests are XOR\n");
			exit_code(2, __PRETTY_FUNCTION__, "INVITE and MESSAGE tests are XOR");
		}
		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, __PRETTY_FUNCTION__, "don't use usrloc INVITE mode without registerting before");
		}
		if (contact_uri!=NULL) {
			if (invite || message) {
				fprintf(stderr, "error: Contact uri is not support for invites or "
					"messages\n");
				exit_code(2, __PRETTY_FUNCTION__, "Contact URI not supported for INVITE or MESSAGE mode");
			}
			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) {
			if (verbose > 1) {
				fprintf(stderr, "warning: Deactivated Via insertion in usrloc mode.\n         Please use option -i to suppress this warning.\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, __PRETTY_FUNCTION__, "flood mode can't be combined with other modes");
		}
		if (!uri_b) {
			fprintf(stderr, "error: we need at least a sip uri for flood\n");
			exit_code(2, __PRETTY_FUNCTION__, "missing target URI");
		}
		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, __PRETTY_FUNCTION__, "random mode can't be combined with other modes");
		}
		if (!uri_b) {
			fprintf(stderr, "error: need at least a sip uri for random\n");
			exit_code(2, __PRETTY_FUNCTION__, "missing target URI");
		}
		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, __PRETTY_FUNCTION__, "missing target SIP URI");
		}
		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, __PRETTY_FUNCTION__, "missing target SIP URI");
		}
	}

	switch (transport) {
#ifdef WITH_TLS_TRANSP
		case SIP_TLS_TRANSPORT:
			transport_str = TRANSPORT_TLS_STR;
			break;
#endif /* WITH_TLS_TRANSP */
		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: %u\n", transport);
			exit_code(2, __PRETTY_FUNCTION__, "unknown transport");
	}

#ifdef WITH_TLS_TRANSP
	if (transport == SIP_TLS_TRANSPORT) {
# ifdef USE_GNUTLS
		gnutls_global_init();
		//gnutls_anon_allocate_client_credentials(&anoncred);
		gnutls_certificate_allocate_credentials(&xcred);
		if (ca_file != NULL) {
			// set the trusted CA file
			gnutls_certificate_set_x509_trust_file(xcred, ca_file, GNUTLS_X509_FMT_PEM);
		}
# else
#  ifdef USE_OPENSSL
		SSL_library_init();
		SSL_load_error_strings();
#  endif
# endif
	}
#endif /* WITH_TLS_TRANSP */

	/* 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() + (getpid() << 15)));
	
	if (processes > 1) {
		if (signal(SIGCHLD , sigchld_handler)  == SIG_ERR ) {
			fprintf(stderr, "error: Could not install SIGCHLD handler\n");
			exit_code(2, __PRETTY_FUNCTION__, "failed to install SIGCHLD handler");
		}
	}

	for(i = 0; i < processes - 1; i++) {
		if ((pid = fork()) < 0) {
			fprintf(stderr, "error: Cannot fork\n");
			exit_code(2, __PRETTY_FUNCTION__, "failed to fork");
		}
		
		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;
}
Example #5
0
int getaddress(char *host, int rport, int transport, struct addrinfo *ret) {
	struct addrinfo *result;
	struct addrinfo *res;
	int error;

	struct addrinfo hints = {
		.ai_family = AF_UNSPEC,
		.ai_socktype = transport == SIP_TCP_TRANSPORT ? SOCK_STREAM : SOCK_DGRAM
	};

	if (rport) {
		char strport[INT_DIGITS10];
		snprintf(strport, INT_DIGITS10, "%i", rport);
		error = getaddrinfo(host, strport, &hints, &result);
	} else {
		error = getaddrinfo(host, "sip", &hints, &result);
	}

	/* resolve the domain name into a list of addresses */
	if (error != 0) {
		if (error == EAI_SYSTEM) {
			perror("getaddrinfo");
		} else {
			fprintf(stderr, "error in getaddrinfo for %s: %s\n", host, gai_strerror(error));
		}
		return -1;
	}

	/* loop over all returned results and do inverse lookup */
	for (res = result; res != NULL; res = res->ai_next) {
		char hostname[NI_MAXHOST];

		error = getnameinfo(res->ai_addr, res->ai_addrlen, hostname, NI_MAXHOST, NULL, 0, 0);
		if (error != 0) {
			fprintf(stderr, "error in getnameinfo: %s\n", gai_strerror(error));
			continue;
		} if (*hostname != '\0') {
			memset(ret, 0, sizeof(struct addrinfo));
			memcpy(ret, res, sizeof(struct addrinfo));

			ret->ai_addr = malloc(res->ai_addrlen);
			memcpy(ret->ai_addr, res->ai_addr, res->ai_addrlen);
			break;
		}
	}

	freeaddrinfo(result);
	return 0;
}

#ifdef HAVE_CARES_H
static const unsigned char *parse_rr(const unsigned char *aptr, const unsigned char *abuf, int alen) {
	char *name;
	long len;
	int status, type, dnsclass, dlen;
	struct in_addr addr;

	dbg("ca_tmpname: %s\n", ca_tmpname);
	status = ares_expand_name(aptr, abuf, alen, &name, &len);
	if (status != ARES_SUCCESS) {
		printf("error: failed to expand query name\n");
		exit_code(2, __PRETTY_FUNCTION__, "failed to expand query name");
	}
	aptr += len;
	if (aptr + NS_RRFIXEDSZ > abuf + alen) {
		printf("error: not enough data in DNS answer 1\n");
		free(name);
		return NULL;
	}
	type = DNS_RR_TYPE(aptr);
	dnsclass = DNS_RR_CLASS(aptr);
	dlen = DNS_RR_LEN(aptr);
	aptr += NS_RRFIXEDSZ;
	if (aptr + dlen > abuf + alen) {
		printf("error: not enough data in DNS answer 2\n");
		free(name);
		return NULL;
	}
	if (dnsclass != CARES_CLASS_C_IN) {
		printf("error: unsupported dnsclass (%i) in DNS answer\n", dnsclass);
		free(name);
		return NULL;
	}
	if ((ca_tmpname == NULL && type != CARES_TYPE_SRV) ||
		(ca_tmpname != NULL &&
		 	(type != CARES_TYPE_A && type != CARES_TYPE_CNAME))) {
		printf("error: unsupported DNS response type (%i)\n", type);
		free(name);
		return NULL;
	}
	if (type == CARES_TYPE_SRV) {
		free(name);
		caport = DNS__16BIT(aptr + 4);
		dbg("caport: %i\n", caport);
		status = ares_expand_name(aptr + 6, abuf, alen, &name, &len);
		if (status != ARES_SUCCESS) {
			printf("error: failed to expand SRV name\n");
			return NULL;
		}
		dbg("SRV name: %s\n", name);
		if (is_ip(name)) {
			caadr = inet_addr(name);
			free(name);
		}
		else {
			ca_tmpname = name;
		}
	}
	else if (type == CARES_TYPE_CNAME) {
		if ((ca_tmpname != NULL) &&
				(STRNCASECMP(ca_tmpname, name, strlen(ca_tmpname)) == 0)) {
			ca_tmpname = malloc(strlen(name));
			if (ca_tmpname == NULL) {
				printf("error: failed to allocate memory\n");
				exit_code(2, __PRETTY_FUNCTION__, "memory allocation failure");
			}
			strcpy(ca_tmpname, name);
			free(name);
		}
		else {
			free(name);
			status = ares_expand_name(aptr, abuf, alen, &name, &len);
			if (status != ARES_SUCCESS) {
				printf("error: failed to expand CNAME\n");
				return NULL;
			}
			dbg("CNAME: %s\n", name);
			if (is_ip(name)) {
				caadr = inet_addr(name);
				free(name);
			}
			else {
				ca_tmpname = name;
			}
		}
	}
	else if (type == CARES_TYPE_A) {
		if (dlen == 4 && STRNCASECMP(ca_tmpname, name, strlen(ca_tmpname)) == 0) {
			memcpy(&addr, aptr, sizeof(struct in_addr));
			caadr = addr.s_addr;
		}
		free(name);
	}
	return aptr + dlen;
}
Example #6
0
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':
			{
				iconv_t	cd;
				char *inbuf = optarg, *outbuf;
				size_t inbytes = strlen(optarg), outbytes = inbytes * 2;
				mes_body = malloc(sizeof(struct bytearray));
				mes_body->data = outbuf = str_alloc(outbytes);
				mes_body->len = outbytes;
				cd = iconv_open("UCS-2BE", "UTF-8");
				iconv(cd, &inbuf, &inbytes, &outbuf, &outbytes);
				iconv_close(cd);
				mes_body->len -= outbytes; // some UTF-8 characters 1-byte long, some 2-byte long. All UCS-2 chars 2-byte long
				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;
			}
		}
		// FIX: what's a peace of crap???
		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;
}
int4 mur_cre_file_extfmt(jnl_ctl_list *jctl, int recstat)
{
	fi_type			*file_info;
	char			*ptr, rename_fn[MAX_FN_LEN];
	int			rename_fn_len, base_len, fn_exten_size, extrlen, tmplen;
	uint4			status;
	mval			op_val, op_pars;
	boolean_t		is_stdout;	/* Output will go STDOUT? */
	static readonly	char 	*fn_exten[] = {EXT_MJF, EXT_BROKEN, EXT_LOST};
	static readonly	char 	*ext_file_type[] = {STR_JNLEXTR, STR_BRKNEXTR, STR_LOSTEXTR};
	static readonly unsigned char		open_params_list[]=
	{
		(unsigned char)iop_m,
		(unsigned char)iop_newversion,
		(unsigned char)iop_noreadonly,
		(unsigned char)iop_nowrap,
		(unsigned char)iop_stream,
		(unsigned char)iop_eol
	};

	assert(GOOD_TN == recstat || BROKEN_TN == recstat || LOST_TN == recstat);
	assert(0 == GOOD_TN);
	assert(1 == BROKEN_TN);
	assert(2 == LOST_TN);
	assert(GOOD_TN != recstat || mur_options.extr[GOOD_TN]);
	/* Argument journal -extract=-stdout ? */
	is_stdout = mur_options.extr_fn[recstat]
		&& (0 == STRNCASECMP(mur_options.extr_fn[recstat], JNL_STDO_EXTR, SIZEOF(JNL_STDO_EXTR)));
	/* If we need to write to stdout, we can bypass file renaming stuff */
	if(!is_stdout)
	{
		ptr = (char *)&jctl->jnl_fn[jctl->jnl_fn_len];
		while (DOT != *ptr)	/* we know journal file name alway has a DOT */
			ptr--;
		base_len = (int)(ptr - (char *)&jctl->jnl_fn[0]);
		file_info = (void *)malloc(SIZEOF(fi_type));
		if (0 == mur_options.extr_fn_len[recstat])
		{
			mur_options.extr_fn[recstat] = malloc(MAX_FN_LEN);
			mur_options.extr_fn_len[recstat] = base_len;
			memcpy(mur_options.extr_fn[recstat], jctl->jnl_fn, base_len);
			fn_exten_size = STRLEN(fn_exten[recstat]);
			memcpy(mur_options.extr_fn[recstat] + base_len, fn_exten[recstat], fn_exten_size);
			mur_options.extr_fn_len[recstat] += fn_exten_size;
		}
		file_info->fn_len = mur_options.extr_fn_len[recstat];
		file_info->fn = mur_options.extr_fn[recstat];
		murgbl.file_info[recstat] = file_info;
		if (RENAME_FAILED == rename_file_if_exists(file_info->fn, file_info->fn_len, rename_fn, &rename_fn_len, &status))
			return status;
		op_pars.mvtype = MV_STR;
		op_pars.str.len = SIZEOF(open_params_list);
		op_pars.str.addr = (char *)open_params_list;
		op_val.mvtype = MV_STR;
		op_val.str.len = file_info->fn_len;
		op_val.str.addr = (char *)file_info->fn;
		if ((status = (*op_open_ptr)(&op_val, &op_pars, 0, NULL)) == 0)
		{
			gtm_putmsg(VARLSTCNT(5) ERR_FILENOTCREATE, 2, file_info->fn_len, file_info->fn, errno);
			return ERR_FILENOTCREATE;
		}
	}
	/* Write file version info for the file created here. See C9B08-001729 */
	if (!mur_options.detail)
	{
		MEMCPY_LIT(murgbl.extr_buff, JNL_EXTR_LABEL);
		extrlen = STR_LIT_LEN(JNL_EXTR_LABEL);
	} else
	{
		MEMCPY_LIT(murgbl.extr_buff, JNL_DET_EXTR_LABEL);
		extrlen = STR_LIT_LEN(JNL_DET_EXTR_LABEL);
	}
	if (LOST_TN == recstat)
	{
		if (mur_options.update)
		{
			if (mur_options.rollback)
				ptr = " ROLLBACK";
			else
				ptr = " RECOVER";
		} else
			ptr = " EXTRACT";
		tmplen = STRLEN(ptr);
		memcpy(&murgbl.extr_buff[extrlen], ptr, tmplen);
		extrlen += tmplen;
		if (mur_options.rollback)
		{
			if (mur_options.fetchresync_port && murgbl.was_rootprimary)
				ptr = " PRIMARY ";
			else
				ptr = " SECONDARY ";
			tmplen = STRLEN(ptr);
			memcpy(&murgbl.extr_buff[extrlen], ptr, tmplen);
			extrlen += tmplen;
			assert(NULL != jnlpool.repl_inst_filehdr);
			ptr = (char *)&jnlpool.repl_inst_filehdr->inst_info.this_instname[0];
			tmplen = STRLEN(ptr);
			memcpy(&murgbl.extr_buff[extrlen], ptr, tmplen);
			extrlen += tmplen;
		}
	}
	if (gtm_utf8_mode)
	{
		murgbl.extr_buff[extrlen++] = ' ';
		MEMCPY_LIT(&murgbl.extr_buff[extrlen], UTF8_NAME);
		extrlen += STR_LIT_LEN(UTF8_NAME);
	}
	murgbl.extr_buff[extrlen++] = '\\';
	jnlext_write((is_stdout ? NULL : file_info), murgbl.extr_buff, extrlen);
	if (!is_stdout) /* We wrote to stdout so it doesn't make a sense to print a message about file creation. */
		gtm_putmsg(VARLSTCNT(6) ERR_FILECREATE, 4, LEN_AND_STR(ext_file_type[recstat]), file_info->fn_len, file_info->fn);
	return SS_NORMAL;
}
Example #8
0
// Initialize Direct3D
bool
initD3D9(HWND hWnd, int argc, char **argv, int *pbTCC)
{
    int dev, device_count = 0;
    bool bSpecifyDevice=false;
    char device_name[256];

    // Check for a min spec of Compute 1.1 capability before running
    checkCudaErrors(cuDeviceGetCount(&device_count));

    for (int i=0; i < argc; i++)
    {
        int string_start = 0;

        while (argv[i][string_start] == '-')
        {
            string_start++;
        }

        const char *string_argv = &argv[i][string_start];

        if (!STRNCASECMP(string_argv, "device=", 7))
        {
            bSpecifyDevice = true;
        }
    }

    // If deviceID == 0, and there is more than 1 device, let's find the first available graphics GPU
    if (!bSpecifyDevice && device_count > 0)
    {
        for (int i=0; i < device_count; i++)
        {
            checkCudaErrors(cuDeviceGet(&dev, i));
            checkCudaErrors(cuDeviceGetName(device_name, 256, dev));

            int bSupported = checkCudaCapabilitiesDRV(1, 1, i);

            if (!bSupported)
            {
                printf("  -> GPU: \"%s\" does not meet the minimum spec of SM 1.1\n", device_name);
                printf("  -> A GPU with a minimum compute capability of SM 1.1 or higher is required.\n");
                return false;
            }

#if CUDA_VERSION >= 3020
            checkCudaErrors(cuDeviceGetAttribute(pbTCC ,  CU_DEVICE_ATTRIBUTE_TCC_DRIVER, dev));
            printf("  -> GPU %d: < %s > driver mode is: %s\n", dev, device_name, *pbTCC ? "TCC" : "WDDM");

            if (*pbTCC)
            {
                continue;
            }
            else
            {
                g_DeviceID = i; // we choose an available WDDM display device
            }

#else

            // We don't know for sure if this is a TCC device or not, if it is Tesla system, we will not run
            if (!STRNCASECMP(device_name, "Tesla", 5))
            {
                printf("  \"%s\" does not support %s\n", device_name, sSDKname);
                *pbTCC = 1;
                return false;
            }
            else
            {
                *pbTCC = 0;
            }

#endif
            printf("\n");
        }
    }
    else
    {
        if ((g_DeviceID > (device_count-1)) || (g_DeviceID < 0))
        {
            printf(" >>> Invalid GPU Device ID=%d specified, only %d GPU device(s) are available.<<<\n", g_DeviceID, device_count);
            printf(" >>> Valid GPU ID (n) range is between [%d,%d]...  Exiting... <<<\n", 0, device_count-1);
            return false;
        }

        // We are specifying a GPU device, check to see if it is TCC or not
        checkCudaErrors(cuDeviceGet(&dev, g_DeviceID));
        checkCudaErrors(cuDeviceGetName(device_name, 256, dev));

        checkCudaErrors(cuDeviceGetAttribute(pbTCC ,  CU_DEVICE_ATTRIBUTE_TCC_DRIVER, dev));
        printf("  -> GPU %d: < %s > driver mode is: %s\n", dev, device_name, *pbTCC ? "TCC" : "WDDM");
    }

    // Only if we are not using a TCC device will we use this path, otherwise we support using the VP w/o TCC
    HRESULT eResult = S_OK;

    if (!(*pbTCC))
    {
        // Create the D3D object.
        if (NULL == (g_pD3D = Direct3DCreate9(D3D_SDK_VERSION)))
        {
            return false;
        }

        // Get primary display identifier
        D3DADAPTER_IDENTIFIER9 adapterId;
        bool bDeviceFound = false;
        int device;

        // Find the first CUDA capable device
        CUresult cuStatus;

        for (unsigned int g_iAdapter = 0; g_iAdapter < g_pD3D->GetAdapterCount(); g_iAdapter++)
        {
            HRESULT hr = g_pD3D->GetAdapterIdentifier(g_iAdapter, 0, &adapterId);

            if (FAILED(hr))
            {
                continue;
            }

            cuStatus = cuD3D9GetDevice(&device, adapterId.DeviceName);
            printf("> Display Device: \"%s\" %s Direct3D9\n",
                   adapterId.Description,
                   (cuStatus == cudaSuccess) ? "supports" : "does not support");

            if (cudaSuccess == cuStatus)
            {
                bDeviceFound = true;
                break;
            }
        }

        // we check to make sure we have found a cuda-compatible D3D device to work on
        if (!bDeviceFound)
        {
            printf("\n");
            printf("  No CUDA-compatible Direct3D9 device available\n");
            // destroy the D3D device
            g_pD3D->Release();
            g_pD3D = NULL;
            return false;
        }

        // Create the D3D Display Device
        RECT                  rc;
        GetClientRect(hWnd, &rc);
        g_pD3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &g_d3ddm);
        ZeroMemory(&g_d3dpp, sizeof(g_d3dpp));

        g_d3dpp.Windowed               = (g_bQAReadback ? TRUE : g_bWindowed); // fullscreen or windowed?

        g_d3dpp.BackBufferCount        = 1;
        g_d3dpp.SwapEffect             = D3DSWAPEFFECT_DISCARD;
        g_d3dpp.hDeviceWindow          = hWnd;
        g_d3dpp.BackBufferWidth        = rc.right  - rc.left;
        g_d3dpp.BackBufferHeight       = rc.bottom - rc.top;
        g_d3dpp.BackBufferFormat       = g_d3ddm.Format;
        g_d3dpp.FullScreen_RefreshRateInHz = 0; // set to 60 for fullscreen, and also don't forget to set Windowed to FALSE
        g_d3dpp.PresentationInterval   = (g_bUseVsync ? D3DPRESENT_INTERVAL_ONE : D3DPRESENT_INTERVAL_IMMEDIATE);

        if (g_bQAReadback)
        {
            g_d3dpp.Flags              = D3DPRESENTFLAG_VIDEO;    // turn off vsync
        }

        eResult = g_pD3D->CreateDevice(0, D3DDEVTYPE_HAL, hWnd,
                                       D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_MULTITHREADED,
                                       &g_d3dpp, &g_pD3DDevice);
    }
    else
    {
        fprintf(stderr, "> %s is decoding w/o visualization\n", sSDKname);
        eResult = S_OK;
    }

    return (eResult == S_OK);
}
Example #9
0
bool JPEGReader::Extract( ICCProfile& icc )
{
   icc.Clear();

   if ( !IsOpen() )
      return false;

   if ( jpeg_decompressor->marker_list == nullptr )
      return true;

   ByteArray iccData;
   uint32 iccSize = 0;
   uint32 iccChunkOffset = 0;

   const ::jpeg_marker_struct* m = jpeg_decompressor->marker_list;

   do
   {
      if ( !STRNCASECMP( (const char*)m->data, "ICC_PROFILE", 11 ) )
      {
         //
         // ICC_PROFILE 0 i N ddddddddddddd...ddd
         // -----------
         //   iCC id
         //
         // 0 = nul character
         // i = index number of this chunk
         // N = total number of chunks
         // d = data bytes in this chunk
         //
         void* iccChunkData = m->data + 14;

         // Allocate ICC data block when we see the first chunk.
         if ( iccChunkOffset == 0 )
         {
            // iccChunkData points now to an ICC profile header.
            // The first field in an ICC profile header is the uint32
            // profile length in bytes. ICC profiles are encoded using
            // big endian byte order.
            iccSize = BigToLittleEndian( *(const uint32*)iccChunkData );
            if ( iccSize == 0 )
               return true;

            iccData = ByteArray( size_type( iccSize ) );
         }

         uint32 iccChunkSize = m->data_length - 14;

         // Guard us against insane ICC profile data.
         if ( iccChunkOffset+iccChunkSize > iccSize )
            return true;

         ::memcpy( iccData.At( iccChunkOffset ), iccChunkData, iccChunkSize );

         iccChunkOffset += iccChunkSize;

         // More chunks ?
         if ( m->data[12] >= m->data[13] )
            break;
      }
   }
   while ( (m = m->next) != nullptr );

   icc.Set( iccData );
   return true;
}
Example #10
0
void JPEGReader::Open( const String& _path )
{
   if ( IsOpen() )
      throw InvalidReadOperation( path );

   if ( _path.IsEmpty() )
      throw InvalidFilePath( _path );

   if ( options.lowerRange >= options.upperRange )
      throw InvalidNormalizationRange( _path );

   info.Reset();

   try
   {
      fileData = new JPEGFileData;
#ifdef __PCL_WINDOWS
      path = File::WindowsPathToUnix( _path );
#else
      path = _path;
#endif

      // Keep critical parameters secured in private data.
      fileData->lowerRange = options.lowerRange;
      fileData->upperRange = options.upperRange;

      IsoString path8 =
#ifdef __PCL_WINDOWS
         File::UnixPathToWindows( path ).ToMBS();
#else
         path.ToUTF8();
#endif
      fileData->handle = ::fopen( path8.c_str(), "rb" );

      if ( fileData->handle == 0 )
         throw UnableToOpenFile( path );

      // Allocate and initialize a JPEG decompression object.

      // This struct contains the JPEG decompression parameters and pointers to
      // working space, which is allocated as needed by the IJG library.
      fileData->decompressor = new ::jpeg_decompress_struct;

      // Set up normal JPEG error routines, passing a pointer to our custom
      // error handler structure.
      jpeg_decompressor->err = ::jpeg_std_error( (::jpeg_error_mgr*)
                  (fileData->errorManager = new JPEGErrorManager( path )) );

      // Override error_exit. JPEG library errors will be handled by throwing
      // exceptions from the JPEGErrorExit() routine.
      ((JPEGErrorManager*)fileData->errorManager)->error.error_exit = JPEGErrorExit;

      // Initialize the JPEG decompression object.
      ::jpeg_create_decompress( jpeg_decompressor );

      // Specify data source (e.g., a file).
      ::jpeg_stdio_src( jpeg_decompressor, fileData->handle );

      // Read file parameters with ::jpeg_read_header().

      ::jpeg_save_markers( jpeg_decompressor, JPEG_COM,     0xFFFF );
      ::jpeg_save_markers( jpeg_decompressor, JPEG_APP0+ 0, 0xFFFF );
      ::jpeg_save_markers( jpeg_decompressor, JPEG_APP0+ 1, 0xFFFF );
      ::jpeg_save_markers( jpeg_decompressor, JPEG_APP0+ 2, 0xFFFF );
      ::jpeg_save_markers( jpeg_decompressor, JPEG_APP0+ 3, 0xFFFF );
      ::jpeg_save_markers( jpeg_decompressor, JPEG_APP0+ 4, 0xFFFF );
      ::jpeg_save_markers( jpeg_decompressor, JPEG_APP0+ 5, 0xFFFF );
      ::jpeg_save_markers( jpeg_decompressor, JPEG_APP0+ 6, 0xFFFF );
      ::jpeg_save_markers( jpeg_decompressor, JPEG_APP0+ 7, 0xFFFF );
      ::jpeg_save_markers( jpeg_decompressor, JPEG_APP0+ 8, 0xFFFF );
      ::jpeg_save_markers( jpeg_decompressor, JPEG_APP0+ 9, 0xFFFF );
      ::jpeg_save_markers( jpeg_decompressor, JPEG_APP0+10, 0xFFFF );
      ::jpeg_save_markers( jpeg_decompressor, JPEG_APP0+11, 0xFFFF );
      ::jpeg_save_markers( jpeg_decompressor, JPEG_APP0+12, 0xFFFF );
      ::jpeg_save_markers( jpeg_decompressor, JPEG_APP0+13, 0xFFFF );
      ::jpeg_save_markers( jpeg_decompressor, JPEG_APP0+14, 0xFFFF );
      ::jpeg_save_markers( jpeg_decompressor, JPEG_APP0+15, 0xFFFF );

      ::jpeg_read_header( jpeg_decompressor, boolean( true ) );

      // Deal with the JFIF marker and associated resolution data.

      if ( (jpegOptions.JFIFMarker = jpeg_decompressor->saw_JFIF_marker) != false )
      {
         jpegOptions.JFIFMajorVersion = jpeg_decompressor->JFIF_major_version;
         jpegOptions.JFIFMinorVersion = jpeg_decompressor->JFIF_minor_version;
         options.metricResolution = jpeg_decompressor->density_unit == 2;
         options.xResolution = jpeg_decompressor->X_density;
         options.yResolution = jpeg_decompressor->Y_density;
      }
      else
      {
         // Set default JFIF version and resolution data if a JFIF marker is
         // not present in this JPEG file.
         jpegOptions.JFIFMajorVersion = 1;
         jpegOptions.JFIFMinorVersion = 2;
         options.metricResolution = false;
         options.xResolution = options.yResolution = 72;
      }

      // Set sample format options.

      options.bitsPerSample = 8;
      options.signedIntegers = options.complexSample = options.ieeefpSampleFormat = false;

      // Extract JPEG quality from dedicated JPEG marker

      jpegOptions.quality = JPEGQuality::Unknown;

      if ( jpeg_decompressor->marker_list != nullptr )
      {
         const jpeg_marker_struct* m = jpeg_decompressor->marker_list;

         do
         {
            if ( !STRNCASECMP( (const char*)m->data, "JPEGQuality", 11 ) )
            {
               // Skip marker header + null char
               jpegOptions.quality = Range( int( *(m->data + 12) ), 1, 100 );
               break;
            }
            else if ( !STRNCASECMP( (const char*)m->data, "JPEG Quality", 12 ) ||
                      !STRNCASECMP( (const char*)m->data, "JPEG_Quality", 12 ) )
            {
               // Skip marker header + null char
               jpegOptions.quality = Range( int( *(m->data + 13) ), 1, 100 );
               break;
            }
         }
         while ( (m = m->next) != nullptr );
      }

      jpegOptions.progressive = jpeg_decompressor->progressive_mode;
      jpegOptions.arithmeticCoding = jpeg_decompressor->arith_code;

      // Fill in ImageInfo and JPEGFileData fields.

      ::jpeg_calc_output_dimensions( jpeg_decompressor );

      info.width = jpeg_decompressor->output_width;
      info.height = jpeg_decompressor->output_height;
      info.numberOfChannels = jpeg_decompressor->out_color_components;
      info.colorSpace = (jpeg_decompressor->out_color_space == JCS_GRAYSCALE) ?
                                             ColorSpace::Gray : ColorSpace::RGB;
      info.supported = true;
   }
   catch ( ... )
   {
      Close();
      throw;
   }
}
/* http://opengis.github.io/geopackage/#table_column_data_types */
OGRFieldType GPkgFieldToOGR(const char *pszGpkgType)
{
    /* Integer types */
    if ( STRNCASECMP("INTEGER", pszGpkgType, 7) == 0 )
        return OFTInteger;
    else if ( STRNCASECMP("INT", pszGpkgType, 3) == 0 )
        return OFTInteger;
    else if ( STRNCASECMP("MEDIUMINT", pszGpkgType, 9) == 0 )
        return OFTInteger;
    else if ( STRNCASECMP("SMALLINT", pszGpkgType, 8) == 0 )
        return OFTInteger;
    else if ( STRNCASECMP("TINYINT", pszGpkgType, 7) == 0 )
        return OFTInteger;
    else if ( STRNCASECMP("BOOLEAN", pszGpkgType, 7) == 0 )
        return OFTInteger;

    /* Real types */
    else if ( STRNCASECMP("FLOAT", pszGpkgType, 5) == 0 )
        return OFTReal;
    else if ( STRNCASECMP("DOUBLE", pszGpkgType, 6) == 0 )
        return OFTReal;
    else if ( STRNCASECMP("REAL", pszGpkgType, 4) == 0 )
        return OFTReal;
        
    /* String/binary types */
    else if ( STRNCASECMP("TEXT", pszGpkgType, 4) == 0 )
        return OFTString;
    else if ( STRNCASECMP("BLOB", pszGpkgType, 4) == 0 )
        return OFTBinary;
        
    /* Date types */
    else if ( STRNCASECMP("DATE", pszGpkgType, 4) == 0 )
        return OFTDate;
    else if ( STRNCASECMP("DATETIME", pszGpkgType, 8) == 0 )
        return OFTDateTime;

    /* Illegal! */
    else 
        return (OGRFieldType)(OFTMaxType + 1);
}