Updated the copyright declaration in several modules, removing any language which...
[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-2011 by the citadel.org team
8  *
9  * This program is open source software; you can redistribute it and/or
10  * modify it under the terms of the GNU General Public License, version 3.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  */
17
18 #include "sysdep.h"
19 #include <stdlib.h>
20 #include <unistd.h>
21 #include <stdio.h>
22 #include <signal.h>
23 #include <sys/types.h>
24 #include <sys/time.h>
25 #include <sys/socket.h>
26 #include <netinet/in.h>
27 #include <arpa/inet.h>
28 #include <netdb.h>
29 #include <string.h>
30 #include <pwd.h>
31 #include <errno.h>
32 #include <stdarg.h>
33 #include <syslog.h>
34 #include <libcitadel.h>
35 #include "citadel.h"
36 #include "server.h"
37 #ifndef HAVE_SNPRINTF
38 #include "snprintf.h"
39 #endif
40 #include "sysdep_decls.h"
41 #include "config.h"
42 #include "clientsocket.h"
43 #include "ctdl_module.h"
44
45 int sock_connect(char *host, char *service)
46 {
47         struct in6_addr serveraddr;
48         struct addrinfo hints;
49         struct addrinfo *res = NULL;
50         struct addrinfo *ai = NULL;
51         int rc = (-1);
52         int sock = (-1);
53
54         if ((host == NULL) || IsEmptyStr(host))
55                 return (-1);
56         if ((service == NULL) || IsEmptyStr(service))
57                 return (-1);
58
59         memset(&hints, 0x00, sizeof(hints));
60         hints.ai_flags = AI_NUMERICSERV;
61         hints.ai_family = AF_UNSPEC;
62         hints.ai_socktype = SOCK_STREAM;
63
64         /*
65          * Handle numeric IPv4 and IPv6 addresses
66          */
67         rc = inet_pton(AF_INET, host, &serveraddr);
68         if (rc == 1) {                                          /* dotted quad */
69                 hints.ai_family = AF_INET;
70                 hints.ai_flags |= AI_NUMERICHOST;
71         } else {
72                 rc = inet_pton(AF_INET6, host, &serveraddr);
73                 if (rc == 1) {                                  /* IPv6 address */
74                         hints.ai_family = AF_INET6;
75                         hints.ai_flags |= AI_NUMERICHOST;
76                 }
77         }
78
79         /* Begin the connection process */
80
81         rc = getaddrinfo(host, service, &hints, &res);
82         if (rc != 0) {
83                 syslog(LOG_ERR, "%s: %s", host, gai_strerror(rc));
84                 return(-1);
85         }
86
87         /*
88          * Try all available addresses until we connect to one or until we run out.
89          */
90         for (ai = res; ai != NULL; ai = ai->ai_next) {
91                 sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
92                 if (sock < 0) {
93                         syslog(LOG_ERR, "socket() failed: %s", strerror(errno));
94                         freeaddrinfo(res);
95                         return(-1);
96                 }
97                 rc = connect(sock, ai->ai_addr, ai->ai_addrlen);
98                 if (rc >= 0) {
99                         freeaddrinfo(res);
100                         return(sock);
101                 }
102                 else {
103                         syslog(LOG_ERR, "connect() failed: %s", strerror(errno));
104                         close(sock);
105                 }
106         }
107         freeaddrinfo(res);
108         return(-1);
109 }
110
111
112
113 /*
114  * Read data from the client socket.
115  *
116  * sock         socket fd to read from
117  * buf          buffer to read into 
118  * bytes        number of bytes to read
119  * timeout      Number of seconds to wait before timing out
120  *
121  * Possible return values:
122  *      1       Requested number of bytes has been read.
123  *      0       Request timed out.
124  *      -1      Connection is broken, or other error.
125  */
126 int socket_read_blob(int *Socket, StrBuf * Target, int bytes, int timeout)
127 {
128         CitContext *CCC = MyContext();
129         const char *Error;
130         int retval = 0;
131
132
133         retval = StrBufReadBLOBBuffered(Target,
134                                         CCC->SBuf.Buf,
135                                         &CCC->SBuf.ReadWritePointer,
136                                         Socket, 1, bytes, O_TERM, &Error);
137         
138         if (retval < 0) {
139                 syslog(LOG_CRIT, "socket_read_blob() failed: %s", Error);
140         }
141         return retval;
142 }
143
144
145 int CtdlSockGetLine(int *sock, StrBuf * Target, int nSec)
146 {
147         CitContext *CCC = MyContext();
148         const char *Error;
149         int rc;
150
151         FlushStrBuf(Target);
152         rc = StrBufTCP_read_buffered_line_fast(Target,
153                                                CCC->SBuf.Buf,
154                                                &CCC->SBuf.ReadWritePointer,
155                                                sock, nSec, 1, &Error);
156         if ((rc < 0) && (Error != NULL))
157                 syslog(LOG_CRIT, "CtdlSockGetLine() failed: %s", Error);
158         return rc;
159 }
160
161
162 /*
163  * client_getln()   ...   Get a LF-terminated line of text from the client.
164  * (This is implemented in terms of client_read() and could be
165  * justifiably moved out of sysdep.c)
166  */
167 int sock_getln(int *sock, char *buf, int bufsize)
168 {
169         int i, retval;
170         CitContext *CCC = MyContext();
171         const char *pCh;
172
173         FlushStrBuf(CCC->sMigrateBuf);
174         retval = CtdlSockGetLine(sock, CCC->sMigrateBuf, 5);
175
176         i = StrLength(CCC->sMigrateBuf);
177         pCh = ChrPtr(CCC->sMigrateBuf);
178
179         memcpy(buf, pCh, i + 1);
180
181         FlushStrBuf(CCC->sMigrateBuf);
182         if (retval < 0) {
183                 safestrncpy(&buf[i], "000", bufsize - i);
184                 i += 3;
185         }
186         return i;
187 }
188
189
190 /*
191  * sock_write() - send binary to server.
192  * Returns the number of bytes written, or -1 for error.
193  */
194 int sock_write(int *sock, const char *buf, int nbytes) 
195 { return sock_write_timeout(sock, buf, nbytes, 50); }
196 int sock_write_timeout(int *sock, const char *buf, int nbytes, int timeout)
197 {
198         int nSuccessLess = 0;
199         int bytes_written = 0;
200         int retval;
201         fd_set rfds;
202         int fdflags;
203         int IsNonBlock;
204         struct timeval tv;
205         int selectresolution = 100;
206
207         fdflags = fcntl(*sock, F_GETFL);
208         IsNonBlock = (fdflags & O_NONBLOCK) == O_NONBLOCK;
209
210         while ((nSuccessLess < timeout) && 
211                (*sock != -1) && 
212                (bytes_written < nbytes)) 
213         {
214                 if (IsNonBlock){
215                         tv.tv_sec = selectresolution;
216                         tv.tv_usec = 0;
217                         
218                         FD_ZERO(&rfds);
219                         FD_SET(*sock, &rfds);
220                         if (select(*sock + 1, NULL, &rfds, NULL, &tv) == -1) {
221 ///                             *Error = strerror(errno);
222                                 close (*sock);
223                                 *sock = -1;
224                                 return -1;
225                         }
226                 }
227                 if (IsNonBlock && !  FD_ISSET(*sock, &rfds)) {
228                         nSuccessLess ++;
229                         continue;
230                 }
231                 retval = write(*sock, &buf[bytes_written],
232                                nbytes - bytes_written);
233                 if (retval < 1) {
234                         sock_close(*sock);
235                         *sock = -1;
236                         return (-1);
237                 }
238                 bytes_written = bytes_written + retval;
239                 if (IsNonBlock && (bytes_written == nbytes)){
240                         tv.tv_sec = selectresolution;
241                         tv.tv_usec = 0;
242                         
243                         FD_ZERO(&rfds);
244                         FD_SET(*sock, &rfds);
245                         if (select(*sock + 1, NULL, &rfds, NULL, &tv) == -1) {
246 ///                             *Error = strerror(errno);
247                                 close (*sock);
248                                 *sock = -1;
249                                 return -1;
250                         }
251                 }
252         }
253         return (bytes_written);
254 }
255
256
257
258 /*
259  * client_getln()   ...   Get a LF-terminated line of text from the client.
260  * (This is implemented in terms of client_read() and could be
261  * justifiably moved out of sysdep.c)
262  */
263 int sock_getln_err(int *sock, char *buf, int bufsize, int *rc, int nSec)
264 {
265         int i, retval;
266         CitContext *CCC = MyContext();
267         const char *pCh;
268
269         FlushStrBuf(CCC->sMigrateBuf);
270         *rc = retval = CtdlSockGetLine(sock, CCC->sMigrateBuf, nSec);
271
272         i = StrLength(CCC->sMigrateBuf);
273         pCh = ChrPtr(CCC->sMigrateBuf);
274
275         memcpy(buf, pCh, i + 1);
276
277         FlushStrBuf(CCC->sMigrateBuf);
278         if (retval < 0) {
279                 safestrncpy(&buf[i], "000", bufsize - i);
280                 i += 3;
281         }
282         return i;
283 }
284
285 /*
286  * Multiline version of sock_gets() ... this is a convenience function for
287  * client side protocol implementations.  It only returns the first line of
288  * a multiline response, discarding the rest.
289  */
290 int ml_sock_gets(int *sock, char *buf, int nSec)
291 {
292         int rc = 0;
293         char bigbuf[1024];
294         int g;
295
296         g = sock_getln_err(sock, buf, SIZ, &rc, nSec);
297         if (rc < 0)
298                 return rc;
299         if (g < 4)
300                 return (g);
301         if (buf[3] != '-')
302                 return (g);
303
304         do {
305                 g = sock_getln_err(sock, bigbuf, SIZ, &rc, nSec);
306                 if (rc < 0)
307                         return rc;
308                 if (g < 0)
309                         return (g);
310         } while ((g >= 4) && (bigbuf[3] == '-'));
311
312         return (strlen(buf));
313 }
314
315
316 /*
317  * sock_puts() - send line to server - implemented in terms of serv_write()
318  * Returns the number of bytes written, or -1 for error.
319  */
320 int sock_puts(int *sock, char *buf)
321 {
322         int i, j;
323
324         i = sock_write(sock, buf, strlen(buf));
325         if (i < 0)
326                 return (i);
327         j = sock_write(sock, "\n", 1);
328         if (j < 0)
329                 return (j);
330         return (i + j);
331 }