Пример #1
0
Файл: net.c Проект: avagin/vzctl
char *find_ip(list_head_t *ip_h, const char *ipaddr)
{
	ip_param *ip;
	char *slash, *ip_slash, *ip_only;
	int len;

	if (list_empty(ip_h))
		return NULL;

	slash = strchr(ipaddr, '/');
	if (slash) {
		len = slash - ipaddr + 1;
		ip_slash = strndupa(ipaddr, len);
		ip_only = strndupa(ipaddr, len - 1);
	}
	else {
		ip_only = NULL;
		len = asprintf(&ip_slash, "%s/", ipaddr);
	}

	list_for_each(ip, ip_h, list) {
		/* Match complete IP or IP/mask string */
		if (!strcmp(ip->val, ipaddr))
			return ip->val;
		/* Match only IP */
		if ((ip_only != NULL) && (!strcmp(ip->val, ip_only)))
			return ip->val;
		/* Match IP/ (same IP, different mask) */
		if (!strncmp(ip->val, ip_slash, len))
			return ip->val;
	}
	return NULL;
}
Пример #2
0
int tc_cmd_env_set(const char *name,  uint32_t namelen,
                   const char *value, uint32_t valuelen)
{
	/* Validate the name */
	uint32_t i = 0;
	for (i = 0; i < namelen; i++) {
		if (!tc_cmd_env_ischar(name[i]))
			break;
	}
	if (i < namelen || namelen == 0) {
		tc_log(TC_LOG_ERR, "Invalid name for variable \"%s\"",
		       strndupa(name, namelen));
		return -1;
	}

	/* Replace an existing value if found */
	tc_cmd_env_t *e = tc_cmd_env_find(name, namelen);
	if (e) {
		free((void *)e->value);
		e->value = strndup(value, valuelen);
		tc_log(TC_LOG_INFO, "Variable %s = \"%s\" (replaced value)",
		       strndupa(name, namelen), strndupa(value, valuelen));
		return 0;
	}

	/* Add the new value if not found */
	e = (tc_cmd_env_t *)malloc(sizeof(tc_cmd_env_t));
	e->name = strndup(name, namelen);
	e->value = strndup(value, valuelen);
	e->next = tc_cmd_env;
	tc_cmd_env = e;
	tc_log(TC_LOG_INFO, "Variable %s = \"%s\" (new value)",
	       strndupa(name, namelen), strndupa(value, valuelen));
	return 0;
}
Пример #3
0
int show_man_page(const char *desc, bool null_stdio) {
        const char *args[4] = { "man", NULL, NULL, NULL };
        char *e = NULL;
        pid_t pid;
        size_t k;
        int r;
        siginfo_t status;

        k = strlen(desc);

        if (desc[k-1] == ')')
                e = strrchr(desc, '(');

        if (e) {
                char *page = NULL, *section = NULL;

                page = strndupa(desc, e - desc);
                section = strndupa(e + 1, desc + k - e - 2);

                args[1] = section;
                args[2] = page;
        } else
                args[1] = desc;

        pid = fork();
        if (pid < 0)
                return log_error_errno(errno, "Failed to fork: %m");

        if (pid == 0) {
                /* Child */

                (void) reset_all_signal_handlers();
                (void) reset_signal_mask();

                if (null_stdio) {
                        r = make_null_stdio();
                        if (r < 0) {
                                log_error_errno(r, "Failed to kill stdio: %m");
                                _exit(EXIT_FAILURE);
                        }
                }

                execvp(args[0], (char**) args);
                log_error_errno(errno, "Failed to execute man: %m");
                _exit(EXIT_FAILURE);
        }

        r = wait_for_terminate(pid, &status);
        if (r < 0)
                return r;

        log_debug("Exit code %i status %i", status.si_code, status.si_status);
        return status.si_status;
}
static void mqtt_callback(char* topic, byte* payload, int len) {
  debug.log("Message arrived [", topic, ']');
  for (int i = 0; i < len; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();

  if (strcmp(topic, mqtt_upgrade_topic) == 0) {
    if (strlen(VERSION) != len || strncmp((const char*)payload, VERSION, len) != 0) {
      check_upgrade();
    } else {
      debug.log("Asking to upgrade to our version, not doing anything");
    }
    // Only after we got an upgrade chance we should go to sleep
    debug.log("MQTT upgrade notification received, sleep lock released");
    sleep_postpone(50);
    return;
  }

  char *data = strndupa((char*)payload, len);
  for (int i = 0; i < NUM_MQTT_SUBS; i++) {
    if (strcmp(subscription[i].topic, topic) == 0) {
      subscription[i].callback(data);
      return;
    }
  }
}
Пример #5
0
int main(int argc, char **argv) {
        static struct gengetopt_args_info args_info;
        assert(cmdline_parser(argc, argv, &args_info) == 0);
        char* pattern = args_info.pattern_orig;
        char* text = read_text(args_info.text_arg);
        uint32_t n = strlen(text);
        uint32_t m = strlen(pattern);
        /* occ[] stores if a position is an occurrence */
        uint32_t* occ = calloc(n, sizeof(*occ));
        assert(occ != NULL);

        /* Initialize random number generator */
        gsl_rng *rng = gsl_rng_alloc(gsl_rng_mt19937);
        uint32_t num_rounds = (size_t) args_info.rounds_arg;
        for (size_t i = 0; i < num_rounds; i++) {
                uint32_t mod = random_prime(rng);
                for (size_t j = 0; j < m; j++)
                        for (size_t c = 0; c < 4; c++)
                                corrections[c] = (j == 0) ? c : (corrections[c] << 2) % mod;
                uint32_t pattern_h = init_h(pattern, m, mod);
                uint32_t pos = m;
                for (uint32_t text_h = init_h(text, m, mod); pos < n;
                     text_h = next_h(text_h, text[pos - m], text[pos], mod), pos++)
                        if (pattern_h == text_h)
                                occ[pos - m]++;
        }
        for (uint32_t pos = 0; pos < n; pos++)
                if (occ[pos] >= num_rounds) {
                        char* x = strndupa(text + pos, m);
                        printf("Occurrence %s at position %d\n", x, pos);
                }
        free(occ);
}
Пример #6
0
/* on call, propagate it to the dbus service */
static void api_dbus_client_call(struct api_dbus *api, struct afb_req req, struct afb_context *context, const char *verb, size_t lenverb)
{
	size_t size;
	int rc;
	char *method = strndupa(verb, lenverb);
	struct dbus_memo *memo;

	/* create the recording data */
	memo = api_dbus_client_make_memo(req, context);
	if (memo == NULL) {
		afb_req_fail(req, "error", "out of memory");
		return;
	}

	/* makes the call */
	rc = sd_bus_call_method_async(api->sdbus, NULL,
		api->name, api->path, api->name, method,
		api_dbus_client_on_reply, memo,
		"ssu",
			afb_req_raw(req, &size),
			ctxClientGetUuid(context->session),
			(uint32_t)context->flags);

	/* if there was an error report it directly */
	if (rc < 0) {
		errno = -rc;
		afb_req_fail(req, "error", "dbus error");
		api_dbus_client_free_memo(memo);
	}
}
Пример #7
0
int
sol_str_slice_to_int(const struct sol_str_slice s, int *value)
{
    const char *tmp;
    char *endptr = NULL;
    long v;

    if (!s.len)
        return -EINVAL;

    tmp = strndupa(s.data, s.len);
    if (!tmp)
        return -errno;

    errno = 0;
    v = strtol(tmp, &endptr, 0);

    if (errno)
        return -errno;

    if (*endptr != 0)
        return -EINVAL;

    if ((long)(int)v != v)
        return -ERANGE;

    *value = v;
    return 0;
}
Пример #8
0
/*
 * consume 1 line from req->parse_start, and store the header field if necessary
 */
static int parse_header_line(struct parser *req)
{
        char *str = req->parse_start;
        static regex_t regex;
        /* store the match. [0] is the whole string.
         * [1] is Host|User-agent... [2] is the corresponding value [3] is
         * useless*/
        static regmatch_t match[4];
        regcomp(&regex, "^([a-zA-Z_-]+): (([^\r]|\r[^\n])+)\r\n", REG_EXTENDED);

        int ret = regexec(&regex, str, 4, match, 0);
        if (ret)
                return -1;

        /* store this  header */
        int i = req->headers_num;
        if (i >= MAX_HEADER)  /* this should not happen in most cases */
                return -1;
        int len = match[1].rm_eo-match[1].rm_so;
        syslog(LOG_INFO, "got %s", strndupa(str, match[1].rm_eo-match[1].rm_so));
        memcpy(req->headers[i].field_name, (str + match[1].rm_so), len);
        req->headers[i].field_name[len] = '\0';
        req->headers[i].value = dup_second_match(str, match);
        req->headers_num++;
        /* finish storing header */

        req->parse_start += match[0].rm_eo;  /* update where next parse should start */

        regfree(&regex);
        return 0;
}
Пример #9
0
/* query a subobject path starting at fsid returning the data in the
   tail of the path */
static int query_subobj_path(int fsid, int subobj, const char *path, int *len, 
		       void *ret[], const int max)
{
	int i=0;
	int idx = 0;
	const char *tok, *end;
	if (max <=0) return 0;
	
	end = strchr(path,'/');
	tok = (end) ? strndupa(path,end-path) : path;

	ret[idx] = query_part(fsid, subobj, tok, &len[idx]);
	if (!ret[idx]) return idx;
	if (end) {
		struct mfs_obj_attr *objattr = ret[idx];
		int count = (len[idx]-4)/sizeof(*objattr);
		for (i=0;i<count;i++) {
			int n;
			fsid = ntohl(objattr->fsid);
			subobj = ntohl(objattr->subobj);
			n = query_subobj_path( 
				fsid, subobj, end+1, len+idx,
				ret+idx, max-idx );
			idx += n;
			objattr++;
		}
	} else
		idx++;
	return idx;
}
Пример #10
0
static int
sync_dir_of(const char *new_path)
{
    /* Sync destination dir, so dir information is sure to be stored */
    char *tmp, *dir_name;
    int dir_fd;

    tmp = strndupa(new_path, PATH_MAX);
    dir_name = dirname(tmp);
    dir_fd = open(dir_name, O_RDONLY | O_CLOEXEC | O_DIRECTORY);
    if (dir_fd < 0) {
        SOL_WRN(
            "Could not open destination directory to ensure file information is stored: %s",
            sol_util_strerrora(errno));
        return -errno;
    }

    errno = 0;
    if (fsync(dir_fd) < 0) {
        SOL_WRN("Could not open ensure file information is stored: %s",
            sol_util_strerrora(errno));
    }

    close(dir_fd);

    return -errno;
}
Пример #11
0
/**
 *  Create a new buffer with the replaced environment values.
 * 
 *  \param buf  Buffer with values to be replaced.
 *  \param len  Length of original buffer and output of final.
 *  \return The allocated buffer that should be freed with free.
 */
static char *tc_cmd_env_subs(const char *buf, uint32_t *len)
{
	uint8_t state = 0;
	uint32_t l = 0;
	uint32_t alloc = 0;
	char *result = NULL;
	uint32_t i = 0;
	bool finished = false;
	while (true) {
		if (l == alloc) {
			alloc = alloc ? (alloc << 1) : 16;
			result = (char *)realloc(result, alloc);
		}
		if (i == *len) {
			finished = true;
			break;
		}
		if (buf[i] == '$') {
			i++;
			if (i == *len)  {
				tc_log(TC_LOG_ERR, "Syntax error: $ at end of command");
				break;
			}
			if (buf[i] != '$') {
				uint32_t endi;
				for (endi = i; endi < *len; endi++)
					if (!tc_cmd_env_ischar(buf[endi]))
						break;
				if (endi == i) { 
					tc_log(TC_LOG_ERR, "Syntax error: $ not followed by variable name");
					break;
				}
				tc_cmd_env_t *env = tc_cmd_env_find(buf + i, endi - i);
				if (!env) {
					tc_log(TC_LOG_ERR, "Syntax error: Variable \"%s\" not found",
					       strndupa(buf + i, endi - i));
					break;
				}
				uint32_t newl = l + strlen(env->value);
				while (alloc < newl) {
					alloc = alloc << 1;
					result = (char *)realloc(result, alloc);
				}
				memcpy(result + l, env->value, strlen(env->value));
				l = newl;
				i = endi;
				continue;
			}
		}
		result[l++] = buf[i++];
	}
	*len = l;
	if (!finished) {
		if (result) {
			free(result);
			result = NULL;
		}
	}
	return result;
}
int socket_address_parse(SocketAddress *a, const char *s) {
        char *e, *n;
        unsigned u;
        int r;

        assert(a);
        assert(s);

        zero(*a);
        a->type = SOCK_STREAM;

        if (*s == '[') {
                /* IPv6 in [x:.....:z]:p notation */

                if (!socket_ipv6_is_supported()) {
                        log_warning("Binding to IPv6 address not available since kernel does not support IPv6.");
                        return -EAFNOSUPPORT;
                }

                e = strchr(s+1, ']');
                if (!e)
                        return -EINVAL;

                n = strndupa(s+1, e-s-1);

                errno = 0;
                if (inet_pton(AF_INET6, n, &a->sockaddr.in6.sin6_addr) <= 0)
                        return errno > 0 ? -errno : -EINVAL;

                e++;
                if (*e != ':')
                        return -EINVAL;

                e++;
                r = safe_atou(e, &u);
                if (r < 0)
                        return r;

                if (u <= 0 || u > 0xFFFF)
                        return -EINVAL;

                a->sockaddr.in6.sin6_family = AF_INET6;
                a->sockaddr.in6.sin6_port = htons((uint16_t) u);
                a->size = sizeof(struct sockaddr_in6);

        } else if (*s == '/') {
                /* AF_UNIX socket */

                size_t l;

                l = strlen(s);
                if (l >= sizeof(a->sockaddr.un.sun_path))
                        return -EINVAL;

                a->sockaddr.un.sun_family = AF_UNIX;
                memcpy(a->sockaddr.un.sun_path, s, l);
                a->size = offsetof(struct sockaddr_un, sun_path) + l + 1;

        } else if (*s == '@') {
Пример #13
0
/* Returns 0 on success and 1 on error */
static int extract_timestamp(const char *b, au_event_t *e)
{
	char *ptr, *tmp;
	int rc = 1;

        e->host = NULL;
	if (*b == 'n')
		tmp = strndupa(b, 340);
	else
		tmp = strndupa(b, 80);
	ptr = audit_strsplit(tmp);
	if (ptr) {
		// Optionally grab the node - may or may not be included
		if (*ptr == 'n') {
			e->host = strdup(ptr+5);
			(void)audit_strsplit(NULL);// Bump along to next one
		}
		// at this point we have type=
		ptr = audit_strsplit(NULL);
		if (ptr) {
			if (*(ptr+9) == '(')
				ptr+=9;
			else
				ptr = strchr(ptr, '(');
			if (ptr) {
				// now we should be pointed at the timestamp
				char *eptr;
				ptr++;
				eptr = strchr(ptr, ')');
				if (eptr)
					*eptr = 0;

				if (str2event(ptr, e) == 0)
					rc = 0;
			}
			// else we have a bad line
		}
		// else we have a bad line
	}
	if (rc)
		free((void *)e->host);

	// else we have a bad line
	return rc;
}
Пример #14
0
int main(int argc, char **argv)
{
	int rc = cib_ok;
	int timeout = 0;
	char *client_epoch = getenv("QUERY_STRING");
	if (client_epoch && client_epoch[0] == '\0')
		client_epoch = NULL;
	if (client_epoch) {
		char *amp = strchrnul(client_epoch, '&');
		if (amp - client_epoch < MAX_EPOCH_LENGTH) {
			/*
			 * Make a copy of the query string, but without any
			 * possible ampersand and subsequent parameters.  This
			 * can be strcmp'd easily later, but allows adding
			 * params to the query string to force the browser not
			 * to cache these requests.
			 */
			client_epoch = strndupa(client_epoch, amp - client_epoch);
		}
	}

	origin = getenv("HTTP_ORIGIN");

	/* Final arg appeared circa pcmk 1.1.8 */
	crm_log_init(NULL, LOG_CRIT, FALSE, FALSE, argc, argv, TRUE);

	cib = cib_new();

	rc = cib_connect();
	if (rc != cib_ok && client_epoch == NULL) {
		/* Client had no epoch, wait to connect */
		do {
			sleep(1);
			rc = cib_connect();
		} while (rc == cib_connection && ++timeout < CONNECT_TIMEOUT);
	}

	if (rc == cib_ok) {
		get_new_epoch();
		if (client_epoch != NULL && strcmp(client_epoch, new_epoch) == 0) {
			/* Wait a while to see if something changes */
			mainloop = g_main_loop_new(NULL, FALSE);
			mainloop_add_signal(SIGTERM, mon_shutdown);
			mainloop_add_signal(SIGINT, mon_shutdown);
			g_timeout_add(CONNECT_TIMEOUT * 1000, mon_timer_popped, NULL);
			g_main_loop_run(mainloop);
			cleanup();
			g_main_loop_unref(mainloop);
			mainloop = NULL;
		}
	}

	cleanup();
	finish();
	return 0; /* never reached */
}
Пример #15
0
/*
 * This function will look at the line and pick out pieces of it.
 */
static int extract_timestamp(const char *b, event *e)
{
	char *ptr, *tmp, *tnode, *ttype;

	e->node = NULL;
	tmp = strndupa(b, 120);
	ptr = strtok(tmp, " ");
	if (ptr) {
		// Check to see if this is the node info
		if (*ptr == 'n') {
			tnode = ptr+5;
			ptr = strtok(NULL, " ");
		} else
			tnode = NULL;

		// at this point we have type=
		ttype = ptr+5;

		// Now should be pointing to msg=
		ptr = strtok(NULL, " ");
		if (ptr) {
			if (*(ptr+9) == '(')
				ptr+=9;
			else
				ptr = strchr(ptr, '(');
			if (ptr) {
			// now we should be pointed at the timestamp
				char *eptr;
				ptr++;
				eptr = strchr(ptr, ')');
				if (eptr)
					*eptr = 0;
				if (str2event(ptr, e)) {
					fprintf(stderr,
					  "Error extracting time stamp (%s)\n",
						ptr);
					return 0;
				} else if ((start_time && e->sec < start_time)
					|| (end_time && e->sec > end_time))
					return 0;
				else {
					if (tnode)
						e->node = strdup(tnode);
					e->type = audit_name_to_msg_type(ttype);
				}
				return 1;
			}
			// else we have a bad line
		}
		// else we have a bad line
	}
	// else we have a bad line
	return 0;
}
Пример #16
0
static int field_set_test(Set *fields, const char *name, size_t n) {
        char *s = NULL;

        if (!fields)
                return 1;

        s = strndupa(name, n);
        if (!s)
                return log_oom();

        return set_get(fields, s) ? 1 : 0;
}
Пример #17
0
static void test_unbase32hexmem_one(const char *hex, bool padding, int retval, const char *ans) {
        _cleanup_free_ void *mem = NULL;
        size_t len;

        assert_se(unbase32hexmem(hex, (size_t) -1, padding, &mem, &len) == retval);
        if (retval == 0) {
                char *str;

                str = strndupa(mem, len);
                assert_se(streq(str, ans));
        }
}
Пример #18
0
int test_and_mkdir(const char *path) {
    // first, find parent path;
    const char *ptr = path + strlen(path);
    while (*ptr != '/' && ptr > path) {
        ptr--;
    }
    char *parent = strndupa(path, ptr - path);  // no need to free manually
    assert(parent != NULL);
    dmd_log(LOG_DEBUG, "in function %s, parent path is %s\n",
            __func__, parent);
    dmd_log(LOG_DEBUG, "in function %s, path is %s\n",
            __func__, path);

    if (access(parent, F_OK) == 0) {  // parent exist, just mkdir
        if (access(path, F_OK) == 0) {  // path exist, just return
            dmd_log(LOG_DEBUG, "in function %s, dir %s existed already\n",
                    __func__, path);
            return 0;
        } else {  // else just mkdir path;
            if (mkdir(path, 0755) == -1) {
                dmd_log(LOG_ERR, "in function %s, mkdir %s error:%s\n",
                        __func__, path, strerror(errno));
                return -1;
            } else {
                dmd_log(LOG_DEBUG, "in function %s, mkdir %s succeed\n",
                        __func__, path);
            }
        }

    } else {  // parent doesn't exist, recursively call test_and_mkdir();
        // first mkdir parent;
        int ret = test_and_mkdir(parent);
        if (ret == -1) {
            return ret;
        }

        // then mkdir path;
        if (mkdir(path, 0755) == -1) {
            dmd_log(LOG_ERR, "in function %s, mkdir %s error:%s\n",
                    __func__, path, strerror(errno));
            return -1;
        } else {
            dmd_log(LOG_DEBUG, "in function %s, mkdir2 %s succeed\n",
                    __func__, path);
        }
    }

    return 0;
}
Пример #19
0
int mkdir_p(const char *path, int len, mode_t mode)
{
	char *start, *end;

	start = strndupa(path, len);
	end = start + len;

	/*
	 * scan backwards, replacing '/' with '\0' while the component doesn't
	 * exist
	 */
	for (;;) {
		int r = is_dir(start);
		if (r > 0) {
			end += strlen(end);

			if (end == start + len)
				return 0;

			/* end != start, since it would be caught on the first
			 * iteration */
			*end = '/';
			break;
		} else if (r == 0)
			return -ENOTDIR;

		if (end == start)
			break;

		*end = '\0';

		/* Find the next component, backwards, discarding extra '/'*/
		while (end > start && *end != '/')
			end--;

		while (end > start && *(end - 1) == '/')
			end--;
	}

	for (; end < start + len;) {
		if (mkdir(start, mode) < 0 && errno != EEXIST)
			return -errno;

		end += strlen(end);
		*end = '/';
	}

	return 0;
}
Пример #20
0
Файл: net.c Проект: avagin/vzctl
static int ip_ctl(vps_handler *h, envid_t veid, int op, char *str)
{
	const char *ip, *mask;

	mask = strchr(str, '/');
	if (mask) {
		ip = strndupa(str, mask - str);
		mask++;
	}
	else {
		ip = str;
	}

	return h->ip_ctl(h, veid, op, ip);
}
Пример #21
0
int mkdir_parents_internal(const char *prefix, const char *path, mode_t mode, mkdir_func_t _mkdir) {
        const char *p, *e;
        int r;

        assert(path);
        assert(_mkdir != mkdir);

        if (prefix && !path_startswith(path, prefix))
                return -ENOTDIR;

        /* return immediately if directory exists */
        e = strrchr(path, '/');
        if (!e)
                return -EINVAL;

        if (e == path)
                return 0;

        p = strndupa(path, e - path);
        r = is_dir(p, true);
        if (r > 0)
                return 0;
        if (r == 0)
                return -ENOTDIR;

        /* create every parent directory in the path, except the last component */
        p = path + strspn(path, "/");
        for (;;) {
                char t[strlen(path) + 1];

                e = p + strcspn(p, "/");
                p = e + strspn(e, "/");

                /* Is this the last component? If so, then we're done */
                if (*p == 0)
                        return 0;

                memcpy(t, path, e - path);
                t[e-path] = 0;

                if (prefix && path_startswith(prefix, t))
                        continue;

                r = _mkdir(t, mode);
                if (r < 0 && r != -EEXIST)
                        return r;
        }
}
Пример #22
0
int parse_percent_unbounded(const char *p) {
        const char *pc, *n;
        unsigned v;
        int r;

        pc = endswith(p, "%");
        if (!pc)
                return -EINVAL;

        n = strndupa(p, pc - p);
        r = safe_atou(n, &v);
        if (r < 0)
                return r;

        return (int) v;
}
Пример #23
0
SOL_API unsigned long int
sol_util_strtoul_n(const char *nptr, char **endptr, ssize_t len, int base)
{
    char *tmpbuf, *tmpbuf_endptr;
    unsigned long int r;

    if (len < 0)
        len = (ssize_t)strlen(nptr);

    tmpbuf = strndupa(nptr, len);
    errno = 0;
    r = strtoul(tmpbuf, &tmpbuf_endptr, base);

    if (endptr)
        *endptr = (char *)nptr + (tmpbuf_endptr - tmpbuf);
    return r;
}
Пример #24
0
static void test_unhexmem_one(const char *s, size_t l, int retval) {
        _cleanup_free_ char *hex = NULL;
        _cleanup_free_ void *mem = NULL;
        size_t len;

        assert_se(unhexmem(s, l, &mem, &len) == retval);
        if (retval == 0) {
                char *answer;

                if (l == (size_t) -1)
                        l = strlen(s);

                assert_se(hex = hexmem(mem, len));
                answer = strndupa(strempty(s), l);
                assert_se(streq(delete_chars(answer, WHITESPACE), hex));
        }
}
Пример #25
0
static int resolve_remote(Connection *c) {

        static const struct addrinfo hints = {
                .ai_family = AF_UNSPEC,
                .ai_socktype = SOCK_STREAM,
                .ai_flags = AI_ADDRCONFIG
        };

        union sockaddr_union sa = {};
        const char *node, *service;
        int r;

        if (IN_SET(arg_remote_host[0], '/', '@')) {
                int salen;

                salen = sockaddr_un_set_path(&sa.un, arg_remote_host);
                if (salen < 0) {
                        log_error_errno(salen, "Specified address doesn't fit in an AF_UNIX address, refusing: %m");
                        goto fail;
                }

                return connection_start(c, &sa.sa, salen);
        }

        service = strrchr(arg_remote_host, ':');
        if (service) {
                node = strndupa(arg_remote_host, service - arg_remote_host);
                service++;
        } else {
                node = arg_remote_host;
                service = "80";
        }

        log_debug("Looking up address info for %s:%s", node, service);
        r = sd_resolve_getaddrinfo(c->context->resolve, &c->resolve_query, node, service, &hints, resolve_cb, c);
        if (r < 0) {
                log_error_errno(r, "Failed to resolve remote host: %m");
                goto fail;
        }

        return 0;

fail:
        connection_free(c);
        return 0; /* ignore errors, continue serving */
}
Пример #26
0
/**
 *  Load a file to add new commands 
 *
 *  \param path   Path of the file with the new commands.
 *  \retval -1 on error (with a log entry).
 *  \retval 1 on file not possible to be read.
 *  \retval 0 on success.
 */
static int tc_cmd_load(const char *path)
{
	/* Try to open the file */
	FILE *f = fopen(path, "rt");
	if (!f) {
		tc_log(TC_LOG_WARN, "Script file \"%s\" not present",
		       path);
		return 1;
	}
	tc_log(TC_LOG_INFO, "Executing script file \"%s\"", path);

	/* Try to read a line until it finishes */
	int result = 0;
	while (true) {
		/* Get a new line without carry return */
		char buf[256];
		char *r = fgets(buf, sizeof(buf), f);
		if (!r)
			break;
		int buf_len = strlen(buf);
		if (!buf_len)
			continue;
		if (buf[buf_len-1] == '\n') {
			buf[--buf_len] = 0;
			if (!buf_len)
				continue;
		}

		/* Execute the commands */
		tc_log(TC_LOG_INFO, "Command \"%s\"", strndupa(buf, buf_len));
		int nr = tc_cmd(buf, buf_len);
		if (nr) {
			if (nr < 0)
				result = -1;
			break;
		}
	}

	/* Close the file */
	fclose(f);

	/* Return the result */
	return result;
}
Пример #27
0
bool decode_primitive_type(const char *parameter, void **value, ffi_type **type)
{
    const char *prefix;

    prefix  = NULL;
    *value  = NULL;
    *type   = NULL;

    // If a colon exists, then everything before it is a type
    if (strchr(parameter, ':')) {
        // Extract the two components.
        prefix    = strndupa(parameter, strchr(parameter, ':') - parameter);
        parameter = strchr(parameter, ':') + 1;
    } else {
        intmax_t n;
        char *string;

        // No type was specified, so there are only two possibilities,
        // If this is a legal number, then it's an int. Otherwise, this is a
        // string.
        if (check_parse_long(parameter, &n)) {
            *type   = &ffi_type_sint;
            *value  = malloc(ffi_type_sint.size);

            memcpy(*value, &n, ffi_type_sint.size);
            return true;
        }

        // This must be a string.
        *type   = &ffi_type_pointer;
        *value  = malloc(ffi_type_pointer.size);
        string  = strdup(parameter);

        memcpy(*value, &string, ffi_type_pointer.size);
        return true;
    }

    if (decode_type_prefix(prefix, parameter, type, value, NULL) != true) {
        builtin_warning("parameter decoding failed");
        return false;
    }

    return true;
}
Пример #28
0
/* create a directory */
int create_directory_at(int dirfd, const char *directory, mode_t mode, int mkparents)
{
	int rc;
	size_t len, l;
	char *copy;
	const char *iter;

	rc = mkdirat(dirfd, directory, mode);
	if (!rc || errno != ENOENT)
		return rc;

	/* check parent of dest */
	iter = strrchr(directory, '/');
	len = iter ? (size_t)(iter - directory) : 0;
	if (!len)
		return rc;
	copy = strndupa(directory, len);

	/* backward loop */
	l = len;
	rc = mkdirat(dirfd, copy, mode);
	while(rc) {
		if (errno != ENOENT)
			return rc;
		while (l && copy[l] != '/')
			l--;
		if (l == 0)
			return rc;
		copy[l] = 0;
		rc = mkdirat(dirfd, copy, mode);
	}
	/* forward loop */
	while(l < len) {
		copy[l] = '/';
		while (copy[++l]);
		rc = mkdirat(dirfd, copy, mode);
		if (rc)
			return rc;
	}

	/* finalize */
	return mkdirat(dirfd, directory, mode);
}
Пример #29
0
static void
esql_postgresql_setup(Esql *e, const char *addr, const char *user, const char *passwd)
{
   const char *port;
   char buf[4096];

   const char *db;

   if (e->backend.conn_str && (!addr) && (!user) && (!passwd)) return; /* reconnect attempt */
   db = e->database ? e->database : user;

   port = strchr(addr, ':');
   if (port)
     e->backend.conn_str_len = snprintf(buf, sizeof(buf), "host=%s port=%s dbname=%s user=%s password=%s connect_timeout=5",
                                                          strndupa(addr, port - addr), port + 1, db, user, passwd);
   else
     e->backend.conn_str_len = snprintf(buf, sizeof(buf), "host=%s dbname=%s user=%s password=%s connect_timeout=5",
                                                          addr, db, user, passwd);
   e->backend.conn_str = strdup(buf);
}
Пример #30
0
static int uid_from_file_name(const char *filename, uid_t *uid) {
        const char *p, *e, *u;

        p = startswith(filename, "core.");
        if (!p)
                return -EINVAL;

        /* Skip the comm field */
        p = strchr(p, '.');
        if (!p)
                return -EINVAL;
        p++;

        /* Find end up UID */
        e = strchr(p, '.');
        if (!e)
                return -EINVAL;

        u = strndupa(p, e-p);
        return parse_uid(u, uid);
}