Esempio n. 1
0
static int
rdata_eui48_to_string(buffer_type *output, rdata_atom_type rdata,
	rr_type* ATTR_UNUSED(rr))
{
	uint8_t* data = rdata_atom_data(rdata);
	uint8_t a1 = data[0];
	uint8_t a2 = data[1];
	uint8_t a3 = data[2];
	uint8_t a4 = data[3];
	uint8_t a5 = data[4];
	uint8_t a6 = data[5];

	buffer_printf(output, "%.2x-%.2x-%.2x-%.2x-%.2x-%.2x",
		a1, a2, a3, a4, a5, a6);
	return 1;
}
Esempio n. 2
0
int advertise_pool_decision_to_catalog(const char *catalog_host, int catalog_port, const char *pool_name, pid_t pid, time_t start_time, const char *decision, int workers_requested)
{
	char address[DATAGRAM_ADDRESS_MAX];
	char owner[USERNAME_MAX];
	buffer_t B;
	const char *text;
	size_t text_size;

	static time_t last_update_time = 0;

	if(time(0) - last_update_time < WORK_QUEUE_CATALOG_POOL_UPDATE_INTERVAL) return 1;

	if(!outgoing_datagram) {
		outgoing_datagram = datagram_create(0);
		if(!outgoing_datagram) {
			fprintf(stderr, "Couldn't create outgoing udp port, thus work queue master info won't be sent to the catalog server!\n");
			return 0;
		}
	}

	if(!username_get(owner)) {
		strcpy(owner,"unknown");
	}

	// port = MAX_TCP_PORT + process id, this is for the catalog server to
	// distinguish the worker pools from the same host. See make_hash_key()
	// function in catalog_server.c
	INT64_T port = 65535 + pid; 

	buffer_init(&B);
	buffer_abortonfailure(&B, 1);
	buffer_printf(&B, "type wq_pool\npool_name %s\nport %" PRId64 "\nstarttime %llu\ndecision %s\nworkers_requested %d\nowner %s\nlifetime %d", pool_name, port, (unsigned long long) start_time, decision, workers_requested, owner, WORK_QUEUE_CATALOG_POOL_AD_LIFETIME);

	text = buffer_tostring(&B, &text_size);
	debug(D_WQ, "Pool AD: \n%s\n", text);

	if(domain_name_cache_lookup(catalog_host, address)) {
		debug(D_WQ, "Sending the pool decision to the catalog server at %s:%d ...", catalog_host, catalog_port);
		datagram_send(outgoing_datagram, text, text_size, address, catalog_port);
	}

	buffer_free(&B);
	last_update_time = time(0);
	return 1;
}
Esempio n. 3
0
/** Reads a single summary from stream. Summaries are not parsed, here
	we simply read between markers (--) **/
