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