Пример #1
0
static void
sanitize_album(cdtext &text)
{
	cut_string(text.album, text.artist);
	sanitize_string(text.album);

	if (text.album != NULL && !strcasecmp(text.album, "My CD")) {
		// don't laugh, people really do that!
		free(text.album);
		text.album = NULL;
	}

	if ((text.artist == NULL || text.artist[0] == '\0') && text.album != NULL) {
		// try to extract artist from album
		char *space = strstr(text.album, "  ");
		if (space != NULL) {
			space[0] = '\0';
			text.artist = text.album;
			text.album = copy_string(space + 2);

			sanitize_string(text.artist);
			sanitize_string(text.album);
		}
	}
}
Пример #2
0
int8_t command_insert( uint8_t *pszCommandString, tUserState *pState )
{
    int32_t iRetVal;
    tDateTime tempDate;
    char szFirstName[MAX_STRING_LENGTH+1];
    char szLastName[MAX_STRING_LENGTH+1];
    char szUserName[MAX_STRING_LENGTH+1];
    char szTemp[MAX_STRING_LENGTH+1];
    uint32_t creationDate;
    uint32_t newRecordNumber;

    printf( "First name: " );

    iRetVal = readLine( STDIN, szFirstName, MAX_STRING_LENGTH );

    sanitize_string( szFirstName );

    printf( "Last name: " );

    iRetVal = readLine( STDIN, szLastName, MAX_STRING_LENGTH );

    sanitize_string( szLastName );

    printf( "User name: " );

    iRetVal = readLine( STDIN, szUserName, MAX_STRING_LENGTH );

    sanitize_string( szUserName );

    printf( "Birthdate (mm/dd/yy hh:mm:ss): " );

    iRetVal = readLine( STDIN, szTemp, MAX_STRING_LENGTH );

    creationDate = parse_date( szTemp, &tempDate );

    if ( creationDate == 0 )
    {
        printf( "Date parsing error.\n" );
        return 0;
    }

    printf( "Date is: $d/$d/$d $d:$d:$d\n", tempDate.month, tempDate.day, GET_DB_YEAR(tempDate.year), tempDate.hour, tempDate.minute, tempDate.second );

    // Insert into database
    newRecordNumber = db_add_record( szUserName, szFirstName, szLastName, tempDate );

    if ( newRecordNumber == BAD_RECORD_ERROR )
    {
        printf( "Database full.\n" );
        return 0;
    }

    printf( "Data added, record $d\n", newRecordNumber );
    return 0;
}
Пример #3
0
static void parse_url(const char *src_url, struct host_info *h)
{
	char *url, *p, *sp;

	free(h->allocated);
	h->allocated = url = xstrdup(src_url);

	if (strncmp(url, "http://", 7) == 0) {
		h->port = bb_lookup_port("http", "tcp", 80);
		h->host = url + 7;
		h->is_ftp = 0;
	} else if (strncmp(url, "ftp://", 6) == 0) {
		h->port = bb_lookup_port("ftp", "tcp", 21);
		h->host = url + 6;
		h->is_ftp = 1;
	} else
		bb_error_msg_and_die("not an http or ftp url: %s", sanitize_string(url));

	// FYI:
	// "Real" wget 'http://busybox.net?var=a/b' sends this request:
	//   'GET /?var=a/b HTTP 1.0'
	//   and saves 'index.html?var=a%2Fb' (we save 'b')
	// wget 'http://busybox.net?login=john@doe':
	//   request: 'GET /?login=john@doe HTTP/1.0'
	//   saves: 'index.html?login=john@doe' (we save '?login=john@doe')
	// wget 'http://busybox.net#test/test':
	//   request: 'GET / HTTP/1.0'
	//   saves: 'index.html' (we save 'test')
	//
	// We also don't add unique .N suffix if file exists...
	sp = strchr(h->host, '/');
	p = strchr(h->host, '?'); if (!sp || (p && sp > p)) sp = p;
	p = strchr(h->host, '#'); if (!sp || (p && sp > p)) sp = p;
	if (!sp) {
		h->path = "";
	} else if (*sp == '/') {
		*sp = '\0';
		h->path = sp + 1;
	} else { // '#' or '?'
		// http://busybox.net?login=john@doe is a valid URL
		// memmove converts to:
		// http:/busybox.nett?login=john@doe...
		memmove(h->host - 1, h->host, sp - h->host);
		h->host--;
		sp[-1] = '\0';
		h->path = sp;
	}

	// We used to set h->user to NULL here, but this interferes
	// with handling of code 302 ("object was moved")

	sp = strrchr(h->host, '@');
	if (sp != NULL) {
		h->user = h->host;
		*sp = '\0';
		h->host = sp + 1;
	}

	sp = h->host;
}
Пример #4
0
template<> string sinsp_fdinfo_t::tostring_clean()
{
	string m_tstr = m_name;
	sanitize_string(m_tstr);

	return m_tstr;
}
Пример #5
0
static char *gethdr(FILE *fp)
{
	char *s, *hdrval;
	int c;

	/* retrieve header line */
	c = fgets_and_trim(fp);

	/* end of the headers? */
	if (G.wget_buf[0] == '\0')
		return NULL;

	/* convert the header name to lower case */
	for (s = G.wget_buf; isalnum(*s) || *s == '-' || *s == '.'; ++s) {
		/* tolower for "A-Z", no-op for "0-9a-z-." */
		*s |= 0x20;
	}

	/* verify we are at the end of the header name */
	if (*s != ':')
		bb_error_msg_and_die("bad header line: %s", sanitize_string(G.wget_buf));

	/* locate the start of the header value */
	*s++ = '\0';
	hdrval = skip_whitespace(s);

	if (c != '\n') {
		/* Rats! The buffer isn't big enough to hold the entire header value */
		while (c = getc(fp), c != EOF && c != '\n')
			continue;
	}

	return hdrval;
}
Пример #6
0
/* thread locks added until all non re-entrant functions it uses have been fixed */
int DBG_log(const char *message, ...)
{
	va_list args;
	char m[LOG_WIDTH]; /* longer messages will be truncated */

	pthread_mutex_lock(&log_mutex);
	va_start(args, message);
	vsnprintf(m, sizeof(m), message, args);
	va_end(args);

	/* then sanitize anything else that is left. */
	sanitize_string(m, sizeof(m));

	if (log_to_stderr || pluto_log_fp != NULL) {
		char buf[34] = "";

		if (log_with_timestamp)
			prettynow(buf, sizeof(buf), "%b %e %T: ");
		fprintf(log_to_stderr ? stderr : pluto_log_fp,
			"%c %s%s\n", debug_prefix, buf, m);
	}
	if (log_to_syslog)
		syslog(LOG_DEBUG, "%c %s", debug_prefix, m);
	if (log_to_perpeer) {
		char prefix[3];
		prefix[0] = debug_prefix;
		prefix[1] = ' ';
		prefix[2] = '\n';
		peerlog(prefix, m);
	}

	pthread_mutex_unlock(&log_mutex);
	return 0;
}
Пример #7
0
static void
sanitize_titles(cdtext &text)
{
	for (uint8 i = 0; i < text.track_count; i++) {
		cut_string(text.titles[i], "(Album Version)");
		sanitize_string(text.titles[i]);
		sanitize_string(text.artists[i]);

		if (text.artists[i] != NULL && text.artist != NULL
			&& !strcasecmp(text.artists[i], text.artist)) {
			// if the title artist is the same as the main artist, remove it
			free(text.artists[i]);
			text.artists[i] = NULL;
		}

		if (text.titles[i] != NULL && text.titles[i][0] == '\t' && i > 0)
			text.titles[i] = copy_string(text.titles[i - 1]);
	}
}
Пример #8
0
static void
format_thread_text (const void *ctx,
		    const char *thread_id,
		    const time_t date,
		    const int matched,
		    const int total,
		    const char *authors,
		    const char *subject)
{
    void *ctx_quote = talloc_new (ctx);

    printf ("thread:%s %12s [%d/%d] %s; %s",
	    thread_id,
	    notmuch_time_relative_date (ctx, date),
	    matched,
	    total,
	    sanitize_string (ctx_quote, authors),
	    sanitize_string (ctx_quote, subject));

    talloc_free (ctx_quote);
}
Пример #9
0
Файл: log.c Проект: mcr/Openswan
/* format a string for the log, with suitable prefixes.
 * A format starting with ~ indicates that this is a reprocessing
 * of the message, so prefixing and quoting is suppressed.
 */
static void
fmt_log(char *buf, size_t buf_len, const char *fmt, va_list ap)
{
    bool reproc = *fmt == '~';
    size_t ps;
    struct connection *c = cur_state != NULL ? cur_state->st_connection
	: cur_connection;

    buf[0] = '\0';
    if (reproc)
	fmt++;	/* ~ at start of format suppresses this prefix */
    else if (c != NULL)
    {
	/* start with name of connection */
	char *const be = buf + buf_len;
	char *bp = buf;

	snprintf(bp, be - bp, "\"%s\"", c->name);
	bp += strlen(bp);

	/* if it fits, put in any connection instance information */
	if (be - bp > CONN_INST_BUF)
	{
	    fmt_conn_instance(c, bp);
	    bp += strlen(bp);
	}

	if (cur_state != NULL)
	{
	    /* state number */
	    snprintf(bp, be - bp, " #%lu", cur_state->st_serialno);
	    bp += strlen(bp);
	}
	snprintf(bp, be - bp, ": ");
    }
    else if (cur_from != NULL)
    {
	/* peer's IP address */
	/* Note: must not use ip_str() because our caller might! */
	char ab[ADDRTOT_BUF];

	(void) addrtot(cur_from, 0, ab, sizeof(ab));
	snprintf(buf, buf_len, "packet from %s:%u: "
	    , ab, (unsigned)cur_from_port);
    }

    ps = strlen(buf);
    vsnprintf(buf + ps, buf_len - ps, fmt, ap);
    if (!reproc)
	(void)sanitize_string(buf, buf_len);
}
Пример #10
0
int main(int argc, char *argv[]) {
    char buffer[BUFSIZ];
    char *sanitized, *result;

    while (fgets(buffer, BUFSIZ, stdin)) {
    	CHOMP(buffer);

    	sanitized = sanitize_string(buffer);
    	result    = is_palindrome(sanitized) ? "" : "not ";
	free(sanitized);
    	printf("%s is %sa palindrome!\n", buffer, result);
    }
	
    return EXIT_SUCCESS;
}
Пример #11
0
size_t lswlog_sanitized(struct lswlog *buf, const char *raw)
{
	if (raw == NULL) {
		return lswlogs(buf, raw); /* appends error */
	}

	size_t size = 0;
	for (const char *p = raw; *p; p++) {
		/* space for at least '\000' and then some */
		char tmp[sizeof("\\000") + 1] = { *p, };
		sanitize_string(tmp, sizeof(tmp));
		size += lswlogs(buf, tmp);
	}
	return size;
}
Пример #12
0
static char *gethdr(char *buf, size_t bufsiz, FILE *fp /*, int *istrunc*/)
{
	char *s, *hdrval;
	int c;

	/* *istrunc = 0; */

	/* retrieve header line */
	if (fgets(buf, bufsiz, fp) == NULL)
		return NULL;

	/* see if we are at the end of the headers */
	for (s = buf; *s == '\r'; ++s)
		continue;
	if (*s == '\n')
		return NULL;

	/* convert the header name to lower case */
	for (s = buf; isalnum(*s) || *s == '-' || *s == '.'; ++s) {
		/* tolower for "A-Z", no-op for "0-9a-z-." */
		*s = (*s | 0x20);
	}

	/* verify we are at the end of the header name */
	if (*s != ':')
		bb_error_msg_and_die("bad header line: %s", sanitize_string(buf));

	/* locate the start of the header value */
	*s++ = '\0';
	hdrval = skip_whitespace(s);

	/* locate the end of header */
	while (*s && *s != '\r' && *s != '\n')
		++s;

	/* end of header found */
	if (*s) {
		*s = '\0';
		return hdrval;
	}

	/* Rats! The buffer isn't big enough to hold the entire header value */
	while (c = getc(fp), c != EOF && c != '\n')
		continue;
	/* *istrunc = 1; */
	return hdrval;
}
Пример #13
0
/*
 * format a string for the log, with suitable prefixes.
 * A format starting with ~ indicates that this is a reprocessing
 * of the message, so prefixing and quoting is suppressed.
 */