char *rmsummary_read_single_chunk(FILE *stream)
{
	struct buffer b;
	char   line[MAX_LINE];

	/* Skip comments, blank lines, and markers before the summary */
	char c;
	while( (c = getc(stream)) == '#' || isblank(c) || c == '-' )
	{
		ungetc(c, stream);

		/* Make sure we read complete comment lines */
		do {
			line[MAX_LINE - 1] = '\0';
			fgets(line, MAX_LINE, stream);
		} while(line[MAX_LINE - 1]);
	}

	if(feof(stream))
	{
		return NULL;
	}

	buffer_init(&b);

	ungetc(c, stream);
	while( (c = getc(stream)) != EOF )
	{
		ungetc(c, stream);
		if(c == '#' || c == '\n')
			continue;

		if(c == '-')
			break;

		fgets(line, MAX_LINE, stream);
		buffer_printf(&b, "%s", line);
	}

	char *summ = xxstrdup(buffer_tostring(&b));

	buffer_free(&b);

	return summ;
}
Esempio n. 4
0
static int
rdata_nxt_to_string(buffer_type *output, rdata_atom_type rdata,
	rr_type* ATTR_UNUSED(rr))
{
	size_t i;
	uint8_t *bitmap = rdata_atom_data(rdata);
	size_t bitmap_size = rdata_atom_size(rdata);

	for (i = 0; i < bitmap_size * 8; ++i) {
		if (get_bit(bitmap, i)) {
			buffer_printf(output, "%s ", rrtype_to_string(i));
		}
	}

	buffer_skip(output, -1);

	return 1;
}
Esempio n. 5
0
static int
rdata_apl_to_string(buffer_type *output, rdata_atom_type rdata,
                    rr_type* ATTR_UNUSED(rr))
{
    int result = 0;
    buffer_type packet;

    buffer_create_from(
        &packet, rdata_atom_data(rdata), rdata_atom_size(rdata));

    if (buffer_available(&packet, 4)) {
        uint16_t address_family = buffer_read_u16(&packet);
        uint8_t prefix = buffer_read_u8(&packet);
        uint8_t length = buffer_read_u8(&packet);
        int negated = length & APL_NEGATION_MASK;
        int af = -1;

        length &= APL_LENGTH_MASK;
        switch (address_family) {
        case 1:
            af = AF_INET;
            break;
        case 2:
            af = AF_INET6;
            break;
        }
        if (af != -1 && buffer_available(&packet, length)) {
            char text_address[1000];
            uint8_t address[128];
            memset(address, 0, sizeof(address));
            buffer_read(&packet, address, length);
            if (inet_ntop(af, address, text_address, sizeof(text_address))) {
                buffer_printf(output, "%s%d:%s/%d",
                              negated ? "!" : "",
                              (int) address_family,
                              text_address,
                              (int) prefix);
                result = 1;
            }
        }
    }
    return result;
}
Esempio n. 6
0
void test_mbt_quote_decode_logging_on(void)
{
	struct mbt_quote_logging_on *logon;

	setup();

	buffer_printf(buf, "L|100=USERNAME;101=PASSWORD\n");

	mbt_msg = mbt_quote_message_decode(buf);

	assert_int_equals(MBT_QUOTE_LOGGING_ON, mbt_msg->Type);

	logon = mbt_quote_message_payload(mbt_msg);

	assert_str_equals("USERNAME", logon->UserName, 8);
	assert_str_equals("PASSWORD", logon->Password, 8);

	teardown();
}
Esempio n. 7
0
void new_mail(buffer_t *buf, const char *maildir) {
	int n = 0;
	DIR *d = NULL;
	struct dirent *rf = NULL;

	if(maildir == NULL || !(d = opendir(maildir))) {
		buffer_clear(buf);
		return;
	}
	while ((rf = readdir(d)) != NULL) {
		if (strcmp(rf->d_name, ".") != 0 && strcmp(rf->d_name, "..") != 0)
			n++;
	}
	closedir(d);
	if (n > 0) {
		buffer_printf(buf, MAIL_FMT, n);
		return;
	}
	buffer_clear(buf);
}
int advertise_master_to_catalog(const char *catalog_host, int catalog_port, const char *project_name, struct work_queue_stats *s, const char *workers_by_pool, int now) {
	char address[DATAGRAM_ADDRESS_MAX];
	char owner[USERNAME_MAX];

	buffer_t *buffer = NULL;
	const char *text;
	size_t text_size;

	static time_t last_update_time = 0;

	if(!now) {
		if(time(0) - last_update_time < WORK_QUEUE_CATALOG_UPDATE_INTERVAL) return 1;
	}

	if(!outgoing_datagram) {
		outgoing_datagram = datagram_create(0);
		if(!outgoing_datagram) {
			fprintf(stderr, "Failed to advertise master to catalog server: couldn't create outgoing udp datagram!\n");
			return 0;
		}
	}

	if(!username_get(owner)) {
		strcpy(owner,"unknown");
	}

	buffer = buffer_create();

	buffer_printf(buffer, "type wq_master\nproject %s\nstart_time %llu\npriority %d\nport %d\nlifetime %d\ntasks_waiting %d\ntasks_complete %d\ntask_running %d\ntotal_tasks_dispatched %d\nworkers_init %d\nworkers_ready %d\nworkers_busy %d\nworkers %d\nworkers_by_pool %s\ncapacity %d\nversion %d.%d.%d\nowner %s", project_name, s->start_time, s->priority, s->port, WORK_QUEUE_CATALOG_LIFETIME, s->tasks_waiting, s->total_tasks_complete, s->workers_busy, s->total_tasks_dispatched, s->workers_init, s->workers_ready, s->workers_busy, s->workers_ready + s->workers_busy, workers_by_pool, s->capacity, CCTOOLS_VERSION_MAJOR, CCTOOLS_VERSION_MINOR, CCTOOLS_VERSION_MICRO, owner);

	text = buffer_tostring(buffer, &text_size);
	if(domain_name_cache_lookup(catalog_host, address)) {
		debug(D_WQ, "Advertising master status to the catalog server at %s:%d ...", catalog_host, catalog_port);
		datagram_send(outgoing_datagram, text, strlen(text), address, catalog_port);
	}

	buffer_delete(buffer);
	last_update_time = time(0);
	return 1;
}
Esempio n. 9
0
int nvpair_print_alloc(struct nvpair *n, char **text)
{
	size_t needed;

	char *key;
	void *value;

	buffer_t b;
	buffer_init(&b);
	buffer_abortonfailure(&b, 0);

	hash_table_firstkey(n->table);
	while(hash_table_nextkey(n->table, &key, &value)) {
		buffer_printf(&b, "%s %s\n", key, (char *) value);
	}

	*text  = xxstrdup(buffer_tostring(&b, &needed));

	buffer_free(&b);

	return needed;
}
Esempio n. 10
0
int advertise_pool_decision_to_catalog(const char *catalog_host, int catalog_port, const char *pool_name, const char *decision)
{
	char address[DATAGRAM_ADDRESS_MAX];
	char owner[USERNAME_MAX];
	buffer_t *buffer = NULL;
	const char *text;
	size_t text_size;

	static time_t last_update_time = 0;

	if(time(0) - last_update_time < WORK_QUEUE_CATALOG_UPDATE_INTERVAL) return 1;

	if(!outgoing_datagram) {
		outgoing_datagram = datagram_create(0);
		if(!outgoing_datagram) {
			fprintf(stderr, "Couldn't create outgoing udp port, thus work queue master info won't be sent to the catalog server!\n");
			return 0;
		}
	}

	if(!username_get(owner)) {
		strcpy(owner,"unknown");
	}

	buffer = buffer_create();
	buffer_printf(buffer, "type wq_pool\npool_name %s\ndecision %s\nowner %s", pool_name, decision, owner);

	text = buffer_tostring(buffer, &text_size);
	debug(D_WQ, "Pool AD: \n%s\n", text);

	if(domain_name_cache_lookup(catalog_host, address)) {
		debug(D_WQ, "Sending the pool decision to the catalog server at %s:%d ...", catalog_host, catalog_port);
		datagram_send(outgoing_datagram, text, text_size, address, catalog_port);
	}

	buffer_delete(buffer);
	last_update_time = time(0);
	return 1;
}
Esempio n. 11
0
int
rdata_atoms_to_unknown_string(buffer_type *output,
			      rrtype_descriptor_type *descriptor,
			      size_t rdata_count,
			      rdata_atom_type *rdatas)
{
	size_t i;
	size_t size =
		rdata_maximum_wireformat_size(descriptor, rdata_count, rdatas);
	buffer_printf(output, " \\# %lu ", (unsigned long) size);
	for (i = 0; i < rdata_count; ++i) {
		if (rdata_atom_is_domain(descriptor->type, i)) {
			const dname_type *dname =
				domain_dname(rdata_atom_domain(rdatas[i]));
			hex_to_string(
				output, dname_name(dname), dname->name_size);
		} else {
			hex_to_string(output, rdata_atom_data(rdatas[i]),
				rdata_atom_size(rdatas[i]));
		}
	}
	return 1;
}
Esempio n. 12
0
static int
rdata_nsec_to_string(buffer_type *output, rdata_atom_type rdata,
	rr_type* ATTR_UNUSED(rr))
{
	size_t saved_position = buffer_position(output);
	buffer_type packet;
	int insert_space = 0;

	buffer_create_from(
		&packet, rdata_atom_data(rdata), rdata_atom_size(rdata));

	while (buffer_available(&packet, 2)) {
		uint8_t window = buffer_read_u8(&packet);
		uint8_t bitmap_size = buffer_read_u8(&packet);
		uint8_t *bitmap = buffer_current(&packet);
		int i;

		if (!buffer_available(&packet, bitmap_size)) {
			buffer_set_position(output, saved_position);
			return 0;
		}

		for (i = 0; i < bitmap_size * 8; ++i) {
			if (get_bit(bitmap, i)) {
				buffer_printf(output,
					      "%s%s",
					      insert_space ? " " : "",
					      rrtype_to_string(
						      window * 256 + i));
				insert_space = 1;
			}
		}
		buffer_skip(&packet, bitmap_size);
	}

	return 1;
}
Esempio n. 13
0
static int find (buffer_t *B, const size_t base, buffer_t *path, const char *pattern, int recursive)
{
	int rc = 0;
	DIR *D = opendir(buffer_tostring(path));
	if (D) {
		struct dirent *entry;
		size_t current = buffer_pos(path);
		while ((entry = readdir(D))) {
			struct stat buf;

			if (buffer_putstring(path, entry->d_name) == -1) goto failure;
			/* N.B. We don't use FNM_PATHNAME, so `*.c' matches `foo/bar.c' */
			if (fnmatch(pattern, buffer_tostring(path)+base, 0) == 0) {
				if (buffer_printf(B, "%s%c", buffer_tostring(path), 0) == -1) goto failure; /* NUL padded */
				rc += 1;
			}
			if (recursive && strcmp(entry->d_name, ".") && strcmp(entry->d_name, "..") && stat(buffer_tostring(path), &buf) == 0 && S_ISDIR(buf.st_mode)) {
				if (buffer_putliteral(path, "/") == -1) goto failure;
				int found = find(B, base, path, pattern, recursive);
				if (found == -1)
					goto failure;
				else if (found > 0)
					rc += found;
			}
			buffer_rewind(path, current);
		}
	} /* else skip */
	goto out;
failure:
	rc = -1;
	goto out;
out:
	if (D)
		closedir(D);
	return rc;
}
Esempio n. 14
0
/* Recursive function. Gets children of the parse tree and concatenates them
by using the buffer_printf(). The end result is a JSON string without spaces,
tabs and newlines.*/
int get_children(cleri_children_t * child, const char * orig, buffer_t * buf)
{
    int count = 0;
    int rc = 0;
    while (child != NULL)
    {
        cleri_node_t * node = child->node;
        if (!count++)
            rc += buffer_printf(buf, "\"children\":[");

        rc += buffer_printf(
            buf,
            "{\"%s\":\"%s\",\"%s\":\"%.*s\",\"%s\":%ld,",
            "type",
            strtp(node->cl_obj->tp),
            "string",
            (int)node->len,
            node->str,
            "position",
            node->str - orig);

        cleri_children_t * grandchild = node->children;
        rc += get_children(grandchild, orig, buf);
        rc += buffer_printf(buf, "}");
        child = child->next;
        if (child != NULL)
            rc += buffer_printf(buf, ",");
    }

    if (!count)
        rc += buffer_printf(buf, "%s:[]", "\"children\"");
    else
        rc += buffer_printf(buf, "]");

    /* When error occurs in the buffer_printf(), it returns -1. */
    return rc;
}
Esempio n. 15
0
static int
rdata_dns_name_to_string(buffer_type *output, rdata_atom_type rdata,
	rr_type* ATTR_UNUSED(rr))
{
	const uint8_t *data = rdata_atom_data(rdata);
	size_t offset = 0;
	uint8_t length = data[offset];
	size_t i;

	while (length > 0)
	{
		if (offset) /* concat label */
			buffer_printf(output, ".");

		for (i = 1; i <= length; ++i) {
			uint8_t ch = data[i+offset];

			if (ch=='.' || ch==';' || ch=='(' || ch==')' || ch=='\\') {
				buffer_printf(output, "\\%c", (char) ch);
			} else if (!isgraph((unsigned char) ch)) {
				buffer_printf(output, "\\%03u", (unsigned int) ch);
			} else if (isprint((unsigned char) ch)) {
				buffer_printf(output, "%c", (char) ch);
			} else {
				buffer_printf(output, "\\%03u", (unsigned int) ch);
			}
		}
		/* next label */
		offset = offset+length+1;
		length = data[offset];
	}

	/* root label */
	buffer_printf(output, ".");
	return 1;
}
Esempio n. 16
0
int
print_rr(FILE *out,
         struct state_pretty_rr *state,
         rr_type *record)
{
	region_type *region = region_create(xalloc, free);
        buffer_type *output = buffer_create(region, MAX_RDLENGTH);
        rrtype_descriptor_type *descriptor
                = rrtype_descriptor_by_type(record->type);
        int result;
        const dname_type *owner = domain_dname(record->owner);
        const dname_type *owner_origin
                = dname_origin(region, owner);
        int owner_changed
                = (!state->previous_owner
                   || dname_compare(state->previous_owner, owner) != 0);
        if (owner_changed) {
                int origin_changed = (!state->previous_owner_origin
                                      || dname_compare(
                                              state->previous_owner_origin,
                                              owner_origin) != 0);
                if (origin_changed) {
                        buffer_printf(
                                output,
                                "$ORIGIN %s\n",
                                dname_to_string(owner_origin, NULL));
                }

                set_previous_owner(state, owner);
                buffer_printf(output,
                              "%s",
                              dname_to_string(owner,
                                              state->previous_owner_origin));
        }

        buffer_printf(output,
                      "\t%lu\t%s\t%s",
                      (unsigned long) record->ttl,
                      rrclass_to_string(record->klass),
                      rrtype_to_string(record->type));

        result = print_rdata(output, descriptor, record);
        if (!result) {
                /*
                 * Some RDATA failed to print, so print the record's
                 * RDATA in unknown format.
                 */
                result = rdata_atoms_to_unknown_string(output,
                                                       descriptor,
                                                       record->rdata_count,
                                                       record->rdatas);
        }

        if (result) {
                buffer_printf(output, "\n");
                buffer_flip(output);
		(void)write_data(out, buffer_current(output), buffer_remaining(output));
/*              fflush(out); */
        }

	region_destroy(region);
        return result;
}
Esempio n. 17
0
struct mime_field *mime_makefield(FILE *instream, const char *line,
        int *readlast)
{
    char tempbuf[BIG_BUF];
    char finalbuf[HUGE_BUF];
    char *name, *value, *params;
    char *tptr, *tptr2;
    struct mime_field *field;

    *readlast = 0;

	if (!line) return NULL;

    memset(tempbuf, 0, sizeof(tempbuf));
    memset(finalbuf, 0, sizeof(finalbuf));
	strncpy(finalbuf, line, HUGE_BUF-1);

    /* The use of BIG_BUF here is deliberate */
    if (finalbuf[strlen(finalbuf) - 1] == '\n')
		finalbuf[strlen(finalbuf) - 1] = 0;

    if (!finalbuf[0]) return NULL;

    tptr = strchr(finalbuf,':');
    if (!tptr) return NULL;

    *tptr++ = 0;

    name = (char *)malloc(strlen(finalbuf) + 1);
    buffer_printf(name,strlen(finalbuf) + 1,"%s",finalbuf);

    /* Eat whitespace */
    while (isspace((int)*tptr)) tptr++;

    tptr2 = strchr(tptr,';');
    if (tptr2) *tptr2++ = 0;

    value = (char *)malloc(strlen(tptr) + 1);
    buffer_printf(value,strlen(tptr) + 1,"%s",tptr);

    params = NULL;

    if (tptr2) {
        tptr = tptr2;
        while (isspace((int)*tptr)) tptr++;

        params = (char *)malloc(strlen(tptr) + 1);
        buffer_printf(params,strlen(tptr) + 1,"%s",tptr);
    }

    field = (struct mime_field *)malloc(sizeof(struct mime_field));
    field->name = name;
    field->value = value;
    field->params = params;

    log_printf(50, "field name: .%s.\n", field->name);
    log_printf(50, "field value: .%s.\n", field->value);
    log_printf(50, "field params: .%s.\n", field->params);

    return field;
}
Esempio n. 18
0
struct link *http_query_size_via_proxy(const char *proxy, const char *urlin, const char *action, INT64_T * size, time_t stoptime, int cache_reload)
{
	char url[HTTP_LINE_MAX];
	char newurl[HTTP_LINE_MAX];
	char line[HTTP_LINE_MAX];
	char addr[LINK_ADDRESS_MAX];
	struct link *link;
	int save_errno;
	int response;
	char actual_host[HTTP_LINE_MAX];
	int actual_port;
	*size = 0;

