Code

564aba70bab4c4a592e86da6bf4be93187f50513
[sysdb.git] / src / utils / unixsock.c
1 /*
2  * SysDB - src/utils/unixsock.c
3  * Copyright (C) 2012 Sebastian 'tokkee' Harl <sh@tokkee.org>
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
17  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
19  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
28 #include "utils/unixsock.h"
29 #include "utils/string.h"
31 #include <assert.h>
32 #include <errno.h>
34 #include <stdarg.h>
35 #include <stdio.h>
36 #include <stdlib.h>
38 #include <string.h>
39 #include <strings.h>
41 #include <unistd.h>
43 #include <sys/socket.h>
44 #include <sys/un.h>
46 /*
47  * private data types
48  */
50 struct sdb_unixsock_client {
51         char *path;
52         FILE *fh;
54         int shutdown;
55 };
57 #define SDB_SHUT_RD   (1 << SHUT_RD)
58 #define SDB_SHUT_WR   (1 << SHUT_WR)
59 #define SDB_SHUT_RDWR (SDB_SHUT_RD | SDB_SHUT_WR)
61 /*
62  * private helper functions
63  */
65 static int
66 sdb_unixsock_get_column_count(const char *string, const char *delim)
67 {
68         int count = 1;
70         assert(string);
72         if ((! delim) || (*string == '\0'))
73                 return 1;
75         if ((delim[0] == '\0') || (delim[1] == '\0')) {
76                 while ((string = strchr(string, (int)delim[0]))) {
77                         ++string;
78                         ++count;
79                 }
80         }
81         else {
82                 while ((string = strpbrk(string, delim))) {
83                         ++string;
84                         ++count;
85                 }
86         }
87         return count;
88 } /* sdb_unixsock_get_column_count */
90 static int
91 sdb_unixsock_parse_cell(char *string, int type, sdb_data_t *data)
92 {
93         char *endptr = NULL;
95         switch (type) {
96                 case SDB_TYPE_INTEGER:
97                         errno = 0;
98                         data->data.integer = strtoll(string, &endptr, 0);
99                         break;
100                 case SDB_TYPE_DECIMAL:
101                         errno = 0;
102                         data->data.decimal = strtod(string, &endptr);
103                         break;
104                 case SDB_TYPE_STRING:
105                         data->data.string = string;
106                         break;
107                 case SDB_TYPE_DATETIME:
108                         {
109                                 double datetime = strtod(string, &endptr);
110                                 data->data.datetime = DOUBLE_TO_SDB_TIME(datetime);
111                         }
112                         break;
113                 case SDB_TYPE_BINARY:
114                         /* we don't support any binary information containing 0-bytes */
115                         data->data.binary.length = strlen(string);
116                         data->data.binary.datum = (const unsigned char *)string;
117                         break;
118                 default:
119                         fprintf(stderr, "unixsock: Unexpected type %i while "
120                                         "parsing query result.\n", type);
121                         return -1;
122         }
124         if ((type == SDB_TYPE_INTEGER) || (type == SDB_TYPE_DECIMAL)
125                         || (type == SDB_TYPE_DATETIME)) {
126                 if (errno || (string == endptr)) {
127                         char errbuf[1024];
128                         fprintf(stderr, "unixsock: Failed to parse string '%s' "
129                                         "as numeric value (type %i): %s\n", string, type,
130                                         sdb_strerror(errno, errbuf, sizeof(errbuf)));
131                         return -1;
132                 }
133                 else if (endptr && (*endptr != '\0'))
134                         fprintf(stderr, "unixsock: Ignoring garbage after number "
135                                         "while parsing numeric value (type %i): %s.\n",
136                                         type, endptr);
137         }
139         data->type = type;
140         return 0;
141 } /* sdb_unixsock_parse_cell */
143 static int
144 sdb_unixsock_client_process_one_line(sdb_unixsock_client_t *client,
145                 char *line, sdb_unixsock_client_data_cb callback,
146                 sdb_object_t *user_data, const char *delim,
147                 int column_count, int *types)
149         sdb_data_t data[column_count];
150         char *orig_line = line;
152         int i;
154         assert(column_count > 0);
156         for (i = 0; i < column_count; ++i) {
157                 char *next;
159                 if (! line) { /* this must no happen */
160                         fprintf(stderr, "unixsock: Unexpected EOL while parsing line "
161                                         "(expected %i columns delimited by '%s'; got %i): %s\n",
162                                         column_count, delim, /* last line number */ i, orig_line);
163                         return -1;
164                 }
166                 if ((delim[0] == '\0') || (delim[1] == '\0'))
167                         next = strchr(line, (int)delim[0]);
168                 else
169                         next = strpbrk(line, delim);
171                 if (next) {
172                         *next = '\0';
173                         ++next;
174                 }
176                 if (sdb_unixsock_parse_cell(line,
177                                         types ? types[i] : SDB_TYPE_STRING, &data[i]))
178                         return -1;
180                 line = next;
181         }
183         if (callback(client, (size_t)column_count, data, user_data))
184                 return -1;
185         return 0;
186 } /* sdb_unixsock_client_process_one_line */
188 /*
189  * public API
190  */
192 sdb_unixsock_client_t *
193 sdb_unixsock_client_create(const char *path)
195         sdb_unixsock_client_t *client;
197         if (! path)
198                 return NULL;
200         client = malloc(sizeof(*client));
201         if (! client)
202                 return NULL;
203         memset(client, 0, sizeof(*client));
204         client->fh = NULL;
206         client->path = strdup(path);
207         if (! client->path) {
208                 sdb_unixsock_client_destroy(client);
209                 return NULL;
210         }
212         client->shutdown = 0;
213         return client;
214 } /* sdb_unixsock_client_create */
216 int
217 sdb_unixsock_client_connect(sdb_unixsock_client_t *client)
219         struct sockaddr_un sa;
220         int fd;
222         if ((! client) || (! client->path))
223                 return -1;
225         memset(&sa, 0, sizeof(sa));
227         if (client->fh)
228                 fclose(client->fh);
230         fd = socket(AF_UNIX, SOCK_STREAM, /* protocol = */ 0);
231         if (fd < 0) {
232                 char errbuf[1024];
233                 fprintf(stderr, "unixsock: Failed to open socket: %s\n",
234                                 sdb_strerror(errno, errbuf, sizeof(errbuf)));
235                 return -1;
236         }
238         sa.sun_family = AF_UNIX;
239         strncpy(sa.sun_path, client->path, sizeof(sa.sun_path));
240         sa.sun_path[sizeof(sa.sun_path) - 1] = '\0';
242         if (connect(fd, (struct sockaddr *)&sa, sizeof(sa))) {
243                 char errbuf[1024];
244                 fprintf(stderr, "unixsock: Failed to connect to %s: %s\n",
245                                 sa.sun_path, sdb_strerror(errno, errbuf, sizeof(errbuf)));
246                 close(fd);
247                 return -1;
248         }
250         client->fh = fdopen(fd, "r+");
251         if (! client->fh) {
252                 char errbuf[1024];
253                 fprintf(stderr, "unixsock: Failed to open I/O stream for %s: %s\n",
254                                 sa.sun_path, sdb_strerror(errno, errbuf, sizeof(errbuf)));
255                 close(fd);
256                 return -1;
257         }
259         client->shutdown = 0;
260         return 0;
261 } /* sdb_unixsock_client_connect */
263 int
264 sdb_unixsock_client_send(sdb_unixsock_client_t *client,
265                 const char *msg)
267         int status;
269         if ((! client) || (! client->fh))
270                 return -1;
272         if (client->shutdown & SDB_SHUT_WR) /* reconnect */
273                 sdb_unixsock_client_connect(client);
275         status = fprintf(client->fh, "%s\r\n", msg);
276         if (status < 0) {
277                 char errbuf[1024];
278                 fprintf(stderr, "unixsock: Failed to write to socket (%s): %s\n",
279                                 client->path, sdb_strerror(errno, errbuf, sizeof(errbuf)));
280                 return status;
281         }
282         return status;
283 } /* sdb_unixsock_client_send */
285 char *
286 sdb_unixsock_client_recv(sdb_unixsock_client_t *client,
287                 char *buffer, size_t buflen)
289         if ((! client) || (! client->fh) || (! buffer))
290                 return NULL;
292         if (client->shutdown & SDB_SHUT_RD) /* reconnect */
293                 sdb_unixsock_client_connect(client);
295         buffer = fgets(buffer, (int)buflen - 1, client->fh);
296         if (! buffer) {
297                 if (! feof(client->fh)) {
298                         char errbuf[1024];
299                         fprintf(stderr, "unixsock: Failed to read from socket (%s): %s\n",
300                                         client->path, sdb_strerror(errno, errbuf, sizeof(errbuf)));
301                 }
302                 return buffer;
303         }
304         buffer[buflen - 1] = '\0';
306         buflen = strlen(buffer);
307         while ((buffer[buflen - 1] == '\n') || (buffer[buflen - 1] == '\r')) {
308                 buffer[buflen - 1] = '\0';
309                 --buflen;
310         }
311         return buffer;
312 } /* sdb_unixsock_client_recv */
314 int
315 sdb_unixsock_client_process_lines(sdb_unixsock_client_t *client,
316                 sdb_unixsock_client_data_cb callback, sdb_object_t *user_data,
317                 long int max_lines, const char *delim, int n_cols, ...)
319         int *types = NULL;
320         int success = 0;
322         if ((! client) || (! client->fh) || (! callback))
323                 return -1;
325         if (n_cols > 0) {
326                 va_list ap;
327                 int i;
329                 types = calloc((size_t)n_cols, sizeof(*types));
330                 if (! types)
331                         return -1;
333                 va_start(ap, n_cols);
335                 for (i = 0; i < n_cols; ++i) {
336                         types[i] = va_arg(ap, int);
338                         if ((types[i] < 1) || (types[i] > SDB_TYPE_BINARY)) {
339                                 fprintf(stderr, "unixsock: Unknown column type %i while "
340                                                 "processing response from the UNIX socket @ %s.\n",
341                                                 types[i], client->path);
342                                 va_end(ap);
343                                 free(types);
344                                 return -1;
345                         }
346                 }
348                 va_end(ap);
349         }
351         while (42) {
352                 char  buffer[1024];
353                 char *line;
355                 int column_count;
357                 if (! max_lines)
358                         break;
360                 if (max_lines > 0)
361                         --max_lines;
363                 sdb_unixsock_client_clearerr(client);
364                 line = sdb_unixsock_client_recv(client, buffer, sizeof(buffer));
366                 if (! line)
367                         break;
369                 column_count = sdb_unixsock_get_column_count(line, delim);
371                 if ((n_cols >= 0) && (n_cols != column_count)) {
372                         fprintf(stderr, "unixsock: number of columns (%i) does not "
373                                         "match the number of requested columns (%i) while "
374                                         "processing response from the UNIX socket @ %s: %s\n",
375                                         column_count, n_cols, client->path, line);
376                         continue;
377                 }
379                 if (column_count <= 0) /* no data */
380                         continue;
382                 if (! sdb_unixsock_client_process_one_line(client, line, callback,
383                                         user_data, delim, column_count, types))
384                         ++success;
385         }
387         free(types);
389         if ((max_lines > 0)
390                         || ((max_lines < 0) && (! sdb_unixsock_client_eof(client)))
391                         || sdb_unixsock_client_error(client)) {
392                 char errbuf[1024];
393                 fprintf(stderr, "unixsock: Unexpected end of data while reading "
394                                 "from socket (%s): %s\n", client->path,
395                                 sdb_strerror(errno, errbuf, sizeof(errbuf)));
396                 return -1;
397         }
398         if (! success)
399                 return -1;
400         return 0;
401 } /* sdb_unixsock_client_process_lines */
403 int
404 sdb_unixsock_client_shutdown(sdb_unixsock_client_t *client, int how)
406         int status;
408         if (! client) {
409                 errno = ENOTSOCK;
410                 return -1;
411         }
413         fflush(client->fh);
414         status = shutdown(fileno(client->fh), how);
416         if (! status) {
417                 if (how == SHUT_RDWR)
418                         client->shutdown |= SDB_SHUT_RDWR;
419                 else
420                         client->shutdown |= 1 << how;
421         }
422         return status;
423 } /* sdb_unixsock_client_shutdown */
425 void
426 sdb_unixsock_client_clearerr(sdb_unixsock_client_t *client)
428         if ((! client) || (! client->fh))
429                 return;
430         clearerr(client->fh);
431 } /* sdb_unixsock_client_clearerr */
433 int
434 sdb_unixsock_client_eof(sdb_unixsock_client_t *client)
436         if ((! client) || (! client->fh)) {
437                 errno = EBADF;
438                 return -1;
439         }
440         return feof(client->fh);
441 } /* sdb_unixsock_client_eof */
443 int
444 sdb_unixsock_client_error(sdb_unixsock_client_t *client)
446         if ((! client) || (! client->fh)) {
447                 errno = EBADF;
448                 return -1;
449         }
450         return ferror(client->fh);
451 } /* sdb_unixsock_client_error */
453 void
454 sdb_unixsock_client_destroy(sdb_unixsock_client_t *client)
456         if (! client)
457                 return;
459         if (client->path)
460                 free(client->path);
461         client->path = NULL;
463         if (client->fh)
464                 fclose(client->fh);
465         client->fh = NULL;
467         free(client);
468 } /* sdb_unixsock_client_destroy */
470 const char *
471 sdb_unixsock_client_path(sdb_unixsock_client_t *client)
473         if (! client)
474                 return NULL;
475         return client->path;
476 } /* sdb_unixsock_client_path */
478 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */