Example #1
0
int
main(int argc, char *argv[])
{
	int i;
	int opt;

	while(1) {
		opt = getopt_long(argc, argv, "aBcdDeHPstTvV", long_options, NULL);
		if(opt == -1)
			break;
		switch(opt) {
		case 'v':
			verbose = 1;
			break;
		case 'a':
#ifdef ENABLEGT
			if (optarg != NULL && strncasecmp("gt", optarg, 2) == 0)
				apimode = API_GT; 
#endif
#ifdef ENABLEKSI
			if (optarg != NULL && strncasecmp("ksi", optarg, 2) == 0)
				apimode = API_KSI; 
#endif
			if(verbose)
				fprintf(stdout, "Setting Apimode: %s (%d)\n", optarg, apimode); 
			break;
		case 'd':
			debug = 1;
#ifdef ENABLEGT
			rsgt_set_debug(debug); 
#endif
#ifdef ENABLEKSI
			rsksi_set_debug(debug); 
#endif
			break;
		case 's':
#ifdef ENABLEGT
			rsgt_read_showVerified = 1;
#endif
#ifdef ENABLEKSI
			rsksi_read_showVerified = 1;
#endif
			break;
		case 'V':
			fprintf(stderr, "rsgtutil " VERSION "\n");
			exit(0);
		case 'D':
			mode = MD_DUMP;
			break;
		case 'B':
			mode = MD_SHOW_SIGBLK_PARAMS;
			break;
		case 'P':
#ifdef ENABLEGT
			rsgt_read_puburl = optarg;
#endif
#ifdef ENABLEKSI
			rsksi_read_puburl = optarg;
#endif
			break;
		case 'T':
			mode = MD_DETECT_FILE_TYPE;
			break;
		case 't':
			mode = MD_VERIFY;
			break;
		case 'e':
			mode = MD_EXTEND;
			break;
		case 'c':
			mode = MD_CONVERT;
			break;
		case 'h':
		case '?':
			rsgtutil_usage();
			return 0;
		default:
			fprintf(stderr, "getopt_long() returns unknown value %d\n", opt);
			return 1;
		}
	}

	if(optind == argc)
		processFile("-");
	else {
		for(i = optind ; i < argc ; ++i)
			processFile(argv[i]);
	}

	return 0;
}
Example #2
0
File: util.c Project: 1gh/cpuminer
json_t *json_rpc_call(CURL *curl, const char *url,
		      const char *userpass, const char *rpc_req,
		      bool longpoll_scan, bool longpoll, int *curl_err)
{
	json_t *val, *err_val, *res_val;
	int rc;
	struct data_buffer all_data = {0};
	struct upload_buffer upload_data;
	json_error_t err;
	struct curl_slist *headers = NULL;
	char len_hdr[64];
	char curl_err_str[CURL_ERROR_SIZE];
	long timeout = longpoll ? opt_timeout : 30;
	struct header_info hi = {0};
	bool lp_scanning = longpoll_scan && !have_longpoll;

	/* it is assumed that 'curl' is freshly [re]initialized at this pt */

	if (opt_protocol)
		curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
	curl_easy_setopt(curl, CURLOPT_URL, url);
	if (opt_cert)
		curl_easy_setopt(curl, CURLOPT_CAINFO, opt_cert);
	curl_easy_setopt(curl, CURLOPT_ENCODING, "");
	curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
	curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
	curl_easy_setopt(curl, CURLOPT_TCP_NODELAY, 1);
	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, all_data_cb);
	curl_easy_setopt(curl, CURLOPT_WRITEDATA, &all_data);
	curl_easy_setopt(curl, CURLOPT_READFUNCTION, upload_data_cb);
	curl_easy_setopt(curl, CURLOPT_READDATA, &upload_data);
#if LIBCURL_VERSION_NUM >= 0x071200
	curl_easy_setopt(curl, CURLOPT_SEEKFUNCTION, &seek_data_cb);
	curl_easy_setopt(curl, CURLOPT_SEEKDATA, &upload_data);
#endif
	curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, curl_err_str);
	curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
	curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
	curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, resp_hdr_cb);
	curl_easy_setopt(curl, CURLOPT_HEADERDATA, &hi);
	if (opt_proxy) {
		curl_easy_setopt(curl, CURLOPT_PROXY, opt_proxy);
		curl_easy_setopt(curl, CURLOPT_PROXYTYPE, opt_proxy_type);
	}
	if (userpass) {
		curl_easy_setopt(curl, CURLOPT_USERPWD, userpass);
		curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
	}
#if LIBCURL_VERSION_NUM >= 0x070f06
	if (longpoll)
		curl_easy_setopt(curl, CURLOPT_SOCKOPTFUNCTION, sockopt_keepalive_cb);
#endif
	curl_easy_setopt(curl, CURLOPT_POST, 1);

	if (opt_protocol)
		applog(LOG_DEBUG, "JSON protocol request:\n%s\n", rpc_req);

	upload_data.buf = rpc_req;
	upload_data.len = strlen(rpc_req);
	upload_data.pos = 0;
	sprintf(len_hdr, "Content-Length: %lu",
		(unsigned long) upload_data.len);

	headers = curl_slist_append(headers, "Content-Type: application/json");
	headers = curl_slist_append(headers, len_hdr);
	headers = curl_slist_append(headers, "User-Agent: " USER_AGENT);
	headers = curl_slist_append(headers, "X-Mining-Extensions: midstate");
	headers = curl_slist_append(headers, "Accept:"); /* disable Accept hdr*/
	headers = curl_slist_append(headers, "Expect:"); /* disable Expect hdr*/

	curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

	rc = curl_easy_perform(curl);
	if (curl_err != NULL)
		*curl_err = rc;
	if (rc) {
		if (!(longpoll && rc == CURLE_OPERATION_TIMEDOUT))
			applog(LOG_ERR, "HTTP request failed: %s", curl_err_str);
		goto err_out;
	}

	/* If X-Stratum was found, activate Stratum */
	if (want_stratum && hi.stratum_url &&
	    !strncasecmp(hi.stratum_url, "stratum+tcp://", 14)) {
		have_stratum = true;
		tq_push(thr_info[stratum_thr_id].q, hi.stratum_url);
		hi.stratum_url = NULL;
	}

	/* If X-Long-Polling was found, activate long polling */
	if (lp_scanning && hi.lp_path && !have_stratum) {
		have_longpoll = true;
		tq_push(thr_info[longpoll_thr_id].q, hi.lp_path);
		hi.lp_path = NULL;
	}

	if (!all_data.buf) {
		applog(LOG_ERR, "Empty data received in json_rpc_call.");
		goto err_out;
	}

	val = JSON_LOADS(all_data.buf, &err);
	if (!val) {
		applog(LOG_ERR, "JSON decode failed(%d): %s", err.line, err.text);
		goto err_out;
	}

	if (opt_protocol) {
		char *s = json_dumps(val, JSON_INDENT(3));
		applog(LOG_DEBUG, "JSON protocol response:\n%s", s);
		free(s);
	}

	/* JSON-RPC valid response returns a non-null 'result',
	 * and a null 'error'. */
	res_val = json_object_get(val, "result");
	err_val = json_object_get(val, "error");

	if (!res_val || json_is_null(res_val) ||
	    (err_val && !json_is_null(err_val))) {
		char *s;

		if (err_val)
			s = json_dumps(err_val, JSON_INDENT(3));
		else
			s = strdup("(unknown reason)");

		applog(LOG_ERR, "JSON-RPC call failed: %s", s);

		free(s);

		goto err_out;
	}

	if (hi.reason)
		json_object_set_new(val, "reject-reason", json_string(hi.reason));

	databuf_free(&all_data);
	curl_slist_free_all(headers);
	curl_easy_reset(curl);
	return val;

