]> the.earth.li Git - onak.git/blob - keydb/keyd.c
0df7192bfb6795b35d0d2b85ae8eafb6b699d6d1
[onak.git] / keydb / keyd.c
1 /*
2  * keyd.c - key retrieval daemon
3  *
4  * Copyright 2004,2011 Jonathan McDowell <noodles@earth.li>
5  *
6  * This program is free software: you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License as published by the Free
8  * Software Foundation; version 2 of the License.
9  *
10  * This program is distributed in the hope that it will be useful, but WITHOUT
11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12  * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
13  * more details.
14  *
15  * You should have received a copy of the GNU General Public License along with
16  * this program.  If not, see <https://www.gnu.org/licenses/>.
17  */
18
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <getopt.h>
22 #include <inttypes.h>
23 #include <signal.h>
24 #include <stdbool.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <sys/select.h>
29 #include <sys/socket.h>
30 #include <sys/types.h>
31 #include <sys/un.h>
32 #include <time.h>
33 #include <unistd.h>
34
35 #include "build-config.h"
36
37 #ifdef HAVE_SYSTEMD
38 #include <systemd/sd-daemon.h>
39 #endif
40
41 #include "charfuncs.h"
42 #include "cleanup.h"
43 #include "keyd.h"
44 #include "keydb.h"
45 #include "keyid.h"
46 #include "keystructs.h"
47 #include "log.h"
48 #include "mem.h"
49 #include "onak-conf.h"
50 #include "parsekey.h"
51
52 /* Maximum number of clients we're prepared to accept at once */
53 #define MAX_CLIENTS 16
54
55 #ifdef HAVE_SYSTEMD
56 static bool using_socket_activation = false;
57 #endif
58
59 static struct keyd_stats *stats;
60
61 static void daemonize(void)
62 {
63         pid_t pid;
64
65         pid = fork();
66
67         if (pid < 0) {
68                 logthing(LOGTHING_CRITICAL,
69                         "Failed to fork into background: %d (%s)",
70                         errno,
71                         strerror(errno));
72                 exit(EXIT_FAILURE);
73         } else if (pid > 0) {
74                 logthing(LOGTHING_INFO, "Backgrounded as pid %d.", pid);
75                 exit(EXIT_SUCCESS);
76         }
77
78         if (setsid() == -1) {
79                 logthing(LOGTHING_CRITICAL,
80                         "Couldn't set process group leader: %d (%s)",
81                         errno,
82                         strerror(errno));
83                 exit(EXIT_FAILURE);
84         }
85
86         if (!freopen("/dev/null", "r", stdin)) {
87                 logthing(LOGTHING_CRITICAL,
88                         "Couldn't reopen stdin to NULL: %d (%s)",
89                         errno,
90                         strerror(errno));
91                 exit(EXIT_FAILURE);
92         }
93         if (!freopen("/dev/null", "w", stdout)) {
94                 logthing(LOGTHING_CRITICAL,
95                         "Couldn't reopen stdout to NULL: %d (%s)",
96                         errno,
97                         strerror(errno));
98                 exit(EXIT_FAILURE);
99         }
100         if (!freopen("/dev/null", "w", stderr)) {
101                 logthing(LOGTHING_CRITICAL,
102                         "Couldn't reopen stderr to NULL: %d (%s)",
103                         errno,
104                         strerror(errno));
105                 exit(EXIT_FAILURE);
106         }
107
108         return;
109 }
110
111 static bool keyd_write_key(int fd, struct openpgp_publickey *key)
112 {
113         struct openpgp_packet_list *packets = NULL;
114         struct openpgp_packet_list *list_end = NULL;
115         struct buffer_ctx           storebuf;
116         ssize_t written;
117         bool    ok = true;
118
119         storebuf.offset = 0;
120         storebuf.size = 8192;
121         storebuf.buffer = malloc(8192);
122
123         flatten_publickey(key,
124                                 &packets,
125                                 &list_end);
126         write_openpgp_stream(buffer_putchar,
127                                 &storebuf,
128                                 packets);
129         logthing(LOGTHING_TRACE,
130                                 "Sending %d bytes.",
131                                 storebuf.offset);
132         written = write(fd, &storebuf.offset,
133                         sizeof(storebuf.offset));
134         if (written == 0) {
135                 ok = false;
136         } else {
137                 written = write(fd, storebuf.buffer,
138                         storebuf.offset);
139                 if (written != storebuf.offset) {
140                         ok = false;
141                 }
142         }
143
144         free(storebuf.buffer);
145         storebuf.buffer = NULL;
146         storebuf.size = storebuf.offset = 0;
147         free_packet_list(packets);
148         packets = list_end = NULL;
149
150         return (ok);
151 }
152
153 static bool keyd_write_reply(int fd, enum keyd_reply _reply)
154 {
155         uint32_t reply = _reply;
156         ssize_t written;
157         bool ok = true;
158
159         written = write(fd, &reply, sizeof(reply));
160         if (written != sizeof(reply)) {
161                 ok = false;
162         }
163
164         return (ok);
165 }
166
167 static bool keyd_write_size(int fd, size_t size)
168 {
169         ssize_t written;
170         bool ok = true;
171
172         written = write(fd, &size, sizeof(size));
173         if (written != sizeof(size)) {
174                 ok = false;
175         }
176
177         return (ok);
178 }
179
180 static void iteratefunc(void *ctx, struct openpgp_publickey *key)
181 {
182         int      *fd = (int *) ctx;
183         uint64_t  keyid;
184
185         if (key != NULL) {
186                 get_keyid(key, &keyid);
187                 logthing(LOGTHING_TRACE,
188                                 "Iterating over 0x%016" PRIX64 ".",
189                                 keyid);
190
191                 keyd_write_key(*fd, key);
192         }
193
194         return;
195 }
196
197 static int sock_init(const char *sockname)
198 {
199         struct sockaddr_un sock;
200         int                fd = -1;
201         int                ret = -1;
202 #ifdef HAVE_SYSTEMD
203         int                n;
204
205         n = sd_listen_fds(0);
206         if (n > 1) {
207                 logthing(LOGTHING_ERROR,
208                         "Too many file descriptors received from systemd.");
209         } else if (n == 1) {
210                 fd = SD_LISTEN_FDS_START + 0;
211                 if (sd_is_socket_unix(fd, SOCK_STREAM, 1, NULL, 0) <= 0) {
212                         logthing(LOGTHING_ERROR,
213                                 "systemd passed an invalid socket.");
214                         fd = -1;
215                 }
216                 using_socket_activation = true;
217         } else {
218 #endif
219                 fd = socket(PF_UNIX, SOCK_STREAM, 0);
220                 if (fd != -1) {
221                         ret = fcntl(fd, F_SETFD, FD_CLOEXEC);
222                 }
223
224                 if (ret != -1) {
225                         sock.sun_family = AF_UNIX;
226                         strncpy(sock.sun_path, sockname,
227                                         sizeof(sock.sun_path) - 1);
228                         unlink(sockname);
229                         ret = bind(fd, (struct sockaddr *) &sock,
230                                         sizeof(sock));
231                 }
232
233                 if (ret != -1) {
234                         ret = listen(fd, 5);
235                 }
236
237                 if (ret == -1) {
238                         logthing(LOGTHING_ERROR,
239                                 "Couldn't open socket to listen on: %s (%d)",
240                                 strerror(errno),
241                                 errno);
242                         close(fd);
243                         fd = -1;
244                 }
245 #ifdef HAVE_SYSTEMD
246         }
247 #endif
248
249         return fd;
250 }
251
252 static int sock_do(struct onak_dbctx *dbctx, int fd)
253 {
254         uint32_t cmd = KEYD_CMD_UNKNOWN;
255         ssize_t  bytes = 0;
256         ssize_t  count = 0;
257         int      ret = 0;
258         uint64_t keyid = 0;
259         char     *search = NULL;
260         struct openpgp_publickey *key = NULL;
261         struct openpgp_packet_list *packets = NULL;
262         struct buffer_ctx storebuf;
263         struct skshash hash;
264         struct openpgp_fingerprint fingerprint;
265
266         /*
267          * Get the command from the client.
268          */
269         bytes = read(fd, &cmd, sizeof(cmd));
270
271         logthing(LOGTHING_DEBUG, "Read %d bytes, command: %d", bytes, cmd);
272
273         if (bytes != sizeof(cmd)) {
274                 ret = 1;
275         }
276         
277         if (ret == 0) {
278                 if (cmd < KEYD_CMD_LAST) {
279                         stats->command_stats[cmd]++;
280                 } else {
281                         stats->command_stats[KEYD_CMD_UNKNOWN]++;
282                 }
283                 switch (cmd) {
284                 case KEYD_CMD_VERSION:
285                         if (!keyd_write_reply(fd, KEYD_REPLY_OK)) {
286                                 ret = 1;
287                         }
288                         if (ret == 0) {
289                                 cmd = sizeof(keyd_version);
290                                 bytes = write(fd, &cmd, sizeof(cmd));
291                                 if (bytes != sizeof(cmd)) {
292                                         ret = 1;
293                                 }
294                         }
295                         if (ret == 0) {
296                                 bytes = write(fd, &keyd_version,
297                                         sizeof(keyd_version));
298                                 if (bytes != sizeof(keyd_version)) {
299                                         ret = 1;
300                                 }
301                         }
302                         break;
303                 case KEYD_CMD_GET_ID:
304                         if (!keyd_write_reply(fd, KEYD_REPLY_OK)) {
305                                 ret = 1;
306                         }
307                         if (ret == 0) {
308                                 bytes = read(fd, &keyid, sizeof(keyid));
309                                 if (bytes != sizeof(keyid)) {
310                                         ret = 1;
311                                 }
312                         }
313                         if (ret == 0) {
314                                 logthing(LOGTHING_INFO,
315                                                 "Fetching 0x%" PRIX64
316                                                 ", result: %d",
317                                                 keyid,
318                                                 dbctx->fetch_key_id(dbctx,
319                                                         keyid,
320                                                         &key, false));
321                                 if (key != NULL) {
322                                         keyd_write_key(fd, key);
323                                         free_publickey(key);
324                                         key = NULL;
325                                 } else {
326                                         if (!keyd_write_size(fd, 0)) {
327                                                 ret = 1;
328                                         }
329                                 }
330                         }
331                         break;
332                 case KEYD_CMD_GET_FP:
333                         if (!keyd_write_reply(fd, KEYD_REPLY_OK)) {
334                                 ret = 1;
335                         }
336                         if (ret == 0) {
337                                 if ((read(fd, &bytes, 1) != 1) ||
338                                                 (bytes > MAX_FINGERPRINT_LEN)) {
339                                         ret = 1;
340                                 } else {
341                                         fingerprint.length = bytes;
342                                         bytes = read(fd, fingerprint.fp,
343                                                 fingerprint.length);
344                                         if (bytes != fingerprint.length) {
345                                                 ret = 1;
346                                         }
347                                 }
348                         }
349                         if (ret == 0) {
350                                 logthing(LOGTHING_INFO,
351                                                 "Fetching by fingerprint"
352                                                 ", result: %d",
353                                                 dbctx->fetch_key_fp(dbctx,
354                                                         &fingerprint,
355                                                         &key, false));
356                                 if (key != NULL) {
357                                         keyd_write_key(fd, key);
358                                         free_publickey(key);
359                                         key = NULL;
360                                 } else {
361                                         if (!keyd_write_size(fd, 0)) {
362                                                 ret = 1;
363                                         }
364                                 }
365                         }
366                         break;
367
368                 case KEYD_CMD_GET_TEXT:
369                         if (!keyd_write_reply(fd, KEYD_REPLY_OK)) {
370                                 ret = 1;
371                         }
372                         if (ret == 0) {
373                                 bytes = read(fd, &count, sizeof(count));
374                                 if (bytes != sizeof(count)) {
375                                         ret = 1;
376                                 }
377                         }
378                         if (ret == 0) {
379                                 search = malloc(count+1);
380                                 bytes = read(fd, search, count);
381                                 if (bytes != count) {
382                                         ret = 1;
383                                         free(search);
384                                         break;
385                                 }
386                                 search[count] = 0;
387                                 logthing(LOGTHING_INFO,
388                                                 "Fetching %s, result: %d",
389                                                 search,
390                                                 dbctx->fetch_key_text(dbctx,
391                                                         search, &key));
392                                 if (key != NULL) {
393                                         keyd_write_key(fd, key);
394                                         free_publickey(key);
395                                         key = NULL;
396                                 } else {
397                                         if (!keyd_write_size(fd, 0)) {
398                                                 ret = 1;
399                                         }
400                                 }
401                                 free(search);
402                         }
403                         break;
404                 case KEYD_CMD_STORE:
405                 case KEYD_CMD_UPDATE:
406                         if (!keyd_write_reply(fd, KEYD_REPLY_OK)) {
407                                 ret = 1;
408                         }
409                         if (ret == 0) {
410                                 bytes = read(fd, &storebuf.size,
411                                         sizeof(storebuf.size));
412                                 logthing(LOGTHING_TRACE, "Reading %d bytes.",
413                                         storebuf.size);
414                                 if (bytes != sizeof(storebuf.size)) {
415                                         ret = 1;
416                                 }
417                         }
418                         if (ret == 0 && storebuf.size > 0) {
419                                 storebuf.buffer = malloc(storebuf.size);
420                                 storebuf.offset = 0;
421                                 bytes = count = 0;
422                                 while (bytes >= 0 && count < storebuf.size) {
423                                         bytes = read(fd,
424                                                 &storebuf.buffer[count],
425                                                 storebuf.size - count);
426                                         logthing(LOGTHING_TRACE,
427                                                         "Read %d bytes.",
428                                                         bytes);
429                                         count += bytes;
430                                 }
431                                 read_openpgp_stream(buffer_fetchchar,
432                                                 &storebuf,
433                                                 &packets,
434                                                 0);
435                                 parse_keys(packets, &key);
436                                 dbctx->store_key(dbctx, key, false,
437                                         (cmd == KEYD_CMD_UPDATE));
438                                 free_packet_list(packets);
439                                 packets = NULL;
440                                 free_publickey(key);
441                                 key = NULL;
442                                 free(storebuf.buffer);
443                                 storebuf.buffer = NULL;
444                                 storebuf.size = storebuf.offset = 0;
445                         }
446                         break;
447                 case KEYD_CMD_DELETE:
448                         if (!keyd_write_reply(fd, KEYD_REPLY_OK)) {
449                                 ret = 1;
450                         }
451                         if (ret == 0) {
452                                 bytes = read(fd, &fingerprint,
453                                                 sizeof(fingerprint));
454                                 if (bytes != sizeof(fingerprint)) {
455                                         ret = 1;
456                                 }
457                         }
458                         if (ret == 0) {
459                                 logthing(LOGTHING_INFO,
460                                                 "Deleting 0x%" PRIX64
461                                                 ", result: %d",
462                                                 keyid,
463                                                 dbctx->delete_key(dbctx,
464                                                         &fingerprint, false));
465                         }
466                         break;
467                 case KEYD_CMD_KEYITER:
468                         if (!keyd_write_reply(fd, KEYD_REPLY_OK)) {
469                                 ret = 1;
470                         }
471                         if (ret == 0) {
472                                 dbctx->iterate_keys(dbctx, iteratefunc,
473                                         &fd);
474                                 if (!keyd_write_size(fd, 0)) {
475                                         ret = 1;
476                                 }
477                         }
478                         break;
479                 case KEYD_CMD_CLOSE:
480                         /* We're going to close the FD even if this fails */
481                         (void) keyd_write_reply(fd, KEYD_REPLY_OK);
482                         ret = 1;
483                         break;
484                 case KEYD_CMD_QUIT:
485                         /* We're going to quit even if this fails */
486                         (void) keyd_write_reply(fd, KEYD_REPLY_OK);
487                         logthing(LOGTHING_NOTICE,
488                                 "Exiting due to quit request.");
489                         ret = 1;
490                         trytocleanup();
491                         break;
492                 case KEYD_CMD_STATS:
493                         if (!keyd_write_reply(fd, KEYD_REPLY_OK)) {
494                                 ret = 1;
495                         }
496                         if (ret == 0) {
497                                 cmd = sizeof(*stats);
498                                 bytes = write(fd, &cmd, sizeof(cmd));
499                                 if (bytes != sizeof(cmd)) {
500                                         ret = 1;
501                                 }
502                         }
503                         if (ret == 0) {
504                                 bytes = write(fd, stats, sizeof(*stats));
505                                 if (bytes != sizeof(*stats)) {
506                                         ret = 1;
507                                 }
508                         }
509                         break;
510                 case KEYD_CMD_GET_SKSHASH:
511                         if (!keyd_write_reply(fd, KEYD_REPLY_OK)) {
512                                 ret = 1;
513                         }
514                         if (ret == 0) {
515                                 bytes = read(fd, hash.hash, sizeof(hash.hash));
516                                 if (bytes != sizeof(hash.hash)) {
517                                         ret = 1;
518                                 }
519                         }
520                         if (ret == 0) {
521                                 logthing(LOGTHING_INFO,
522                                                 "Fetching by hash"
523                                                 ", result: %d",
524                                                 dbctx->fetch_key_skshash(dbctx,
525                                                         &hash, &key));
526                                 if (key != NULL) {
527                                         keyd_write_key(fd, key);
528                                         free_publickey(key);
529                                         key = NULL;
530                                 } else {
531                                         if (!keyd_write_size(fd, 0)) {
532                                                 ret = 1;
533                                         }
534                                 }
535                         }
536                         break;
537
538                 default:
539                         logthing(LOGTHING_ERROR, "Got unknown command: %d",
540                                         cmd);
541                         if (!keyd_write_reply(fd, KEYD_REPLY_UNKNOWN_CMD)) {
542                                 ret = 1;
543                         }
544                 }
545         }
546
547         return(ret);
548 }
549
550 static int sock_close(int fd)
551 {
552         shutdown(fd, SHUT_RDWR);
553         return close(fd);
554 }
555
556 static int sock_accept(int fd)
557 {
558         struct sockaddr_un sock;
559         socklen_t          socklen;
560         int    srv = -1;
561         int    ret = -1;
562
563         socklen = sizeof(sock);
564         srv = accept(fd, (struct sockaddr *) &sock, &socklen);
565         if (srv != -1) {
566                 ret = fcntl(srv, F_SETFD, FD_CLOEXEC);
567         }
568
569         if (ret != -1) {
570                 stats->connects++;
571         }
572
573         return (srv);
574 }
575
576 static void usage(void)
577 {
578         puts("keyd " ONAK_VERSION " - backend key serving daemon for the "
579                 "onak PGP keyserver.\n");
580         puts("Usage:\n");
581         puts("\tkeyd [options]\n");
582         puts("\tOptions:\n:");
583         puts("-c <file> - use <file> as the config file");
584         puts("-f        - run in the foreground");
585         puts("-h        - show this help text");
586         exit(EXIT_FAILURE);
587 }
588
589 int main(int argc, char *argv[])
590 {
591         int fd = -1, maxfd, i, clients[MAX_CLIENTS];
592         fd_set rfds = { 0 }; /* Avoid scan-build false report for FD_SET */
593         char sockname[100];
594         char *configfile = NULL;
595         bool foreground = false;
596         int optchar;
597         struct onak_dbctx *dbctx;
598
599         while ((optchar = getopt(argc, argv, "c:fh")) != -1 ) {
600                 switch (optchar) {
601                 case 'c':
602                         if (configfile != NULL) {
603                                 free(configfile);
604                         }
605                         configfile = strdup(optarg);
606                         break;
607                 case 'f':
608                         foreground = true;
609                         break;
610                 case 'h':
611                 default:
612                         usage();
613                         break;
614                 }
615         }
616
617         readconfig(configfile);
618         free(configfile);
619         configfile = NULL;
620         initlogthing("keyd", config.logfile);
621         config.use_keyd = false;
622
623         if (!foreground) {
624                 daemonize();
625         }
626
627         catchsignals();
628         signal(SIGPIPE, SIG_IGN);
629
630
631         stats = calloc(1, sizeof(*stats));
632         if (!stats) {
633                 logthing(LOGTHING_ERROR,
634                         "Couldn't allocate memory for stats structure.");
635                 exit(EXIT_FAILURE);
636         }
637         stats->started = time(NULL);
638
639         snprintf(sockname, sizeof(sockname) - 1, "%s/%s",
640                         config.sock_dir, KEYD_SOCKET);
641         fd = sock_init(sockname);
642
643         if (fd != -1) {
644                 FD_ZERO(&rfds);
645                 FD_SET(fd, &rfds);
646                 maxfd = fd;
647                 memset(clients, -1, sizeof (clients));
648
649                 dbctx = config.dbinit(config.backend, false);
650
651                 logthing(LOGTHING_NOTICE, "Accepting connections.");
652                 while (!cleanup() && select(maxfd + 1, &rfds, NULL, NULL, NULL) != -1) {
653                         /*
654                          * Deal with existing clients first; if we're at our
655                          * connection limit then processing them might free
656                          * things up and let us accept the next client below.
657                          */
658                         for (i = 0; i < MAX_CLIENTS; i++) {
659                                 if (clients[i] != -1 &&
660                                                 FD_ISSET(clients[i], &rfds)) {
661                                         logthing(LOGTHING_DEBUG,
662                                                 "Handling connection for client %d.", i);
663                                         if (sock_do(dbctx, clients[i])) {
664                                                 sock_close(clients[i]);
665                                                 clients[i] = -1;
666                                                 logthing(LOGTHING_DEBUG,
667                                                         "Closed connection for client %d.", i);
668                                         }
669                                 }
670                         }
671                         /*
672                          * Check if we have a new incoming connection to accept.
673                          */
674                         if (FD_ISSET(fd, &rfds)) {
675                                 for (i = 0; i < MAX_CLIENTS; i++) {
676                                         if (clients[i] == -1) {
677                                                 break;
678                                         }
679                                 }
680                                 if (i < MAX_CLIENTS) {
681                                         logthing(LOGTHING_INFO,
682                                                 "Accepted connection %d.", i);
683                                         clients[i] = sock_accept(fd);
684                                 }
685                         }
686                         FD_ZERO(&rfds);
687                         FD_SET(fd, &rfds);
688                         maxfd = fd;
689                         for (i = 0; i < MAX_CLIENTS; i++) {
690                                 if (clients[i] != -1) {
691                                         FD_SET(clients[i], &rfds);
692                                         maxfd = (maxfd > clients[i]) ?
693                                                         maxfd : clients[i];
694                                 }
695                         }
696                 }
697                 dbctx->cleanupdb(dbctx);
698 #ifdef HAVE_SYSTEMD
699                 if (!using_socket_activation) {
700 #endif
701                         sock_close(fd);
702                         unlink(sockname);
703 #ifdef HAVE_SYSTEMD
704                 }
705 #endif
706         }
707
708         free(stats);
709
710         cleanuplogthing();
711         cleanupconfig();
712
713         return(EXIT_SUCCESS);
714 }