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-2010 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 #include "ctdl_module.h"
49
50 int sock_connect(char *host, char *service)
51 {
52         struct in6_addr serveraddr;
53         struct addrinfo hints;
54         struct addrinfo *res = NULL;
55         struct addrinfo *ai = NULL;
56         int rc = (-1);
57         int sock = (-1);
58
59         if ((host == NULL) || IsEmptyStr(host))
60                 return (-1);
61         if ((service == NULL) || IsEmptyStr(service))
62                 return (-1);
63
64         memset(&hints, 0x00, sizeof(hints));
65         hints.ai_flags = AI_NUMERICSERV;
66         hints.ai_family = AF_UNSPEC;
67         hints.ai_socktype = SOCK_STREAM;
68
69         /*
70          * Handle numeric IPv4 and IPv6 addresses
71          */
72         rc = inet_pton(AF_INET, host, &serveraddr);
73         if (rc == 1) {                                          /* dotted quad */
74                 hints.ai_family = AF_INET;
75                 hints.ai_flags |= AI_NUMERICHOST;
76         } else {
77                 rc = inet_pton(AF_INET6, host, &serveraddr);
78                 if (rc == 1) {                                  /* IPv6 address */
79                         hints.ai_family = AF_INET6;
80                         hints.ai_flags |= AI_NUMERICHOST;
81                 }
82         }
83
84         /* Begin the connection process */
85
86         rc = getaddrinfo(host, service, &hints, &res);
87         if (rc != 0) {
88                 CtdlLogPrintf(CTDL_ERR, "%s: %s\n", host, gai_strerror(rc));
89                 return(-1);
90         }
91
92         /*
93          * Try all available addresses until we connect to one or until we run out.
94          */
95         for (ai = res; ai != NULL; ai = ai->ai_next) {
96                 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
97                 if (sock < 0) {
98                         CtdlLogPrintf(CTDL_ERR, "socket() failed: %s\n", strerror(errno));
99                         return(-1);
100                 }
101                 rc = connect(sock, ai->ai_addr, ai->ai_addrlen);
102                 if (rc >= 0) {
103                         return(sock);
104                 }
105                 else {
106                         CtdlLogPrintf(CTDL_ERR, "connect() failed: %s\n", strerror(errno));
107                         close(sock);
108                 }
109         }
110
111         return(-1);
112 }
113
114
115
116 /*
117  * Read data from the client socket.
118  *
119  * sock         socket fd to read from
120  * buf          buffer to read into 
121  * bytes        number of bytes to read
122  * timeout      Number of seconds to wait before timing out
123  *
124  * Possible return values:
125  *      1       Requested number of bytes has been read.
126  *      0       Request timed out.
127  *      -1      Connection is broken, or other error.
128  */
129 int socket_read_blob(int *Socket, StrBuf * Target, int bytes, int timeout)
130 {
131         CitContext *CCC = MyContext();
132         const char *Error;
133         int retval = 0;
134
135
136         retval = StrBufReadBLOBBuffered(Target,
137                                         CCC->sReadBuf,
138                                         &CCC->sPos,
139                                         Socket, 1, bytes, O_TERM, &Error);
140         if (retval < 0) {
141                 CtdlLogPrintf(CTDL_CRIT,
142                               "%s failed: %s\n", __FUNCTION__, Error);
143         }
144         return retval;
145 }
146
147
148 int sock_read_to(int *sock, char *buf, int bytes, int timeout,
149                  int keep_reading_until_full)
150 {
151         CitContext *CCC = MyContext();
152         int rc;
153
154         FlushStrBuf(CCC->MigrateBuf);
155         rc = socket_read_blob(sock, CCC->sMigrateBuf, bytes, timeout);
156         if (rc < 0) {
157                 *buf = '\0';
158                 return rc;
159         } else {
160                 if (StrLength(CCC->MigrateBuf) < bytes)
161                         bytes = StrLength(CCC->MigrateBuf);
162                 memcpy(buf, ChrPtr(CCC->MigrateBuf), bytes);
163
164                 FlushStrBuf(CCC->MigrateBuf);
165                 return rc;
166         }
167 }
168
169
170 int CtdlSockGetLine(int *sock, StrBuf * Target)
171 {
172         CitContext *CCC = MyContext();
173         const char *Error;
174         int rc;
175
176         FlushStrBuf(Target);
177         rc = StrBufTCP_read_buffered_line_fast(Target,
178                                                CCC->sReadBuf,
179                                                &CCC->sPos,
180                                                sock, 5, 1, &Error);
181         if ((rc < 0) && (Error != NULL))
182                 CtdlLogPrintf(CTDL_CRIT,
183                               "%s failed: %s\n", __FUNCTION__, Error);
184         return rc;
185 }
186
187
188 /*
189  * client_getln()   ...   Get a LF-terminated line of text from the client.
190  * (This is implemented in terms of client_read() and could be
191  * justifiably moved out of sysdep.c)
192  */
193 int sock_getln(int *sock, char *buf, int bufsize)
194 {
195         int i, retval;
196         CitContext *CCC = MyContext();
197         const char *pCh;
198
199         FlushStrBuf(CCC->sMigrateBuf);
200         retval = CtdlSockGetLine(sock, CCC->sMigrateBuf);
201
202         i = StrLength(CCC->sMigrateBuf);
203         pCh = ChrPtr(CCC->sMigrateBuf);
204
205         memcpy(buf, pCh, i + 1);
206
207         FlushStrBuf(CCC->sMigrateBuf);
208         if (retval < 0) {
209                 safestrncpy(&buf[i], "000", bufsize - i);
210                 i += 3;
211         }
212         return i;
213 }
214
215
216 /*
217  * sock_read() - input binary data from socket.
218  * Returns the number of bytes read, or -1 for error.
219  */
220 INLINE int sock_read(int *sock, char *buf, int bytes,
221                      int keep_reading_until_full)
222 {
223         return sock_read_to(sock, buf, bytes, CLIENT_TIMEOUT,
224                             keep_reading_until_full);
225 }
226
227
228 /*
229  * sock_write() - send binary to server.
230  * Returns the number of bytes written, or -1 for error.
231  */
232 int sock_write(int *sock, const char *buf, int nbytes)
233 {
234         int nSuccessLess = 0;
235         int bytes_written = 0;
236         int retval;
237         fd_set rfds;
238         int fdflags;
239         int IsNonBlock;
240         int timeout = 50;
241         struct timeval tv;
242         int selectresolution = 100;
243
244         fdflags = fcntl(*sock, F_GETFL);
245         IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
246
247         while ((nSuccessLess < timeout) && 
248                (*sock != -1) && 
249                (bytes_written < nbytes)) 
250         {
251                 if (IsNonBlock){
252                         tv.tv_sec = selectresolution;
253                         tv.tv_usec = 0;
254                         
255                         FD_ZERO(&rfds);
256                         FD_SET(*sock, &rfds);
257                         if (select(*sock + 1, NULL, &rfds, NULL, &tv) == -1) {
258 ///                             *Error = strerror(errno);
259                                 close (*sock);
260                                 *sock = -1;
261                                 return -1;
262                         }
263                 }
264                 if (IsNonBlock && !  FD_ISSET(*sock, &rfds)) {
265                         nSuccessLess ++;
266                         continue;
267                 }
268                 retval = write(*sock, &buf[bytes_written],
269                                nbytes - bytes_written);
270                 if (retval < 1) {
271                         sock_close(*sock);
272                         *sock = -1;
273                         return (-1);
274                 }
275                 bytes_written = bytes_written + retval;
276         }
277         return (bytes_written);
278 }
279
280
281
282 /*
283  * client_getln()   ...   Get a LF-terminated line of text from the client.
284  * (This is implemented in terms of client_read() and could be
285  * justifiably moved out of sysdep.c)
286  */
287 int sock_getln_err(int *sock, char *buf, int bufsize, int *rc)
288 {
289         int i, retval;
290         CitContext *CCC = MyContext();
291         const char *pCh;
292
293         FlushStrBuf(CCC->sMigrateBuf);
294         *rc = retval = CtdlSockGetLine(sock, CCC->sMigrateBuf);
295
296         i = StrLength(CCC->sMigrateBuf);
297         pCh = ChrPtr(CCC->sMigrateBuf);
298
299         memcpy(buf, pCh, i + 1);
300
301         FlushStrBuf(CCC->sMigrateBuf);
302         if (retval < 0) {
303                 safestrncpy(&buf[i], "000", bufsize - i);
304                 i += 3;
305         }
306         return i;
307 }
308
309 /*
310  * Multiline version of sock_gets() ... this is a convenience function for
311  * client side protocol implementations.  It only returns the first line of
312  * a multiline response, discarding the rest.
313  */
314 int ml_sock_gets(int *sock, char *buf)
315 {
316         int rc = 0;
317         char bigbuf[1024];
318         int g;
319
320         g = sock_getln_err(sock, buf, SIZ, &rc);
321         if (rc < 0)
322                 return rc;
323         if (g < 4)
324                 return (g);
325         if (buf[3] != '-')
326                 return (g);
327
328         do {
329                 g = sock_getln_err(sock, bigbuf, SIZ, &rc);
330                 if (rc < 0)
331                         return rc;
332                 if (g < 0)
333                         return (g);
334         } while ((g >= 4) && (bigbuf[3] == '-'));
335
336         return (strlen(buf));
337 }
338
339
340 /*
341  * sock_puts() - send line to server - implemented in terms of serv_write()
342  * Returns the number of bytes written, or -1 for error.
343  */
344 int sock_puts(int *sock, char *buf)
345 {
346         int i, j;
347
348         i = sock_write(sock, buf, strlen(buf));
349         if (i < 0)
350                 return (i);
351         j = sock_write(sock, "\n", 1);
352         if (j < 0)
353                 return (j);
354         return (i + j);
355 }