have flexible timouts while reading lines in our client mode connections
[citadel.git] / citadel / clientsocket.c
1 /*
2  * This module handles client-side sockets opened by the Citadel server (for
3  * the client side of Internet protocols, etc.)   It does _not_ handle client
4  * sockets for the Citadel client; for that you must look in ipc_c_tcp.c
5  * (which, uncoincidentally, bears a striking similarity to this file).
6  *
7  * Copyright (c) 1987-2009 by the citadel.org team
8  *
9  *  This program is free software; you can redistribute it and/or modify
10  *  it under the terms of the GNU General Public License as published by
11  *  the Free Software Foundation; either version 3 of the License, or
12  *  (at your option) any later version.
13  *
14  *  This program is distributed in the hope that it will be useful,
15  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  *  GNU General Public License for more details.
18  *
19  *  You should have received a copy of the GNU General Public License
20  *  along with this program; if not, write to the Free Software
21  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  */
23
24 #include "sysdep.h"
25 #include <stdlib.h>
26 #include <unistd.h>
27 #include <stdio.h>
28 #include <signal.h>
29 #include <sys/types.h>
30 #include <sys/time.h>
31 #include <sys/socket.h>
32 #include <netinet/in.h>
33 #include <arpa/inet.h>
34 #include <netdb.h>
35 #include <string.h>
36 #include <pwd.h>
37 #include <errno.h>
38 #include <stdarg.h>
39 #include <libcitadel.h>
40 #include "citadel.h"
41 #include "server.h"
42 #ifndef HAVE_SNPRINTF
43 #include "snprintf.h"
44 #endif
45 #include "sysdep_decls.h"
46 #include "config.h"
47 #include "clientsocket.h"
48
49 #include "ctdl_module.h"
50
51 #ifndef INADDR_NONE
52 #define INADDR_NONE 0xffffffff
53 #endif
54
55 int sock_connect(char *host, char *service, char *protocol)
56 {
57         struct hostent *phe;
58         struct servent *pse;
59         struct protoent *ppe;
60         struct sockaddr_in sin;
61         struct sockaddr_in egress_sin;
62         int s, type;
63
64         if ((host == NULL) || IsEmptyStr(host)) 
65                 return(-1);
66         if ((service == NULL) || IsEmptyStr(service)) 
67                 return(-1);
68         if ((protocol == NULL) || IsEmptyStr(protocol)) 
69                 return(-1);
70
71         memset(&sin, 0, sizeof(sin));
72         sin.sin_family = AF_INET;
73
74         pse = getservbyname(service, protocol);
75         if (pse) {
76                 sin.sin_port = pse->s_port;
77         } else if ((sin.sin_port = htons((u_short) atoi(service))) == 0) {
78                 CtdlLogPrintf(CTDL_CRIT, "Can't get %s service entry: %s\n",
79                         service, strerror(errno));
80                 return(-1);
81         }
82         phe = gethostbyname(host);
83         if (phe) {
84                 memcpy(&sin.sin_addr, phe->h_addr, phe->h_length);
85         } else if ((sin.sin_addr.s_addr = inet_addr(host)) == INADDR_NONE) {
86                 CtdlLogPrintf(CTDL_ERR, "Can't get %s host entry: %s\n",
87                         host, strerror(errno));
88                 return(-1);
89         }
90         if ((ppe = getprotobyname(protocol)) == 0) {
91                 CtdlLogPrintf(CTDL_CRIT, "Can't get %s protocol entry: %s\n",
92                         protocol, strerror(errno));
93                 return(-1);
94         }
95         if (!strcmp(protocol, "udp")) {
96                 type = SOCK_DGRAM;
97         } else {
98                 type = SOCK_STREAM;
99         }
100
101         s = socket(PF_INET, type, ppe->p_proto);
102         if (s < 0) {
103                 CtdlLogPrintf(CTDL_CRIT, "Can't create socket: %s\n", strerror(errno));
104                 return(-1);
105         }
106
107         /* If citserver is bound to a specific IP address on the host, make
108          * sure we use that address for outbound connections.
109          */
110         memset(&egress_sin, 0, sizeof(egress_sin));
111         egress_sin.sin_family = AF_INET;
112         if (!IsEmptyStr(config.c_ip_addr)) {
113                 egress_sin.sin_addr.s_addr = inet_addr(config.c_ip_addr);
114                 if (egress_sin.sin_addr.s_addr == !INADDR_ANY) {
115                         egress_sin.sin_addr.s_addr = INADDR_ANY;
116                 }
117
118                 /* If this bind fails, no problem; we can still use INADDR_ANY */
119                 bind(s, (struct sockaddr *)&egress_sin, sizeof(egress_sin));
120         }
121
122         /* Now try to connect to the remote host. */
123         if (connect(s, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
124                 CtdlLogPrintf(CTDL_ERR, "Can't connect to %s:%s: %s\n",
125                         host, service, strerror(errno));
126                 close(s);
127                 return(-1);
128         }
129
130         return (s);
131 }
132
133
134
135 /*
136  * Read data from the client socket.
137  *
138  * sock         socket fd to read from
139  * buf          buffer to read into 
140  * bytes        number of bytes to read
141  * timeout      Number of seconds to wait before timing out
142  *
143  * Possible return values:
144  *      1       Requested number of bytes has been read.
145  *      0       Request timed out.
146  *      -1      Connection is broken, or other error.
147  */
148 int socket_read_blob(int *Socket, 
149                      StrBuf *Target, 
150                      int bytes, 
151                      int timeout)
152 {
153         CitContext *CCC=CC;
154         const char *Error;
155         int retval = 0;
156
157
158         retval = StrBufReadBLOBBuffered(Target, 
159                                         CCC->sReadBuf,
160                                         &CCC->sPos,
161                                         Socket,
162                                         1, 
163                                         bytes,
164                                         O_TERM,
165                                         &Error);
166         if (retval < 0) {
167                 CtdlLogPrintf(CTDL_CRIT, 
168                               "%s failed: %s\n",
169                               __FUNCTION__,
170                               Error);
171         }
172         return retval;
173 }
174
175
176 int sock_read_to(int *sock, char *buf, int bytes, int timeout, int keep_reading_until_full)
177 {
178         CitContext *CCC=CC;
179         int rc;
180
181         FlushStrBuf(CCC->MigrateBuf);
182         rc = socket_read_blob(sock, 
183                               CCC->sMigrateBuf, 
184                               bytes, 
185                               timeout);
186         if (rc < 0)
187         {
188                 *buf = '\0';
189                 return rc;
190         }
191         else
192         {
193                 if (StrLength(CCC->MigrateBuf) < bytes)
194                         bytes = StrLength(CCC->MigrateBuf);
195                 memcpy(buf, 
196                        ChrPtr(CCC->MigrateBuf),
197                        bytes);
198
199                 FlushStrBuf(CCC->MigrateBuf);
200                 return rc;
201         }
202 }
203
204
205 int CtdlSockGetLine(int *sock, StrBuf * Target, int nSec)
206 {
207         CitContext *CCC=CC;
208         const char *Error;
209         int rc;
210
211         FlushStrBuf(Target);
212         rc = StrBufTCP_read_buffered_line_fast(Target, 
213                                                CCC->sReadBuf,
214                                                &CCC->sPos,
215                                                sock, nSec, 1, &Error);
216         if ((rc < 0) && (Error != NULL))
217                 CtdlLogPrintf(CTDL_CRIT, 
218                               "%s failed: %s\n",
219                               __FUNCTION__,
220                               Error);
221         return rc;
222 }
223
224
225 /*
226  * client_getln()   ...   Get a LF-terminated line of text from the client.
227  * (This is implemented in terms of client_read() and could be
228  * justifiably moved out of sysdep.c)
229  */
230 int sock_getln(int *sock, char *buf, int bufsize)
231 {
232         int i, retval;
233         CitContext *CCC=CC;
234         const char *pCh;
235
236         FlushStrBuf(CCC->sMigrateBuf);
237         retval = CtdlSockGetLine(sock, CCC->sMigrateBuf, 5);
238
239         i = StrLength(CCC->sMigrateBuf);
240         pCh = ChrPtr(CCC->sMigrateBuf);
241
242         memcpy(buf, pCh, i + 1);
243
244         FlushStrBuf(CCC->sMigrateBuf);
245         if (retval < 0) {
246                 safestrncpy(&buf[i], "000", bufsize - i);
247                 i += 3;
248         }
249         return i;
250 }
251
252
253 /*
254  * sock_read() - input binary data from socket.
255  * Returns the number of bytes read, or -1 for error.
256  */
257 INLINE int sock_read(int *sock, char *buf, int bytes, int keep_reading_until_full)
258 {
259         return sock_read_to(sock, buf, bytes, CLIENT_TIMEOUT, keep_reading_until_full);
260 }
261
262
263 /*
264  * sock_write() - send binary to server.
265  * Returns the number of bytes written, or -1 for error.
266  */
267 int sock_write(int *sock, const char *buf, int nbytes)
268 {
269         int bytes_written = 0;
270         int retval;
271
272         while ((*sock != -1)  && 
273                (bytes_written < nbytes))
274         {
275                 retval = write(*sock, &buf[bytes_written],
276                                nbytes - bytes_written);
277                 if (retval < 1) {
278                         sock_close(*sock);
279                         *sock = -1;
280                         return (-1);
281                 }
282                 bytes_written = bytes_written + retval;
283                 if (IsNonBlock && (bytes_written == nbytes)){
284                         tv.tv_sec = selectresolution;
285                         tv.tv_usec = 0;
286                         
287                         FD_ZERO(&rfds);
288                         FD_SET(*sock, &rfds);
289                         if (select(*sock + 1, NULL, &rfds, NULL, &tv) == -1) {
290 ///                             *Error = strerror(errno);
291                                 close (*sock);
292                                 *sock = -1;
293                                 return -1;
294                         }
295                 }
296         }
297         return (bytes_written);
298 }
299
300
301
302 /*
303  * client_getln()   ...   Get a LF-terminated line of text from the client.
304  * (This is implemented in terms of client_read() and could be
305  * justifiably moved out of sysdep.c)
306  */
307 int sock_getln_err(int *sock, char *buf, int bufsize, int *rc, int nSec)
308 {
309         int i, retval;
310         CitContext *CCC = MyContext();
311         const char *pCh;
312
313         FlushStrBuf(CCC->sMigrateBuf);
314         *rc = retval = CtdlSockGetLine(sock, CCC->sMigrateBuf, nSec);
315
316         i = StrLength(CCC->sMigrateBuf);
317         pCh = ChrPtr(CCC->sMigrateBuf);
318
319         memcpy(buf, pCh, i + 1);
320
321         FlushStrBuf(CCC->sMigrateBuf);
322         if (retval < 0) {
323                 safestrncpy(&buf[i], "000", bufsize - i);
324                 i += 3;
325         }
326         return i;
327 }
328
329 /*
330  * Multiline version of sock_gets() ... this is a convenience function for
331  * client side protocol implementations.  It only returns the first line of
332  * a multiline response, discarding the rest.
333  */
334
335 int ml_sock_gets(int *sock, char *buf, int nSec)
336 {
337         int rc = 0;
338         char bigbuf[1024];
339         int g;
340
341         g = sock_getln_err(sock, buf, SIZ, &rc, nSec);
342         if (rc < 0)
343                 return rc;
344         if (g < 4)
345                 return (g);
346         if (buf[3] != '-')
347                 return (g);
348
349         do {
350                 g = sock_getln_err(sock, bigbuf, SIZ, &rc, nSec);
351                 if (rc < 0)
352                         return rc;
353                 if (g < 0)
354                         return (g);
355         } while ((g >= 4) && (bigbuf[3] == '-'));
356
357         return(strlen(buf));
358 }
359
360
361 /*
362  * sock_puts() - send line to server - implemented in terms of serv_write()
363  * Returns the number of bytes written, or -1 for error.
364  */
365 int sock_puts(int *sock, char *buf)
366 {
367         int i, j;
368
369         i = sock_write(sock, buf, strlen(buf));
370         if (i<0) return(i);
371         j = sock_write(sock, "\n", 1);
372         if (j<0) return(j);
373         return(i+j);
374 }