wm: ticl

ref: 8df402e53d02ca2c0b976715ce57c28750dd99d9
dir: /util.c/

View raw version
/*
 * This work is dedicated to the public domain.
 * See COPYING file for more information.
 */

#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <errno.h>

void *
ecalloc(size_t nmemb, size_t size)
{
	void *p;
	if ((p = calloc(nmemb, size)) == NULL) {
		printf("error: calloc: %s\n", strerror(errno));
		return NULL;
	}
	return p;
}

char*
split(char **str, char ch)
{
	char *token = *str;

	if (**str == '\0') return *str;

	while (**str != ch && **str != '\0')
		(*str)++;
	if (**str == '\0')
		return token;
	**str = '\0';
	(*str)++;
	while(**str == ch && **str != '\0')
		(*str)++;
	return token;
}

ssize_t
fdprintf(int fd, const char *fmt, ...)
{
	va_list args;
	char buf[1024];
	size_t len;
	ssize_t n, i = 0;

	va_start(args, fmt);
	vsnprintf(buf, sizeof(buf), fmt, args);
	va_end(args);

	len = strlen(buf);
	while (i < (ssize_t)len) {
		if ((n = write(fd, buf + i, len - (size_t)i)) == -1) {
			printf("error: write failed: %s\n", strerror(errno));
			return -1;
		}
		i += n;
	}
	return i;
}

int
dial(char *host, char *port)
{
	static struct addrinfo hints, *res = NULL, *res0;
	int fd = -1, r;

	memset(&hints, 0, sizeof(hints));
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;

	if ((r = getaddrinfo(host, port, &hints, &res0)) != 0) {
		printf("error: getaddrinfo: %s\n", gai_strerror(r));
		return -1;
	}
	for (res = res0; res != NULL; res = res->ai_next) {
		if ((fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) < 0)
			continue;
		if (connect(fd, res->ai_addr, res->ai_addrlen) != 0) {
			close(fd);
			fd = -1;
			continue;
		}
		break;
	}
	if (fd == -1)
		printf("error: cannot connect to host '%s'\n", host);

	freeaddrinfo(res0);
	return fd;
}

ssize_t
readline(int fd, char *buffer, size_t size)
{
	ssize_t n, i = 0;
	char c;

	do {
		if ((n = read(fd, &c, sizeof(char))) != sizeof(char))
			return n;
		buffer[i++] = c;
	} while ((i < (ssize_t)size) && (c != '\n') && (c != '\0'));

	buffer[i-1] = '\0';
	return i;
}