	url_encode(urlin, url, sizeof(url));

	if(proxy && !strcmp(proxy, "DIRECT"))
		proxy = 0;

	if(proxy) {
		int fields = sscanf(proxy, "http://%[^:]:%d", actual_host, &actual_port);
		if(fields == 2) {
			/* host and port are good */
		} else if(fields == 1) {
			actual_port = HTTP_PORT;
		} else {
			debug(D_HTTP, "invalid proxy syntax: %s", proxy);
			return 0;
		}
	} else {
		int fields = sscanf(url, "http://%[^:]:%d", actual_host, &actual_port);
		if(fields != 2) {
			fields = sscanf(url, "http://%[^/]", actual_host);
			if(fields == 1) {
				actual_port = HTTP_PORT;
			} else {
				debug(D_HTTP, "malformed url: %s", url);
				return 0;
			}
		}
	}

	debug(D_HTTP, "connect %s port %d", actual_host, actual_port);
	if(!domain_name_lookup(actual_host, addr))
		return 0;

	link = link_connect(addr, actual_port, stoptime);
	if(!link) {
		errno = ECONNRESET;
		return 0;
	}


	{
		buffer_t B;

		buffer_init(&B);
		buffer_abortonfailure(&B, 1);

		buffer_printf(&B, "%s %s HTTP/1.1\r\n", action, url);
		if(cache_reload)
			buffer_putliteral(&B, "Cache-Control: max-age=0\r\n");
		buffer_putliteral(&B, "Connection: close\r\n");
		buffer_printf(&B, "Host: %s\r\n", actual_host);
		if(getenv("HTTP_USER_AGENT"))
			buffer_printf(&B, "User-Agent: Mozilla/5.0 (compatible; CCTools %d.%d.%s Parrot; http://www.nd.edu/~ccl/ %s)\r\n", CCTOOLS_VERSION_MAJOR, CCTOOLS_VERSION_MINOR, CCTOOLS_VERSION_MICRO, getenv("HTTP_USER_AGENT"));
		else
			buffer_printf(&B, "User-Agent: Mozilla/5.0 (compatible; CCTools %d.%d.%s Parrot; http://www.nd.edu/~ccl/)\r\n", CCTOOLS_VERSION_MAJOR, CCTOOLS_VERSION_MINOR, CCTOOLS_VERSION_MICRO);
		buffer_putliteral(&B, "\r\n"); /* header terminator */

		debug(D_HTTP, "%s", buffer_tostring(&B, NULL));
		link_putstring(link, buffer_tostring(&B, NULL), stoptime);

		buffer_free(&B);
	}

