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