]> the.earth.li Git - onak.git/blob - keyd.c
Move to CMake over autoconf
[onak.git] / 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                         if (ret == -1) {
236                                 close(fd);
237                                 fd = -1;
238                         }
239                 }
240 #ifdef HAVE_SYSTEMD
241         }
242 #endif
243
244         return fd;
245 }
246
247 static int sock_do(struct onak_dbctx *dbctx, int fd)
248 {
249         uint32_t cmd = KEYD_CMD_UNKNOWN;
250         ssize_t  bytes = 0;
251         ssize_t  count = 0;
252         int      ret = 0;
253         uint64_t keyid = 0;
254         char     *search = NULL;
255         struct openpgp_publickey *key = NULL;
256         struct openpgp_packet_list *packets = NULL;
257         struct buffer_ctx storebuf;
258         struct skshash hash;
259         struct openpgp_fingerprint fingerprint;
260
261         /*
262          * Get the command from the client.
263          */
264         bytes = read(fd, &cmd, sizeof(cmd));
265
266         logthing(LOGTHING_DEBUG, "Read %d bytes, command: %d", bytes, cmd);
267
268         if (bytes != sizeof(cmd)) {
269                 ret = 1;
270         }
271         
272         if (ret == 0) {
273                 if (cmd < KEYD_CMD_LAST) {
274                         stats->command_stats[cmd]++;
275                 } else {
276                         stats->command_stats[KEYD_CMD_UNKNOWN]++;
277                 }
278                 switch (cmd) {
279                 case KEYD_CMD_VERSION:
280                         if (!keyd_write_reply(fd, KEYD_REPLY_OK)) {
281                                 ret = 1;
282                         }
283                         if (ret == 0) {
284                                 cmd = sizeof(keyd_version);
285                                 bytes = write(fd, &cmd, sizeof(cmd));
286                                 if (bytes != sizeof(cmd)) {
287                                         ret = 1;
288                                 }
289                         }
290                         if (ret == 0) {
291                                 bytes = write(fd, &keyd_version,
292                                         sizeof(keyd_version));
293                                 if (bytes != sizeof(keyd_version)) {
294                                         ret = 1;
295                                 }
296                         }
297                         break;
298                 case KEYD_CMD_GET_ID:
299                         if (!keyd_write_reply(fd, KEYD_REPLY_OK)) {
300                                 ret = 1;
301                         }
302                         if (ret == 0) {
303                                 bytes = read(fd, &keyid, sizeof(keyid));
304                                 if (bytes != sizeof(keyid)) {
305                                         ret = 1;
306                                 }
307                         }
308                         if (ret == 0) {
309                                 logthing(LOGTHING_INFO,
310                                                 "Fetching 0x%" PRIX64
311                                                 ", result: %d",
312                                                 keyid,
313                                                 dbctx->fetch_key_id(dbctx,
314                                                         keyid,
315                                                         &key, false));
316                                 if (key != NULL) {
317                                         keyd_write_key(fd, key);
318                                         free_publickey(key);
319                                         key = NULL;
320                                 } else {
321                                         if (!keyd_write_size(fd, 0)) {
322                                                 ret = 1;
323                                         }
324                                 }
325                         }
326                         break;
327                 case KEYD_CMD_GET_FP:
328                         if (!keyd_write_reply(fd, KEYD_REPLY_OK)) {
329                                 ret = 1;
330                         }
331                         if (ret == 0) {
332                                 if ((read(fd, &bytes, 1) != 1) ||
333                                                 (bytes > MAX_FINGERPRINT_LEN)) {
334                                         ret = 1;
335                                 } else {
336                                         fingerprint.length = bytes;
337                                         bytes = read(fd, fingerprint.fp,
338                                                 fingerprint.length);
339                                         if (bytes != fingerprint.length) {
340                                                 ret = 1;
341                                         }
342                                 }
343                         }
344                         if (ret == 0) {
345                                 logthing(LOGTHING_INFO,
346                                                 "Fetching by fingerprint"
347                                                 ", result: %d",
348                                                 dbctx->fetch_key_fp(dbctx,
349                                                         &fingerprint,
350                                                         &key, false));
351                                 if (key != NULL) {
352                                         keyd_write_key(fd, key);
353                                         free_publickey(key);
354                                         key = NULL;
355                                 } else {
356                                         if (!keyd_write_size(fd, 0)) {
357                                                 ret = 1;
358                                         }
359                                 }
360                         }
361                         break;
362
363                 case KEYD_CMD_GET_TEXT:
364                         if (!keyd_write_reply(fd, KEYD_REPLY_OK)) {
365                                 ret = 1;
366                         }
367                         if (ret == 0) {
368                                 bytes = read(fd, &count, sizeof(count));
369                                 if (bytes != sizeof(count)) {
370                                         ret = 1;
371                                 }
372                         }
373                         if (ret == 0) {
374                                 search = malloc(count+1);
375                                 bytes = read(fd, search, count);
376                                 if (bytes != count) {
377                                         ret = 1;
378                                         free(search);
379                                         break;
380                                 }
381                                 search[count] = 0;
382                                 logthing(LOGTHING_INFO,
383                                                 "Fetching %s, result: %d",
384                                                 search,
385                                                 dbctx->fetch_key_text(dbctx,
386                                                         search, &key));
387                                 if (key != NULL) {
388                                         keyd_write_key(fd, key);
389                                         free_publickey(key);
390                                         key = NULL;
391                                 } else {
392                                         if (!keyd_write_size(fd, 0)) {
393                                                 ret = 1;
394                                         }
395                                 }
396                                 free(search);
397                         }
398                         break;
399                 case KEYD_CMD_STORE:
400                 case KEYD_CMD_UPDATE:
401                         if (!keyd_write_reply(fd, KEYD_REPLY_OK)) {
402                                 ret = 1;
403                         }
404                         if (ret == 0) {
405                                 bytes = read(fd, &storebuf.size,
406                                         sizeof(storebuf.size));
407                                 logthing(LOGTHING_TRACE, "Reading %d bytes.",
408                                         storebuf.size);
409                                 if (bytes != sizeof(storebuf.size)) {
410                                         ret = 1;
411                                 }
412                         }
413                         if (ret == 0 && storebuf.size > 0) {
414                                 storebuf.buffer = malloc(storebuf.size);
415                                 storebuf.offset = 0;
416                                 bytes = count = 0;
417                                 while (bytes >= 0 && count < storebuf.size) {
418                                         bytes = read(fd,
419                                                 &storebuf.buffer[count],
420                                                 storebuf.size - count);
421                                         logthing(LOGTHING_TRACE,
422                                                         "Read %d bytes.",
423                                                         bytes);
424                                         count += bytes;
425                                 }
426                                 read_openpgp_stream(buffer_fetchchar,
427                                                 &storebuf,
428                                                 &packets,
429                                                 0);
430                                 parse_keys(packets, &key);
431                                 dbctx->store_key(dbctx, key, false,
432                                         (cmd == KEYD_CMD_UPDATE));
433                                 free_packet_list(packets);
434                                 packets = NULL;
435                                 free_publickey(key);
436                                 key = NULL;
437                                 free(storebuf.buffer);
438                                 storebuf.buffer = NULL;
439                                 storebuf.size = storebuf.offset = 0;
440                         }
441                         break;
442                 case KEYD_CMD_DELETE:
443                         if (!keyd_write_reply(fd, KEYD_REPLY_OK)) {
444                                 ret = 1;
445                         }
446                         if (ret == 0) {
447                                 bytes = read(fd, &keyid, sizeof(keyid));
448                                 if (bytes != sizeof(keyid)) {
449                                         ret = 1;
450                                 }
451                         }
452                         if (ret == 0) {
453                                 logthing(LOGTHING_INFO,
454                                                 "Deleting 0x%" PRIX64
455                                                 ", result: %d",
456                                                 keyid,
457                                                 dbctx->delete_key(dbctx,
458                                                         keyid, false));
459                         }
460                         break;
461                 case KEYD_CMD_GETFULLKEYID:
462                         if (!keyd_write_reply(fd, KEYD_REPLY_OK)) {
463                                 ret = 1;
464                         }
465                         if (ret == 0) {
466                                 bytes = read(fd, &keyid, sizeof(keyid));
467                                 if (bytes != sizeof(keyid)) {
468                                         ret = 1;
469                                 }
470                         }
471                         if (ret == 0) {
472                                 keyid = dbctx->getfullkeyid(dbctx, keyid);
473                                 cmd = sizeof(keyid);
474                                 bytes = write(fd, &cmd, sizeof(cmd));
475                                 if (bytes != sizeof(cmd)) {
476                                         ret = 1;
477                                 }
478                         }
479                         if (ret == 0) {
480                                 bytes = write(fd, &keyid, sizeof(keyid));
481                                 if (bytes != sizeof(keyid)) {
482                                         ret = 1;
483                                 }
484                         }
485                         break;
486                 case KEYD_CMD_KEYITER:
487                         if (!keyd_write_reply(fd, KEYD_REPLY_OK)) {
488                                 ret = 1;
489                         }
490                         if (ret == 0) {
491                                 dbctx->iterate_keys(dbctx, iteratefunc,
492                                         &fd);
493                                 if (!keyd_write_size(fd, 0)) {
494                                         ret = 1;
495                                 }
496                         }
497                         break;
498                 case KEYD_CMD_CLOSE:
499                         /* We're going to close the FD even if this fails */
500                         (void) keyd_write_reply(fd, KEYD_REPLY_OK);
501                         ret = 1;
502                         break;
503                 case KEYD_CMD_QUIT:
504                         /* We're going to quit even if this fails */
505                         (void) keyd_write_reply(fd, KEYD_REPLY_OK);
506                         logthing(LOGTHING_NOTICE,
507                                 "Exiting due to quit request.");
508                         ret = 1;
509                         trytocleanup();
510                         break;
511                 case KEYD_CMD_STATS:
512                         if (!keyd_write_reply(fd, KEYD_REPLY_OK)) {
513                                 ret = 1;
514                         }
515                         if (ret == 0) {
516                                 cmd = sizeof(*stats);
517                                 bytes = write(fd, &cmd, sizeof(cmd));
518                                 if (bytes != sizeof(cmd)) {
519                                         ret = 1;
520                                 }
521                         }
522                         if (ret == 0) {
523                                 bytes = write(fd, stats, sizeof(*stats));
524                                 if (bytes != sizeof(*stats)) {
525                                         ret = 1;
526                                 }
527                         }
528                         break;
529                 case KEYD_CMD_GET_SKSHASH:
530                         if (!keyd_write_reply(fd, KEYD_REPLY_OK)) {
531                                 ret = 1;
532                         }
533                         if (ret == 0) {
534                                 bytes = read(fd, hash.hash, sizeof(hash.hash));
535                                 if (bytes != sizeof(hash.hash)) {
536                                         ret = 1;
537                                 }
538                         }
539                         if (ret == 0) {
540                                 logthing(LOGTHING_INFO,
541                                                 "Fetching by hash"
542                                                 ", result: %d",
543                                                 dbctx->fetch_key_skshash(dbctx,
544                                                         &hash, &key));
545                                 if (key != NULL) {
546                                         keyd_write_key(fd, key);
547                                         free_publickey(key);
548                                         key = NULL;
549                                 } else {
550                                         if (!keyd_write_size(fd, 0)) {
551                                                 ret = 1;
552                                         }
553                                 }
554                         }
555                         break;
556
557                 default:
558                         logthing(LOGTHING_ERROR, "Got unknown command: %d",
559                                         cmd);
560                         if (!keyd_write_reply(fd, KEYD_REPLY_UNKNOWN_CMD)) {
561                                 ret = 1;
562                         }
563                 }
564         }
565
566         return(ret);
567 }
568
569 static int sock_close(int fd)
570 {
571         shutdown(fd, SHUT_RDWR);
572         return close(fd);
573 }
574
575 static int sock_accept(int fd)
576 {
577         struct sockaddr_un sock;
578         socklen_t          socklen;
579         int    srv = -1;
580         int    ret = -1;
581
582         socklen = sizeof(sock);
583         srv = accept(fd, (struct sockaddr *) &sock, &socklen);
584         if (srv != -1) {
585                 ret = fcntl(srv, F_SETFD, FD_CLOEXEC);
586         }
587
588         if (ret != -1) {
589                 stats->connects++;
590         }
591
592         return (srv);
593 }
594
595 static void usage(void)
596 {
597         puts("keyd " ONAK_VERSION " - backend key serving daemon for the "
598                 "onak PGP keyserver.\n");
599         puts("Usage:\n");
600         puts("\tkeyd [options]\n");
601         puts("\tOptions:\n:");
602         puts("-c <file> - use <file> as the config file");
603         puts("-f        - run in the foreground");
604         puts("-h        - show this help text");
605         exit(EXIT_FAILURE);
606 }
607
608 int main(int argc, char *argv[])
609 {
610         int fd = -1, maxfd, i, clients[MAX_CLIENTS];
611         fd_set rfds = { 0 }; /* Avoid scan-build false report for FD_SET */
612         char sockname[100];
613         char *configfile = NULL;
614         bool foreground = false;
615         int optchar;
616         struct onak_dbctx *dbctx;
617
618         while ((optchar = getopt(argc, argv, "c:fh")) != -1 ) {
619                 switch (optchar) {
620                 case 'c':
621                         if (configfile != NULL) {
622                                 free(configfile);
623                         }
624                         configfile = strdup(optarg);
625                         break;
626                 case 'f':
627                         foreground = true;
628                         break;
629                 case 'h':
630                 default:
631                         usage();
632                         break;
633                 }
634         }
635
636         readconfig(configfile);
637         free(configfile);
638         configfile = NULL;
639         initlogthing("keyd", config.logfile);
640         config.use_keyd = false;
641
642         if (!foreground) {
643                 daemonize();
644         }
645
646         catchsignals();
647         signal(SIGPIPE, SIG_IGN);
648
649
650         stats = calloc(1, sizeof(*stats));
651         if (!stats) {
652                 logthing(LOGTHING_ERROR,
653                         "Couldn't allocate memory for stats structure.");
654                 exit(EXIT_FAILURE);
655         }
656         stats->started = time(NULL);
657
658         snprintf(sockname, sizeof(sockname) - 1, "%s/%s",
659                         config.sock_dir, KEYD_SOCKET);
660         fd = sock_init(sockname);
661
662         if (fd != -1) {
663                 FD_ZERO(&rfds);
664                 FD_SET(fd, &rfds);
665                 maxfd = fd;
666                 memset(clients, -1, sizeof (clients));
667
668                 dbctx = config.dbinit(config.backend, false);
669
670                 logthing(LOGTHING_NOTICE, "Accepting connections.");
671                 while (!cleanup() && select(maxfd + 1, &rfds, NULL, NULL, NULL) != -1) {
672                         /*
673                          * Deal with existing clients first; if we're at our
674                          * connection limit then processing them might free
675                          * things up and let us accept the next client below.
676                          */
677                         for (i = 0; i < MAX_CLIENTS; i++) {
678                                 if (clients[i] != -1 &&
679                                                 FD_ISSET(clients[i], &rfds)) {
680                                         logthing(LOGTHING_DEBUG,
681                                                 "Handling connection for client %d.", i);
682                                         if (sock_do(dbctx, clients[i])) {
683                                                 sock_close(clients[i]);
684                                                 clients[i] = -1;
685                                                 logthing(LOGTHING_DEBUG,
686                                                         "Closed connection for client %d.", i);
687                                         }
688                                 }
689                         }
690                         /*
691                          * Check if we have a new incoming connection to accept.
692                          */
693                         if (FD_ISSET(fd, &rfds)) {
694                                 for (i = 0; i < MAX_CLIENTS; i++) {
695                                         if (clients[i] == -1) {
696                                                 break;
697                                         }
698                                 }
699                                 if (i < MAX_CLIENTS) {
700                                         logthing(LOGTHING_INFO,
701                                                 "Accepted connection %d.", i);
702                                         clients[i] = sock_accept(fd);
703                                 }
704                         }
705                         FD_ZERO(&rfds);
706                         FD_SET(fd, &rfds);
707                         maxfd = fd;
708                         for (i = 0; i < MAX_CLIENTS; i++) {
709                                 if (clients[i] != -1) {
710                                         FD_SET(clients[i], &rfds);
711                                         maxfd = (maxfd > clients[i]) ?
712                                                         maxfd : clients[i];
713                                 }
714                         }
715                 }
716                 dbctx->cleanupdb(dbctx);
717 #ifdef HAVE_SYSTEMD
718                 if (!using_socket_activation) {
719 #endif
720                         sock_close(fd);
721                         unlink(sockname);
722 #ifdef HAVE_SYSTEMD
723                 }
724 #endif
725         }
726
727         free(stats);
728
729         cleanuplogthing();
730         cleanupconfig();
731
732         return(EXIT_SUCCESS);
733 }