	if(link_readline(link, line, HTTP_LINE_MAX, stoptime)) {
		string_chomp(line);
		debug(D_HTTP, "%s", line);
		if(sscanf(line, "HTTP/%*d.%*d %d", &response) == 1) {
			newurl[0] = 0;
			while(link_readline(link, line, HTTP_LINE_MAX, stoptime)) {
				string_chomp(line);
				debug(D_HTTP, "%s", line);
				sscanf(line, "Location: %s", newurl);
				sscanf(line, "Content-Length: %" SCNd64, size);
				if(strlen(line) <= 2) {
					break;
				}
			}

			switch (response) {
			case 200:
				return link;
				break;
			case 301:
			case 302:
			case 303:
			case 307:
				link_close(link);
				if(newurl[0]) {
					if(!strcmp(url, newurl)) {
						debug(D_HTTP, "error: server gave %d redirect from %s back to the same url!", response, url);
						errno = EIO;
						return 0;
					} else {
						return http_query_size_via_proxy(proxy,newurl,action,size,stoptime,cache_reload);
					}
				} else {
					errno = ENOENT;
					return 0;
				}
				break;
			default:
				link_close(link);
				errno = http_response_to_errno(response);
				return 0;
				break;
			}
		} else {
			debug(D_HTTP, "malformed response");
			save_errno = ECONNRESET;
		}
	} else {
		debug(D_HTTP, "malformed response");
		save_errno = ECONNRESET;
	}

