summaryrefslogtreecommitdiff
path: root/util.c
blob: 9d9c5d3687b34b962474752b80f864b2aeae14b1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#define _GNU_SOURCE
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/socket.h>
#include <errno.h>
#include "memory.h"
#include "util.h"


char* copy_buf(char *buf,int len){
	char *dst=malloc(len+1,char);
	memcpy(dst,buf,len);
	dst[len]='\0';
	return dst;
}

char* copy_str(char *str){
	return copy_buf(str,strlen(str));
}

void str_toupper(char *str){
	while(*str!='\0'){
		*str=toupper(*str);
		str++;
	}
}


// Returns -1 on error, 0 on success
int sendall(int sock,const char *buf,ssize_t len){
	if(len==-1){
		len=strlen(buf);
	}

	ssize_t sent=0;
	while(sent<len){
		ssize_t ret=send(sock,buf+sent,len-sent,0);
		if(ret<0){
			if(errno==EINTR){
				continue;
			} else {
				return -1;
			}
		}
		sent+=ret;
	}

	return 0;
}

__attribute__((format (printf, 2, 3)))
int sendallf(int sock,const char *format,...){
	va_list ap;
	va_start(ap,format);
	char *buf;
	int len=vasprintf(&buf,format,ap);
	va_end(ap);
	if(len<0){
		return -1;
	}
	int ret=sendall(sock,buf,len);
	free(buf);
	return ret;
}