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