Memleak: sock_connect() needs to call freeaddrinfo()
[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                         freeaddrinfo(res);
100                         return(-1);
101                 }
102                 rc = connect(sock, ai->ai_addr, ai->ai_addrlen);
103                 if (rc >= 0) {
104                         freeaddrinfo(res);
105                         return(sock);
106                 }
107                 else {
108                         CtdlLogPrintf(CTDL_ERR, "connect() failed: %s\n", strerror(errno));
109                         close(sock);
110                 }
111         }
112         freeaddrinfo(res);
113         return(-1);
114 }
115
116
117
118 /*
119  * Read data from the client socket.
120  *
121  * sock         socket fd to read from
122  * buf          buffer to read into 
123  * bytes        number of bytes to read
124  * timeout      Number of seconds to wait before timing out
125  *
126  * Possible return values:
127  *      1       Requested number of bytes has been read.
128  *      0       Request timed out.
129  *      -1      Connection is broken, or other error.
130  */
131 int socket_read_blob(int *Socket, StrBuf * Target, int bytes, int timeout)
132 {
133         CitContext *CCC = MyContext();
134         const char *Error;
135         int retval = 0;
136
137
138         retval = StrBufReadBLOBBuffered(Target,
139                                         CCC->sReadBuf,
140                                         &CCC->sPos,
141                                         Socket, 1, bytes, O_TERM, &Error);
142         if (retval < 0) {
143                 CtdlLogPrintf(CTDL_CRIT,
144                               "%s failed: %s\n", __FUNCTION__, Error);
145         }
146         return retval;
147 }
148
149
150 int sock_read_to(int *sock, char *buf, int bytes, int timeout,
151                  int keep_reading_until_full)
152 {
153         CitContext *CCC = MyContext();
154         int rc;
155
156         FlushStrBuf(CCC->MigrateBuf);
157         rc = socket_read_blob(sock, CCC->sMigrateBuf, bytes, timeout);
158         if (rc < 0) {
159                 *buf = '\0';
160                 return rc;
161         } else {
162                 if (StrLength(CCC->MigrateBuf) < bytes)
163                         bytes = StrLength(CCC->MigrateBuf);
164                 memcpy(buf, ChrPtr(CCC->MigrateBuf), bytes);
165
166                 FlushStrBuf(CCC->MigrateBuf);
167                 return rc;
168         }
169 }
170
171
172 int CtdlSockGetLine(int *sock, StrBuf * Target, int nSec)
173 {
174         CitContext *CCC = MyContext();
175         const char *Error;
176         int rc;
177
178         FlushStrBuf(Target);
179         rc = StrBufTCP_read_buffered_line_fast(Target,
180                                                CCC->sReadBuf,
181                                                &CCC->sPos,
182                                                sock, nSec, 1, &Error);
183         if ((rc < 0) && (Error != NULL))
184                 CtdlLogPrintf(CTDL_CRIT,
185                               "%s failed: %s\n", __FUNCTION__, Error);
186         return rc;
187 }
188
189
190 /*
191  * client_getln()   ...   Get a LF-terminated line of text from the client.
192  * (This is implemented in terms of client_read() and could be
193  * justifiably moved out of sysdep.c)
194  */
195 int sock_getln(int *sock, char *buf, int bufsize)
196 {
197         int i, retval;
198         CitContext *CCC = MyContext();
199         const char *pCh;
200
201         FlushStrBuf(CCC->sMigrateBuf);
202         retval = CtdlSockGetLine(sock, CCC->sMigrateBuf, 5);
203
204         i = StrLength(CCC->sMigrateBuf);
205         pCh = ChrPtr(CCC->sMigrateBuf);
206
207         memcpy(buf, pCh, i + 1);
208
209         FlushStrBuf(CCC->sMigrateBuf);
210         if (retval < 0) {
211                 safestrncpy(&buf[i], "000", bufsize - i);
212                 i += 3;
213         }
214         return i;
215 }
216
217
218 /*
219  * sock_read() - input binary data from socket.
220  * Returns the number of bytes read, or -1 for error.
221  */
222 INLINE int sock_read(int *sock, char *buf, int bytes,
223                      int keep_reading_until_full)
224 {
225         return sock_read_to(sock, buf, bytes, CLIENT_TIMEOUT,
226                             keep_reading_until_full);
227 }
228
229
230 /*
231  * sock_write() - send binary to server.
232  * Returns the number of bytes written, or -1 for error.
233  */
234 int sock_write(int *sock, const char *buf, int nbytes)
235 {
236         int nSuccessLess = 0;
237         int bytes_written = 0;
238         int retval;
239         fd_set rfds;
240         int fdflags;
241         int IsNonBlock;
242         int timeout = 50;
243         struct timeval tv;
244         int selectresolution = 100;
245
246         fdflags = fcntl(*sock, F_GETFL);
247         IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
248
249         while ((nSuccessLess < timeout) && 
250                (*sock != -1) && 
251                (bytes_written < nbytes)) 
252         {
253                 if (IsNonBlock){
254                         tv.tv_sec = selectresolution;
255                         tv.tv_usec = 0;
256                         
257                         FD_ZERO(&rfds);
258                         FD_SET(*sock, &rfds);
259                         if (select(*sock + 1, NULL, &rfds, NULL, &tv) == -1) {
260 ///                             *Error = strerror(errno);
261                                 close (*sock);
262                                 *sock = -1;
263                                 return -1;
264                         }
265                 }
266                 if (IsNonBlock && !  FD_ISSET(*sock, &rfds)) {
267                         nSuccessLess ++;
268                         continue;
269                 }
270                 retval = write(*sock, &buf[bytes_written],
271                                nbytes - bytes_written);
272                 if (retval < 1) {
273                         sock_close(*sock);
274                         *sock = -1;
275                         return (-1);
276                 }
277                 bytes_written = bytes_written + retval;
278                 if (IsNonBlock && (bytes_written == nbytes)){
279                         tv.tv_sec = selectresolution;
280                         tv.tv_usec = 0;
281                         
282                         FD_ZERO(&rfds);
283                         FD_SET(*sock, &rfds);
284                         if (select(*sock + 1, NULL, &rfds, NULL, &tv) == -1) {
285 ///                             *Error = strerror(errno);
286                                 close (*sock);
287                                 *sock = -1;
288                                 return -1;
289                         }
290                 }
291         }
292         return (bytes_written);
293 }
294
295
296
297 /*
298  * client_getln()   ...   Get a LF-terminated line of text from the client.
299  * (This is implemented in terms of client_read() and could be
300  * justifiably moved out of sysdep.c)
301  */
302 int sock_getln_err(int *sock, char *buf, int bufsize, int *rc, int nSec)
303 {
304         int i, retval;
305         CitContext *CCC = MyContext();
306         const char *pCh;
307
308         FlushStrBuf(CCC->sMigrateBuf);
309         *rc = retval = CtdlSockGetLine(sock, CCC->sMigrateBuf, nSec);
310
311         i = StrLength(CCC->sMigrateBuf);
312         pCh = ChrPtr(CCC->sMigrateBuf);
313
314         memcpy(buf, pCh, i + 1);
315
316         FlushStrBuf(CCC->sMigrateBuf);
317         if (retval < 0) {
318                 safestrncpy(&buf[i], "000", bufsize - i);
319                 i += 3;
320         }
321         return i;
322 }
323
324 /*
325  * Multiline version of sock_gets() ... this is a convenience function for
326  * client side protocol implementations.  It only returns the first line of
327  * a multiline response, discarding the rest.
328  */
329 int ml_sock_gets(int *sock, char *buf, int nSec)
330 {
331         int rc = 0;
332         char bigbuf[1024];
333         int g;
334
335         g = sock_getln_err(sock, buf, SIZ, &rc, nSec);
336         if (rc < 0)
337                 return rc;
338         if (g < 4)
339                 return (g);
340         if (buf[3] != '-')
341                 return (g);
342
343         do {
344                 g = sock_getln_err(sock, bigbuf, SIZ, &rc, nSec);
345                 if (rc < 0)
346                         return rc;
347                 if (g < 0)
348                         return (g);
349         } while ((g >= 4) && (bigbuf[3] == '-'));
350
351         return (strlen(buf));
352 }
353
354
355 /*
356  * sock_puts() - send line to server - implemented in terms of serv_write()
357  * Returns the number of bytes written, or -1 for error.
358  */
359 int sock_puts(int *sock, char *buf)
360 {
361         int i, j;
362
363         i = sock_write(sock, buf, strlen(buf));
364         if (i < 0)
365                 return (i);
366         j = sock_write(sock, "\n", 1);
367         if (j < 0)
368                 return (j);
369         return (i + j);
370 }