Began removing $Id$ tags. This will be an ongoing process.
[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         /* Strip the trailing LF, and the trailing CR if present.
205          */
206         if (bufsize <= i)
207                 i = bufsize - 1;
208         while ((i > 0)
209                && ((pCh[i - 1] == 13)
210                    || (pCh[i - 1] == 10))) {
211                 i--;
212         }
213         memcpy(buf, pCh, i);
214         buf[i] = 0;
215
216         FlushStrBuf(CCC->sMigrateBuf);
217         if (retval < 0) {
218                 safestrncpy(&buf[i], "000", bufsize - i);
219                 i += 3;
220         }
221         return i;
222 }
223
224
225 /*
226  * sock_read() - input binary data from socket.
227  * Returns the number of bytes read, or -1 for error.
228  */
229 INLINE int sock_read(int *sock, char *buf, int bytes,
230                      int keep_reading_until_full)
231 {
232         return sock_read_to(sock, buf, bytes, CLIENT_TIMEOUT,
233                             keep_reading_until_full);
234 }
235
236
237 /*
238  * sock_write() - send binary to server.
239  * Returns the number of bytes written, or -1 for error.
240  */
241 int sock_write(int *sock, const char *buf, int nbytes)
242 {
243         int bytes_written = 0;
244         int retval;
245
246         while ((*sock != -1) && (bytes_written < nbytes)) {
247                 retval = write(*sock, &buf[bytes_written],
248                                nbytes - bytes_written);
249                 if (retval < 1) {
250                         sock_close(*sock);
251                         *sock = -1;
252                         return (-1);
253                 }
254                 bytes_written = bytes_written + retval;
255         }
256         return (bytes_written);
257 }
258
259
260 /*
261  * Multiline version of sock_gets() ... this is a convenience function for
262  * client side protocol implementations.  It only returns the first line of
263  * a multiline response, discarding the rest.
264  */
265 int ml_sock_gets(int *sock, char *buf)
266 {
267         char bigbuf[1024];
268         int g;
269
270         g = sock_getln(sock, buf, SIZ);
271         if (g < 4)
272                 return (g);
273         if (buf[3] != '-')
274                 return (g);
275
276         do {
277                 g = sock_getln(sock, bigbuf, SIZ);
278                 if (g < 0)
279                         return (g);
280         } while ((g >= 4) && (bigbuf[3] == '-'));
281
282         return (strlen(buf));
283 }
284
285
286 /*
287  * sock_puts() - send line to server - implemented in terms of serv_write()
288  * Returns the number of bytes written, or -1 for error.
289  */
290 int sock_puts(int *sock, char *buf)
291 {
292         int i, j;
293
294         i = sock_write(sock, buf, strlen(buf));
295         if (i < 0)
296                 return (i);
297         j = sock_write(sock, "\n", 1);
298         if (j < 0)
299                 return (j);
300         return (i + j);
301 }