bd5d46bbbbe869d28c0fdfe355c5ad86425384c7
[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-2009 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
49 #include "ctdl_module.h"
50
51 #ifndef INADDR_NONE
52 #define INADDR_NONE 0xffffffff
53 #endif
54
55 int sock_connect(char *host, char *service, char *protocol)
56 {
57         struct hostent *phe;
58         struct servent *pse;
59         struct protoent *ppe;
60         struct sockaddr_in sin;
61         struct sockaddr_in egress_sin;
62         int s, type;
63
64         if ((host == NULL) || IsEmptyStr(host)) 
65                 return(-1);
66         if ((service == NULL) || IsEmptyStr(service)) 
67                 return(-1);
68         if ((protocol == NULL) || IsEmptyStr(protocol)) 
69                 return(-1);
70
71         memset(&sin, 0, sizeof(sin));
72         sin.sin_family = AF_INET;
73
74         pse = getservbyname(service, protocol);
75         if (pse) {
76                 sin.sin_port = pse->s_port;
77         } else if ((sin.sin_port = htons((u_short) atoi(service))) == 0) {
78                 CtdlLogPrintf(CTDL_CRIT, "Can't get %s service entry: %s\n",
79                         service, strerror(errno));
80                 return(-1);
81         }
82         phe = gethostbyname(host);
83         if (phe) {
84                 memcpy(&sin.sin_addr, phe->h_addr, phe->h_length);
85         } else if ((sin.sin_addr.s_addr = inet_addr(host)) == INADDR_NONE) {
86                 CtdlLogPrintf(CTDL_ERR, "Can't get %s host entry: %s\n",
87                         host, strerror(errno));
88                 return(-1);
89         }
90         if ((ppe = getprotobyname(protocol)) == 0) {
91                 CtdlLogPrintf(CTDL_CRIT, "Can't get %s protocol entry: %s\n",
92                         protocol, strerror(errno));
93                 return(-1);
94         }
95         if (!strcmp(protocol, "udp")) {
96                 type = SOCK_DGRAM;
97         } else {
98                 type = SOCK_STREAM;
99         }
100
101         s = socket(PF_INET, type, ppe->p_proto);
102         if (s < 0) {
103                 CtdlLogPrintf(CTDL_CRIT, "Can't create socket: %s\n", strerror(errno));
104                 return(-1);
105         }
106
107         /* If citserver is bound to a specific IP address on the host, make
108          * sure we use that address for outbound connections.
109          */
110         memset(&egress_sin, 0, sizeof(egress_sin));
111         egress_sin.sin_family = AF_INET;
112         if (!IsEmptyStr(config.c_ip_addr)) {
113                 egress_sin.sin_addr.s_addr = inet_addr(config.c_ip_addr);
114                 if (egress_sin.sin_addr.s_addr == !INADDR_ANY) {
115                         egress_sin.sin_addr.s_addr = INADDR_ANY;
116                 }
117
118                 /* If this bind fails, no problem; we can still use INADDR_ANY */
119                 bind(s, (struct sockaddr *)&egress_sin, sizeof(egress_sin));
120         }
121
122         /* Now try to connect to the remote host. */
123         if (connect(s, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
124                 CtdlLogPrintf(CTDL_ERR, "Can't connect to %s:%s: %s\n",
125                         host, service, strerror(errno));
126                 close(s);
127                 return(-1);
128         }
129
130         return (s);
131 }
132
133
134
135 /*
136  * Read data from the client socket.
137  *
138  * sock         socket fd to read from
139  * buf          buffer to read into 
140  * bytes        number of bytes to read
141  * timeout      Number of seconds to wait before timing out
142  *
143  * Possible return values:
144  *      1       Requested number of bytes has been read.
145  *      0       Request timed out.
146  *      -1      Connection is broken, or other error.
147  */
148 int socket_read_blob(int *Socket, 
149                      StrBuf *Target, 
150                      int bytes, 
151                      int timeout)
152 {
153         CitContext *CCC=CC;
154         const char *Error;
155         int retval = 0;
156
157
158         retval = StrBufReadBLOBBuffered(Target, 
159                                         CCC->sReadBuf,
160                                         &CCC->sPos,
161                                         Socket,
162                                         1, 
163                                         bytes,
164                                         O_TERM,
165                                         &Error);
166         if (retval < 0) {
167                 CtdlLogPrintf(CTDL_CRIT, 
168                               "%s failed: %s\n",
169                               __FUNCTION__,
170                               Error);
171         }
172         return retval;
173 }
174
175
176 int sock_read_to(int *sock, char *buf, int bytes, int timeout, int keep_reading_until_full)
177 {
178         CitContext *CCC=CC;
179         int rc;
180
181         FlushStrBuf(CCC->MigrateBuf);
182         rc = socket_read_blob(sock, 
183                               CCC->sMigrateBuf, 
184                               bytes, 
185                               timeout);
186         if (rc < 0)
187         {
188                 *buf = '\0';
189                 return rc;
190         }
191         else
192         {
193                 if (StrLength(CCC->MigrateBuf) < bytes)
194                         bytes = StrLength(CCC->MigrateBuf);
195                 memcpy(buf, 
196                        ChrPtr(CCC->MigrateBuf),
197                        bytes);
198
199                 FlushStrBuf(CCC->MigrateBuf);
200                 return rc;
201         }
202 }
203
204
205 int CtdlSockGetLine(int *sock, StrBuf *Target)
206 {
207         CitContext *CCC=CC;
208         const char *Error;
209         int rc;
210
211         FlushStrBuf(Target);
212         rc = StrBufTCP_read_buffered_line_fast(Target, 
213                                                CCC->sReadBuf,
214                                                &CCC->sPos,
215                                                sock,
216                                                5,
217                                                1,
218                                                &Error);
219         if ((rc < 0) && (Error != NULL))
220                 CtdlLogPrintf(CTDL_CRIT, 
221                               "%s failed: %s\n",
222                               __FUNCTION__,
223                               Error);
224         return rc;
225 }
226
227
228 /*
229  * client_getln()   ...   Get a LF-terminated line of text from the client.
230  * (This is implemented in terms of client_read() and could be
231  * justifiably moved out of sysdep.c)
232  */
233 int sock_getln(int *sock, char *buf, int bufsize)
234 {
235         int i, retval;
236         CitContext *CCC=CC;
237         const char *pCh;
238
239         FlushStrBuf(CCC->sMigrateBuf);
240         retval = CtdlSockGetLine(sock, CCC->sMigrateBuf);
241
242         i = StrLength(CCC->sMigrateBuf);
243         pCh = ChrPtr(CCC->sMigrateBuf);
244         /* Strip the trailing LF, and the trailing CR if present.
245          */
246         if (bufsize <= i)
247                 i = bufsize - 1;
248         while ( (i > 0)
249                 && ( (pCh[i - 1]==13)
250                      || ( pCh[i - 1]==10)) ) {
251                 i--;
252         }
253         memcpy(buf, pCh, i);
254         buf[i] = 0;
255
256         FlushStrBuf(CCC->sMigrateBuf);
257         if (retval < 0) {
258                 safestrncpy(&buf[i], "000", bufsize - i);
259                 i += 3;
260         }
261         return i;
262 }
263
264
265 /*
266  * sock_read() - input binary data from socket.
267  * Returns the number of bytes read, or -1 for error.
268  */
269 INLINE int sock_read(int *sock, char *buf, int bytes, int keep_reading_until_full)
270 {
271         return sock_read_to(sock, buf, bytes, CLIENT_TIMEOUT, keep_reading_until_full);
272 }
273
274
275 /*
276  * sock_write() - send binary to server.
277  * Returns the number of bytes written, or -1 for error.
278  */
279 int sock_write(int *sock, const char *buf, int nbytes)
280 {
281         int bytes_written = 0;
282         int retval;
283
284         while ((*sock != -1)  && 
285                (bytes_written < nbytes))
286         {
287                 retval = write(*sock, &buf[bytes_written],
288                                nbytes - bytes_written);
289                 if (retval < 1) {
290                         sock_close(*sock);
291                         *sock = -1;
292                         return (-1);
293                 }
294                 bytes_written = bytes_written + retval;
295         }
296         return (bytes_written);
297 }
298
299
300 /*
301  * Multiline version of sock_gets() ... this is a convenience function for
302  * client side protocol implementations.  It only returns the first line of
303  * a multiline response, discarding the rest.
304  */
305 int ml_sock_gets(int *sock, char *buf) {
306         char bigbuf[1024];
307         int g;
308
309         g = sock_getln(sock, buf, SIZ);
310         if (g < 4) return(g);
311         if (buf[3] != '-') return(g);
312
313         do {
314                 g = sock_getln(sock, bigbuf, SIZ);
315                 if (g < 0) return(g);
316         } while ( (g >= 4) && (bigbuf[3] == '-') );
317
318         return(strlen(buf));
319 }
320
321
322 /*
323  * sock_puts() - send line to server - implemented in terms of serv_write()
324  * Returns the number of bytes written, or -1 for error.
325  */
326 int sock_puts(int *sock, char *buf)
327 {
328         int i, j;
329
330         i = sock_write(sock, buf, strlen(buf));
331         if (i<0) return(i);
332         j = sock_write(sock, "\n", 1);
333         if (j<0) return(j);
334         return(i+j);
335 }