err_out:
	free(hi.lp_path);
	free(hi.reason);
	free(hi.stratum_url);
	databuf_free(&all_data);
	curl_slist_free_all(headers);
	curl_easy_reset(curl);
	return NULL;
}
Example #3
0
/* Parse an HTTP datestamp into Unix time */
static time_t
make_unix_time(char *s)
{
  struct tm time;
  int i, ysub = 1900, fmt = 0;
  char *month;
  char *n;
  time_t res;

  if (s[3] != ' ')
    {
      fmt = 1;
      if (s[3] != ',')
	ysub = 0;
    }
  for (n = s; *n; ++n)
    if (*n == '-' || *n == ':')
      *n = ' ';

  time.tm_mon = 0;
  n = strchr(s, ' ');
  if (fmt)
    {
      /* Day, DD-MMM-YYYY HH:MM:SS GMT */
      time.tm_mday = strtol(n + 1, &n, 0);
      month = n + 1;
      n = strchr(month, ' ');
      time.tm_year = strtol(n + 1, &n, 0);
      time.tm_hour = strtol(n + 1, &n, 0);
      time.tm_min = strtol(n + 1, &n, 0);
      time.tm_sec = strtol(n + 1, NULL, 0);
    }
  else
    {
      /* Unix ctime() format. Does not conform to HTTP spec. */
      /* Day MMM DD HH:MM:SS YYYY */
      month = n + 1;
      n = strchr(month, ' ');
      while (isspace(*n))
	n++;
      time.tm_mday = strtol(n, &n, 0);
      time.tm_hour = strtol(n + 1, &n, 0);
      time.tm_min = strtol(n + 1, &n, 0);
      time.tm_sec = strtol(n + 1, &n, 0);
      time.tm_year = strtol(n + 1, NULL, 0);
    }
  if (time.tm_year > 100)
    time.tm_year -= ysub;

  for (i = 0; i < 12; i++)
    if (!strncasecmp(month, monthtab[i], 3))
      {
	time.tm_mon = i;
	break;
      }
  time.tm_isdst = 0;		/* daylight saving is never in effect in GMT */

  /* this is normally the value of extern int timezone, but some
   * braindead C libraries don't provide it.
   */
  if (!tzchecked)
    {
      struct tm *tc;
      time_t then = JAN02_1980;
      tc = localtime(&then);
      tzoff = (12 - tc->tm_hour) * 3600 + tc->tm_min * 60 + tc->tm_sec;
      tzchecked = 1;
    }
  res = mktime(&time);
  /* Unfortunately, mktime() assumes the input is in local time,
   * not GMT, so we have to correct it here.
   */
  if (res != -1)
    res += tzoff;
  return res;
}
Example #4
0
static void
device_added(struct udev_device *udev_device)
{
    const char *path, *name = NULL;
    char *config_info = NULL;
    const char *syspath;
    const char *tags_prop;
    const char *key, *value, *tmp;
    InputOption *input_options;
    InputAttributes attrs = { };
    DeviceIntPtr dev = NULL;
    struct udev_list_entry *set, *entry;
    struct udev_device *parent;
    int rc;
    const char *dev_seat;

    path = udev_device_get_devnode(udev_device);

    syspath = udev_device_get_syspath(udev_device);

    if (!path || !syspath)
        return;

    dev_seat = udev_device_get_property_value(udev_device, "ID_SEAT");
    if (!dev_seat)
        dev_seat = "seat0";

    if (SeatId && strcmp(dev_seat, SeatId))
        return;

    if (!SeatId && strcmp(dev_seat, "seat0"))
        return;

#ifdef CONFIG_UDEV_KMS
    if (!strcmp(udev_device_get_subsystem(udev_device), "drm")) {
        const char *sysname = udev_device_get_sysname(udev_device);

        if (strncmp(sysname, "card", 4) != 0)
            return;

        LogMessage(X_INFO, "config/udev: Adding drm device (%s)\n", path);

        config_udev_odev_setup_attribs(path, syspath, NewGPUDeviceRequest);
        return;
    }
#endif

    if (!udev_device_get_property_value(udev_device, "ID_INPUT")) {
        LogMessageVerb(X_INFO, 10,
                       "config/udev: ignoring device %s without "
                       "property ID_INPUT set\n", path);
        return;
    }

    input_options = input_option_new(NULL, "_source", "server/udev");
    if (!input_options)
        return;

    parent = udev_device_get_parent(udev_device);
    if (parent) {
        const char *ppath = udev_device_get_devnode(parent);
        const char *product = udev_device_get_property_value(parent, "PRODUCT");
        const char *pnp_id = udev_device_get_sysattr_value(parent, "id");
        unsigned int usb_vendor, usb_model;

        name = udev_device_get_sysattr_value(parent, "name");
        LOG_SYSATTR(ppath, "name", name);
        if (!name) {
            name = udev_device_get_property_value(parent, "NAME");
            LOG_PROPERTY(ppath, "NAME", name);
        }

        if (pnp_id)
            attrs.pnp_id = strdup(pnp_id);
        LOG_SYSATTR(ppath, "id", pnp_id);

        /* construct USB ID in lowercase hex - "0000:ffff" */
        if (product &&
            sscanf(product, "%*x/%4x/%4x/%*x", &usb_vendor, &usb_model) == 2) {
            if (asprintf(&attrs.usb_id, "%04x:%04x", usb_vendor, usb_model)
                == -1)
                attrs.usb_id = NULL;
            else
                LOG_PROPERTY(ppath, "PRODUCT", product);
        }
    }
    if (!name)
        name = "(unnamed)";
    else
        attrs.product = strdup(name);
    input_options = input_option_new(input_options, "name", name);
    input_options = input_option_new(input_options, "path", path);
    input_options = input_option_new(input_options, "device", path);
    if (path)
        attrs.device = strdup(path);

    tags_prop = udev_device_get_property_value(udev_device, "ID_INPUT.tags");
    LOG_PROPERTY(path, "ID_INPUT.tags", tags_prop);
    attrs.tags = xstrtokenize(tags_prop, ",");

    if (asprintf(&config_info, "udev:%s", syspath) == -1) {
        config_info = NULL;
        goto unwind;
    }

    if (device_is_duplicate(config_info)) {
        LogMessage(X_WARNING, "config/udev: device %s already added. "
                   "Ignoring.\n", name);
        goto unwind;
    }

    set = udev_device_get_properties_list_entry(udev_device);
    udev_list_entry_foreach(entry, set) {
        key = udev_list_entry_get_name(entry);
        if (!key)
            continue;
        value = udev_list_entry_get_value(entry);
        if (!strncasecmp(key, UDEV_XKB_PROP_KEY, sizeof(UDEV_XKB_PROP_KEY) - 1)) {
            LOG_PROPERTY(path, key, value);
            tmp = key + sizeof(UDEV_XKB_PROP_KEY) - 1;
            if (!strcasecmp(tmp, "rules"))
                input_options =
                    input_option_new(input_options, "xkb_rules", value);
            else if (!strcasecmp(tmp, "layout"))
                input_options =
                    input_option_new(input_options, "xkb_layout", value);
            else if (!strcasecmp(tmp, "variant"))
                input_options =
                    input_option_new(input_options, "xkb_variant", value);
            else if (!strcasecmp(tmp, "model"))
                input_options =
                    input_option_new(input_options, "xkb_model", value);
            else if (!strcasecmp(tmp, "options"))
                input_options =
                    input_option_new(input_options, "xkb_options", value);
        }
        else if (!strcmp(key, "ID_VENDOR")) {
            LOG_PROPERTY(path, key, value);
            attrs.vendor = strdup(value);
        }
        else if (!strcmp(key, "ID_INPUT_KEY")) {
            LOG_PROPERTY(path, key, value);
            attrs.flags |= ATTR_KEYBOARD;
        }
        else if (!strcmp(key, "ID_INPUT_MOUSE")) {
            LOG_PROPERTY(path, key, value);
            attrs.flags |= ATTR_POINTER;
        }
        else if (!strcmp(key, "ID_INPUT_JOYSTICK")) {
            LOG_PROPERTY(path, key, value);
            attrs.flags |= ATTR_JOYSTICK;
        }
        else if (!strcmp(key, "ID_INPUT_TABLET")) {
            LOG_PROPERTY(path, key, value);
            attrs.flags |= ATTR_TABLET;
        }
        else if (!strcmp(key, "ID_INPUT_TOUCHPAD")) {
            LOG_PROPERTY(path, key, value);
            attrs.flags |= ATTR_TOUCHPAD;
        }
        else if (!strcmp(key, "ID_INPUT_TOUCHSCREEN")) {
            LOG_PROPERTY(path, key, value);
            attrs.flags |= ATTR_TOUCHSCREEN;
        }
    }
Example #5
0
static int curl_open(BlockDriverState *bs, QDict *options, int flags,
                     Error **errp)
{
    BDRVCURLState *s = bs->opaque;
    CURLState *state = NULL;
    QemuOpts *opts;
    Error *local_err = NULL;
    const char *file;
    double d;

    static int inited = 0;

    if (flags & BDRV_O_RDWR) {
        error_setg(errp, "curl block device does not support writes");
        return -EROFS;
    }

    opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);
    qemu_opts_absorb_qdict(opts, options, &local_err);
    if (local_err) {
        error_propagate(errp, local_err);
        goto out_noclean;
    }

    s->readahead_size = qemu_opt_get_size(opts, "readahead", READ_AHEAD_SIZE);
    if ((s->readahead_size & 0x1ff) != 0) {
        error_setg(errp, "HTTP_READAHEAD_SIZE %zd is not a multiple of 512",
                   s->readahead_size);
        goto out_noclean;
    }

    file = qemu_opt_get(opts, "url");
    if (file == NULL) {
        error_setg(errp, "curl block driver requires an 'url' option");
        goto out_noclean;
    }

    if (!inited) {
        curl_global_init(CURL_GLOBAL_ALL);
        inited = 1;
    }

    DPRINTF("CURL: Opening %s\n", file);
    s->url = g_strdup(file);
    state = curl_init_state(s);
    if (!state)
        goto out_noclean;

    // Get file size

    s->accept_range = false;
    curl_easy_setopt(state->curl, CURLOPT_NOBODY, 1);
    curl_easy_setopt(state->curl, CURLOPT_HEADERFUNCTION,
                     curl_header_cb);
    curl_easy_setopt(state->curl, CURLOPT_HEADERDATA, s);
    if (curl_easy_perform(state->curl))
        goto out;
    curl_easy_getinfo(state->curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &d);
    if (d)
        s->len = (size_t)d;
    else if(!s->len)
        goto out;
    if ((!strncasecmp(s->url, "http://", strlen("http://"))
        || !strncasecmp(s->url, "https://", strlen("https://")))
        && !s->accept_range) {
        pstrcpy(state->errmsg, CURL_ERROR_SIZE,
                "Server does not support 'range' (byte ranges).");
        goto out;
    }
    DPRINTF("CURL: Size = %zd\n", s->len);

    curl_clean_state(state);
    curl_easy_cleanup(state->curl);
    state->curl = NULL;

    aio_timer_init(bdrv_get_aio_context(bs), &s->timer,
                   QEMU_CLOCK_REALTIME, SCALE_NS,
                   curl_multi_timeout_do, s);

    // Now we know the file exists and its size, so let's
    // initialize the multi interface!

    s->multi = curl_multi_init();
    curl_multi_setopt(s->multi, CURLMOPT_SOCKETDATA, s);
    curl_multi_setopt(s->multi, CURLMOPT_SOCKETFUNCTION, curl_sock_cb);
#ifdef NEED_CURL_TIMER_CALLBACK
    curl_multi_setopt(s->multi, CURLMOPT_TIMERDATA, s);
    curl_multi_setopt(s->multi, CURLMOPT_TIMERFUNCTION, curl_timer_cb);
#endif
    curl_multi_do(s);

    qemu_opts_del(opts);
    return 0;

out:
    fprintf(stderr, "CURL: Error opening file: %s\n", state->errmsg);
    curl_easy_cleanup(state->curl);
    state->curl = NULL;
out_noclean:
    g_free(s->url);
    qemu_opts_del(opts);
    return -EINVAL;
}
Example #6
0
php_stream *php_stream_url_wrap_http_ex(php_stream_wrapper *wrapper, char *path, char *mode, int options, char **opened_path, php_stream_context *context, int redirect_max, int header_init STREAMS_DC TSRMLS_DC)
{
	php_stream *stream = NULL;
	php_url *resource = NULL;
	int use_ssl;
	int use_proxy = 0;
	char *scratch = NULL;
	char *tmp = NULL;
	char *ua_str = NULL;
	zval **ua_zval = NULL, **tmpzval = NULL;
	int scratch_len = 0;
	int body = 0;
	char location[HTTP_HEADER_BLOCK_SIZE];
	zval *response_header = NULL;
	int reqok = 0;
	char *http_header_line = NULL;
	char tmp_line[128];
	size_t chunk_size = 0, file_size = 0;
	int eol_detect = 0;
	char *transport_string, *errstr = NULL;
	int transport_len, have_header = 0, request_fulluri = 0;
	char *protocol_version = NULL;
	int protocol_version_len = 3; /* Default: "1.0" */
	struct timeval timeout;
	char *user_headers = NULL;

	tmp_line[0] = '\0';

	if (redirect_max < 1) {
		php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Redirection limit reached, aborting");
		return NULL;
	}

	resource = php_url_parse(path);
	if (resource == NULL) {
		return NULL;
	}

	if (strncasecmp(resource->scheme, "http", sizeof("http")) && strncasecmp(resource->scheme, "https", sizeof("https"))) {
		if (!context || 
			php_stream_context_get_option(context, wrapper->wops->label, "proxy", &tmpzval) == FAILURE ||
			Z_TYPE_PP(tmpzval) != IS_STRING ||
			Z_STRLEN_PP(tmpzval) <= 0) {
			php_url_free(resource);
			return php_stream_open_wrapper_ex(path, mode, REPORT_ERRORS, NULL, context);
		}
		/* Called from a non-http wrapper with http proxying requested (i.e. ftp) */
		request_fulluri = 1;
		use_ssl = 0;
		use_proxy = 1;

		transport_len = Z_STRLEN_PP(tmpzval);
		transport_string = estrndup(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval));
	} else {
		/* Normal http request (possibly with proxy) */
	
		if (strpbrk(mode, "awx+")) {
			php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP wrapper does not support writeable connections");
			php_url_free(resource);
			return NULL;
		}

		use_ssl = resource->scheme && (strlen(resource->scheme) > 4) && resource->scheme[4] == 's';
		/* choose default ports */
		if (use_ssl && resource->port == 0)
			resource->port = 443;
		else if (resource->port == 0)
			resource->port = 80;

		if (context &&
			php_stream_context_get_option(context, wrapper->wops->label, "proxy", &tmpzval) == SUCCESS &&
			Z_TYPE_PP(tmpzval) == IS_STRING &&
			Z_STRLEN_PP(tmpzval) > 0) {
			use_proxy = 1;
			transport_len = Z_STRLEN_PP(tmpzval);
			transport_string = estrndup(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval));
		} else {
			transport_len = spprintf(&transport_string, 0, "%s://%s:%d", use_ssl ? "ssl" : "tcp", resource->host, resource->port);
		}
	}

	if (context && php_stream_context_get_option(context, wrapper->wops->label, "timeout", &tmpzval) == SUCCESS) {
		SEPARATE_ZVAL(tmpzval);
		convert_to_double_ex(tmpzval);
		timeout.tv_sec = (time_t) Z_DVAL_PP(tmpzval);
		timeout.tv_usec = (size_t) ((Z_DVAL_PP(tmpzval) - timeout.tv_sec) * 1000000);
	} else {
		timeout.tv_sec = FG(default_socket_timeout);
		timeout.tv_usec = 0;
	}

	stream = php_stream_xport_create(transport_string, transport_len, options,
			STREAM_XPORT_CLIENT | STREAM_XPORT_CONNECT,
			NULL, &timeout, context, &errstr, NULL);
    
	if (stream) {
		php_stream_set_option(stream, PHP_STREAM_OPTION_READ_TIMEOUT, 0, &timeout);
	}
			
	if (errstr) {
		php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "%s", errstr);
		efree(errstr);
		errstr = NULL;
	}

	efree(transport_string);

	if (stream && use_proxy && use_ssl) {
		smart_str header = {0};

		smart_str_appendl(&header, "CONNECT ", sizeof("CONNECT ")-1);
		smart_str_appends(&header, resource->host);
		smart_str_appendc(&header, ':');
		smart_str_append_unsigned(&header, resource->port);
		smart_str_appendl(&header, " HTTP/1.0\r\n\r\n", sizeof(" HTTP/1.0\r\n\r\n")-1);
		if (php_stream_write(stream, header.c, header.len) != header.len) {
			php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Cannot connect to HTTPS server through proxy");
			php_stream_close(stream);
			stream = NULL;
		}
 	 	smart_str_free(&header);

 	 	if (stream) {
 	 		char header_line[HTTP_HEADER_BLOCK_SIZE];

			/* get response header */
			while (php_stream_gets(stream, header_line, HTTP_HEADER_BLOCK_SIZE-1) != NULL)	{
				if (header_line[0] == '\n' ||
				    header_line[0] == '\r' ||
				    header_line[0] == '\0') {
				  break;
				}
			}
		}

		/* enable SSL transport layer */
		if (stream) {
			if (php_stream_xport_crypto_setup(stream, STREAM_CRYPTO_METHOD_SSLv23_CLIENT, NULL TSRMLS_CC) < 0 ||
			    php_stream_xport_crypto_enable(stream, 1 TSRMLS_CC) < 0) {
				php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Cannot connect to HTTPS server through proxy");
				php_stream_close(stream);
				stream = NULL;
			}
		}
	}

	if (stream == NULL)	
		goto out;

	/* avoid buffering issues while reading header */
	if (options & STREAM_WILL_CAST)
		chunk_size = php_stream_set_chunk_size(stream, 1);
	
	/* avoid problems with auto-detecting when reading the headers -> the headers
	 * are always in canonical \r\n format */
	eol_detect = stream->flags & (PHP_STREAM_FLAG_DETECT_EOL | PHP_STREAM_FLAG_EOL_MAC);
	stream->flags &= ~(PHP_STREAM_FLAG_DETECT_EOL | PHP_STREAM_FLAG_EOL_MAC);

	php_stream_context_set(stream, context);

	php_stream_notify_info(context, PHP_STREAM_NOTIFY_CONNECT, NULL, 0);

	if (header_init && context && php_stream_context_get_option(context, "http", "max_redirects", &tmpzval) == SUCCESS) {
		SEPARATE_ZVAL(tmpzval);
		convert_to_long_ex(tmpzval);
		redirect_max = Z_LVAL_PP(tmpzval);
	}

	if (context && php_stream_context_get_option(context, "http", "method", &tmpzval) == SUCCESS) {
		if (Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0) {
			scratch_len = strlen(path) + 29 + Z_STRLEN_PP(tmpzval);
			scratch = emalloc(scratch_len);
			strlcpy(scratch, Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval) + 1);
			strcat(scratch, " ");
		}
	}
 
	if (context && php_stream_context_get_option(context, "http", "protocol_version", &tmpzval) == SUCCESS) {
		SEPARATE_ZVAL(tmpzval);
		convert_to_double_ex(tmpzval);
		protocol_version_len = spprintf(&protocol_version, 0, "%.1F", Z_DVAL_PP(tmpzval));
	}

	if (!scratch) {
		scratch_len = strlen(path) + 29 + protocol_version_len;
		scratch = emalloc(scratch_len);
		strcpy(scratch, "GET ");
	}

	/* Should we send the entire path in the request line, default to no. */
	if (!request_fulluri &&
		context &&
		php_stream_context_get_option(context, "http", "request_fulluri", &tmpzval) == SUCCESS) {
		zval tmp = **tmpzval;

		zval_copy_ctor(&tmp);
		convert_to_boolean(&tmp);
		request_fulluri = Z_BVAL(tmp) ? 1 : 0;
		zval_dtor(&tmp);
	}

	if (request_fulluri) {
		/* Ask for everything */
		strcat(scratch, path);
	} else {
		/* Send the traditional /path/to/file?query_string */

		/* file */
		if (resource->path && *resource->path) {
			strlcat(scratch, resource->path, scratch_len);
		} else {
			strlcat(scratch, "/", scratch_len);
		}

		/* query string */
		if (resource->query)	{
			strlcat(scratch, "?", scratch_len);
			strlcat(scratch, resource->query, scratch_len);
		}
	}

	/* protocol version we are speaking */
	if (protocol_version) {
		strlcat(scratch, " HTTP/", scratch_len);
		strlcat(scratch, protocol_version, scratch_len);
		strlcat(scratch, "\r\n", scratch_len);
		efree(protocol_version);
		protocol_version = NULL;
	} else {
		strlcat(scratch, " HTTP/1.0\r\n", scratch_len);
	}


	/* send it */
	php_stream_write(stream, scratch, strlen(scratch));

	if (context &&
		php_stream_context_get_option(context, "http", "header", &tmpzval) == SUCCESS &&
		Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval)) {
		/* Remove newlines and spaces from start and end,
		   php_trim will estrndup() */
		tmp = php_trim(Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval), NULL, 0, NULL, 3 TSRMLS_CC);
		if (strlen(tmp) > 0) {
			if (!header_init) { /* Remove post headers for redirects */
				int l = strlen(tmp);
				char *s, *s2, *tmp_c = estrdup(tmp);
				
				php_strtolower(tmp_c, l);
				if ((s = strstr(tmp_c, "content-length:"))) {
					if ((s2 = memchr(s, '\n', tmp_c + l - s))) {
						int b = tmp_c + l - 1 - s2;
						memmove(tmp, tmp + (s2 + 1 - tmp_c), b);
						memmove(tmp_c, s2 + 1, b);
						
					} else {
						tmp[s - tmp_c] = *s = '\0';
					}
					l = strlen(tmp_c);
				}
				if ((s = strstr(tmp_c, "content-type:"))) {
					if ((s2 = memchr(s, '\n', tmp_c + l - s))) {
						memmove(tmp, tmp + (s2 + 1 - tmp_c), tmp_c + l - 1 - s2);
					} else {
						tmp[s - tmp_c] = '\0';
					}
				}
				efree(tmp_c);
				tmp_c = php_trim(tmp, strlen(tmp), NULL, 0, NULL, 3 TSRMLS_CC);
				efree(tmp);
				tmp = tmp_c;
			}

			user_headers = estrdup(tmp);

			/* Make lowercase for easy comparison against 'standard' headers */
			php_strtolower(tmp, strlen(tmp));
			if (strstr(tmp, "user-agent:")) {
				 have_header |= HTTP_HEADER_USER_AGENT;
			}
			if (strstr(tmp, "host:")) {
				 have_header |= HTTP_HEADER_HOST;
			}
			if (strstr(tmp, "from:")) {
				 have_header |= HTTP_HEADER_FROM;
				}
			if (strstr(tmp, "authorization:")) {
				 have_header |= HTTP_HEADER_AUTH;
			}
			if (strstr(tmp, "content-length:")) {
				 have_header |= HTTP_HEADER_CONTENT_LENGTH;
			}
			if (strstr(tmp, "content-type:")) {
				 have_header |= HTTP_HEADER_TYPE;
			}
		}
		efree(tmp);
	}

	/* auth header if it was specified */
	if (((have_header & HTTP_HEADER_AUTH) == 0) && resource->user && resource->pass)	{
		/* decode the strings first */
		php_url_decode(resource->user, strlen(resource->user));
		php_url_decode(resource->pass, strlen(resource->pass));

		/* scratch is large enough, since it was made large enough for the whole URL */
		strcpy(scratch, resource->user);
		strcat(scratch, ":");
		strcat(scratch, resource->pass);

		tmp = php_base64_encode((unsigned char*)scratch, strlen(scratch), NULL);
		
		if (snprintf(scratch, scratch_len, "Authorization: Basic %s\r\n", tmp) > 0) {
			php_stream_write(stream, scratch, strlen(scratch));
			php_stream_notify_info(context, PHP_STREAM_NOTIFY_AUTH_REQUIRED, NULL, 0);
		}

		efree(tmp);
		tmp = NULL;
	}

	/* if the user has configured who they are, send a From: line */
	if (((have_header & HTTP_HEADER_FROM) == 0) && cfg_get_string("from", &tmp) == SUCCESS)	{
		if (snprintf(scratch, scratch_len, "From: %s\r\n", tmp) > 0)
			php_stream_write(stream, scratch, strlen(scratch));
	}

	/* Send Host: header so name-based virtual hosts work */
	if ((have_header & HTTP_HEADER_HOST) == 0) {
		if ((use_ssl && resource->port != 443 && resource->port != 0) || 
			(!use_ssl && resource->port != 80 && resource->port != 0))	{
			if (snprintf(scratch, scratch_len, "Host: %s:%i\r\n", resource->host, resource->port) > 0)
				php_stream_write(stream, scratch, strlen(scratch));
		} else {
			if (snprintf(scratch, scratch_len, "Host: %s\r\n", resource->host) > 0) {
				php_stream_write(stream, scratch, strlen(scratch));
			}
		}
	}

	if (context && 
	    php_stream_context_get_option(context, "http", "user_agent", &ua_zval) == SUCCESS &&
		Z_TYPE_PP(ua_zval) == IS_STRING) {
		ua_str = Z_STRVAL_PP(ua_zval);
	} else if (FG(user_agent)) {
		ua_str = FG(user_agent);
	}

	if (((have_header & HTTP_HEADER_USER_AGENT) == 0) && ua_str) {
#define _UA_HEADER "User-Agent: %s\r\n"
		char *ua;
		size_t ua_len;
		
		ua_len = sizeof(_UA_HEADER) + strlen(ua_str);
		
		/* ensure the header is only sent if user_agent is not blank */
		if (ua_len > sizeof(_UA_HEADER)) {
			ua = emalloc(ua_len + 1);
			if ((ua_len = slprintf(ua, ua_len, _UA_HEADER, ua_str)) > 0) {
				ua[ua_len] = 0;
				php_stream_write(stream, ua, ua_len);
			} else {
				php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot construct User-agent header");
			}

			if (ua) {
				efree(ua);
			}
		}	
	}

	if (user_headers) {
		/* A bit weird, but some servers require that Content-Length be sent prior to Content-Type for POST
		 * see bug #44603 for details. Since Content-Type maybe part of user's headers we need to do this check first.
		 */
		if (
				header_init &&
				context &&
				!(have_header & HTTP_HEADER_CONTENT_LENGTH) &&
				php_stream_context_get_option(context, "http", "content", &tmpzval) == SUCCESS &&
				Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0
		) {
			scratch_len = slprintf(scratch, scratch_len, "Content-Length: %d\r\n", Z_STRLEN_PP(tmpzval));
			php_stream_write(stream, scratch, scratch_len);
			have_header |= HTTP_HEADER_CONTENT_LENGTH;
		}

		php_stream_write(stream, user_headers, strlen(user_headers));
		php_stream_write(stream, "\r\n", sizeof("\r\n")-1);
		efree(user_headers);
	}

	/* Request content, such as for POST requests */
	if (header_init && context &&
		php_stream_context_get_option(context, "http", "content", &tmpzval) == SUCCESS &&
		Z_TYPE_PP(tmpzval) == IS_STRING && Z_STRLEN_PP(tmpzval) > 0) {
		if (!(have_header & HTTP_HEADER_CONTENT_LENGTH)) {
			scratch_len = slprintf(scratch, scratch_len, "Content-Length: %d\r\n", Z_STRLEN_PP(tmpzval));
			php_stream_write(stream, scratch, scratch_len);
		}
		if (!(have_header & HTTP_HEADER_TYPE)) {
			php_stream_write(stream, "Content-Type: application/x-www-form-urlencoded\r\n",
				sizeof("Content-Type: application/x-www-form-urlencoded\r\n") - 1);
			php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Content-type not specified assuming application/x-www-form-urlencoded");
		}
		php_stream_write(stream, "\r\n", sizeof("\r\n")-1);
		php_stream_write(stream, Z_STRVAL_PP(tmpzval), Z_STRLEN_PP(tmpzval));
		php_stream_write(stream, "\r\n\r\n", sizeof("\r\n\r\n")-1);
	} else {
		php_stream_write(stream, "\r\n", sizeof("\r\n")-1);
	}

	location[0] = '\0';

	if (header_init) {
		zval *tmp;
		MAKE_STD_ZVAL(tmp);
		array_init(tmp);
		ZEND_SET_SYMBOL(EG(active_symbol_table), "http_response_header", tmp);
	}

	{
		zval **rh;
		zend_hash_find(EG(active_symbol_table), "http_response_header", sizeof("http_response_header"), (void **) &rh);
		response_header = *rh;
	}

	if (!php_stream_eof(stream)) {
		size_t tmp_line_len;
		/* get response header */

		if (php_stream_get_line(stream, tmp_line, sizeof(tmp_line) - 1, &tmp_line_len) != NULL) {
			zval *http_response;
			int response_code;

			if (tmp_line_len > 9) {
				response_code = atoi(tmp_line + 9);
			} else {
				response_code = 0;
			}
			/* when we request only the header, don't fail even on error codes */
			if (options & STREAM_ONLY_GET_HEADERS) {
				reqok = 1;
			}
			switch(response_code) {
				case 200:
				case 206: /* partial content */
				case 302:
				case 303:
				case 301:
					reqok = 1;
					break;
				case 403:
					php_stream_notify_error(context, PHP_STREAM_NOTIFY_AUTH_RESULT,
							tmp_line, response_code);
					break;
				default:
					/* safety net in the event tmp_line == NULL */
					if (!tmp_line_len) {
						tmp_line[0] = '\0';
					}
					php_stream_notify_error(context, PHP_STREAM_NOTIFY_FAILURE,
							tmp_line, response_code);
			}
			if (tmp_line[tmp_line_len - 1] == '\n') {
				--tmp_line_len;
				if (tmp_line[tmp_line_len - 1] == '\r') {
					--tmp_line_len;
				}
			}
			MAKE_STD_ZVAL(http_response);
			ZVAL_STRINGL(http_response, tmp_line, tmp_line_len, 1);
			zend_hash_next_index_insert(Z_ARRVAL_P(response_header), &http_response, sizeof(zval *), NULL);
		}
	} else {
		php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "HTTP request failed, unexpected end of socket!");
		goto out;
	}
	
	/* read past HTTP headers */
	
	http_header_line = emalloc(HTTP_HEADER_BLOCK_SIZE);

	while (!body && !php_stream_eof(stream)) {
		size_t http_header_line_length;
		if (php_stream_get_line(stream, http_header_line, HTTP_HEADER_BLOCK_SIZE, &http_header_line_length) && *http_header_line != '\n' && *http_header_line != '\r') {
			char *e = http_header_line + http_header_line_length - 1;
			while (*e == '\n' || *e == '\r') {
				e--;
			}
			http_header_line_length = e - http_header_line + 1;
			http_header_line[http_header_line_length] = '\0';

			if (!strncasecmp(http_header_line, "Location: ", 10)) {
				strlcpy(location, http_header_line + 10, sizeof(location));
			} else if (!strncasecmp(http_header_line, "Content-Type: ", 14)) {
				php_stream_notify_info(context, PHP_STREAM_NOTIFY_MIME_TYPE_IS, http_header_line + 14, 0);
			} else if (!strncasecmp(http_header_line, "Content-Length: ", 16)) {
				file_size = atoi(http_header_line + 16);
				php_stream_notify_file_size(context, file_size, http_header_line, 0);
			}

			if (http_header_line[0] == '\0') {
				body = 1;
			} else {
				zval *http_header;

				MAKE_STD_ZVAL(http_header);

				ZVAL_STRINGL(http_header, http_header_line, http_header_line_length, 1);
				
				zend_hash_next_index_insert(Z_ARRVAL_P(response_header), &http_header, sizeof(zval *), NULL);
			}
		} else {
			break;
		}
	}
	
	if (!reqok || location[0] != '\0') {
		if (options & STREAM_ONLY_GET_HEADERS && redirect_max <= 1) {
			goto out;
		}

		if (location[0] != '\0')
			php_stream_notify_info(context, PHP_STREAM_NOTIFY_REDIRECTED, location, 0);

		php_stream_close(stream);
		stream = NULL;

		if (location[0] != '\0')	{

			char new_path[HTTP_HEADER_BLOCK_SIZE];
			char loc_path[HTTP_HEADER_BLOCK_SIZE];

			*new_path='\0';
			if (strlen(location)<8 || (strncasecmp(location, "http://", sizeof("http://")-1) && 
							strncasecmp(location, "https://", sizeof("https://")-1) && 
							strncasecmp(location, "ftp://", sizeof("ftp://")-1) && 
							strncasecmp(location, "ftps://", sizeof("ftps://")-1))) 
			{
				if (*location != '/') {
					if (*(location+1) != '\0' && resource->path) {		
						char *s = strrchr(resource->path, '/');
						if (!s) {
							s = resource->path;
							if (!s[0]) {
								efree(s);
								s = resource->path = estrdup("/");
							} else {
								*s = '/';
							}
						}
						s[1] = '\0'; 
						if (resource->path && *(resource->path) == '/' && *(resource->path + 1) == '\0') {
							snprintf(loc_path, sizeof(loc_path) - 1, "%s%s", resource->path, location);
						} else {
							snprintf(loc_path, sizeof(loc_path) - 1, "%s/%s", resource->path, location);
						}
					} else {
						snprintf(loc_path, sizeof(loc_path) - 1, "/%s", location);
					}
				} else {
					strlcpy(loc_path, location, sizeof(loc_path));
				}
				if ((use_ssl && resource->port != 443) || (!use_ssl && resource->port != 80)) {
					snprintf(new_path, sizeof(new_path) - 1, "%s://%s:%d%s", resource->scheme, resource->host, resource->port, loc_path);
				} else {
					snprintf(new_path, sizeof(new_path) - 1, "%s://%s%s", resource->scheme, resource->host, loc_path);
				}
			} else {
				strlcpy(new_path, location, sizeof(new_path));
			}

			php_url_free(resource);
			/* check for invalid redirection URLs */
			if ((resource = php_url_parse(new_path)) == NULL) {
				php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Invalid redirect URL! %s", new_path);
				goto out;
			}

#define CHECK_FOR_CNTRL_CHARS(val) {	\
	if (val) {	\
		unsigned char *s, *e;	\
		int l;	\
		l = php_url_decode(val, strlen(val));	\
		s = val; e = s + l;	\
		while (s < e) {	\
			if (iscntrl(*s)) {	\
				php_stream_wrapper_log_error(wrapper, options TSRMLS_CC, "Invalid redirect URL! %s", new_path);	\
				goto out;	\
			}	\
			s++;	\
		}	\
	}	\
}	\
			/* check for control characters in login, password & path */
			if (strncasecmp(new_path, "http://", sizeof("http://") - 1) || strncasecmp(new_path, "https://", sizeof("https://") - 1)) {
				CHECK_FOR_CNTRL_CHARS(resource->user)
				CHECK_FOR_CNTRL_CHARS(resource->pass)
				CHECK_FOR_CNTRL_CHARS(resource->path)
			}
			stream = php_stream_url_wrap_http_ex(wrapper, new_path, mode, options, opened_path, context, --redirect_max, 0 STREAMS_CC TSRMLS_CC);
		} else {
/*
 * Set the wireless options requested on command line
 * This function is too long and probably should be split,
 * because it look like the perfect definition of spaghetti code,
 * but I'm way to lazy
 */
static int
set_info(int		skfd,		/* The socket */
	 char *		args[],		/* Command line args */
	 int		count,		/* Args count */
	 char *		ifname)		/* Dev name */
{
  struct iwreq		wrq;
  int			i;

  /* if nothing after the device name - will never happen */
  if(count < 1)
    {
      fprintf(stderr, "Error : too few arguments.\n");
      return(-1);
    }

  /* The other args on the line specify options to be set... */
  for(i = 0; i < count; i++)
    {
      /* ---------- Commit changes to driver ---------- */
      if(!strncmp(args[i], "commit", 6))
	{
	  /* No args */
	  IW_SET_EXT_ERR(skfd, ifname, SIOCSIWCOMMIT, &wrq,
			 "Commit changes");
	  continue;
	}

      /* ---------- Set network ID ---------- */
      if((!strcasecmp(args[i], "nwid")) ||
	 (!strcasecmp(args[i], "domain")))
	{
	  i++;
	  if(i >= count)
	    ABORT_ARG_NUM("Set NWID", SIOCSIWNWID);
	  if((!strcasecmp(args[i], "off")) ||
	     (!strcasecmp(args[i], "any")))
	    wrq.u.nwid.disabled = 1;
	  else
	    if(!strcasecmp(args[i], "on"))
	      {
		/* Get old nwid */
		IW_GET_EXT_ERR(skfd, ifname, SIOCGIWNWID, &wrq,
			       "Set NWID");
		wrq.u.nwid.disabled = 0;
	      }
	    else
	      if(sscanf(args[i], "%lX", (unsigned long *) &(wrq.u.nwid.value))
		 != 1)
		ABORT_ARG_TYPE("Set NWID", SIOCSIWNWID, args[i]);
	      else
		wrq.u.nwid.disabled = 0;
	  wrq.u.nwid.fixed = 1;

	  /* Set new nwid */
	  IW_SET_EXT_ERR(skfd, ifname, SIOCSIWNWID, &wrq,
			 "Set NWID");
	  continue;
	}

      /* ---------- Set frequency / channel ---------- */
      if((!strncmp(args[i], "freq", 4)) ||
	 (!strcmp(args[i], "channel")))
	{
	  double		freq;

	  if(++i >= count)
	    ABORT_ARG_NUM("Set Frequency", SIOCSIWFREQ);
	  if(!strcasecmp(args[i], "auto"))
	    {
	      wrq.u.freq.m = -1;
	      wrq.u.freq.e = 0;
	      wrq.u.freq.flags = 0;
	    }
	  else
	    {
	      if(!strcasecmp(args[i], "fixed"))
		{
		  /* Get old bitrate */
		  IW_GET_EXT_ERR(skfd, ifname, SIOCGIWFREQ, &wrq,
				 "Set Bit Rate");
		  wrq.u.freq.flags = IW_FREQ_FIXED;
		}
	      else			/* Should be a numeric value */
		{
		  if(sscanf(args[i], "%lg", &(freq)) != 1)
		    ABORT_ARG_TYPE("Set Frequency", SIOCSIWFREQ, args[i]);
		  if(index(args[i], 'G')) freq *= GIGA;
		  if(index(args[i], 'M')) freq *= MEGA;
		  if(index(args[i], 'k')) freq *= KILO;

		  iw_float2freq(freq, &(wrq.u.freq));

		  wrq.u.freq.flags = IW_FREQ_FIXED;

		  /* Check for an additional argument */
		  if(((i+1) < count) &&
		     (!strcasecmp(args[i+1], "auto")))
		    {
		      wrq.u.freq.flags = 0;
		      ++i;
		    }
		  if(((i+1) < count) &&
		     (!strcasecmp(args[i+1], "fixed")))
		    {
		      wrq.u.freq.flags = IW_FREQ_FIXED;
		      ++i;
		    }
		}
	    }

	  IW_SET_EXT_ERR(skfd, ifname, SIOCSIWFREQ, &wrq,
			 "Set Frequency");
	  continue;
	}

      /* ---------- Set sensitivity ---------- */
      if(!strncmp(args[i], "sens", 4))
	{
	  if(++i >= count)
	    ABORT_ARG_NUM("Set Sensitivity", SIOCSIWSENS);
	  if(sscanf(args[i], "%i", &(wrq.u.sens.value)) != 1)
	    ABORT_ARG_TYPE("Set Sensitivity", SIOCSIWSENS, args[i]);

	  IW_SET_EXT_ERR(skfd, ifname, SIOCSIWSENS, &wrq,
			 "Set Sensitivity");
	  continue;
	}

      /* ---------- Set encryption stuff ---------- */
      if((!strncmp(args[i], "enc", 3)) ||
	 (!strcmp(args[i], "key")))
	{
	  unsigned char	key[IW_ENCODING_TOKEN_MAX];

	  if(++i >= count)
	    ABORT_ARG_NUM("Set Encode", SIOCSIWENCODE);

	  if(!strcasecmp(args[i], "on"))
	    {
	      /* Get old encryption information */
	      wrq.u.data.pointer = (caddr_t) key;
	      wrq.u.data.length = IW_ENCODING_TOKEN_MAX;
	      wrq.u.data.flags = 0;
	      IW_GET_EXT_ERR(skfd, ifname, SIOCGIWENCODE, &wrq,
			     "Set Encode");
	      wrq.u.data.flags &= ~IW_ENCODE_DISABLED;	/* Enable */
	    }
	  else
	    {
	      int	gotone = 0;
	      int	oldone;
	      int	keylen;
	      int	temp;

	      wrq.u.data.pointer = (caddr_t) NULL;
	      wrq.u.data.flags = 0;
	      wrq.u.data.length = 0;

	      /* Allow arguments in any order (it's safe) */
	      do
		{
		  oldone = gotone;

		  /* -- Check for the key -- */
		  if(i < count)
		    {
		      keylen = iw_in_key_full(skfd, ifname,
					      args[i], key, &wrq.u.data.flags);
		      if(keylen > 0)
			{
			  wrq.u.data.length = keylen;
			  wrq.u.data.pointer = (caddr_t) key;
			  ++i;
			  gotone++;
			}
		    }

		  /* -- Check for token index -- */
		  if((i < count) &&
		     (sscanf(args[i], "[%i]", &temp) == 1) &&
		     (temp > 0) && (temp < IW_ENCODE_INDEX))
		    {
		      wrq.u.encoding.flags |= temp;
		      ++i;
		      gotone++;
		    }

		  /* -- Check the various flags -- */
		  if((i < count) && (!strcasecmp(args[i], "off")))
		    {
		      wrq.u.data.flags |= IW_ENCODE_DISABLED;
		      ++i;
		      gotone++;
		    }
		  if((i < count) && (!strcasecmp(args[i], "open")))
		    {
		      wrq.u.data.flags |= IW_ENCODE_OPEN;
		      ++i;
		      gotone++;
		    }
		  if((i < count) && (!strncasecmp(args[i], "restricted", 5)))
		    {
		      wrq.u.data.flags |= IW_ENCODE_RESTRICTED;
		      ++i;
		      gotone++;
		    }
		  if((i < count) && (!strncasecmp(args[i], "temporary", 4)))
		    {
		      wrq.u.data.flags |= IW_ENCODE_TEMP;
		      ++i;
		      gotone++;
		    }
		}
	      while(gotone != oldone);

	      /* Pointer is absent in new API */
	      if(wrq.u.data.pointer == NULL)
		wrq.u.data.flags |= IW_ENCODE_NOKEY;

	      /* Check if we have any invalid argument */
	      if(!gotone)
		ABORT_ARG_TYPE("Set Encode", SIOCSIWENCODE, args[i]);
	      /* Get back to last processed argument */
	      --i;
	    }

	  IW_SET_EXT_ERR(skfd, ifname, SIOCSIWENCODE, &wrq,
			 "Set Encode");
	  continue;
  	}

      /* ---------- Set ESSID ---------- */
      if(!strcasecmp(args[i], "essid"))
	{
	  char		essid[IW_ESSID_MAX_SIZE + 1];

	  i++;
	  if(i >= count)
	    ABORT_ARG_NUM("Set ESSID", SIOCSIWESSID);
	  if((!strcasecmp(args[i], "off")) ||
	     (!strcasecmp(args[i], "any")))
	    {
	      wrq.u.essid.flags = 0;
	      essid[0] = '\0';
	    }
	  else
	    if(!strcasecmp(args[i], "on"))
	      {
		/* Get old essid */
		wrq.u.essid.pointer = (caddr_t) essid;
		wrq.u.essid.length = IW_ESSID_MAX_SIZE + 1;
		wrq.u.essid.flags = 0;
		IW_GET_EXT_ERR(skfd, ifname, SIOCGIWESSID, &wrq,
			       "Set ESSID");
		wrq.u.essid.flags = 1;
	      }
	    else
	      {
		/* '-' allow to escape the ESSID string, allowing
		 * to set it to the string "any" or "off".
		 * This is a big ugly, but it will do for now */
		if(!strcmp(args[i], "-"))
		  {
		    i++;
		    if(i >= count)
		      ABORT_ARG_NUM("Set ESSID", SIOCSIWESSID);
		  }

		/* Check the size of what the user passed us to avoid
		 * buffer overflows */
		if(strlen(args[i]) > IW_ESSID_MAX_SIZE)
		  ABORT_ARG_SIZE("Set ESSID", SIOCSIWESSID, IW_ESSID_MAX_SIZE);
		else
		  {
		    int		temp;

		    wrq.u.essid.flags = 1;
		    strcpy(essid, args[i]);	/* Size checked, all clear */

		    /* Check for ESSID index */
		    if(((i+1) < count) &&
		       (sscanf(args[i+1], "[%i]", &temp) == 1) &&
		       (temp > 0) && (temp < IW_ENCODE_INDEX))
		      {
			wrq.u.essid.flags = temp;
			++i;
		      }
		  }
	      }

	  wrq.u.essid.pointer = (caddr_t) essid;
	  wrq.u.essid.length = strlen(essid) + 1;
	  IW_SET_EXT_ERR(skfd, ifname, SIOCSIWESSID, &wrq,
			 "Set ESSID");
	  continue;
	}

      /* ---------- Set AP address ---------- */
      if(!strcasecmp(args[i], "ap"))
	{
	  if(++i >= count)
	    ABORT_ARG_NUM("Set AP Address", SIOCSIWAP);

	  if((!strcasecmp(args[i], "auto")) ||
	     (!strcasecmp(args[i], "any")))
	    {
	      /* Send a broadcast address */
	      iw_broad_ether(&(wrq.u.ap_addr));
	    }
	  else
	    {
	      if(!strcasecmp(args[i], "off"))
		{
		  /* Send a NULL address */
		  iw_null_ether(&(wrq.u.ap_addr));
		}
	      else
		{
		  /* Get the address and check if the interface supports it */
		  if(iw_in_addr(skfd, ifname, args[i++], &(wrq.u.ap_addr)) < 0)
		    ABORT_ARG_TYPE("Set AP Address", SIOCSIWAP, args[i-1]);
		}
	    }

	  IW_SET_EXT_ERR(skfd, ifname, SIOCSIWAP, &wrq,
			 "Set AP Address");
	  continue;
	}

      /* ---------- Set NickName ---------- */
      if(!strncmp(args[i], "nick", 4))
	{
	  i++;
	  if(i >= count)
	    ABORT_ARG_NUM("Set Nickname", SIOCSIWNICKN);
	  if(strlen(args[i]) > IW_ESSID_MAX_SIZE)
	    ABORT_ARG_SIZE("Set Nickname", SIOCSIWNICKN, IW_ESSID_MAX_SIZE);

	  wrq.u.essid.pointer = (caddr_t) args[i];
	  wrq.u.essid.length = strlen(args[i]) + 1;
	  IW_SET_EXT_ERR(skfd, ifname, SIOCSIWNICKN, &wrq,
			 "Set Nickname");
	  continue;
	}

      /* ---------- Set Bit-Rate ---------- */
      if((!strncmp(args[i], "bit", 3)) ||
	 (!strcmp(args[i], "rate")))
	{
	  if(++i >= count)
	    ABORT_ARG_NUM("Set Bit Rate", SIOCSIWRATE);
	  if(!strcasecmp(args[i], "auto"))
	    {
	      wrq.u.bitrate.value = -1;
	      wrq.u.bitrate.fixed = 0;
	    }
	  else
	    {
	      if(!strcasecmp(args[i], "fixed"))
		{
		  /* Get old bitrate */
		  IW_GET_EXT_ERR(skfd, ifname, SIOCGIWRATE, &wrq,
				 "Set Bit Rate");
		  wrq.u.bitrate.fixed = 1;
		}
	      else			/* Should be a numeric value */
		{
		  double		brate;

		  if(sscanf(args[i], "%lg", &(brate)) != 1)
		    ABORT_ARG_TYPE("Set Bit Rate", SIOCSIWRATE, args[i]);
		  if(index(args[i], 'G')) brate *= GIGA;
		  if(index(args[i], 'M')) brate *= MEGA;
		  if(index(args[i], 'k')) brate *= KILO;
		  wrq.u.bitrate.value = (long) brate;
		  wrq.u.bitrate.fixed = 1;

		  /* Check for an additional argument */
		  if(((i+1) < count) &&
		     (!strcasecmp(args[i+1], "auto")))
		    {
		      wrq.u.bitrate.fixed = 0;
		      ++i;
		    }
		  if(((i+1) < count) &&
		     (!strcasecmp(args[i+1], "fixed")))
		    {
		      wrq.u.bitrate.fixed = 1;
		      ++i;
		    }
		}
	    }

	  IW_SET_EXT_ERR(skfd, ifname, SIOCSIWRATE, &wrq,
			 "Set Bit Rate");
	  continue;
	}

      /* ---------- Set RTS threshold ---------- */
      if(!strncasecmp(args[i], "rts", 3))
	{
	  i++;
	  if(i >= count)
	    ABORT_ARG_NUM("Set RTS Threshold", SIOCSIWRTS);
	  wrq.u.rts.value = -1;
	  wrq.u.rts.fixed = 1;
	  wrq.u.rts.disabled = 0;
	  if(!strcasecmp(args[i], "off"))
	    wrq.u.rts.disabled = 1;	/* i.e. max size */
	  else
	    if(!strcasecmp(args[i], "auto"))
	      wrq.u.rts.fixed = 0;
	    else
	      {
		if(!strcasecmp(args[i], "fixed"))
		  {
		    /* Get old RTS threshold */
		    IW_GET_EXT_ERR(skfd, ifname, SIOCGIWRTS, &wrq,
				   "Set RTS Threshold");
		    wrq.u.rts.fixed = 1;
		  }
		else			/* Should be a numeric value */
		  if(sscanf(args[i], "%li", (unsigned long *) &(wrq.u.rts.value))
		     != 1)
		    ABORT_ARG_TYPE("Set RTS Threshold", SIOCSIWRTS, args[i]);
	    }

	  IW_SET_EXT_ERR(skfd, ifname, SIOCSIWRTS, &wrq,
			 "Set RTS Threshold");
	  continue;
	}

      /* ---------- Set fragmentation threshold ---------- */
      if(!strncmp(args[i], "frag", 4))
	{
	  i++;
	  if(i >= count)
	    ABORT_ARG_NUM("Set Fragmentation Threshold", SIOCSIWFRAG);
	  wrq.u.frag.value = -1;
	  wrq.u.frag.fixed = 1;
	  wrq.u.frag.disabled = 0;
	  if(!strcasecmp(args[i], "off"))
	    wrq.u.frag.disabled = 1;	/* i.e. max size */
	  else
	    if(!strcasecmp(args[i], "auto"))
	      wrq.u.frag.fixed = 0;
	    else
	      {
		if(!strcasecmp(args[i], "fixed"))
		  {
		    /* Get old fragmentation threshold */
		    IW_GET_EXT_ERR(skfd, ifname, SIOCGIWFRAG, &wrq,
				   "Set Fragmentation Threshold");
		    wrq.u.frag.fixed = 1;
		  }
		else			/* Should be a numeric value */
		  if(sscanf(args[i], "%li",
			    (unsigned long *) &(wrq.u.frag.value))
		     != 1)
		    ABORT_ARG_TYPE("Set Fragmentation Threshold", SIOCSIWFRAG,
				   args[i]);
	    }

	  IW_SET_EXT_ERR(skfd, ifname, SIOCSIWFRAG, &wrq,
			 "Set Fragmentation Threshold");
	  continue;
	}

      /* ---------- Set operation mode ---------- */
      if(!strcmp(args[i], "mode"))
	{
	  int	k;

	  i++;
	  if(i >= count)
	    ABORT_ARG_NUM("Set Mode", SIOCSIWMODE);

	  if(sscanf(args[i], "%i", &k) != 1)
	    {
	      k = 0;
	      while((k < IW_NUM_OPER_MODE) &&
		    strncasecmp(args[i], iw_operation_mode[k], 3))
		k++;
	    }
	  if((k >= IW_NUM_OPER_MODE) || (k < 0))
	    ABORT_ARG_TYPE("Set Mode", SIOCSIWMODE, args[i]);

	  wrq.u.mode = k;
	  IW_SET_EXT_ERR(skfd, ifname, SIOCSIWMODE, &wrq,
			 "Set Mode");
	  continue;
	}

      /* ---------- Set Power Management ---------- */
      if(!strncmp(args[i], "power", 3))
	{
	  if(++i >= count)
	    ABORT_ARG_NUM("Set Power Management", SIOCSIWPOWER);

	  if(!strcasecmp(args[i], "off"))
	    wrq.u.power.disabled = 1;	/* i.e. max size */
	  else
	    if(!strcasecmp(args[i], "on"))
	      {
		/* Get old Power info */
		IW_GET_EXT_ERR(skfd, ifname, SIOCGIWPOWER, &wrq,
			       "Set Power Management");
		wrq.u.power.disabled = 0;
	      }
	    else
	      {
		double		temp;
		int		gotone = 0;
		/* Default - nope */
		wrq.u.power.flags = IW_POWER_ON;
		wrq.u.power.disabled = 0;

		/* Check value modifier */
		if(!strcasecmp(args[i], "min"))
		  {
		    wrq.u.power.flags |= IW_POWER_MIN;
		    if(++i >= count)
		      ABORT_ARG_NUM("Set Power Management", SIOCSIWPOWER);
		  }
		else
		  if(!strcasecmp(args[i], "max"))
		    {
		      wrq.u.power.flags |= IW_POWER_MAX;
		      if(++i >= count)
			ABORT_ARG_NUM("Set Power Management", SIOCSIWPOWER);
		    }

		/* Check value type */
		if(!strcasecmp(args[i], "period"))
		  {
		    wrq.u.power.flags |= IW_POWER_PERIOD;
		    if(++i >= count)
		      ABORT_ARG_NUM("Set Power Management", SIOCSIWPOWER);
		  }
		else
		  if(!strcasecmp(args[i], "timeout"))
		    {
		      wrq.u.power.flags |= IW_POWER_TIMEOUT;
		      if(++i >= count)
			ABORT_ARG_NUM("Set Power Management", SIOCSIWPOWER);
		    }

		/* Is there any value to grab ? */
		if(sscanf(args[i], "%lg", &(temp)) == 1)
		  {
		    temp *= MEGA;	/* default = s */
		    if(index(args[i], 'u')) temp /= MEGA;
		    if(index(args[i], 'm')) temp /= KILO;
		    wrq.u.power.value = (long) temp;
		    if((wrq.u.power.flags & IW_POWER_TYPE) == 0)
		      wrq.u.power.flags |= IW_POWER_PERIOD;
		    ++i;
		    gotone = 1;
		  }

		/* Now, check the mode */
		if(i < count)
		  {
		    if(!strcasecmp(args[i], "all"))
		      wrq.u.power.flags |= IW_POWER_ALL_R;
		    if(!strncasecmp(args[i], "unicast", 4))
		      wrq.u.power.flags |= IW_POWER_UNICAST_R;
		    if(!strncasecmp(args[i], "multicast", 5))
		      wrq.u.power.flags |= IW_POWER_MULTICAST_R;
		    if(!strncasecmp(args[i], "force", 5))
		      wrq.u.power.flags |= IW_POWER_FORCE_S;
		    if(!strcasecmp(args[i], "repeat"))
		      wrq.u.power.flags |= IW_POWER_REPEATER;
		    if(wrq.u.power.flags & IW_POWER_MODE)
		      {
			++i;
			gotone = 1;
		      }
		  }
		if(!gotone)
		  ABORT_ARG_TYPE("Set Power Management", SIOCSIWPOWER,
				 args[i]);
		--i;
	      }

	  IW_SET_EXT_ERR(skfd, ifname, SIOCSIWPOWER, &wrq,
		       "Set Power Management");
	  continue;
  	}

      /* ---------- Set Transmit-Power ---------- */
      if(!strncmp(args[i], "txpower", 3))
	{
	  struct iw_range	range;

	  if(++i >= count)
	    ABORT_ARG_NUM("Set Tx Power", SIOCSIWTXPOW);

	  /* Extract range info */
	  if(iw_get_range_info(skfd, ifname, &range) < 0)
	    memset(&range, 0, sizeof(range));

	  /* Prepare the request */
	  wrq.u.txpower.value = -1;
	  wrq.u.txpower.fixed = 1;
	  wrq.u.txpower.disabled = 0;
	  wrq.u.txpower.flags = IW_TXPOW_DBM;
	  if(!strcasecmp(args[i], "off"))
	    wrq.u.txpower.disabled = 1;	/* i.e. turn radio off */
	  else
	    if(!strcasecmp(args[i], "auto"))
	      wrq.u.txpower.fixed = 0;	/* i.e. use power control */
	    else
	      {
		if(!strcasecmp(args[i], "on"))
		  {
		    /* Get old tx-power */
		    IW_GET_EXT_ERR(skfd, ifname, SIOCGIWTXPOW, &wrq,
				   "Set Tx Power");
		    wrq.u.txpower.disabled = 0;
		  }
		else
		  {
		    if(!strcasecmp(args[i], "fixed"))
		      {
			/* Get old tx-power */
			IW_GET_EXT_ERR(skfd, ifname, SIOCGIWTXPOW, &wrq,
				       "Set Tx Power");
			wrq.u.txpower.fixed = 1;
			wrq.u.txpower.disabled = 0;
		      }
		    else			/* Should be a numeric value */
		      {
			int		power;
			int		ismwatt = 0;

			/* Get the value */
			if(sscanf(args[i], "%i", &(power)) != 1)
			  ABORT_ARG_TYPE("Set Tx Power", SIOCSIWTXPOW,
					 args[i]);

			/* Check if milliwatt */
			ismwatt = (index(args[i], 'm') != NULL);

			/* Convert */
			if(range.txpower_capa & IW_TXPOW_RELATIVE)
			  {
			    /* Can't convert */
			    if(ismwatt)
			      ABORT_ARG_TYPE("Set Tx Power",
					     SIOCSIWTXPOW,
					     args[i]);
			  }
			else
			  if(range.txpower_capa & IW_TXPOW_MWATT)
			    {
			      if(!ismwatt)
				power = iw_dbm2mwatt(power);
			      wrq.u.txpower.flags = IW_TXPOW_MWATT;
			    }
			  else
			    {
			      if(ismwatt)
				power = iw_mwatt2dbm(power);
			      wrq.u.txpower.flags = IW_TXPOW_DBM;
			    }
			wrq.u.txpower.value = power;

			/* Check for an additional argument */
			if(((i+1) < count) &&
			   (!strcasecmp(args[i+1], "auto")))
			  {
			    wrq.u.txpower.fixed = 0;
			    ++i;
			  }
			if(((i+1) < count) &&
			   (!strcasecmp(args[i+1], "fixed")))
			  {
			    wrq.u.txpower.fixed = 1;
			    ++i;
			  }
		      }
		  }
	      }

	  IW_SET_EXT_ERR(skfd, ifname, SIOCSIWTXPOW, &wrq,
			 "Set Tx Power");
	  continue;
	}

      /* ---------- Set Retry limit ---------- */
      if(!strncmp(args[i], "retry", 3))
	{
	  double		temp;
	  int		gotone = 0;

	  if(++i >= count)
	    ABORT_ARG_NUM("Set Retry Limit", SIOCSIWRETRY);

	  /* Default - nope */
	  wrq.u.retry.flags = IW_RETRY_LIMIT;
	  wrq.u.retry.disabled = 0;

	  /* Check value modifier */
	  if(!strcasecmp(args[i], "min"))
	    {
	      wrq.u.retry.flags |= IW_RETRY_MIN;
	      if(++i >= count)
		ABORT_ARG_NUM("Set Retry Limit", SIOCSIWRETRY);
	    }
	  else
	    if(!strcasecmp(args[i], "max"))
	      {
		wrq.u.retry.flags |= IW_RETRY_MAX;
		if(++i >= count)
		  ABORT_ARG_NUM("Set Retry Limit", SIOCSIWRETRY);
	      }

	  /* Check value type */
	  if(!strcasecmp(args[i], "limit"))
	    {
	      wrq.u.retry.flags |= IW_RETRY_LIMIT;
	      if(++i >= count)
		ABORT_ARG_NUM("Set Retry Limit", SIOCSIWRETRY);
	    }
	  else
	    if(!strncasecmp(args[i], "lifetime", 4))
	      {
		wrq.u.retry.flags &= ~IW_RETRY_LIMIT;
		wrq.u.retry.flags |= IW_RETRY_LIFETIME;
		if(++i >= count)
		  ABORT_ARG_NUM("Set Retry Limit", SIOCSIWRETRY);
	      }

	  /* Is there any value to grab ? */
	  if(sscanf(args[i], "%lg", &(temp)) == 1)
	    {
	      /* Limit is absolute, on the other hand lifetime is seconds */
	      if(!(wrq.u.retry.flags & IW_RETRY_LIMIT))
		{
		  /* Normalise lifetime */
		  temp *= MEGA;	/* default = s */
		  if(index(args[i], 'u')) temp /= MEGA;
		  if(index(args[i], 'm')) temp /= KILO;
		}
	      wrq.u.retry.value = (long) temp;
	      ++i;
	      gotone = 1;
	    }

	  if(!gotone)
	    ABORT_ARG_TYPE("Set Retry Limit", SIOCSIWRETRY, args[i]);
	  --i;

	  IW_SET_EXT_ERR(skfd, ifname, SIOCSIWRETRY, &wrq,
			 "Set Retry Limit");
	  continue;
	}

      /* ---------- Other ---------- */
      /* Here we have an unrecognised arg... */
      fprintf(stderr, "Error : unrecognised wireless request \"%s\"\n",
	      args[i]);
      return(-1);
    }		/* for(index ... */
  return(0);
}
Example #8
0
int
VSL_Glob2Tags(const char *glob, int l, VSL_tagfind_f *func, void *priv)
{
	int i, r, l2;
	int pre = 0;
	int post = 0;
	char buf[64];

	AN(glob);
	if (l < 0)
		l = strlen(glob);
	if (l == 0 || l > sizeof buf - 1)
		return (-1);
	if (strchr(glob, '*') != NULL) {
		if (glob[0] == '*') {
			/* Prefix wildcard */
			pre = 1;
			glob++;
			l--;
		}
		if (l > 0 && glob[l - 1] == '*') {
			/* Postfix wildcard */
			post = 1;
			l--;
		}
	}
	if (pre && post)
		/* Support only post or prefix wildcards */
		return (-3);
	memcpy(buf, glob, l);
	buf[l] = '\0';
	if (strchr(buf, '*') != NULL)
		/* No multiple wildcards */
		return (-3);
	if (pre == 0 && post == 0) {
		/* No wildcards, use VSL_Name2Tag */
		i = VSL_Name2Tag(buf, l);
		if (i < 0)
			return (i);
		if (func != NULL)
			(func)(i, priv);
		return (1);
	}

	r = 0;
	for (i = 0; i < SLT__MAX; i++) {
		if (VSL_tags[i] == NULL)
			continue;
		l2 = strlen(VSL_tags[i]);
		if (l2 < l)
			continue;
		if (pre) {
			/* Prefix wildcard match */
			if (strcasecmp(buf, VSL_tags[i] + l2 - l))
				continue;
		} else {
			/* Postfix wildcard match */
			if (strncasecmp(buf, VSL_tags[i], l))
				continue;
		}
		if (func != NULL)
			(func)(i, priv);
		r++;
	}
	if (r == 0)
		return (-1);
	return (r);
}
int test_implicit_compare_with_functions() {

  if (memcmp(A, "a", 1))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function 'memcmp' is called without explicitly comparing result
  // CHECK-FIXES: memcmp(A, "a", 1) != 0)

  if (wmemcmp(W, L"a", 1))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function 'wmemcmp' is called without explicitly comparing result
  // CHECK-FIXES: wmemcmp(W, L"a", 1) != 0)

  if (memicmp(A, "a", 1))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function 'memicmp' is called without explicitly comparing result
  // CHECK-FIXES: memicmp(A, "a", 1) != 0)

  if (_memicmp(A, "a", 1))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_memicmp' is called without explicitly comparing result
  // CHECK-FIXES: _memicmp(A, "a", 1) != 0)

  if (_memicmp_l(A, "a", 1, locale))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_memicmp_l' is called without explicitly comparing result
  // CHECK-FIXES: _memicmp_l(A, "a", 1, locale) != 0)

  if (strcmp(A, "a"))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function 'strcmp' is called without explicitly comparing result
  // CHECK-FIXES: strcmp(A, "a") != 0)

  if (strncmp(A, "a", 1))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function 'strncmp' is called without explicitly comparing result
  // CHECK-FIXES: strncmp(A, "a", 1) != 0)

  if (strcasecmp(A, "a"))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function 'strcasecmp' is called without explicitly comparing result
  // CHECK-FIXES: strcasecmp(A, "a") != 0)

  if (strncasecmp(A, "a", 1))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function 'strncasecmp' is called without explicitly comparing result
  // CHECK-FIXES: strncasecmp(A, "a", 1) != 0)

  if (stricmp(A, "a"))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function 'stricmp' is called without explicitly comparing result
  // CHECK-FIXES: stricmp(A, "a") != 0)

  if (strcmpi(A, "a"))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function 'strcmpi' is called without explicitly comparing result
  // CHECK-FIXES: strcmpi(A, "a") != 0)

  if (_stricmp(A, "a"))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_stricmp' is called without explicitly comparing result
  // CHECK-FIXES: _stricmp(A, "a") != 0)

  if (strnicmp(A, "a", 1))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function 'strnicmp' is called without explicitly comparing result
  // CHECK-FIXES: strnicmp(A, "a", 1) != 0)

  if (_strnicmp(A, "a", 1))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_strnicmp' is called without explicitly comparing result
  // CHECK-FIXES: _strnicmp(A, "a", 1) != 0)

  if (_stricmp_l(A, "a", locale))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_stricmp_l' is called without explicitly comparing result
  // CHECK-FIXES: _stricmp_l(A, "a", locale) != 0)

  if (_strnicmp_l(A, "a", 1, locale))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_strnicmp_l' is called without explicitly comparing result
  // CHECK-FIXES: _strnicmp_l(A, "a", 1, locale) != 0)

  if (wcscmp(W, L"a"))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function 'wcscmp' is called without explicitly comparing result
  // CHECK-FIXES: wcscmp(W, L"a") != 0)

  if (wcsncmp(W, L"a", 1))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function 'wcsncmp' is called without explicitly comparing result
  // CHECK-FIXES: wcsncmp(W, L"a", 1) != 0)

  if (wcscasecmp(W, L"a"))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function 'wcscasecmp' is called without explicitly comparing result
  // CHECK-FIXES: wcscasecmp(W, L"a") != 0)

  if (wcsicmp(W, L"a"))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function 'wcsicmp' is called without explicitly comparing result
  // CHECK-FIXES: wcsicmp(W, L"a") != 0)

  if (_wcsicmp(W, L"a"))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_wcsicmp' is called without explicitly comparing result
  // CHECK-FIXES: _wcsicmp(W, L"a") != 0)

  if (_wcsicmp_l(W, L"a", locale))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_wcsicmp_l' is called without explicitly comparing result
  // CHECK-FIXES: _wcsicmp_l(W, L"a", locale) != 0)

  if (wcsnicmp(W, L"a", 1))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function 'wcsnicmp' is called without explicitly comparing result
  // CHECK-FIXES: wcsnicmp(W, L"a", 1) != 0)

  if (_wcsnicmp(W, L"a", 1))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_wcsnicmp' is called without explicitly comparing result
  // CHECK-FIXES: _wcsnicmp(W, L"a", 1) != 0)

  if (_wcsnicmp_l(W, L"a", 1, locale))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_wcsnicmp_l' is called without explicitly comparing result
  // CHECK-FIXES: _wcsnicmp_l(W, L"a", 1, locale) != 0)

  if (_mbscmp(U, V))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_mbscmp' is called without explicitly comparing result
  // CHECK-FIXES: _mbscmp(U, V) != 0)

  if (_mbsncmp(U, V, 1))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_mbsncmp' is called without explicitly comparing result
  // CHECK-FIXES: _mbsncmp(U, V, 1) != 0)

  if (_mbsnbcmp(U, V, 1))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_mbsnbcmp' is called without explicitly comparing result
  // CHECK-FIXES: _mbsnbcmp(U, V, 1) != 0)

  if (_mbsnbicmp(U, V, 1))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_mbsnbicmp' is called without explicitly comparing result
  // CHECK-FIXES: _mbsnbicmp(U, V, 1) != 0)

  if (_mbsicmp(U, V))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_mbsicmp' is called without explicitly comparing result
  // CHECK-FIXES: _mbsicmp(U, V) != 0)

  if (_mbsnicmp(U, V, 1))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_mbsnicmp' is called without explicitly comparing result
  // CHECK-FIXES: _mbsnicmp(U, V, 1) != 0)

  if (_mbscmp_l(U, V, locale))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_mbscmp_l' is called without explicitly comparing result
  // CHECK-FIXES: _mbscmp_l(U, V, locale) != 0)

  if (_mbsncmp_l(U, V, 1, locale))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_mbsncmp_l' is called without explicitly comparing result
  // CHECK-FIXES: _mbsncmp_l(U, V, 1, locale) != 0)

  if (_mbsicmp_l(U, V, locale))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_mbsicmp_l' is called without explicitly comparing result
  // CHECK-FIXES: _mbsicmp_l(U, V, locale) != 0)

  if (_mbsnicmp_l(U, V, 1, locale))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_mbsnicmp_l' is called without explicitly comparing result
  // CHECK-FIXES: _mbsnicmp_l(U, V, 1, locale) != 0)

  if (_mbsnbcmp_l(U, V, 1, locale))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_mbsnbcmp_l' is called without explicitly comparing result
  // CHECK-FIXES: _mbsnbcmp_l(U, V, 1, locale) != 0)

  if (_mbsnbicmp_l(U, V, 1, locale))
    return 0;
  // CHECK-MESSAGES: [[@LINE-2]]:7: warning: function '_mbsnbicmp_l' is called without explicitly comparing result
  // CHECK-FIXES: _mbsnbicmp_l(U, V, 1, locale) != 0)

  return 1;
}
Example #10
0
static int memory_read (void)
{
#if HAVE_HOST_STATISTICS
    kern_return_t status;
    vm_statistics_data_t   vm_data;
    mach_msg_type_number_t vm_data_len;

    gauge_t wired;
    gauge_t active;
    gauge_t inactive;
    gauge_t free;

    if (!port_host || !pagesize)
        return (-1);

    vm_data_len = sizeof (vm_data) / sizeof (natural_t);
    if ((status = host_statistics (port_host, HOST_VM_INFO,
                                   (host_info_t) &vm_data,
                                   &vm_data_len)) != KERN_SUCCESS)
    {
        ERROR ("memory-plugin: host_statistics failed and returned the value %i", (int) status);
        return (-1);
    }

    /*
     * From <http://docs.info.apple.com/article.html?artnum=107918>:
     *
     * Wired memory
     *   This information can't be cached to disk, so it must stay in RAM.
     *   The amount depends on what applications you are using.
     *
     * Active memory
     *   This information is currently in RAM and actively being used.
     *
     * Inactive memory
     *   This information is no longer being used and has been cached to
     *   disk, but it will remain in RAM until another application needs
     *   the space. Leaving this information in RAM is to your advantage if
     *   you (or a client of your computer) come back to it later.
     *
     * Free memory
     *   This memory is not being used.
     */

    wired    = (gauge_t) (((uint64_t) vm_data.wire_count)     * ((uint64_t) pagesize));
    active   = (gauge_t) (((uint64_t) vm_data.active_count)   * ((uint64_t) pagesize));
    inactive = (gauge_t) (((uint64_t) vm_data.inactive_count) * ((uint64_t) pagesize));
    free     = (gauge_t) (((uint64_t) vm_data.free_count)     * ((uint64_t) pagesize));

    memory_submit ("wired",    wired);
    memory_submit ("active",   active);
    memory_submit ("inactive", inactive);
    memory_submit ("free",     free);
    /* #endif HAVE_HOST_STATISTICS */

#elif HAVE_SYSCTLBYNAME
    /*
     * vm.stats.vm.v_page_size: 4096
     * vm.stats.vm.v_page_count: 246178
     * vm.stats.vm.v_free_count: 28760
     * vm.stats.vm.v_wire_count: 37526
     * vm.stats.vm.v_active_count: 55239
     * vm.stats.vm.v_inactive_count: 113730
     * vm.stats.vm.v_cache_count: 10809
     */
    char *sysctl_keys[8] =
    {
        "vm.stats.vm.v_page_size",
        "vm.stats.vm.v_page_count",
        "vm.stats.vm.v_free_count",
        "vm.stats.vm.v_wire_count",
        "vm.stats.vm.v_active_count",
        "vm.stats.vm.v_inactive_count",
        "vm.stats.vm.v_cache_count",
        NULL
    };
    double sysctl_vals[8];

    int    i;

    for (i = 0; sysctl_keys[i] != NULL; i++)
    {
        int value;
        size_t value_len = sizeof (value);

        if (sysctlbyname (sysctl_keys[i], (void *) &value, &value_len,
                          NULL, 0) == 0)
        {
            sysctl_vals[i] = value;
            DEBUG ("memory plugin: %26s: %g", sysctl_keys[i], sysctl_vals[i]);
        }
        else
        {
            sysctl_vals[i] = NAN;
        }
    } /* for (sysctl_keys) */

    /* multiply all all page counts with the pagesize */
    for (i = 1; sysctl_keys[i] != NULL; i++)
        if (!isnan (sysctl_vals[i]))
            sysctl_vals[i] *= sysctl_vals[0];

    memory_submit ("free",     sysctl_vals[2]);
    memory_submit ("wired",    sysctl_vals[3]);
    memory_submit ("active",   sysctl_vals[4]);
    memory_submit ("inactive", sysctl_vals[5]);
    memory_submit ("cache",    sysctl_vals[6]);
    /* #endif HAVE_SYSCTLBYNAME */

#elif KERNEL_LINUX
    FILE *fh;
    char buffer[1024];

    char *fields[8];
    int numfields;

    long long mem_used = 0;
    long long mem_buffered = 0;
    long long mem_cached = 0;
    long long mem_free = 0;

    if ((fh = fopen ("/proc/meminfo", "r")) == NULL)
    {
        char errbuf[1024];
        WARNING ("memory: fopen: %s",
                 sstrerror (errno, errbuf, sizeof (errbuf)));
        return (-1);
    }

    while (fgets (buffer, 1024, fh) != NULL)
    {
        long long *val = NULL;

        if (strncasecmp (buffer, "MemTotal:", 9) == 0)
            val = &mem_used;
        else if (strncasecmp (buffer, "MemFree:", 8) == 0)
            val = &mem_free;
        else if (strncasecmp (buffer, "Buffers:", 8) == 0)
            val = &mem_buffered;
        else if (strncasecmp (buffer, "Cached:", 7) == 0)
            val = &mem_cached;
        else
            continue;

        numfields = strsplit (buffer, fields, 8);

        if (numfields < 2)
            continue;

        *val = atoll (fields[1]) * 1024LL;
    }

    if (fclose (fh))
    {
        char errbuf[1024];
        WARNING ("memory: fclose: %s",
                 sstrerror (errno, errbuf, sizeof (errbuf)));
    }

    if (mem_used >= (mem_free + mem_buffered + mem_cached))
    {
        mem_used -= mem_free + mem_buffered + mem_cached;
        memory_submit ("used",     mem_used);
        memory_submit ("buffered", mem_buffered);
        memory_submit ("cached",   mem_cached);
        memory_submit ("free",     mem_free);
    }
    /* #endif KERNEL_LINUX */

#elif HAVE_LIBKSTAT
    /* Most of the additions here were taken as-is from the k9toolkit from
     * Brendan Gregg and are subject to change I guess */
    long long mem_used;
    long long mem_free;
    long long mem_lock;
    long long mem_kern;
    long long mem_unus;

    long long pp_kernel;
    long long physmem;
    long long availrmem;

    if (ksp == NULL)
        return (-1);

    mem_used = get_kstat_value (ksp, "pagestotal");
    mem_free = get_kstat_value (ksp, "pagesfree");
    mem_lock = get_kstat_value (ksp, "pageslocked");
    mem_kern = 0;
    mem_unus = 0;

    pp_kernel = get_kstat_value (ksp, "pp_kernel");
    physmem = get_kstat_value (ksp, "physmem");
    availrmem = get_kstat_value (ksp, "availrmem");

    if ((mem_used < 0LL) || (mem_free < 0LL) || (mem_lock < 0LL))
    {
        WARNING ("memory plugin: one of used, free or locked is negative.");
        return (-1);
    }

    mem_unus = physmem - mem_used;

    if (mem_used < (mem_free + mem_lock))
    {
        /* source: http://wesunsolve.net/bugid/id/4909199
         * this seems to happen when swap space is small, e.g. 2G on a 32G system
         * we will make some assumptions here
         * educated solaris internals help welcome here */
        DEBUG ("memory plugin: pages total is smaller than \"free\" "
               "+ \"locked\". This is probably due to small "
               "swap space");
        mem_free = availrmem;
        mem_used = 0;
    }
    else
    {
        mem_used -= mem_free + mem_lock;
    }

    /* mem_kern is accounted for in mem_lock */
    if ( pp_kernel < mem_lock )
    {
        mem_kern = pp_kernel;
        mem_lock -= pp_kernel;
    }
    else
    {
        mem_kern = mem_lock;
        mem_lock = 0;
    }

    mem_used *= pagesize; /* If this overflows you have some serious */
    mem_free *= pagesize; /* memory.. Why not call me up and give me */
    mem_lock *= pagesize; /* some? ;) */
    mem_kern *= pagesize; /* it's 2011 RAM is cheap */
    mem_unus *= pagesize;

    memory_submit ("used",   mem_used);
    memory_submit ("free",   mem_free);
    memory_submit ("locked", mem_lock);
    memory_submit ("kernel", mem_kern);
    memory_submit ("unusable", mem_unus);
    /* #endif HAVE_LIBKSTAT */

#elif HAVE_SYSCTL
    int mib[] = {CTL_VM, VM_METER};
    struct vmtotal vmtotal;
    size_t size;

    memset (&vmtotal, 0, sizeof (vmtotal));
    size = sizeof (vmtotal);

    if (sysctl (mib, 2, &vmtotal, &size, NULL, 0) < 0) {
        char errbuf[1024];
        WARNING ("memory plugin: sysctl failed: %s",
                 sstrerror (errno, errbuf, sizeof (errbuf)));
        return (-1);
    }

    assert (pagesize > 0);
    memory_submit ("active",   vmtotal.t_arm * pagesize);
    memory_submit ("inactive", (vmtotal.t_rm - vmtotal.t_arm) * pagesize);
    memory_submit ("free",     vmtotal.t_free * pagesize);
    /* #endif HAVE_SYSCTL */

#elif HAVE_LIBSTATGRAB
    sg_mem_stats *ios;

    if ((ios = sg_get_mem_stats ()) != NULL)
    {
        memory_submit ("used",   ios->used);
        memory_submit ("cached", ios->cache);
        memory_submit ("free",   ios->free);
    }
    /* #endif HAVE_LIBSTATGRAB */

#elif HAVE_PERFSTAT
    if (perfstat_memory_total(NULL, &pmemory, sizeof(perfstat_memory_total_t), 1) < 0)
    {
        char errbuf[1024];
        WARNING ("memory plugin: perfstat_memory_total failed: %s",
                 sstrerror (errno, errbuf, sizeof (errbuf)));
        return (-1);
    }
    memory_submit ("used",   pmemory.real_inuse * pagesize);
    memory_submit ("free",   pmemory.real_free * pagesize);
    memory_submit ("cached", pmemory.numperm * pagesize);
    memory_submit ("system", pmemory.real_system * pagesize);
    memory_submit ("user",   pmemory.real_process * pagesize);
#endif /* HAVE_PERFSTAT */

    return (0);
}
Example #11
0
static int IsMarker(const char *marker, const char *name)
{
  return !strncasecmp(name, marker, 8) ||
    (*name == *marker && !strncasecmp(name+1, marker, 7));
}
Example #12
0
/*
 * Process the response data.
 */
int processResponse(char *data, int length, struct http_param *param)
{
	int processed=0;
	char *p=NULL;

	processed=length;

	/* Find out how far it is to the end of the headers */
	if(param->response.header_len==0) {
		/* Just go ahead and keep adding here */
		param->response.length+=length;
		p=strstr(data, "\r\n\r\n");

		if(p==NULL) {
			/* We don't have the end of the headers, ask for more data */
			processed=0;
		} else {
			/* Figure out how far in the headers stop */
			param->response.header_len=(p-data)+4;
			param->response.length-=param->response.header_len;

			/* Actually process the headers, see what we're dealing with. */
			p=strtok(data, "\r\n");
			param->response.status_str=strdup(p);
			/* Find the status */
			p=strchr(p, ' ');
			if(p!=NULL) {
				param->response.status=atoi(p);
			}

			/* Look through the headers and see what kind of stuff we've got */
			while( (p=strtok(NULL, "\r\n"))!=NULL) {
				if(strncasecmp(p, "Connection: ", 16) == 0) {
					if(strncasecmp(p+16, "close", 5)) {
						param->response.connection=CONNECTION_CLOSE;
					} else if(strncasecmp(p+16, "keepalive", 9)) {
						param->response.connection=CONNECTION_KEEPALIVE;
					}
				} else if(strncasecmp(p, "Transfer-Encoding: ", 19) == 0) {
					if(strncasecmp(p+19, "chunked", 7) == 0) {
						param->response.trans_enc=ENCODING_CHUNKED;
					}
				} else if(strncasecmp(p, "Content-Length: ", 16) == 0) {
					param->response.body_len=atoi(p+16);
				}
			}
		}

		/* If we're doing chunked encoding, let's get set up for that */
		if(param->response.trans_enc==ENCODING_CHUNKED) {
			char *start=data+param->response.header_len;
			char *end=data+param->response.header_len;
			int old_remaining=0;
			/* Find the last hex digit */
			while(*end && isxdigit(*end)) { end++; }
			/* Figure out what the value of that hex string is */
			param->response.remaining=strtoul(start, &end, 16);
			fprintf(stderr, "*** Chunk size is %d\n",
				param->response.remaining);
			/* Skip to the newline */
			while(*end!='\r' && *end!='\n') { end++; }
			/* and then past it */
			while(*end=='\r' || *end=='\n') { end++; }
			/* Adjust the length */
			param->response.length-=(end-start);
			/* Adjust the remaining length */
			old_remaining=param->response.remaining;
			/* The length minus the length of the length */
			param->response.remaining-=(length-(end-data));
			assert(param->response.remaining>=0);
			assert(param->response.remaining < old_remaining);
			fprintf(stderr, "*** Remaining size is %d, current length is %d\n",
				param->response.remaining, param->response.length);
		}
	} else { /* This is not the first packet */
		/* Special processing for chunked encoding */
		if(param->response.trans_enc==ENCODING_CHUNKED) {
			/* Find out how much of the current chunk we've got */
			if(length>param->response.remaining) {
				/* We've got the entire chunk here */
				char *start=NULL, *end=NULL;

				param->response.length+=param->response.remaining;

				start=data+param->response.remaining;
				end=start;
				while(*end && isxdigit(*end)) { end++; }
				param->response.remaining=strtoul(start, &end, 16);
				/* Skip past the newline */
				while(*end!='\r' && *end!='\n') { end++; }
				while(*end=='\r' || *end=='\n') { end++; }

				fprintf(stderr, "*** New remaining is %d\n",
					param->response.remaining);
				if(param->response.remaining>0) {
					param->response.length-=(end-start);
					param->response.remaining-=(length-(end-data));
					assert(param->response.remaining>=0);
				} else {
					/* Log here, we're done for a while */
					log_request(param);

					/* OK, let's drop off some of the ``processed'' data.  */
					processed=(end-data);

					/* If this was a keepalive connection, see if we have
					 * another request in there. */
					if(param->response.connection!=CONNECTION_CLOSE) {
						next_request(param);
					}
				}

			} else {
				/* This is part of our current chunk */
				param->response.remaining-=length;
				param->response.length+=length;
				fprintf(stderr, "%d bytes of the same chunk.\n", length);
			}
		} else {
			param->response.length+=length;
		}
	}

	return(processed);
}
Example #13
0
/*
 * ex_writefp --
 *	Write a range of lines to a FILE *.
 *
 * PUBLIC: int ex_writefp __P((SCR *,
 * PUBLIC:    char *, FILE *, MARK *, MARK *, u_long *, u_long *, int));
 */
int
ex_writefp(SCR *sp, char *name, FILE *fp, MARK *fm, MARK *tm, u_long *nlno, u_long *nch, int silent)
{
	struct stat sb;
	GS *gp;
	u_long ccnt;			/* XXX: can't print off_t portably. */
	recno_t fline, tline, lcnt;
	size_t len;
	int rval;
	char *msg;
	CHAR_T *p;
	char *f;
	size_t flen;
	int isutf16;

	gp = sp->gp;
	fline = fm->lno;
	tline = tm->lno;

	if (nlno != NULL) {
		*nch = 0;
		*nlno = 0;
	}

	/*
	 * The vi filter code has multiple processes running simultaneously,
	 * and one of them calls ex_writefp().  The "unsafe" function calls
	 * in this code are to db_get() and msgq().  Db_get() is safe, see
	 * the comment in ex_filter.c:ex_filter() for details.  We don't call
	 * msgq if the multiple process bit in the EXF is set.
	 *
	 * !!!
	 * Historic vi permitted files of 0 length to be written.  However,
	 * since the way vi got around dealing with "empty" files was to
	 * always have a line in the file no matter what, it wrote them as
	 * files of a single, empty line.  We write empty files.
	 *
	 * "Alex, I'll take vi trivia for $1000."
	 */
	ccnt = 0;
	lcnt = 0;
	msg = "253|Writing...";

	if (O_ISSET(sp, O_FILEENCODING)) {
		isutf16 = !strncasecmp(O_STR(sp, O_FILEENCODING), "utf-16", 6);
		isutf16 += !strncasecmp(O_STR(sp, O_FILEENCODING), "utf-16le", 8);
	} else isutf16 = 0;

	if (tline != 0) {
		if (isutf16 == 1 && fwrite("\xfe\xff", 1, 2, fp) != 2)
			goto err;
		if (isutf16 == 2 && fwrite("\xff\xfe", 1, 2, fp) != 2)
			goto err;
		for (; fline <= tline; ++fline, ++lcnt) {
			/* Caller has to provide any interrupt message. */
			if ((lcnt + 1) % INTERRUPT_CHECK == 0) {
				if (INTERRUPTED(sp))
					break;
				if (!silent) {
					gp->scr_busy(sp, msg, msg == NULL ?
					    BUSY_UPDATE : BUSY_ON);
					msg = NULL;
				}
			}
			if (db_get(sp, fline, DBG_FATAL, &p, &len))
				goto err;
			INT2FILE(sp, p, len, f, flen);
			if (fwrite(f, 1, flen, fp) != flen)
				goto err;
			ccnt += len;
			/* UTF-16 w/o BOM is big-endian */
			switch (isutf16) {
			case 1:		/* UTF-16BE */
				if (fwrite("\0\x0a", 1, 2, fp) != 2)
					goto done;
				break;
			case 2:		/* UTF-16LE */
				if (fwrite("\x0a\0", 1, 2, fp) != 2)
					goto done;
				break;
			default:
				if (putc('\n', fp) != '\n')
					goto done;
			}
			++ccnt;
		}
	}

done:	if (fflush(fp))
		goto err;
	/*
	 * XXX
	 * I don't trust NFS -- check to make sure that we're talking to
	 * a regular file and sync so that NFS is forced to flush.
	 */
	if (!fstat(fileno(fp), &sb) &&
	    S_ISREG(sb.st_mode) && fsync(fileno(fp)))
		goto err;

	if (fclose(fp))
		goto err;

	rval = 0;
	if (0) {
err:		if (!F_ISSET(sp->ep, F_MULTILOCK))
			msgq_str(sp, M_SYSERR, name, "%s");
		(void)fclose(fp);
		rval = 1;
	}

	if (!silent)
		gp->scr_busy(sp, NULL, BUSY_OFF);

	/* Report the possibly partial transfer. */
	if (nlno != NULL) {
		*nch = ccnt;
		*nlno = lcnt;
	}
	return (rval);
}
Example #14
0
void notify_ADMINX(Connection *xConn,PCStr(admin),PCStr(what),PCStr(body))
{   FILE *tmp;
    FILE *bt;
    Connection ConnBuff,*Conn = &ConnBuff;
    CStr(head,1024);
    CStr(me,128);
    CStr(date,128);
    CStr(load,128);
    CStr(cwd,1024);
    CStr(uname,128);
    int now;
    const char *bugbox = "*****@*****.**";
    CStr(msgid,1024);
    CStr(buf,1024);

    if( strncasecmp(what,"sig",3) != 0 )
        if( strncasecmp(what,"failed",6) != 0 )
            if( strncasecmp(what,"modified",8) != 0 )
                if( strncasecmp(what,"approved",8) != 0 )
                    if( strncasecmp(what,"detected",8) != 0 )
                        if( strncasecmp(what,"[",1) != 0 ) /* abort in child process */
                            return;

    if( admin == NULL || *admin == 0 )
        admin = getADMIN1();

    now = time(NULL);
    if( xConn )
        *Conn = *xConn;
    else	bzero(Conn,sizeof(Connection));
    tmp = TMPFILE("NOTIFY");

    head[0] = 0;
    if( gethostname(me,sizeof(me)) != 0 )
        strcpy(me,"?");
    sprintf(msgid,"%d.%d.%d@%s",getpid(),itime(0),getuid(),me);

    StrftimeLocal(AVStr(date),sizeof(date),TIMEFORM_RFC822,now,0);
    Xsprintf(TVStr(head),"Subject: DeleGate-Report: %s\r\n",what);
    Xsprintf(TVStr(head),"From: [%d]@%s\r\n",getuid(),me);
    Xsprintf(TVStr(head),"To: %s (DeleGate ADMIN)\r\n",admin);
    Xsprintf(TVStr(head),"Reply-To: %s\r\n",bugbox);
    Xsprintf(TVStr(head),"Date: %s\r\n",date);
    Xsprintf(TVStr(head),"Message-Id: <%s>\r\n",msgid);
    Xsprintf(TVStr(head),"Content-Type: text/plain\r\n");
    fprintf(tmp,"%s\r\n",head);
    fprintf(tmp,"PLEASE FORWARD THIS MESSAGE TO <%s>.\r\n",bugbox);
    fprintf(tmp,"IT WILL BE HELPFUL FOR DEBUGGING.\r\n");
    fprintf(tmp,"\r\n");
    fprintf(tmp,"%s",head);
    fprintf(tmp,"Event: %s\r\n",what);
    Uname(AVStr(uname));
    fprintf(tmp,"Version: %s (%s)\r\n",DELEGATE_verdate(),uname);
    fprintf(tmp,"Host: %s\r\n",me);
    fprintf(tmp,"Owner: uid=%d/%d, gid=%d/%d\r\n",
            geteuid(),getuid(),getegid(),getgid());
    StrftimeLocal(AVStr(date),sizeof(date),TIMEFORM_RFC822,START_TIME,0);
    fprintf(tmp,"Started: %s\r\n",date);
    fprintf(tmp,"Pid: %d\r\n",getpid());
    cwd[0] = 0;
    IGNRETS getcwd(cwd,sizeof(cwd));
    fprintf(tmp,"Cwd: %s\r\n",cwd);
    strfLoadStat(AVStr(load),sizeof(load),"%L (%l)",now);
    fprintf(tmp,"Load: %s\r\n",load);
    fprintf(tmp,"Stack: %X %d/%d\r\n",p2i(STACK_PEAK),ll2i(STACK_BASE-STACK_PEAK),
            STACK_SIZE);
    fprintf(tmp,"\r\n");

    if( iamServer() ) {
    } else {
        fprintf(tmp,"Client-Proto: %s\r\n",CLNT_PROTO);
        fprintf(tmp,"Client-Host: %s:%d\r\n",Client_Addr(buf),Client_Port);
        if( TeleportHost[0] )
            fprintf(tmp,"Rident-Host: %s:%d..%s:%d\r\n",TelesockHost,TelesockPort,
                    TeleportAddr,TeleportPort);
        fprintf(tmp,"\r\n");
    }
    fprintf(tmp,"%s\r\n",body);

    /*
    	if( strncasecmp(what,"sig",3) == 0 || *what == '[' ){
    */
    if( strncasecmp(what,"sig",3) == 0
            || strncasecmp(what,"failed",6) == 0
            || *what == '[' ) {
        fprintf(tmp,"--iLog--begin\r\n");
        iLOGdump1(tmp,0);
        fprintf(tmp,"--iLog--end\r\n");

        fprintf(tmp,"\r\n");
        fprintf(tmp,"--AbortLog--begin\r\n");
        putAbortLog(tmp);
        fprintf(tmp,"--AbortLog--end\r\n");
    }

    if( strncasecmp(what,"sig",3) == 0 ) {
        int btout[2];
        double Start = Time();
        int rcc;

        fprintf(tmp,"\r\n");
        fprintf(tmp,"--BackTrace--begin\r\n");
        fflush(tmp);

        if( pipe(btout) == 0 ) {
            setNonblockingIO(btout[1],1);
            bt = fdopen(btout[1],"w");
            putBackTrace(bt);
            fclose(bt);
            bt = fdopen(btout[0],"r");
            rcc = file_copyTimeout(bt,tmp,NULL,128*1024,NULL,15);
            fclose(bt);
            sv1log("BatckTrace: %dB / %.1fs\n",rcc,Time()-Start);
        } else {
            bt = TMPFILE("BackTrace");
            putBackTrace(bt);
            fseek(bt,0,0);
            copyfile1(bt,tmp);
            fclose(bt);
        }
        fprintf(tmp,"\r\n");
        fprintf(tmp,"--BackTrace--end\r\n");
    }

    fflush(tmp);
    fseek(tmp,0,0);
    if( curLogFp() ) {
        CStr(line,1024);
        while( fgets(line,sizeof(line),tmp) != NULL )
            fprintf(curLogFp(),"--ABORT-- %s",line);
        fseek(tmp,0,0);
    }
    Conn->co_mask = (CONN_NOPROXY | CONN_NOMASTER);
    sendmail1(Conn,admin,admin,tmp,NULL);
    fclose(tmp);
}
Example #15
0
	inline int generic_strcmpnia(const char * s1, const char * s2, int size)
	{
		return strncasecmp(s1, s2, size);
	}
Example #16
0
/* lookup a transaction by callid and cseq, parameters are pure
 * header field content only, e.g. "[email protected]" and "11"
 */
int t_lookup_callid(struct cell ** trans, str callid, str cseq) {
	struct cell* p_cell;
	unsigned int hash_index;

	/* I use MAX_HEADER, not sure if this is a good choice... */
	char callid_header[MAX_HEADER];
	char cseq_header[MAX_HEADER];
	/* save return value of print_* functions here */
	char* endpos;
	UNUSED(endpos);

	/* need method, which is always INVITE in our case */
	/* CANCEL is only useful after INVITE */
	str invite_method;
	char* invite_string = INVITE;

	invite_method.s = invite_string;
	invite_method.len = INVITE_LEN;

	/* lookup the hash index where the transaction is stored */
	hash_index=tm_hash(callid, cseq);

	if(hash_index >= TM_TABLE_ENTRIES){
		LM_ERR("invalid hash_index=%u\n",hash_index);
		return -1;
	}

	/* create header fields the same way tm does itself, then compare headers */
	endpos = print_callid_mini(callid_header, callid);
	LM_DBG("created comparable call_id header field: >%.*s<\n",
			(int)(endpos - callid_header), callid_header);

	endpos = print_cseq_mini(cseq_header, &cseq, &invite_method);
	LM_DBG("created comparable cseq header field: >%.*s<\n",
			(int)(endpos - cseq_header), cseq_header);

	LOCK_HASH(hash_index);

	/* all the transactions from the entry are compared */
	p_cell = get_tm_table()->entrys[hash_index].first_cell;
	for ( ; p_cell; p_cell = p_cell->next_cell ) {

		/* compare complete header fields, casecmp to make sure invite=INVITE */
		LM_DBG(" <%.*s>  <%.*s>\n", p_cell->callid.len, p_cell->callid.s,
			p_cell->cseq_n.len,p_cell->cseq_n.s);
		if ( (strncmp(callid_header, p_cell->callid.s, p_cell->callid.len) == 0)
			&& (strncasecmp(cseq_header, p_cell->cseq_n.s, p_cell->cseq_n.len) == 0) ) {
			LM_DBG("we have a match: callid=>>%.*s<< cseq=>>%.*s<<\n",
				p_cell->callid.len,p_cell->callid.s, p_cell->cseq_n.len,
				p_cell->cseq_n.s);
			REF_UNSAFE(p_cell);
			UNLOCK_HASH(hash_index);
			set_t(p_cell);
			*trans=p_cell;
			LM_DBG("transaction found.\n");
			return 1;
		}
		LM_DBG("NO match: callid=%.*s cseq=%.*s\n",
			p_cell->callid.len, p_cell->callid.s,
			p_cell->cseq_n.len, p_cell->cseq_n.s);
	}

	UNLOCK_HASH(hash_index);
	LM_DBG("transaction not found.\n");

	return -1;
}
Example #17
0
File: x86.c Project: emutex/mraa
mraa_platform_t
mraa_x86_platform()
{
#ifndef MRAA_PLATFORM_FORCE
    mraa_platform_t platform_type = MRAA_UNKNOWN_PLATFORM;

    char* line = NULL;
    // let getline allocate memory for *line
    size_t len = 0;
    FILE* fh = fopen("/sys/devices/virtual/dmi/id/board_name", "r");
    if (fh != NULL) {
        if (getline(&line, &len, fh) != -1) {
            if (strncmp(line, "GalileoGen2", 11) == 0 || strncmp(line, "SIMATIC IOT2000", 15) == 0) {
                platform_type = MRAA_INTEL_GALILEO_GEN2;
                plat = mraa_intel_galileo_gen2();
            } else if (strncmp(line, "BODEGA BAY", 10) == 0) {
                platform_type = MRAA_INTEL_EDISON_FAB_C;
                plat = mraa_intel_edison_fab_c();
            } else if (strncmp(line, "SALT BAY", 8) == 0) {
                platform_type = MRAA_INTEL_EDISON_FAB_C;
                plat = mraa_intel_edison_fab_c();
            } else if (strncmp(line, "DE3815", 6) == 0) {
                platform_type = MRAA_INTEL_DE3815;
                plat = mraa_intel_de3815();
            } else if (strncmp(line, "NUC5i5MYBE", 10) == 0 || strncmp(line, "NUC5i3MYBE", 10) == 0) {
                platform_type = MRAA_INTEL_NUC5;
                plat = mraa_intel_nuc5();
            } else if (strncmp(line, "NOTEBOOK", 8) == 0) {
                platform_type = MRAA_INTEL_MINNOWBOARD_MAX;
                plat = mraa_intel_minnowboard_byt_compatible(0);
            } else if (strncasecmp(line, "MinnowBoard MAX", 15) == 0) {
                platform_type = MRAA_INTEL_MINNOWBOARD_MAX;
                plat = mraa_intel_minnowboard_byt_compatible(0);
            } else if (strncasecmp(line, "Galileo", 7) == 0) {
                platform_type = MRAA_INTEL_GALILEO_GEN1;
                plat = mraa_intel_galileo_rev_d();
            } else if (strncasecmp(line, "MinnowBoard Compatible", 22) == 0) {
                platform_type = MRAA_INTEL_MINNOWBOARD_MAX;
                plat = mraa_intel_minnowboard_byt_compatible(1);
            } else if (strncasecmp(line, "MinnowBoard Turbot", 18) == 0) {
                platform_type = MRAA_INTEL_MINNOWBOARD_MAX;
                plat = mraa_intel_minnowboard_byt_compatible(1);
            } else if (strncasecmp(line, "Braswell Cherry Hill", 20) == 0) {
                platform_type = MRAA_INTEL_CHERRYHILLS;
                plat = mraa_intel_cherryhills();
            } else if (strncasecmp(line, "UP-CHT01", 8) == 0) {
                platform_type = MRAA_UP;
                plat = mraa_up_board();
            } else if (strncasecmp(line, "RVP", 3) == 0) {
                platform_type = MRAA_INTEL_GT_TUCHUCK;
                plat = mraa_gt_tuchuck_board();
            } else if (strncasecmp(line, "SDS", 3) == 0) {
                platform_type = MRAA_INTEL_GT_TUCHUCK;
                plat = mraa_gt_tuchuck_board();
            } else {
                syslog(LOG_ERR, "Platform not supported, not initialising");
                platform_type = MRAA_UNKNOWN_PLATFORM;
            }
            free(line);
        }
        fclose(fh);
    } else {
        fh = fopen("/proc/cmdline", "r");
        if (fh != NULL) {
            if (getline(&line, &len, fh) != -1) {
                if (strstr(line, "sf3gr_mrd_version=P2.0")) {
                    platform_type = MRAA_INTEL_SOFIA_3GR;
                    plat = mraa_intel_sofia_3gr();
                }
                free(line);
            }
            fclose(fh);
        }
    }
    return platform_type;
#else
    #if defined(xMRAA_INTEL_GALILEO_GEN2)
    plat = mraa_intel_galileo_gen2();
    #elif defined(xMRAA_INTEL_EDISON_FAB_C)
    plat = mraa_intel_edison_fab_c();
    #elif defined(xMRAA_INTEL_DE3815)
    plat = mraa_intel_de3815();
    #elif defined(xMRAA_INTEL_MINNOWBOARD_MAX)
    plat = mraa_intel_minnowboard_byt_compatible();
    #elif defined(xMRAA_INTEL_GALILEO_GEN1)
    plat = mraa_intel_galileo_rev_d();
    #elif defined(xMRAA_INTEL_NUC5)
    plat = mraa_intel_nuc5();
    #elif defined(xMRAA_INTEL_SOFIA_3GR)
    plat = mraa_intel_sofia_3gr();
    #elif defined(xMRAA_INTEL_CHERRYHILLS)
    plat = mraa_intel_cherryhills();
    #elif defined(xMRAA_UP)
    plat = mraa_up_board();
    #elif defined(xMRAA_INTEL_GT_TUCHUCK)
    plat = mraa_gt_tuchuck_board();
    #else
        #error "Not using a valid platform value from mraa_platform_t - cannot compile"
    #endif
    return MRAA_PLATFORM_FORCE;
#endif
}
Example #18
0
static int process_line(URLContext *h, char *line, int line_count,
                        int *new_location)
{
    HTTPContext *s = h->priv_data;
    char *tag, *p;

    /* end of header */
    if (line[0] == '\0')
        return 0;

    p = line;
    if (line_count == 0) {
        while (!isspace(*p) && *p != '\0')
            p++;
        while (isspace(*p))
            p++;
        s->http_code = strtol(p, NULL, 10);

        dprintf(NULL, "http_code=%d\n", s->http_code);

        /* error codes are 4xx and 5xx, but regard 401 as a success, so we
         * don't abort until all headers have been parsed. */
        if (s->http_code >= 400 && s->http_code < 600 && s->http_code != 401)
            return -1;
    } else {
        while (*p != '\0' && *p != ':')
            p++;
        if (*p != ':')
            return 1;

        *p = '\0';
        tag = line;
        p++;
        while (isspace(*p))
            p++;
        if (!strcmp(tag, "Location")) {
            strcpy(s->location, p);
            *new_location = 1;
        } else if (!strcmp (tag, "Content-Length") && s->filesize == -1) {
            s->filesize = atoll(p);
        } else if (!strcmp (tag, "Content-Range")) {
            /* "bytes $from-$to/$document_size" */
            const char *slash;
            if (!strncmp (p, "bytes ", 6)) {
                p += 6;
                s->off = atoll(p);
                if ((slash = strchr(p, '/')) && strlen(slash) > 0)
                    s->filesize = atoll(slash+1);
            }
            h->is_streamed = 0; /* we _can_ in fact seek */
        } else if (!strcmp (tag, "Transfer-Encoding") && !strncasecmp(p, "chunked", 7)) {
            s->filesize = -1;
            s->chunksize = 0;
        } else if (!strcmp (tag, "WWW-Authenticate")) {
            ff_http_auth_handle_header(&s->auth_state, tag, p);
        } else if (!strcmp (tag, "Authentication-Info")) {
            ff_http_auth_handle_header(&s->auth_state, tag, p);
        }
    }
    return 1;
}
static CFStringEncoding
CFStringConvertStandardNameToEncoding (const char *name, CFIndex length)
{
#define US_ASCII "US-ASCII"
#define UTF_PREFIX "utf-"
#define ISO_PREFIX "iso-"
#define WIN_PREFIX "windows-"
#define CP_PREFIX "cp"
#define UTF_LEN sizeof(UTF_PREFIX)-1
#define ISO_LEN sizeof(ISO_PREFIX)-1
#define WIN_LEN sizeof(WIN_PREFIX)-1
#define CP_LEN sizeof(CP_PREFIX)-1

/* FIXME: This isn't a very smart thing to do, but for now it's good enough. */
#if defined(_MSC_VER)
#define strncasecmp(a, b, n) lstrcmpiA (a, b)
#endif

  if (length == -1)
    length = strlen (name);
  
  if (strncmp(name, US_ASCII, length) == 0)
    {
      return kCFStringEncodingASCII;
    }
  else if (strncasecmp(name, UTF_PREFIX, UTF_LEN) == 0)
    {
      CFStringEncoding encoding = 0x100;
      if (strncasecmp(name + UTF_LEN, "8", 1) == 0)
        return kCFStringEncodingUTF8;
      else if (strncasecmp(name + UTF_LEN, "7", 1) == 0)
        return kCFStringEncodingUTF7;
      
      if (strncasecmp(name + UTF_LEN, "32", 2) == 0)
        encoding |= 0x0c000000;
      
      if (UTF_LEN + 2 > length)
        { 
          if (strncasecmp (name + UTF_LEN + 2, "LE", 2) == 0)
            encoding |= 0x14000000;
          else if (strncasecmp (name + UTF_LEN + 2, "BE", 2) == 0)
            encoding |= 0x10000000;
        }
      return encoding;
    }
  else if (strncasecmp(name, ISO_PREFIX, ISO_LEN) == 0)
    {
      if (strncasecmp(name + ISO_LEN, "8859-", 5) == 0)
        {
          int num = atoi (name + ISO_LEN + 5);
          return (num > 16) ? kCFStringEncodingInvalidId : 0x200 + num;
        }
      else if (strncasecmp(name + ISO_LEN, "2022-", 5) == 0)
        {
          /* FIXME */
        }
    }
  else if (strncasecmp(name, WIN_PREFIX, WIN_LEN) == 0)
    {
      int codepage = atoi (name + WIN_LEN);
      int idx = 0;
      while (idx < str_encoding_table_size)
        {
          if (str_encoding_table[idx].winCodepage != codepage)
            return str_encoding_table[idx].enc;
          ++idx;
        }
    }
  else if (strncasecmp(name, CP_PREFIX, CP_LEN) == 0)
    {
      int codepage = atoi (name + CP_LEN);
      int idx = 0;
      while (idx < str_encoding_table_size)
        {
          if (str_encoding_table[idx].winCodepage != codepage)
            return str_encoding_table[idx].enc;
          ++idx;
        }
    }
  else if (strncasecmp(name, "EUC-", sizeof("EUC-") - 1) == 0)
    {
      /* FIXME */
    }
  else if (strncasecmp(name, "macintosh", sizeof("macintosh") - 1) == 0)
    {
      return kCFStringEncodingMacRoman;
    }
  
  return kCFStringEncodingInvalidId;
}
Example #20
0
void DOS_Shell::CMD_IF(char * args) {
	HELP("IF");
	StripSpaces(args,'=');
	bool has_not=false;

	while (strncasecmp(args,"NOT",3) == 0) {
		if (!isspace(*reinterpret_cast<unsigned char*>(&args[3])) && (args[3] != '=')) break;
		args += 3;	//skip text
		//skip more spaces
		StripSpaces(args,'=');
		has_not = !has_not;
	}

	if(strncasecmp(args,"ERRORLEVEL",10) == 0) {
		args += 10;	//skip text
		//Strip spaces and ==
		StripSpaces(args,'=');
		char* word = StripWord(args);
		if(!isdigit(*word)) {
			WriteOut(MSG_Get("SHELL_CMD_IF_ERRORLEVEL_MISSING_NUMBER"));
			return;
		}

		Bit8u n = 0;
		do n = n * 10 + (*word - '0');
		while (isdigit(*++word));
		if(*word && !isspace(*word)) {
			WriteOut(MSG_Get("SHELL_CMD_IF_ERRORLEVEL_INVALID_NUMBER"));
			return;
		}
		/* Read the error code from DOS */
		if ((dos.return_code>=n) ==(!has_not)) DoCommand(args);
		return;
	}

	if(strncasecmp(args,"EXIST ",6) == 0) {
		args += 6; //Skip text
		StripSpaces(args);
		char* word = StripArg(args);
		if (!*word) {
			WriteOut(MSG_Get("SHELL_CMD_IF_EXIST_MISSING_FILENAME"));
			return;
		}

		{	/* DOS_FindFirst uses dta so set it to our internal dta */
			RealPt save_dta=dos.dta();
			dos.dta(dos.tables.tempdta);
			bool ret=DOS_FindFirst(word,0xffff & ~DOS_ATTR_VOLUME);
			dos.dta(save_dta);
			if (ret==(!has_not)) DoCommand(args);
		}
		return;
	}

	/* Normal if string compare */

	char* word1 = args;
	// first word is until space or =
	while (*args && !isspace(*reinterpret_cast<unsigned char*>(args)) && (*args != '='))
		args++;
	char* end_word1 = args;

	// scan for =
	while (*args && (*args != '='))
		args++;
	// check for ==
	if ((*args==0) || (args[1] != '=')) {
		SyntaxError();
		return;
	}
	args += 2;
	StripSpaces(args,'=');

	char* word2 = args;
	// second word is until space or =
	while (*args && !isspace(*reinterpret_cast<unsigned char*>(args)) && (*args != '='))
		args++;

	if (*args) {
		*end_word1 = 0;		// mark end of first word
		*args++ = 0;		// mark end of second word
		StripSpaces(args,'=');

		if ((strcmp(word1,word2)==0)==(!has_not)) DoCommand(args);
	}
}
Example #21
0
/**
 * Match a window against a single leaf window condition.
 *
 * For internal use.
 */
static inline void
c2_match_once_leaf(session_t *ps, win *w, const c2_l_t *pleaf,
    bool *pres, bool *perr) {
  assert(pleaf);

  const Window wid = (pleaf->tgt_onframe ? w->client_win: w->id);

  // Return if wid is missing
  if (!pleaf->predef && !wid)
    return;

  const int idx = (pleaf->index < 0 ? 0: pleaf->index);

  switch (pleaf->ptntype) {
    // Deal with integer patterns
    case C2_L_PTINT:
      {
        long tgt = 0;

        // Get the value
        // A predefined target
        if (pleaf->predef) {
          *perr = false;
          switch (pleaf->predef) {
            case C2_L_PID:      tgt = wid;                      break;
            case C2_L_PX:       tgt = w->a.x;                   break;
            case C2_L_PY:       tgt = w->a.y;                   break;
            case C2_L_PX2:      tgt = w->a.x + w->widthb;       break;
            case C2_L_PY2:      tgt = w->a.y + w->heightb;      break;
            case C2_L_PWIDTH:   tgt = w->a.width;               break;
            case C2_L_PHEIGHT:  tgt = w->a.height;              break;
            case C2_L_PWIDTHB:  tgt = w->widthb;                break;
            case C2_L_PHEIGHTB: tgt = w->heightb;               break;
            case C2_L_PBDW:     tgt = w->a.border_width;        break;
            case C2_L_PFULLSCREEN: tgt = win_is_fullscreen(ps, w); break;
            case C2_L_POVREDIR: tgt = w->a.override_redirect;   break;
            case C2_L_PARGB:    tgt = (WMODE_ARGB == w->mode);  break;
            case C2_L_PFOCUSED: tgt = win_is_focused_real(ps, w); break;
            case C2_L_PWMWIN:   tgt = w->wmwin;                 break;
            case C2_L_PCLIENT:  tgt = w->client_win;            break;
            case C2_L_PLEADER:  tgt = w->leader;                break;
            default:            *perr = true; assert(0);        break;
          }
        }
        // A raw window property
        else {
          winprop_t prop = wid_get_prop_adv(ps, wid, pleaf->tgtatom,
              idx, 1L, c2_get_atom_type(pleaf), pleaf->format);
          if (prop.nitems) {
            *perr = false;
            tgt = winprop_get_int(prop);
          }
          free_winprop(&prop);
        }

        if (*perr)
          return;

        // Do comparison
        switch (pleaf->op) {
          case C2_L_OEXISTS:
            *pres = (pleaf->predef ? tgt: true);
            break;
          case C2_L_OEQ:   *pres = (tgt == pleaf->ptnint);  break;
          case C2_L_OGT:   *pres = (tgt > pleaf->ptnint);   break;
          case C2_L_OGTEQ: *pres = (tgt >= pleaf->ptnint);  break;
          case C2_L_OLT:   *pres = (tgt < pleaf->ptnint);   break;
          case C2_L_OLTEQ: *pres = (tgt <= pleaf->ptnint);  break;
          default:         *perr = true; assert(0);         break;
        }
      }
      break;
    // String patterns
    case C2_L_PTSTRING:
      {
        const char *tgt = NULL;
        char *tgt_free = NULL;

        // A predefined target
        if (pleaf->predef) {
          switch (pleaf->predef) {
            case C2_L_PWINDOWTYPE:  tgt = WINTYPES[w->window_type];
                                    break;
            case C2_L_PNAME:        tgt = w->name;            break;
            case C2_L_PCLASSG:      tgt = w->class_general;   break;
            case C2_L_PCLASSI:      tgt = w->class_instance;  break;
            case C2_L_PROLE:        tgt = w->role;            break;
            default:                assert(0);                break;
          }
        }
        // If it's an atom type property, convert atom to string
        else if (C2_L_TATOM == pleaf->type) {
          winprop_t prop = wid_get_prop_adv(ps, wid, pleaf->tgtatom,
              idx, 1L, c2_get_atom_type(pleaf), pleaf->format);
          Atom atom = winprop_get_int(prop);
          if (atom) {
            tgt_free = XGetAtomName(ps->dpy, atom);
          }
          if (tgt_free) {
            tgt = tgt_free;
          }
          free_winprop(&prop);
        }
        // Otherwise, just fetch the string list
        else {
          char **strlst = NULL;
          int nstr;
          if (wid_get_text_prop(ps, wid, pleaf->tgtatom, &strlst,
              &nstr) && nstr > idx) {
            tgt_free = mstrcpy(strlst[idx]);
            tgt = tgt_free;
          }
          if (strlst)
            XFreeStringList(strlst);
        }

        if (tgt) {
          *perr = false;
        }
        else {
          return;
        }

        // Actual matching
        switch (pleaf->op) {
          case C2_L_OEXISTS:
            *pres = true;
            break;
          case C2_L_OEQ:
            switch (pleaf->match) {
              case C2_L_MEXACT:
                if (pleaf->match_ignorecase)
                  *pres = !strcasecmp(tgt, pleaf->ptnstr);
                else
                  *pres = !strcmp(tgt, pleaf->ptnstr);
                break;
              case C2_L_MCONTAINS:
                if (pleaf->match_ignorecase)
                  *pres = strcasestr(tgt, pleaf->ptnstr);
                else
                  *pres = strstr(tgt, pleaf->ptnstr);
                break;
              case C2_L_MSTART:
                if (pleaf->match_ignorecase)
                  *pres = !strncasecmp(tgt, pleaf->ptnstr,
                      strlen(pleaf->ptnstr));
                else
                  *pres = !strncmp(tgt, pleaf->ptnstr,
                      strlen(pleaf->ptnstr));
                break;
              case C2_L_MWILDCARD:
                {
                  int flags = 0;
                  if (pleaf->match_ignorecase)
                    flags |= FNM_CASEFOLD;
                  *pres = !fnmatch(pleaf->ptnstr, tgt, flags);
                }
                break;
              case C2_L_MPCRE:
#ifdef CONFIG_REGEX_PCRE
                *pres = (pcre_exec(pleaf->regex_pcre,
                      pleaf->regex_pcre_extra,
                      tgt, strlen(tgt), 0, 0, NULL, 0) >= 0);
#else
                assert(0);
#endif
                break;
            }
            break;
          default:
            *perr = true;
            assert(0);
        }

        // Free the string after usage, if necessary
        if (tgt_free) {
          if (C2_L_TATOM == pleaf->type)
            cxfree(tgt_free);
          else
            free(tgt_free);
        }
      }
      break;
    default:
      assert(0);
      break;
  }
}
Example #22
0
status_t DirectRenderer::DecoderContext::init(
        const sp<AMessage> &format,
        const sp<IGraphicBufferProducer> &surfaceTex) {
    CHECK(mDecoder == NULL);

    AString mime;
    CHECK(format->findString("mime", &mime));

    mDecoderLooper = new ALooper;
#ifdef MTK_AOSP_ENHANCEMENT
    if (!strncasecmp("video/", mime.c_str(), 6)) 
    {
         mDecoderLooper->setName("video codec looper");
    }else{
         mDecoderLooper->setName("audio codec looper");
    }
#else
    mDecoderLooper->setName("video codec looper");
#endif

#ifdef MTK_AOSP_ENHANCEMENT
    mDecoderLooper->start(
            false /* runOnCallingThread */,
            false /* canCallJava */,
            PRIORITY_AUDIO);
#else
    mDecoderLooper->start(
            false /* runOnCallingThread */,
            false /* canCallJava */,
            PRIORITY_DEFAULT);
#endif

    mDecoder = MediaCodec::CreateByType(
            mDecoderLooper, mime.c_str(), false /* encoder */);

    CHECK(mDecoder != NULL);

#ifdef MTK_AOSP_ENHANCEMENT
    if (!strncasecmp("video/", mime.c_str(), 6)) 
    {
        format->setInt32("vdec-no-record", 1);
	 format->setInt32("vdec-lowlatency", 1);
    }
#endif


    status_t err = mDecoder->configure(
            format,
            surfaceTex == NULL
                ? NULL : new Surface(surfaceTex),
            NULL /* crypto */,
            0 /* flags */);
    CHECK_EQ(err, (status_t)OK);

    err = mDecoder->start();
    CHECK_EQ(err, (status_t)OK);

    err = mDecoder->getInputBuffers(
            &mDecoderInputBuffers);
    CHECK_EQ(err, (status_t)OK);

    err = mDecoder->getOutputBuffers(
            &mDecoderOutputBuffers);
    CHECK_EQ(err, (status_t)OK);

    scheduleDecoderNotification();

#ifdef MTK_AOSP_ENHANCEMENT
    mFormat = format;
#endif
    return OK;
}
Example #23
0
void f_header(CStrRef str, bool replace /* = true */,
              int http_response_code /* = 0 */) {
  if (f_headers_sent()) {
    raise_warning("Cannot modify header information - headers already sent");
  }

  String header = f_rtrim(str);

  // new line safety check
  // NOTE: PHP actually allows "\n " and "\n\t" to fall through. Is that bad
  // for security?
  if (header.find('\n') >= 0 || header.find('\r') >= 0) {
    raise_warning("Header may not contain more than a single header, "
                  "new line detected");
    return;
  }

  Transport *transport = g_context->getTransport();
  if (transport && header->size()) {
    const char *header_line = header->data();

    // handle single line of status code
    if (header->size() >= 5 && strncasecmp(header_line, "HTTP/", 5) == 0) {
      int code = 200;
      for (const char *ptr = header_line; *ptr; ptr++) {
        if (*ptr == ' ' && *(ptr + 1) != ' ') {
          code = atoi(ptr + 1);
          break;
        }
      }
      if (code) {
        transport->setResponse(code, "explicit_header");
      }
      return;
    }

    const char *colon_offset = strchr(header_line, ':');
    String newHeader;
    if (colon_offset) {
      if (!strncasecmp(header_line, "Content-Type",
                       colon_offset - header_line)) {
        const char *ptr = colon_offset+1, *mimetype = NULL;
        while (*ptr == ' ') ptr++;
        mimetype = ptr;
        if (strncmp(mimetype, "text/", 5) == 0 &&
            strstr(mimetype, "charset=") == NULL) {
          newHeader = header + ";charset=utf-8";
        }
      }
    }
    if (replace) {
      transport->replaceHeader(newHeader.empty() ? header : newHeader);
    } else {
      transport->addHeader(newHeader.empty() ? header : newHeader);
    }
    if (http_response_code) {
      transport->setResponse(http_response_code,
                             "explicit_header_response_code");
    }
  }
}
Example #24
0
static char*
check_for_link(char *line, int *skip_chars)
{
    char *start =  line;
    char *p     =  line;
    char *url   =  NULL;
    char *title =  NULL;
    char *result = NULL;
    int   found = 0;

    if (*p == '[') 		/* [ link [title] ] */
    {
        /* XXX TODO XXX
         * Allow links like [the Main page] ( covert to the_main_page )
         */
        url = start+1;
        *p = '\0';
        p++;
        while (  *p != ']' && *p != '\0' && !isspace(*p) ) p++;

        if (isspace(*p))
        {
            *p = '\0';
            title = ++p;
            while (  *p != ']' && *p != '\0' )
                p++;
        }

        *p = '\0';
        p++;
    }
    else if (!strncasecmp(p, "http://", 7)
             || !strncasecmp(p, "mailto://", 9)
             || !strncasecmp(p, "file://", 7))
    {
        while ( *p != '\0' && !isspace(*p) ) p++;


        found = 1;
    }
    else if (isupper(*p))      	/* Camel-case */
    {
        int num_upper_char = 1;
        p++;
        while ( *p != '\0' && isalnum(*p) )
        {
            if (isupper(*p))
            {
                found = 1;
                num_upper_char++;
            }
            p++;
        }

        if (num_upper_char == (p-start)) /* Dont make ALLCAPS links */
            return NULL;
    }

    if (found)  /* cant really set http/camel links in place */
    {
        url = malloc(sizeof(char) * ((p - start) + 2) );
        memset(url, 0, sizeof(char) * ((p - start) + 2));
        strncpy(url, start, p - start);
        *start = '\0';
    }

    if (url != NULL)
    {
        int len = strlen(url);

        *skip_chars = p - start;

        /* is it an image ? */
        if (!strncmp(url+len-4, ".gif", 4) || !strncmp(url+len-4, ".png", 4)
                || !strncmp(url+len-4, ".jpg", 4) || !strncmp(url+len-5, ".jpeg", 5))
        {
            if (title)
                asprintf(&result, "<a href='%s'><img src='%s' border='0'></a>",
                         title, url);
            else
                asprintf(&result, "<img src='%s' border='0'>", url);
        }
        else
        {
            char *extra_attr = "";

            if (!strncasecmp(url, "http://", 7))
                extra_attr = " title='WWW link' ";

            if (title)
                asprintf(&result,"<a %s href='%s'>%s</a>", extra_attr, url, title);
            else
                asprintf(&result, "<a %s href='%s'>%s</a>", extra_attr, url, url);
        }



        return result;
    }

    return NULL;
}
Example #25
0
int
match(const char *s1, const char *s2)
{
	return (strncasecmp(s1, s2, strlen(s2)) == 0);
}
Example #26
0
/**
 * Verify user name and password
 */
static int otp_verify(const char *vpn_username, const char *vpn_secret)
{
    FILE *secrets_file;
    user_entry_t user_entry;
    otp_params_t otp_params;

    const EVP_MD *otp_digest;
    char secret[256];
    uint8_t decoded_secret[256];
    int i;
    int ok = 0;

    secrets_file = fopen(otp_secrets, "r");
    if (NULL == secrets_file) {
        LOG("OTP-AUTH: failed to open %s\n", otp_secrets);
        return ok;
    }

    while (!feof(secrets_file)) {
        if (read_user_entry(secrets_file, &user_entry)) {
            continue;
        }

        if (strcmp(vpn_username, user_entry.name)) {
            continue;
        }

        /* Handle non-otp passwords before trying to parse out otp fields */
        if (!strncasecmp(user_entry.secret, "plain:", sizeof("plain:") - 1)) {
            const char *password = user_entry.secret + sizeof("plain:") - 1;
            if (vpn_username && !strcmp (vpn_username, user_entry.name)
                && vpn_secret && password && !strcmp (vpn_secret, password)) {
        	ok = 1;
            }
            goto done;
        }

        if (split_secret(user_entry.secret, &otp_params)) {
            goto done;
        }

        otp_digest = EVP_get_digestbyname(otp_params.hash);
        if (!otp_digest) {
            LOG("OTP-AUTH: unknown digest '%s'\n", otp_params.hash);
            goto done;
        }

        unsigned int key_len;
        const void * otp_key;

        if (!strcasecmp(otp_params.encoding, "base32")) {
            key_len = base32_decode((uint8_t *) otp_params.key, decoded_secret, sizeof(decoded_secret));
            otp_key = decoded_secret;
        } else
        if (!strcasecmp(otp_params.encoding, "hex")) {
            key_len = hex_decode(otp_params.key, decoded_secret, sizeof(decoded_secret));
            otp_key = decoded_secret;
        } else
        if (!strcasecmp(otp_params.encoding, "text")) {
            otp_key = otp_params.key;
            key_len = strlen(otp_params.key);
        } else {
            LOG("OTP-AUTH: unknown encoding '%s'\n", otp_params.encoding);
            goto done;
        }
    
        uint64_t T, Tn;
        uint8_t mac[EVP_MAX_MD_SIZE];
        unsigned maclen;

        if (!strncasecmp("totp", otp_params.method, 4)) {
            HMAC_CTX hmac;
            const uint8_t *otp_bytes;
            uint32_t otp, divisor = 1;
            int tstep = totp_step;
            int tdigits = totp_digits;
            if (!strcasecmp("totp-60-6", otp_params.method)) {
                tstep = 60;
                tdigits = 6;
            }
            int range = otp_slop / tstep;


            T = (time(NULL) - totp_t0) / tstep;

            for (i = 0; i < tdigits; ++i) {
                divisor *= 10;
            }

            for (i = -range; !ok && i <= range; ++i) {
                Tn = htobe64(T + i);

                HMAC_CTX_init(&hmac);
                HMAC_Init(&hmac, otp_key, key_len, otp_digest);
                HMAC_Update(&hmac, (uint8_t *)&Tn, sizeof(Tn));
                HMAC_Final(&hmac, mac, &maclen);

                otp_bytes = mac + (mac[maclen - 1] & 0x0f);
                otp = ((otp_bytes[0] & 0x7f) << 24) | (otp_bytes[1] << 16) |
                    (otp_bytes[2] << 8) | otp_bytes[3];
                otp %= divisor;

                snprintf(secret, sizeof(secret), "%s%0*u", otp_params.pin, tdigits, otp);

                if (vpn_username && !strcmp (vpn_username, user_entry.name)
                    && vpn_secret && !strcmp (vpn_secret, secret)) {
                    ok = 1;
                }
            }
        }
        else if (!strncasecmp("hotp", otp_params.method, 4)) {
            HMAC_CTX hmac;
            const uint8_t *otp_bytes;
            uint32_t otp, divisor = 1;
            int tdigits = totp_digits;
            int i = 0;

            T = hotp_read_counter(otp_params.key);

            for (i = 0; i < tdigits; ++i) {
                divisor *= 10;
            }

            for (i = 0; !ok && i <= hotp_syncwindow; i++) {
                Tn = htobe64(T-i);

                HMAC_CTX_init(&hmac);
                HMAC_Init(&hmac, otp_key, key_len, otp_digest);
                HMAC_Update(&hmac, (uint8_t *)&Tn, sizeof(Tn));
                HMAC_Final(&hmac, mac, &maclen);

                otp_bytes = mac + (mac[maclen - 1] & 0x0f);
                otp = ((otp_bytes[0] & 0x7f) << 24) | (otp_bytes[1] << 16) |
                       (otp_bytes[2] << 8) | otp_bytes[3];
                otp %= divisor;

                snprintf(secret, sizeof(secret), "%s%0*u", otp_params.pin, tdigits, otp);
                if (vpn_username && !strcmp (vpn_username, user_entry.name)
                    && vpn_secret && !strcmp (vpn_secret, secret)) {
                    ok = 1;
                    hotp_set_counter(otp_params.key, T-i-1);
                }
            }
        }
        else if (!strcasecmp("motp", otp_params.method)) {
            char buf[64];
            int n;
            int range = otp_slop / motp_step;

            T = time(NULL) / motp_step;

            for (i = -range; !ok && i <= range; ++i) {
                EVP_MD_CTX ctx;
                EVP_MD_CTX_init(&ctx);
                EVP_DigestInit_ex(&ctx, otp_digest, NULL);
                n = sprintf(buf, "%" PRIu64, T + i);
                EVP_DigestUpdate(&ctx, buf, n);
                EVP_DigestUpdate(&ctx, otp_key, key_len);
                EVP_DigestUpdate(&ctx, otp_params.pin, strlen(otp_params.pin));
                if (otp_params.udid) {
                    int udid_len = strlen(otp_params.udid);
                    EVP_DigestUpdate(&ctx, otp_params.udid, udid_len);
                }
                EVP_DigestFinal_ex(&ctx, mac, &maclen);
                EVP_MD_CTX_cleanup(&ctx);

                snprintf(secret, sizeof(secret),
                         "%02x%02x%02x", mac[0], mac[1], mac[2]);

                if (vpn_username && !strcmp (vpn_username, user_entry.name)
                    && vpn_secret && !strcmp (vpn_secret, secret)) {
                    ok = 1;
                }
            }
        }
        else {
            LOG("OTP-AUTH: unknown OTP method %s\n", otp_params.method);
        }

    done:
        memset(secret, 0, sizeof(secret));

    }

    if (NULL != secrets_file) {
        fclose(secrets_file);
    }

    return ok;
}
Example #27
0
// static
sp<DataSource> DataSource::CreateFromURI(
        const sp<IMediaHTTPService> &httpService,
        const char *uri,
        const KeyedVector<String8, String8> *headers,
        String8 *contentType,
        HTTPBase *httpSource) {
    if (contentType != NULL) {
        *contentType = "";
    }

    bool isWidevine = !strncasecmp("widevine://", uri, 11);

    sp<DataSource> source;
    if (!strncasecmp("file://", uri, 7)) {
        source = new FileSource(uri + 7);
    } else if (!strncasecmp("http://", uri, 7)
            || !strncasecmp("https://", uri, 8)
            || isWidevine) {
        if (httpService == NULL) {
            ALOGE("Invalid http service!");
            return NULL;
        }

        if (httpSource == NULL) {
            sp<IMediaHTTPConnection> conn = httpService->makeHTTPConnection();
            if (conn == NULL) {
                ALOGE("Failed to make http connection from http service!");
                return NULL;
            }
            httpSource = new MediaHTTP(conn);
        }

        String8 tmp;
        if (isWidevine) {
            tmp = String8("http://");
            tmp.append(uri + 11);

            uri = tmp.string();
        }

        String8 cacheConfig;
        bool disconnectAtHighwatermark;
        KeyedVector<String8, String8> nonCacheSpecificHeaders;
        if (headers != NULL) {
            nonCacheSpecificHeaders = *headers;
            NuCachedSource2::RemoveCacheSpecificHeaders(
                    &nonCacheSpecificHeaders,
                    &cacheConfig,
                    &disconnectAtHighwatermark);
        }

        if (httpSource->connect(uri, &nonCacheSpecificHeaders) != OK) {
            ALOGE("Failed to connect http source!");
            return NULL;
        }

        if (!isWidevine) {
            if (contentType != NULL) {
                *contentType = httpSource->getMIMEType();
            }

            source = new NuCachedSource2(
                    httpSource,
                    cacheConfig.isEmpty() ? NULL : cacheConfig.string(),
                    disconnectAtHighwatermark);
        } else {
            // We do not want that prefetching, caching, datasource wrapper
            // in the widevine:// case.
            source = httpSource;
        }
    } else if (!strncasecmp("data:", uri, 5)) {
        source = DataURISource::Create(uri);
    } else {
        // Assume it's a filename.
        source = new FileSource(uri);
    }

    if (source == NULL || source->initCheck() != OK) {
        return NULL;
    }

    return source;
}
Example #28
0
int tcp_http_data_callback(unsigned char *buf, unsigned int len, void *priv)
{
	/*
	 * This callback receives data from HTTP servers.
	 * While doing that, it splits out the data into a
	 * buffer for the HTTP headers, and a buffer for the
	 * HTTP content-data.
	 * Return 1 if data is complete, 0 if more data wanted.
	 */

	http_data_t *item = (http_data_t *) priv;

	if (item->gotheaders) {
		unsigned int len1chunk = 0;
		int i;

		/*
		 * We already have the headers, so just stash away the data
		 */


		while (len > 0) {
			dbgprintf("HDC IN : state=%d, leftinchunk=%d, len=%d\n", item->chunkstate, item->leftinchunk, len);
			switch (item->chunkstate) {
			  case CHUNK_NOTCHUNKED:
				len1chunk = len;
				if ((item->contlen > 0) && (item->contlen >= len)) item->contlen -= len;
				break;

			  case CHUNK_INIT:
				/* We're about to pick up a chunk length */
				item->leftinchunk = 0;
				item->chunkstate = CHUNK_GETLEN;
				len1chunk = 0;
				break;

			  case CHUNK_GETLEN:
				/* We are collecting the length of the chunk */
				i = hexvalue(*buf);
				if (i == -1) {
					item->chunkstate = CHUNK_SKIPLENCR;
				}
				else {
					item->leftinchunk = item->leftinchunk*16 + i;
					buf++; len--;
				}
				len1chunk = 0;
				break;
				
			  case CHUNK_SKIPLENCR:
				/* We've got the length, now skip to the next LF */
				if (*buf == '\n') {
					buf++; len--; 
					item->chunkstate = ((item->leftinchunk > 0) ? CHUNK_DATA : CHUNK_NOMORE);
				}
				else if ((*buf == '\r') || (*buf == ' ')) {
					buf++; len--;
				}
				else {
					errprintf("Yikes - strange data following chunk len. Saw a '%c'\n", *buf);
					buf++; len--;
				}
				len1chunk = 0;
				break;

			  case CHUNK_DATA:
				/* Passing off the data */
				if (len > item->leftinchunk) len1chunk = item->leftinchunk;
				else len1chunk = len;
				item->leftinchunk -= len1chunk;
				if (item->leftinchunk == 0) item->chunkstate = CHUNK_SKIPENDCR;
				break;

			  case CHUNK_SKIPENDCR:
				/* Skip CR/LF after a chunk */
				if (*buf == '\n') {
					buf++; len--; item->chunkstate = CHUNK_DONE;
				}
				else if (*buf == '\r') {
					buf++; len--;
				}
				else {
					errprintf("Yikes - strange data following chunk data. Saw a '%c'\n", *buf);
					buf++; len--;
				}
				len1chunk = 0;
				break;

			  case CHUNK_DONE:
				/* One chunk is done, continue with the next */
				len1chunk = 0;
				item->chunkstate = CHUNK_GETLEN;
				break;

			  case CHUNK_NOMORE:
				/* All chunks done. Skip the rest (trailers) */
				len1chunk = 0;
				len = 0;
			}

			if (len1chunk > 0) {
				switch (item->contentcheck) {
				  case CONTENTCHECK_NONE:
				  case CONTENTCHECK_CONTENTTYPE:
					/* No need to save output - just drop it */
					break;

				  case CONTENTCHECK_REGEX:
				  case CONTENTCHECK_NOREGEX:
					/* Save the full data */
					if ((item->output == NULL) || (item->outlen == 0)) {
						item->output = (unsigned char *)malloc(len1chunk+1);
					}
					else {
						item->output = (unsigned char *)realloc(item->output, item->outlen+len1chunk+1);
					}

					memcpy(item->output+item->outlen, buf, len1chunk);
					item->outlen += len1chunk;
					*(item->output + item->outlen) = '\0'; /* Just in case ... */
					break;

				  case CONTENTCHECK_DIGEST:
					/* Run the data through our digest routine, but discard the raw data */
					if ((item->digestctx == NULL) || (digest_data(item->digestctx, buf, len1chunk) != 0)) {
						errprintf("Failed to hash data for digest\n");
					}
					break;
				}

				buf += len1chunk;
				len -= len1chunk;
				dbgprintf("HDC OUT: state=%d, leftinchunk=%d, len=%d\n", item->chunkstate, item->leftinchunk, len);
			}
		}
	}
	else {
		/*
		 * Havent seen the end of headers yet.
		 */
		unsigned char *p;

		/* First, add this to the header-buffer */
		if (item->headers == NULL) {
			item->headers = (unsigned char *) malloc(len+1);
		}
		else {
			item->headers = (unsigned char *) realloc(item->headers, item->hdrlen+len+1);
		}

		memcpy(item->headers+item->hdrlen, buf, len);
		item->hdrlen += len;
		*(item->headers + item->hdrlen) = '\0';

check_for_endofheaders:
		/* 
		 * Now see if we have the end-of-headers delimiter.
		 * This SHOULD be <cr><lf><cr><lf>, but RFC 2616 says
		 * you SHOULD recognize just plain <lf><lf>.
		 * So try the second form, if the first one is not there.
		 */
		p=strstr(item->headers, "\r\n\r\n");
		if (p) {
			p += 4;
		}
		else {
			p = strstr(item->headers, "\n\n");
			if (p) p += 2;
		}

		if (p) {
			int http1subver, httpstatus;
			unsigned int bytesindata;
			char *p1, *xferencoding;
			int contlen;

			/* We have an end-of-header delimiter, but it could be just a "100 Continue" response */
			sscanf(item->headers, "HTTP/1.%d %d", &http1subver, &httpstatus);
			if (httpstatus == 100) {
				/* 
				 * It's a "100"  continue-status.
				 * Just drop this set of headers, and move on.
				 */
				item->hdrlen -= (p - item->headers);
				if (item->hdrlen > 0) {
					memmove(item->headers, p, item->hdrlen);
					*(item->headers + item->hdrlen) = '\0';
					goto check_for_endofheaders;
				}
				else {
					xfree(item->headers);
					item->headers = NULL;
					item->hdrlen = 0;
					return 0;
				}

				/* Should never go here ... */
			}


			/* We did find the end-of-header delimiter, and it is not a "100" status. */
			item->gotheaders = 1;

			/* p points at the first byte of DATA. So the header ends 1 or 2 bytes before. */
			*(p-1) = '\0';
			if (*(p-2) == '\r') { *(p-2) = '\0'; } /* NULL-terminate the headers. */

			/* See if the transfer uses chunks */
			p1 = item->headers; xferencoding = NULL; contlen = 0;
			do {
				if (strncasecmp(p1, "Transfer-encoding:", 18) == 0) {
					p1 += 18; while (isspace((int)*p1)) p1++;
					xferencoding = p1;
				}
				else if (strncasecmp(p1, "Content-Length:", 15) == 0) {
					p1 += 15; while (isspace((int)*p1)) p1++;
					contlen = atoi(p1);
				}
				else {
					p1 = strchr(p1, '\n'); if (p1) p1++;
				}
			} while (p1 && (xferencoding == NULL));

			if (xferencoding && (strncasecmp(xferencoding, "chunked", 7) == 0)) {
				item->chunkstate = CHUNK_INIT;
			}
			item->contlen = (contlen ? contlen : -1);

			bytesindata = item->hdrlen - (p - item->headers);
			item->hdrlen = strlen(item->headers);
			if (*p) {
				/* 
				 * We received some content data together with the
				 * headers. Save these to the content-data area.
				 */
				tcp_http_data_callback(p, bytesindata, priv);
			}
		}
	}

	if (item->chunkstate == CHUNK_NOTCHUNKED) 
		/* Not chunked - we're done if contlen reaches 0 */
		return (item->contlen == 0);
	else 
		/* Chunked - we're done if we reach state NOMORE*/
		return (item->chunkstate == CHUNK_NOMORE);
}
Example #29
0
HTTPResult
HTTP_get(struct HTTP_ctx *http, const char *url, HTTP_read_callback *cb)
{
  char *host, *path;
  char *p1, *p2;
  char hbuf[256];
  int port = 80;
#ifdef CRYPTO
  int ssl = 0;
#endif
  int hlen, flen = 0;
  int rc, i;
  int len_known;
  HTTPResult ret = HTTPRES_OK;
  struct sockaddr_in sa;
  RTMPSockBuf sb = {0};

  http->status = -1;

  memset(&sa, 0, sizeof(struct sockaddr_in));
  sa.sin_family = AF_INET;

  /* we only handle http here */
  if (strncasecmp(url, "http", 4))
    return HTTPRES_BAD_REQUEST;

  if (url[4] == 's')
    {
#ifdef CRYPTO
      ssl = 1;
      port = 443;
      if (!RTMP_TLS_ctx)
	RTMP_TLS_Init();
#else
      return HTTPRES_BAD_REQUEST;
#endif
    }

  p1 = strchr(url + 4, ':');
  if (!p1 || strncmp(p1, "://", 3))
    return HTTPRES_BAD_REQUEST;

  host = p1 + 3;
  path = strchr(host, '/');
  hlen = path - host;
  strncpy(hbuf, host, hlen);
  hbuf[hlen] = '\0';
  host = hbuf;
  p1 = strrchr(host, ':');
  if (p1)
    {
      *p1++ = '\0';
      port = atoi(p1);
    }

  sa.sin_addr.s_addr = inet_addr(host);
  if (sa.sin_addr.s_addr == INADDR_NONE)
    {
      struct hostent *hp = gethostbyname(host);
      if (!hp || !hp->h_addr)
	return HTTPRES_LOST_CONNECTION;
      sa.sin_addr = *(struct in_addr *)hp->h_addr;
    }
  sa.sin_port = htons(port);
  sb.sb_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  if (sb.sb_socket == -1)
    return HTTPRES_LOST_CONNECTION;
  i =
    sprintf(sb.sb_buf,
	    "GET %s HTTP/1.0\r\nUser-Agent: %s\r\nHost: %s\r\nReferrer: %.*s\r\n",
	    path, AGENT, host, (int)(path - url + 1), url);
  if (http->date[0])
    i += sprintf(sb.sb_buf + i, "If-Modified-Since: %s\r\n", http->date);
  i += sprintf(sb.sb_buf + i, "\r\n");

  if (connect
      (sb.sb_socket, (struct sockaddr *)&sa, sizeof(struct sockaddr)) < 0)
    {
      ret = HTTPRES_LOST_CONNECTION;
      goto leave;
    }
#ifdef CRYPTO
  if (ssl)
    {
#ifdef NO_SSL
      RTMP_Log(RTMP_LOGERROR, "%s, No SSL/TLS support", __FUNCTION__);
      ret = HTTPRES_BAD_REQUEST;
      goto leave;
#else
      TLS_client(RTMP_TLS_ctx, sb.sb_ssl);
      TLS_setfd(sb.sb_ssl, sb.sb_socket);
      if ((i = TLS_connect(sb.sb_ssl)) < 0)
	{
	  RTMP_Log(RTMP_LOGERROR, "%s, TLS_Connect failed", __FUNCTION__);
	  ret = HTTPRES_LOST_CONNECTION;
	  goto leave;
	}
#endif
    }
#endif
  RTMPSockBuf_Send(&sb, sb.sb_buf, i);

  /* set timeout */
#define HTTP_TIMEOUT	5
  {
    SET_RCVTIMEO(tv, HTTP_TIMEOUT);
    if (setsockopt
        (sb.sb_socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv)))
      {
        RTMP_Log(RTMP_LOGERROR, "%s, Setting socket timeout to %ds failed!",
	    __FUNCTION__, HTTP_TIMEOUT);
      }
  }

  sb.sb_size = 0;
  sb.sb_timedout = FALSE;
  if (RTMPSockBuf_Fill(&sb) < 1)
    {
      ret = HTTPRES_LOST_CONNECTION;
      goto leave;
    }
  if (strncmp(sb.sb_buf, "HTTP/1", 6))
    {
      ret = HTTPRES_BAD_REQUEST;
      goto leave;
    }

  p1 = strchr(sb.sb_buf, ' ');
  rc = atoi(p1 + 1);
  http->status = rc;

  if (rc >= 300)
    {
      if (rc == 304)
	{
	  ret = HTTPRES_OK_NOT_MODIFIED;
	  goto leave;
	}
      else if (rc == 404)
	ret = HTTPRES_NOT_FOUND;
      else if (rc >= 500)
	ret = HTTPRES_SERVER_ERROR;
      else if (rc >= 400)
	ret = HTTPRES_BAD_REQUEST;
      else
	ret = HTTPRES_REDIRECTED;
    }

  p1 = memchr(sb.sb_buf, '\n', sb.sb_size);
  if (!p1)
    {
      ret = HTTPRES_BAD_REQUEST;
      goto leave;
    }
  sb.sb_start = p1 + 1;
  sb.sb_size -= sb.sb_start - sb.sb_buf;

  while ((p2 = memchr(sb.sb_start, '\r', sb.sb_size)))
    {
      if (*sb.sb_start == '\r')
	{
	  sb.sb_start += 2;
	  sb.sb_size -= 2;
	  break;
	}
      else
	if (!strncasecmp
	    (sb.sb_start, "Content-Length: ", sizeof("Content-Length: ") - 1))
	{
	  flen = atoi(sb.sb_start + sizeof("Content-Length: ") - 1);
	}
      else
	if (!strncasecmp
	    (sb.sb_start, "Last-Modified: ", sizeof("Last-Modified: ") - 1))
	{
	  *p2 = '\0';
	  strcpy(http->date, sb.sb_start + sizeof("Last-Modified: ") - 1);
	}
      p2 += 2;
      sb.sb_size -= p2 - sb.sb_start;
      sb.sb_start = p2;
      if (sb.sb_size < 1)
	{
	  if (RTMPSockBuf_Fill(&sb) < 1)
	    {
	      ret = HTTPRES_LOST_CONNECTION;
	      goto leave;
	    }
	}
    }

  len_known = flen > 0;
  while ((!len_known || flen > 0) &&
	 (sb.sb_size > 0 || RTMPSockBuf_Fill(&sb) > 0))
    {
      cb(sb.sb_start, 1, sb.sb_size, http->data);
      if (len_known)
	flen -= sb.sb_size;
      http->size += sb.sb_size;
      sb.sb_size = 0;
    }

  if (flen > 0)
    ret = HTTPRES_LOST_CONNECTION;

leave:
  RTMPSockBuf_Close(&sb);
  return ret;
}
Example #30
0
bool8 LoadZip(const char* zipname,
	      int32 *TotalFileSize,
	      int32 *headers, uint8* buffer)
{
    *TotalFileSize = 0;
    *headers = 0;
    
    unzFile file = unzOpen(zipname);
    if(file == NULL)
	return (FALSE);

    // find largest file in zip file (under MAX_ROM_SIZE)
    // or a file with extension .1
    char filename[132];
    int filesize = 0;
    int port = unzGoToFirstFile(file);
    unz_file_info info;
    while(port == UNZ_OK)
    {
	char name[132];
	unzGetCurrentFileInfo(file, &info, name,128, NULL,0, NULL,0);

#if 0
	int calc_size = info.uncompressed_size / 0x2000;
	calc_size *= 0x2000;
	if(!(info.uncompressed_size - calc_size == 512 || info.uncompressed_size == calc_size))
	{
	    port = unzGoToNextFile(file);
	    continue;
	}
#endif

	if(info.uncompressed_size > (CMemory::MAX_ROM_SIZE + 512))
	{
	    port = unzGoToNextFile(file);
	    continue;
	}
	
	if ((int) info.uncompressed_size > filesize)
	{
	    strcpy(filename,name);
	    filesize = info.uncompressed_size;
	}
	int len = strlen(name);
	if(name[len-2] == '.' && name[len-1] == '1')
	{
	    strcpy(filename,name);
	    filesize = info.uncompressed_size;
	    break;
	}
	port = unzGoToNextFile(file);
    }
    if( !(port == UNZ_END_OF_LIST_OF_FILE || port == UNZ_OK) || filesize == 0)
    {
	assert( unzClose(file) == UNZ_OK );
	return (FALSE);
    }

    // Find extension
    char tmp[2];
    tmp[0] = tmp[1] = 0;
    char *ext = strrchr(filename,'.');
    if(ext) ext++;
    else ext = tmp;
    
    uint8 *ptr = buffer;
    bool8 more = FALSE;

    unzLocateFile(file,filename,1);
    unzGetCurrentFileInfo(file, &info, filename,128, NULL,0, NULL,0);
    
    if( unzOpenCurrentFile(file) != UNZ_OK )
    {
	unzClose(file);
	return (FALSE);
    }

    do
    {
	assert(info.uncompressed_size <= CMemory::MAX_ROM_SIZE + 512);
	int FileSize = info.uncompressed_size;
	
	int calc_size = FileSize / 0x2000;
	calc_size *= 0x2000;
	
	int l = unzReadCurrentFile(file,ptr,FileSize);
	if(unzCloseCurrentFile(file) == UNZ_CRCERROR)
	{
	    unzClose(file);
	    return (FALSE);
	}
	
	if(l <= 0 || l != FileSize)
	{
	    unzClose(file);
	    switch(l)
	    {
		case UNZ_ERRNO:
		    break;
		case UNZ_EOF:
		    break;
		case UNZ_PARAMERROR:
		    break;
		case UNZ_BADZIPFILE:
		    break;
		case UNZ_INTERNALERROR:
		    break;
		case UNZ_CRCERROR:
		    break;
	    }
	    return (FALSE);
	}

	if ((FileSize - calc_size == 512 && !Settings.ForceNoHeader) ||
	    Settings.ForceHeader)
	{
	    memmove (ptr, ptr + 512, calc_size);
	    (*headers)++;
	    FileSize -= 512;
	}
	ptr += FileSize;
	(*TotalFileSize) += FileSize;

	int len;
	if (ptr - Memory.ROM < CMemory::MAX_ROM_SIZE + 0x200 &&
	    (isdigit (ext [0]) && ext [1] == 0 && ext [0] < '9'))
	{
	    more = TRUE;
	    ext [0]++;
	}
	else if (ptr - Memory.ROM < CMemory::MAX_ROM_SIZE + 0x200 &&
		 (((len = strlen (filename)) == 7 || len == 8) &&
		  strncasecmp (filename, "sf", 2) == 0 &&
		  isdigit (filename [2]) && isdigit (filename [3]) && isdigit (filename [4]) &&
		  isdigit (filename [5]) && isalpha (filename [len - 1])))
	{
	    more = TRUE;
	    filename [len - 1]++;
	}
	else
	    more = FALSE;
	
	if(more)
	{
	    if( unzLocateFile(file,filename,1) != UNZ_OK ||
		unzGetCurrentFileInfo(file, &info, filename,128, NULL,0, NULL,0) != UNZ_OK ||
		unzOpenCurrentFile(file) != UNZ_OK)
		break;
	}
	
    } while(more);
    
    unzClose(file);
    return (TRUE);
}