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