* Replaced sock_connect() with a new version that can connect to both IPv4 and IPv6...
[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, *res = NULL;
56         int rc;
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         sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
93         if (sock < 0) {
94                 CtdlLogPrintf(CTDL_ERR, "socket() failed: %s\n", strerror(errno));
95                 return(-1);
96         }
97
98         rc = connect(sock, res->ai_addr, res->ai_addrlen);
99         if (rc < 0) {
100                 /*
101                  * Note: the res is a linked list of addresses found for server.
102                  * If the connect() fails to the first one, subsequent addresses
103                  * (if any) in the list could be tried if desired.
104                  */
105                 CtdlLogPrintf(CTDL_ERR, "connect() failed: %s\n", strerror(errno));
106                 return(-1);
107         }
108
109         return (sock);
110 }
111
112
113
114 /*
115  * Read data from the client socket.
116  *
117  * sock         socket fd to read from
118  * buf          buffer to read into 
119  * bytes        number of bytes to read
120  * timeout      Number of seconds to wait before timing out
121  *
122  * Possible return values:
123  *      1       Requested number of bytes has been read.
124  *      0       Request timed out.
125  *      -1      Connection is broken, or other error.
126  */
127 int socket_read_blob(int *Socket, StrBuf * Target, int bytes, int timeout)
128 {
129         CitContext *CCC = MyContext();
130         const char *Error;
131         int retval = 0;
132
133
134         retval = StrBufReadBLOBBuffered(Target,
135                                         CCC->sReadBuf,
136                                         &CCC->sPos,
137                                         Socket, 1, bytes, O_TERM, &Error);
138         if (retval < 0) {
139                 CtdlLogPrintf(CTDL_CRIT,
140                               "%s failed: %s\n", __FUNCTION__, Error);
141         }
142         return retval;
143 }
144
145
146 int sock_read_to(int *sock, char *buf, int bytes, int timeout,
147                  int keep_reading_until_full)
148 {
149         CitContext *CCC = MyContext();
150         int rc;
151
152         FlushStrBuf(CCC->MigrateBuf);
153         rc = socket_read_blob(sock, CCC->sMigrateBuf, bytes, timeout);
154         if (rc < 0) {
155                 *buf = '\0';
156                 return rc;
157         } else {
158                 if (StrLength(CCC->MigrateBuf) < bytes)
159                         bytes = StrLength(CCC->MigrateBuf);
160                 memcpy(buf, ChrPtr(CCC->MigrateBuf), bytes);
161
162                 FlushStrBuf(CCC->MigrateBuf);
163                 return rc;
164         }
165 }
166
167
168 int CtdlSockGetLine(int *sock, StrBuf * Target)
169 {
170         CitContext *CCC = MyContext();
171         const char *Error;
172         int rc;
173
174         FlushStrBuf(Target);
175         rc = StrBufTCP_read_buffered_line_fast(Target,
176                                                CCC->sReadBuf,
177                                                &CCC->sPos,
178                                                sock, 5, 1, &Error);
179         if ((rc < 0) && (Error != NULL))
180                 CtdlLogPrintf(CTDL_CRIT,
181                               "%s failed: %s\n", __FUNCTION__, Error);
182         return rc;
183 }
184
185
186 /*
187  * client_getln()   ...   Get a LF-terminated line of text from the client.
188  * (This is implemented in terms of client_read() and could be
189  * justifiably moved out of sysdep.c)
190  */
191 int sock_getln(int *sock, char *buf, int bufsize)
192 {
193         int i, retval;
194         CitContext *CCC = MyContext();
195         const char *pCh;
196
197         FlushStrBuf(CCC->sMigrateBuf);
198         retval = CtdlSockGetLine(sock, CCC->sMigrateBuf);
199
200         i = StrLength(CCC->sMigrateBuf);
201         pCh = ChrPtr(CCC->sMigrateBuf);
202         /* Strip the trailing LF, and the trailing CR if present.
203          */
204         if (bufsize <= i)
205                 i = bufsize - 1;
206         while ((i > 0)
207                && ((pCh[i - 1] == 13)
208                    || (pCh[i - 1] == 10))) {
209                 i--;
210         }
211         memcpy(buf, pCh, i);
212         buf[i] = 0;
213
214         FlushStrBuf(CCC->sMigrateBuf);
215         if (retval < 0) {
216                 safestrncpy(&buf[i], "000", bufsize - i);
217                 i += 3;
218         }
219         return i;
220 }
221
222
223 /*
224  * sock_read() - input binary data from socket.
225  * Returns the number of bytes read, or -1 for error.
226  */
227 INLINE int sock_read(int *sock, char *buf, int bytes,
228                      int keep_reading_until_full)
229 {
230         return sock_read_to(sock, buf, bytes, CLIENT_TIMEOUT,
231                             keep_reading_until_full);
232 }
233
234
235 /*
236  * sock_write() - send binary to server.
237  * Returns the number of bytes written, or -1 for error.
238  */
239 int sock_write(int *sock, const char *buf, int nbytes)
240 {
241         int bytes_written = 0;
242         int retval;
243
244         while ((*sock != -1) && (bytes_written < nbytes)) {
245                 retval = write(*sock, &buf[bytes_written],
246                                nbytes - bytes_written);
247                 if (retval < 1) {
248                         sock_close(*sock);
249                         *sock = -1;
250                         return (-1);
251                 }
252                 bytes_written = bytes_written + retval;
253         }
254         return (bytes_written);
255 }
256
257
258 /*
259  * Multiline version of sock_gets() ... this is a convenience function for
260  * client side protocol implementations.  It only returns the first line of
261  * a multiline response, discarding the rest.
262  */
263 int ml_sock_gets(int *sock, char *buf)
264 {
265         char bigbuf[1024];
266         int g;
267
268         g = sock_getln(sock, buf, SIZ);
269         if (g < 4)
270                 return (g);
271         if (buf[3] != '-')
272                 return (g);
273
274         do {
275                 g = sock_getln(sock, bigbuf, SIZ);
276                 if (g < 0)
277                         return (g);
278         } while ((g >= 4) && (bigbuf[3] == '-'));
279
280         return (strlen(buf));
281 }
282
283
284 /*
285  * sock_puts() - send line to server - implemented in terms of serv_write()
286  * Returns the number of bytes written, or -1 for error.
287  */
288 int sock_puts(int *sock, char *buf)
289 {
290         int i, j;
291
292         i = sock_write(sock, buf, strlen(buf));
293         if (i < 0)
294                 return (i);
295         j = sock_write(sock, "\n", 1);
296         if (j < 0)
297                 return (j);
298         return (i + j);
299 }