* Fixed bug in webcit-to-citadel IPv6/IPv4 connectivity
[citadel.git] / citadel / clientsocket.c
1 /*
2  * $Id$
3  *
4  * This module handles client-side sockets opened by the Citadel server (for
5  * the client side of Internet protocols, etc.)   It does _not_ handle client
6  * sockets for the Citadel client; for that you must look in ipc_c_tcp.c
7  * (which, uncoincidentally, bears a striking similarity to this file).
8  *
9  * Copyright (c) 1987-2010 by the citadel.org team
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 3 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
24  */
25
26 #include "sysdep.h"
27 #include <stdlib.h>
28 #include <unistd.h>
29 #include <stdio.h>
30 #include <signal.h>
31 #include <sys/types.h>
32 #include <sys/time.h>
33 #include <sys/socket.h>
34 #include <netinet/in.h>
35 #include <arpa/inet.h>
36 #include <netdb.h>
37 #include <string.h>
38 #include <pwd.h>
39 #include <errno.h>
40 #include <stdarg.h>
41 #include <libcitadel.h>
42 #include "citadel.h"
43 #include "server.h"
44 #ifndef HAVE_SNPRINTF
45 #include "snprintf.h"
46 #endif
47 #include "sysdep_decls.h"
48 #include "config.h"
49 #include "clientsocket.h"
50 #include "ctdl_module.h"
51
52 int sock_connect(char *host, char *service)
53 {
54         struct in6_addr serveraddr;
55         struct addrinfo hints;
56         struct addrinfo *res = NULL;
57         struct addrinfo *ai = NULL;
58         int rc = (-1);
59         int sock = (-1);
60
61         if ((host == NULL) || IsEmptyStr(host))
62                 return (-1);
63         if ((service == NULL) || IsEmptyStr(service))
64                 return (-1);
65
66         memset(&hints, 0x00, sizeof(hints));
67         hints.ai_flags = AI_NUMERICSERV;
68         hints.ai_family = AF_UNSPEC;
69         hints.ai_socktype = SOCK_STREAM;
70
71         /*
72          * Handle numeric IPv4 and IPv6 addresses
73          */
74         rc = inet_pton(AF_INET, host, &serveraddr);
75         if (rc == 1) {                                          /* dotted quad */
76                 hints.ai_family = AF_INET;
77                 hints.ai_flags |= AI_NUMERICHOST;
78         } else {
79                 rc = inet_pton(AF_INET6, host, &serveraddr);
80                 if (rc == 1) {                                  /* IPv6 address */
81                         hints.ai_family = AF_INET6;
82                         hints.ai_flags |= AI_NUMERICHOST;
83                 }
84         }
85
86         /* Begin the connection process */
87
88         rc = getaddrinfo(host, service, &hints, &res);
89         if (rc != 0) {
90                 CtdlLogPrintf(CTDL_ERR, "%s: %s\n", host, gai_strerror(rc));
91                 return(-1);
92         }
93
94         /*
95          * Try all available addresses until we connect to one or until we run out.
96          */
97         for (ai = res; ai != NULL; ai = ai->ai_next) {
98                 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
99                 if (sock < 0) {
100                         CtdlLogPrintf(CTDL_ERR, "socket() failed: %s\n", strerror(errno));
101                         return(-1);
102                 }
103                 rc = connect(sock, ai->ai_addr, ai->ai_addrlen);
104                 if (rc >= 0) {
105                         return(sock);
106                 }
107                 else {
108                         CtdlLogPrintf(CTDL_ERR, "connect() failed: %s\n", strerror(errno));
109                         close(sock);
110                 }
111         }
112
113         return(-1);
114 }
115
116
117
118 /*
119  * Read data from the client socket.
120  *
121  * sock         socket fd to read from
122  * buf          buffer to read into 
123  * bytes        number of bytes to read
124  * timeout      Number of seconds to wait before timing out
125  *
126  * Possible return values:
127  *      1       Requested number of bytes has been read.
128  *      0       Request timed out.
129  *      -1      Connection is broken, or other error.
130  */
131 int socket_read_blob(int *Socket, StrBuf * Target, int bytes, int timeout)
132 {
133         CitContext *CCC = MyContext();
134         const char *Error;
135         int retval = 0;
136
137
138         retval = StrBufReadBLOBBuffered(Target,
139                                         CCC->sReadBuf,
140                                         &CCC->sPos,
141                                         Socket, 1, bytes, O_TERM, &Error);
142         if (retval < 0) {
143                 CtdlLogPrintf(CTDL_CRIT,
144                               "%s failed: %s\n", __FUNCTION__, Error);
145         }
146         return retval;
147 }
148
149
150 int sock_read_to(int *sock, char *buf, int bytes, int timeout,
151                  int keep_reading_until_full)
152 {
153         CitContext *CCC = MyContext();
154         int rc;
155
156         FlushStrBuf(CCC->MigrateBuf);
157         rc = socket_read_blob(sock, CCC->sMigrateBuf, bytes, timeout);
158         if (rc < 0) {
159                 *buf = '\0';
160                 return rc;
161         } else {
162                 if (StrLength(CCC->MigrateBuf) < bytes)
163                         bytes = StrLength(CCC->MigrateBuf);
164                 memcpy(buf, ChrPtr(CCC->MigrateBuf), bytes);
165
166                 FlushStrBuf(CCC->MigrateBuf);
167                 return rc;
168         }
169 }
170
171
172 int CtdlSockGetLine(int *sock, StrBuf * Target)
173 {
174         CitContext *CCC = MyContext();
175         const char *Error;
176         int rc;
177
178         FlushStrBuf(Target);
179         rc = StrBufTCP_read_buffered_line_fast(Target,
180                                                CCC->sReadBuf,
181                                                &CCC->sPos,
182                                                sock, 5, 1, &Error);
183         if ((rc < 0) && (Error != NULL))
184                 CtdlLogPrintf(CTDL_CRIT,
185                               "%s failed: %s\n", __FUNCTION__, Error);
186         return rc;
187 }
188
189
190 /*
191  * client_getln()   ...   Get a LF-terminated line of text from the client.
192  * (This is implemented in terms of client_read() and could be
193  * justifiably moved out of sysdep.c)
194  */
195 int sock_getln(int *sock, char *buf, int bufsize)
196 {
197         int i, retval;
198         CitContext *CCC = MyContext();
199         const char *pCh;
200
201         FlushStrBuf(CCC->sMigrateBuf);
202         retval = CtdlSockGetLine(sock, CCC->sMigrateBuf);
203
204         i = StrLength(CCC->sMigrateBuf);
205         pCh = ChrPtr(CCC->sMigrateBuf);
206         /* Strip the trailing LF, and the trailing CR if present.
207          */
208         if (bufsize <= i)
209                 i = bufsize - 1;
210         while ((i > 0)
211                && ((pCh[i - 1] == 13)
212                    || (pCh[i - 1] == 10))) {
213                 i--;
214         }
215         memcpy(buf, pCh, i);
216         buf[i] = 0;
217
218         FlushStrBuf(CCC->sMigrateBuf);
219         if (retval < 0) {
220                 safestrncpy(&buf[i], "000", bufsize - i);
221                 i += 3;
222         }
223         return i;
224 }
225
226
227 /*
228  * sock_read() - input binary data from socket.
229  * Returns the number of bytes read, or -1 for error.
230  */
231 INLINE int sock_read(int *sock, char *buf, int bytes,
232                      int keep_reading_until_full)
233 {
234         return sock_read_to(sock, buf, bytes, CLIENT_TIMEOUT,
235                             keep_reading_until_full);
236 }
237
238
239 /*
240  * sock_write() - send binary to server.
241  * Returns the number of bytes written, or -1 for error.
242  */
243 int sock_write(int *sock, const char *buf, int nbytes)
244 {
245         int bytes_written = 0;
246         int retval;
247
248         while ((*sock != -1) && (bytes_written < nbytes)) {
249                 retval = write(*sock, &buf[bytes_written],
250                                nbytes - bytes_written);
251                 if (retval < 1) {
252                         sock_close(*sock);
253                         *sock = -1;
254                         return (-1);
255                 }
256                 bytes_written = bytes_written + retval;
257         }
258         return (bytes_written);
259 }
260
261
262 /*
263  * Multiline version of sock_gets() ... this is a convenience function for
264  * client side protocol implementations.  It only returns the first line of
265  * a multiline response, discarding the rest.
266  */
267 int ml_sock_gets(int *sock, char *buf)
268 {
269         char bigbuf[1024];
270         int g;
271
272         g = sock_getln(sock, buf, SIZ);
273         if (g < 4)
274                 return (g);
275         if (buf[3] != '-')
276                 return (g);
277
278         do {
279                 g = sock_getln(sock, bigbuf, SIZ);
280                 if (g < 0)
281                         return (g);
282         } while ((g >= 4) && (bigbuf[3] == '-'));
283
284         return (strlen(buf));
285 }
286
287
288 /*
289  * sock_puts() - send line to server - implemented in terms of serv_write()
290  * Returns the number of bytes written, or -1 for error.
291  */
292 int sock_puts(int *sock, char *buf)
293 {
294         int i, j;
295
296         i = sock_write(sock, buf, strlen(buf));
297         if (i < 0)
298                 return (i);
299         j = sock_write(sock, "\n", 1);
300         if (j < 0)
301                 return (j);
302         return (i + j);
303 }