Nonblocking sockets need to select while writing
[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 nSuccessLess = 0;
270         int bytes_written = 0;
271         int retval;
272         fd_set rfds;
273         int fdflags;
274         int IsNonBlock;
275         int timeout = 50;
276         struct timeval tv;
277         int selectresolution = 100;
278
279         fdflags = fcntl(*sock, F_GETFL);
280         IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
281
282         while ((nSuccessLess < timeout) && 
283                (*sock != -1) && 
284                (bytes_written < nbytes)) 
285         {
286                 if (IsNonBlock){
287                         tv.tv_sec = selectresolution;
288                         tv.tv_usec = 0;
289                         
290                         FD_ZERO(&rfds);
291                         FD_SET(*sock, &rfds);
292                         if (select(*sock + 1, NULL, &rfds, NULL, &tv) == -1) {
293 ///                             *Error = strerror(errno);
294                                 close (*sock);
295                                 *sock = -1;
296                                 return -1;
297                         }
298                 }
299                 if (IsNonBlock && !  FD_ISSET(*sock, &rfds)) {
300                         nSuccessLess ++;
301                         continue;
302                 }
303                 retval = write(*sock, &buf[bytes_written],
304                                nbytes - bytes_written);
305                 if (retval < 1) {
306                         sock_close(*sock);
307                         *sock = -1;
308                         return (-1);
309                 }
310                 bytes_written = bytes_written + retval;
311                 if (IsNonBlock && (bytes_written == nbytes)){
312                         tv.tv_sec = selectresolution;
313                         tv.tv_usec = 0;
314                         
315                         FD_ZERO(&rfds);
316                         FD_SET(*sock, &rfds);
317                         if (select(*sock + 1, NULL, &rfds, NULL, &tv) == -1) {
318 ///                             *Error = strerror(errno);
319                                 close (*sock);
320                                 *sock = -1;
321                                 return -1;
322                         }
323                 }
324         }
325         return (bytes_written);
326 }
327
328
329
330 /*
331  * client_getln()   ...   Get a LF-terminated line of text from the client.
332  * (This is implemented in terms of client_read() and could be
333  * justifiably moved out of sysdep.c)
334  */
335 int sock_getln_err(int *sock, char *buf, int bufsize, int *rc, int nSec)
336 {
337         int i, retval;
338         CitContext *CCC = MyContext();
339         const char *pCh;
340
341         FlushStrBuf(CCC->sMigrateBuf);
342         *rc = retval = CtdlSockGetLine(sock, CCC->sMigrateBuf, nSec);
343
344         i = StrLength(CCC->sMigrateBuf);
345         pCh = ChrPtr(CCC->sMigrateBuf);
346
347         memcpy(buf, pCh, i + 1);
348
349         FlushStrBuf(CCC->sMigrateBuf);
350         if (retval < 0) {
351                 safestrncpy(&buf[i], "000", bufsize - i);
352                 i += 3;
353         }
354         return i;
355 }
356
357 /*
358  * Multiline version of sock_gets() ... this is a convenience function for
359  * client side protocol implementations.  It only returns the first line of
360  * a multiline response, discarding the rest.
361  */
362
363 int ml_sock_gets(int *sock, char *buf, int nSec)
364 {
365         int rc = 0;
366         char bigbuf[1024];
367         int g;
368
369         g = sock_getln_err(sock, buf, SIZ, &rc, nSec);
370         if (rc < 0)
371                 return rc;
372         if (g < 4)
373                 return (g);
374         if (buf[3] != '-')
375                 return (g);
376
377         do {
378                 g = sock_getln_err(sock, bigbuf, SIZ, &rc, nSec);
379                 if (rc < 0)
380                         return rc;
381                 if (g < 0)
382                         return (g);
383         } while ((g >= 4) && (bigbuf[3] == '-'));
384
385         return(strlen(buf));
386 }
387
388
389 /*
390  * sock_puts() - send line to server - implemented in terms of serv_write()
391  * Returns the number of bytes written, or -1 for error.
392  */
393 int sock_puts(int *sock, char *buf)
394 {
395         int i, j;
396
397         i = sock_write(sock, buf, strlen(buf));
398         if (i<0) return(i);
399         j = sock_write(sock, "\n", 1);
400         if (j<0) return(j);
401         return(i+j);
402 }