static void fmt_log(char *buf, size_t buf_len,
		const char *fmt, va_list ap)
{
	bool reproc = *fmt == '~';
	char *p = buf;

	buf[0] = '\0';
	if (reproc) {
		fmt++;	/* ~ at start of format suppresses this prefix */
	} else if (progname != NULL && (strlen(progname) + 1 + 1) < buf_len) {
		/* start with name of connection */
		p = add_str(buf, buf_len, jam_str(buf, buf_len, progname), " ");
	}
	vsnprintf(p, buf_len - (p - buf), fmt, ap);
	if (!reproc)
		sanitize_string(buf, buf_len);
}
Пример #14
0
void
openswan_DBG_log(const char *message, ...)
{
    va_list args;
    char m[LOG_WIDTH];	/* longer messages will be truncated */

    va_start(args, message);
    vsnprintf(m, sizeof(m), message, args);
    va_end(args);

    /* then sanitize anything else that is left. */
    (void)sanitize_string(m, sizeof(m));

    if (log_to_stderr)
	fprintf(stderr, "| %s\n", m);
    if (log_to_syslog)
	syslog(LOG_DEBUG, "| %s", m);
}
Пример #15
0
/*
 * format a string for the log, with suitable prefixes.
 * A format starting with ~ indicates that this is a reprocessing
 * of the message, so prefixing and quoting is suppressed.
 */
static void fmt_log(char *buf, size_t buf_len,
		    const char *fmt, va_list ap)
{
	bool reproc = *fmt == '~';
	size_t ps;

	buf[0] = '\0';
	if (reproc) {
		fmt++; /* ~ at start of format suppresses this prefix */
	} else if (progname != NULL && (strlen(progname) + 1 + 1) < buf_len) {
		/* start with name of connection */
		strncat(buf, progname, buf_len - 1);
		strncat(buf, " ", buf_len - 1);
	}

	ps = strlen(buf);
	vsnprintf(buf + ps, buf_len - ps, fmt, ap);
	if (!reproc)
		(void)sanitize_string(buf, buf_len);
}
Пример #16
0
Файл: log.c Проект: mcr/Openswan
int
DBG_log(const char *message, ...)
{
    va_list args;
    char m[LOG_WIDTH];	/* longer messages will be truncated */

    va_start(args, message);
    vsnprintf(m, sizeof(m), message, args);
    va_end(args);

    /* then sanitize anything else that is left. */
    (void)sanitize_string(m, sizeof(m));

    if (log_to_stderr) {
	if (log_with_timestamp) {
		struct tm *timeinfo;
		char fmt[32];
		time_t rtime;
		time(&rtime);
		timeinfo = localtime (&rtime);
		strftime (fmt,sizeof(fmt),"%b %e %T",timeinfo);
		fprintf(stderr, "%c %s: %s\n", debug_prefix, fmt, m);
	} else {
		fprintf(stderr, "%c %s\n", debug_prefix, m);
	}
    }
    if (log_to_syslog)
	syslog(LOG_DEBUG, "%c %s", debug_prefix, m);
    if (log_to_perpeer) {
	char prefix[3];
	prefix[0]=debug_prefix;
	prefix[1]=' ';
	prefix[2]='\n';
	peerlog(prefix, m);
    }

    return 0;
}
Пример #17
0
/*
 * Get the concatenated Received: headers and search from the front
 * (last Received: header added) and try to extract from them
 * indications to which email address this message was delivered.
 *
 * The Received: header is special in our get_header function and is
 * always concatenated.
 *
 * Return the address that was found, if any, and NULL otherwise.
 */