	link_close(link);
	errno = save_errno;
	return 0;
}
Esempio n. 19
0
// TODO: these tests suck
bool
test_buffer_printf () {
	size_t n = 0;
	buffer_t *buf = buffer_new();

	if (!buf) {
		FAIL("buffer_new() failed\n");
	}

	n = buffer_printf(buf, "%s", "Hello, world!");
	DUMP_BUFFER();
	printf("n: %lu, strlen(\"Hello, world!\"): %lu\n", n, strlen("Hello, world!"));
	if (n != strlen("Hello, world!")) {
		FAIL("buffer_printf() \"Hello world!\" failed\n");
	}


	n = buffer_printf(buf, "%d %d", 345, 543);
	DUMP_BUFFER();
	printf("n: %lu, strlen(\"345 543\"): %lu\n", n, strlen("345 543"));
	if (n != strlen("345 543")) {
		FAIL("buffer_printf() \"345 543\" failed\n");
	}


	n = buffer_printf(buf, "%s",
		"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
		"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
		"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
		"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
		"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
		"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
		"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
		"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
		"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
		"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
		"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
		"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
		"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
		"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
		"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
		"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
		"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
	);
	DUMP_BUFFER();

	if (n !=
		strlen(
			"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
			"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
			"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
			"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
			"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
			"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
			"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
			"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
			"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
			"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
			"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
			"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
			"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
			"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
			"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
			"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
			"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
		)
	) {
		FAIL("buffer_printf() - big print failed");
	}

	PASS();
}
Esempio n. 20
0
enum xfrd_packet_result
xfrd_handle_received_xfr_packet(xfrd_zone_t* zone, buffer_type* packet)
{
	xfrd_soa_t soa;
	enum xfrd_packet_result res;

	/* parse and check the packet - see if it ends the xfr */
	switch((res=xfrd_parse_received_xfr_packet(zone, packet, &soa)))
	{
		case xfrd_packet_more:
		case xfrd_packet_transfer:
			/* continue with commit */
			break;
		case xfrd_packet_newlease:
			return xfrd_packet_newlease;
		case xfrd_packet_tcp:
			return xfrd_packet_tcp;
		case xfrd_packet_notimpl:
		case xfrd_packet_bad:
		default:
		{
			/* rollback */
			if(zone->msg_seq_nr > 0) {
				/* do not process xfr - if only one part simply ignore it. */
				/* rollback previous parts of commit */
				buffer_clear(packet);
				buffer_printf(packet, "xfrd: zone %s xfr "
						      "rollback serial %u at "
						      "time %u from %s of %u "
						      "parts",
					zone->apex_str,
					(int)zone->msg_new_serial,
					(int)xfrd_time(),
					zone->master->ip_address_spec,
					zone->msg_seq_nr);

				buffer_flip(packet);
				diff_write_commit(zone->apex_str,
					zone->msg_old_serial,
					zone->msg_new_serial,
					zone->query_id, zone->msg_seq_nr, 0,
					(char*)buffer_begin(packet),
					xfrd->nsd->options);
				DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: zone %s "
							       "xfr reverted "
							       "\"%s\"",
					zone->apex_str,
					(char*)buffer_begin(packet)));
			}
			if (res == xfrd_packet_notimpl)
				return res;
			else
				return xfrd_packet_bad;
		}
	}

	/* dump reply on disk to diff file */
	diff_write_packet(zone->apex_str, zone->msg_new_serial, zone->query_id,
		zone->msg_seq_nr, buffer_begin(packet), buffer_limit(packet),
		xfrd->nsd->options);
	VERBOSITY(1, (LOG_INFO,
		"xfrd: zone %s written received XFR from %s with serial %u to "
		"disk", zone->apex_str, zone->master->ip_address_spec,
		(int)zone->msg_new_serial));
	zone->msg_seq_nr++;
	if(res == xfrd_packet_more) {
		/* wait for more */
		return xfrd_packet_more;
	}

	/* done. we are completely sure of this */
	buffer_clear(packet);
	buffer_printf(packet, "xfrd: zone %s received update to serial %u at "
			      "time %u from %s in %u parts",
		zone->apex_str, (int)zone->msg_new_serial, (int)xfrd_time(),
		zone->master->ip_address_spec, zone->msg_seq_nr);
	if(zone->master->key_options) {
		buffer_printf(packet, " TSIG verified with key %s",
			zone->master->key_options->name);
	}
	buffer_flip(packet);
	diff_write_commit(zone->apex_str, zone->msg_old_serial,
		zone->msg_new_serial, zone->query_id, zone->msg_seq_nr, 1,
		(char*)buffer_begin(packet), xfrd->nsd->options);
	VERBOSITY(1, (LOG_INFO, "xfrd: zone %s committed \"%s\"",
		zone->apex_str, (char*)buffer_begin(packet)));
	/* update the disk serial no. */
	zone->soa_disk_acquired = xfrd_time();
	zone->soa_disk = soa;
	if(zone->soa_notified_acquired && (
		zone->soa_notified.serial == 0 ||
		compare_serial(htonl(zone->soa_disk.serial),
		htonl(zone->soa_notified.serial)) >= 0))
	{
		zone->soa_notified_acquired = 0;
	}
	if(!zone->soa_notified_acquired) {
		/* do not set expired zone to ok:
		 * it would cause nsd to start answering
		 * bad data, since the zone is not loaded yet.
		 * if nsd does not reload < retry time, more
		 * queries (for even newer versions) are made.
		 * For expired zone after reload it is set ok (SOAINFO ipc). */
		if(zone->state != xfrd_zone_expired)
			xfrd_set_zone_state(zone, xfrd_zone_ok);
		DEBUG(DEBUG_XFRD,1, (LOG_INFO,
			"xfrd: zone %s is waiting for reload",
			zone->apex_str));
		zone->round_num = -1; /* next try start anew */
		xfrd_set_timer_refresh(zone);
		xfrd_set_reload_timeout();
		return xfrd_packet_transfer;
	} else {
		/* try to get an even newer serial */
		/* pretend it was bad to continue queries */
		xfrd_set_reload_timeout();
		return xfrd_packet_bad;
	}
}
Esempio n. 21
0
//Using default sampling interval. We may want to add an option
//to change it.
char *resource_monitor_write_command(const char *monitor_path, const char *template_filename, const struct rmsummary *limits, const char *extra_monitor_options, int debug_output, int time_series, int inotify_stats)
{


	buffer_t cmd_builder;
	buffer_init(&cmd_builder);

	if(!monitor_path)
		fatal("Monitor path should be specified.");

	buffer_printf(&cmd_builder, "%s", monitor_path);
	buffer_printf(&cmd_builder, " --with-output-files=%s", template_filename);

	if(debug_output)
		buffer_printf(&cmd_builder, " -dall -o %s.debug", template_filename);

	if(time_series)
		buffer_printf(&cmd_builder, " --with-time-series");

	if(inotify_stats)
		buffer_printf(&cmd_builder, " --with-inotify");

	if(limits) {
		if(limits->end > -1)
			buffer_printf(&cmd_builder, " -L 'end: %lf'", limits->end/1000000e0);

		if(limits->wall_time > -1)
			buffer_printf(&cmd_builder, " -L 'wall_time: %lf'", limits->wall_time/1000000e0);

		if(limits->cpu_time > -1)
			buffer_printf(&cmd_builder, " -L 'cpu_time: %lf'", limits->cpu_time/1000000e0);

		if(limits->cores > -1)
			buffer_printf(&cmd_builder, " -L 'cores: %" PRId64 "'", limits->cores);

		if(limits->max_concurrent_processes > -1)
			buffer_printf(&cmd_builder, " -L 'max_concurrent_processes: %" PRId64 "'", limits->max_concurrent_processes);

		if(limits->total_processes > -1)
			buffer_printf(&cmd_builder, " -L 'total_processes: %" PRId64 "'", limits->total_processes);

		if(limits->virtual_memory > -1)
			buffer_printf(&cmd_builder, " -L 'virtual_memory: %" PRId64 "'", limits->virtual_memory);

		if(limits->memory > -1)
			buffer_printf(&cmd_builder, " -L 'memory: %" PRId64 "'", limits->memory);

		if(limits->swap_memory > -1)
			buffer_printf(&cmd_builder, " -L 'swap_memory: %" PRId64 "'", limits->swap_memory);

		if(limits->bytes_read > -1)
			buffer_printf(&cmd_builder, " -L 'bytes_read: %" PRId64 "'", limits->bytes_read);

		if(limits->bytes_written > -1)
			buffer_printf(&cmd_builder, " -L 'bytes_written: %" PRId64 "'", limits->bytes_written);

		if(limits->total_files > -1)
			buffer_printf(&cmd_builder, " -L 'total_files: %" PRId64 "'", limits->total_files);

		if(limits->disk > -1)
			buffer_printf(&cmd_builder, " -L 'disk: %" PRId64 "'", limits->disk);
	}

	if(extra_monitor_options)
		buffer_printf(&cmd_builder, " %s", extra_monitor_options);

	buffer_printf(&cmd_builder, " --sh []");

	char *result;
	buffer_dupl(&cmd_builder, &result, 0);
	buffer_free(&cmd_builder);

	return result;
}
Esempio n. 22
0
static void write_long(struct buffer *buf, const char *header, long val)
{
    buffer_printf(buf, "%%%s%%\n%ld\n\n", header, val);
}
Esempio n. 23
0
int address_match(const char *addy1, const char *addy2)
{
	/*
	 * 9/9/2005 JKT
	 * Moved no-loose-domain-match support here from higher level function
	 * user.c (so that it would be supported in userdb queries as well as
	 * users queries).
	 */
    char domain1[SMALL_BUF], domain2[SMALL_BUF];
    char user1[SMALL_BUF], user2[SMALL_BUF];
    char buf[BIG_BUF], mbuf1[BIG_BUF], mbuf2[BIG_BUF];
    char *tptr1, *tptr2, *tptr3;

	int notloose = get_bool("no-loose-domain-match"); /* 9/9/2005 JKT */

    buffer_printf(buf, sizeof(buf) - 1, "%s", addy1);

    tptr1 = strchr(buf, '@');
    if (notloose || !tptr1) { /* 9/9/2005 JKT - added notloose condition */
        return (strcasecmp(addy1,addy2) == 0);
    };

    *tptr1++ = 0;

    buffer_printf(user1, sizeof(user1) - 1, "%s", buf);

    /* Handle dotted non-local hosts correctly. */
    tptr2 = strchr(tptr1,'.');
    if (tptr2) {
        tptr2++;

        while ((tptr3 = strchr(tptr2,'.'))) {
           tptr1 = tptr2;
           tptr2 = tptr3 + 1;
        }                  
    }

    buffer_printf(domain1, sizeof(domain1) - 1, "%s", tptr1);

    buffer_printf(buf, sizeof(buf) - 1, "%s", addy2);

    tptr1 = strchr(buf, '@');
    if (!tptr1) return 0;

    *tptr1++ = 0;

    buffer_printf(user2, sizeof(user2) - 1, "%s", buf);

    /* Handle dotted non-local hosts correctly. */
    tptr2 = strchr(tptr1,'.');
    if (tptr2) {
        tptr2++;

        while ((tptr3 = strchr(tptr2,'.'))) {
           tptr1 = tptr2;
           tptr2 = tptr3 + 1;
        }                  
    }

    buffer_printf(domain2, sizeof(domain2) - 1, "%s", tptr1);

    buffer_printf(mbuf1, sizeof(mbuf1) - 1, "%s@%s", user1, domain1);
    buffer_printf(mbuf2, sizeof(mbuf2) - 1, "%s@%s", user2, domain2);

    return (strcasecmp(mbuf1,mbuf2) == 0);
}
Esempio n. 24
0
void parse_and_execute(char *dir, char *presetdir,
                       char *url, int ulen, buffer_t *buf)
{
    char *urlend = url + ulen;
    if(urlend == url)
        return; // Empty path, can't do anything
    if(ulen >= 11 && !strncmp(urlend - 11, "/index.json", 11)) {
        if(ulen == 11) {
            // It's root index, let's send short index
            STDASSERT(buffer_printf(buf, "{\"presets\": [\n"));
            DIR *dhandle = opendir(presetdir);
            if(dhandle) {
                struct dirent *ent;
                int first = TRUE;
                while((ent = readdir(dhandle))) {
                    if(ent->d_name[0] == '.') continue;
                    if(!first) {
                        STDASSERT(buffer_printf(buf, ",\n"));
                    } else {
                        first = FALSE;
                    }
                    STDASSERT(buffer_printf(buf, "\"%s\"", ent->d_name));
                }
                STDASSERT(closedir(dhandle));
            }
            STDASSERT(buffer_printf(buf, "\n], \"hosts\": [\n"));
            dhandle = opendir(dir);
            if(dhandle) {
                struct dirent *ent;
                int first = TRUE;
                while((ent = readdir(dhandle))) {
                    if(ent->d_name[0] == '.') continue;
                    if(!first) {
                        STDASSERT(buffer_printf(buf, ",\n"));
                    } else {
                        first = FALSE;
                    }
                    STDASSERT(buffer_printf(buf, "\"%s\"", ent->d_name));
                }
                STDASSERT(closedir(dhandle));
            }
            STDASSERT(buffer_printf(buf, "]}\n"));
        } else {
            // It's a directory, let's send info on all files
            int dirlen = strlen(dir);
            char fulldir[dirlen + urlend - url - 10];
            strcpy(fulldir, dir);
            if(fulldir[dirlen-1] == '/') {
                fulldir[dirlen-1] = 0;
            }
            assert(url[0] == '/');
            strncat(fulldir, url, urlend - url - 10);
            char *dirs[] = {fulldir, NULL};
            quickvisit_tree(buf, dirs, strlen(fulldir));
        }
    } else {
        char *query = memchr(url, '?', urlend - url);
        if(!query) {
            buffer_printf(buf, "{\"error\": \"no query\"}");
            return;
        }
        int dirlen = strlen(dir);
        char fullpath[dirlen + query - url + 1];
        strcpy(fullpath, dir);
        int fullen = dirlen;
        if(fullpath[dirlen-1] == '/') {
            fullpath[dirlen-1] = 0;
            fullen --;
        }
        assert(url[0] == '/');
        if(*(query-1) == '/') {
            char *dirs[] = {fullpath, NULL};
            traverse_tree(buf, dirs, strlen(fullpath));
            return;
        }
        strncpy(fullpath + fullen, url, query - url);
        fullen += query - url;
        if(fullen > 5 && !memcmp(fullpath+fullen-5, ".json", 5)) {
            fullen -= 5;
            fullpath[fullen] = 0;
        } else {
            fullpath[fullen] = 0;
        }
        char cf[16] = "AVERAGE";
        char sbuf[16];
        time_t start = 0;
        time_t end = 0;
        int step = 0;
        for(char *q = query+1; q < urlend;) {
            char *eq = memchr(q, '=', urlend - q);
            char *amp = memchr(q, '&', urlend - q);
            if(amp && amp < eq) {
                q = amp+1;
                continue;
            }
            if(!eq) break;
            if(!amp) amp = urlend;
            if(eq - q == 2 && !strncmp(q, "cf", 2)) {
                int len = amp - eq - 1;
                if(len > 15) len = 15;
                memcpy(cf, eq+1, len);
                cf[len] = 0;
            } if(eq - q == 5 && !strncmp(q, "start", 5)) {
                int len = amp - eq - 1;
                if(len > 15) len = 15;
                memcpy(sbuf, eq+1, len);
                sbuf[len] = 0;
                start = strtol(sbuf, NULL, 10);
            } if(eq - q == 3 && !strncmp(q, "end", 3)) {
                int len = amp - eq - 1;
                if(len > 15) len = 15;
                memcpy(sbuf, eq+1, len);
                sbuf[len] = 0;
                end = strtol(sbuf, NULL, 10);
            } if(eq - q == 4 && !strncmp(q, "step", 4)) {
                int len = amp - eq - 1;
                if(len > 15) len = 15;
                memcpy(sbuf, eq+1, len);
                sbuf[len] = 0;
                step = strtol(sbuf, NULL, 10);
            }
            q = amp+1;
        }
        format_data(buf, fullpath, cf, start, end, step);
    }
}
Esempio n. 25
0
/* YOU WILL NEED TO FREE THIS RETURN RESULT */
const char *mime_parameter(struct mime_header *header, const char *fieldname,
        const char *paramname)
{
    char temp[BIG_BUF], temp2[SMALL_BUF];
    char *tptr, *tptr2;
    int done, eattrail, length; 
    struct mime_field *field;
    int escape;

    field = mime_getfield(header,fieldname);
    if (!field) return NULL;
    if (!field->params) return NULL;

    /* Get some sane temporary workspace */
    buffer_printf(temp, sizeof(temp) - 1, "%s", field->params);

    tptr = strtok(temp,";");

    done = 0;

    while (tptr && !done) {
        /* Clear our temporary buffer */
        memset(temp2, 0, sizeof(temp2));

        tptr2 = &temp2[0];

        while (*tptr && (*tptr != '=') && tptr2 < temp2 + sizeof(temp2) - 1) {
            if (!isspace((int)*tptr)) *tptr2++ = *tptr;
            tptr++;
        }

        /* Is this our parameter? */
        if (strcasecmp(temp2,paramname) == 0) {
            char *endspace = NULL ;
            done = 1; eattrail = 1;
            tptr++;

            escape = 0;

            /* Clear our temporary buffer */
            memset(temp2, 0, sizeof(temp2));

            tptr2 = &temp2[0];

            while (*tptr && (*tptr != ';') && tptr2 < temp2 + sizeof(temp2) - 1) {
                if ( (!escape) && isspace((int)*tptr) ) {
                    if (!eattrail) {
                        /* We store the position to remove end spaces */
                        if (!endspace) endspace = tptr2 ;
                        *tptr2++ = *tptr;
                    }
                } else {
                    eattrail = 0;
                    endspace = NULL ;

                    if ( !(*tptr == '\"' || *tptr == '\\') || escape) {
                        *tptr2++ = *tptr;
                        escape = 0;
                    }
                    else { /* this is to avoid a '\' to escape itself */
                        if (*tptr == '\\') escape = 1;
                    }
                }

                tptr++;
            }

            if (endspace) *endspace = 0 ;

        } else tptr = strtok(NULL,";");
    }

    if (!done) return NULL;

    length = strlen(temp2);

    tptr = (char *)malloc(length + 1);
    memset(tptr,0,length + 1);
    buffer_printf(tptr,length + 1,"%s",temp2);

    return tptr;   
}
Esempio n. 26
0
int main(int argc, char *argv[]) {
	char *host = CATALOG_HOST;
	int   port = CATALOG_PORT;

	static struct option long_options[] = {{"catalog", required_argument, 0, 'c'},
                {0,0,0,0}};

	signed int c;
	while ((c = getopt_long(argc, argv, "c:", long_options, NULL)) > -1) {
		switch (c) {
			case 'c':
				host = optarg;
				break;
			default:
				show_help(argv[0]);
				return EXIT_FAILURE;
		}
	}

	struct datagram *d;
	d = datagram_create(DATAGRAM_PORT_ANY);
	if (!d) {
		fatal("could not create datagram port!");
	}

	buffer_t B;
	const char *text;
	size_t text_size;
	buffer_init(&B);
	buffer_abortonfailure(&B, 1);

	struct utsname name;
	int cpus;
	int uptime;	
	double load[3];
	UINT64_T memory_total, memory_avail;
	char owner[USERNAME_MAX];

	uname(&name);
	string_tolower(name.sysname);
	string_tolower(name.machine);
	string_tolower(name.release);
	load_average_get(load);
	cpus = load_average_get_cpus();
	memory_info_get(&memory_avail, &memory_total);
	uptime = uptime_get();
	username_get(owner);

	buffer_printf(&B, "type %s\nversion %d.%d.%s\ncpu %s\nopsys %s\nopsysversion %s\nload1 %0.02lf\nload5 %0.02lf\nload15 %0.02lf\nmemory_total %llu\nmemory_avail %llu\ncpus %d\nuptime %d\nowner %s\n",
		DEFAULT_TYPE,
		CCTOOLS_VERSION_MAJOR, CCTOOLS_VERSION_MINOR, CCTOOLS_VERSION_MICRO,
		name.machine,
		name.sysname,
		name.release,
		load[0],
		load[1],
		load[2],
		(unsigned long long) memory_total,
		(unsigned long long) memory_avail,
		cpus,
		uptime,
		owner
	);

	int i;
	for (i = optind; i < argc; i++) {
		char *name;
		char *value;

		name  = argv[i];
		value = strchr(name, '=');
		if (!value) {
			fatal("invalid name/value pair = %s", name);
		} else {
			*value++ = 0;
		}

		buffer_printf(&B, "%s %s\n", name, value);
	}

        text = buffer_tostring(&B, &text_size);

	char address[DATAGRAM_ADDRESS_MAX];
	if (domain_name_cache_lookup(host, address)) {
		datagram_send(d, text, text_size, address, port);
	} else {
		fatal("unable to lookup address of host: %s", host);
	}

	buffer_free(&B);
	datagram_delete(d);
	return EXIT_SUCCESS;
}
Esempio n. 27
0
int main(int argc, char **argv) {
    void *zmqcontext = zmq_init(1);
    assert(zmqcontext);
    void *zmqsock = zmq_socket(zmqcontext, ZMQ_REP);
    assert(zmqsock);
    char *dir = NULL;
    char *prefix = "";
    char *presetdir = "/etc/jarred";
    int prefixlen = 0;

    int opt;
    while((opt = getopt(argc, argv, "hc:b:d:p:s:")) != -1) {
        switch(opt) {
        case 'c': // connect
            STDASSERT(zmq_connect(zmqsock, optarg))
            break;
        case 'b': // bind
            STDASSERT(zmq_bind(zmqsock, optarg))
            break;
        case 'd': // dir
            dir = optarg;
            break;
        case 'p': // prefix
            prefix = optarg;
            prefixlen = strlen(optarg);
            break;
        case 's': // dir with presets
            presetdir = optarg;
            break;
        case 'h':
            print_usage(stdout);
            exit(0);
        default:
            print_usage(stderr);
            exit(1);
        }
    }
    if(!dir) {
        dir = getcwd(NULL, 0);
    }

    while(TRUE) {
        zmq_msg_t msg;
        zmq_msg_init(&msg);
        int rc = zmq_recv(zmqsock, &msg, 0);
        if(rc < 0) {
            if(errno == EINTR || errno == EAGAIN) continue;
            perror("Error receiving message");
            abort();
        }
        uint64_t opt;
        size_t opt_size = sizeof(opt);
        STDASSERT(zmq_getsockopt(zmqsock, ZMQ_RCVMORE, &opt, &opt_size));
        assert(!opt); // could reopen socket, but restart is ok
        buffer_t *buf = malloc(sizeof(buffer_t));
        buffer_init(buf, 1024);
        char *data = zmq_msg_data(&msg);
        int dlen = zmq_msg_size(&msg);
        if(dlen < prefixlen) {
            buffer_printf(buf, "{\"error\": \"uri too short\"}");
        } else if(memcmp(data, prefix, prefixlen)) {
            buffer_printf(buf, "{\"error\": \"wrong path prefix\"}");
        } else {
            data += prefixlen;
            dlen -= prefixlen;
            parse_and_execute(dir, presetdir, data, dlen, buf);
        }
        zmq_msg_init_data(&msg, buf->data, buf->size,
            (void (*)(void*, void*))free_buffer, buf);
        STDASSERT(zmq_send(zmqsock, &msg, 0));
    }
    zmq_close(zmqsock);
    zmq_term(zmqcontext);
    // Free directory if needed
}
Esempio n. 28
0
int main() {
  struct tm t;
  time_t zero = 0;
  struct buffer b[1];

  buffer_init(b);
  assert(b->base == NULL);
  assert(b->pos == 0);
  assert(b->size == 0);

  buffer_putc(b, 'a');
  assert(b->base != NULL);
  assert(!strncmp(b->base, "a", 1));
  assert(b->pos == 1);
  assert(b->pos < b->size);

  buffer_putc(b, 'b');
  assert(b->base != NULL);
  assert(!strncmp(b->base, "ab", 2));
  assert(b->pos == 2);
  assert(b->pos < b->size);

  buffer_append(b, "12345678901234567890");
  assert(b->base != NULL);
  assert(!strncmp(b->base, "ab12345678901234567890", 22));
  assert(b->pos == 22);
  assert(b->pos < b->size);

  buffer_append_n(b, "spong", 4);
  assert(b->base != NULL);
  assert(!strncmp(b->base, "ab12345678901234567890spon", 26));
  assert(b->pos == 26);
  assert(b->pos < b->size);

  buffer_printf(b, "%s", "");
  assert(b->base != NULL);
  assert(!strncmp(b->base, "ab12345678901234567890spon", 26));
  assert(b->pos == 26);
  assert(b->pos < b->size);

  buffer_printf(b, "%s", "123456");
  assert(b->base != NULL);
  assert(!strncmp(b->base, "ab12345678901234567890spon123456", 32));
  assert(b->pos == 32);
  assert(b->pos < b->size);
  b->pos -= 6;

  buffer_printf(b, "%s", "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
  assert(b->base != NULL);
  assert(!strncmp(b->base, "ab12345678901234567890sponABCDEFGHIJKLMNOPQRSTUVWXYZ", 52));
  assert(b->pos == 52);
  assert(b->pos < b->size);

  buffer_terminate(b);
  assert(b->base != NULL);
  assert(!strcmp(b->base, "ab12345678901234567890sponABCDEFGHIJKLMNOPQRSTUVWXYZ"));
  assert(b->pos == 52);
  assert(b->pos < b->size);

  b->pos = 0;
  gmtime_r(&zero, &t);
  buffer_strftime(b, "", &t);
  assert(b->pos == 0);
  buffer_strftime(b, "%F %T", &t);
  buffer_terminate(b);
  assert(!strcmp(b->base, "1970-01-01 00:00:00"));

  free(b->base);
  return 0;
}