netbufread.c (1629B)
1 /************************************************************************* 2 * This file is part of Crosroads 1.23, a load balancer and fail over 3 * utility for TCP. Copyright (c) Karel Kubat, distributed under GPL. 4 * Visit http://crossroads.e-tunity.com for information. 5 *************************************************************************/ 6 #include "crossroads.h" 7 8 unsigned char *net_bufread (int sock, unsigned max, unsigned *nread, 9 int is_client) { 10 unsigned char *buf; 11 unsigned *bufpos, *bufmax, rest; 12 unsigned char *ret; 13 14 /* Make sure we have the buffers. */ 15 if (!clbuf) { 16 clbuf = xmalloc (TCP_BUFSZ); 17 srbuf = xmalloc (TCP_BUFSZ); 18 clbufmax = srbufmax = 0; 19 msg ("Service %s: Allocated client and server buffers", 20 activeservice->name); 21 } 22 23 if (is_client) { 24 buf = clbuf; 25 bufpos = &clbufpos; 26 bufmax = &clbufmax; 27 } else { 28 buf = srbuf; 29 bufpos = &srbufpos; 30 bufmax = &srbufmax; 31 } 32 33 /* If buffer is empty, do an actual read */ 34 if (! *bufmax) { 35 *bufmax = net_read (sock, TCP_BUFSZ, buf, is_client); 36 msg ("Service %s: Got %u bytes from %s", 37 activeservice->name, *bufmax, is_client ? "client" : "server"); 38 *bufpos = 0; 39 } 40 41 /* Got buffer contents. How much do we return? */ 42 rest = *bufmax - *bufpos; 43 44 if (rest > max) { 45 /* Caller wants less than what we have in cache. */ 46 if (nread) 47 *nread = max; 48 ret = buf + *bufpos; 49 *bufpos += max; 50 } else { 51 /* Caller wants more than what we have in cache. 52 * We'll return what we got. */ 53 if (nread) 54 *nread = rest; 55 ret = buf + *bufpos; 56 *bufmax = 0; 57 } 58 59 return (ret); 60 }