static const char *
guess_from_in_received_headers (notmuch_config_t *config,
				notmuch_message_t *message)
{
    const char *received, *addr;
    char *sanitized;

    received = notmuch_message_get_header (message, "received");
    if (! received)
	return NULL;

    sanitized = sanitize_string (NULL, received);
    if (! sanitized)
	return NULL;

    addr = guess_from_in_received_for (config, sanitized);
    if (! addr)
	addr = guess_from_in_received_by (config, sanitized);

    talloc_free (sanitized);

    return addr;
}
Пример #18
0
int wget_main(int argc UNUSED_PARAM, char **argv)
{
    char buf[512];
    struct host_info server, target;
    len_and_sockaddr *lsa;
    unsigned opt;
    int redir_limit;
    char *proxy = NULL;
    char *dir_prefix = NULL;
#if ENABLE_FEATURE_WGET_LONG_OPTIONS
    char *post_data;
    char *extra_headers = NULL;
    llist_t *headers_llist = NULL;
#endif
    FILE *sfp;                      /* socket to web/ftp server         */
    FILE *dfp;                      /* socket to ftp server (data)      */
    char *fname_out;                /* where to direct output (-O)      */
    int output_fd = -1;
    bool use_proxy;                 /* Use proxies if env vars are set  */
    const char *proxy_flag = "on";  /* Use proxies if env vars are set  */
    const char *user_agent = "Wget";/* "User-Agent" header field        */

    static const char keywords[] ALIGN1 =
        "content-length\0""transfer-encoding\0""chunked\0""location\0";
    enum {
        KEY_content_length = 1, KEY_transfer_encoding, KEY_chunked, KEY_location
    };
#if ENABLE_FEATURE_WGET_LONG_OPTIONS
    static const char wget_longopts[] ALIGN1 =
        /* name, has_arg, val */
        "continue\0"         No_argument       "c"
        "spider\0"           No_argument       "s"
        "quiet\0"            No_argument       "q"
        "output-document\0"  Required_argument "O"
        "directory-prefix\0" Required_argument "P"
        "proxy\0"            Required_argument "Y"
        "user-agent\0"       Required_argument "U"
        /* Ignored: */
        // "tries\0"            Required_argument "t"
        // "timeout\0"          Required_argument "T"
        /* Ignored (we always use PASV): */
        "passive-ftp\0"      No_argument       "\xff"
        "header\0"           Required_argument "\xfe"
        "post-data\0"        Required_argument "\xfd"
        /* Ignored (we don't do ssl) */
        "no-check-certificate\0" No_argument   "\xfc"
        ;
#endif

    INIT_G();

#if ENABLE_FEATURE_WGET_LONG_OPTIONS
    applet_long_options = wget_longopts;
#endif
    /* server.allocated = target.allocated = NULL; */
    opt_complementary = "-1" IF_FEATURE_WGET_LONG_OPTIONS(":\xfe::");
    opt = getopt32(argv, "csqO:P:Y:U:" /*ignored:*/ "t:T:",
                   &fname_out, &dir_prefix,
                   &proxy_flag, &user_agent,
                   NULL, /* -t RETRIES */
                   NULL /* -T NETWORK_READ_TIMEOUT */
                   IF_FEATURE_WGET_LONG_OPTIONS(, &headers_llist)
                   IF_FEATURE_WGET_LONG_OPTIONS(, &post_data)
                  );
#if ENABLE_FEATURE_WGET_LONG_OPTIONS
    if (headers_llist) {
        int size = 1;
        char *cp;
        llist_t *ll = headers_llist;
        while (ll) {
            size += strlen(ll->data) + 2;
            ll = ll->link;
        }
        extra_headers = cp = xmalloc(size);
        while (headers_llist) {
            cp += sprintf(cp, "%s\r\n", (char*)llist_pop(&headers_llist));
        }
    }
#endif

    /* TODO: compat issue: should handle "wget URL1 URL2..." */

    target.user = NULL;
    parse_url(argv[optind], &target);

    /* Use the proxy if necessary */
    use_proxy = (strcmp(proxy_flag, "off") != 0);
    if (use_proxy) {
        proxy = getenv(target.is_ftp ? "ftp_proxy" : "http_proxy");
        if (proxy && proxy[0]) {
            server.user = NULL;
            parse_url(proxy, &server);
        } else {
            use_proxy = 0;
        }
    }
    if (!use_proxy) {
        server.port = target.port;
        if (ENABLE_FEATURE_IPV6) {
            server.host = xstrdup(target.host);
        } else {
            server.host = target.host;
        }
    }

    if (ENABLE_FEATURE_IPV6)
        strip_ipv6_scope_id(target.host);

    /* Guess an output filename, if there was no -O FILE */
    if (!(opt & WGET_OPT_OUTNAME)) {
        fname_out = bb_get_last_path_component_nostrip(target.path);
        /* handle "wget http://kernel.org//" */
        if (fname_out[0] == '/' || !fname_out[0])
            fname_out = (char*)"index.html";
        /* -P DIR is considered only if there was no -O FILE */
        if (dir_prefix)
            fname_out = concat_path_file(dir_prefix, fname_out);
    } else {
        if (LONE_DASH(fname_out)) {
            /* -O - */
            output_fd = 1;
            opt &= ~WGET_OPT_CONTINUE;
        }
    }
#if ENABLE_FEATURE_WGET_STATUSBAR
    G.curfile = bb_get_last_path_component_nostrip(fname_out);
#endif

    /* Impossible?
    if ((opt & WGET_OPT_CONTINUE) && !fname_out)
    	bb_error_msg_and_die("can't specify continue (-c) without a filename (-O)");
    */

    /* Determine where to start transfer */
    if (opt & WGET_OPT_CONTINUE) {
        output_fd = open(fname_out, O_WRONLY);
        if (output_fd >= 0) {
            G.beg_range = xlseek(output_fd, 0, SEEK_END);
        }
        /* File doesn't exist. We do not create file here yet.
         * We are not sure it exists on remove side */
    }

    redir_limit = 5;
resolve_lsa:
    lsa = xhost2sockaddr(server.host, server.port);
    if (!(opt & WGET_OPT_QUIET)) {
        char *s = xmalloc_sockaddr2dotted(&lsa->u.sa);
        fprintf(stderr, "Connecting to %s (%s)\n", server.host, s);
        free(s);
    }
establish_session:
    if (use_proxy || !target.is_ftp) {
        /*
         *  HTTP session
         */
        char *str;
        int status;

        /* Open socket to http server */
        sfp = open_socket(lsa);

        /* Send HTTP request */
        if (use_proxy) {
            fprintf(sfp, "GET %stp://%s/%s HTTP/1.1\r\n",
                    target.is_ftp ? "f" : "ht", target.host,
                    target.path);
        } else {
            if (opt & WGET_OPT_POST_DATA)
                fprintf(sfp, "POST /%s HTTP/1.1\r\n", target.path);
            else
                fprintf(sfp, "GET /%s HTTP/1.1\r\n", target.path);
        }

        fprintf(sfp, "Host: %s\r\nUser-Agent: %s\r\n",
                target.host, user_agent);

#if ENABLE_FEATURE_WGET_AUTHENTICATION
        if (target.user) {
            fprintf(sfp, "Proxy-Authorization: Basic %s\r\n"+6,
                    base64enc_512(buf, target.user));
        }
        if (use_proxy && server.user) {
            fprintf(sfp, "Proxy-Authorization: Basic %s\r\n",
                    base64enc_512(buf, server.user));
        }
#endif

        if (G.beg_range)
            fprintf(sfp, "Range: bytes=%"OFF_FMT"u-\r\n", G.beg_range);
#if ENABLE_FEATURE_WGET_LONG_OPTIONS
        if (extra_headers)
            fputs(extra_headers, sfp);

        if (opt & WGET_OPT_POST_DATA) {
            char *estr = URL_escape(post_data);
            fprintf(sfp, "Content-Type: application/x-www-form-urlencoded\r\n");
            fprintf(sfp, "Content-Length: %u\r\n" "\r\n" "%s",
                    (int) strlen(estr), estr);
            /*fprintf(sfp, "Connection: Keep-Alive\r\n\r\n");*/
            /*fprintf(sfp, "%s\r\n", estr);*/
            free(estr);
        } else
#endif
        {   /* If "Connection:" is needed, document why */
            fprintf(sfp, /* "Connection: close\r\n" */ "\r\n");
        }

        /*
         * Retrieve HTTP response line and check for "200" status code.
         */
read_response:
        if (fgets(buf, sizeof(buf), sfp) == NULL)
            bb_error_msg_and_die("no response from server");

        str = buf;
        str = skip_non_whitespace(str);
        str = skip_whitespace(str);
        // FIXME: no error check
        // xatou wouldn't work: "200 OK"
        status = atoi(str);
        switch (status) {
        case 0:
        case 100:
            while (gethdr(buf, sizeof(buf), sfp /*, &n*/) != NULL)
                /* eat all remaining headers */;
            goto read_response;
        case 200:
        /*
        Response 204 doesn't say "null file", it says "metadata
        has changed but data didn't":

        "10.2.5 204 No Content
        The server has fulfilled the request but does not need to return
        an entity-body, and might want to return updated metainformation.
        The response MAY include new or updated metainformation in the form
        of entity-headers, which if present SHOULD be associated with
        the requested variant.

        If the client is a user agent, it SHOULD NOT change its document
        view from that which caused the request to be sent. This response
        is primarily intended to allow input for actions to take place
        without causing a change to the user agent's active document view,
        although any new or updated metainformation SHOULD be applied
        to the document currently in the user agent's active view.

        The 204 response MUST NOT include a message-body, and thus
        is always terminated by the first empty line after the header fields."

        However, in real world it was observed that some web servers
        (e.g. Boa/0.94.14rc21) simply use code 204 when file size is zero.
        */
        case 204:
            break;
        case 300:	/* redirection */
        case 301:
        case 302:
        case 303:
            break;
        case 206:
            if (G.beg_range)
                break;
        /* fall through */
        default:
            bb_error_msg_and_die("server returned error: %s", sanitize_string(buf));
        }

        /*
         * Retrieve HTTP headers.
         */
        while ((str = gethdr(buf, sizeof(buf), sfp /*, &n*/)) != NULL) {
            /* gethdr converted "FOO:" string to lowercase */
            smalluint key;
            /* strip trailing whitespace */
            char *s = strchrnul(str, '\0') - 1;
            while (s >= str && (*s == ' ' || *s == '\t')) {
                *s = '\0';
                s--;
            }
            key = index_in_strings(keywords, buf) + 1;
            if (key == KEY_content_length) {
                G.content_len = BB_STRTOOFF(str, NULL, 10);
                if (G.content_len < 0 || errno) {
                    bb_error_msg_and_die("content-length %s is garbage", sanitize_string(str));
                }
                G.got_clen = 1;
                continue;
            }
            if (key == KEY_transfer_encoding) {
                if (index_in_strings(keywords, str_tolower(str)) + 1 != KEY_chunked)
                    bb_error_msg_and_die("transfer encoding '%s' is not supported", sanitize_string(str));
                G.chunked = G.got_clen = 1;
            }
            if (key == KEY_location && status >= 300) {
                if (--redir_limit == 0)
                    bb_error_msg_and_die("too many redirections");
                fclose(sfp);
                G.got_clen = 0;
                G.chunked = 0;
                if (str[0] == '/')
                    /* free(target.allocated); */
                    target.path = /* target.allocated = */ xstrdup(str+1);
                /* lsa stays the same: it's on the same server */
                else {
                    parse_url(str, &target);
                    if (!use_proxy) {
                        server.host = target.host;
                        /* strip_ipv6_scope_id(target.host); - no! */
                        /* we assume remote never gives us IPv6 addr with scope id */
                        server.port = target.port;
                        free(lsa);
                        goto resolve_lsa;
                    } /* else: lsa stays the same: we use proxy */
                }
                goto establish_session;
            }
        }
//		if (status >= 300)
//			bb_error_msg_and_die("bad redirection (no Location: header from server)");

        /* For HTTP, data is pumped over the same connection */
        dfp = sfp;

    } else {
        /*
         *  FTP session
         */
        sfp = prepare_ftp_session(&dfp, &target, lsa);
    }

    if (opt & WGET_OPT_SPIDER) {
        if (ENABLE_FEATURE_CLEAN_UP)
            fclose(sfp);
        return EXIT_SUCCESS;
    }

    if (output_fd < 0) {
        int o_flags = O_WRONLY | O_CREAT | O_TRUNC | O_EXCL;
        /* compat with wget: -O FILE can overwrite */
        if (opt & WGET_OPT_OUTNAME)
            o_flags = O_WRONLY | O_CREAT | O_TRUNC;
        output_fd = xopen(fname_out, o_flags);
    }

    retrieve_file_data(dfp, output_fd);
    xclose(output_fd);

    if (dfp != sfp) {
        /* It's ftp. Close it properly */
        fclose(dfp);
        if (ftpcmd(NULL, NULL, sfp, buf) != 226)
            bb_error_msg_and_die("ftp error: %s", sanitize_string(buf+4));
        /* ftpcmd("QUIT", NULL, sfp, buf); - why bother? */
    }

    return EXIT_SUCCESS;
}
Пример #19
0
void handle_test_result(const boost::math::tools::test_result<T>& result,
                       const Seq& worst, int row, 
                       const char* type_name, 
                       const char* test_name, 
                       const char* group_name)
{
   T eps = boost::math::tools::epsilon<T>();
   T max_error_found = (result.max)() / eps;
   T mean_error_found = result.rms() / eps;

   std::string cell_name = sanitize_string(BOOST_COMPILER) + "_" + sanitize_string(BOOST_PLATFORM) + "_" + sanitize_string(type_name) 
      + "_" + sanitize_string(test_name) + "_" + sanitize_string(TEST_LIBRARY_NAME) + "_" + sanitize_string(group_name);

   std::stringstream ss;
   ss << std::setprecision(3);
   if(std::string(TEST_LIBRARY_NAME) != "boost")
      ss << "(['" << TEST_LIBRARY_NAME << ":] ";
   else
      ss << "[role blue ";

   if((result.max)() > std::sqrt(eps))
      ss << "[role red ";


   ss << "Max = ";
   if((boost::math::isfinite)(max_error_found))
      ss << max_error_found;
   else
      ss << "+INF";
   ss << "[epsilon] (Mean = ";
   if((boost::math::isfinite)(mean_error_found))
      ss << mean_error_found;
   else
      ss << "+INF";
   ss << "[epsilon])";

   //
   // Now check for error output from gross errors or unexpected exceptions:
   //
   std::stringbuf* pbuf = dynamic_cast<std::stringbuf*>(std::cerr.rdbuf());
   bool have_errors = false;
   std::string error_id = "errors_" + cell_name;
   if(pbuf)
   {
      std::string err_s = pbuf->str();
      if(err_s.size())
      {
         if(err_s.size() > 4096)
         {
            std::string::size_type pos = err_s.find("\n", 4096);
            if(pos != std::string::npos)
            {
               err_s.erase(pos);
               err_s += "\n*** FURTHER CONTENT HAS BEEN TRUNCATED FOR BREVITY ***\n";
            }
         }
         std::string::size_type pos = err_s.find("\n");
         while(pos != std::string::npos)
         {
            err_s.replace(pos, 1, "[br]");
            pos = err_s.find("\n");
         }
         err_s = "[h4 Error Output For " + std::string(test_name) + std::string(" with compiler ") + std::string(BOOST_COMPILER)
            + std::string(" and library ") + std::string(TEST_LIBRARY_NAME) + " and test data "
            + std::string(group_name) + "]\n\n[#" + error_id + "]\n" + err_s + std::string("\n\n\n");
         ss << "  [link " << error_id << " And other failures.]";
         pbuf->str("");
         set_error_content(error_id, err_s);
         have_errors = true;
      }
   }
   if(!have_errors)
      remove_error_content(error_id);


   if(std::string(TEST_LIBRARY_NAME) != "boost")
      ss << ")";
   else
      ss << "]";

   if((result.max)() > std::sqrt(eps))
      ss << "]";

   std::string cell_content = ss.str();

   set_result(cell_name, cell_content, test_name, group_name, type_name);
}
Пример #20
0
static void download_one_url(const char *url)
{
	bool use_proxy;                 /* Use proxies if env vars are set  */
	int redir_limit;
	len_and_sockaddr *lsa;
	FILE *sfp;                      /* socket to web/ftp server         */
	FILE *dfp;                      /* socket to ftp server (data)      */
	char *proxy = NULL;
	char *fname_out_alloc;
	char *redirected_path = NULL;
	struct host_info server;
	struct host_info target;

	server.allocated = NULL;
	target.allocated = NULL;
	server.user = NULL;
	target.user = NULL;

	parse_url(url, &target);

	/* Use the proxy if necessary */
	use_proxy = (strcmp(G.proxy_flag, "off") != 0);
	if (use_proxy) {
		proxy = getenv(target.is_ftp ? "ftp_proxy" : "http_proxy");
		use_proxy = (proxy && proxy[0]);
		if (use_proxy)
			parse_url(proxy, &server);
	}
	if (!use_proxy) {
		server.port = target.port;
		if (ENABLE_FEATURE_IPV6) {
			//free(server.allocated); - can't be non-NULL
			server.host = server.allocated = xstrdup(target.host);
		} else {
			server.host = target.host;
		}
	}

	if (ENABLE_FEATURE_IPV6)
		strip_ipv6_scope_id(target.host);

	/* If there was no -O FILE, guess output filename */
	fname_out_alloc = NULL;
	if (!(option_mask32 & WGET_OPT_OUTNAME)) {
		G.fname_out = bb_get_last_path_component_nostrip(target.path);
		/* handle "wget http://kernel.org//" */
		if (G.fname_out[0] == '/' || !G.fname_out[0])
			G.fname_out = (char*)"index.html";
		/* -P DIR is considered only if there was no -O FILE */
		if (G.dir_prefix)
			G.fname_out = fname_out_alloc = concat_path_file(G.dir_prefix, G.fname_out);
		else {
			/* redirects may free target.path later, need to make a copy */
			G.fname_out = fname_out_alloc = xstrdup(G.fname_out);
		}
	}
#if ENABLE_FEATURE_WGET_STATUSBAR
	G.curfile = bb_get_last_path_component_nostrip(G.fname_out);
#endif

	/* Determine where to start transfer */
	G.beg_range = 0;
	if (option_mask32 & WGET_OPT_CONTINUE) {
		G.output_fd = open(G.fname_out, O_WRONLY);
		if (G.output_fd >= 0) {
			G.beg_range = xlseek(G.output_fd, 0, SEEK_END);
		}
		/* File doesn't exist. We do not create file here yet.
		 * We are not sure it exists on remote side */
	}

	redir_limit = 5;
 resolve_lsa:
	lsa = xhost2sockaddr(server.host, server.port);
	if (!(option_mask32 & WGET_OPT_QUIET)) {
		char *s = xmalloc_sockaddr2dotted(&lsa->u.sa);
		fprintf(stderr, "Connecting to %s (%s)\n", server.host, s);
		free(s);
	}
 establish_session:
	/*G.content_len = 0; - redundant, got_clen = 0 is enough */
	G.got_clen = 0;
	G.chunked = 0;
	if (use_proxy || !target.is_ftp) {
		/*
		 *  HTTP session
		 */
		char *str;
		int status;


		/* Open socket to http server */
		sfp = open_socket(lsa);

		/* Send HTTP request */
		if (use_proxy) {
			fprintf(sfp, "GET %stp://%s/%s HTTP/1.1\r\n",
				target.is_ftp ? "f" : "ht", target.host,
				target.path);
		} else {
			if (option_mask32 & WGET_OPT_POST_DATA)
				fprintf(sfp, "POST /%s HTTP/1.1\r\n", target.path);
			else
				fprintf(sfp, "GET /%s HTTP/1.1\r\n", target.path);
		}

		fprintf(sfp, "Host: %s\r\nUser-Agent: %s\r\n",
			target.host, G.user_agent);

		/* Ask server to close the connection as soon as we are done
		 * (IOW: we do not intend to send more requests)
		 */
		fprintf(sfp, "Connection: close\r\n");

#if ENABLE_FEATURE_WGET_AUTHENTICATION
		if (target.user) {
			fprintf(sfp, "Proxy-Authorization: Basic %s\r\n"+6,
				base64enc(target.user));
		}
		if (use_proxy && server.user) {
			fprintf(sfp, "Proxy-Authorization: Basic %s\r\n",
				base64enc(server.user));
		}
#endif

		if (G.beg_range != 0)
			fprintf(sfp, "Range: bytes=%"OFF_FMT"u-\r\n", G.beg_range);

#if ENABLE_FEATURE_WGET_LONG_OPTIONS
		if (G.extra_headers)
			fputs(G.extra_headers, sfp);

		if (option_mask32 & WGET_OPT_POST_DATA) {
			fprintf(sfp,
				"Content-Type: application/x-www-form-urlencoded\r\n"
				"Content-Length: %u\r\n"
				"\r\n"
				"%s",
				(int) strlen(G.post_data), G.post_data
			);
		} else
#endif
		{
			fprintf(sfp, "\r\n");
		}

		fflush(sfp);

		/*
		 * Retrieve HTTP response line and check for "200" status code.
		 */
 read_response:
		fgets_and_trim(sfp);

		str = G.wget_buf;
		str = skip_non_whitespace(str);
		str = skip_whitespace(str);
		// FIXME: no error check
		// xatou wouldn't work: "200 OK"
		status = atoi(str);
		switch (status) {
		case 0:
		case 100:
			while (gethdr(sfp) != NULL)
				/* eat all remaining headers */;
			goto read_response;
		case 200:
/*
Response 204 doesn't say "null file", it says "metadata
has changed but data didn't":

"10.2.5 204 No Content
The server has fulfilled the request but does not need to return
an entity-body, and might want to return updated metainformation.
The response MAY include new or updated metainformation in the form
of entity-headers, which if present SHOULD be associated with
the requested variant.

If the client is a user agent, it SHOULD NOT change its document
view from that which caused the request to be sent. This response
is primarily intended to allow input for actions to take place
without causing a change to the user agent's active document view,
although any new or updated metainformation SHOULD be applied
to the document currently in the user agent's active view.

The 204 response MUST NOT include a message-body, and thus
is always terminated by the first empty line after the header fields."

However, in real world it was observed that some web servers
(e.g. Boa/0.94.14rc21) simply use code 204 when file size is zero.
*/
		case 204:
			if (G.beg_range != 0) {
				/* "Range:..." was not honored by the server.
				 * Restart download from the beginning.
				 */
				reset_beg_range_to_zero();
			}
			break;
		case 300:  /* redirection */
		case 301:
		case 302:
		case 303:
			break;
		case 206: /* Partial Content */
			if (G.beg_range != 0)
				/* "Range:..." worked. Good. */
				break;
			/* Partial Content even though we did not ask for it??? */
			/* fall through */
		default:
			bb_error_msg_and_die("server returned error: %s", sanitize_string(G.wget_buf));
		}

		/*
		 * Retrieve HTTP headers.
		 */
		while ((str = gethdr(sfp)) != NULL) {
			static const char keywords[] ALIGN1 =
				"content-length\0""transfer-encoding\0""location\0";
			enum {
				KEY_content_length = 1, KEY_transfer_encoding, KEY_location
			};
			smalluint key;

			/* gethdr converted "FOO:" string to lowercase */

			/* strip trailing whitespace */
			char *s = strchrnul(str, '\0') - 1;
			while (s >= str && (*s == ' ' || *s == '\t')) {
				*s = '\0';
				s--;
			}
			key = index_in_strings(keywords, G.wget_buf) + 1;
			if (key == KEY_content_length) {
				G.content_len = BB_STRTOOFF(str, NULL, 10);
				if (G.content_len < 0 || errno) {
					bb_error_msg_and_die("content-length %s is garbage", sanitize_string(str));
				}
				G.got_clen = 1;
				continue;
			}
			if (key == KEY_transfer_encoding) {
				if (strcmp(str_tolower(str), "chunked") != 0)
					bb_error_msg_and_die("transfer encoding '%s' is not supported", sanitize_string(str));
				G.chunked = 1;
			}
			if (key == KEY_location && status >= 300) {
				if (--redir_limit == 0)
					bb_error_msg_and_die("too many redirections");
				fclose(sfp);
				if (str[0] == '/') {
					free(redirected_path);
					target.path = redirected_path = xstrdup(str+1);
					/* lsa stays the same: it's on the same server */
				} else {
					parse_url(str, &target);
					if (!use_proxy) {
						free(server.allocated);
						server.allocated = NULL;
						server.host = target.host;
						/* strip_ipv6_scope_id(target.host); - no! */
						/* we assume remote never gives us IPv6 addr with scope id */
						server.port = target.port;
						free(lsa);
						goto resolve_lsa;
					} /* else: lsa stays the same: we use proxy */
				}
				goto establish_session;
			}
		}
//		if (status >= 300)
//			bb_error_msg_and_die("bad redirection (no Location: header from server)");

		/* For HTTP, data is pumped over the same connection */
		dfp = sfp;

	} else {
Пример #21
0
static FILE* prepare_ftp_session(FILE **dfpp, struct host_info *target, len_and_sockaddr *lsa)
{
    char buf[512];
    FILE *sfp;
    char *str;
    int port;

    if (!target->user)
        target->user = xstrdup("anonymous:busybox@");

    sfp = open_socket(lsa);
    if (ftpcmd(NULL, NULL, sfp, buf) != 220)
        bb_error_msg_and_die("%s", sanitize_string(buf+4));

    /*
     * Splitting username:password pair,
     * trying to log in
     */
    str = strchr(target->user, ':');
    if (str)
        *str++ = '\0';
    switch (ftpcmd("USER ", target->user, sfp, buf)) {
    case 230:
        break;
    case 331:
        if (ftpcmd("PASS ", str, sfp, buf) == 230)
            break;
    /* fall through (failed login) */
    default:
        bb_error_msg_and_die("ftp login: %s", sanitize_string(buf+4));
    }

    ftpcmd("TYPE I", NULL, sfp, buf);

    /*
     * Querying file size
     */
    if (ftpcmd("SIZE ", target->path, sfp, buf) == 213) {
        G.content_len = BB_STRTOOFF(buf+4, NULL, 10);
        if (G.content_len < 0 || errno) {
            bb_error_msg_and_die("SIZE value is garbage");
        }
        G.got_clen = 1;
    }

    /*
     * Entering passive mode
     */
    if (ftpcmd("PASV", NULL, sfp, buf) != 227) {
pasv_error:
        bb_error_msg_and_die("bad response to %s: %s", "PASV", sanitize_string(buf));
    }
    // Response is "227 garbageN1,N2,N3,N4,P1,P2[)garbage]
    // Server's IP is N1.N2.N3.N4 (we ignore it)
    // Server's port for data connection is P1*256+P2
    str = strrchr(buf, ')');
    if (str) str[0] = '\0';
    str = strrchr(buf, ',');
    if (!str) goto pasv_error;
    port = xatou_range(str+1, 0, 255);
    *str = '\0';
    str = strrchr(buf, ',');
    if (!str) goto pasv_error;
    port += xatou_range(str+1, 0, 255) * 256;
    set_nport(lsa, htons(port));

    *dfpp = open_socket(lsa);

    if (G.beg_range) {
        sprintf(buf, "REST %"OFF_FMT"u", G.beg_range);
        if (ftpcmd(buf, NULL, sfp, buf) == 350)
            G.content_len -= G.beg_range;
    }

    if (ftpcmd("RETR ", target->path, sfp, buf) > 150)
        bb_error_msg_and_die("bad response to %s: %s", "RETR", sanitize_string(buf));

    return sfp;
}
Пример #22
0
static void parse_url(const char *src_url, struct host_info *h)
{
	char *url, *p, *sp;

	free(h->allocated);
	h->allocated = url = xstrdup(src_url);

	if (strncmp(url, "http://", 7) == 0) {
		h->port = bb_lookup_port("http", "tcp", 80);
		h->host = url + 7;
		h->is_ftp = 0;
	} else if (strncmp(url, "ftp://", 6) == 0) {
		h->port = bb_lookup_port("ftp", "tcp", 21);
		h->host = url + 6;
		h->is_ftp = 1;
	} else
		bb_error_msg_and_die("not an http or ftp url: %s", sanitize_string(url));

	// FYI:
	// "Real" wget 'http://busybox.net?var=a/b' sends this request:
	//   'GET /?var=a/b HTTP 1.0'
	//   and saves 'index.html?var=a%2Fb' (we save 'b')
	// wget 'http://busybox.net?login=john@doe':
	//   request: 'GET /?login=john@doe HTTP/1.0'
	//   saves: 'index.html?login=john@doe' (we save '?login=john@doe')
	// wget 'http://busybox.net#test/test':
	//   request: 'GET / HTTP/1.0'
	//   saves: 'index.html' (we save 'test')
	//
	// We also don't add unique .N suffix if file exists...
	sp = strchr(h->host, '/');
	p = strchr(h->host, '?'); if (!sp || (p && sp > p)) sp = p;
	p = strchr(h->host, '#'); if (!sp || (p && sp > p)) sp = p;
	if (!sp) {
		h->path = "";
	} else if (*sp == '/') {
		*sp = '\0';
		h->path = sp + 1;
	} else { // '#' or '?'
		// http://busybox.net?login=john@doe is a valid URL
		// memmove converts to:
		// http:/busybox.nett?login=john@doe...
		memmove(h->host - 1, h->host, sp - h->host);
		h->host--;
		sp[-1] = '\0';
		h->path = sp;
	}

	// We used to set h->user to NULL here, but this interferes
	// with handling of code 302 ("object was moved")

	sp = strrchr(h->host, '@');
	if (sp != NULL) {
		// URL-decode "user:password" string before base64-encoding:
		// wget http://test:my%[email protected] should send
		// Authorization: Basic dGVzdDpteSBwYXNz
		// which decodes to "test:my pass".
		// Standard wget and curl do this too.
		*sp = '\0';
		h->user = percent_decode_in_place(h->host, /*strict:*/ 0);
		h->host = sp + 1;
	}

	sp = h->host;
}
Пример #23
0
FILE *start_wget(char *url, int *total)
{
	char buf[512];
	struct host_info server, target;
	len_and_sockaddr *lsa;
	int redir_limit;
#if ENABLE_FEATURE_WGET_LONG_OPTIONS
	char *post_data;
	char *extra_headers = NULL;
	llist_t *headers_llist = NULL;
#endif
	FILE *sfp;                      /* socket to web/ftp server         */
	int use_proxy = 0;              /* Use proxies if env vars are set  */
	const char *user_agent = "Wget";/* "User-Agent" header field        */
	struct globals state;
	char *str;
	int status;
    bzero(&state, sizeof(state));

	static const char keywords[] =
		"content-length\0""transfer-encoding\0""chunked\0""location\0";
	enum {
		KEY_content_length = 1, KEY_transfer_encoding, KEY_chunked, KEY_location
	};

	target.user = NULL;
	parse_url(url, &target);

	state.timeout_seconds = 900;
	server.port = target.port;
	server.host = target.host;

#if 0
	if (opt & WGET_OPT_CONTINUE) {
		output_fd = open(fname_out, O_WRONLY);
		if (output_fd >= 0) {
			state.beg_range = xlseek(output_fd, 0, SEEK_END);
		}
		/* File doesn't exist. We do not create file here yet.
		 * We are not sure it exists on remove side */
	}
#endif

	redir_limit = 5;
 resolve_lsa:
	lsa = xhost2sockaddr(server.host, server.port);
 establish_session:
	/*
	 *  HTTP session
	 */

	/* Open socket to http server */
	sfp = open_socket(lsa);
	if (!sfp) {
		ERROR("Couldn't connect to %s:%d", server.host, server.port);
		return NULL;
	}

	/* Send HTTP request */
	fprintf(sfp, "GET /%s HTTP/1.1\r\n", target.path);

	fprintf(sfp, "Host: %s\r\nUser-Agent: %s\r\n",
		target.host, user_agent);

	/* Ask server to close the connection as soon as we are done
	 * (IOW: we do not intend to send more requests)
	 */
	fprintf(sfp, "Connection: close\r\n");

	if (state.beg_range)
		fprintf(sfp, "Range: bytes=%lu-\r\n", state.beg_range);

	fprintf(sfp, "\r\n");
	fflush(sfp);


	/*
	 * Retrieve HTTP response line and check for "200" status code.
	 */
 read_response:
	if (fgets(buf, sizeof(buf), sfp) == NULL)
		ERROR("no response from server");

	str = buf;
	str = skip_non_whitespace(str);
	str = skip_whitespace(str);
	// FIXME: no error check
	// xatou wouldn't work: "200 OK"
	status = atoi(str);
	switch (status) {
	case 0:
	case 100:
		while (gethdr(buf, sizeof(buf), sfp /*, &n*/) != NULL)
			/* eat all remaining headers */;
		goto read_response;
	case 200:
/*
Response 204 doesn't say "null file", it says "metadata
has changed but data didn't":

"10.2.5 204 No Content
The server has fulfilled the request but does not need to return
an entity-body, and might want to return updated metainformation.
The response MAY include new or updated metainformation in the form
of entity-headers, which if present SHOULD be associated with
the requested variant.

If the client is a user agent, it SHOULD NOT change its document
view from that which caused the request to be sent. This response
is primarily intended to allow input for actions to take place
without causing a change to the user agent's active document view,
although any new or updated metainformation SHOULD be applied
to the document currently in the user agent's active view.

The 204 response MUST NOT include a message-body, and thus
is always terminated by the first empty line after the header fields."

However, in real world it was observed that some web servers
(e.g. Boa/0.94.14rc21) simply use code 204 when file size is zero.
*/
	case 204:
		break;
	case 300:  /* redirection */
	case 301:
	case 302:
	case 303:
		break;
	case 206:
		if (state.beg_range)
			break;
		/* fall through */
	default:
		ERROR("server returned error: %s", sanitize_string(buf));
	}

	/*
	 * Retrieve HTTP headers.
	 */
	while ((str = gethdr(buf, sizeof(buf), sfp /*, &n*/)) != NULL) {
		/* gethdr converted "FOO:" string to lowercase */
		smalluint key;
		/* strip trailing whitespace */
		char *s = strchrnul(str, '\0') - 1;
		while (s >= str && (*s == ' ' || *s == '\t')) {
			*s = '\0';
			s--;
		}
		key = index_in_strings(keywords, buf) + 1;
		if (key == KEY_content_length) {
			state.content_len = strtoul(str, NULL, 10);
			state.total_len   = strtoul(str, NULL, 10);
			if (state.content_len < 0 || errno) {
				ERROR("content-length %s is garbage", sanitize_string(str));
			}
			state.got_clen = 1;
			continue;
		}
		if (key == KEY_transfer_encoding) {
			if (index_in_strings(keywords, str_tolower(str)) + 1 != KEY_chunked)
				ERROR("transfer encoding '%s' is not supported", sanitize_string(str));
			state.chunked = state.got_clen = 1;
		}
		if (key == KEY_location && status >= 300) {
			if (--redir_limit == 0)
				ERROR("too many redirections");
			fclose(sfp);
			state.got_clen = 0;
			state.chunked = 0;
			if (str[0] == '/')
				/* free(target.allocated); */
				target.path = /* target.allocated = */ strdup(str+1);
				/* lsa stays the same: it's on the same server */
			else {
				parse_url(str, &target);
				if (!use_proxy) {
					server.host = target.host;
					server.port = target.port;
					free(lsa);
					goto resolve_lsa;
				} /* else: lsa stays the same: we use proxy */
			}
			goto establish_session;
		}
	}
//		if (status >= 300)
//			ERROR("bad redirection (no Location: header from server)");


	if (total)
		*total = state.content_len;
	ndelay_off(fileno(sfp));
	clearerr(sfp);
	return sfp;
#if 0
	if (retrieve_file_data(&state, sfp, progress, handle, data))
		return -1;
	handle(data, NULL, 0);

	return EXIT_SUCCESS;
#endif
}
Пример #24
0
/**
 Search for a hostname match in the SubjectAlternativeNames.
*/
uint32_t
check_san (SSL *ssl, const char *hostname)
{
  X509 *cert;
  int extcount, ok = 0;
  /* What an OpenSSL mess ... */
  if (NULL == (cert = SSL_get_peer_certificate(ssl)))
  {
    die ("Getting certificate failed");
  }

  if ((extcount = X509_get_ext_count(cert)) > 0)
  {
    int i;
    for (i = 0; i < extcount; ++i)
    {
      const char *extstr;
      X509_EXTENSION *ext;
      ext = X509_get_ext(cert, i);
      extstr = OBJ_nid2sn(OBJ_obj2nid(X509_EXTENSION_get_object(ext)));

      if (!strcmp(extstr, "subjectAltName"))
      {

        int j;
        void *extvalstr;
        const unsigned char *tmp;

        STACK_OF(CONF_VALUE) *val;
        CONF_VALUE *nval;
#if OPENSSL_VERSION_NUMBER >= 0x10000000L
        const
#endif
        X509V3_EXT_METHOD *method;

        if (!(method = X509V3_EXT_get(ext)))
        {
          break;
        }

        tmp = ext->value->data;
        if (method->it)
        {
          extvalstr = ASN1_item_d2i(NULL, &tmp, ext->value->length,
                                    ASN1_ITEM_ptr(method->it));
        } else {
          extvalstr = method->d2i(NULL, &tmp, ext->value->length);
        }

        if (!extvalstr)
        {
          break;
        }

        if (method->i2v)
        {
          val = method->i2v(method, extvalstr, NULL);
          for (j = 0; j < sk_CONF_VALUE_num(val); ++j)
          {
            nval = sk_CONF_VALUE_value(val, j);
            if ((!strcasecmp(nval->name, "DNS") &&
                !strcasecmp(nval->value, hostname) ) ||
                (!strcasecmp(nval->name, "iPAddress") &&
                !strcasecmp(nval->value, hostname)))
            {
              verb ("V: subjectAltName matched: %s, type: %s", nval->value, nval->name); // We matched this; so it's safe to print
              ok = 1;
              break;
            }
            // Attempt to match subjectAltName DNS names
            if (!strcasecmp(nval->name, "DNS"))
            {
              ok = check_wildcard_match_rfc2595(hostname, nval->value);
              if (ok)
              {
                break;
              }
            }
            verb_debug ("V: subjectAltName found but not matched: %s, type: %s",
                nval->value, sanitize_string(nval->name));
          }
        }
      } else {
        verb_debug ("V: found non subjectAltName extension");
      }
      if (ok)
      {
        break;
      }
    }
  } else {
    verb_debug ("V: no X509_EXTENSION field(s) found");
  }
  X509_free(cert);
  return ok;
}
Пример #25
0
void add_cell(boost::intmax_t val, const std::string& table_name, const std::string& row_name, const std::string& column_heading)
{
   //
   // Load the table, add our data, and re-write:
   //
   std::string table_id = "table_" + sanitize_string(table_name);
   boost::regex table_e("\\[table:" + table_id
      + "\\s[^\\[]++"
      "((\\["
      "([^\\[\\]]*+(?2)?+)*+"
      "\\]\\s*+)*+\\s*+)"
      "\\]"
      );

   boost::smatch table_location;
   if(regex_search(content, table_location, table_e))
   {
      std::vector<std::vector<std::string> > table_data;
      load_table(table_data, table_location[1].first, table_location[1].second);
      //
      // Figure out which column we're on:
      //
      unsigned column_id = 1001u;
      for(unsigned i = 0; i < table_data[0].size(); ++i)
      {
         if(table_data[0][i] == column_heading)
         {
            column_id = i;
            break;
         }
      }
      if(column_id > 1000)
      {
         //
         // Need a new column, must be adding a new compiler to the table!
         //
         table_data[0].push_back(column_heading);
         for(unsigned i = 1; i < table_data.size(); ++i)
            table_data[i].push_back(std::string());
         column_id = table_data[0].size() - 1;
      }
      //
      // Figure out the row:
      //
      unsigned row_id = 1001;
      for(unsigned i = 1; i < table_data.size(); ++i)
      {
         if(table_data[i][0] == row_name)
         {
            row_id = i;
            break;
         }
      }
      if(row_id > 1000)
      {
         //
         // Need a new row, add it now:
         //
         table_data.push_back(std::vector<std::string>());
         table_data.back().push_back(row_name);
         for(unsigned i = 1; i < table_data[0].size(); ++i)
            table_data.back().push_back(std::string());
         row_id = table_data.size() - 1;
      }
      //
      // Find the best result in this row:
      //
      boost::uintmax_t best = (std::numeric_limits<boost::uintmax_t>::max)();
      std::vector<boost::intmax_t> values;
      for(unsigned i = 1; i < table_data[row_id].size(); ++i)
      {
         if(i == column_id)
         {
            if(val < best)
               best = val;
            values.push_back(val);
         }
         else
         {
            std::cout << "Existing cell value was " << table_data[row_id][i] << std::endl;
            boost::uintmax_t cell_val = get_value_from_cell(table_data[row_id][i]);
            std::cout << "Extracted value: " << cell_val << std::endl;
            if(cell_val < best)
               best = cell_val;
            values.push_back(cell_val);
         }
      }
      //
      // Update the row:
      //
      for(unsigned i = 1; i < table_data[row_id].size(); ++i)
      {
         std::string& s = table_data[row_id][i];
         s = "[role ";
         if(values[i - 1] < 0)
         {
            s += "grey -]";
         }
         else
         {
            s += get_colour(values[i - 1], best);
            s += " ";
            s += format_precision(static_cast<double>(values[i - 1]) / best, 2);
            s += "[br](";
            s += boost::lexical_cast<std::string>(values[i - 1]) + "ns)]";
         }
      }
      //
      // Convert back to a string and insert into content:
      std::sort(table_data.begin() + 1, table_data.end(), [](std::vector<std::string> const& a, std::vector<std::string> const& b) { return a[0] < b[0]; } );
      std::string c = save_table(table_data);
      content.replace(table_location.position(1), table_location.length(1), c);
   }
   else
   {
      //
      // Create a new table and try again:
      //
      std::string new_table = "\n[template " + table_id;
      new_table += "[]\n[table:" + table_id;
      new_table += " ";
      new_table += table_name;
      new_table += "\n[[Function][";
      new_table += column_heading;
      new_table += "]]\n";
      new_table += "[[";
      new_table += row_name;
      new_table += "][[role blue 1.00[br](";
      new_table += boost::lexical_cast<std::string>(val);
      new_table += "ns)]]]\n]\n]\n";

      std::string::size_type pos = content.find("[/tables:]");
      if(pos != std::string::npos)
         content.insert(pos + 10, new_table);
      else
         content += "\n\n[/tables:]\n" + new_table;
      //
      // Add a section for this table as well:
      //
      std::string section_id = "section_" + sanitize_string(table_name);
      if(content.find(section_id + "[]") == std::string::npos)
      {
         std::string new_section = "\n[template " + section_id + "[]\n[section:" + section_id + " " + table_name + "]\n[" + table_id + "]\n[endsect]\n]\n";
         pos = content.find("[/sections:]");
         if(pos != std::string::npos)
            content.insert(pos + 12, new_section);
         else
            content += "\n\n[/sections:]\n" + new_section;
         add_to_all_sections(section_id);
      }
      //
      // Add to list of all tables (not in sections):
      //
      add_to_all_sections(table_id, "performance_all_tables");
   }
}
Пример #26
0
static int
handle_date_line(const char *dateline, uint32_t *result)
{
  int year,mon,day,hour,min,sec;
  char month[4];
  struct tm tm;
  int i;
  time_t t;
  /* We recognize the three formats in RFC2616, section 3.3.1.  Month
     names are always in English.  The formats are:

      Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123
      Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
      Sun Nov  6 08:49:37 1994       ; ANSI C's asctime() format

     Note that the first is preferred.
   */

  static const char *MONTHS[] =
    { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
      "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", NULL };

  if (strncmp("\r\nDate: ", dateline, 8))
    return 0;

  dateline += 8;
  if (strlen(dateline) > MAX_DATE_LINE_LEN) {
    verb("V: The date line was impossibly long.");
    return -1;
  }
  verb("V: The alleged date is <%s>", sanitize_string(dateline));

  while (*dateline == ' ')
    ++dateline;
  while (*dateline && *dateline != ' ')
    ++dateline;
  while (*dateline == ' ')
    ++dateline;
  /* We just skipped over the day of the week. Now we have:*/
  if (sscanf(dateline, "%d %3s %d %d:%d:%d",
             &day, month, &year, &hour, &min, &sec) == 6 ||
      sscanf(dateline, "%d-%3s-%d %d:%d:%d",
             &day, month, &year, &hour, &min, &sec) == 6 ||
      sscanf(dateline, "%3s %d %d:%d:%d %d",
             month, &day, &hour, &min, &sec, &year) == 6) {

    /* Two digit dates are defined to be relative to 1900; all other dates
     * are supposed to be represented as four digits. */
    if (year < 100)
      year += 1900;

    verb("V: Parsed the date: %04d-%s-%02d %02d:%02d:%02d",
         year, month, day, hour, min, sec);
  } else {
    verb("V: Couldn't parse date.");
    return -1;
  }

  for (i = 0; ; ++i) {
    if (!MONTHS[i])
      return -2;
    if (!strcmp(month, MONTHS[i])) {
      mon = i;
      break;
    }
  }

  memset(&tm, 0, sizeof(tm));
  tm.tm_year = year - 1900;
  tm.tm_mon = mon;
  tm.tm_mday = day;
  tm.tm_hour = hour;
  tm.tm_min = min;
  tm.tm_sec = sec;

  t = timegm(&tm);
  if (t > 0xffffffff || t < 0)
    return -1;

  *result = (uint32_t) t;

  return 1;
}
Пример #27
0
/*
 * Check if the NAND chip is ONFI compliant, returns 1 if it is, 0 otherwise.
 */
int nand_onfi_detect(struct nand_chip *chip)
{
	struct mtd_info *mtd = nand_to_mtd(chip);
	struct nand_onfi_params *p;
	struct onfi_params *onfi;
	int onfi_version = 0;
	char id[4];
	int i, ret, val;

	/* Try ONFI for unknown chip or LP */
	ret = nand_readid_op(chip, 0x20, id, sizeof(id));
	if (ret || strncmp(id, "ONFI", 4))
		return 0;

	/* ONFI chip: allocate a buffer to hold its parameter page */
	p = kzalloc((sizeof(*p) * 3), GFP_KERNEL);
	if (!p)
		return -ENOMEM;

	ret = nand_read_param_page_op(chip, 0, NULL, 0);
	if (ret) {
		ret = 0;
		goto free_onfi_param_page;
	}

	for (i = 0; i < 3; i++) {
		ret = nand_read_data_op(chip, &p[i], sizeof(*p), true);
		if (ret) {
			ret = 0;
			goto free_onfi_param_page;
		}

		if (onfi_crc16(ONFI_CRC_BASE, (u8 *)&p[i], 254) ==
				le16_to_cpu(p->crc)) {
			if (i)
				memcpy(p, &p[i], sizeof(*p));
			break;
		}
	}

	if (i == 3) {
		const void *srcbufs[3] = {p, p + 1, p + 2};

		pr_warn("Could not find a valid ONFI parameter page, trying bit-wise majority to recover it\n");
		nand_bit_wise_majority(srcbufs, ARRAY_SIZE(srcbufs), p,
				       sizeof(*p));

		if (onfi_crc16(ONFI_CRC_BASE, (u8 *)p, 254) !=
				le16_to_cpu(p->crc)) {
			pr_err("ONFI parameter recovery failed, aborting\n");
			goto free_onfi_param_page;
		}
	}

	if (chip->manufacturer.desc && chip->manufacturer.desc->ops &&
	    chip->manufacturer.desc->ops->fixup_onfi_param_page)
		chip->manufacturer.desc->ops->fixup_onfi_param_page(chip, p);

	/* Check version */
	val = le16_to_cpu(p->revision);
	if (val & ONFI_VERSION_2_3)
		onfi_version = 23;
	else if (val & ONFI_VERSION_2_2)
		onfi_version = 22;
	else if (val & ONFI_VERSION_2_1)
		onfi_version = 21;
	else if (val & ONFI_VERSION_2_0)
		onfi_version = 20;
	else if (val & ONFI_VERSION_1_0)
		onfi_version = 10;

	if (!onfi_version) {
		pr_info("unsupported ONFI version: %d\n", val);
		goto free_onfi_param_page;
	}

	sanitize_string(p->manufacturer, sizeof(p->manufacturer));
	sanitize_string(p->model, sizeof(p->model));
	chip->parameters.model = kstrdup(p->model, GFP_KERNEL);
	if (!chip->parameters.model) {
		ret = -ENOMEM;
		goto free_onfi_param_page;
	}

	mtd->writesize = le32_to_cpu(p->byte_per_page);

	/*
	 * pages_per_block and blocks_per_lun may not be a power-of-2 size
	 * (don't ask me who thought of this...). MTD assumes that these
	 * dimensions will be power-of-2, so just truncate the remaining area.
	 */
	mtd->erasesize = 1 << (fls(le32_to_cpu(p->pages_per_block)) - 1);
	mtd->erasesize *= mtd->writesize;

	mtd->oobsize = le16_to_cpu(p->spare_bytes_per_page);

	/* See erasesize comment */
	chip->chipsize = 1 << (fls(le32_to_cpu(p->blocks_per_lun)) - 1);
	chip->chipsize *= (uint64_t)mtd->erasesize * p->lun_count;
	chip->bits_per_cell = p->bits_per_cell;

	chip->max_bb_per_die = le16_to_cpu(p->bb_per_lun);
	chip->blocks_per_die = le32_to_cpu(p->blocks_per_lun);

	if (le16_to_cpu(p->features) & ONFI_FEATURE_16_BIT_BUS)
		chip->options |= NAND_BUSWIDTH_16;

	if (p->ecc_bits != 0xff) {
		chip->ecc_strength_ds = p->ecc_bits;
		chip->ecc_step_ds = 512;
	} else if (onfi_version >= 21 &&
		(le16_to_cpu(p->features) & ONFI_FEATURE_EXT_PARAM_PAGE)) {

		/*
		 * The nand_flash_detect_ext_param_page() uses the
		 * Change Read Column command which maybe not supported
		 * by the chip->legacy.cmdfunc. So try to update the
		 * chip->legacy.cmdfunc now. We do not replace user supplied
		 * command function.
		 */
		nand_legacy_adjust_cmdfunc(chip);

		/* The Extended Parameter Page is supported since ONFI 2.1. */
		if (nand_flash_detect_ext_param_page(chip, p))
			pr_warn("Failed to detect ONFI extended param page\n");
	} else {
		pr_warn("Could not retrieve ONFI ECC requirements\n");
	}

	/* Save some parameters from the parameter page for future use */
	if (le16_to_cpu(p->opt_cmd) & ONFI_OPT_CMD_SET_GET_FEATURES) {
		chip->parameters.supports_set_get_features = true;
		bitmap_set(chip->parameters.get_feature_list,
			   ONFI_FEATURE_ADDR_TIMING_MODE, 1);
		bitmap_set(chip->parameters.set_feature_list,
			   ONFI_FEATURE_ADDR_TIMING_MODE, 1);
	}

	onfi = kzalloc(sizeof(*onfi), GFP_KERNEL);
	if (!onfi) {
		ret = -ENOMEM;
		goto free_model;
	}

	onfi->version = onfi_version;
	onfi->tPROG = le16_to_cpu(p->t_prog);
	onfi->tBERS = le16_to_cpu(p->t_bers);
	onfi->tR = le16_to_cpu(p->t_r);
	onfi->tCCS = le16_to_cpu(p->t_ccs);
	onfi->async_timing_mode = le16_to_cpu(p->async_timing_mode);
	onfi->vendor_revision = le16_to_cpu(p->vendor_revision);
	memcpy(onfi->vendor, p->vendor, sizeof(p->vendor));
	chip->parameters.onfi = onfi;

	/* Identification done, free the full ONFI parameter page and exit */
	kfree(p);

	return 1;

free_model:
	kfree(chip->parameters.model);
free_onfi_param_page:
	kfree(p);

	return ret;
}
Пример #28
0
/* handle_entry: parses and handles the given entry. */
int handle_entry (int num_tokens, const char **token, string *cur_origin,
                  const string *top_origin, unsigned int *ttl) {
    int i;

    if (!num_tokens) return 0;

    /* $ORIGIN */
    if (!strcasecmp (token[0], "$ORIGIN")) {
        if (num_tokens != 2)
            fatal ("$ORIGIN directive has wrong number "
                   "of arguments", start_line_num);
        if (qualify_domain (cur_origin, token[1], cur_origin))
            fatal ("choked on domain name in $ORIGIN statement",
                   start_line_num);
    /* $TTL */
    } else if (!strcasecmp (token[0], "$TTL")) {
        if (num_tokens != 2) {
            warning ("$TTL directive has wrong number of arguments",
                     start_line_num);
            *ttl = DEFAULT_TTL;
        } else if (str_to_uint (ttl, token[1], 1) ||
               *ttl > 2147483646) {
            warning ("invalid $TTL value; using default instead",
                 start_line_num);
            *ttl = DEFAULT_TTL;
        }
    /* $GENERATE */
    } else if (!strcasecmp (token[0], "$GENERATE")) {
        int start, stop, step, found, num_lhs_parts, num_rhs_parts;
        char *lhs_parts[MAX_GEN_PARTS], *rhs_parts[MAX_GEN_PARTS];
        int lhs_offsets[MAX_GEN_PARTS], rhs_offsets[MAX_GEN_PARTS];
        int lhs_widths[MAX_GEN_PARTS], rhs_widths[MAX_GEN_PARTS];
        char lhs_bases[MAX_GEN_PARTS], rhs_bases[MAX_GEN_PARTS];
        char lhs_line[LINE_LEN+1], rhs_line[LINE_LEN+1];
        char lhs_str[DOMAIN_STR_LEN], rhs_str[DOMAIN_STR_LEN];
        char *gen_token[3];

        if (num_tokens != 5)
            fatal ("$GENERATE directive has wrong number "
                   "of arguments", start_line_num);
        if (strcasecmp (token[3], "PTR") &&
            strcasecmp (token[3], "CNAME") &&
            strcasecmp (token[3], "A") &&
            strcasecmp (token[3], "NS"))
            fatal ("$GENERATE directive has unknown RR type",
                   start_line_num);

        gen_token[1] = (char *) token[3];

        /* read range */
        for (found = 0, start = 0, i = 0;
             token[1][i] >= '0' && token[1][i] <= '9'; i++) {
            start *= 10;
            start += token[1][i] - '0';
            found = 1;
        }
        if (!found || token[1][i] != '-')
            fatal ("$GENERATE directive has invalid range "
                   "(unable to parse start)", start_line_num);
        for (found = 0, stop = 0, i++;
             token[1][i] >= '0' && token[1][i] <= '9'; i++) {
            stop *= 10;
            stop += token[1][i] - '0';
            found = 1;
        }
        if (!found || (token[1][i] != '\0' && token[1][i] != '/'))
            fatal ("$GENERATE directive has invalid range "
                   "(unable to parse stop)", start_line_num);
        if (token[1][i] == '/') {
            for (found = 0, step = 0, i++;
                 token[1][i] >= '0' && token[1][i] <= '9'; i++) {
                step *= 10;
                step += token[1][i] - '0';
                found = 1;
            }
            if (!found || token[1][i] != '\0' || !step)
                fatal ("$GENERATE directive has invalid range "
                       "(unable to parse step)",
                       start_line_num);
        } else {
            step = 1;
        }

        /* parse lhs and rhs */
        strcpy (lhs_line, token[2]);
        strcpy (rhs_line, token[4]);
        parse_gen_string (lhs_line, lhs_parts, lhs_offsets,
                  lhs_widths, lhs_bases, &num_lhs_parts);
        parse_gen_string (rhs_line, rhs_parts, rhs_offsets,
                  rhs_widths, rhs_bases, &num_rhs_parts);

        /* pass generated lines back into this function */
        for (i = start; i <= stop; i += step) {
            construct_gen_output (lhs_str, lhs_parts, lhs_offsets,
                          lhs_widths, lhs_bases,
                          num_lhs_parts, i);
            construct_gen_output (rhs_str, rhs_parts, rhs_offsets,
                          rhs_widths, rhs_bases,
                          num_rhs_parts, i);
            gen_token[0] = lhs_str;
            gen_token[2] = rhs_str;

            handle_entry (3, (const char **) gen_token,
                      cur_origin, top_origin, ttl);
        }
    /* $INCLUDE */
    } else if (!strcasecmp (token[0], "$INCLUDE")) {
        fatal ("sorry, $INCLUDE directive is not implemented",
               start_line_num);
    } else if (token[0][0] == '$') {
        warning ("ignoring unknown $ directive", start_line_num);
    /* handle records */
    } else {
        int next;
        unsigned int local_ttl;
        static string owner;
        static int prev_owner = 0;
        string rdomain;

        if (num_tokens < 3) {
            fatal("RR does not have enough tokens", start_line_num);
        }

        if (strcmp(token[0], " ")) {
            if (qualify_domain(&owner, token[0], cur_origin)) {
                fatal("choked on owner name in RR", start_line_num);
            }
            /* we only need to check that this data is within the top-level
             * origin if the top level origin isn't ".". */
            if (strcmp(top_origin->text, ".")) {
                /* we know that the data is out-of-zone if:
                 * 1) the origin is longer than this record's owner
                 * 2) the fully-qualified owner doesn't end with the origin
                 * 3) the owner doesn't equal the origin, and there's no
                 *    period immediately to the left of the origin in the
                 *    owner. */
                if (top_origin->real_len > owner.real_len ||
                    strcasecmp (top_origin->text,
                        owner.text + owner.real_len -
                        top_origin->real_len) ||
                    (owner.real_len > top_origin->real_len &&
                     *(owner.text + owner.real_len -
                       top_origin->real_len - 1) != '.')) {
                    warning ("ignoring out-of-zone data",
                         start_line_num);
                    return 1;
                }
            }
            prev_owner = 1;
        } else {
            if (!prev_owner) {
                fatal ("RR tried to inherit owner from "
                       "previous record, but there was no "
                       "previous RR", start_line_num);
            }
        }

        local_ttl = *ttl;

        /* process ttl and/or class, and find where type
         * token is.  whose brilliant idea was it to let
         * these two come in either order? */
        next = 1;
        if (!str_to_uint (&local_ttl, token[1], 1)) {
            if (local_ttl > 2147483646) {
                warning ("invalid TTL in RR", start_line_num);
                local_ttl = *ttl;
            }
            if (!strcasecmp (token[2], "IN")) {
                next = 3;
            } else {
                next = 2;
            }
        } else if (!strcasecmp (token[1], "IN")) {
            if (!str_to_uint (&local_ttl, token[2], 1)) {
                if (local_ttl > 2147483646) {
                    warning ("invalid TTL in RR",
                             start_line_num);
                    local_ttl = *ttl;
                }
                next = 3;
            } else {
                next = 2;
            }
        }

        /* SOA */
        if (!strcasecmp (token[next], "SOA")) {
            string rname;
            unsigned int serial, refresh, retry;
            unsigned int expire, minimum;
            if (num_tokens - next - 1 == 2)
                fatal ("wrong number of tokens in SOA RDATA "
                       "(perhaps an opening parenthesis is on "
                       "the next line instead of this one?)",
                       start_line_num);
            if (num_tokens - next - 1 != 7)
                fatal ("wrong number of tokens in SOA RDATA",
                       start_line_num);
            if (qualify_domain (&rdomain, token[next+1],
                        cur_origin))
                fatal ("choked on MNAME in SOA RDATA",
                       start_line_num);
            if (qualify_domain (&rname, token[next+2], cur_origin))
                fatal ("choked on RNAME in SOA RDATA",
                       start_line_num);
            if (str_to_uint (&serial, token[next+3], 0))
                fatal ("invalid SERIAL in SOA RDATA",
                       start_line_num);
            if (str_to_uint (&refresh, token[next+4], 1) ||
                refresh > 2147483646)
                fatal ("invalid REFRESH in SOA RDATA",
                       start_line_num);
            if (str_to_uint (&retry, token[next+5], 1) ||
                retry > 2147483646)
                fatal ("invalid RETRY in SOA RDATA",
                       start_line_num);
            if (str_to_uint (&expire, token[next+6], 1) ||
                expire > 2147483646)
                fatal ("invalid EXPIRE in SOA RDATA",
                       start_line_num);
            if (str_to_uint (&minimum, token[next+7], 1) ||
                minimum > 2147483646)
                fatal ("invalid MINIMUM in SOA RDATA",
                       start_line_num);
            fprintf (file, "Z%s:%s:%s:%u:%u:%u:%u:%u\n",
                 owner.text, rdomain.text, rname.text,
                 serial, refresh, retry, expire, minimum);
        /* NS */
        } else if (!strcasecmp (token[next], "NS")) {
            if (num_tokens - next - 1 != 1)
                fatal ("wrong number of tokens in NS RDATA",
                       start_line_num);
            if (qualify_domain (&rdomain, token[next+1],
                        cur_origin))
                fatal ("choked on domain name in NS RDATA",
                       start_line_num);
            fprintf (file, "&%s::%s:%d\n", owner.text,
                 rdomain.text, local_ttl);
        /* MX */
        } else if (!strcasecmp (token[next], "MX")) {
            unsigned int priority;
            if (num_tokens - next - 1 != 2)
                fatal ("wrong number of tokens in MX RDATA",
                       start_line_num);
            if (str_to_uint (&priority, token[next+1], 0) ||
                priority > 65535)
                fatal ("invalid priority in MX RDATA",
                       start_line_num);
            if (qualify_domain (&rdomain, token[next+2],
                        cur_origin))
                fatal ("choked on domain name in MX RDATA",
                       start_line_num);
            fprintf (file, "@%s::%s:%d:%d\n", owner.text,
                 rdomain.text, priority, local_ttl);
        /* A */
        } else if (!strcasecmp (token[next], "A")) {
            char ip[16];
            if (num_tokens - next - 1 != 1)
                fatal ("wrong number of tokens in A RDATA",
                       start_line_num);
            if (sanitize_ip (ip, token[next+1]))
                fatal ("invalid IP address in A RDATA",
                       start_line_num);
            fprintf (file, "+%s:%s:%d\n", owner.text,
                 ip, local_ttl);
        /* AAAA */
        } else if (!strcasecmp (token[next], "AAAA")) {
            unsigned char ipv6_bytes[16];
            if (num_tokens - next - 1 != 1)
                fatal ("wrong number of tokens in AAAA RDATA", start_line_num);
            if (!inet_pton(AF_INET6, token[next+1], ipv6_bytes))
                fatal ("invalid IPv6 address in AAAA RDATA", start_line_num);
            fprintf (file, ":%s:28:", owner.text);
            for (i = 0; i < 16; i++)
                fprintf (file, "\\%03o", ipv6_bytes[i]);
            fprintf (file, ":%d\n", local_ttl);
        /* CNAME */
        } else if (!strcasecmp (token[next], "CNAME")) {
            if (num_tokens - next - 1 != 1)
                fatal ("wrong number of tokens in CNAME RDATA",
                       start_line_num);
            if (qualify_domain (&rdomain, token[next+1],
                        cur_origin))
                fatal ("choked on domain name in CNAME RDATA",
                       start_line_num);
            fprintf (file, "C%s:%s:%d\n", owner.text,
                 rdomain.text, local_ttl);
        /* PTR */
        } else if (!strcasecmp (token[next], "PTR")) {
            if (num_tokens - next - 1 != 1)
                fatal ("wrong number of tokens in PTR RDATA",
                       start_line_num);
            if (qualify_domain (&rdomain, token[next+1],
                        cur_origin))
                fatal ("choked on domain name in PTR RDATA",
                       start_line_num);
            fprintf (file, "^%s:%s:%d\n", owner.text,
                 rdomain.text, local_ttl);
        /* TXT */
        } else if (!strcasecmp (token[next], "TXT")) {
            string txt_rdata;
            if (num_tokens - next - 1 < 1)
                fatal ("too few tokens in TXT RDATA",
                       start_line_num);
            fprintf (file, ":%s:16:", owner.text);
            for (i = next + 1; i < num_tokens; i++) {
                if (sanitize_string (&txt_rdata, token[i]))
                    fatal ("choked while sanitizing TXT "
                           "RDATA", start_line_num);
                fprintf (file, "\\%03o%s", txt_rdata.len,
                     txt_rdata.text);
            }
            fprintf (file, ":%d\n", local_ttl);
        /* SRV */
        } else if (!strcasecmp (token[next], "SRV")) {
            unsigned int priority, weight, port;
            if (num_tokens - next - 1 != 4)
                fatal ("wrong number of tokens "
                       "in SRV RDATA", start_line_num);
            if (str_to_uint (&priority, token[next+1], 0) ||
                priority > 65535)
                fatal ("invalid priority in SRV RDATA",
                       start_line_num);
            if (str_to_uint (&weight, token[next+2], 0) ||
                weight > 65535)
                fatal ("invalid weight in SRV RDATA",
                       start_line_num);
            if (str_to_uint (&port, token[next+3], 0) ||
                port > 65535)
                fatal ("invalid port in SRV RDATA",
                       start_line_num);
            if (qualify_domain (&rdomain, token[next+4],
                        cur_origin))
                fatal ("choked on domain name in SRV "
                       "RDATA", start_line_num);
            if (octal_escape_hostname_labels (&rdomain, rdomain.text)) {
                fatal ("unable to escape hostname labels in SRV RDATA",
                       start_line_num);
            }
            fprintf (file, ":%s:33:\\%03o\\%03o"
                 "\\%03o\\%03o\\%03o\\%03o%s:%d\n",
                 owner.text, priority / 256, priority % 256,
                 weight / 256, weight % 256, port / 256, port % 256,
                 rdomain.text, local_ttl);
        /* other */
        } else {
            warning ("skipping unknown RR type", start_line_num);
        }
    }

    return 0;
}
Пример #29
0
/* qualify_domain: given char* name (in BIND format) and string origin
 * (which has already been passed through sanitize_string), constructs a
 * fully-qualified domain name and copies it to dest.  name and origin can
 * not both be empty.  trailing periods are removed.  a temporary string is
 * used, so dest can point to memory contained in either name or origin.  0
 * is returned on success, and 1 otherwise. */
int qualify_domain (string *dest, const char *name, const string *origin)
{
    string temp, sname;

    if (!dest || !name) {
        warning ("qualify_domain: missing dest or name", -1);
        return 1;
    }

    if (sanitize_string (&sname, name)) {
        warning ("qualify_domain: unable to sanitize name", -1);
        return 1;
    }

    /* if sname isn't empty */
    if (sname.len) {
        if (sname.text[0] == '.' && sname.text[1] != '\0') {
            warning ("qualify_domain: empty label", -1);
            return 1;
        }
        /* make sure sname doesn't have two dots in a row */
        if (strstr (sname.text, "..")) {
            warning ("qualify_domain: empty label", -1);
            return 1;
        }
        /* if sname is '@' */
        if (sname.text[0] == '@' && sname.text[1] == '\0') {
            if (!origin || !origin->len) {
                warning ("qualify_domain: name is '@', "
                     "origin is missing", -1);
                return 1;
            }
            memcpy (&temp, origin, sizeof (string));
        /* name is not '@' */
        } else {
            /* if sname is fully-qualified */
            if (sname.text[sname.real_len-1] == '.') {
                memcpy (&temp, &sname, sizeof (string));
            /* sname is not fully-qualified */
            } else {
                /* origin does not exist */
                if (!origin || !origin->len) {
                    warning ("qualify_domain: name is not "
                         "fully qualified and origin "
                         "is missing", -1);
                    return 1;
                }
                /* if the origin is just the root */
                if (origin->text[0] == '.' &&
                    origin->text[1] == '\0') {
                    /* make sure it fits */
                    if (sname.len + 1 > DOMAIN_LEN) {
                        warning ("qualify_domain: "
                             "name is too "
                             "long", -1);
                        return 1;
                    }
                    memcpy (&temp, &sname, sizeof (string));
                    temp.text[sname.real_len] = '.';
                    temp.text[sname.real_len+1] = '\0';
                    temp.len++;
                    temp.real_len++;
                /* origin is not just root */
                } else {
                    if (sname.len + 1 +
                        origin->len > DOMAIN_LEN) {
                        warning ("qualify_domain: "
                             "name plus origin "
                             "is too long", -1);
                        return 1;
                    }
                    memcpy (&temp, &sname, sizeof (string));
                    temp.text[sname.real_len] = '.';
                    strcpy (temp.text + sname.real_len + 1,
                        origin->text);
                    temp.len += 1 + origin->len;
                    temp.real_len += 1 + origin->real_len;
                }
            }
        }
    /* sname is empty */
    } else {
        /* if origin does not exist */
        if (!origin || !origin->len) {
            warning ("qualify_domain: name and origin are "
                 "both empty or missing", -1);
            return 1;
        }
        memcpy (&temp, origin, sizeof (string));
    }

    memcpy (dest, &temp, sizeof (string));
    return 0;
}
Пример #30
0
void add_cell(const std::string& cell_name, const std::string& table_name, const std::string& row_name, const std::string& type_name)
{
   //
   // Load the table, add our data, and re-write:
   //
   std::string table_id = "table_" + sanitize_string(table_name);
   std::string column_heading = BOOST_COMPILER;
   column_heading += "[br]";
   column_heading += BOOST_PLATFORM;
   column_heading += "[br]";
   column_heading += type_name;
   boost::regex table_e("\\[table:" + table_id
      + "\\s[^\\[]+"
         "((\\["
            "([^\\[\\]]*(?2)?)*"
         "\\]\\s*)*\\s*)"
       "\\]"
       );

   boost::smatch table_location;
   if(regex_search(content, table_location, table_e))
   {
      std::vector<std::vector<std::string> > table_data;
      load_table(table_data, table_location[1].first, table_location[1].second);
      //
      // Figure out which column we're on:
      //
      unsigned column_id = 1001u;
      for(unsigned i = 0; i < table_data[0].size(); ++i)
      {
         if(table_data[0][i] == column_heading)
         {
            column_id = i;
            break;
         }
      }
      if(column_id > 1000)
      {
         //
         // Need a new column, must be adding a new compiler to the table!
         //
         table_data[0].push_back(column_heading);
         for(unsigned i = 1; i < table_data.size(); ++i)
            table_data[i].push_back(std::string());
         column_id = table_data[0].size() - 1;
      }
      //
      // Figure out the row:
      //
      unsigned row_id = 1001;
      for(unsigned i = 1; i < table_data.size(); ++i)
      {
         if(table_data[i][0] == row_name)
         {
            row_id = i;
            break;
         }
      }
      if(row_id > 1000)
      {
         //
         // Need a new row, add it now:
         //
         table_data.push_back(std::vector<std::string>());
         table_data.back().push_back(row_name);
         for(unsigned i = 1; i < table_data[0].size(); ++i)
            table_data.back().push_back(std::string());
         row_id = table_data.size() - 1;
      }
      //
      // Update the entry:
      //
      std::string& s = table_data[row_id][column_id];
      if(s.empty())
      {
         std::cout << "Adding " << cell_name << " to empty cell.";
         s = "[" + cell_name + "]";
      }
      else
      {
         if(cell_name.find("_boost_") != std::string::npos)
         {
            std::cout << "Adding " << cell_name << " to start of cell.";
            s.insert(0, "[" + cell_name + "][br][br]");
         }
         else
         {
            std::cout << "Adding " << cell_name << " to end of cell.";
            if((s.find("_boost_") != std::string::npos) && (s.find("[br]") == std::string::npos))
               s += "[br]"; // extra break if we're adding directly after the boost results.
            s += "[br][" + cell_name + "]";
         }
      }
      //
      // Convert back to a string and insert into content:
      std::string c = save_table(table_data);
      content.replace(table_location.position(1), table_location.length(1), c);
   }
   else
   {
      //
      // Create a new table and try again:
      //
      std::string new_table = "\n[template " + table_id;
      new_table += "[]\n[table:" + table_id;
      new_table += " Error rates for ";
      new_table += table_name;
      new_table += "\n[[][";
      new_table += column_heading;
      new_table += "]]\n";
      new_table += "[[";
      new_table += row_name;
      new_table += "][[";
      new_table += cell_name;
      new_table += "]]]\n]\n]\n";

      std::string::size_type pos = content.find("[/tables:]");
      if(pos != std::string::npos)
         content.insert(pos + 10, new_table);
      else
         content += "\n\n[/tables:]\n" + new_table;
      //
      // Add a section for this table as well:
      //
      std::string section_id = "section_" + sanitize_string(table_name);
      if(content.find(section_id + "[]") == std::string::npos)
      {
         std::string new_section = "\n[template " + section_id + "[]\n[section:" + section_id + " " + table_name + "]\n[" + table_id + "]\n[endsect]\n]\n";
         pos = content.find("[/sections:]");
         if(pos != std::string::npos)
            content.insert(pos + 12, new_section);
         else
            content += "\n\n[/sections:]\n" + new_section;
         add_to_all_sections(section_id);
      }
      //
      // Add to list of all tables (not in sections):
      //
      add_to_all_sections(table_id, "all_tables");
   }
}