clientRead.c 2.3 KB
#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;
}