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