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