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