clientRead.c
2.3 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <unistd.h> /* for getopt */
#include <stdlib.h> /* for exit */
#include <string.h> /* for memset and stuff */
#include <errno.h> /* for errno */
#include "include/client.h"
#include "include/monitor.h"
#define GET_MULTIPLIER(size) (((size) - 1) / READBUFSIZE + 1)
int
_clientReallocBuffer(tClient * client, unsigned int newSize)
{
unsigned int newMult = GET_MULTIPLIER(newSize);
if (CLIENTMULTMAX < newMult) {
/* line exceeds maximum line length */
return 0;
}
if (client->bufMult < newMult) {
char * newBuffer = calloc(newMult * READBUFSIZE, sizeof(char));
if (NULL == newBuffer) {
syslogMonitor(LOG_ERR, MON_CRITICAL, "calloc",
"calloc for readbuffer[%s] failed",
client->remoteAddr);
syslogMonitor(LOG_ERR, MON_FAILURE, "calloc",
"calloc for readbuffer[%s] failed - service terminated",
client->remoteAddr);
exit(EXIT_FAILURE);
}
if (NULL != client->buffer) {
memcpy(newBuffer, client->buffer, client->readPos);
free(client->buffer);
}
client->buffer = newBuffer;
client->bufMult = newMult;
}
return newMult;
}
int clientRead(tClient * client)
{
int readSize;
char readBuf[READBUFSIZE];
/*
* initialize values // read data from socket
*/
memset(readBuf, 0, READBUFSIZE);
readSize = read(client->socket, readBuf, READBUFSIZE);
switch (readSize) {
case -1:
syslogMonitor(LOG_WARNING, MON_WARNING, "socket.read",
"read returns -1 for client[%s]: %s - connection closed",
client->remoteAddr, strerror(errno));
break;
case 0:
break;
default:
if (!_clientReallocBuffer(client, client->readPos + readSize)) {
syslogMonitor(LOG_WARNING, MON_WARNING, "data.longline",
"got to long line from client[%s] - connection closed",
client->remoteAddr);
return READ_ERR_LONGLINE;
}
memcpy(client->buffer+client->readPos, readBuf, readSize);
client->readPos += readSize;
break;
}
return readSize;
}