ref: 5ff9649e6c51bae0dd09f218e4943fa5f4d458be
dir: /utils.c/
/* * 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 "utils.h" void fatal(const char *fmt, ...) { va_list ap; va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); if (fmt[0] && fmt[strlen(fmt)-1] == ':') { fputc(' ', stderr); perror(NULL); } else { fputc('\n', stderr); } exit(1); } void * ecalloc(size_t nmemb, size_t size) { void *p; if ((p = calloc(nmemb, size)) == NULL) fatal("calloc:"); 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; } void ircsend(int fd, const char *format, ...) { static char buf[4096]; va_list args; va_start(args, format); vsnprintf(buf, sizeof(buf), format, args); va_end(args); strcat(buf, "\r\n"); send(fd, buf, strlen(buf), 0); } 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); return -1; } freeaddrinfo(res0); return fd; } int isstrnumber(char *str) { int i; for (i = 0; str[i]!= '\0'; i++) { if (isdigit(str[i]) == 0) return 0; } return 1; } size_t strlcpy(char *dst, const char *src, size_t size) { size_t i; if (size == 0) return 0; for (i = 0; i < size; i++) { dst[i] = src[i]; if (src[i] == '\0') return i; } dst[size-1] = '\0'; return size-1; } ssize_t dreadline(int fd, char *buffer, size_t size) { size_t i = 0; char c; ssize_t l; do { if ((l = read(fd, &c, sizeof(char))) != sizeof(char)) return l; buffer[i++] = c; } while ((i < size) && (c != '\n') && (c != '\0')); buffer[i-1] = '\0'; return (ssize_t)i; }