GENKEY: Require an opened data file.
[pwmd.git] / src / commands.c
bloba3989efcf40c1ff9858e8666259aca68e86ddbec
1 /*
2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015,
3 2016, 2017
4 Ben Kibbey <bjk@luxsci.net>
6 This file is part of pwmd.
8 Pwmd is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 2 of the License, or
11 (at your option) any later version.
13 Pwmd is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
21 #ifdef HAVE_CONFIG_H
22 #include <config.h>
23 #endif
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <err.h>
29 #include <errno.h>
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <fcntl.h>
33 #include <ctype.h>
34 #include <dirent.h>
35 #include <pthread.h>
36 #include <stdint.h>
37 #include <assert.h>
38 #include <signal.h>
40 #include "pwmd-error.h"
41 #include <gcrypt.h>
43 #include "mem.h"
44 #include "xml.h"
45 #include "util-misc.h"
46 #include "common.h"
47 #include "rcfile.h"
48 #include "cache.h"
49 #include "commands.h"
50 #include "mutex.h"
51 #include "crypto.h"
52 #include "acl.h"
54 /* These are command option flags. */
55 #define OPT_INQUIRE 0x0001
56 #define OPT_NO_PASSPHRASE 0x0002
57 #define OPT_ASK 0x0004
58 #define OPT_LIST_RECURSE 0x0008
59 #define OPT_VERBOSE 0x0010
60 #define OPT_LOCK 0x0020
61 #define OPT_LOCK_ON_OPEN 0x0040
62 #define OPT_SIGN 0x0080
63 #define OPT_LIST_ALL 0x0100
64 #define OPT_DATA 0x0200
65 #define OPT_NO_AGENT 0x0400
66 #define OPT_SECRET 0x0800
67 #define OPT_INQUIRE_KEYID 0x1000
68 #define OPT_SYMMETRIC 0x4000
69 #define OPT_NO_SIGNER 0x8000
70 #define OPT_HTML 0x10000
71 #define OPT_CACHE_AGENT 0x20000
72 #define OPT_CACHE_SIGN 0x40000
73 #define OPT_KEYINFO_LEARN 0x80000
75 #define FLOCK_TYPE_NONE 0
76 #define FLOCK_TYPE_SH 0x0001
77 #define FLOCK_TYPE_EX 0x0002
78 #define FLOCK_TYPE_KEEP 0x0004
80 static char env_display[256];
81 static char env_gpg_tty[256];
82 static char env_term[256];
84 struct command_table_s
86 const char *name;
87 gpg_error_t (*handler) (assuan_context_t, char *line);
88 const char *help;
89 int ignore_startup;
90 int unlock; // unlock the file mutex after validating the checksum
91 unsigned flock_type;
94 static struct command_table_s **command_table;
96 static gpg_error_t do_lock (struct client_s *client, int add);
97 static gpg_error_t validate_checksum (struct client_s *, const char *filename,
98 struct cache_data_s *, unsigned char **,
99 size_t *);
100 static gpg_error_t update_checksum (struct client_s *client,
101 unsigned char *from_crc, size_t crclen);
103 /* When 'status' is true the 'self' field of the status line will be false
104 * because we never send the STATE status message to the same client that
105 * initiated it. */
106 static char *
107 build_client_info_line (struct client_thread_s *thd, int status)
109 char *uid, *username = NULL;
110 char *line;
112 #ifdef WITH_GNUTLS
113 if (thd->remote)
114 uid = str_asprintf("#%s", thd->tls->fp);
115 else
117 uid = str_asprintf("%u", thd->peer->uid);
118 username = get_username (thd->peer->uid);
120 #else
121 uid = str_asprintf("%u", thd->peer->uid);
122 username = get_username (thd->peer->uid);
123 #endif
124 line = str_asprintf ("%p %s %s %s %u %u %u %s %s %u",
125 thd->tid,
126 thd->name ? thd->name : "-",
127 thd->cl && thd->cl->filename
128 && (thd->cl->flags & FLAG_OPEN)
129 ? thd->cl->filename : "/",
130 #ifdef WITH_GNUTLS
131 thd->remote ? thd->peeraddr : "-",
132 #else
133 "-",
134 #endif
135 thd->cl && thd->cl->flags & FLAG_HAS_LOCK ? 1 : 0,
136 !status && pthread_equal (pthread_self (), thd->tid) ? 1 : 0,
137 thd->state, uid,
138 #ifdef WITH_GNUTLS
139 thd->remote ? "-" : username,
140 #else
141 username,
142 #endif
143 thd->conntime
146 xfree (username);
147 xfree (uid);
148 return line;
151 void
152 update_client_state (struct client_s *client, unsigned s)
154 MUTEX_LOCK (&cn_mutex);
155 client->thd->state = s;
156 MUTEX_UNLOCK (&cn_mutex);
158 if (client->thd->state != CLIENT_STATE_UNKNOWN)
160 char *line = build_client_info_line (client->thd, 1);
162 pthread_cleanup_push (xfree, line);
163 if (line)
164 send_status_all_not_self (STATUS_STATE, "%s", line);
165 pthread_cleanup_pop (1);
169 static gpg_error_t
170 unlock_file_mutex (struct client_s *client, int remove)
172 gpg_error_t rc = 0;
174 // OPEN: keep the lock for the same file being reopened.
175 if (client->flags & FLAG_KEEP_LOCK && client->flags & FLAG_HAS_LOCK)
176 return 0;
178 if (!(client->flags & FLAG_HAS_LOCK))
179 return GPG_ERR_NOT_LOCKED;
181 rc = cache_unlock_mutex (client->filename, remove);
182 if (rc)
183 rc = GPG_ERR_INV_STATE;
184 else
185 client->flags &= ~(FLAG_HAS_LOCK | FLAG_LOCK_CMD);
187 return rc;
190 static gpg_error_t
191 lock_file_mutex (struct client_s *client, int add)
193 gpg_error_t rc = 0;
194 long timeout = config_get_long (client->filename, "cache_timeout");
196 if (client->flags & FLAG_HAS_LOCK)
197 return 0;
199 rc = cache_lock_mutex (client->ctx, client->filename,
200 client->lock_timeout, add, timeout);
201 if (!rc)
202 client->flags |= FLAG_HAS_LOCK;
204 return rc;
207 static gpg_error_t
208 file_modified (struct client_s *client, struct command_table_s *cmd)
210 gpg_error_t rc = 0;
211 int type = !cmd->flock_type || (cmd->flock_type & FLOCK_TYPE_SH)
212 ? LOCK_SH : LOCK_EX;
214 if (!(client->flags & FLAG_OPEN))
215 return GPG_ERR_INV_STATE;
217 rc = lock_file_mutex (client, 0);
218 if (rc && rc != GPG_ERR_NO_DATA)
219 return rc;
221 rc = lock_flock (client->ctx, client->filename, type, &client->flock_fd);
222 if (!rc)
224 rc = validate_checksum (client, client->filename, NULL, NULL, NULL);
225 if (gpg_err_code (rc) == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
226 rc = 0;
227 else if (rc)
228 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
230 else if (gpg_err_code (rc) == GPG_ERR_ENOENT)
231 rc = 0;
233 /* FLAG_HAS_LOCK may have been set by the LOCK command or OPEN --lock. */
234 if ((cmd->unlock && !(client->flags & FLAG_HAS_LOCK)) || rc)
235 unlock_file_mutex (client, 0);
237 if (rc || !(cmd->flock_type & FLOCK_TYPE_KEEP))
238 unlock_flock (&client->flock_fd);
240 return rc;
243 static gpg_error_t
244 parse_xml (assuan_context_t ctx, int new)
246 struct client_s *client = assuan_get_pointer (ctx);
247 int cached = client->doc != NULL;
248 gpg_error_t rc = 0;
250 if (new)
252 client->doc = xml_new_document ();
253 if (client->doc)
255 xmlChar *result;
256 int len;
258 xmlDocDumpFormatMemory (client->doc, &result, &len, 0);
259 client->crypto->plaintext = result;
260 client->crypto->plaintext_size = len;
261 if (!client->crypto->plaintext)
263 xmlFreeDoc (client->doc);
264 client->doc = NULL;
265 rc = GPG_ERR_ENOMEM;
268 else
269 rc = GPG_ERR_ENOMEM;
271 else if (!cached)
272 rc = xml_parse_doc ((char *) client->crypto->plaintext,
273 client->crypto->plaintext_size,
274 (xmlDocPtr *)&client->doc);
276 return rc;
279 static void
280 free_client (struct client_s *client)
282 cache_plaintext_release (&client->doc);
283 xfree (client->crc);
284 xfree (client->filename);
285 xfree (client->last_error);
286 crypto_free (client->crypto);
287 client->crypto = NULL;
290 void
291 reset_client (struct client_s *client)
293 assuan_context_t ctx = client->ctx;
294 struct client_thread_s *thd = client->thd;
295 long lock_timeout = client->lock_timeout;
296 xmlErrorPtr xml_error = client->xml_error;
297 int no_pinentry = (client->flags & FLAG_NO_PINENTRY);
298 int flock_fd = client->flock_fd;
300 unlock_file_mutex (client, client->flags & FLAG_NEW);
301 free_client (client);
302 memset (client, 0, sizeof (struct client_s));
303 client->flock_fd = flock_fd;
304 client->xml_error = xml_error;
305 client->ctx = ctx;
306 client->thd = thd;
307 client->lock_timeout = lock_timeout;
308 client->flags |= no_pinentry ? FLAG_NO_PINENTRY : 0;
311 static void
312 req_free (void *arg)
314 if (!arg)
315 return;
317 strv_free ((char **) arg);
320 static gpg_error_t
321 parse_open_opt_lock (void *data, void *value)
323 struct client_s *client = data;
325 (void)value;
326 client->opts |= OPT_LOCK_ON_OPEN;
327 return 0;
330 static gpg_error_t
331 parse_opt_inquire (void *data, void *value)
333 struct client_s *client = data;
335 (void) value;
336 client->opts |= OPT_INQUIRE;
337 return 0;
340 static gpg_error_t
341 update_checksum (struct client_s *client, unsigned char *from_crc,
342 size_t crclen)
344 unsigned char *crc;
345 size_t len;
346 struct cache_data_s *cdata;
347 gpg_error_t rc;
349 if (!from_crc)
351 rc = get_checksum (client->filename, &crc, &len);
352 if (rc)
353 return rc;
355 else
357 crc = from_crc;
358 len = crclen;
361 xfree (client->crc);
362 client->crc = xmalloc (len);
363 memcpy (client->crc, crc, len);
364 pthread_cleanup_push (xfree, crc);
365 cdata = cache_get_data (client->filename, NULL);
366 pthread_cleanup_pop (0);
367 if (cdata)
369 xfree (cdata->crc);
370 cdata->crc = xmalloc (len);
371 memcpy (cdata->crc, crc, len);
374 if (!from_crc)
375 xfree (crc);
376 return 0;
379 static gpg_error_t
380 validate_checksum (struct client_s *client, const char *filename,
381 struct cache_data_s *cdata, unsigned char **r_crc,
382 size_t *r_crclen)
384 unsigned char *crc;
385 size_t len;
386 gpg_error_t rc;
387 int n = 0;
389 if (cdata && !cdata->crc)
390 return GPG_ERR_CHECKSUM;
392 rc = get_checksum (filename, &crc, &len);
393 if (rc)
394 return rc;
396 if (client->crc)
397 n = memcmp (client->crc, crc, len);
398 else if ((client->flags & FLAG_NEW) && cache_get_data (filename, NULL))
399 n = 1;
401 if (!n && cdata)
402 n = memcmp (cdata->crc, crc, len);
404 if (!n && r_crc)
406 *r_crc = crc;
407 *r_crclen = len;
409 else
410 xfree (crc);
412 return n ? GPG_ERR_CHECKSUM : 0;
415 static gpg_error_t
416 open_command (assuan_context_t ctx, char *line)
418 gpg_error_t rc;
419 struct client_s *client = assuan_get_pointer (ctx);
420 int same_file = 0;
421 assuan_peercred_t peer;
422 struct cache_data_s *cdata = NULL;
423 int cached = 0;
424 unsigned char *crc = NULL;
425 size_t crclen = 0;
426 int plaintext = 0;
427 struct argv_s *args[] = {
428 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_open_opt_lock},
429 NULL
432 rc = parse_options (&line, args, client, 1);
433 if (rc)
434 return send_error (ctx, rc);
436 rc = do_validate_peer (ctx, line, &peer);
437 if (rc == GPG_ERR_FORBIDDEN)
439 rc = peer_is_invoker (client);
440 if (rc == GPG_ERR_EACCES)
441 rc = GPG_ERR_FORBIDDEN;
444 if (rc)
445 return send_error (ctx, rc);
447 if (!valid_filename (line))
448 return send_error (ctx, GPG_ERR_INV_VALUE);
450 /* This client may have locked a different file with ISCACHED --lock than
451 * the current filename. This will remove that lock. */
452 same_file = client->filename && !strcmp (line, client->filename);
453 if (client->flags & FLAG_OPEN ||
454 (client->flags & FLAG_HAS_LOCK && !same_file))
456 unsigned opts = client->opts;
457 unsigned flags = client->flags;
459 if (same_file)
460 client->flags |= FLAG_KEEP_LOCK;
462 /* Another client wrote to the same data file as currently opened. */
463 if (cache_get_data (client->filename, NULL))
464 flags &= ~FLAG_NEW;
465 /* Remove cache entry for the new file that hadn't been written. */
466 else if (client->flags & FLAG_NEW)
467 cache_clear (NULL, client->filename, 0, 0);
469 reset_client (client);
470 client->opts = opts;
471 client->flags |= flags;
472 client->flags &= ~(FLAG_LOCK_CMD);
473 if (!same_file)
474 client->flags &= ~(FLAG_HAS_LOCK | FLAG_NEW);
477 client->filename = str_dup (line);
478 if (!client->filename)
479 return send_error(ctx, GPG_ERR_ENOMEM);
481 /* Need to lock the mutex here because file_modified() cannot without
482 * knowing the filename. */
483 rc = lock_file_mutex (client, 1);
484 if (rc)
485 client->flags &= ~FLAG_OPEN;
487 if (!rc)
489 rc = lock_flock (ctx, client->filename, LOCK_SH, &client->flock_fd);
490 if (gpg_err_code (rc) == GPG_ERR_ENOENT)
491 rc = 0;
494 if (!rc)
496 char *keyfile = config_get_string (client->filename, "passphrase_file");
498 rc = crypto_init (&client->crypto, client->ctx, client->filename,
499 client->flags & FLAG_NO_PINENTRY, keyfile);
500 if (rc)
501 xfree (keyfile);
502 else
503 rc = open_check_file (client->filename, NULL, NULL, 1);
506 if (!rc || gpg_err_code (rc) == GPG_ERR_ENOENT)
508 int reload = 0;
509 int defer = 0;
511 if (rc) // new file
513 rc = 0;
515 if (config_get_boolean ("global", "strict_open"))
517 rc = peer_is_invoker (client);
518 if (rc == GPG_ERR_EACCES)
519 rc = GPG_ERR_FORBIDDEN;
522 if (!rc)
524 client->flags |= FLAG_NEW;
525 // data file disappeared. clear the cache entry.
526 cache_clear (NULL, client->filename, 1, 1);
527 cdata = NULL;
530 goto done;
533 cdata = cache_get_data (client->filename, &defer);
534 if (cdata && !defer
535 && !cache_plaintext_get (client->filename, &client->doc))
537 rc = validate_checksum (client, client->filename, cdata, &crc,
538 &crclen);
539 if (rc)
541 log_write ("%s: %s", client->filename,
542 pwmd_strerror (rc));
543 cache_plaintext_release (&client->doc);
544 if (rc == GPG_ERR_CHECKSUM)
546 cache_clear (NULL, client->filename, 1, 1);
547 cdata = NULL;
548 goto decrypt;
552 #ifdef WITH_GNUTLS
553 if (!rc && client->thd->remote
554 && config_get_boolean (client->filename, "tcp_require_key")
555 && !(client->flags & FLAG_NEW))
557 rc = crypto_try_decrypt (client,
558 (client->flags & FLAG_NO_PINENTRY));
560 #endif
561 if (!rc)
563 strv_free (client->crypto->pubkey);
564 client->crypto->pubkey = NULL;
565 if (cdata->pubkey)
566 client->crypto->pubkey = strv_dup (cdata->pubkey);
568 xfree (client->crypto->sigkey);
569 client->crypto->sigkey = NULL;
570 if (cdata->sigkey)
571 client->crypto->sigkey = str_dup (cdata->sigkey);
573 cached = 1;
574 plaintext = 1;
577 else if (cdata && cdata->doc) // cached document
579 if (!rc && !(client->flags & FLAG_NEW))
581 rc = validate_checksum (client, client->filename, cdata, &crc,
582 &crclen);
583 if (rc == GPG_ERR_CHECKSUM)
585 rc = 0;
586 reload = 1;
590 if (!rc)
592 rc = cache_iscached (client->filename, &defer, 0, 0);
593 if ((!rc || rc == GPG_ERR_ENOENT) && defer)
595 rc = 0;
596 reload = 2;
600 if (!rc && reload)
602 if (reload == 1)
603 log_write ("%s: %s", client->filename,
604 pwmd_strerror (GPG_ERR_CHECKSUM));
605 cache_clear (NULL, client->filename, 1, 1);
606 cdata = NULL;
607 rc = crypto_decrypt (client, client->crypto);
609 #ifdef WITH_GNUTLS
610 else if (!rc)
612 if (client->thd->remote
613 && config_get_boolean (client->filename, "tcp_require_key")
614 && !(client->flags & FLAG_NEW))
615 rc = crypto_try_decrypt (client,
616 (client->flags & FLAG_NO_PINENTRY));
618 #endif
620 if (!rc && cdata)
622 client->crypto->plaintext = cdata->doc;
623 client->crypto->plaintext_size = cdata->size;
624 rc = cache_decrypt (client->crypto);
625 if (!rc)
627 cdata->doc = NULL;
628 cdata->size = 0;
630 strv_free (client->crypto->pubkey);
631 client->crypto->pubkey = NULL;
632 if (cdata->pubkey)
633 client->crypto->pubkey = strv_dup (cdata->pubkey);
635 xfree (client->crypto->sigkey);
636 client->crypto->sigkey = NULL;
637 if (cdata->sigkey)
638 client->crypto->sigkey = str_dup (cdata->sigkey);
640 cached = 1;
642 else
644 client->crypto->plaintext = NULL;
645 client->crypto->plaintext_size = 0;
649 else // existing file
651 decrypt:
652 cached = cdata != NULL;
653 rc = crypto_decrypt (client, client->crypto);
657 done:
658 if (!rc && !plaintext)
660 rc = parse_xml (ctx, client->flags & FLAG_NEW);
661 if (!rc)
663 rc = cache_encrypt (client->crypto);
664 if (rc)
665 cache_clear (NULL, client->filename, 1, 1);
666 else
668 long timeout = config_get_long (client->filename,
669 "cache_timeout");
671 cache_free_data_once (cdata);
672 cdata = xcalloc (1, sizeof (struct cache_data_s));
673 cdata->doc = client->crypto->plaintext;
674 cdata->size = client->crypto->plaintext_size;
675 cdata->pubkey = strv_dup(client->crypto->pubkey);
676 cdata->sigkey = client->crypto->sigkey ? str_dup(client->crypto->sigkey) : NULL;
677 client->crypto->plaintext = NULL;
678 client->crypto->plaintext_size = 0;
680 if (cached) // wont increment the refcount
682 if (crclen)
684 xfree (client->crc);
685 client->crc = NULL;
686 xfree (cdata->crc);
687 cdata->crc = xmalloc (crclen);
688 memcpy (cdata->crc, crc, crclen);
691 rc = cache_set_data (client->filename, cdata);
692 /* The cache entry may have been removed and cache_set_data()
693 * already sent STATUS_CACHE. */
694 if (!cache_iscached (client->filename, NULL, 0, 0))
695 rc = send_status (ctx, STATUS_CACHE, NULL);
697 else
698 rc = cache_add_file (client->filename, cdata, timeout);
700 if (!rc)
701 cache_plaintext_set (client->filename, client->doc, 0);
705 else if (!rc)
707 xfree (client->crc);
708 client->crc = NULL;
709 if (crc)
711 client->crc = xmalloc (crclen);
712 memcpy (client->crc, crc, crclen);
716 xfree (crc);
718 if (!rc && !(client->flags & FLAG_NEW) && !cached)
719 rc = update_checksum (client, NULL, 0);
721 if (!rc)
723 client->flags |= FLAG_OPEN;
725 if (client->flags & FLAG_NEW)
726 rc = send_status (ctx, STATUS_NEWFILE, NULL);
728 if (!rc && (client->opts & OPT_LOCK_ON_OPEN))
729 rc = do_lock (client, 0);
732 if (rc)
734 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
736 if (client->flags & FLAG_NEW)
737 cache_clear (NULL, client->filename, 1, 1);
739 crypto_free (client->crypto);
740 client->crypto = NULL;
741 client->flags &= ~FLAG_OPEN;
742 cache_plaintext_release (&client->doc);
744 else
745 crypto_free_non_keys (client->crypto);
747 return send_error (ctx, rc);
750 /* If not the invoking_user or is an existing file, check that the list of user
751 * supplied key ID's are in the list of current key ID's obtained when
752 * decrypting the data file.
754 static gpg_error_t
755 permitted_to_save (struct client_s *client, const char **keys,
756 const char **value)
758 gpg_error_t rc = 0;
759 const char **v;
761 if ((client->flags & FLAG_NEW) || (client->opts & OPT_SYMMETRIC))
762 return 0;
764 rc = peer_is_invoker (client);
765 if (!rc)
766 return 0;
767 else if (rc == GPG_ERR_EACCES)
768 rc = GPG_ERR_FORBIDDEN;
769 else if (rc)
770 return rc;
772 /* Empty match. */
773 if ((!value && !keys) || ((value && !*value) && (keys && !*keys)))
774 return 0;
776 for (v = value; v && *v; v++)
778 const char **k, *pv = *v;
779 int match = 0;
781 if (*pv == '0' && *(pv+1) == 'x')
782 pv += 2;
784 for (k = keys; k && *k; k++)
786 const char *pk = *k;
788 if (*pk == '0' && *(pk+1) == 'x')
789 pk += 2;
791 rc = !strcmp (pv, pk) ? 0 : GPG_ERR_FORBIDDEN;
792 if (rc)
793 rc = !strcmp (pv, *k) ? 0 : GPG_ERR_FORBIDDEN;
795 if (!rc)
797 match = 1;
798 break;
802 if (!match)
803 return GPG_ERR_FORBIDDEN;
806 return rc;
809 /* Requires that the keyid be a fingerprint in 16 byte form. */
810 static gpg_error_t
811 parse_save_opt_keyid_common (struct client_s *client, const char **list,
812 const char *value, char ***dst)
814 gpg_error_t rc = 0;
815 char **keys = NULL;
817 if (value && *value)
819 keys = str_split (value, ",", 0);
820 if (!keys)
821 return GPG_ERR_ENOMEM;
824 rc = crypto_keyid_to_16b (keys);
825 if (!rc)
826 rc = permitted_to_save (client, list, (const char **)keys);
828 if (!rc)
829 *dst = keys;
830 else
831 strv_free (keys);
833 return rc;
836 static gpg_error_t
837 parse_save_opt_keyid (void *data, void *value)
839 struct client_s *client = data;
840 const char *str = value;
841 char **dst = NULL;
842 gpg_error_t rc;
844 rc = parse_save_opt_keyid_common (client,
845 (const char **)client->crypto->pubkey,
846 str, &dst);
847 if (rc)
848 return rc;
850 client->crypto->save.pubkey = dst;
851 return 0;
854 static gpg_error_t
855 parse_save_opt_sign_keyid (void *data, void *value)
857 struct client_s *client = data;
858 const char *str = value;
859 char **dst = NULL;
860 gpg_error_t rc;
861 char **tmp = NULL;
863 if (client->crypto->sigkey)
865 if (!strv_printf (&tmp, "%s", client->crypto->sigkey))
866 return GPG_ERR_ENOMEM;
869 rc = parse_save_opt_keyid_common (client, (const char **)tmp, str, &dst);
870 strv_free (tmp);
871 if (rc)
872 return rc;
874 if (!dst)
875 client->opts |= OPT_NO_SIGNER;
876 else
877 client->crypto->save.sigkey = str_dup (*dst);
879 strv_free (dst);
880 return 0;
883 static gpg_error_t
884 parse_save_opt_inquire_keyid (void *data, void *value)
886 struct client_s *client = data;
888 (void)value;
890 if (!(client->flags & FLAG_NEW))
892 gpg_error_t rc = peer_is_invoker (client);
894 if (rc)
895 return rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc;
898 client->opts |= OPT_INQUIRE_KEYID;
899 return 0;
902 static gpg_error_t
903 parse_save_opt_symmetric (void *data, void *value)
905 struct client_s *client = data;
907 (void)value;
908 client->opts |= OPT_SYMMETRIC;
909 return 0;
912 static gpg_error_t
913 parse_genkey_opt_userid (void *data, void *value)
915 struct client_s *client = data;
917 if (!(client->flags & FLAG_NEW))
919 gpg_error_t rc = peer_is_invoker (client);
921 if (rc)
922 return rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc;
925 client->crypto->save.userid = str_dup (value);
926 return client->crypto->save.userid ? 0 : GPG_ERR_ENOMEM;
929 static gpg_error_t
930 parse_genkey_opt_algo (void *data, void *value)
932 struct client_s *client = data;
934 client->crypto->save.algo = str_dup (value);
935 return client->crypto->save.algo ? 0 : GPG_ERR_ENOMEM;
938 static gpg_error_t
939 parse_genkey_opt_expire (void *data, void *value)
941 struct client_s *client = data;
942 gpg_error_t rc = 0;
943 char *p = NULL;
944 unsigned long t;
946 errno = 0;
947 t = strtoul (value, &p, 10);
949 if (!errno && p && *p)
950 rc = GPG_ERR_INV_VALUE;
951 else if (t == ULONG_MAX)
952 rc = GPG_ERR_INV_VALUE;
953 else if (errno)
954 rc = gpg_error_from_syserror ();
955 else
956 client->crypto->save.expire = t;
958 return rc;
961 static gpg_error_t
962 parse_genkey_opt_no_passphrase (void *data, void *value)
964 struct client_s *client = data;
966 (void)value;
967 client->crypto->save.flags |= GPGME_CREATE_NOPASSWD;
968 return 0;
971 /* Tests that the keys in new_keys are also in old_keys. */
972 static gpg_error_t
973 compare_keys (char **new_keys, char **old_keys)
975 char **o;
977 if (!old_keys || !*old_keys)
978 return 0;
980 crypto_keyid_to_16b (new_keys);
982 for (o = old_keys; *o; o++)
984 char **n;
986 for (n = new_keys; *n; n++)
988 if (!strcmp (*n, *o))
989 break;
992 if (!*n)
993 return GPG_ERR_NOT_FOUND;
996 return 0;
999 static gpg_error_t
1000 inquire_keyid (struct client_s *client)
1002 gpg_error_t rc;
1003 unsigned char *result = NULL;
1004 size_t len;
1005 const char *s = "KEYID";
1006 char ***orig;
1007 char ***save;
1009 orig = &client->crypto->pubkey;
1010 save = &client->crypto->save.pubkey;
1011 rc = assuan_inquire (client->ctx, s, &result, &len, 0);
1012 if (!rc)
1014 char **dst = NULL;
1016 rc = parse_save_opt_keyid_common (client, (const char **)*orig,
1017 (char *)result, &dst);
1018 if (!rc)
1019 *save = dst;
1022 xfree (result);
1023 return rc;
1027 /* When a key lookup in gpg-agent's cache fails, the agent tries the last
1028 * successful key to be unlocked. This prevents pwmd from successfully
1029 * clearing a signing key since the previous key, which more than likely
1030 * belongs to the same keypair as the encryption/decryption key, will have the
1031 * passphrase cached and therefore the signing key also cached. So we need to
1032 * clear both the signing and encryption keys to get the effect of requiring a
1033 * passphrase when generating a new keypair for an existing data file, or when
1034 * the "require_save_key" configuration parameter is set. This parameter is
1035 * mostly a failsafe of the gpg-agent option --ignore-cache-for-signing since
1036 * some/most/all users may fail to set it.
1038 static gpg_error_t
1039 save_command (assuan_context_t ctx, char *line)
1041 struct client_s *client = assuan_get_pointer (ctx);
1042 struct cache_data_s *cdata = NULL;
1043 int sym = 0;
1044 gpg_error_t rc = 0, cache_rc = 0;
1045 int defer = 0;
1046 struct argv_s *args[] = {
1047 &(struct argv_s) {"keyid", OPTION_TYPE_ARG, parse_save_opt_keyid},
1048 &(struct argv_s) {"inquire-keyid", OPTION_TYPE_NOARG,
1049 parse_save_opt_inquire_keyid },
1050 &(struct argv_s) {"sign-keyid", OPTION_TYPE_OPTARG,
1051 parse_save_opt_sign_keyid},
1052 &(struct argv_s) {"symmetric", OPTION_TYPE_NOARG,
1053 parse_save_opt_symmetric },
1054 NULL
1057 crypto_free_save (&client->crypto->save);
1058 client->crypto->save.expire = DEFAULT_EXPIRE;
1060 rc = crypto_is_symmetric (client->filename);
1061 if (!rc || rc == GPG_ERR_BAD_DATA || rc == GPG_ERR_ENOENT)
1063 if (!rc)
1065 client->opts |= OPT_SYMMETRIC;
1066 sym = 1;
1068 else if (rc == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
1069 rc = 0; // New file
1070 else
1071 rc = 0; // PKI
1074 if (rc)
1075 return send_error (ctx, rc);
1077 rc = parse_options (&line, args, client, 0);
1078 if (rc)
1079 return send_error (ctx, rc);
1081 if (config_get_boolean (client->filename, "require_save_key")
1082 || (client->opts & OPT_SYMMETRIC))
1083 client->opts |= OPT_ASK;
1085 rc = open_check_file (client->filename, NULL, NULL, 1);
1086 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
1088 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
1089 return send_error (ctx, rc);
1092 if (!rc)
1093 cache_rc = rc = cache_iscached (client->filename, &defer, 0, 1);
1095 if (gpg_err_code (rc) == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
1096 rc = 0;
1097 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
1098 rc = 0;
1100 if (rc)
1101 return send_error (ctx, rc);
1103 /* Specifying both a recipient and symmetric encryption is an error. */
1104 if ((client->opts & OPT_INQUIRE_KEYID) && (client->opts & OPT_SYMMETRIC))
1105 return send_error (ctx, GPG_ERR_CONFLICT);
1106 /* Existing file with a recipient and wanting symmetric is an error. */
1107 else if ((client->opts & OPT_SYMMETRIC) && client->crypto->save.pubkey)
1108 return send_error (ctx, GPG_ERR_CONFLICT);
1109 else if (client->crypto->save.pubkey && (client->opts & OPT_INQUIRE_KEYID))
1110 return send_error (ctx, GPG_ERR_CONFLICT);
1111 else if (!sym && (client->opts & OPT_SYMMETRIC) && !(client->flags & FLAG_NEW))
1112 return send_error (ctx, GPG_ERR_CONFLICT);
1113 /* New file that is not symmetric without either a recipient or signer. */
1114 else if ((client->flags & FLAG_NEW) && !(client->opts & OPT_SYMMETRIC)
1115 && (!client->crypto->save.pubkey || !client->crypto->save.sigkey))
1116 return send_error (ctx, GPG_ERR_SYNTAX);
1117 else if (client->opts & OPT_INQUIRE_KEYID)
1118 rc = inquire_keyid (client);
1120 if (!rc)
1122 client->crypto->keyfile = config_get_string (client->filename,
1123 "passphrase_file");
1124 rc = crypto_init_ctx (client->crypto, (client->flags & FLAG_NO_PINENTRY),
1125 client->crypto->keyfile);
1128 if (!rc && (client->flags & FLAG_NEW))
1130 /* Require --keyid when --sign-keyid exists to keep KEYINFO
1131 * synchronized. */
1132 if (!client->crypto->save.pubkey && client->crypto->save.sigkey
1133 && !(client->opts & OPT_SYMMETRIC))
1134 rc = GPG_ERR_NO_PUBKEY;
1136 else if (!rc)
1138 cdata = cache_get_data (client->filename, NULL);
1139 if (cdata)
1141 if (client->crypto->save.pubkey)
1142 rc = compare_keys (client->crypto->save.pubkey, cdata->pubkey);
1144 /* Always allow a signer for symmetric data files. */
1145 if (!rc && client->crypto->save.sigkey
1146 && !(client->opts & OPT_SYMMETRIC))
1147 rc = !strcmp (client->crypto->save.sigkey, cdata->sigkey)
1148 ? 0 : GPG_ERR_NOT_FOUND;
1150 /* Prevent saving to a recipient who is not in the original recipient
1151 * list without a passphrase. */
1152 if (rc || (client->crypto->sigkey && (client->opts & OPT_NO_SIGNER)))
1153 client->opts |= OPT_ASK;
1155 if (rc == GPG_ERR_NOT_FOUND)
1157 rc = peer_is_invoker (client);
1158 if (rc == GPG_ERR_EACCES)
1159 rc = GPG_ERR_FORBIDDEN;
1162 if (!client->crypto->save.pubkey
1163 && !(client->opts & OPT_SYMMETRIC))
1164 client->crypto->save.pubkey = strv_dup (cdata->pubkey);
1166 if (!rc && !client->crypto->save.sigkey && cdata->sigkey
1167 && !(client->opts & OPT_NO_SIGNER))
1168 client->crypto->save.sigkey = str_dup (cdata->sigkey);
1169 else if (!rc && !client->crypto->save.sigkey
1170 && (client->opts & OPT_NO_SIGNER)
1171 && !(client->opts & OPT_SYMMETRIC))
1172 rc = GPG_ERR_NO_SIGNATURE_SCHEME;
1174 else
1176 client->crypto->save.pubkey = strv_dup (client->crypto->pubkey);
1177 client->crypto->save.sigkey = str_dup (client->crypto->sigkey);
1181 if (!rc && !(client->flags & FLAG_NEW))
1183 /* Fixes {NEW_,SIGN_}PASSPHRASE inquire keywords. See passphrase_cb(). */
1184 if (client->opts & OPT_SYMMETRIC)
1185 client->crypto->flags |= CRYPTO_FLAG_PASSWD;
1187 if (client->opts & OPT_ASK)
1189 rc = cache_clear_agent_keys (client->filename, 1, 1);
1190 if (!rc)
1191 rc = crypto_try_decrypt (client, client->flags & FLAG_NO_PINENTRY);
1195 if (!rc && client->opts & OPT_SYMMETRIC)
1196 client->crypto->flags |= CRYPTO_FLAG_PASSWD_NEW;
1198 if (!rc)
1199 rc = xml_update_element_mtime (client, xmlDocGetRootElement (client->doc));
1201 if (!rc)
1203 int size;
1205 xmlDocDumpFormatMemory (client->doc, &client->crypto->plaintext, &size,
1207 if (size > 0)
1208 client->crypto->plaintext_size = (size_t) size;
1209 else
1210 rc = GPG_ERR_ENOMEM;
1212 if (!rc)
1214 client->crypto->flags |= (client->opts & OPT_SYMMETRIC) ? CRYPTO_FLAG_SYMMETRIC : 0;
1215 client->crypto->flags |= (client->flags & FLAG_NEW) ? CRYPTO_FLAG_NEWFILE : 0;
1216 client->crypto->flags |= !(client->opts & OPT_SYMMETRIC) ? CRYPTO_FLAG_PASSWD_SIGN : 0;
1217 rc = crypto_encrypt (client, client->crypto);
1218 client->crypto->flags &= ~CRYPTO_FLAG_SYMMETRIC;
1221 if (!rc)
1223 unsigned char *crc = NULL;
1224 size_t crclen = 0;
1226 rc = crypto_write_file (client->crypto, &crc, &crclen);
1227 pthread_cleanup_push ((void *)xfree, crc);
1228 if (!rc)
1230 if (!cache_rc)
1231 cdata = cache_get_data (client->filename, NULL);
1232 else
1233 cdata = xcalloc (1, sizeof (struct cache_data_s));
1236 if (!rc)
1238 rc = cache_encrypt (client->crypto);
1239 if (rc)
1241 cache_clear (NULL, client->filename, 1, 1);
1242 client->flags &= ~(FLAG_NEW);
1244 strv_free (client->crypto->pubkey);
1245 client->crypto->pubkey = NULL;
1246 if (client->crypto->save.pubkey)
1247 client->crypto->pubkey = strv_dup (client->crypto->save.pubkey);
1249 xfree (client->crypto->sigkey);
1250 client->crypto->sigkey = NULL;
1251 if (client->crypto->save.sigkey)
1252 client->crypto->sigkey = str_dup (client->crypto->save.sigkey);
1256 if (!rc)
1258 long timeout = config_get_long (client->filename, "cache_timeout");
1259 xmlDocPtr doc = xmlCopyDoc (client->doc, 1);
1261 if (!doc)
1262 rc = GPG_ERR_ENOMEM;
1264 if (!rc)
1266 cache_plaintext_release (&client->doc);
1267 strv_free (cdata->pubkey);
1268 cdata->pubkey = client->crypto->save.pubkey;
1269 client->crypto->save.pubkey = NULL;
1271 xfree (cdata->sigkey);
1272 cdata->sigkey = client->crypto->save.sigkey;
1273 client->crypto->save.sigkey = NULL;
1275 xfree (cdata->crc);
1276 cdata->crc = NULL;
1278 /* cache_encrypt() does in-place encryption */
1279 xfree (cdata->doc);
1280 cdata->doc = client->crypto->plaintext;
1281 client->crypto->plaintext = NULL;
1282 cdata->size = client->crypto->plaintext_size;
1283 client->crypto->plaintext_size = 0;
1285 client->doc = doc;
1286 cache_plaintext_set (client->filename, client->doc, 0);
1288 /* Update in case the cache entry expires the next SAVE may
1289 * not have any known keys. */
1290 strv_free (client->crypto->pubkey);
1291 client->crypto->pubkey = NULL;
1292 if (cdata->pubkey)
1293 client->crypto->pubkey = strv_dup (cdata->pubkey);
1295 xfree (client->crypto->sigkey);
1296 client->crypto->sigkey = NULL;
1297 if (cdata->sigkey)
1298 client->crypto->sigkey = str_dup (cdata->sigkey);
1300 if (!cache_rc) // wont increment refcount
1301 rc = cache_set_data (client->filename, cdata);
1302 else
1303 rc = cache_add_file (client->filename, cdata, timeout);
1306 if (!rc && (cache_rc || (client->flags & FLAG_NEW)))
1307 send_status_all (STATUS_CACHE, NULL);
1309 if (!rc)
1311 rc = update_checksum (client, crc, crclen);
1312 client->flags &= ~(FLAG_NEW);
1316 pthread_cleanup_pop (1);
1317 if (!rc)
1318 client->did_cow = 0;
1322 crypto_free_non_keys (client->crypto);
1323 return send_error (ctx, rc);
1326 static gpg_error_t
1327 parse_genkey_opt_usage (void *data, void *v)
1329 struct client_s *client = data;
1330 char *value = v;
1332 if (!value || !*value)
1333 return GPG_ERR_INV_VALUE;
1334 else if (!strcmp (value, "sign"))
1335 client->crypto->save.flags |= GPGME_CREATE_SIGN;
1336 else if (!strcmp (value, "encrypt"))
1337 client->crypto->save.flags |= GPGME_CREATE_ENCR;
1338 else if (!strcmp (value, "default"))
1339 client->crypto->save.flags &= ~(GPGME_CREATE_ENCR|GPGME_CREATE_SIGN);
1340 else
1341 return GPG_ERR_INV_VALUE;
1343 return 0;
1346 gpg_error_t
1347 parse_genkey_opt_subkey_of (void *data, void *v)
1349 gpg_error_t rc;
1350 struct client_s *client = data;
1351 char *value = v;
1352 char *tmp[] = { value, NULL };
1353 gpgme_key_t *keys = NULL;
1355 rc = peer_is_invoker (client);
1356 if (rc)
1357 return rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc;
1359 if (!value || !*value)
1360 return GPG_ERR_INV_VALUE;
1362 rc = crypto_list_keys (client->crypto, tmp, 1, &keys);
1363 if (rc)
1364 return rc;
1366 if (!keys || !*keys)
1368 crypto_free_key_list (keys);
1369 return GPG_ERR_NO_SECKEY;
1372 client->crypto->save.mainkey = keys;
1373 return 0;
1376 static gpg_error_t
1377 genkey_command (assuan_context_t ctx, char *line)
1379 struct client_s *client = assuan_get_pointer (ctx);
1380 struct crypto_s *crypto, *orig;
1381 gpg_error_t rc = 0;
1382 struct argv_s *args[] = {
1383 &(struct argv_s) {"userid", OPTION_TYPE_ARG,
1384 parse_genkey_opt_userid},
1385 &(struct argv_s) {"expire", OPTION_TYPE_ARG,
1386 parse_genkey_opt_expire},
1387 &(struct argv_s) {"algo", OPTION_TYPE_ARG,
1388 parse_genkey_opt_algo},
1389 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG,
1390 parse_genkey_opt_no_passphrase},
1391 &(struct argv_s) {"usage", OPTION_TYPE_ARG,
1392 parse_genkey_opt_usage},
1393 &(struct argv_s) {"subkey-of", OPTION_TYPE_ARG,
1394 parse_genkey_opt_subkey_of},
1395 NULL
1398 if (!(client->flags & FLAG_OPEN))
1399 return send_error (ctx, GPG_ERR_INV_STATE);
1401 rc = crypto_init (&crypto, ctx, client->filename,
1402 client->flags & FLAG_NO_PINENTRY, NULL);
1403 if (rc)
1404 return send_error (ctx, rc);
1406 pthread_cleanup_push ((void *)crypto_free, client->crypto);
1407 orig = client->crypto;
1408 client->crypto = crypto;
1409 rc = parse_options (&line, args, client, 0);
1410 if (rc)
1411 goto fail;
1413 if (!client->crypto->save.userid && !client->crypto->save.mainkey)
1415 rc = GPG_ERR_SYNTAX;
1416 goto fail;
1419 client->crypto->flags |= CRYPTO_FLAG_NEWFILE;
1420 rc = crypto_genkey (client, client->crypto);
1422 fail:
1423 pthread_cleanup_pop (0);
1424 crypto_free (crypto);
1425 client->crypto = orig;
1426 return send_error (ctx, rc);
1429 static gpg_error_t
1430 do_delete (assuan_context_t ctx, char *line)
1432 struct client_s *client = assuan_get_pointer (ctx);
1433 struct xml_request_s *req;
1434 xmlNodePtr n;
1435 gpg_error_t rc;
1437 rc = xml_new_request (client, line, XML_CMD_DELETE, &req);
1438 if (rc)
1439 return rc;
1441 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1442 xml_free_request (req);
1443 if (rc)
1444 return rc;
1446 rc = xml_is_element_owner (client, n);
1447 if (!rc)
1448 rc = xml_unlink_node (client, n);
1450 return rc;
1453 /* Won't update cdata->plaintext. Other clients are working on the original or
1454 * copy of the same document. The first client to SAVE wins and requires others
1455 * to reopen the data file do to a checksum error. */
1456 static gpg_error_t
1457 copy_on_write (struct client_s *client)
1459 struct cache_data_s *cdata;
1461 if (client->did_cow)
1462 return 0;
1464 cdata = cache_get_data (client->filename, NULL);
1465 if (cdata)
1467 gpg_error_t rc;
1468 xmlDocPtr doc = xmlCopyDoc (client->doc, 1);
1470 if (!doc)
1471 return GPG_ERR_ENOMEM;
1473 rc = cache_plaintext_set (client->filename, doc, 1);
1474 if (rc)
1476 xmlFree (doc);
1477 return rc;
1480 (void)cache_plaintext_release (&client->doc);
1481 client->doc = doc;
1482 client->did_cow = 1;
1483 return 0;
1486 return GPG_ERR_NO_DATA;
1489 static gpg_error_t
1490 delete_command (assuan_context_t ctx, char *line)
1492 struct client_s *client = assuan_get_pointer (ctx);
1493 gpg_error_t rc;
1494 struct argv_s *args[] = {
1495 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1496 NULL
1499 rc = parse_options (&line, args, client, 1);
1500 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1501 rc = GPG_ERR_SYNTAX;
1502 if (rc)
1503 return send_error (ctx, rc);
1505 rc = copy_on_write (client);
1506 if (rc)
1507 return send_error (ctx, rc);
1509 if (client->opts & OPT_INQUIRE)
1511 unsigned char *result;
1512 size_t len;
1514 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1515 if (rc)
1516 return send_error (ctx, rc);
1518 pthread_cleanup_push ((void *)xfree, result);
1519 rc = do_delete (ctx, (char *)result);
1520 pthread_cleanup_pop (1);
1522 else
1523 rc = do_delete (ctx, line);
1525 return send_error (ctx, rc);
1528 static gpg_error_t
1529 update_element_expirey (struct client_s *client, xmlNodePtr n)
1531 gpg_error_t rc = 0;
1532 xmlChar *expire, *incr;
1533 char *p;
1534 time_t e, e_orig, i;
1535 time_t now = time (NULL);
1537 expire = xml_attribute_value (n, (xmlChar *)"expire");
1538 if (!expire)
1539 return 0;
1541 errno = 0;
1542 e = strtoul ((char *)expire, &p, 10);
1543 if (errno || *p || e == ULONG_MAX || *expire == '-')
1545 xmlFree (expire);
1546 rc = GPG_ERR_ERANGE;
1547 goto fail;
1550 xmlFree (expire);
1551 incr = xml_attribute_value (n, (xmlChar *)"expire_increment");
1552 if (!incr)
1553 return 0;
1555 i = strtoul ((char *)incr, &p, 10);
1556 if (errno || *p || i == ULONG_MAX || *incr == '-')
1558 xmlFree (incr);
1559 rc = GPG_ERR_ERANGE;
1560 goto fail;
1563 xmlFree (incr);
1564 e_orig = e;
1565 e = now + i;
1566 p = str_asprintf ("%lu", e);
1567 if (!p)
1569 rc = GPG_ERR_ENOMEM;
1570 goto fail;
1573 rc = xml_add_attribute (client, n, "expire", p);
1574 xfree (p);
1575 if (!rc)
1576 rc = send_status (client->ctx, STATUS_EXPIRE, "%lu %lu", e_orig, e);
1578 fail:
1579 return rc;
1582 static gpg_error_t
1583 store_command (assuan_context_t ctx, char *line)
1585 struct client_s *client = assuan_get_pointer (ctx);
1586 gpg_error_t rc;
1587 size_t len;
1588 unsigned char *result;
1589 xmlNodePtr n, parent;
1590 int has_content;
1591 char *content = NULL;
1592 struct xml_request_s *req;
1594 if (line && *line)
1595 return send_error (ctx, GPG_ERR_SYNTAX);
1597 rc = copy_on_write (client);
1598 if (rc)
1599 return send_error (ctx, rc);
1601 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1602 if (rc)
1603 return send_error (ctx, rc);
1605 rc = xml_new_request (client, (char *)result, XML_CMD_STORE, &req);
1606 xfree (result);
1607 if (rc)
1608 return send_error (ctx, rc);
1610 /* Prevent passing the element content around to save some memory. */
1611 len = strv_length (req->args);
1612 has_content = line && line[strlen (line) - 1] != '\t' && len > 1;
1613 if (*(req->args+1) && !xml_valid_element_path (req->args, has_content))
1615 xml_free_request (req);
1616 return send_error (ctx, GPG_ERR_INV_VALUE);
1619 if (has_content || !*req->args[len-1])
1621 content = req->args[len-1];
1622 req->args[len-1] = NULL;
1625 if (strv_length (req->args) > 1)
1627 rc = xml_check_recursion (client, req);
1628 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
1629 goto fail;
1632 parent = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1634 if (!rc && len > 1)
1636 rc = xml_is_element_owner (client, parent);
1637 if (!rc)
1639 n = xml_find_text_node (parent->children);
1640 if (n)
1641 xmlNodeSetContent (n, (xmlChar *) content);
1642 else
1643 xmlNodeAddContent (parent, (xmlChar *) content);
1645 (void)xml_update_element_mtime (client, parent);
1646 (void)update_element_expirey (client, parent);
1650 fail:
1651 xfree (content);
1652 xml_free_request (req);
1653 return send_error (ctx, rc);
1656 static gpg_error_t
1657 xfer_data (assuan_context_t ctx, const char *line, int total)
1659 struct client_s *client = assuan_get_pointer (ctx);
1660 int to_send;
1661 int sent = 0;
1662 gpg_error_t rc = 0;
1663 int progress = config_get_integer ("global", "xfer_progress");
1664 int flush = 0;
1666 if (!(client->flags & FLAG_LOCK_CMD))
1667 rc = unlock_file_mutex (client, 0);
1668 if (rc && rc != GPG_ERR_NOT_LOCKED)
1669 return rc;
1671 progress =
1672 progress > 0 ? (progress / ASSUAN_LINELENGTH) * ASSUAN_LINELENGTH : 0;
1673 to_send = total < ASSUAN_LINELENGTH ? total : ASSUAN_LINELENGTH;
1674 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1676 if (rc)
1677 return rc;
1679 again:
1682 if (sent + to_send > total)
1683 to_send = total - sent;
1685 rc = assuan_send_data (ctx, flush ? NULL : (char *) line + sent,
1686 flush ? 0 : to_send);
1687 if (!rc)
1689 sent += flush ? 0 : to_send;
1691 if ((progress && !(sent % progress) && sent != total) ||
1692 (sent == total && flush))
1693 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1695 if (!flush && !rc && sent == total)
1697 flush = 1;
1698 goto again;
1702 while (!rc && sent < total);
1704 return rc;
1707 static gpg_error_t
1708 do_get (assuan_context_t ctx, char *line)
1710 struct client_s *client = assuan_get_pointer (ctx);
1711 gpg_error_t rc;
1712 struct xml_request_s *req;
1713 xmlNodePtr n;
1715 rc = xml_new_request (client, line, XML_CMD_NONE, &req);
1716 if (rc)
1717 return rc;
1719 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1720 if (!rc)
1722 if (n && n->children)
1724 xmlNodePtr tmp = n;
1726 n = xml_find_text_node (n->children);
1727 if (!n || !n->content || !*n->content)
1728 rc = GPG_ERR_NO_DATA;
1729 else
1731 rc = xfer_data (ctx, (char *) n->content, xmlStrlen (n->content));
1732 if (!rc)
1734 xmlChar *expire = xml_attribute_value (tmp,
1735 (xmlChar *)"expire");
1736 if (expire)
1738 time_t now = time (NULL);
1739 time_t e;
1740 char *p;
1742 errno = 0;
1743 e = strtoul ((char *)expire, &p, 10);
1744 if (errno || *p || e == ULONG_MAX || *expire == '-')
1745 log_write (_("invalid expire attribute value: %s"),
1746 expire);
1747 else if (now >= e)
1749 pthread_cleanup_push (xmlFree, expire);
1750 rc = send_status (ctx, STATUS_EXPIRE, "%lu 0", e);
1751 pthread_cleanup_pop (0);
1754 xmlFree (expire);
1759 else
1760 rc = GPG_ERR_NO_DATA;
1763 xml_free_request (req);
1764 return rc;
1767 static gpg_error_t
1768 get_command (assuan_context_t ctx, char *line)
1770 struct client_s *client = assuan_get_pointer (ctx);
1771 gpg_error_t rc;
1772 struct argv_s *args[] = {
1773 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1774 NULL
1777 rc = parse_options (&line, args, client, 1);
1778 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1779 rc = GPG_ERR_SYNTAX;
1780 if (rc)
1781 return send_error (ctx, rc);
1783 if (client->opts & OPT_INQUIRE)
1785 unsigned char *result;
1786 size_t len;
1788 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1789 if (rc)
1790 return send_error (ctx, rc);
1792 pthread_cleanup_push ((void *)xfree, result);
1793 rc = do_get (ctx, (char *)result);
1794 pthread_cleanup_pop (1);
1796 else
1797 rc = do_get (ctx, line);
1799 return send_error (ctx, rc);
1802 static void list_command_free1 (void *arg);
1803 static gpg_error_t
1804 realpath_command (assuan_context_t ctx, char *line)
1806 gpg_error_t rc;
1807 char **realpath = NULL;
1808 struct client_s *client = assuan_get_pointer (ctx);
1809 struct argv_s *args[] = {
1810 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1811 NULL
1814 rc = parse_options (&line, args, client, 1);
1815 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1816 rc = GPG_ERR_SYNTAX;
1817 if (rc)
1818 return send_error (ctx, rc);
1820 if (client->opts & OPT_INQUIRE)
1822 unsigned char *result;
1823 size_t len;
1825 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1826 if (rc)
1827 return send_error (ctx, rc);
1829 pthread_cleanup_push ((void *)xfree, result);
1830 (void)xml_resolve_path (client, client->doc, result, &realpath, &rc);
1831 pthread_cleanup_pop (1);
1833 else
1834 (void)xml_resolve_path (client, client->doc, (unsigned char *)line,
1835 &realpath, &rc);
1837 if (!rc)
1839 char *tmp = strv_join ((char *)"\t", realpath);
1841 strv_free (realpath);
1842 if (!tmp)
1843 return send_error (ctx, GPG_ERR_ENOMEM);
1845 pthread_cleanup_push ((void *)xfree, tmp);
1846 rc = xfer_data (ctx, tmp, strlen (tmp));
1847 pthread_cleanup_pop (1);
1850 return send_error (ctx, rc);
1853 static void
1854 list_command_free1 (void *arg)
1856 if (arg)
1857 string_free ((struct string_s *) arg, 1);
1860 static gpg_error_t
1861 parse_list_opt_recurse (void *data, void *value)
1863 struct client_s *client = data;
1865 (void)value;
1866 client->opts |= OPT_LIST_RECURSE;
1867 return 0;
1870 static gpg_error_t
1871 parse_opt_verbose (void *data, void *value)
1873 struct client_s *client = data;
1875 (void)value;
1876 client->opts |= OPT_VERBOSE;
1877 return 0;
1880 static gpg_error_t
1881 list_path_once (struct client_s *client, char *line,
1882 struct element_list_s *elements, struct string_s *result)
1884 gpg_error_t rc;
1886 rc = xml_create_path_list (client, client->doc, NULL, elements, line, 0);
1887 if (rc == GPG_ERR_ELOOP || rc == GPG_ERR_EACCES)
1888 rc = 0;
1890 if (!rc)
1892 int total = slist_length (elements->list);
1894 if (total)
1896 int i;
1898 for (i = 0; i < total; i++)
1900 char *tmp = slist_nth_data (elements->list, i);
1902 string_append_printf (result, "%s%s", tmp,
1903 i + 1 == total ? "" : "\n");
1906 else
1907 rc = GPG_ERR_NO_DATA;
1910 return rc;
1913 static gpg_error_t
1914 do_list (assuan_context_t ctx, char *line)
1916 struct client_s *client = assuan_get_pointer (ctx);
1917 gpg_error_t rc = GPG_ERR_NO_DATA;
1918 struct element_list_s *elements = NULL;
1920 if (!line || !*line)
1922 struct string_s *str = string_new (NULL);
1923 xmlNodePtr n;
1925 if (!str)
1926 return GPG_ERR_ENOMEM;
1928 pthread_cleanup_push ((void *)list_command_free1, str);
1929 n = xmlDocGetRootElement (client->doc);
1930 for (n = n->children; n; n = n->next)
1932 xmlChar *name;
1934 if (n->type != XML_ELEMENT_NODE)
1935 continue;
1937 name = xmlGetProp (n, (xmlChar *)"_name");
1938 if (!name)
1940 rc = GPG_ERR_ENOMEM;
1941 break;
1944 elements = xcalloc (1, sizeof (struct element_list_s));
1945 if (!elements)
1947 xmlFree (name);
1948 rc = GPG_ERR_ENOMEM;
1949 break;
1952 elements->prefix = string_new (NULL);
1953 if (!elements->prefix)
1955 xmlFree (name);
1956 xml_free_element_list (elements);
1957 rc = GPG_ERR_ENOMEM;
1958 break;
1961 elements->recurse = client->opts & OPT_LIST_RECURSE;
1962 elements->root_only = !elements->recurse;
1963 pthread_cleanup_push ((void *)xml_free_element_list, elements);
1964 rc = list_path_once (client, (char *)name, elements, str);
1965 xmlFree (name);
1966 pthread_cleanup_pop (1);
1967 if (rc)
1968 break;
1970 if (n->next)
1971 string_append (str, "\n");
1974 if (!rc)
1975 rc = xfer_data (ctx, str->str, str->len);
1977 pthread_cleanup_pop (1);
1978 return rc;
1981 elements = xcalloc (1, sizeof (struct element_list_s));
1982 if (!elements)
1983 return GPG_ERR_ENOMEM;
1985 elements->prefix = string_new (NULL);
1986 if (!elements->prefix)
1988 xml_free_element_list (elements);
1989 return GPG_ERR_ENOMEM;
1992 elements->recurse = client->opts & OPT_LIST_RECURSE;
1993 pthread_cleanup_push ((void *)xml_free_element_list, elements);
1994 struct string_s *str = string_new (NULL);
1995 pthread_cleanup_push ((void *)list_command_free1, str);
1996 rc = list_path_once (client, line, elements, str);
1997 if (!rc)
1998 rc = xfer_data (ctx, str->str, str->len);
2000 pthread_cleanup_pop (1);
2001 pthread_cleanup_pop (1);
2002 return rc;
2005 static gpg_error_t
2006 list_command (assuan_context_t ctx, char *line)
2008 struct client_s *client = assuan_get_pointer (ctx);
2009 gpg_error_t rc;
2010 struct argv_s *args[] = {
2011 &(struct argv_s) {"recurse", OPTION_TYPE_NOARG, parse_list_opt_recurse},
2012 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2013 /* These are deprecated but kept for backward compatibility with older
2014 * clients. */
2015 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, NULL},
2016 &(struct argv_s) {"with-target", OPTION_TYPE_NOARG, NULL},
2017 &(struct argv_s) {"all", OPTION_TYPE_NOARG, parse_list_opt_recurse},
2018 &(struct argv_s) {"no-recurse", OPTION_TYPE_NOARG, NULL},
2019 NULL
2022 if (disable_list_and_dump == 1)
2023 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2025 rc = parse_options (&line, args, client, 1);
2026 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2027 rc = GPG_ERR_SYNTAX;
2028 if (rc)
2029 return send_error (ctx, rc);
2031 if (client->opts & OPT_INQUIRE)
2033 unsigned char *result;
2034 size_t len;
2036 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2037 if (rc)
2038 return send_error (ctx, rc);
2040 pthread_cleanup_push ((void *)xfree, result);
2041 rc = do_list (ctx, (char *)result);
2042 pthread_cleanup_pop (1);
2044 else
2045 rc = do_list (ctx, line);
2047 return send_error (ctx, rc);
2050 #define RESUMABLE_ERROR(rc) (rc == GPG_ERR_ELOOP || rc == GPG_ERR_EACCES \
2051 || rc == GPG_ERR_ELEMENT_NOT_FOUND || !rc)
2053 * args[0] - element path
2055 static gpg_error_t
2056 attribute_list (assuan_context_t ctx, char **args)
2058 struct client_s *client = assuan_get_pointer (ctx);
2059 char **attrlist = NULL;
2060 int i = 0;
2061 int target = 0;
2062 xmlAttrPtr a;
2063 xmlNodePtr n, an, r;
2064 char *line;
2065 gpg_error_t rc;
2066 struct xml_request_s *req;
2068 if (!args || !args[0] || !*args[0])
2069 return GPG_ERR_SYNTAX;
2071 rc = xml_new_request (client, args[0], XML_CMD_ATTR_LIST, &req);
2072 if (rc)
2073 return rc;
2075 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2076 xml_free_request (req);
2077 if (rc)
2078 return rc;
2080 again:
2081 for (a = n->properties; a; a = a->next)
2083 char **pa;
2085 if (target && xml_reserved_attribute ((char *)a->name))
2086 continue;
2088 pa = xrealloc (attrlist, (i + 2) * sizeof (char *));
2089 if (!pa)
2091 if (attrlist)
2092 strv_free (attrlist);
2094 log_write ("%s(%i): %s", __FILE__, __LINE__,
2095 pwmd_strerror (GPG_ERR_ENOMEM));
2096 return GPG_ERR_ENOMEM;
2099 attrlist = pa;
2100 an = a->children;
2101 attrlist[i] = str_asprintf ("%s %s", (char *) a->name, an && an->content
2102 ? (char *)an->content : "");
2104 if (!attrlist[i])
2106 strv_free (attrlist);
2107 log_write ("%s(%i): %s", __FILE__, __LINE__,
2108 pwmd_strerror (GPG_ERR_ENOMEM));
2109 return GPG_ERR_ENOMEM;
2112 attrlist[++i] = NULL;
2115 if (!attrlist)
2116 return GPG_ERR_NO_DATA;
2118 if (!target)
2120 r = xml_resolve_path (client, client->doc, (xmlChar *)args[0], NULL, &rc);
2121 if (!RESUMABLE_ERROR (rc))
2123 strv_free (attrlist);
2124 return rc;
2126 else if (!rc && r != n)
2128 target = 1;
2129 n = r;
2130 goto again;
2133 rc = 0;
2136 line = strv_join ("\n", attrlist);
2137 if (!line)
2139 log_write ("%s(%i): %s", __FILE__, __LINE__,
2140 pwmd_strerror (GPG_ERR_ENOMEM));
2141 strv_free (attrlist);
2142 return GPG_ERR_ENOMEM;
2145 pthread_cleanup_push ((void *)xfree, line);
2146 pthread_cleanup_push ((void *)req_free, attrlist);
2147 rc = xfer_data (ctx, line, strlen (line));
2148 pthread_cleanup_pop (1);
2149 pthread_cleanup_pop (1);
2150 return rc;
2154 * args[0] - attribute
2155 * args[1] - element path
2157 static gpg_error_t
2158 attribute_delete (struct client_s *client, char **args)
2160 gpg_error_t rc;
2161 xmlNodePtr n;
2163 if (!args || !args[0] || !*args[0] || !args[1] || !*args[1])
2164 return GPG_ERR_SYNTAX;
2166 if (!strcmp (args[0], "_name") || !strcmp (args[0], "target"))
2167 return GPG_ERR_INV_ATTR;
2169 rc = copy_on_write (client);
2170 if (rc)
2171 return rc;
2173 if (!xml_reserved_attribute (args[0]))
2174 n = xml_resolve_path (client, client->doc, (xmlChar *)args[1], NULL, &rc);
2175 else
2177 struct xml_request_s *req;
2179 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
2180 if (rc)
2181 return rc;
2183 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2184 xml_free_request (req);
2187 if (!rc)
2188 rc = xml_is_element_owner (client, n);
2190 if (!rc)
2191 rc = xml_delete_attribute (client, n, (xmlChar *) args[0]);
2193 return rc;
2197 * Creates the "target" attribute. When other commands encounter an element
2198 * with this attribute they follow the "target" after appending remaining
2199 * elements from the original element path to the target. The exception is the
2200 * ATTR command that operates on the element itself (for reserved attribute
2201 * names) and not the target.
2203 * If the source element path doesn't exist when using 'ATTR SET target', it is
2204 * created, but the destination element path must exist. This is simliar to the
2205 * ls(1) command: ln -s src dst.
2207 * args[0] - source element path
2208 * args[1] - destination element path
2210 static gpg_error_t
2211 set_target_attribute (struct client_s *client, char **args)
2213 struct xml_request_s *req = NULL;
2214 char **src, **dst;
2215 gpg_error_t rc;
2216 xmlNodePtr n;
2218 if (!args || !args[0] || !args[1])
2219 return GPG_ERR_SYNTAX;
2221 src = str_split (args[0], "\t", 0);
2222 if (!src)
2223 return GPG_ERR_SYNTAX;
2225 if (!xml_valid_element_path (src, 0))
2227 strv_free (src);
2228 return GPG_ERR_INV_VALUE;
2231 dst = str_split (args[1], "\t", 0);
2232 if (!dst)
2234 strv_free (src);
2235 return GPG_ERR_SYNTAX;
2238 rc = copy_on_write (client);
2239 if (rc)
2240 goto fail;
2242 // Be sure the destination element path exists. */
2243 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
2244 if (rc)
2245 goto fail;
2247 (void)xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2248 if (rc && rc != GPG_ERR_EACCES)
2249 goto fail;
2251 xml_free_request (req);
2252 req = NULL;
2254 if (!strcmp (args[0], args[1]))
2256 rc = GPG_ERR_EEXIST;
2257 goto fail;
2260 rc = xml_new_request (client, args[0], XML_CMD_ATTR_TARGET, &req);
2261 if (rc)
2262 goto fail;
2264 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2265 if (rc && rc != GPG_ERR_EACCES)
2266 goto fail;
2268 if (!rc)
2270 rc = xml_add_attribute (client, n, "target", args[1]);
2271 if (!rc)
2272 rc = xml_unlink_node (client, n->children);
2275 fail:
2276 strv_free (src);
2277 strv_free (dst);
2278 xml_free_request (req);
2279 return rc;
2283 * args[0] - attribute
2284 * args[1] - element path
2286 static gpg_error_t
2287 attribute_get (assuan_context_t ctx, char **args)
2289 struct client_s *client = assuan_get_pointer (ctx);
2290 xmlNodePtr n;
2291 xmlChar *a;
2292 gpg_error_t rc;
2293 struct xml_request_s *req;
2295 if (!args || !args[0] || !*args[0] || !args[1] || !*args[1])
2296 return GPG_ERR_SYNTAX;
2298 if (!xml_reserved_attribute (args[0]))
2299 n = xml_resolve_path (client, client->doc, (xmlChar *)args[1], NULL, &rc);
2300 else
2302 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
2303 if (rc)
2304 return rc;
2306 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2307 xml_free_request (req);
2310 if (rc)
2311 return rc;
2313 a = xmlGetProp (n, (xmlChar *) args[0]);
2314 if (!a)
2315 return GPG_ERR_NOT_FOUND;
2317 pthread_cleanup_push ((void *)xmlFree, a);
2319 if (*a)
2320 rc = xfer_data (ctx, (char *) a, xmlStrlen (a));
2321 else
2322 rc = GPG_ERR_NO_DATA;
2324 pthread_cleanup_pop (1);
2325 return rc;
2329 * args[0] - attribute
2330 * args[1] - element path
2331 * args[2] - value
2333 static gpg_error_t
2334 attribute_set (struct client_s *client, char **args)
2336 struct xml_request_s *req;
2337 gpg_error_t rc;
2338 xmlNodePtr n;
2340 if (!args || !args[0] || !args[1])
2341 return GPG_ERR_SYNTAX;
2344 * Reserved attribute names.
2346 if (!strcmp (args[0], "_name")) // Use the RENAME command instead
2347 return GPG_ERR_INV_ATTR;
2348 else if (!strcmp (args[0], "target"))
2349 return set_target_attribute (client, args + 1);
2350 else if (!xml_valid_attribute (args[0]))
2351 return GPG_ERR_INV_VALUE;
2353 if (!xml_valid_attribute_value (args[2]))
2354 return GPG_ERR_INV_VALUE;
2356 rc = copy_on_write (client);
2357 if (rc)
2358 return rc;
2360 if (!xml_reserved_attribute (args[0]))
2362 n = xml_resolve_path (client, client->doc, (xmlChar *)args[1], NULL, &rc);
2363 if (!rc)
2365 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
2366 if (!rc)
2368 rc = xml_check_recursion (client, req);
2369 xml_free_request (req);
2373 else
2375 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
2376 if (rc)
2377 return rc;
2379 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2380 xml_free_request (req);
2383 if (!rc)
2384 rc = xml_is_element_owner (client, n);
2386 if (!rc)
2387 rc = xml_add_attribute (client, n, args[0], args[2]);
2389 return rc;
2393 * req[0] - command
2394 * req[1] - attribute name or element path if command is LIST
2395 * req[2] - element path
2396 * req[2] - element path or value
2399 static gpg_error_t
2400 do_attr (assuan_context_t ctx, char *line)
2402 struct client_s *client = assuan_get_pointer (ctx);
2403 gpg_error_t rc = 0;
2404 char **req;
2406 req = str_split (line, " ", 4);
2407 if (!req || !req[0] || !req[1])
2409 strv_free (req);
2410 return GPG_ERR_SYNTAX;
2413 pthread_cleanup_push ((void *)req_free, req);
2415 if (strcasecmp (req[0], "SET") == 0)
2416 rc = attribute_set (client, req + 1);
2417 else if (strcasecmp (req[0], "GET") == 0)
2418 rc = attribute_get (ctx, req + 1);
2419 else if (strcasecmp (req[0], "DELETE") == 0)
2420 rc = attribute_delete (client, req + 1);
2421 else if (strcasecmp (req[0], "LIST") == 0)
2422 rc = attribute_list (ctx, req + 1);
2423 else
2424 rc = GPG_ERR_SYNTAX;
2426 client->flags &= ~(FLAG_ACL_IGNORE|FLAG_ACL_ERROR);
2427 pthread_cleanup_pop (1);
2428 return rc;
2431 static gpg_error_t
2432 attr_command (assuan_context_t ctx, char *line)
2434 struct client_s *client = assuan_get_pointer (ctx);
2435 gpg_error_t rc;
2436 struct argv_s *args[] = {
2437 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2438 NULL
2441 rc = parse_options (&line, args, client, 1);
2442 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2443 rc = GPG_ERR_SYNTAX;
2444 if (rc)
2445 return send_error (ctx, rc);
2447 if (client->opts & OPT_INQUIRE)
2449 unsigned char *result;
2450 size_t len;
2452 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2453 if (rc)
2454 return send_error (ctx, rc);
2456 pthread_cleanup_push ((void *)xfree, result);
2457 rc = do_attr (ctx, (char *)result);
2458 pthread_cleanup_pop (1);
2460 else
2461 rc = do_attr (ctx, line);
2463 return send_error (ctx, rc);
2466 static gpg_error_t
2467 parse_iscached_opt_lock (void *data, void *value)
2469 struct client_s *client = data;
2471 (void) value;
2472 client->opts |= OPT_LOCK;
2473 return 0;
2476 static gpg_error_t
2477 parse_iscached_opt_agent (void *data, void *value)
2479 struct client_s *client = data;
2481 (void) value;
2482 client->opts |= OPT_CACHE_AGENT;
2483 return 0;
2486 static gpg_error_t
2487 parse_iscached_opt_sign (void *data, void *value)
2489 struct client_s *client = data;
2491 (void) value;
2492 client->opts |= OPT_CACHE_SIGN;
2493 return 0;
2496 static gpg_error_t
2497 iscached_command (assuan_context_t ctx, char *line)
2499 struct client_s *client = assuan_get_pointer (ctx);
2500 gpg_error_t rc;
2501 int defer = 0;
2502 struct argv_s *args[] = {
2503 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_iscached_opt_lock},
2504 &(struct argv_s) {"agent", OPTION_TYPE_NOARG, parse_iscached_opt_agent},
2505 &(struct argv_s) {"sign", OPTION_TYPE_NOARG, parse_iscached_opt_sign},
2506 NULL
2509 if (!line || !*line)
2510 return send_error (ctx, GPG_ERR_SYNTAX);
2512 rc = parse_options (&line, args, client, 1);
2513 if (rc)
2514 return send_error (ctx, rc);
2515 else if (!valid_filename (line))
2516 return send_error (ctx, GPG_ERR_INV_VALUE);
2518 if (!(client->flags & FLAG_OPEN)
2519 && ((client->opts & OPT_CACHE_AGENT) || (client->opts & OPT_CACHE_SIGN)))
2520 return send_error (ctx, GPG_ERR_INV_STATE);
2522 rc = cache_iscached (line, &defer, (client->opts & OPT_CACHE_AGENT),
2523 (client->opts & OPT_CACHE_SIGN));
2524 if (!rc && defer)
2525 rc = GPG_ERR_NO_DATA;
2527 if (!rc)
2529 struct cache_data_s *cdata = cache_get_data (line, NULL);
2531 if (cdata)
2533 rc = validate_checksum (client, line, cdata, NULL, NULL);
2534 if (rc == GPG_ERR_CHECKSUM)
2535 rc = GPG_ERR_NO_DATA;
2539 if (client->opts & OPT_LOCK
2540 && (!rc || gpg_err_code (rc) == GPG_ERR_NO_DATA))
2542 gpg_error_t trc = rc;
2544 if (strcmp (line, client->filename))
2545 reset_client (client);
2547 xfree (client->filename);
2548 client->filename = str_dup (line);
2549 rc = do_lock (client, 1);
2550 if (!rc)
2551 rc = trc;
2554 return send_error (ctx, rc);
2557 static gpg_error_t
2558 clearcache_command (assuan_context_t ctx, char *line)
2560 struct client_s *client = assuan_get_pointer (ctx);
2561 gpg_error_t rc = 0, all_rc = 0;
2562 int i;
2563 int t;
2564 int all = 0;
2565 struct client_thread_s *once = NULL;
2566 unsigned count;
2568 cache_lock ();
2569 pthread_cleanup_push (cache_release_mutex, NULL);
2570 count = cache_file_count ();
2571 MUTEX_LOCK (&cn_mutex);
2572 pthread_cleanup_push ((void *)release_mutex_cb, &cn_mutex);
2574 if (!line || !*line)
2575 all = 1;
2577 t = slist_length (cn_thread_list);
2579 for (i = 0; i < t; i++)
2581 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2582 assuan_peercred_t peer;
2584 if (!thd->cl)
2585 continue;
2587 /* Lock each connected clients' file mutex to prevent any other client
2588 * from accessing the cache entry (the file mutex is locked upon
2589 * command startup). The cache for the entry is not cleared if the
2590 * file mutex is locked by another client to prevent this function
2591 * from blocking. Rather, it returns an error.
2593 if (all)
2595 if (thd->cl->filename)
2597 rc = do_validate_peer (ctx, thd->cl->filename, &peer);
2598 /* The current client doesn't have permission to open the other
2599 * filename do to "access" configuration parameter in a filename
2600 * section. Since we are clearning all cache entries the error
2601 * will be returned later during cache_clear(). */
2602 if (rc)
2604 rc = 0;
2605 continue;
2608 else // Idle client without opened file?
2609 continue;
2611 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->filename, -1, 0, -1);
2612 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2614 /* The current client owns the lock. */
2615 if (pthread_equal (pthread_self (), thd->tid))
2616 rc = 0;
2617 else
2619 if (cache_iscached (thd->cl->filename, NULL, 0, 0)
2620 == GPG_ERR_NO_DATA)
2622 rc = 0;
2623 continue;
2626 /* The cache entry will be cleared when the other client
2627 * disconnects and cache_timer_thread() does its thing. */
2628 cache_defer_clear (thd->cl->filename);
2631 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
2633 rc = 0;
2634 continue;
2637 if (!rc)
2639 rc = cache_clear (NULL, thd->cl->filename, 1, 0);
2640 cache_unlock_mutex (thd->cl->filename, 0);
2643 if (rc)
2644 all_rc = rc;
2646 rc = 0;
2648 else
2650 /* A single data filename was specified. Lock only this data file
2651 * mutex and free the cache entry. */
2652 rc = do_validate_peer (ctx, line, &peer);
2653 if (rc == GPG_ERR_FORBIDDEN)
2654 rc = peer_is_invoker (client);
2656 if (rc == GPG_ERR_EACCES)
2657 rc = GPG_ERR_FORBIDDEN;
2659 if (!rc && thd->cl->filename && !strcmp (thd->cl->filename , line))
2661 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->filename, -1, 0, -1);
2662 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2664 /* The current client owns the lock. */
2665 if (pthread_equal (pthread_self (), thd->tid))
2666 rc = 0;
2669 if (!rc)
2671 once = thd;
2672 rc = cache_clear (NULL, thd->cl->filename, 1, 0);
2673 cache_unlock_mutex (thd->cl->filename, 0);
2675 else
2676 cache_defer_clear (thd->cl->filename);
2678 /* Found a client with the opened file. The cache entry has been
2679 * either cleared (self) or defered to be cleared. */
2680 break;
2685 /* Only connected clients' cache entries have been cleared. Now clear any
2686 * remaining cache entries without clients but only if there wasn't an
2687 * error from above since this would defeat the locking check of the
2688 * remaining entries. */
2689 if (all && !all_rc && cache_file_count ())
2691 rc = cache_clear (client, NULL, 1, 0);
2692 if (rc == GPG_ERR_EACCES)
2693 rc = GPG_ERR_FORBIDDEN;
2696 /* No clients are using the specified file. */
2697 else if (!all_rc && !rc && !once)
2698 rc = cache_clear (NULL, line, 1, 0);
2700 /* Release the connection mutex. */
2701 pthread_cleanup_pop (1);
2703 if (!rc || (cache_file_count () && count != cache_file_count ()))
2704 send_status_all (STATUS_CACHE, NULL);
2706 /* Release the cache mutex. */
2707 pthread_cleanup_pop (1);
2709 /* One or more files were locked while clearing all cache entries. */
2710 if (all_rc)
2711 rc = all_rc;
2713 return send_error (ctx, rc);
2716 static gpg_error_t
2717 cachetimeout_command (assuan_context_t ctx, char *line)
2719 struct client_s *client = assuan_get_pointer (ctx);
2720 long timeout;
2721 char **req = str_split (line, " ", 0);
2722 char *p;
2723 gpg_error_t rc = 0;
2725 if (!(client->flags & FLAG_OPEN))
2726 return send_error (ctx, GPG_ERR_INV_STATE);
2728 if (!req || !*req || strv_length (req) > 1)
2730 strv_free (req);
2731 return send_error (ctx, GPG_ERR_SYNTAX);
2734 errno = 0;
2735 timeout = strtol (req[0], &p, 10);
2736 if (errno != 0 || *p || timeout < (long)-1)
2737 rc = GPG_ERR_SYNTAX;
2739 if (!rc)
2741 rc = cache_set_timeout (client->filename, timeout);
2742 if (!rc || gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
2744 rc = 0;
2745 MUTEX_LOCK (&rcfile_mutex);
2746 config_set_long_param (&global_config, client->filename,
2747 "cache_timeout", req[0]);
2748 MUTEX_UNLOCK (&rcfile_mutex);
2752 strv_free (req);
2753 return send_error (ctx, rc);
2756 static gpg_error_t
2757 dump_command (assuan_context_t ctx, char *line)
2759 xmlChar *xml;
2760 int len;
2761 struct client_s *client = assuan_get_pointer (ctx);
2762 gpg_error_t rc;
2764 if (disable_list_and_dump == 1)
2765 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2767 if (line && *line)
2768 return send_error (ctx, GPG_ERR_SYNTAX);
2770 rc = peer_is_invoker(client);
2771 if (rc)
2772 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
2774 xmlDocDumpFormatMemory (client->doc, &xml, &len, 1);
2776 if (!xml)
2778 log_write ("%s(%i): %s", __FILE__, __LINE__,
2779 pwmd_strerror (GPG_ERR_ENOMEM));
2780 return send_error (ctx, GPG_ERR_ENOMEM);
2783 pthread_cleanup_push ((void *)xmlFree, xml);
2784 rc = xfer_data (ctx, (char *) xml, len);
2785 pthread_cleanup_pop (1);
2786 return send_error (ctx, rc);
2789 static gpg_error_t
2790 getconfig_command (assuan_context_t ctx, char *line)
2792 struct client_s *client = assuan_get_pointer (ctx);
2793 gpg_error_t rc = 0;
2794 char filename[255] = { 0 }, param[747] = { 0 };
2795 char *p, *tmp = NULL, *fp = client->filename, *paramp = line;
2797 if (!line || !*line)
2798 return send_error (ctx, GPG_ERR_SYNTAX);
2800 if (strchr (line, ' '))
2802 int ret = sscanf (line, " %254[^ ] %746c", filename, param);
2804 if (ret <= 0)
2805 return send_error (ctx, gpg_error_from_syserror());
2806 paramp = param;
2807 fp = filename;
2810 if (fp && !valid_filename (fp))
2811 return send_error (ctx, GPG_ERR_INV_VALUE);
2813 paramp = str_down (paramp);
2814 p = config_get_value (fp ? fp : "global", paramp);
2815 if (!p)
2816 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2818 tmp = expand_homedir (p);
2819 xfree (p);
2820 if (!tmp)
2822 log_write ("%s(%i): %s", __FILE__, __LINE__,
2823 pwmd_strerror (GPG_ERR_ENOMEM));
2824 return send_error (ctx, GPG_ERR_ENOMEM);
2827 p = tmp;
2828 pthread_cleanup_push ((void *)xfree, p);
2829 rc = xfer_data (ctx, p, strlen (p));
2830 pthread_cleanup_pop (1);
2831 return send_error (ctx, rc);
2834 struct xpath_s
2836 xmlXPathContextPtr xp;
2837 xmlXPathObjectPtr result;
2838 xmlBufferPtr buf;
2839 char **req;
2842 static void
2843 xpath_command_free (void *arg)
2845 struct xpath_s *xpath = arg;
2847 if (!xpath)
2848 return;
2850 req_free (xpath->req);
2852 if (xpath->buf)
2853 xmlBufferFree (xpath->buf);
2855 if (xpath->result)
2856 xmlXPathFreeObject (xpath->result);
2858 if (xpath->xp)
2859 xmlXPathFreeContext (xpath->xp);
2862 static gpg_error_t
2863 do_xpath (assuan_context_t ctx, char *line)
2865 gpg_error_t rc;
2866 struct client_s *client = assuan_get_pointer (ctx);
2867 struct xpath_s _x = { 0 };
2868 struct xpath_s *xpath = &_x;
2870 if (!line || !*line)
2871 return GPG_ERR_SYNTAX;
2873 if ((xpath->req = str_split (line, "\t", 2)) == NULL)
2875 if (strv_printf (&xpath->req, "%s", line) == 0)
2876 return GPG_ERR_ENOMEM;
2879 if (xpath->req[1])
2881 rc = copy_on_write (client);
2882 if (rc)
2883 goto fail;
2886 xpath->xp = xmlXPathNewContext (client->doc);
2887 if (!xpath->xp)
2889 rc = GPG_ERR_BAD_DATA;
2890 goto fail;
2893 xpath->result =
2894 xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2895 if (!xpath->result)
2897 rc = GPG_ERR_BAD_DATA;
2898 goto fail;
2901 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2903 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2904 goto fail;
2907 rc = xml_recurse_xpath_nodeset (client, client->doc,
2908 xpath->result->nodesetval,
2909 (xmlChar *) xpath->req[1], &xpath->buf, 0,
2910 NULL);
2911 if (rc)
2912 goto fail;
2913 else if (!xpath->req[1] && !xmlBufferLength (xpath->buf))
2915 rc = GPG_ERR_NO_DATA;
2916 goto fail;
2918 else if (xpath->req[1])
2920 rc = 0;
2921 goto fail;
2924 pthread_cleanup_push ((void *)xpath_command_free, &xpath);
2925 rc = xfer_data (ctx, (char *) xmlBufferContent (xpath->buf),
2926 xmlBufferLength (xpath->buf));
2927 pthread_cleanup_pop (0);
2928 fail:
2929 xpath_command_free (xpath);
2930 return rc;
2933 static gpg_error_t
2934 xpath_command (assuan_context_t ctx, char *line)
2936 struct client_s *client = assuan_get_pointer (ctx);
2937 gpg_error_t rc;
2938 struct argv_s *args[] = {
2939 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2940 NULL
2943 if (disable_list_and_dump == 1)
2944 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2946 rc = peer_is_invoker(client);
2947 if (rc)
2948 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
2950 rc = parse_options (&line, args, client, 1);
2951 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2952 rc = GPG_ERR_SYNTAX;
2953 if (rc)
2954 return send_error (ctx, rc);
2956 if (client->opts & OPT_INQUIRE)
2958 unsigned char *result;
2959 size_t len;
2961 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2962 if (rc)
2963 return send_error (ctx, rc);
2965 pthread_cleanup_push ((void *)xfree, result);
2966 rc = do_xpath (ctx, (char *)result);
2967 pthread_cleanup_pop (1);
2969 else
2970 rc = do_xpath (ctx, line);
2972 return send_error (ctx, rc);
2975 static gpg_error_t
2976 do_xpathattr (assuan_context_t ctx, char *line)
2978 struct client_s *client = assuan_get_pointer (ctx);
2979 gpg_error_t rc;
2980 char **req = NULL;
2981 int cmd = 0; //SET
2982 struct xpath_s _x = { 0 };
2983 struct xpath_s *xpath = &_x;
2985 if (!line || !*line)
2986 return GPG_ERR_SYNTAX;
2988 if ((req = str_split (line, " ", 3)) == NULL)
2989 return GPG_ERR_ENOMEM;
2991 if (!req[0])
2993 rc = GPG_ERR_SYNTAX;
2994 goto fail;
2997 if (!strcasecmp (req[0], "SET"))
2998 cmd = 0;
2999 else if (!strcasecmp (req[0], "DELETE"))
3000 cmd = 1;
3001 else
3003 rc = GPG_ERR_SYNTAX;
3004 goto fail;
3007 if (!req[1] || !req[2])
3009 rc = GPG_ERR_SYNTAX;
3010 goto fail;
3013 if ((xpath->req = str_split (req[2], "\t", 3)) == NULL)
3015 rc = GPG_ERR_ENOMEM;
3016 goto fail;
3019 if (!xpath->req[0] || (!xpath->req[1] && !cmd) || (xpath->req[1] && cmd))
3021 rc = GPG_ERR_SYNTAX;
3022 goto fail;
3025 rc = copy_on_write (client);
3026 if (rc)
3027 goto fail;
3029 xpath->xp = xmlXPathNewContext (client->doc);
3030 if (!xpath->xp)
3032 rc = GPG_ERR_BAD_DATA;
3033 goto fail;
3036 xpath->result = xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
3037 if (!xpath->result)
3039 rc = GPG_ERR_BAD_DATA;
3040 goto fail;
3043 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
3045 rc = GPG_ERR_ELEMENT_NOT_FOUND;
3046 goto fail;
3049 rc = xml_recurse_xpath_nodeset (client, client->doc,
3050 xpath->result->nodesetval,
3051 (xmlChar *) xpath->req[1], &xpath->buf, cmd,
3052 (xmlChar *) req[1]);
3054 fail:
3055 xpath_command_free (xpath);
3056 strv_free (req);
3057 return rc;
3060 /* XPATHATTR SET|DELETE <name> <expression>[<TAB>[value]] */
3061 static gpg_error_t
3062 xpathattr_command (assuan_context_t ctx, char *line)
3064 struct client_s *client = assuan_get_pointer (ctx);
3065 gpg_error_t rc;
3066 struct argv_s *args[] = {
3067 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3068 NULL
3071 if (disable_list_and_dump == 1)
3072 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
3074 rc = peer_is_invoker(client);
3075 if (rc)
3076 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
3078 rc = parse_options (&line, args, client, 1);
3079 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3080 rc = GPG_ERR_SYNTAX;
3081 if (rc)
3082 return send_error (ctx, rc);
3084 if (client->opts & OPT_INQUIRE)
3086 unsigned char *result;
3087 size_t len;
3089 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3090 if (rc)
3091 return send_error (ctx, rc);
3093 pthread_cleanup_push ((void *)xfree, result);
3094 rc = do_xpathattr (ctx, (char *)result);
3095 pthread_cleanup_pop (1);
3097 else
3098 rc = do_xpathattr (ctx, line);
3100 return send_error (ctx, rc);
3103 static gpg_error_t
3104 do_import (struct client_s *client, const char *root_element,
3105 unsigned char *content)
3107 xmlDocPtr doc = NULL;
3108 xmlNodePtr n = NULL, root;
3109 gpg_error_t rc = 0;
3110 struct string_s *str = NULL, *tstr = NULL;
3111 struct xml_request_s *req = NULL;
3113 if (!content || !*content)
3114 return GPG_ERR_SYNTAX;
3116 if (root_element)
3118 rc = xml_new_request (client, root_element, XML_CMD_STORE, &req);
3119 if (rc)
3121 xfree (content);
3122 return rc;
3125 if (!xml_valid_element_path (req->args, 0))
3127 xml_free_request (req);
3128 xfree (content);
3129 return GPG_ERR_INV_VALUE;
3133 str = string_new_content ((char *)content);
3134 tstr = string_prepend (str, "<pwmd>");
3135 if (tstr)
3137 str = tstr;
3138 tstr = string_append (str, "</pwmd>");
3139 if (!tstr)
3140 rc = GPG_ERR_ENOMEM;
3142 else
3143 rc = GPG_ERR_ENOMEM;
3145 if (rc)
3146 goto fail;
3148 doc = xmlReadDoc ((xmlChar *) str->str, NULL, "UTF-8", XML_PARSE_NOBLANKS);
3149 string_free (str, 1);
3150 if (!doc)
3152 rc = GPG_ERR_BAD_DATA;
3153 goto fail;
3156 root = xmlDocGetRootElement (doc);
3157 root = root->children;
3158 if (root->type != XML_ELEMENT_NODE)
3160 rc = GPG_ERR_BAD_DATA;
3161 goto fail;
3164 rc = xml_validate_import (client, root);
3165 if (rc)
3166 goto fail;
3168 if (req)
3170 /* Create the new specified root element path, if needed. */
3171 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc),
3172 &rc);
3173 if (rc)
3174 goto fail;
3176 /* Overwrite the children of the specified root element path. */
3177 (void)xml_unlink_node (client, n->children);
3178 n->children = NULL;
3180 else
3181 n = xmlDocGetRootElement (client->doc);
3183 if (n)
3185 xmlNodePtr copy;
3186 xmlChar *name = xml_attribute_value (root, (xmlChar *)"_name");
3188 if (!name)
3189 rc = GPG_ERR_BAD_DATA;
3190 else if (!req)
3192 /* No --root argument passed. Overwrite the current documents' root
3193 * element matching the root element of the imported data. */
3194 xml_free_request (req);
3195 req = NULL;
3196 rc = xml_new_request (client, (char *)name, XML_CMD_DELETE, &req);
3197 xmlFree (name);
3198 if (!rc)
3200 xmlNodePtr tmp;
3202 tmp = xml_find_elements (client, req,
3203 xmlDocGetRootElement (req->doc), &rc);
3204 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3205 goto fail;
3207 if (!rc)
3208 (void)xml_unlink_node (client, tmp);
3210 rc = 0;
3214 if (!rc)
3216 copy = xmlCopyNodeList (root);
3217 if (!copy)
3218 rc = GPG_ERR_ENOMEM;
3219 else
3221 n = xmlAddChildList (n, copy);
3222 if (!n)
3223 rc = GPG_ERR_ENOMEM;
3228 if (!rc && n && n->parent)
3229 rc = xml_update_element_mtime (client, n->parent);
3231 fail:
3232 xml_free_request (req);
3234 if (doc)
3235 xmlFreeDoc (doc);
3237 return rc;
3240 static gpg_error_t
3241 parse_import_opt_root (void *data, void *value)
3243 struct client_s *client = data;
3245 client->import_root = str_dup (value);
3246 return client->import_root ? 0 : GPG_ERR_ENOMEM;
3249 static gpg_error_t
3250 import_command (assuan_context_t ctx, char *line)
3252 gpg_error_t rc;
3253 struct client_s *client = assuan_get_pointer (ctx);
3254 unsigned char *result;
3255 size_t len;
3256 struct argv_s *args[] = {
3257 &(struct argv_s) {"root", OPTION_TYPE_ARG, parse_import_opt_root},
3258 NULL
3261 xfree (client->import_root);
3262 client->import_root = NULL;
3263 rc = parse_options (&line, args, client, 0);
3264 if (rc)
3265 return send_error (ctx, rc);
3267 rc = copy_on_write (client);
3268 if (rc)
3269 return send_error (ctx, rc);
3271 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3272 if (rc)
3274 xfree (client->import_root);
3275 client->import_root = NULL;
3276 return send_error (ctx, rc);
3279 rc = do_import (client, client->import_root, result);
3280 xfree (client->import_root);
3281 client->import_root = NULL;
3282 return send_error (ctx, rc);
3285 static gpg_error_t
3286 do_lock (struct client_s *client, int add)
3288 gpg_error_t rc = lock_file_mutex (client, add);
3290 if (!rc)
3291 client->flags |= FLAG_LOCK_CMD;
3293 return rc;
3296 static gpg_error_t
3297 lock_command (assuan_context_t ctx, char *line)
3299 struct client_s *client = assuan_get_pointer (ctx);
3300 gpg_error_t rc;
3302 if (line && *line)
3303 return send_error (ctx, GPG_ERR_SYNTAX);
3305 rc = do_lock (client, 0);
3306 return send_error (ctx, rc);
3309 static gpg_error_t
3310 unlock_command (assuan_context_t ctx, char *line)
3312 struct client_s *client = assuan_get_pointer (ctx);
3313 gpg_error_t rc;
3315 if (line && *line)
3316 return send_error (ctx, GPG_ERR_SYNTAX);
3318 rc = unlock_file_mutex (client, 0);
3319 return send_error (ctx, rc);
3322 static void
3323 set_env (const char *name, char *buf, size_t size, const char *value)
3325 MUTEX_LOCK (&rcfile_mutex);
3326 if (!value || !*value)
3328 unsetenv (name);
3329 buf[0] = 0;
3331 else if (!buf[0] || strcmp (buf, value))
3333 snprintf (buf, size, "%s=%s", name, value);
3334 putenv (buf);
3337 MUTEX_UNLOCK (&rcfile_mutex);
3340 static gpg_error_t
3341 option_command (assuan_context_t ctx, char *line)
3343 struct client_s *client = assuan_get_pointer (ctx);
3344 gpg_error_t rc = 0;
3345 char namebuf[255] = { 0 };
3346 char *name = namebuf;
3347 char *value = NULL, *p, *tmp = NULL;
3349 p = strchr (line, '=');
3350 if (!p)
3352 strncpy (namebuf, line, sizeof(namebuf));
3353 namebuf[sizeof(namebuf)-1] = 0;
3355 else
3357 strncpy (namebuf, line, strlen (line)-strlen (p));
3358 namebuf[sizeof(namebuf)-1] = 0;
3359 value = p+1;
3362 log_write2 ("OPTION name='%s' value='%s'", name, value);
3364 if (strcasecmp (name, (char *) "lock-timeout") == 0)
3366 long n = 0;
3368 if (value)
3370 n = strtol (value, &tmp, 10);
3371 if (tmp && *tmp)
3372 return send_error (ctx, GPG_ERR_INV_VALUE);
3375 client->lock_timeout = n;
3377 else if (strcasecmp (name, (char *) "client-state") == 0)
3379 long n = 0;
3381 MUTEX_LOCK (&client->thd->status_mutex);
3382 if (value)
3384 n = strtol (value, &tmp, 10);
3385 if ((tmp && *tmp) || (n < 0 || n > 1))
3387 MUTEX_UNLOCK (&client->thd->status_mutex);
3388 return send_error (ctx, GPG_ERR_INV_VALUE);
3390 client->client_state = n;
3392 else
3393 client->client_state = 0;
3394 MUTEX_UNLOCK (&client->thd->status_mutex);
3396 else if (strcasecmp (name, (char *) "NAME") == 0)
3398 if (value && strchr (value, ' '))
3399 rc = GPG_ERR_INV_VALUE;
3400 else
3402 MUTEX_LOCK (&cn_mutex);
3403 tmp = pthread_getspecific (thread_name_key);
3404 pthread_setspecific (thread_name_key, NULL);
3405 xfree (tmp);
3406 xfree (client->thd->name);
3407 client->thd->name = NULL;
3408 if (value && *value)
3410 pthread_setspecific (thread_name_key, str_dup (value));
3411 client->thd->name = str_dup (value);
3413 MUTEX_UNLOCK (&cn_mutex);
3416 else if (strcasecmp (name, "disable-pinentry") == 0)
3418 int n = 1;
3420 if (value && *value)
3422 n = (int) strtol (value, &tmp, 10);
3423 if (*tmp || n < 0 || n > 1)
3424 return send_error (ctx, GPG_ERR_INV_VALUE);
3427 if (n)
3428 client->flags |= FLAG_NO_PINENTRY;
3429 else
3430 client->flags &= ~FLAG_NO_PINENTRY;
3432 else if (strcasecmp (name, "ttyname") == 0)
3433 set_env ("GPG_TTY", env_gpg_tty, sizeof (env_gpg_tty), value);
3434 else if (strcasecmp (name, "ttytype") == 0)
3435 set_env ("TERM", env_term, sizeof (env_term), value);
3436 else if (strcasecmp (name, "display") == 0)
3437 set_env ("DISPLAY", env_display, sizeof (env_display), value);
3438 else if (strcasecmp (name, "lc_messages") == 0)
3441 else if (strcasecmp (name, "lc_ctype") == 0)
3444 else if (strcasecmp (name, "desc") == 0)
3447 else if (strcasecmp (name, "pinentry-timeout") == 0)
3450 else
3451 rc = GPG_ERR_UNKNOWN_OPTION;
3453 return send_error (ctx, rc);
3456 static gpg_error_t
3457 do_rename (assuan_context_t ctx, char *line)
3459 struct client_s *client = assuan_get_pointer (ctx);
3460 char **args, *p;
3461 xmlNodePtr src, dst;
3462 struct string_s *str = NULL, *tstr;
3463 struct xml_request_s *req;
3464 gpg_error_t rc;
3466 args = str_split (line, " ", 0);
3467 if (!args || strv_length (args) != 2)
3469 strv_free (args);
3470 return GPG_ERR_SYNTAX;
3473 if (!xml_valid_element ((xmlChar *) args[1]))
3475 strv_free (args);
3476 return GPG_ERR_INV_VALUE;
3479 rc = xml_new_request (client, args[0], XML_CMD_RENAME, &req);
3480 if (rc)
3482 strv_free (args);
3483 return rc;
3486 src = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3487 if (rc)
3488 goto fail;
3490 rc = xml_is_element_owner (client, src);
3491 if (rc)
3492 goto fail;
3494 xmlChar *a = xmlGetProp (src, (xmlChar *) "_name");
3495 if (!a)
3497 rc = GPG_ERR_ENOMEM;
3498 goto fail;
3501 /* To prevent unwanted effects:
3503 * <element _name="a"><element _name="b"/></element>
3505 * RENAME a<TAB>b b
3507 if (xmlStrEqual (a, (xmlChar *) args[1]))
3509 xmlFree (a);
3510 rc = GPG_ERR_EEXIST;
3511 goto fail;
3514 xmlFree (a);
3515 str = string_new (args[0]);
3516 if (!str)
3518 rc = GPG_ERR_ENOMEM;
3519 goto fail;
3522 p = strrchr (str->str, '\t');
3523 if (p)
3524 tstr = string_truncate (str, strlen (str->str)-strlen (p));
3525 else
3526 tstr = string_truncate (str, 0);
3528 if (!tstr)
3530 string_free (str, 1);
3531 rc = GPG_ERR_ENOMEM;
3532 goto fail;
3535 str = tstr;
3536 tstr = string_append_printf (str, "%s%s", str->len ? "\t" : "", args[1]);
3537 if (!tstr)
3539 string_free (str, 1);
3540 rc = GPG_ERR_ENOMEM;
3541 goto fail;
3544 str = tstr;
3545 xml_free_request (req);
3546 rc = xml_new_request (client, str->str, XML_CMD_RENAME, &req);
3547 string_free (str, 1);
3548 if (rc)
3550 req = NULL;
3551 goto fail;
3554 dst = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3555 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3556 goto fail;
3558 rc = 0;
3560 /* Target may exist:
3562 * <element _name="a"/>
3563 * <element _name="b" target="a"/>
3565 * RENAME b a
3567 if (src == dst)
3569 rc = GPG_ERR_EEXIST;
3570 goto fail;
3573 if (dst)
3575 rc = xml_is_element_owner (client, dst);
3576 if (rc)
3577 goto fail;
3579 rc = xml_add_attribute (client, src, "_name", args[1]);
3580 if (!rc)
3581 xml_unlink_node (client, dst);
3583 else
3584 rc = xml_add_attribute (client, src, "_name", args[1]);
3586 fail:
3587 xml_free_request (req);
3588 strv_free (args);
3589 return rc;
3592 static gpg_error_t
3593 rename_command (assuan_context_t ctx, char *line)
3595 struct client_s *client = assuan_get_pointer (ctx);
3596 gpg_error_t rc;
3597 struct argv_s *args[] = {
3598 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3599 NULL
3602 rc = parse_options (&line, args, client, 1);
3603 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3604 rc = GPG_ERR_SYNTAX;
3605 if (rc)
3606 return send_error (ctx, rc);
3608 rc = copy_on_write (client);
3609 if (rc)
3610 return send_error (ctx, rc);
3612 if (client->opts & OPT_INQUIRE)
3614 unsigned char *result;
3615 size_t len;
3617 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3618 if (rc)
3619 return send_error (ctx, rc);
3621 pthread_cleanup_push ((void *)xfree, result);
3622 rc = do_rename (ctx, (char *)result);
3623 pthread_cleanup_pop (1);
3625 else
3626 rc = do_rename (ctx, line);
3628 return send_error (ctx, rc);
3631 static gpg_error_t
3632 do_copy (assuan_context_t ctx, char *line)
3634 struct client_s *client = assuan_get_pointer (ctx);
3635 char **args, **targs;
3636 xmlNodePtr src, dst, tree = NULL;
3637 struct xml_request_s *req;
3638 gpg_error_t rc;
3640 args = str_split (line, " ", 0);
3641 if (!args || strv_length (args) != 2)
3643 strv_free (args);
3644 return GPG_ERR_SYNTAX;
3647 targs = str_split (args[1], "\t", 0);
3648 if (!targs)
3650 strv_free (args);
3651 return GPG_ERR_SYNTAX;
3654 if (!xml_valid_element_path (targs, 0))
3656 strv_free (args);
3657 strv_free (targs);
3658 return GPG_ERR_INV_VALUE;
3660 strv_free (targs);
3662 rc = xml_new_request (client, args[0], XML_CMD_NONE, &req);
3663 if (rc)
3665 strv_free (args);
3666 return rc;
3669 src = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3670 if (rc)
3671 goto fail;
3673 tree = xmlCopyNodeList (src);
3674 if (!tree)
3676 rc = GPG_ERR_ENOMEM;
3677 goto fail;
3680 xml_free_request (req);
3681 /* Create the destination element path if it does not exist. */
3682 rc = xml_new_request (client, args[1], XML_CMD_STORE, &req);
3683 if (rc)
3685 req = NULL;
3686 goto fail;
3689 dst = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3690 if (rc)
3691 goto fail;
3693 rc = xml_is_element_owner (client, dst);
3694 if (rc)
3695 goto fail;
3697 rc = xml_validate_target (client, req->doc, args[1], src);
3698 if (rc || src == dst)
3700 rc = rc ? rc : GPG_ERR_EEXIST;
3701 goto fail;
3704 /* Merge any attributes from the src node to the initial dst node. */
3705 for (xmlAttrPtr attr = tree->properties; attr; attr = attr->next)
3707 if (xmlStrEqual (attr->name, (xmlChar *) "_name"))
3708 continue;
3710 xmlAttrPtr a = xmlHasProp (dst, attr->name);
3711 if (a)
3712 xmlRemoveProp (a);
3714 xmlChar *tmp = xmlNodeGetContent (attr->children);
3715 xmlNewProp (dst, attr->name, tmp);
3716 xmlFree (tmp);
3717 /* Create the default attributes. */
3718 rc = xml_add_attribute (client, dst, NULL, NULL);
3721 xmlNodePtr n = dst->children;
3722 (void)xml_unlink_node (client, n);
3723 dst->children = NULL;
3725 if (tree->children)
3727 n = xmlCopyNodeList (tree->children);
3728 if (!n)
3730 rc = GPG_ERR_ENOMEM;
3731 goto fail;
3734 n = xmlAddChildList (dst, n);
3735 if (!n)
3737 rc = GPG_ERR_ENOMEM;
3738 goto fail;
3741 rc = xml_update_element_mtime (client, xmlDocGetRootElement (client->doc)
3742 == dst->parent ? dst : dst->parent);
3745 fail:
3746 if (tree)
3747 (void)xml_unlink_node (client, tree);
3749 xml_free_request (req);
3750 strv_free (args);
3751 return rc;
3754 static gpg_error_t
3755 copy_command (assuan_context_t ctx, char *line)
3757 struct client_s *client = assuan_get_pointer (ctx);
3758 gpg_error_t rc;
3759 struct argv_s *args[] = {
3760 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3761 NULL
3764 rc = parse_options (&line, args, client, 1);
3765 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3766 rc = GPG_ERR_SYNTAX;
3767 if (rc)
3768 return send_error (ctx, rc);
3770 rc = copy_on_write (client);
3771 if (rc)
3772 return send_error (ctx, rc);
3774 if (client->opts & OPT_INQUIRE)
3776 unsigned char *result;
3777 size_t len;
3779 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3780 if (rc)
3781 return send_error (ctx, rc);
3783 pthread_cleanup_push ((void *)xfree, result);
3784 rc = do_copy (ctx, (char *)result);
3785 pthread_cleanup_pop (1);
3787 else
3788 rc = do_copy (ctx, line);
3790 return send_error (ctx, rc);
3793 static gpg_error_t
3794 do_move (assuan_context_t ctx, char *line)
3796 struct client_s *client = assuan_get_pointer (ctx);
3797 char **args;
3798 xmlNodePtr src, dst;
3799 struct xml_request_s *req;
3800 gpg_error_t rc;
3802 args = str_split (line, " ", 0);
3803 if (!args || strv_length (args) != 2)
3805 strv_free (args);
3806 return GPG_ERR_SYNTAX;
3809 if (*args[1])
3811 char **targs = str_split (args[1], "\t", 0);
3812 if (!targs)
3814 strv_free (args);
3815 return GPG_ERR_ENOMEM;
3818 if (!xml_valid_element_path (targs, 0))
3820 strv_free (targs);
3821 strv_free (args);
3822 return GPG_ERR_INV_VALUE;
3825 strv_free (targs);
3828 rc = xml_new_request (client, args[0], XML_CMD_MOVE, &req);
3829 if (rc)
3831 strv_free (args);
3832 return rc;
3835 src = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3836 if (rc)
3837 goto fail;
3839 rc = xml_is_element_owner (client, src);
3840 if (rc)
3841 goto fail;
3843 xml_free_request (req);
3844 req = NULL;
3845 if (*args[1])
3847 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
3848 if (rc)
3849 goto fail;
3851 dst = xml_find_elements (client, req, xmlDocGetRootElement (req->doc),
3852 &rc);
3854 else
3855 dst = xmlDocGetRootElement (client->doc);
3857 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3858 goto fail;
3860 rc = 0;
3862 for (xmlNodePtr n = dst; n; n = n->parent)
3864 if (n == src)
3866 rc = GPG_ERR_EEXIST;
3867 goto fail;
3871 if (dst)
3873 xmlChar *a = xml_attribute_value (src, (xmlChar *) "_name");
3874 xmlNodePtr dup = xml_find_element (client, dst->children, (char *) a, &rc);
3876 xmlFree (a);
3877 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3878 goto fail;
3880 rc = 0;
3882 if (dup)
3884 if (dup == src)
3886 rc = GPG_ERR_EEXIST;
3887 goto fail;
3890 if (dst == xmlDocGetRootElement (client->doc))
3892 xmlNodePtr n = src;
3893 int match = 0;
3895 while (n->parent && n->parent != dst)
3896 n = n->parent;
3898 a = xml_attribute_value (n, (xmlChar *) "_name");
3899 xmlChar *b = xml_attribute_value (src, (xmlChar *) "_name");
3901 if (xmlStrEqual (a, b))
3903 match = 1;
3904 xmlUnlinkNode (src);
3905 (void)xml_unlink_node (client, n);
3908 xmlFree (a);
3909 xmlFree (b);
3911 if (!match)
3912 (void)xml_unlink_node (client, dup);
3914 else
3915 xmlUnlinkNode (dup);
3919 if (!dst && req && req->args && *req->args)
3921 struct xml_request_s *nreq = NULL;
3922 xmlChar *name = xml_attribute_value (src, (xmlChar *) "_name");
3924 if (src->parent == xmlDocGetRootElement (client->doc)
3925 && !strcmp ((char *) name, *req->args))
3927 xmlFree (name);
3928 rc = GPG_ERR_EEXIST;
3929 goto fail;
3932 xmlFree (name);
3933 rc = xml_new_request (client, args[1], XML_CMD_STORE, &nreq);
3934 if (!rc)
3936 dst = xml_find_elements (client, nreq,
3937 xmlDocGetRootElement (nreq->doc), &rc);
3938 xml_free_request (nreq);
3941 if (rc)
3942 goto fail;
3945 xml_update_element_mtime (client, src->parent);
3946 xmlUnlinkNode (src);
3948 dst = xmlAddChildList (dst, src);
3949 if (!dst)
3950 rc = GPG_ERR_ENOMEM;
3951 else
3952 xml_update_element_mtime (client, dst->parent);
3954 fail:
3955 xml_free_request (req);
3956 strv_free (args);
3957 return rc;
3960 static gpg_error_t
3961 move_command (assuan_context_t ctx, char *line)
3963 struct client_s *client = assuan_get_pointer (ctx);
3964 gpg_error_t rc;
3965 struct argv_s *args[] = {
3966 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3967 NULL
3970 rc = parse_options (&line, args, client, 1);
3971 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3972 rc = GPG_ERR_SYNTAX;
3973 if (rc)
3974 return send_error (ctx, rc);
3976 rc = copy_on_write (client);
3977 if (rc)
3978 return send_error (ctx, rc);
3980 if (client->opts & OPT_INQUIRE)
3982 unsigned char *result;
3983 size_t len;
3985 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3986 if (rc)
3987 return send_error (ctx, rc);
3989 pthread_cleanup_push ((void *)xfree, result);
3990 rc = do_move (ctx, (char *)result);
3991 pthread_cleanup_pop (1);
3993 else
3994 rc = do_move (ctx, line);
3996 return send_error (ctx, rc);
3999 static int
4000 sort_files (const void *arg1, const void *arg2)
4002 char *const *a = arg1;
4003 char *const *b = arg2;
4005 return strcmp (*a, *b);
4008 static gpg_error_t
4009 ls_command (assuan_context_t ctx, char *line)
4011 gpg_error_t rc;
4012 char *tmp;
4013 char *dir;
4014 DIR *d;
4015 char *list = NULL;
4016 char **v = NULL;
4017 #ifdef HAVE_READDIR_R
4018 size_t len;
4019 struct dirent *cur = NULL, *p;
4020 #else
4021 struct dirent *cur = NULL;
4022 #endif
4024 if (line && *line)
4025 return send_error (ctx, GPG_ERR_SYNTAX);
4027 tmp = str_asprintf ("%s/data", homedir);
4028 dir = expand_homedir (tmp);
4029 xfree (tmp);
4030 if (!dir)
4031 return send_error (ctx, GPG_ERR_ENOMEM);
4033 d = opendir (dir);
4034 rc = gpg_error_from_errno (errno);
4036 if (!d)
4038 xfree (dir);
4039 return send_error (ctx, rc);
4042 #ifdef HAVE_READDIR_R
4043 len = offsetof (struct dirent, d_name) + pathconf (dir, _PC_NAME_MAX) + 1;
4044 p = xmalloc (len);
4045 if (!p)
4047 xfree (dir);
4048 closedir (d);
4049 return send_error (ctx, GPG_ERR_ENOMEM);
4051 pthread_cleanup_push (xfree, p);
4052 #endif
4054 pthread_cleanup_push ((void *)closedir, d);
4055 xfree (dir);
4056 rc = 0;
4058 #ifdef HAVE_READDIR_R
4059 while (!readdir_r (d, p, &cur) && cur)
4060 #else
4061 while ((cur = readdir (d)))
4062 #endif
4064 char **vtmp;
4066 pthread_cleanup_push ((void *)strv_free, v);
4067 rc = open_check_file (cur->d_name, NULL, NULL, 1);
4068 if (rc)
4069 continue;
4071 tmp = str_dup (cur->d_name);
4072 if (!tmp)
4074 rc = GPG_ERR_ENOMEM;
4075 break;
4078 vtmp = strv_cat (v, tmp);
4079 if (!vtmp)
4081 xfree (tmp);
4082 rc = GPG_ERR_ENOMEM;
4083 break;
4086 v = vtmp;
4087 pthread_cleanup_pop (0);
4090 pthread_cleanup_pop (1); // closedir (d)
4091 #ifdef HAVE_READDIR_R
4092 pthread_cleanup_pop (1); // xfree (p)
4093 #endif
4095 if (rc && rc != GPG_ERR_ENODEV)
4097 strv_free (v);
4098 return send_error (ctx, rc);
4101 rc = 0;
4102 if (v && *v)
4104 unsigned n, t = strv_length (v);
4106 qsort (v, t, sizeof (char **), sort_files);
4108 for (n = 0; n < t; n++)
4110 tmp = str_asprintf ("%s%s\n", list ? list : "", v[n]);
4111 if (!tmp)
4113 xfree (list);
4114 rc = GPG_ERR_ENOMEM;
4115 break;
4118 xfree (list);
4119 list = tmp;
4123 strv_free (v);
4124 if (!list)
4125 return send_error (ctx, GPG_ERR_NO_DATA);
4127 list[strlen (list) - 1] = 0;
4128 pthread_cleanup_push (xfree, list);
4129 rc = xfer_data (ctx, list, strlen (list));
4130 pthread_cleanup_pop (1);
4131 return send_error (ctx, rc);
4134 static gpg_error_t
4135 bye_notify (assuan_context_t ctx, char *line)
4137 struct client_s *cl = assuan_get_pointer (ctx);
4138 gpg_error_t ret = 0;
4140 (void)line;
4141 update_client_state (cl, CLIENT_STATE_DISCON);
4143 #ifdef WITH_GNUTLS
4144 cl->disco = 1;
4145 if (cl->thd->remote)
4147 int rc;
4151 struct timeval tv = { 0, 50000 };
4153 rc = gnutls_bye (cl->thd->tls->ses, GNUTLS_SHUT_RDWR);
4154 if (rc == GNUTLS_E_AGAIN)
4155 select (0, NULL, NULL, NULL, &tv);
4157 while (rc == GNUTLS_E_AGAIN);
4159 #endif
4161 /* This will let assuan_process_next() return. */
4162 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
4164 cl->last_rc = gpg_error_from_errno (errno);
4165 ret = cl->last_rc;
4168 cl->last_rc = 0; // BYE command result
4169 return ret;
4172 static gpg_error_t
4173 reset_notify (assuan_context_t ctx, char *line)
4175 struct client_s *client = assuan_get_pointer (ctx);
4177 (void)line;
4178 if (client)
4179 reset_client (client);
4181 return 0;
4185 * This is called before every Assuan command.
4187 static gpg_error_t
4188 command_startup (assuan_context_t ctx, const char *name)
4190 struct client_s *client = assuan_get_pointer (ctx);
4191 gpg_error_t rc;
4192 struct command_table_s *cmd = NULL;
4194 log_write2 ("command='%s'", name);
4195 client->last_rc = client->opts = 0;
4197 for (int i = 0; command_table[i]; i++)
4199 if (!strcasecmp (name, command_table[i]->name))
4201 if (command_table[i]->ignore_startup)
4202 return 0;
4203 cmd = command_table[i];
4204 break;
4208 if (!cmd)
4209 return GPG_ERR_UNKNOWN_COMMAND;
4211 client->last_rc = rc = gpg_error (file_modified (client, cmd));
4212 if (!rc)
4213 update_client_state (client, CLIENT_STATE_COMMAND);
4215 return rc;
4219 * This is called after every Assuan command.
4221 static void
4222 command_finalize (assuan_context_t ctx, gpg_error_t rc)
4224 struct client_s *client = assuan_get_pointer (ctx);
4226 if (!(client->flags & FLAG_LOCK_CMD))
4227 unlock_file_mutex (client, 0);
4229 unlock_flock (&client->flock_fd);
4230 log_write2 (_("command completed: rc=%u"), rc ? rc : client->last_rc);
4231 client->last_rc = gpg_error (GPG_ERR_UNKNOWN_COMMAND);
4232 #ifdef WITH_GNUTLS
4233 client->thd->buffer_timeout = client->thd->last_buffer_size = 0;
4234 #endif
4235 if (client->thd->state != CLIENT_STATE_DISCON)
4236 update_client_state (client, CLIENT_STATE_IDLE);
4239 static gpg_error_t
4240 parse_help_opt_html (void *data, void *value)
4242 struct client_s *client = data;
4244 (void) value;
4245 client->opts |= OPT_HTML;
4246 return 0;
4249 static gpg_error_t
4250 help_command (assuan_context_t ctx, char *line)
4252 gpg_error_t rc;
4253 int i;
4254 struct client_s *client = assuan_get_pointer (ctx);
4255 struct argv_s *args[] = {
4256 &(struct argv_s) {"html", OPTION_TYPE_NOARG, parse_help_opt_html},
4257 NULL
4260 rc = parse_options (&line, args, client, 1);
4261 if (rc)
4262 return send_error (ctx, rc);
4264 if (!line || !*line)
4266 char *tmp;
4267 char *help = str_dup (_("Usage: HELP [--html] [<COMMAND>]\n"
4268 "For commands that take an element path as an argument, each element is "
4269 "separated with an ASCII @key{TAB} character (ASCII 0x09)."
4270 "@*@*COMMANDS:"));
4272 for (i = 0; command_table[i]; i++)
4274 if (!command_table[i]->help)
4275 continue;
4277 /* @npxref{} won't put a "See " or "see " in front of the command.
4278 * It's not a texinfo command but needed for --html. */
4279 tmp = str_asprintf ("%s %s%s%s", help,
4280 client->opts & OPT_HTML ? "@npxref{" : "",
4281 command_table[i]->name,
4282 client->opts & OPT_HTML ? "}" : "");
4283 xfree (help);
4284 help = tmp;
4287 tmp = strip_texi_and_wrap (help, client->opts & OPT_HTML);
4288 xfree (help);
4289 pthread_cleanup_push ((void *)xfree, tmp);
4290 rc = xfer_data (ctx, tmp, strlen (tmp));
4291 pthread_cleanup_pop (1);
4292 return send_error (ctx, rc);
4295 for (i = 0; command_table[i]; i++)
4297 if (!strcasecmp (line, command_table[i]->name))
4299 char *help, *tmp;
4301 if (!command_table[i]->help)
4302 break;
4304 help = strip_texi_and_wrap (command_table[i]->help,
4305 client->opts & OPT_HTML);
4306 tmp = str_asprintf ("%s%s",
4307 (client->opts & OPT_HTML) ? "" : _("Usage: "),
4308 help);
4309 xfree (help);
4310 pthread_cleanup_push ((void *)xfree, tmp);
4311 rc = xfer_data (ctx, tmp, strlen (tmp));
4312 pthread_cleanup_pop (1);
4313 return send_error (ctx, rc);
4317 return send_error (ctx, GPG_ERR_INV_NAME);
4320 static void
4321 new_command (const char *name, int ignore, int unlock, int flock_type,
4322 gpg_error_t (*handler) (assuan_context_t, char *),
4323 const char *help)
4325 int i = 0;
4326 struct command_table_s **tmp;
4328 if (command_table)
4329 for (i = 0; command_table[i]; i++);
4331 tmp = xrealloc (command_table, (i + 2) * sizeof (struct command_table_s *));
4332 assert (tmp);
4333 command_table = tmp;
4334 command_table[i] = xcalloc (1, sizeof (struct command_table_s));
4335 command_table[i]->name = name;
4336 command_table[i]->handler = handler;
4337 command_table[i]->ignore_startup = ignore;
4338 command_table[i]->unlock = unlock;
4339 command_table[i]->flock_type = flock_type;
4340 command_table[i++]->help = help;
4341 command_table[i] = NULL;
4344 void
4345 deinit_commands ()
4347 int i;
4349 for (i = 0; command_table[i]; i++)
4350 xfree (command_table[i]);
4352 xfree (command_table);
4355 static int
4356 sort_commands (const void *arg1, const void *arg2)
4358 struct command_table_s *const *a = arg1;
4359 struct command_table_s *const *b = arg2;
4361 if (!*a || !*b)
4362 return 0;
4363 else if (*a && !*b)
4364 return 1;
4365 else if (!*a && *b)
4366 return -1;
4368 return strcmp ((*a)->name, (*b)->name);
4371 static gpg_error_t
4372 passwd_command (assuan_context_t ctx, char *line)
4374 struct client_s *client = assuan_get_pointer (ctx);
4375 gpg_error_t rc;
4377 (void)line;
4378 rc = peer_is_invoker (client);
4379 if (rc)
4380 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
4382 if (client->flags & FLAG_NEW)
4383 return send_error (ctx, GPG_ERR_INV_STATE);
4385 client->crypto->keyfile = config_get_string (client->filename,
4386 "passphrase_file");
4387 rc = crypto_init_ctx (client->crypto, client->flags & FLAG_NO_PINENTRY,
4388 client->crypto->keyfile);
4389 if (!rc)
4390 rc = crypto_passwd (client, client->crypto);
4392 crypto_free_non_keys (client->crypto);
4393 return send_error (ctx, rc);
4396 static gpg_error_t
4397 parse_opt_data (void *data, void *value)
4399 struct client_s *client = data;
4401 (void) value;
4402 client->opts |= OPT_DATA;
4403 return 0;
4406 static gpg_error_t
4407 send_client_list (assuan_context_t ctx)
4409 struct client_s *client = assuan_get_pointer (ctx);
4410 gpg_error_t rc = 0;
4412 if (client->opts & OPT_VERBOSE)
4414 unsigned i, t;
4415 char **list = NULL;
4416 char *line;
4418 MUTEX_LOCK (&cn_mutex);
4419 pthread_cleanup_push ((void *)release_mutex_cb, &cn_mutex);
4420 t = slist_length (cn_thread_list);
4422 for (i = 0; i < t; i++)
4424 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
4425 char *tmp;
4427 if (thd->state == CLIENT_STATE_UNKNOWN)
4428 continue;
4430 tmp = build_client_info_line (thd, 0);
4431 if (tmp)
4433 char **l = strv_cat (list, tmp);
4434 if (!l)
4435 rc = GPG_ERR_ENOMEM;
4436 else
4437 list = l;
4439 else
4440 rc = GPG_ERR_ENOMEM;
4442 if (rc)
4444 strv_free (list);
4445 break;
4449 pthread_cleanup_pop (1);
4450 if (rc)
4451 return rc;
4453 line = strv_join ("\n", list);
4454 strv_free (list);
4455 pthread_cleanup_push ((void *)xfree, line);
4456 rc = xfer_data (ctx, line, strlen (line));
4457 pthread_cleanup_pop (1);
4458 return rc;
4461 if (client->opts & OPT_DATA)
4463 char buf[ASSUAN_LINELENGTH];
4465 MUTEX_LOCK (&cn_mutex);
4466 snprintf (buf, sizeof (buf), "%u", slist_length (cn_thread_list));
4467 MUTEX_UNLOCK (&cn_mutex);
4468 rc = xfer_data (ctx, buf, strlen (buf));
4470 else
4471 rc = send_status (ctx, STATUS_CLIENTS, NULL);
4473 return rc;
4476 static gpg_error_t
4477 getinfo_command (assuan_context_t ctx, char *line)
4479 struct client_s *client = assuan_get_pointer (ctx);
4480 gpg_error_t rc;
4481 char buf[ASSUAN_LINELENGTH];
4482 struct argv_s *args[] = {
4483 &(struct argv_s) {"data", OPTION_TYPE_NOARG, parse_opt_data},
4484 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_opt_verbose},
4485 NULL
4488 rc = parse_options (&line, args, client, 1);
4489 if (rc)
4490 return send_error (ctx, rc);
4492 if (!strcasecmp (line, "clients"))
4494 rc = send_client_list (ctx);
4496 else if (!strcasecmp (line, "cache"))
4498 if (client->opts & OPT_DATA)
4500 snprintf (buf, sizeof (buf), "%u", cache_file_count ());
4501 rc = xfer_data (ctx, buf, strlen (buf));
4503 else
4504 rc = send_status (ctx, STATUS_CACHE, NULL);
4506 else if (!strcasecmp (line, "pid"))
4508 pid_t pid = getpid ();
4510 snprintf (buf, sizeof (buf), "%u", pid);
4511 rc = xfer_data (ctx, buf, strlen (buf));
4513 else if (!strcasecmp (line, "version"))
4515 char *tmp = str_asprintf ("0x%06x %s", VERSION_HEX,
4516 #ifdef WITH_GNUTLS
4517 "GNUTLS "
4518 #endif
4519 #ifdef WITH_LIBACL
4520 "ACL "
4521 #endif
4522 "");
4523 pthread_cleanup_push (xfree, tmp);
4524 rc = xfer_data (ctx, tmp, strlen (tmp));
4525 pthread_cleanup_pop (1);
4527 else if (!strcasecmp (line, "last_error"))
4529 if (client->last_error)
4530 rc = xfer_data (ctx, client->last_error, strlen (client->last_error));
4531 else
4532 rc = GPG_ERR_NO_DATA;
4534 else if (!strcasecmp (line, "user"))
4536 char *user = NULL;
4538 #ifdef WITH_GNUTLS
4539 if (client->thd->remote)
4540 user = str_asprintf ("#%s", client->thd->tls->fp);
4541 else
4542 user = get_username (client->thd->peer->uid);
4543 #else
4544 user = get_username (client->thd->peer->uid);
4545 #endif
4546 if (user)
4548 pthread_cleanup_push ((void *)xfree, user);
4549 rc = xfer_data (ctx, user, strlen (user));
4550 pthread_cleanup_pop (1);
4552 else
4553 rc = GPG_ERR_NO_DATA;
4555 else
4556 rc = gpg_error (GPG_ERR_SYNTAX);
4558 return send_error (ctx, rc);
4561 static gpg_error_t
4562 parse_opt_secret (void *data, void *value)
4564 struct client_s *client = data;
4566 (void) value;
4567 client->opts |= OPT_SECRET;
4568 return 0;
4571 static gpg_error_t
4572 parse_keyinfo_opt_learn (void *data, void *value)
4574 struct client_s *client = data;
4576 (void)value;
4577 client->opts |= OPT_KEYINFO_LEARN;
4578 return 0;
4581 static gpg_error_t
4582 keyinfo_command (assuan_context_t ctx, char *line)
4584 struct client_s *client = assuan_get_pointer (ctx);
4585 gpg_error_t rc = 0;
4586 char **keys = NULL, **p = NULL;
4587 int sym = 0;
4588 struct argv_s *args[] = {
4589 &(struct argv_s) {"learn", OPTION_TYPE_NOARG, parse_keyinfo_opt_learn},
4590 NULL
4593 rc = parse_options (&line, args, client, 0);
4594 if (rc)
4595 return send_error (ctx, rc);
4597 if (line && *line)
4598 return send_error (ctx, GPG_ERR_SYNTAX);
4600 if (!(client->flags & FLAG_OPEN))
4601 return send_error (ctx, GPG_ERR_INV_STATE);
4603 if (client->opts & OPT_KEYINFO_LEARN)
4605 rc = cache_agent_command ("LEARN");
4606 return send_error (ctx, rc);
4609 if (client->flags & FLAG_NEW)
4610 return send_error (ctx, GPG_ERR_NO_DATA);
4612 rc = lock_flock (ctx, client->filename, FLOCK_TYPE_SH, &client->flock_fd);
4613 if (rc)
4614 return send_error (ctx, rc);
4616 rc = crypto_is_symmetric (client->filename);
4617 unlock_flock (&client->flock_fd);
4618 if (!rc)
4619 sym = 1;
4620 else if (rc != GPG_ERR_BAD_DATA)
4621 return send_error (ctx, rc);
4623 rc = 0;
4624 if (!sym)
4626 p = strv_catv (keys, client->crypto->pubkey);
4627 if (!p)
4628 rc = GPG_ERR_ENOMEM;
4629 else
4630 keys = p;
4633 if (!rc && client->crypto->sigkey)
4635 if (!strv_printf (&keys, "S%s", client->crypto->sigkey))
4637 strv_free (keys);
4638 return send_error (ctx, GPG_ERR_ENOMEM);
4642 if (!rc)
4644 if (keys)
4646 line = strv_join ("\n", keys);
4647 strv_free (keys);
4648 pthread_cleanup_push ((void *)xfree, line);
4649 if (line)
4650 rc = xfer_data (ctx, line, strlen (line));
4651 else
4652 rc = GPG_ERR_ENOMEM;
4654 pthread_cleanup_pop (1);
4656 else
4657 rc = GPG_ERR_NO_DATA;
4659 else
4660 strv_free (keys);
4662 return send_error (ctx, rc);
4665 static gpg_error_t
4666 deletekey_command (assuan_context_t ctx, char *line)
4668 gpg_error_t rc;
4669 struct client_s *client = assuan_get_pointer (ctx);
4670 struct crypto_s *crypto = NULL;
4671 char *keys[] = { NULL, NULL };
4672 gpgme_key_t *result;
4673 char **p = NULL;
4675 if (!(client->flags & FLAG_OPEN))
4676 return send_error (ctx, GPG_ERR_INV_STATE);
4678 rc = peer_is_invoker (client);
4679 if (rc)
4680 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
4682 if (client->flags & FLAG_NO_PINENTRY)
4683 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
4685 if (!*line)
4686 return send_error (ctx, GPG_ERR_SYNTAX);
4688 rc = crypto_keyid_to_16b_once (line);
4689 if (rc)
4690 return send_error (ctx, rc);
4692 for (p = client->crypto->pubkey; p && *p; p++)
4694 if (!strcmp (*p, line))
4695 break;
4698 if (!p)
4700 if (client->crypto->sigkey && strcmp (client->crypto->sigkey, line))
4701 return send_error (ctx, GPG_ERR_FORBIDDEN);
4702 else if (!client->crypto->sigkey)
4703 return send_error (ctx, GPG_ERR_NO_SECKEY);
4706 rc = crypto_init (&crypto, client->ctx, client->filename,
4707 client->flags & FLAG_NO_PINENTRY, NULL);
4708 if (rc)
4709 return send_error (ctx, rc);
4711 pthread_cleanup_push ((void *)crypto_free, crypto);
4712 keys[0] = line;
4713 rc = crypto_list_keys (crypto, keys, 1, &result);
4714 if (!rc)
4716 pthread_cleanup_push ((void *)crypto_free_key_list, result);
4717 rc = crypto_delete_key (client, crypto, *result, 1);
4718 pthread_cleanup_pop (1);
4721 pthread_cleanup_pop (1);
4722 if (gpg_err_source (rc) == GPG_ERR_SOURCE_GPGME
4723 && gpg_err_code (rc) == GPG_ERR_CANCELED)
4724 rc = gpg_error (GPG_ERR_NOT_CONFIRMED);
4726 return send_error (ctx, rc);
4729 static gpg_error_t
4730 kill_command (assuan_context_t ctx, char *line)
4732 struct client_s *client = assuan_get_pointer (ctx);
4733 gpg_error_t rc;
4734 unsigned i, t;
4736 if (!line || !*line)
4737 return send_error (ctx, GPG_ERR_SYNTAX);
4739 MUTEX_LOCK (&cn_mutex);
4740 pthread_cleanup_push ((void *)release_mutex_cb, &cn_mutex);
4741 t = slist_length (cn_thread_list);
4742 rc = GPG_ERR_ESRCH;
4744 for (i = 0; i < t; i++)
4746 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
4747 char *tmp = str_asprintf ("%p", thd->tid);
4749 if (strcmp (line, tmp))
4751 xfree (tmp);
4752 continue;
4755 xfree (tmp);
4756 rc = peer_is_invoker (client);
4757 if (!rc)
4759 #ifdef HAVE_PTHREAD_CANCEL
4760 pthread_cancel (thd->tid);
4761 #else
4762 pthread_kill (thd->tid, SIGUSR2);
4763 #endif
4764 break;
4766 else if (rc == GPG_ERR_EACCES)
4767 rc = GPG_ERR_FORBIDDEN;
4768 else if (rc)
4769 break;
4771 if (config_get_boolean ("global", "strict_kill"))
4772 break;
4774 #ifdef WITH_GNUTLS
4775 if (client->thd->remote && thd->remote)
4777 if (!thd->tls || !thd->tls->fp)
4779 rc = GPG_ERR_INV_STATE;
4780 break;
4782 if (!strcmp (client->thd->tls->fp, thd->tls->fp))
4784 #ifdef HAVE_PTHREAD_CANCEL
4785 pthread_cancel (thd->tid);
4786 #else
4787 pthread_kill (thd->tid, SIGUSR2);
4788 #endif
4789 break;
4792 else if (!client->thd->remote && !thd->remote)
4793 #endif
4795 if (client->thd->peer->uid == thd->peer->uid)
4797 #ifdef HAVE_PTHREAD_CANCEL
4798 pthread_cancel (thd->tid);
4799 #else
4800 pthread_kill (thd->tid, SIGUSR2);
4801 #endif
4804 break;
4807 pthread_cleanup_pop (1);
4808 return send_error (ctx, rc);
4811 static gpg_error_t
4812 listkeys_command (assuan_context_t ctx, char *line)
4814 struct client_s *client = assuan_get_pointer (ctx);
4815 struct crypto_s *crypto = NULL;
4816 char **pattern = NULL;
4817 gpgme_key_t *keys = NULL;
4818 char **result = NULL;
4819 gpg_error_t rc;
4820 struct argv_s *args[] = {
4821 &(struct argv_s) {"secret-only", OPTION_TYPE_NOARG, parse_opt_secret},
4822 NULL
4825 rc = parse_options (&line, args, client, 1);
4826 if (rc)
4827 return send_error (ctx, rc);
4829 rc = crypto_init (&crypto, client->ctx, client->filename,
4830 client->flags & FLAG_NO_PINENTRY, NULL);
4831 if (rc)
4832 return send_error (ctx, rc);
4834 pthread_cleanup_push ((void *)crypto_free, crypto);
4835 pattern = str_split (line, ",", 0);
4836 pthread_cleanup_push ((void *)(void *)strv_free, pattern);
4837 rc = crypto_list_keys (crypto, pattern, client->opts & OPT_SECRET,
4838 &keys);
4839 pthread_cleanup_pop (1);
4840 pthread_cleanup_pop (1);
4841 if (!rc)
4843 int i;
4845 for (i = 0; keys[i]; i++)
4847 char *p = crypto_key_info (keys[i]);
4848 char **r;
4850 if (!p)
4852 rc = GPG_ERR_ENOMEM;
4853 break;
4856 r = strv_cat (result, p);
4857 if (!r)
4859 rc = GPG_ERR_ENOMEM;
4860 break;
4863 result = r;
4866 if (!i)
4867 rc = GPG_ERR_NO_DATA;
4869 crypto_free_key_list (keys);
4872 if (!rc)
4874 line = strv_join ("\n", result);
4875 strv_free (result);
4876 pthread_cleanup_push ((void *)xfree, line);
4877 if (!line)
4878 rc = GPG_ERR_ENOMEM;
4879 else
4880 rc = xfer_data (ctx, line, strlen (line));
4882 pthread_cleanup_pop (1);
4884 else
4885 strv_free (result);
4887 if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
4888 || gpg_err_code (rc) == GPG_ERR_NO_SECKEY)
4889 rc = GPG_ERR_NO_DATA;
4891 return send_error (ctx, rc);
4894 void
4895 init_commands ()
4897 /* !BEGIN-HELP-TEXT!
4899 * This comment is used as a marker to generate the offline documentation
4900 * found in doc/pwmd.info. The indentation needs to be kept for the awk
4901 * script to determine where commands begin and end.
4903 new_command("HELP", 1, 1, 0, help_command, _(
4904 "HELP [--html] [<COMMAND>]\n" /* Showing available commands. */
4905 "Show available commands or command specific help text."
4906 "@*@*"
4907 "The @option{--html} option will output the help text in HTML format."
4910 new_command("DELETEKEY", 1, 1, FLOCK_TYPE_SH|FLOCK_TYPE_KEEP, deletekey_command, _(
4911 "DELETEKEY <keyid>\n" /* Deleting a key from the key ring. */
4912 "Deletes the secret key associated with key @var{keyid} from the keyring. "
4913 "Note that when the key is deleted, the current or other data files using "
4914 "this key will no longer be able to be opened."
4917 new_command("KILL", 1, 0, 0, kill_command, _(
4918 "KILL <thread_id>\n" /* Terminating another client. */
4919 "Terminates the client identified by @var{thread_id} and releases any file "
4920 "lock or other resources it has held. See @code{GETINFO} (@pxref{GETINFO}) "
4921 "for details about listing connected clients. An @code{invoking_user} "
4922 "(@pxref{Configuration}) may kill any client while others may only kill "
4923 "clients of the same @code{UID} or @abbr{TLS} fingerprint."
4926 new_command("LISTKEYS", 1, 0, 0, listkeys_command, _(
4927 "LISTKEYS [--secret-only] [pattern[,<pattern>]]\n" /* Listing keys in the key ring. */
4928 "Returns a new line separated list of key information matching a comma "
4929 "separated list of @var{pattern}'s. When option @option{--secret-only} is "
4930 "specified, only keys matching @var{pattern} that also have a secret key "
4931 "available will be returned."
4934 new_command("KEYINFO", 1, 0, 0, keyinfo_command, _(
4935 "KEYINFO [--learn]\n" /* Showing keys used for the current data file. */
4936 "Returns a new line separated list of key ID's that the currently opened "
4937 "data file has recipients and signers for. If the key is a signing key it "
4938 "will be prefixed with an @code{S}. If the file is a new one, or has no "
4939 "signers in the case of being symmetrically encrypted, the error code "
4940 "@code{GPG_ERR_NO_DATA} is returned."
4941 "@*@*"
4942 "When the @option{--learn} option is passed, keys on a smartcard will be "
4943 "imported."
4946 new_command("GETINFO", 1, 1, 0, getinfo_command, _(
4947 "GETINFO [--data] [--verbose] CACHE | CLIENTS | PID | USER | LAST_ERROR | VERSION\n" /* Obtaining server and client information. */
4948 "Get server and other information. The information is returned via a status "
4949 "message (@pxref{Status Messages}) unless otherwise noted or @option{--data} "
4950 "is specified."
4951 "@*@*"
4952 "@var{CACHE} returns the number of cached documents."
4953 "@*@*"
4954 "@var{CLIENTS} returns the number of "
4955 "connected clients via a status message or a list of connected clients when "
4956 "the @option{--verbose} parameter is used (implies @option{--data}). A "
4957 "verbose line of a client list contains "
4958 "space delimited "
4959 "fields: the thread ID, client name, opened file (@code{/} if none opened), "
4960 "IP address if remote, file lock status, whether the current client is self "
4961 "or not, client state (see below), "
4962 "user ID or TLS fingerprint of the connected client, username if the "
4963 "client is a local one else @code{-}, and finally the time stamp of when the "
4964 "client connected."
4965 "@*@*"
4966 "Client state @code{0} is an unknown client state, state @code{1} indicates "
4967 "the client has connected but hasn't completed initializing, state @code{2} "
4968 "indicates that the client is idle, state @code{3} means the "
4969 "client is in a command and state @code{4} means the client is disconnecting. "
4970 "@*@*"
4971 "@var{PID} returns the process ID number of the server via a data response."
4972 "@*@*"
4973 "@var{VERSION} returns the server version number and compile-time features "
4974 "via a data response with each being space delimited."
4975 "@*@*"
4976 "@var{LAST_ERROR} returns a detailed description of the last failed command "
4977 "via a data response, when available."
4978 "@*@*"
4979 "@var{USER} returns the username or @abbr{TLS} hash of the connected client "
4980 "via a data response."
4983 new_command("PASSWD", 0, 0, FLOCK_TYPE_EX|FLOCK_TYPE_KEEP, passwd_command, _(
4984 "PASSWD\n" /* Changing the passphrase for a key. */
4985 "Changes the passphrase of the secret key required to open the current "
4986 "data file. If the data file is symmetrically encrypted, the error "
4987 "@code{GPG_ERR_NOT_SUPPORTED} is returned. When symmetrically encrypted, "
4988 "the @code{SAVE} command (@pxref{SAVE}) should be used instead to prevent "
4989 "this command saving any unwanted changes to the @abbr{XML} document."
4990 "@*@*"
4991 "This command is not available to non-invoking clients "
4992 "(@pxref{Access Control})."
4995 new_command("OPEN", 1, 1, FLOCK_TYPE_SH|FLOCK_TYPE_KEEP, open_command, _(
4996 "OPEN [--lock] <filename>\n" /* Opening a data file. */
4997 "Opens @var{filename}. When the @var{filename} is not found on the "
4998 "file-system then a new in-memory document will be created. If the file is "
4999 "found, it is looked for in the file cache and when found no passphrase will "
5000 "be required to open it. When not cached, @cite{pinentry(1)} will be used to "
5001 "retrieve the passphrase for decryption unless @option{disable-pinentry} "
5002 "(@pxref{OPTION}) was specified in which case @command{pwmd} will "
5003 "@emph{INQUIRE} the client for the passphrase. Note than when configuration "
5004 "option @option{strict_open} is enabled and the client is not an "
5005 "@option{invoking_user}, an error will be returned when the data file does "
5006 "not exist."
5007 "@*@*"
5008 "When the @option{--lock} option is passed then the file mutex will be "
5009 "locked as if the @code{LOCK} command (@pxref{LOCK}) had been sent after the "
5010 "file had been opened."
5013 new_command("GENKEY", 1, 1, 0, genkey_command, _(
5014 "GENKEY --subkey-of=fpr | --userid=\"str\" [--expire=N] [--algo=\"str\"] [--no-passphrase] [--usage=\"default|sign|encrypt\"]\n" /* Generating a new key. */
5015 "Generates a new key based on option arguments. One of "
5016 "@option{--subkey-of} or @option{--userid} is "
5017 "required. The @option{--subkey-of} option will generate a subkey for the key "
5018 "of the specified fingerprint."
5021 new_command("SAVE", 0, 0, FLOCK_TYPE_EX|FLOCK_TYPE_KEEP, save_command, _(
5022 "SAVE [--sign-keyid=[<fpr>]] [--symmetric | --keyid=<fpr>[,..] | --inquire-keyid]\n" /* Saving document changes to disk. */
5023 "Writes the in-memory @abbr{XML} document to disk. The file written to is the "
5024 "file that was opened when using the @code{OPEN} command (@pxref{OPEN})."
5025 "@*@*"
5026 "If the file is a new one, one of @option{--symmetric}, @option{--keyid} or"
5027 "@option{--inquire-keyid} is required. When not @option{--symmetric}, option "
5028 "@option{--sign-keyid} is also required, but optional otherwise."
5029 "@*@*"
5030 "You can encrypt the data file to a recipient other than the one that it "
5031 "was originally encrypted with by passing the @option{--keyid} or "
5032 "@option{--inquire-keyid} option with a comma separated list of "
5033 "public encryption key fingerprints as its argument. Use the "
5034 "@command{LISTKEYS} command (@pxref{LISTKEYS}) to show key information by "
5035 "pattern. The @option{--sign-keyid} option may also be used to sign the data "
5036 "file with an alternate key by specifying the fingerprint of a signing key. "
5037 "Only one signing key is supported unlike the @option{--keyid} option. "
5038 "A passphrase to decrypt the data file "
5039 "will be required when one or more of the original encryption keys or signing "
5040 "key are not found in either of these two options' arguments or when the data "
5041 "file is symmetrically encrypted reguardless of the @code{require_save_key} "
5042 "configuration parameter. The original encryption keys and signing key will be "
5043 "used when neither of these options are specified."
5044 "@*@*"
5045 "The @option{--keyid} and @option{--sign-keyid} options are not available "
5046 "to non-invoking clients "
5047 "(@pxref{Access Control}) when the recipients or signer do not match those "
5048 "that were used when the file was @code{OPEN}'ed."
5049 "@*@*"
5050 "The @option{--symmetric} option specifies that a new data file be "
5051 "conventionally encrypted. These types of data files do not use a recipient "
5052 "public key but may optionally be signed by using the @option{--sign-keyid} "
5053 "option. To remove the signing key from a symmtrically encrypted data file, "
5054 "leave the option value empty."
5055 "@*@*"
5056 "Note that you cannot change encryption schemes once a data file has been "
5057 "saved."
5060 new_command("ISCACHED", 1, 0, 0, iscached_command, _(
5061 "ISCACHED [--lock] [--agent [--sign]] <filename>\n" /* Testing cache status. */
5062 "Determines the file cache status of the specified @var{filename}. "
5063 "The default is to test whether the filename is cached in memory. Passing "
5064 "option @option{--agent} will test the @command{gpg-agent} cache for at most "
5065 "one cached key used for opening the data file (@pxref{OPEN}). To test if "
5066 "a signing key is cached, pass @option{--sign} along with @option{--agent}. "
5067 "Both the @option{--agent} and @option{--sign} options require an opened data "
5068 "file."
5069 "@*@*"
5070 "An @emph{OK} response is returned if the specified @var{filename} is found "
5071 "in the cache. If not found in the cache but exists on the filesystem "
5072 "then @code{GPG_ERR_NO_DATA} is returned. Otherwise a filesystem error is "
5073 "returned."
5074 "@*@*"
5075 "The @option{--lock} option will lock the file mutex of @var{filename} when "
5076 "the file exists; it does not need to be opened nor cached. The lock will be "
5077 "released when the client exits or sends the @code{UNLOCK} command "
5078 "(@pxref{UNLOCK}). When this option is passed the current data file is closed."
5081 new_command("CLEARCACHE", 1, 1, 0, clearcache_command, _(
5082 "CLEARCACHE [<filename>]\n" /* Removing a cache entry. */
5083 "Clears a file cache entry for all or the specified @var{filename}. Note that "
5084 "this will also clear any @command{gpg-agent} cached keys which may cause "
5085 "problems if another data file shares the same keys as @var{filename}."
5086 "@*@*"
5087 "When clearing all cache entries a permissions test is done against the "
5088 "current client based on the @var{allowed} configuration parameter in a "
5089 "@var{filename} section. Both a cache entry may be cleared and an error "
5090 "returned depending on cached data files and client permissions."
5093 new_command("CACHETIMEOUT", 1, 1, 0, cachetimeout_command, _(
5094 "CACHETIMEOUT <seconds>\n" /* Setting the cache timeout. */
5095 "The time in @var{seconds} until the currently opened data file will be "
5096 "removed from the cache. @code{-1} will keep the cache entry forever, "
5097 "@code{0} will require the passphrase for each @code{OPEN} command "
5098 "(@pxref{OPEN}) or @code{SAVE} (@pxref{SAVE}) command. @xref{Configuration}, "
5099 "and the @code{cache_timeout} parameter."
5102 new_command("LIST", 0, 1, 0, list_command, _(
5103 "LIST [--inquire] [--recurse] [element[<TAB>child[..]]]\n" /* Showing document elements. */
5104 "If no element path is given then a newline separated list of root elements "
5105 "is returned with a data response. If given, then children of the specified "
5106 "element path are returned."
5107 "@*@*"
5108 "Each element path "
5109 "returned will have zero or more flags appened to it. These flags are "
5110 "delimited from the element path by a single space character. A flag itself "
5111 "is a single character. Flag @code{P} indicates that access to the element "
5112 "is denied. Flag @code{+} indicates that there are child nodes of "
5113 "the current element path. Flag @code{E} indicates that an element of the "
5114 "element path contained in a @var{target} attribute could not be found. Flag "
5115 "@code{O} indicates that a @var{target} attribute recursion limit was reached "
5116 "(@pxref{Configuration}). Flag @code{T}, followed by a single space character, "
5117 "then an element path, is the element path of the @var{target} attribute "
5118 "contained in the current element."
5119 "@*@*"
5120 "When a specified element path contains an error, beit from the final "
5121 "element in the path or any previous element, the path is still shown but "
5122 "will contain the error flag for the element with the error. Determining "
5123 "the actual element which contains the error is up to the client. This can be "
5124 "done by traversing the final element up to parent elements that contain the "
5125 "same error flag."
5126 "@*@*"
5127 "The option @option{--recurse} may be used to list the entire element tree "
5128 "for a specified element path or the entire tree for all root elements."
5129 "@*@*"
5130 "When the @option{--inquire} option is passed then all remaining non-option "
5131 "arguments are retrieved via a server @emph{INQUIRE}."
5134 new_command("REALPATH", 0, 1, 0, realpath_command, _(
5135 "REALPATH [--inquire] element[<TAB>child[..]]\n" /* Resolving an element. */
5136 "Resolves all @code{target} attributes of the specified element path and "
5137 "returns the result with a data response. @xref{Target Attribute}, for details."
5138 "@*@*"
5139 "When the @option{--inquire} option is passed then all remaining non-option "
5140 "arguments are retrieved via a server @emph{INQUIRE}."
5143 new_command("STORE", 0, 1, 0, store_command, _(
5144 "STORE element[<TAB>child[..]]<TAB>[content]\n" /* Modifying the content of an element. */
5145 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
5146 "@*@*"
5147 "Creates a new element path or modifies the @var{content} of an existing "
5148 "element. If only a single element is specified then a new root element is "
5149 "created. Otherwise, elements are @key{TAB} delimited and the content will be "
5150 "set to the final @key{TAB} delimited element. If no @var{content} is "
5151 "specified after the final @key{TAB}, then the content of the existing "
5152 "element will be removed; or will be empty if creating a new element."
5153 "@*@*"
5154 "The only restriction of an element name is that it not contain whitespace "
5155 "characters. There is no other whitespace between the @key{TAB} delimited "
5156 "elements. It is recommended that the content of an element be base64 encoded "
5157 "when it contains control or @key{TAB} characters to prevent @abbr{XML} "
5158 "parsing and @command{pwmd} syntax errors."
5161 new_command("RENAME", 0, 1, 0, rename_command, _(
5162 "RENAME [--inquire] element[<TAB>child[..]] <value>\n" /* Renaming an element. */
5163 "Renames the specified @var{element} to the new @var{value}. If an element of "
5164 "the same name as the @var{value} already exists it will be overwritten."
5165 "@*@*"
5166 "When the @option{--inquire} option is passed then all remaining non-option "
5167 "arguments are retrieved via a server @emph{INQUIRE}."
5170 new_command("COPY", 0, 1, 0, copy_command, _(
5171 "COPY [--inquire] source[<TAB>child[..]] dest[<TAB>child[..]]\n" /* Copying an element. */
5172 "Copies the entire element tree starting from the child node of the source "
5173 "element, to the destination element path. If the destination element path "
5174 "does not exist then it will be created; otherwise it is overwritten."
5175 "@*@*"
5176 "Note that attributes from the source element are merged into the "
5177 "destination element when the destination element path exists. When an "
5178 "attribute of the same name exists in both the source and destination "
5179 "elements then the destination attribute will be updated to the source "
5180 "attribute value."
5181 "@*@*"
5182 "When the @option{--inquire} option is passed then all remaining non-option "
5183 "arguments are retrieved via a server @emph{INQUIRE}."
5186 new_command("MOVE", 0, 1, 0, move_command, _(
5187 "MOVE [--inquire] source[<TAB>child[..]] [dest[<TAB>child[..]]]\n" /* Moving an element. */
5188 "Moves the source element path to the destination element path. If the "
5189 "destination is not specified then it will be moved to the root node of the "
5190 "document. If the destination is specified and exists then it will be "
5191 "overwritten; otherwise non-existing elements of the destination element "
5192 "path will be created."
5193 "@*@*"
5194 "When the @option{--inquire} option is passed then all remaining non-option "
5195 "arguments are retrieved via a server @emph{INQUIRE}."
5198 new_command("DELETE", 0, 1, 0, delete_command, _(
5199 "DELETE [--inquire] element[<TAB>child[..]]\n" /* Deleting an element. */
5200 "Removes the specified element path and all of its children. This may break "
5201 "an element with a @code{target} attribute (@pxref{Target Attribute}) that "
5202 "refers to this element or any of its children."
5203 "@*@*"
5204 "When the @option{--inquire} option is passed then all remaining non-option "
5205 "arguments are retrieved via a server @emph{INQUIRE}."
5208 new_command("GET", 0, 1, 0, get_command, _(
5209 "GET [--inquire] element[<TAB>child[..]]\n" /* Getting the content of an element. */
5210 "Retrieves the content of the specified element. The content is returned "
5211 "with a data response."
5212 "@*@*"
5213 "When the @option{--inquire} option is passed then all remaining non-option "
5214 "arguments are retrieved via a server @emph{INQUIRE}."
5217 new_command("ATTR", 0, 1, 0, attr_command, _(
5218 "ATTR [--inquire] SET|GET|DELETE|LIST [<attribute>] element[<TAB>child[..]] ..\n" /* Modifying element attributes. */
5219 "@table @asis\n"
5220 "@item ATTR SET attribute element[<TAB>child[..]] [value]\n"
5221 " Stores or updates an @var{attribute} name and optional @var{value} of an "
5222 "element. When no @var{value} is specified any existing value will be removed."
5223 "@*@*"
5224 "@item ATTR DELETE attribute element[<TAB>child[..]]\n"
5225 " Removes an attribute from an element. If @var{attribute} is @code{_name} "
5226 "or @code{target} an error is returned. Use the @command{DELETE} command "
5227 "(@pxref{DELETE}) instead."
5228 "@*@*"
5229 "@item ATTR LIST element[<TAB>child[..]]\n"
5230 " Retrieves a newline separated list of attributes names and values "
5231 "from the specified element. Each attribute name and value is space delimited."
5232 "@*@*"
5233 "@item ATTR GET attribute element[<TAB>child[..]]\n"
5234 " Retrieves the value of an @var{attribute} from an element."
5235 "@end table\n"
5236 "@*@*"
5237 "When the @option{--inquire} option is passed then all remaining non-option "
5238 "arguments are retrieved via a server @emph{INQUIRE}."
5239 "@*@*"
5240 "@xref{Target Attribute}, for details about this special attribute and also "
5241 "@pxref{Other Attributes} for other attributes that are handled specially "
5242 "by @command{pwmd}."
5245 new_command("XPATH", 0, 1, 0, xpath_command, _(
5246 "XPATH [--inquire] <expression>[<TAB>[value]]\n" /* Modifying more than one element. */
5247 "Evaluates an XPath @var{expression}. If no @var{value} argument is "
5248 "specified it is assumed the expression is a request to return a result. "
5249 "Otherwise, the result is set to the @var{value} argument and the document is "
5250 "updated. If there is no @var{value} after the @key{TAB} character, the value "
5251 "is assumed to be empty and the document is updated. For example:"
5252 "@sp 1\n"
5253 "@example\n"
5254 "XPATH //element[@@_name='password']@key{TAB}\n"
5255 "@end example\n"
5256 "@sp 1\n"
5257 "would clear the content of all @var{password} elements in the data file "
5258 "while leaving off the trailing @key{TAB} would return all @var{password} "
5259 "elements in @abbr{XML} format."
5260 "@*@*"
5261 "When the @option{--inquire} option is passed then all remaining non-option "
5262 "arguments are retrieved via a server @emph{INQUIRE}."
5263 "@*@*"
5264 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
5265 "expression syntax."
5268 new_command("XPATHATTR", 0, 1, 0, xpathattr_command, _(
5269 "XPATHATTR [--inquire] SET|DELETE <name> <expression>[<TAB>[<value>]]\n" /* Modifying more than one element's attributes. */
5270 "Like the @code{XPATH} command (@pxref{XPATH}) but operates on element "
5271 "attributes and does not return a result. For the @var{SET} operation the "
5272 "@var{value} is optional but the field is required. If not specified then "
5273 "the attribute value will be empty. For example:"
5274 "@sp 1\n"
5275 "@example\n"
5276 "XPATHATTR SET password //element[@@_name='password']@key{TAB}\n"
5277 "@end example\n"
5278 "@sp 1\n"
5279 "would create a @var{password} attribute for each @var{password} element "
5280 "found in the document. The attribute value will be empty but still exist."
5281 "@*@*"
5282 "When the @option{--inquire} option is passed then all remaining non-option "
5283 "arguments are retrieved via a server @emph{INQUIRE}."
5284 "@*@*"
5285 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
5286 "expression syntax."
5289 new_command("IMPORT", 0, 1, 0, import_command, _(
5290 "IMPORT [--root=element[<TAB>child[..]]]\n" /* Creating elements from XML. */
5291 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
5292 "@*@*"
5293 "Like the @code{STORE} command (@pxref{STORE}), but the @var{content} "
5294 "argument is raw @abbr{XML} data. The content is created as a child of "
5295 "the element path specified with the @option{--root} option or at the "
5296 "document root when not specified. Existing elements of the same name will "
5297 "be overwritten."
5298 "@*@*"
5299 "The content must begin with an @abbr{XML} element node. @xref{Introduction}, "
5300 "for details."
5303 new_command("DUMP", 1, 1, 0, dump_command, _(
5304 "DUMP\n" /* Showing the XML document. */
5305 "Shows the in memory @abbr{XML} document with indenting. @xref{XPATH}, for "
5306 "dumping a specific node."
5309 new_command("LOCK", 0, 0, 0, lock_command, _(
5310 "LOCK\n" /* Locking the current data file. */
5311 "Locks the mutex associated with the opened file. This prevents other clients "
5312 "from sending commands to the same opened file until the client "
5313 "that sent this command either disconnects or sends the @code{UNLOCK} "
5314 "command. @xref{UNLOCK}."
5317 new_command("UNLOCK", 1, 0, 0, unlock_command, _(
5318 "UNLOCK\n" /* Removing a data file lock. */
5319 "Unlocks the file mutex which was locked with the @code{LOCK} command or "
5320 "a commands' @option{--lock} option (@pxref{LOCK}, @pxref{OPEN}, "
5321 "@pxref{ISCACHED})."
5324 new_command("GETCONFIG", 1, 1, 0, getconfig_command, _(
5325 "GETCONFIG [filename] <parameter>\n" /* Obtaining a configuration value. */
5326 "Returns the value of a @command{pwmd} configuration @var{parameter} with a "
5327 "data response. If no file has been opened then the value for @var{filename} "
5328 "or the default from the @var{global} section will be returned. If a file "
5329 "has been opened and no @var{filename} is specified, the value previously "
5330 "set with the @code{OPTION} command (@pxref{OPTION}) will be returned."
5333 new_command("OPTION", 1, 1, 0, option_command, _(
5334 "OPTION <NAME>=[<VALUE>]\n" /* Setting various client parameters. */
5335 "Sets a client option @var{name} to @var{value}. The value for an option is "
5336 "kept for the duration of the connection with the exception of the "
5337 "@command{pinentry} options which are defaults for all future connections "
5338 "(@pxref{Pinentry}). When @var{value} is empty the option is unset."
5339 "@*@*"
5340 "@table @asis\n"
5341 "@item DISABLE-PINENTRY\n"
5342 "Disable use of @command{pinentry} for passphrase retrieval. When @code{1}, a "
5343 "server inquire is sent to the client to obtain the passphrase. This option "
5344 "may be set as needed before the @code{OPEN} (@pxref{OPEN}), @code{PASSWD} "
5345 "(@pxref{PASSWD}) and @code{SAVE} (@pxref{SAVE}) commands. Set to @code{0} "
5346 "to use a @command{pinentry}."
5347 "@*@*"
5348 "@item DISPLAY\n"
5349 "Set or unset the X11 display to use when prompting for a passphrase."
5350 "@*@*"
5351 "@item TTYNAME\n"
5352 "Set the terminal device path to use when prompting for a passphrase."
5353 "@*@*"
5354 "@item TTYTYPE\n"
5355 "Set the terminal type for use with @option{TTYNAME}."
5356 "@*@*"
5357 "@item NAME\n"
5358 "Associates the thread ID of the connection with the specified textual "
5359 "representation. Useful for debugging log messages. May not contain whitespace."
5360 "@*@*"
5361 "@item LOCK-TIMEOUT\n"
5362 "When not @code{0}, the duration in tenths of a second to wait for the file "
5363 "mutex which has been locked by another thread to be released before returning "
5364 "an error. When @code{-1} the error will be returned immediately."
5365 "@*@*"
5366 "@item CLIENT-STATE\n"
5367 "When set to @code{1} then client state status messages for other clients are "
5368 "sent to the current client. The default is @code{0}."
5369 "@end table\n"
5372 new_command("LS", 1, 1, 0, ls_command, _(
5373 "LS\n" /* Showing available data files. */
5374 "Returns a newline separated list of data files stored in the data directory "
5375 "@file{HOMEDIR/data} (@pxref{Invoking}) with a data response."
5378 new_command("RESET", 1, 1, 0, NULL, _(
5379 "RESET\n" /* Resetting the client state. */
5380 "Closes the currently opened file but keeps any previously set client options "
5381 "(@pxref{OPTION})."
5384 new_command("NOP", 1, 1, 0, NULL, _(
5385 "NOP\n" /* Testing the connection. */
5386 "This command does nothing. It is useful for testing the connection for a "
5387 "timeout condition."
5390 /* !END-HELP-TEXT! */
5391 new_command ("CANCEL", 1, 1, 0, NULL, NULL);
5392 new_command ("END", 1, 1, 0, NULL, NULL);
5393 new_command ("BYE", 1, 1, 0, NULL, NULL);
5395 int i;
5396 for (i = 0; command_table[i]; i++);
5397 qsort (command_table, i - 1, sizeof (struct command_table_s *),
5398 sort_commands);
5401 gpg_error_t
5402 register_commands (assuan_context_t ctx)
5404 int i = 0, rc;
5406 for (; command_table[i]; i++)
5408 if (!command_table[i]->handler)
5409 continue;
5411 rc = assuan_register_command (ctx, command_table[i]->name,
5412 command_table[i]->handler,
5413 command_table[i]->help);
5414 if (rc)
5415 return rc;
5418 rc = assuan_register_bye_notify (ctx, bye_notify);
5419 if (rc)
5420 return rc;
5422 rc = assuan_register_reset_notify (ctx, reset_notify);
5423 if (rc)
5424 return rc;
5426 rc = assuan_register_pre_cmd_notify (ctx, command_startup);
5427 if (rc)
5428 return rc;
5430 return assuan_register_post_cmd_notify (ctx, command_finalize);