Rename inquire keywords for keyid's.
[pwmd.git] / src / commands.c
blobb587b2782a88554277702db5880af8d2cd937862
1 /*
2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015,
3 2016
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_ONLY 0x0800
67 #define OPT_INQUIRE_KEYID 0x1000
68 #define OPT_INQUIRE_SIGN_KEYID 0x2000
69 #define OPT_SYMMETRIC 0x4000
70 #define OPT_NO_SIGNER 0x8000
71 #define OPT_HTML 0x10000
72 #define OPT_CACHE_AGENT 0x20000
73 #define OPT_CACHE_SIGN 0x40000
74 #define OPT_KEYINFO_LEARN 0x80000
76 #define FLOCK_TYPE_NONE 0
77 #define FLOCK_TYPE_SH 0x0001
78 #define FLOCK_TYPE_EX 0x0002
79 #define FLOCK_TYPE_KEEP 0x0004
81 struct command_table_s
83 const char *name;
84 gpg_error_t (*handler) (assuan_context_t, char *line);
85 const char *help;
86 int ignore_startup;
87 int unlock; // unlock the file mutex after validating the checksum
88 unsigned flock_type;
91 static struct command_table_s **command_table;
93 static gpg_error_t do_lock (struct client_s *client, int add);
94 static gpg_error_t validate_checksum (struct client_s *, const char *filename,
95 struct cache_data_s *, unsigned char **,
96 size_t *);
97 static gpg_error_t update_checksum (struct client_s *client);
99 /* When 'status' is true the 'self' field of the status line will be false
100 * because we never send the STATE status message to the same client that
101 * initiated it. */
102 static char *
103 build_client_info_line (struct client_thread_s *thd, int status)
105 char *uid, *username = NULL;
106 char *line;
107 char *name = pthread_getspecific (thread_name_key);
109 #ifdef WITH_GNUTLS
110 if (thd->remote)
111 uid = str_asprintf("#%s", thd->tls->fp);
112 else
114 uid = str_asprintf("%u", thd->peer->uid);
115 username = get_username (thd->peer->uid);
117 #else
118 uid = str_asprintf("%u", thd->peer->uid);
119 username = get_username (thd->peer->uid);
120 #endif
121 line = str_asprintf ("%p %s %s %s %u %u %u %s %s %u",
122 thd->tid,
123 name ? name : "-",
124 thd->cl && thd->cl->filename
125 && (thd->cl->flags & FLAG_OPEN)
126 ? thd->cl->filename : "/",
127 #ifdef WITH_GNUTLS
128 thd->remote ? thd->peeraddr : "-",
129 #else
130 "-",
131 #endif
132 thd->cl && thd->cl->flags & FLAG_HAS_LOCK ? 1 : 0,
133 !status && pthread_equal (pthread_self (), thd->tid) ? 1 : 0,
134 thd->state, uid,
135 #ifdef WITH_GNUTLS
136 thd->remote ? "-" : username,
137 #else
138 username,
139 #endif
140 thd->conntime
143 xfree (username);
144 xfree (uid);
145 return line;
148 void
149 update_client_state (struct client_s *client, unsigned s)
151 MUTEX_LOCK (&cn_mutex);
152 client->thd->state = s;
153 MUTEX_UNLOCK (&cn_mutex);
155 if (client->thd->state != CLIENT_STATE_UNKNOWN)
157 char *line = build_client_info_line (client->thd, 1);
159 pthread_cleanup_push (xfree, line);
160 if (line)
161 send_status_all_not_self (STATUS_STATE, "%s", line);
162 pthread_cleanup_pop (1);
166 static gpg_error_t
167 unlock_file_mutex (struct client_s *client, int remove)
169 gpg_error_t rc = 0;
171 // OPEN: keep the lock for the same file being reopened.
172 if (client->flags & FLAG_KEEP_LOCK && client->flags & FLAG_HAS_LOCK)
173 return 0;
175 if (!(client->flags & FLAG_HAS_LOCK))
176 return GPG_ERR_NOT_LOCKED;
178 rc = cache_unlock_mutex (client->filename, remove);
179 if (rc)
180 rc = GPG_ERR_INV_STATE;
181 else
182 client->flags &= ~(FLAG_HAS_LOCK | FLAG_LOCK_CMD);
184 return rc;
187 static gpg_error_t
188 lock_file_mutex (struct client_s *client, int add)
190 gpg_error_t rc = 0;
191 int timeout = config_get_integer (client->filename, "cache_timeout");
193 if (client->flags & FLAG_HAS_LOCK)
194 return 0;
196 rc = cache_lock_mutex (client->ctx, client->filename,
197 client->lock_timeout, add, timeout);
198 if (!rc)
199 client->flags |= FLAG_HAS_LOCK;
201 return rc;
204 static gpg_error_t
205 file_modified (struct client_s *client, struct command_table_s *cmd)
207 gpg_error_t rc = 0;
208 int type = !cmd->flock_type || (cmd->flock_type & FLOCK_TYPE_SH)
209 ? LOCK_SH : LOCK_EX;
211 if (!(client->flags & FLAG_OPEN))
212 return GPG_ERR_INV_STATE;
214 rc = lock_file_mutex (client, 0);
215 if (rc && rc != GPG_ERR_NO_DATA)
216 return rc;
218 rc = lock_flock (client->ctx, client->filename, type, &client->flock_fd);
219 if (!rc)
221 rc = validate_checksum (client, client->filename, NULL, NULL, NULL);
222 if (gpg_err_code (rc) == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
223 rc = 0;
224 else if (rc)
225 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
227 else if (gpg_err_code (rc) == GPG_ERR_ENOENT)
228 rc = 0;
230 /* FLAG_HAS_LOCK may have been set by the LOCK command or OPEN --lock. */
231 if ((cmd->unlock && !(client->flags & FLAG_HAS_LOCK)) || rc)
232 unlock_file_mutex (client, 0);
234 if (rc || !(cmd->flock_type & FLOCK_TYPE_KEEP))
235 unlock_flock (&client->flock_fd);
237 return rc;
240 static gpg_error_t
241 parse_xml (assuan_context_t ctx, int new)
243 struct client_s *client = assuan_get_pointer (ctx);
244 int cached = client->doc != NULL;
245 gpg_error_t rc = 0;
247 if (new)
249 client->doc = xml_new_document ();
250 if (client->doc)
252 xmlChar *result;
253 int len;
255 xmlDocDumpFormatMemory (client->doc, &result, &len, 0);
256 client->crypto->plaintext = result;
257 client->crypto->plaintext_size = len;
258 if (!client->crypto->plaintext)
260 xmlFreeDoc (client->doc);
261 client->doc = NULL;
262 rc = GPG_ERR_ENOMEM;
265 else
266 rc = GPG_ERR_ENOMEM;
268 else if (!cached)
269 rc = xml_parse_doc ((char *) client->crypto->plaintext,
270 client->crypto->plaintext_size,
271 (xmlDocPtr *)&client->doc);
273 return rc;
276 static void
277 free_client (struct client_s *client)
279 if (client->doc)
280 xmlFreeDoc (client->doc);
282 xfree (client->crc);
283 xfree (client->filename);
284 xfree (client->last_error);
285 crypto_free (client->crypto);
286 client->crypto = NULL;
289 void
290 reset_client (struct client_s *client)
292 assuan_context_t ctx = client->ctx;
293 struct client_thread_s *thd = client->thd;
294 long lock_timeout = client->lock_timeout;
295 xmlErrorPtr xml_error = client->xml_error;
296 int no_pinentry = (client->flags & FLAG_NO_PINENTRY);
297 int flock_fd = client->flock_fd;
299 unlock_file_mutex (client, client->flags & FLAG_NEW);
300 free_client (client);
301 memset (client, 0, sizeof (struct client_s));
302 client->flock_fd = flock_fd;
303 client->xml_error = xml_error;
304 client->ctx = ctx;
305 client->thd = thd;
306 client->lock_timeout = lock_timeout;
307 client->flags |= no_pinentry ? FLAG_NO_PINENTRY : 0;
310 static void
311 req_free (void *arg)
313 if (!arg)
314 return;
316 strv_free ((char **) arg);
319 static gpg_error_t
320 parse_open_opt_lock (void *data, void *value)
322 struct client_s *client = data;
324 (void)value;
325 client->opts |= OPT_LOCK_ON_OPEN;
326 return 0;
329 static gpg_error_t
330 parse_opt_inquire (void *data, void *value)
332 struct client_s *client = data;
334 (void) value;
335 client->opts |= OPT_INQUIRE;
336 return 0;
339 static gpg_error_t
340 update_checksum (struct client_s *client)
342 unsigned char *crc;
343 size_t len;
344 struct cache_data_s *cdata;
345 gpg_error_t rc = get_checksum (client->filename, &crc, &len);
347 if (rc)
348 return rc;
350 xfree (client->crc);
351 client->crc = crc;
352 cdata = cache_get_data (client->filename);
353 if (cdata)
355 xfree (cdata->crc);
356 cdata->crc = xmalloc (len);
357 memcpy (cdata->crc, crc, len);
360 return 0;
363 static gpg_error_t
364 validate_checksum (struct client_s *client, const char *filename,
365 struct cache_data_s *cdata, unsigned char **r_crc,
366 size_t *r_crclen)
368 unsigned char *crc;
369 size_t len;
370 gpg_error_t rc;
371 int n = 0;
373 if (cdata && !cdata->crc)
374 return GPG_ERR_CHECKSUM;
376 rc = get_checksum (filename, &crc, &len);
377 if (rc)
378 return rc;
380 if (cdata)
381 n = memcmp (cdata->crc, crc, len);
382 else if (client->crc)
383 n = memcmp (client->crc, crc, len);
385 if (!n && r_crc)
387 *r_crc = crc;
388 *r_crclen = len;
390 else
391 xfree (crc);
393 return n ? GPG_ERR_CHECKSUM : 0;
396 static gpg_error_t
397 open_command (assuan_context_t ctx, char *line)
399 gpg_error_t rc;
400 struct client_s *client = assuan_get_pointer (ctx);
401 char **req, *filename;
402 int same_file = 0;
403 assuan_peercred_t peer;
404 struct cache_data_s *cdata = NULL;
405 int cached = 0;
406 unsigned char *crc = NULL;
407 size_t crclen = 0;
408 struct argv_s *args[] = {
409 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_open_opt_lock},
410 NULL
413 rc = parse_options (&line, args, client, 1);
414 if (rc)
415 return send_error (ctx, rc);
417 req = str_split (line, " ", 2);
418 if (!req)
419 return send_error (ctx, GPG_ERR_SYNTAX);
421 rc = do_validate_peer (ctx, req[0], &peer);
422 if (rc == GPG_ERR_FORBIDDEN)
423 rc = peer_is_invoker (client);
425 if (rc)
427 strv_free (req);
428 return send_error (ctx, rc);
431 filename = req[0];
432 if (!valid_filename (filename))
434 strv_free (req);
435 return send_error (ctx, GPG_ERR_INV_VALUE);
438 pthread_cleanup_push ((void *)req_free, req);
439 /* This client may have locked a different file with ISCACHED --lock than
440 * the current filename. This will remove that lock. */
441 same_file = client->filename && !strcmp (filename, client->filename);
442 if (client->flags & FLAG_OPEN ||
443 (client->flags & FLAG_HAS_LOCK && !same_file))
445 unsigned opts = client->opts;
446 unsigned flags = client->flags;
448 if (same_file)
449 client->flags |= FLAG_KEEP_LOCK;
450 else if (client->flags & FLAG_NEW)
451 cache_clear (NULL, client->filename, 0);
453 reset_client (client);
454 client->opts = opts;
455 client->flags |= flags;
456 client->flags &= ~(FLAG_LOCK_CMD);
457 if (!same_file)
458 client->flags &= ~(FLAG_HAS_LOCK | FLAG_NEW);
461 client->filename = str_dup (filename);
462 if (!client->filename)
464 strv_free (req);
465 return send_error(ctx, GPG_ERR_ENOMEM);
468 /* Need to lock the mutex here because file_modified() cannot without
469 * knowing the filename. */
470 rc = lock_file_mutex (client, 1);
471 if (rc)
472 client->flags &= ~FLAG_OPEN;
474 if (!rc)
476 rc = lock_flock (ctx, filename, LOCK_SH, &client->flock_fd);
477 if (gpg_err_code (rc) == GPG_ERR_ENOENT)
478 rc = 0;
481 if (!rc)
483 char *keyfile = config_get_string (client->filename, "passphrase_file");
485 rc = crypto_init (&client->crypto, client->ctx, client->filename,
486 client->flags & FLAG_NO_PINENTRY, keyfile);
487 if (rc)
488 xfree (keyfile);
490 rc = open_check_file (client->filename, NULL, NULL, 1);
493 if (!rc || gpg_err_code (rc) == GPG_ERR_ENOENT)
495 cdata = cache_get_data (client->filename);
497 if (rc) // new file
499 rc = 0;
500 client->flags |= FLAG_NEW;
501 // data file disappeared. clear the cache entry.
502 cache_clear (NULL, client->filename, 1);
503 cdata = NULL;
505 else if (cdata && cdata->doc) // cached document
507 int reload = 0;
508 int defer = 0;
510 if (!rc && !(client->flags & FLAG_NEW))
512 rc = validate_checksum (client, client->filename, cdata, &crc,
513 &crclen);
514 if (rc == GPG_ERR_CHECKSUM)
516 rc = 0;
517 reload = 1;
521 if (!rc)
523 rc = cache_iscached (client->filename, &defer, 0, 0);
524 if ((!rc || rc == GPG_ERR_ENOENT) && defer)
526 rc = 0;
527 reload = 2;
531 if (!rc && reload)
533 if (reload == 1)
534 log_write ("%s: %s", client->filename,
535 pwmd_strerror (GPG_ERR_CHECKSUM));
536 cache_clear (NULL, client->filename, 1);
537 cdata = NULL;
538 rc = crypto_decrypt (client, client->crypto);
540 #ifdef WITH_GNUTLS
541 else if (!rc)
543 if (client->thd->remote
544 && config_get_boolean (client->filename, "tcp_require_key")
545 && !(client->flags & FLAG_NEW))
546 rc = crypto_try_decrypt (client,
547 (client->flags & FLAG_NO_PINENTRY));
549 #endif
551 if (!rc && cdata)
553 client->crypto->plaintext = cdata->doc;
554 client->crypto->plaintext_size = cdata->size;
555 rc = cache_decrypt (client->crypto);
556 if (!rc)
558 cdata->doc = NULL;
559 cdata->size = 0;
560 strv_free (client->crypto->pubkey);
561 strv_free (client->crypto->sigkey);
562 client->crypto->pubkey = strv_dup (cdata->pubkey);
563 client->crypto->sigkey = strv_dup (cdata->sigkey);
564 cached = 1;
566 else
568 client->crypto->plaintext = NULL;
569 client->crypto->plaintext_size = 0;
573 else // existing file
575 cached = cdata != NULL;
576 rc = crypto_decrypt (client, client->crypto);
580 if (!rc)
582 rc = parse_xml (ctx, client->flags & FLAG_NEW);
583 if (!rc)
585 rc = cache_encrypt (client->crypto);
586 if (rc)
587 cache_clear (NULL, client->filename, 1);
588 else
590 int timeout = config_get_integer (client->filename,
591 "cache_timeout");
593 cache_free_data_once (cdata);
594 cdata = xcalloc (1, sizeof (struct cache_data_s));
595 cdata->doc = client->crypto->plaintext;
596 cdata->size = client->crypto->plaintext_size;
597 cdata->pubkey = strv_dup(client->crypto->pubkey);
598 cdata->sigkey = strv_dup(client->crypto->sigkey);
599 client->crypto->plaintext = NULL;
600 client->crypto->plaintext_size = 0;
602 if (cached) // wont increment the refcount
604 /* Prevent using another FD to update the checksum for a
605 * cached data file. The validity has already been
606 * verified. */
607 xfree (client->crc);
608 client->crc = xmalloc (crclen);
609 memcpy (client->crc, crc, crclen);
610 xfree (cdata->crc);
611 cdata->crc = xmalloc (crclen);
612 memcpy (cdata->crc, crc, crclen);
614 rc = cache_set_data (client->filename, cdata);
615 /* The cache entry may have been removed and cache_set_data()
616 * already sent STATUS_CACHE. */
617 if (!cache_iscached (client->filename, NULL, 0, 0))
618 rc = send_status (ctx, STATUS_CACHE, NULL);
620 else
621 rc = cache_add_file (client->filename, cdata, timeout);
626 pthread_cleanup_pop (1);
627 xfree (crc);
629 if (!rc && !(client->flags & FLAG_NEW) && !cached)
630 rc = update_checksum (client);
632 if (!rc)
634 client->flags |= FLAG_OPEN;
636 if (client->flags & FLAG_NEW)
637 rc = send_status (ctx, STATUS_NEWFILE, NULL);
639 if (!rc && (client->opts & OPT_LOCK_ON_OPEN))
640 rc = do_lock (client, 0);
643 if (rc)
645 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
647 if (client->flags & FLAG_NEW)
648 cache_clear (NULL, client->filename, 1);
650 crypto_free (client->crypto);
651 client->crypto = NULL;
652 client->flags &= ~FLAG_OPEN;
654 else
655 crypto_free_non_keys (client->crypto);
657 return send_error (ctx, rc);
660 /* If not the invoking_user or is an existing file, check that the list of user
661 * supplied key ID's are in the list of current key ID's obtained when
662 * decrypting the data file.
664 static gpg_error_t
665 permitted_to_save (struct client_s *client, const char **keys,
666 const char **value)
668 gpg_error_t rc = 0;
669 const char **v;
671 if ((client->flags & FLAG_NEW) || (client->opts & OPT_SYMMETRIC))
672 return 0;
674 rc = peer_is_invoker (client);
675 if (!rc)
676 return 0;
678 /* Empty match. */
679 if ((!value && !keys) || ((value && !*value) && (keys && !*keys)))
680 return 0;
682 for (v = value; v && *v; v++)
684 const char **k, *pv = *v;
685 int match = 0;
687 if (*pv == '0' && *(pv+1) == 'x')
688 pv += 2;
690 for (k = keys; k && *k; k++)
692 const char *pk = *k;
694 if (*pk == '0' && *(pk+1) == 'x')
695 pk += 2;
697 rc = !strcmp (pv, pk) ? 0 : GPG_ERR_FORBIDDEN;
698 if (rc)
699 rc = !strcmp (pv, *k) ? 0 : GPG_ERR_FORBIDDEN;
701 if (!rc)
703 match = 1;
704 break;
708 if (!match)
709 return GPG_ERR_FORBIDDEN;
712 return rc;
715 /* Requires that the keyid be a fingerprint in 16 byte form. */
716 static gpg_error_t
717 parse_save_opt_keyid_common (struct client_s *client, const char **list,
718 const char *value, char ***dst)
720 gpg_error_t rc = 0;
721 char **keys = NULL;
723 if (value && *value)
725 keys = str_split (value, ",", 0);
726 if (!keys)
727 return GPG_ERR_ENOMEM;
730 rc = crypto_keyid_to_16b (keys);
731 if (!rc)
732 rc = permitted_to_save (client, list, (const char **)keys);
734 if (!rc)
735 *dst = keys;
736 else
737 strv_free (keys);
739 return rc;
742 static gpg_error_t
743 parse_save_opt_keyid (void *data, void *value)
745 struct client_s *client = data;
746 const char *str = value;
747 char **dst = NULL;
748 gpg_error_t rc;
750 rc = parse_save_opt_keyid_common (client,
751 (const char **)client->crypto->pubkey,
752 str, &dst);
753 if (rc)
754 return rc;
756 client->crypto->save.pubkey = dst;
757 return 0;
760 static gpg_error_t
761 parse_save_opt_sign_keyid (void *data, void *value)
763 struct client_s *client = data;
764 const char *str = value;
765 char **dst = NULL;
766 gpg_error_t rc;
768 rc = parse_save_opt_keyid_common (client,
769 (const char **)client->crypto->sigkey,
770 str, &dst);
771 if (rc)
772 return rc;
774 if (!dst)
775 client->opts |= OPT_NO_SIGNER;
777 client->crypto->save.sigkey = dst;
778 return 0;
781 static gpg_error_t
782 parse_save_opt_inquire (struct client_s *client, unsigned opt)
784 if (opt == OPT_INQUIRE && !(client->flags & FLAG_NEW))
786 gpg_error_t rc = peer_is_invoker (client);
788 if (rc)
789 return rc;
792 client->opts |= opt;
793 return 0;
796 static gpg_error_t
797 parse_save_opt_inquire_keyparam (void *data, void *value)
799 (void)value;
800 return parse_save_opt_inquire (data, OPT_INQUIRE);
803 static gpg_error_t
804 parse_save_opt_inquire_keyid (void *data, void *value)
806 (void)value;
807 return parse_save_opt_inquire (data, OPT_INQUIRE_KEYID);
810 static gpg_error_t
811 parse_save_opt_inquire_sign_keyid (void *data, void *value)
813 (void)value;
814 return parse_save_opt_inquire (data, OPT_INQUIRE_SIGN_KEYID);
817 static gpg_error_t
818 parse_save_opt_symmetric (void *data, void *value)
820 struct client_s *client = data;
822 (void)value;
823 client->opts |= OPT_SYMMETRIC;
824 return 0;
827 /* Tests that the keys in new_keys are also in old_keys. */
828 static gpg_error_t
829 compare_keys (char **new_keys, char **old_keys)
831 char **o;
833 if (!old_keys || !*old_keys)
834 return 0;
836 crypto_keyid_to_16b (new_keys);
838 for (o = old_keys; *o; o++)
840 char **n;
842 for (n = new_keys; *n; n++)
844 if (!strcmp (*n, *o))
845 break;
848 if (!*n)
849 return GPG_ERR_NOT_FOUND;
852 return 0;
855 static gpg_error_t
856 inquire_keyid (struct client_s *client, unsigned opt)
858 gpg_error_t rc;
859 unsigned char *result = NULL;
860 size_t len;
861 const char *s;
862 char ***orig;
863 char ***save;
865 if (opt == OPT_INQUIRE_KEYID)
867 s = "KEYID";
868 orig = &client->crypto->pubkey;
869 save = &client->crypto->save.pubkey;
871 else
873 s = "SIGN_KEYID";
874 orig = &client->crypto->sigkey;
875 save = &client->crypto->save.sigkey;
878 rc = assuan_inquire (client->ctx, s, &result, &len, 0);
879 if (!rc)
881 char **dst = NULL;
883 rc = parse_save_opt_keyid_common (client, (const char **)*orig,
884 (char *)result, &dst);
885 if (!rc)
887 if (!dst && opt == OPT_INQUIRE_SIGN_KEYID
888 && client->opts & OPT_SYMMETRIC)
889 client->opts |= OPT_NO_SIGNER;
891 *save = dst;
895 xfree (result);
896 return rc;
899 /* The caching test of gpg-agent is both a blessing and a curse. When a key
900 * lookup in its cache fails it tries the last successful key to be unlocked.
901 * This prevents pwmd from successfully clearing a signing key since the
902 * previous key, which more than likely belongs to the same keypair as the
903 * encryption/decryption key, will have the passphrase cached and therefore the
904 * signing key also cached. So we need to clear both the signing and encryption
905 * keys to get the effect of requiring a passphrase when generating a new
906 * keypair for an existing data file, or when the "require_save_key"
907 * configuration parameter is set. The "require_save_key" parameter is mostly a
908 * failsafe of the gpg-agent option --ignore-cache-for-signing since
909 * some/most/all users may fail to set it.
911 static gpg_error_t
912 save_command (assuan_context_t ctx, char *line)
914 struct client_s *client = assuan_get_pointer (ctx);
915 struct cache_data_s *cdata = NULL;
916 gpg_error_t rc = 0, cached = 0;
917 int defer = 0;
918 struct argv_s *args[] = {
919 &(struct argv_s) {"keyid", OPTION_TYPE_ARG, parse_save_opt_keyid},
920 &(struct argv_s) {"sign-keyid", OPTION_TYPE_OPTARG,
921 parse_save_opt_sign_keyid},
922 &(struct argv_s) {"inquire-keyparam", OPTION_TYPE_NOARG,
923 parse_save_opt_inquire_keyparam },
924 &(struct argv_s) {"inquire-keyid", OPTION_TYPE_NOARG,
925 parse_save_opt_inquire_keyid },
926 &(struct argv_s) {"inquire-sign-keyid", OPTION_TYPE_NOARG,
927 parse_save_opt_inquire_sign_keyid },
928 &(struct argv_s) {"symmetric", OPTION_TYPE_NOARG,
929 parse_save_opt_symmetric },
930 NULL
933 crypto_free_save (&client->crypto->save);
935 if (!(client->flags & FLAG_NEW))
937 rc = crypto_is_symmetric (client->filename);
938 if (!rc || rc == GPG_ERR_BAD_DATA)
940 if (!rc)
941 client->opts |= OPT_SYMMETRIC;
943 rc = 0; // PKI
947 if (rc)
948 return send_error (ctx, rc);
950 rc = parse_options (&line, args, client, 0);
951 if (rc)
952 return send_error (ctx, rc);
955 if (config_get_boolean (client->filename, "require_save_key")
956 || (client->opts & OPT_SYMMETRIC))
957 client->opts |= OPT_ASK;
959 rc = open_check_file (client->filename, NULL, NULL, 1);
960 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
962 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
963 return send_error (ctx, rc);
966 if (!rc)
967 cached = rc = cache_iscached (client->filename, &defer, 0, 1);
969 if (gpg_err_code (rc) == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
970 rc = 0;
971 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
972 rc = 0;
974 if (rc)
975 return send_error (ctx, rc);
977 /* Specifying both a recipient and symmetric encryption is an error. */
978 if (client->opts & OPT_INQUIRE_KEYID && client->opts & OPT_SYMMETRIC)
980 return send_error (ctx, GPG_ERR_CONFLICT);
982 else if (client->opts & OPT_INQUIRE && client->opts & OPT_SYMMETRIC)
984 return send_error (ctx, GPG_ERR_CONFLICT);
986 /* Existing file with a recipient and wanting symmetric is an error. */
987 else if (client->opts & OPT_SYMMETRIC && client->crypto->save.pubkey)
989 return send_error (ctx, GPG_ERR_CONFLICT);
991 else if (((client->opts & OPT_INQUIRE_KEYID)
992 || (client->opts & OPT_INQUIRE_SIGN_KEYID)))
994 if (client->opts & OPT_INQUIRE)
995 return send_error (ctx, GPG_ERR_CONFLICT);
997 if (client->opts & OPT_INQUIRE_KEYID)
998 rc = inquire_keyid (client, OPT_INQUIRE_KEYID);
1000 if (!rc && (client->opts & OPT_INQUIRE_SIGN_KEYID))
1001 rc = inquire_keyid (client, OPT_INQUIRE_SIGN_KEYID);
1003 else if ((client->crypto->save.pubkey || client->crypto->save.sigkey)
1004 && client->opts & OPT_INQUIRE)
1005 return send_error (ctx, GPG_ERR_CONFLICT);
1007 if (!rc)
1009 client->crypto->keyfile = config_get_string (client->filename,
1010 "passphrase_file");
1011 rc = crypto_init_ctx (client->crypto, (client->flags & FLAG_NO_PINENTRY),
1012 client->crypto->keyfile);
1015 if (!rc && (client->opts & OPT_INQUIRE))
1017 /* Require a passphrase when generating a new key pair for an existing
1018 * file.
1020 if (!(client->flags & FLAG_NEW))
1022 rc = cache_clear_agent_keys (client->filename, 1, 1);
1023 if (!rc)
1025 rc = crypto_try_decrypt (client, client->flags & FLAG_NO_PINENTRY);
1026 client->opts &= ~OPT_ASK;
1030 if (!rc)
1032 unsigned char *params = NULL;
1033 size_t len;
1035 rc = assuan_inquire (client->ctx, "KEYPARAM", &params, &len, 0);
1036 if (!rc)
1038 client->crypto->flags |= CRYPTO_FLAG_NEWFILE;
1039 pthread_cleanup_push ((void *)xfree, params);
1040 rc = crypto_genkey (client, client->crypto, params);
1041 pthread_cleanup_pop (1);
1045 else if (!rc && (client->flags & FLAG_NEW))
1047 if (!client->crypto->save.pubkey && !client->crypto->save.sigkey
1048 && !(client->opts & OPT_SYMMETRIC))
1050 char *params = crypto_default_key_params ();
1052 if (!params)
1053 rc = GPG_ERR_ENOMEM;
1055 if (!rc)
1057 client->crypto->flags |= CRYPTO_FLAG_NEWFILE;
1058 pthread_cleanup_push ((void *)xfree, params);
1059 rc = crypto_genkey (client, client->crypto,
1060 (unsigned char *)params);
1061 pthread_cleanup_pop (1);
1064 else
1066 if (!client->crypto->save.pubkey && client->crypto->save.sigkey
1067 && !(client->opts & OPT_SYMMETRIC))
1068 client->crypto->save.pubkey = strv_dup (client->crypto->save.sigkey);
1070 if (client->crypto->save.pubkey && !client->crypto->save.sigkey)
1071 client->crypto->save.sigkey = strv_dup (client->crypto->save.pubkey);
1074 else if (!rc)
1076 cdata = cache_get_data (client->filename);
1077 if (cdata)
1079 if (client->crypto->save.pubkey)
1080 rc = compare_keys (client->crypto->save.pubkey, cdata->pubkey);
1082 /* Always allow a signer for symmetric data files. */
1083 if (!rc && client->crypto->save.sigkey
1084 && !(client->opts & OPT_SYMMETRIC))
1085 rc = compare_keys (client->crypto->save.sigkey, cdata->sigkey);
1087 /* Prevent saving to a recipient who is not in the original recipient
1088 * list without a passphrase. */
1089 if (rc || (client->crypto->sigkey && client->opts & OPT_NO_SIGNER))
1090 client->opts |= OPT_ASK;
1092 if (rc == GPG_ERR_NOT_FOUND)
1094 rc = peer_is_invoker (client);
1095 if (rc == GPG_ERR_EACCES)
1096 rc = GPG_ERR_FORBIDDEN;
1099 if (!client->crypto->save.pubkey
1100 && !(client->opts & OPT_SYMMETRIC))
1101 client->crypto->save.pubkey = strv_dup (cdata->pubkey);
1103 if (!rc && !client->crypto->save.sigkey && cdata->sigkey
1104 && !(client->opts & OPT_NO_SIGNER))
1105 client->crypto->save.sigkey = strv_dup (cdata->sigkey);
1106 else if (!rc && !client->crypto->save.sigkey
1107 && (client->opts & OPT_NO_SIGNER)
1108 && !(client->opts & OPT_SYMMETRIC))
1109 rc = GPG_ERR_NO_SIGNATURE_SCHEME;
1111 else
1113 client->crypto->save.pubkey = strv_dup (client->crypto->pubkey);
1114 client->crypto->save.sigkey = strv_dup (client->crypto->sigkey);
1118 if (!rc && !(client->flags & FLAG_NEW))
1120 /* Fixes {NEW_,SIGN_}PASSPHRASE inquire keywords. See passphrase_cb(). */
1121 if (client->opts & OPT_SYMMETRIC)
1122 client->crypto->flags |= CRYPTO_FLAG_PASSWD;
1124 if (client->opts & OPT_ASK)
1126 rc = cache_clear_agent_keys (client->filename, 1, 1);
1127 if (!rc)
1128 rc = crypto_try_decrypt (client, client->flags & FLAG_NO_PINENTRY);
1132 if (!rc && client->opts & OPT_SYMMETRIC)
1133 client->crypto->flags |= CRYPTO_FLAG_PASSWD_NEW;
1135 if (!rc)
1136 rc = xml_update_element_mtime (client, xmlDocGetRootElement (client->doc));
1138 if (!rc)
1140 int size;
1142 xmlDocDumpFormatMemory (client->doc, &client->crypto->plaintext, &size,
1144 if (size > 0)
1145 client->crypto->plaintext_size = (size_t) size;
1146 else
1147 rc = GPG_ERR_ENOMEM;
1149 if (!rc)
1151 client->crypto->flags |= (client->opts & OPT_SYMMETRIC) ? CRYPTO_FLAG_SYMMETRIC : 0;
1152 client->crypto->flags |= (client->flags & FLAG_NEW) ? CRYPTO_FLAG_NEWFILE : 0;
1153 client->crypto->flags |= !(client->opts & OPT_SYMMETRIC) ? CRYPTO_FLAG_PASSWD_SIGN : 0;
1154 rc = crypto_encrypt (client, client->crypto);
1155 client->crypto->flags &= ~CRYPTO_FLAG_SYMMETRIC;
1158 if (!rc)
1160 rc = crypto_write_file (client->crypto);
1161 if (!rc)
1163 if (!cached) // no error
1164 cdata = cache_get_data (client->filename);
1167 if (!rc)
1169 rc = cache_encrypt (client->crypto);
1170 if (rc)
1172 cache_clear (NULL, client->filename, 1);
1173 strv_free (client->crypto->pubkey);
1174 client->crypto->pubkey = strv_dup (client->crypto->save.pubkey);
1175 strv_free (client->crypto->sigkey);
1176 client->crypto->sigkey = strv_dup (client->crypto->save.sigkey);
1177 client->flags &= ~(FLAG_NEW);
1181 if (!rc)
1183 int timeout = config_get_integer (client->filename,
1184 "cache_timeout");
1186 cache_free_data_once (cdata);
1187 cdata = xcalloc (1, sizeof (struct cache_data_s));
1188 cdata->doc = client->crypto->plaintext;
1189 client->crypto->plaintext = NULL;
1190 cdata->size = client->crypto->plaintext_size;
1191 client->crypto->plaintext_size = 0;
1192 cdata->pubkey = client->crypto->save.pubkey;
1193 client->crypto->save.pubkey = NULL;
1194 cdata->sigkey = client->crypto->save.sigkey;
1195 client->crypto->save.sigkey = NULL;
1197 /* Update in case the cache entry expires the next SAVE may not
1198 * have any known keys. */
1199 strv_free (client->crypto->pubkey);
1200 client->crypto->pubkey = strv_dup (cdata->pubkey);
1201 strv_free (client->crypto->sigkey);
1202 client->crypto->sigkey = strv_dup (cdata->sigkey);
1204 if (!cached) // no error and wont increment refcount
1205 rc = cache_set_data (client->filename, cdata);
1206 else
1207 rc = cache_add_file (client->filename, cdata, timeout);
1209 if (!rc && (cached || (client->flags & FLAG_NEW)))
1210 send_status_all (STATUS_CACHE, NULL);
1212 if (!rc)
1214 rc = update_checksum (client);
1215 client->flags &= ~(FLAG_NEW);
1221 crypto_free_non_keys (client->crypto);
1222 return send_error (ctx, rc);
1225 static gpg_error_t
1226 do_delete (assuan_context_t ctx, char *line)
1228 struct client_s *client = assuan_get_pointer (ctx);
1229 struct xml_request_s *req;
1230 xmlNodePtr n;
1231 gpg_error_t rc;
1233 rc = xml_new_request (client, line, XML_CMD_DELETE, &req);
1234 if (rc)
1235 return rc;
1237 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1238 xml_free_request (req);
1239 if (rc)
1240 return rc;
1242 rc = xml_is_element_owner (client, n);
1243 if (!rc)
1244 rc = xml_unlink_node (client, n);
1246 return rc;
1249 static gpg_error_t
1250 delete_command (assuan_context_t ctx, char *line)
1252 struct client_s *client = assuan_get_pointer (ctx);
1253 gpg_error_t rc;
1254 struct argv_s *args[] = {
1255 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1256 NULL
1259 rc = parse_options (&line, args, client, 1);
1260 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1261 rc = GPG_ERR_SYNTAX;
1262 if (rc)
1263 return send_error (ctx, rc);
1265 if (client->opts & OPT_INQUIRE)
1267 unsigned char *result;
1268 size_t len;
1270 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1271 if (rc)
1272 return send_error (ctx, rc);
1274 pthread_cleanup_push ((void *)xfree, result);
1275 rc = do_delete (ctx, (char *)result);
1276 pthread_cleanup_pop (1);
1278 else
1279 rc = do_delete (ctx, line);
1281 return send_error (ctx, rc);
1284 static gpg_error_t
1285 update_element_expirey (struct client_s *client, xmlNodePtr n)
1287 gpg_error_t rc = 0;
1288 xmlChar *expire, *incr;
1289 char *p;
1290 time_t e, e_orig, i;
1291 time_t now = time (NULL);
1293 expire = xml_attribute_value (n, (xmlChar *)"expire");
1294 if (!expire)
1295 return 0;
1297 errno = 0;
1298 e = strtoul ((char *)expire, &p, 10);
1299 if (errno || *p || e == ULONG_MAX || *expire == '-')
1301 xmlFree (expire);
1302 rc = GPG_ERR_ERANGE;
1303 goto fail;
1306 xmlFree (expire);
1307 incr = xml_attribute_value (n, (xmlChar *)"expire_increment");
1308 if (!incr)
1309 return 0;
1311 i = strtoul ((char *)incr, &p, 10);
1312 if (errno || *p || i == ULONG_MAX || *incr == '-')
1314 xmlFree (incr);
1315 rc = GPG_ERR_ERANGE;
1316 goto fail;
1319 xmlFree (incr);
1320 e_orig = e;
1321 e = now + i;
1322 p = str_asprintf ("%lu", e);
1323 if (!p)
1325 rc = GPG_ERR_ENOMEM;
1326 goto fail;
1329 rc = xml_add_attribute (client, n, "expire", p);
1330 xfree (p);
1331 if (!rc)
1332 rc = send_status (client->ctx, STATUS_EXPIRE, "%lu %lu", e_orig, e);
1334 fail:
1335 return rc;
1338 static gpg_error_t
1339 store_command (assuan_context_t ctx, char *line)
1341 struct client_s *client = assuan_get_pointer (ctx);
1342 gpg_error_t rc;
1343 size_t len;
1344 unsigned char *result;
1345 xmlNodePtr n, parent;
1346 int has_content;
1347 char *content = NULL;
1348 struct xml_request_s *req;
1350 if (line && *line)
1351 return send_error (ctx, GPG_ERR_SYNTAX);
1353 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1354 if (rc)
1355 return send_error (ctx, rc);
1357 rc = xml_new_request (client, (char *)result, XML_CMD_STORE, &req);
1358 xfree (result);
1359 if (rc)
1360 return send_error (ctx, rc);
1362 /* Prevent passing the element content around to save some memory. */
1363 len = strv_length (req->args);
1364 has_content = line[strlen (line) - 1] != '\t' && len > 1;
1365 if (*(req->args+1) && !xml_valid_element_path (req->args, has_content))
1367 xml_free_request (req);
1368 return send_error (ctx, GPG_ERR_INV_VALUE);
1371 if (has_content || !*req->args[len-1])
1373 has_content = 1;
1374 content = req->args[len-1];
1375 req->args[len-1] = NULL;
1378 if (strv_length (req->args) > 1)
1380 rc = xml_check_recursion (client, req);
1381 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
1382 goto fail;
1385 parent = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1387 if (!rc && len > 1)
1389 rc = xml_is_element_owner (client, parent);
1390 if (!rc)
1392 n = xml_find_text_node (parent->children);
1393 if (n)
1394 xmlNodeSetContent (n, (xmlChar *) content);
1395 else
1396 xmlNodeAddContent (parent, (xmlChar *) content);
1398 (void)xml_update_element_mtime (client, parent);
1399 (void)update_element_expirey (client, parent);
1403 fail:
1404 xfree (content);
1405 xml_free_request (req);
1406 return send_error (ctx, rc);
1409 static gpg_error_t
1410 xfer_data (assuan_context_t ctx, const char *line, int total)
1412 struct client_s *client = assuan_get_pointer (ctx);
1413 int to_send;
1414 int sent = 0;
1415 gpg_error_t rc = 0;
1416 int progress = config_get_integer ("global", "xfer_progress");
1417 int flush = 0;
1419 if (!(client->flags & FLAG_LOCK_CMD))
1420 rc = unlock_file_mutex (client, 0);
1421 if (rc && rc != GPG_ERR_NOT_LOCKED)
1422 return rc;
1424 progress =
1425 progress > 0 ? (progress / ASSUAN_LINELENGTH) * ASSUAN_LINELENGTH : 0;
1426 to_send = total < ASSUAN_LINELENGTH ? total : ASSUAN_LINELENGTH;
1427 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1429 if (rc)
1430 return rc;
1432 again:
1435 if (sent + to_send > total)
1436 to_send = total - sent;
1438 rc = assuan_send_data (ctx, flush ? NULL : (char *) line + sent,
1439 flush ? 0 : to_send);
1440 if (!rc)
1442 sent += flush ? 0 : to_send;
1444 if ((progress && !(sent % progress) && sent != total) ||
1445 (sent == total && flush))
1446 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1448 if (!flush && !rc && sent == total)
1450 flush = 1;
1451 goto again;
1455 while (!rc && sent < total);
1457 return rc;
1460 static gpg_error_t
1461 do_get (assuan_context_t ctx, char *line)
1463 struct client_s *client = assuan_get_pointer (ctx);
1464 gpg_error_t rc;
1465 struct xml_request_s *req;
1466 xmlNodePtr n;
1468 rc = xml_new_request (client, line, XML_CMD_NONE, &req);
1469 if (rc)
1470 return rc;
1472 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1473 if (!rc)
1475 if (n && n->children)
1477 xmlNodePtr tmp = n;
1479 n = xml_find_text_node (n->children);
1480 if (!n || !n->content || !*n->content)
1481 rc = GPG_ERR_NO_DATA;
1482 else
1484 rc = xfer_data (ctx, (char *) n->content, xmlStrlen (n->content));
1485 if (!rc)
1487 xmlChar *expire = xml_attribute_value (tmp,
1488 (xmlChar *)"expire");
1489 if (expire)
1491 time_t now = time (NULL);
1492 time_t e;
1493 char *p;
1495 errno = 0;
1496 e = strtoul ((char *)expire, &p, 10);
1497 if (errno || *p || e == ULONG_MAX || *expire == '-')
1498 log_write (_("invalid expire attribute value: %s"),
1499 expire);
1500 else if (now >= e)
1501 rc = send_status (ctx, STATUS_EXPIRE, "%lu 0", e);
1503 xmlFree (expire);
1508 else
1509 rc = GPG_ERR_NO_DATA;
1512 xml_free_request (req);
1513 return rc;
1516 static gpg_error_t
1517 get_command (assuan_context_t ctx, char *line)
1519 struct client_s *client = assuan_get_pointer (ctx);
1520 gpg_error_t rc;
1521 struct argv_s *args[] = {
1522 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1523 NULL
1526 rc = parse_options (&line, args, client, 1);
1527 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1528 rc = GPG_ERR_SYNTAX;
1529 if (rc)
1530 return send_error (ctx, rc);
1532 if (client->opts & OPT_INQUIRE)
1534 unsigned char *result;
1535 size_t len;
1537 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1538 if (rc)
1539 return send_error (ctx, rc);
1541 pthread_cleanup_push ((void *)xfree, result);
1542 rc = do_get (ctx, (char *)result);
1543 pthread_cleanup_pop (1);
1545 else
1546 rc = do_get (ctx, line);
1548 return send_error (ctx, rc);
1551 static void list_command_free1 (void *arg);
1552 static gpg_error_t
1553 realpath_command (assuan_context_t ctx, char *line)
1555 gpg_error_t rc;
1556 char **realpath = NULL;
1557 struct client_s *client = assuan_get_pointer (ctx);
1558 struct argv_s *args[] = {
1559 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1560 NULL
1563 rc = parse_options (&line, args, client, 1);
1564 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1565 rc = GPG_ERR_SYNTAX;
1566 if (rc)
1567 return send_error (ctx, rc);
1569 if (client->opts & OPT_INQUIRE)
1571 unsigned char *result;
1572 size_t len;
1574 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1575 if (rc)
1576 return send_error (ctx, rc);
1578 pthread_cleanup_push ((void *)xfree, result);
1579 (void)xml_resolve_path (client, client->doc, result, &realpath, &rc);
1580 pthread_cleanup_pop (1);
1582 else
1583 (void)xml_resolve_path (client, client->doc, (unsigned char *)line,
1584 &realpath, &rc);
1586 if (!rc)
1588 char *tmp = strv_join ((char *)"\t", realpath);
1590 strv_free (realpath);
1591 if (!tmp)
1592 return send_error (ctx, GPG_ERR_ENOMEM);
1594 pthread_cleanup_push ((void *)xfree, tmp);
1595 rc = xfer_data (ctx, tmp, strlen (tmp));
1596 pthread_cleanup_pop (1);
1599 return send_error (ctx, rc);
1602 static void
1603 list_command_free1 (void *arg)
1605 if (arg)
1606 string_free ((struct string_s *) arg, 1);
1609 static gpg_error_t
1610 parse_list_opt_recurse (void *data, void *value)
1612 struct client_s *client = data;
1614 (void)value;
1615 client->opts |= OPT_LIST_RECURSE;
1616 return 0;
1619 static gpg_error_t
1620 parse_opt_verbose (void *data, void *value)
1622 struct client_s *client = data;
1624 (void)value;
1625 client->opts |= OPT_VERBOSE;
1626 return 0;
1629 static gpg_error_t
1630 list_path_once (struct client_s *client, char *line,
1631 struct element_list_s *elements, struct string_s *result)
1633 gpg_error_t rc;
1635 rc = xml_create_path_list (client, client->doc, NULL, elements, line, 0);
1636 if (rc == GPG_ERR_ELOOP || rc == GPG_ERR_EACCES)
1637 rc = 0;
1639 if (!rc)
1641 int total = slist_length (elements->list);
1643 if (total)
1645 int i;
1647 for (i = 0; i < total; i++)
1649 char *tmp = slist_nth_data (elements->list, i);
1651 string_append_printf (result, "%s%s", tmp,
1652 i + 1 == total ? "" : "\n");
1655 else
1656 rc = GPG_ERR_NO_DATA;
1659 return rc;
1662 static gpg_error_t
1663 do_list (assuan_context_t ctx, char *line)
1665 struct client_s *client = assuan_get_pointer (ctx);
1666 gpg_error_t rc = GPG_ERR_NO_DATA;
1667 struct element_list_s *elements = NULL;
1669 if (!line || !*line)
1671 struct string_s *str = string_new (NULL);
1672 xmlNodePtr n;
1674 if (!str)
1675 return GPG_ERR_ENOMEM;
1677 pthread_cleanup_push ((void *)list_command_free1, str);
1678 n = xmlDocGetRootElement (client->doc);
1679 for (n = n->children; n; n = n->next)
1681 xmlChar *name;
1683 if (n->type != XML_ELEMENT_NODE)
1684 continue;
1686 name = xmlGetProp (n, (xmlChar *)"_name");
1687 if (!name)
1689 rc = GPG_ERR_ENOMEM;
1690 break;
1693 elements = xcalloc (1, sizeof (struct element_list_s));
1694 if (!elements)
1696 xmlFree (name);
1697 rc = GPG_ERR_ENOMEM;
1698 break;
1701 elements->prefix = string_new (NULL);
1702 if (!elements->prefix)
1704 xmlFree (name);
1705 xml_free_element_list (elements);
1706 rc = GPG_ERR_ENOMEM;
1707 break;
1710 elements->recurse = client->opts & OPT_LIST_RECURSE;
1711 elements->root_only = !elements->recurse;
1712 pthread_cleanup_push ((void *)xml_free_element_list, elements);
1713 rc = list_path_once (client, (char *)name, elements, str);
1714 xmlFree (name);
1715 pthread_cleanup_pop (1);
1716 if (rc)
1717 break;
1719 if (n->next)
1720 string_append (str, "\n");
1723 if (!rc)
1724 rc = xfer_data (ctx, str->str, str->len);
1726 pthread_cleanup_pop (1);
1727 return rc;
1730 elements = xcalloc (1, sizeof (struct element_list_s));
1731 if (!elements)
1732 return GPG_ERR_ENOMEM;
1734 elements->prefix = string_new (NULL);
1735 if (!elements->prefix)
1737 xml_free_element_list (elements);
1738 return GPG_ERR_ENOMEM;
1741 elements->recurse = client->opts & OPT_LIST_RECURSE;
1742 pthread_cleanup_push ((void *)xml_free_element_list, elements);
1743 struct string_s *str = string_new (NULL);
1744 pthread_cleanup_push ((void *)list_command_free1, str);
1745 rc = list_path_once (client, line, elements, str);
1746 if (!rc)
1747 rc = xfer_data (ctx, str->str, str->len);
1749 pthread_cleanup_pop (1);
1750 pthread_cleanup_pop (1);
1751 return rc;
1754 static gpg_error_t
1755 list_command (assuan_context_t ctx, char *line)
1757 struct client_s *client = assuan_get_pointer (ctx);
1758 gpg_error_t rc;
1759 struct argv_s *args[] = {
1760 &(struct argv_s) {"recurse", OPTION_TYPE_NOARG, parse_list_opt_recurse},
1761 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1762 /* These are deprecated but kept for backward compatibility with older
1763 * clients. */
1764 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, NULL},
1765 &(struct argv_s) {"with-target", OPTION_TYPE_NOARG, NULL},
1766 &(struct argv_s) {"all", OPTION_TYPE_NOARG, parse_list_opt_recurse},
1767 &(struct argv_s) {"no-recurse", OPTION_TYPE_NOARG, NULL},
1768 NULL
1771 if (disable_list_and_dump == 1)
1772 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
1774 rc = parse_options (&line, args, client, 1);
1775 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1776 rc = GPG_ERR_SYNTAX;
1777 if (rc)
1778 return send_error (ctx, rc);
1780 if (client->opts & OPT_INQUIRE)
1782 unsigned char *result;
1783 size_t len;
1785 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1786 if (rc)
1787 return send_error (ctx, rc);
1789 pthread_cleanup_push ((void *)xfree, result);
1790 rc = do_list (ctx, (char *)result);
1791 pthread_cleanup_pop (1);
1793 else
1794 rc = do_list (ctx, line);
1796 return send_error (ctx, rc);
1799 #define RESUMABLE_ERROR(rc) (rc == GPG_ERR_ELOOP || rc == GPG_ERR_EACCES \
1800 || rc == GPG_ERR_ELEMENT_NOT_FOUND || !rc)
1802 * args[0] - element path
1804 static gpg_error_t
1805 attribute_list (assuan_context_t ctx, char **args)
1807 struct client_s *client = assuan_get_pointer (ctx);
1808 char **attrlist = NULL;
1809 int i = 0;
1810 int target = 0;
1811 xmlAttrPtr a;
1812 xmlNodePtr n, an, r;
1813 char *line;
1814 gpg_error_t rc;
1815 struct xml_request_s *req;
1817 if (!args || !args[0] || !*args[0])
1818 return GPG_ERR_SYNTAX;
1820 rc = xml_new_request (client, args[0], XML_CMD_ATTR_LIST, &req);
1821 if (rc)
1822 return rc;
1824 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1825 xml_free_request (req);
1826 if (rc)
1827 return rc;
1829 again:
1830 for (a = n->properties; a; a = a->next)
1832 char **pa;
1834 if (target && xml_reserved_attribute ((char *)a->name))
1835 continue;
1837 pa = xrealloc (attrlist, (i + 2) * sizeof (char *));
1838 if (!pa)
1840 if (attrlist)
1841 strv_free (attrlist);
1843 log_write ("%s(%i): %s", __FILE__, __LINE__,
1844 pwmd_strerror (GPG_ERR_ENOMEM));
1845 return GPG_ERR_ENOMEM;
1848 attrlist = pa;
1849 an = a->children;
1850 attrlist[i] = str_asprintf ("%s %s", (char *) a->name, an && an->content
1851 ? (char *)an->content : "");
1853 if (!attrlist[i])
1855 strv_free (attrlist);
1856 log_write ("%s(%i): %s", __FILE__, __LINE__,
1857 pwmd_strerror (GPG_ERR_ENOMEM));
1858 return GPG_ERR_ENOMEM;
1861 attrlist[++i] = NULL;
1864 if (!attrlist)
1865 return GPG_ERR_NO_DATA;
1867 if (!target)
1869 r = xml_resolve_path (client, client->doc, (xmlChar *)args[0], NULL, &rc);
1870 if (!RESUMABLE_ERROR (rc))
1872 strv_free (attrlist);
1873 return rc;
1875 else if (!rc && r != n)
1877 target = 1;
1878 n = r;
1879 goto again;
1882 rc = 0;
1885 line = strv_join ("\n", attrlist);
1886 if (!line)
1888 log_write ("%s(%i): %s", __FILE__, __LINE__,
1889 pwmd_strerror (GPG_ERR_ENOMEM));
1890 strv_free (attrlist);
1891 return GPG_ERR_ENOMEM;
1894 pthread_cleanup_push ((void *)xfree, line);
1895 pthread_cleanup_push ((void *)req_free, attrlist);
1896 rc = xfer_data (ctx, line, strlen (line));
1897 pthread_cleanup_pop (1);
1898 pthread_cleanup_pop (1);
1899 return rc;
1903 * args[0] - attribute
1904 * args[1] - element path
1906 static gpg_error_t
1907 attribute_delete (struct client_s *client, char **args)
1909 gpg_error_t rc;
1910 xmlNodePtr n;
1912 if (!args || !args[0] || !*args[0] || !args[1] || !*args[1])
1913 return GPG_ERR_SYNTAX;
1915 if (!strcmp (args[0], "_name") || !strcmp (args[0], "target"))
1916 return GPG_ERR_INV_ATTR;
1918 if (!xml_reserved_attribute (args[0]))
1919 n = xml_resolve_path (client, client->doc, (xmlChar *)args[1], NULL, &rc);
1920 else
1922 struct xml_request_s *req;
1924 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
1925 if (rc)
1926 return rc;
1928 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1929 xml_free_request (req);
1932 if (!rc)
1933 rc = xml_is_element_owner (client, n);
1935 if (!rc)
1936 rc = xml_delete_attribute (client, n, (xmlChar *) args[0]);
1938 return rc;
1942 * Creates the "target" attribute. When other commands encounter an element
1943 * with this attribute they follow the "target" after appending remaining
1944 * elements from the original element path to the target. The exception is the
1945 * ATTR command that operates on the element itself (for reserved attribute
1946 * names) and not the target.
1948 * If the source element path doesn't exist when using 'ATTR SET target', it is
1949 * created, but the destination element path must exist. This is simliar to the
1950 * ls(1) command: ln -s src dst.
1952 * args[0] - source element path
1953 * args[1] - destination element path
1955 static gpg_error_t
1956 set_target_attribute (struct client_s *client, char **args)
1958 struct xml_request_s *req = NULL;
1959 char **src, **dst;
1960 gpg_error_t rc;
1961 xmlNodePtr n;
1963 if (!args || !args[0] || !args[1])
1964 return GPG_ERR_SYNTAX;
1966 src = str_split (args[0], "\t", 0);
1967 if (!src)
1968 return GPG_ERR_SYNTAX;
1970 if (!xml_valid_element_path (src, 0))
1972 strv_free (src);
1973 return GPG_ERR_INV_VALUE;
1976 dst = str_split (args[1], "\t", 0);
1977 if (!dst)
1979 strv_free (src);
1980 return GPG_ERR_SYNTAX;
1983 // Be sure the destination element path exists. */
1984 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
1985 if (rc)
1986 goto fail;
1988 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1989 if (rc && rc != GPG_ERR_EACCES)
1990 goto fail;
1992 xml_free_request (req);
1993 req = NULL;
1995 if (!strcmp (args[0], args[1]))
1997 rc = GPG_ERR_EEXIST;
1998 goto fail;
2001 rc = xml_new_request (client, args[0], XML_CMD_ATTR_TARGET, &req);
2002 if (rc)
2003 goto fail;
2005 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2006 if (rc && rc != GPG_ERR_EACCES)
2007 goto fail;
2009 if (!rc)
2011 rc = xml_add_attribute (client, n, "target", args[1]);
2012 if (!rc)
2013 rc = xml_unlink_node (client, n->children);
2016 fail:
2017 strv_free (src);
2018 strv_free (dst);
2019 xml_free_request (req);
2020 return rc;
2024 * args[0] - attribute
2025 * args[1] - element path
2027 static gpg_error_t
2028 attribute_get (assuan_context_t ctx, char **args)
2030 struct client_s *client = assuan_get_pointer (ctx);
2031 xmlNodePtr n;
2032 xmlChar *a;
2033 gpg_error_t rc;
2034 struct xml_request_s *req;
2036 if (!args || !args[0] || !*args[0] || !args[1] || !*args[1])
2037 return GPG_ERR_SYNTAX;
2039 if (!xml_reserved_attribute (args[0]))
2040 n = xml_resolve_path (client, client->doc, (xmlChar *)args[1], NULL, &rc);
2041 else
2043 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
2044 if (rc)
2045 return rc;
2047 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2048 xml_free_request (req);
2051 if (rc)
2052 return rc;
2054 a = xmlGetProp (n, (xmlChar *) args[0]);
2055 if (!a)
2056 return GPG_ERR_NOT_FOUND;
2058 pthread_cleanup_push ((void *)xmlFree, a);
2060 if (*a)
2061 rc = xfer_data (ctx, (char *) a, xmlStrlen (a));
2062 else
2063 rc = GPG_ERR_NO_DATA;
2065 pthread_cleanup_pop (1);
2066 return rc;
2070 * args[0] - attribute
2071 * args[1] - element path
2072 * args[2] - value
2074 static gpg_error_t
2075 attribute_set (struct client_s *client, char **args)
2077 struct xml_request_s *req;
2078 gpg_error_t rc;
2079 xmlNodePtr n;
2081 if (!args || !args[0] || !args[1])
2082 return GPG_ERR_SYNTAX;
2085 * Reserved attribute names.
2087 if (!strcmp (args[0], "_name")) // Use the RENAME command instead
2088 return GPG_ERR_INV_ATTR;
2089 else if (!strcmp (args[0], "target"))
2090 return set_target_attribute (client, args + 1);
2091 else if (!xml_valid_attribute (args[0]))
2092 return GPG_ERR_INV_VALUE;
2094 if (!xml_valid_attribute_value (args[2]))
2095 return GPG_ERR_INV_VALUE;
2097 if (!xml_reserved_attribute (args[0]))
2099 n = xml_resolve_path (client, client->doc, (xmlChar *)args[1], NULL, &rc);
2100 if (!rc)
2102 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
2103 if (!rc)
2105 rc = xml_check_recursion (client, req);
2106 xml_free_request (req);
2110 else
2112 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
2113 if (rc)
2114 return rc;
2116 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2117 xml_free_request (req);
2120 if (!rc)
2121 rc = xml_is_element_owner (client, n);
2123 if (!rc)
2124 rc = xml_add_attribute (client, n, args[0], args[2]);
2126 return rc;
2130 * req[0] - command
2131 * req[1] - attribute name or element path if command is LIST
2132 * req[2] - element path
2133 * req[2] - element path or value
2136 static gpg_error_t
2137 do_attr (assuan_context_t ctx, char *line)
2139 struct client_s *client = assuan_get_pointer (ctx);
2140 gpg_error_t rc = 0;
2141 char **req;
2143 req = str_split (line, " ", 4);
2144 if (!req || !req[0] || !req[1])
2146 strv_free (req);
2147 return GPG_ERR_SYNTAX;
2150 pthread_cleanup_push ((void *)req_free, req);
2152 if (strcasecmp (req[0], "SET") == 0)
2153 rc = attribute_set (client, req + 1);
2154 else if (strcasecmp (req[0], "GET") == 0)
2155 rc = attribute_get (ctx, req + 1);
2156 else if (strcasecmp (req[0], "DELETE") == 0)
2157 rc = attribute_delete (client, req + 1);
2158 else if (strcasecmp (req[0], "LIST") == 0)
2159 rc = attribute_list (ctx, req + 1);
2160 else
2161 rc = GPG_ERR_SYNTAX;
2163 client->flags &= ~(FLAG_ACL_IGNORE|FLAG_ACL_ERROR);
2164 pthread_cleanup_pop (1);
2165 return rc;
2168 static gpg_error_t
2169 attr_command (assuan_context_t ctx, char *line)
2171 struct client_s *client = assuan_get_pointer (ctx);
2172 gpg_error_t rc;
2173 struct argv_s *args[] = {
2174 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2175 NULL
2178 rc = parse_options (&line, args, client, 1);
2179 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2180 rc = GPG_ERR_SYNTAX;
2181 if (rc)
2182 return send_error (ctx, rc);
2184 if (client->opts & OPT_INQUIRE)
2186 unsigned char *result;
2187 size_t len;
2189 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2190 if (rc)
2191 return send_error (ctx, rc);
2193 pthread_cleanup_push ((void *)xfree, result);
2194 rc = do_attr (ctx, (char *)result);
2195 pthread_cleanup_pop (1);
2197 else
2198 rc = do_attr (ctx, line);
2200 return send_error (ctx, rc);
2203 static gpg_error_t
2204 parse_iscached_opt_lock (void *data, void *value)
2206 struct client_s *client = data;
2208 (void) value;
2209 client->opts |= OPT_LOCK;
2210 return 0;
2213 static gpg_error_t
2214 parse_iscached_opt_agent (void *data, void *value)
2216 struct client_s *client = data;
2218 (void) value;
2219 client->opts |= OPT_CACHE_AGENT;
2220 return 0;
2223 static gpg_error_t
2224 parse_iscached_opt_sign (void *data, void *value)
2226 struct client_s *client = data;
2228 (void) value;
2229 client->opts |= OPT_CACHE_SIGN;
2230 return 0;
2233 static gpg_error_t
2234 iscached_command (assuan_context_t ctx, char *line)
2236 struct client_s *client = assuan_get_pointer (ctx);
2237 gpg_error_t rc;
2238 int defer = 0;
2239 struct argv_s *args[] = {
2240 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_iscached_opt_lock},
2241 &(struct argv_s) {"agent", OPTION_TYPE_NOARG, parse_iscached_opt_agent},
2242 &(struct argv_s) {"sign", OPTION_TYPE_NOARG, parse_iscached_opt_sign},
2243 NULL
2246 if (!line || !*line)
2247 return send_error (ctx, GPG_ERR_SYNTAX);
2249 rc = parse_options (&line, args, client, 1);
2250 if (rc)
2251 return send_error (ctx, rc);
2252 else if (!valid_filename (line))
2253 return send_error (ctx, GPG_ERR_INV_VALUE);
2255 if (!(client->flags & FLAG_OPEN)
2256 && ((client->opts & OPT_CACHE_AGENT) || (client->opts & OPT_CACHE_SIGN)))
2257 return send_error (ctx, GPG_ERR_INV_STATE);
2259 rc = cache_iscached (line, &defer, (client->opts & OPT_CACHE_AGENT),
2260 (client->opts & OPT_CACHE_SIGN));
2261 if (!rc && defer)
2262 rc = GPG_ERR_NO_DATA;
2264 if (!rc)
2266 struct cache_data_s *cdata = cache_get_data (line);
2268 if (cdata)
2270 rc = validate_checksum (client, line, cdata, NULL, NULL);
2271 if (rc == GPG_ERR_CHECKSUM)
2272 rc = GPG_ERR_NO_DATA;
2276 if (client->opts & OPT_LOCK
2277 && (!rc || gpg_err_code (rc) == GPG_ERR_NO_DATA))
2279 gpg_error_t trc = rc;
2281 if (strcmp (line, client->filename))
2282 reset_client (client);
2284 xfree (client->filename);
2285 client->filename = str_dup (line);
2286 rc = do_lock (client, 1);
2287 if (!rc)
2288 rc = trc;
2291 return send_error (ctx, rc);
2294 static gpg_error_t
2295 clearcache_command (assuan_context_t ctx, char *line)
2297 struct client_s *client = assuan_get_pointer (ctx);
2298 gpg_error_t rc = 0, all_rc = 0;
2299 int i;
2300 int t;
2301 int all = 0;
2302 struct client_thread_s *once = NULL;
2303 unsigned count;
2305 cache_lock ();
2306 pthread_cleanup_push (cache_release_mutex, NULL);
2307 count = cache_file_count ();
2308 MUTEX_LOCK (&cn_mutex);
2309 pthread_cleanup_push ((void *)release_mutex_cb, &cn_mutex);
2311 if (!line || !*line)
2312 all = 1;
2314 t = slist_length (cn_thread_list);
2316 for (i = 0; i < t; i++)
2318 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2319 assuan_peercred_t peer;
2321 if (!thd->cl)
2322 continue;
2324 /* Lock each connected clients' file mutex to prevent any other client
2325 * from accessing the cache entry (the file mutex is locked upon
2326 * command startup). The cache for the entry is not cleared if the
2327 * file mutex is locked by another client to prevent this function
2328 * from blocking. Rather, it returns an error.
2330 if (all)
2332 if (thd->cl->filename)
2334 rc = do_validate_peer (ctx, thd->cl->filename, &peer);
2335 /* The current client doesn't have permission to open the other
2336 * filename do to "access" configuration parameter in a filename
2337 * section. Since we are clearning all cache entries the error
2338 * will be returned later during cache_clear(). */
2339 if (rc)
2341 rc = 0;
2342 continue;
2345 else // Idle client without opened file?
2346 continue;
2348 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->filename, -1, 0, -1);
2349 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2351 /* The current client owns the lock. */
2352 if (pthread_equal (pthread_self (), thd->tid))
2353 rc = 0;
2354 else
2356 if (cache_iscached (thd->cl->filename, NULL, 0, 0)
2357 == GPG_ERR_NO_DATA)
2359 rc = 0;
2360 continue;
2363 /* The cache entry will be cleared when the other client
2364 * disconnects and cache_timer_thread() does its thing. */
2365 cache_defer_clear (thd->cl->filename);
2368 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
2370 rc = 0;
2371 continue;
2374 if (!rc)
2376 rc = cache_clear (NULL, thd->cl->filename, 1);
2377 cache_unlock_mutex (thd->cl->filename, 0);
2380 if (rc)
2381 all_rc = rc;
2383 rc = 0;
2385 else
2387 /* A single data filename was specified. Lock only this data file
2388 * mutex and free the cache entry. */
2389 rc = do_validate_peer (ctx, line, &peer);
2390 if (rc == GPG_ERR_FORBIDDEN)
2391 rc = peer_is_invoker (client);
2393 if (rc == GPG_ERR_EACCES)
2394 rc = GPG_ERR_FORBIDDEN;
2396 if (!rc && thd->cl->filename && !strcmp (thd->cl->filename , line))
2398 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->filename, -1, 0, -1);
2399 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2401 /* The current client owns the lock. */
2402 if (pthread_equal (pthread_self (), thd->tid))
2403 rc = 0;
2406 if (!rc)
2408 once = thd;
2409 rc = cache_clear (NULL, thd->cl->filename, 1);
2410 cache_unlock_mutex (thd->cl->filename, 0);
2412 else
2413 cache_defer_clear (thd->cl->filename);
2415 /* Found a client with the opened file. The cache entry has been
2416 * either cleared (self) or defered to be cleared. */
2417 break;
2422 /* Only connected clients' cache entries have been cleared. Now clear any
2423 * remaining cache entries without clients but only if there wasn't an
2424 * error from above since this would defeat the locking check of the
2425 * remaining entries. */
2426 if (all && !all_rc && cache_file_count ())
2428 rc = cache_clear (client, NULL, 1);
2429 if (rc == GPG_ERR_EACCES)
2430 rc = GPG_ERR_FORBIDDEN;
2433 /* No clients are using the specified file. */
2434 else if (!all_rc && !rc && !once)
2435 rc = cache_clear (NULL, line, 1);
2437 /* Release the connection mutex. */
2438 pthread_cleanup_pop (1);
2440 if (!rc || (cache_file_count () && count != cache_file_count ()))
2441 send_status_all (STATUS_CACHE, NULL);
2443 /* Release the cache mutex. */
2444 pthread_cleanup_pop (1);
2446 /* One or more files were locked while clearing all cache entries. */
2447 if (all_rc)
2448 rc = all_rc;
2450 return send_error (ctx, rc);
2453 static gpg_error_t
2454 cachetimeout_command (assuan_context_t ctx, char *line)
2456 struct client_s *client = assuan_get_pointer (ctx);
2457 int timeout;
2458 char **req = str_split (line, " ", 0);
2459 char *p;
2460 gpg_error_t rc = 0;
2461 assuan_peercred_t peer;
2463 if (!req || !*req || !req[1])
2465 strv_free (req);
2466 return send_error (ctx, GPG_ERR_SYNTAX);
2469 errno = 0;
2470 timeout = (int) strtol (req[1], &p, 10);
2471 if (errno != 0 || *p || timeout < -1)
2473 strv_free (req);
2474 return send_error (ctx, GPG_ERR_SYNTAX);
2477 rc = do_validate_peer (ctx, req[0], &peer);
2478 if (rc == GPG_ERR_FORBIDDEN)
2480 rc = peer_is_invoker (client);
2481 if (rc == GPG_ERR_EACCES)
2482 rc = GPG_ERR_FORBIDDEN;
2485 if (!rc)
2487 rc = cache_set_timeout (req[0], timeout);
2488 if (!rc || gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
2490 rc = 0;
2491 MUTEX_LOCK (&rcfile_mutex);
2492 config_set_int_param (&global_config, req[0], "cache_timeout",
2493 req[1]);
2494 MUTEX_UNLOCK (&rcfile_mutex);
2498 strv_free (req);
2499 return send_error (ctx, rc);
2502 static gpg_error_t
2503 dump_command (assuan_context_t ctx, char *line)
2505 xmlChar *xml;
2506 int len;
2507 struct client_s *client = assuan_get_pointer (ctx);
2508 gpg_error_t rc;
2510 if (disable_list_and_dump == 1)
2511 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2513 if (line && *line)
2514 return send_error (ctx, GPG_ERR_SYNTAX);
2516 rc = peer_is_invoker(client);
2517 if (rc)
2518 return send_error (ctx, rc);
2520 xmlDocDumpFormatMemory (client->doc, &xml, &len, 1);
2522 if (!xml)
2524 log_write ("%s(%i): %s", __FILE__, __LINE__,
2525 pwmd_strerror (GPG_ERR_ENOMEM));
2526 return send_error (ctx, GPG_ERR_ENOMEM);
2529 pthread_cleanup_push ((void *)xmlFree, xml);
2530 rc = xfer_data (ctx, (char *) xml, len);
2531 pthread_cleanup_pop (1);
2532 return send_error (ctx, rc);
2535 static gpg_error_t
2536 getconfig_command (assuan_context_t ctx, char *line)
2538 struct client_s *client = assuan_get_pointer (ctx);
2539 gpg_error_t rc = 0;
2540 char filename[255] = { 0 }, param[747] = { 0 };
2541 char *p, *tmp = NULL, *fp = client->filename, *paramp = line;
2543 if (!line || !*line)
2544 return send_error (ctx, GPG_ERR_SYNTAX);
2546 if (strchr (line, ' '))
2548 int ret = sscanf (line, " %254[^ ] %746c", filename, param);
2550 if (ret <= 0)
2551 return send_error (ctx, gpg_error_from_syserror());
2552 paramp = param;
2553 fp = filename;
2556 if (fp && !valid_filename (fp))
2557 return send_error (ctx, GPG_ERR_INV_VALUE);
2559 paramp = str_down (paramp);
2560 p = config_get_value (fp ? fp : "global", paramp);
2561 if (!p)
2562 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2564 tmp = expand_homedir (p);
2565 xfree (p);
2566 if (!tmp)
2568 log_write ("%s(%i): %s", __FILE__, __LINE__,
2569 pwmd_strerror (GPG_ERR_ENOMEM));
2570 return send_error (ctx, GPG_ERR_ENOMEM);
2573 p = tmp;
2574 pthread_cleanup_push ((void *)xfree, p);
2575 rc = xfer_data (ctx, p, strlen (p));
2576 pthread_cleanup_pop (1);
2577 return send_error (ctx, rc);
2580 struct xpath_s
2582 xmlXPathContextPtr xp;
2583 xmlXPathObjectPtr result;
2584 xmlBufferPtr buf;
2585 char **req;
2588 static void
2589 xpath_command_free (void *arg)
2591 struct xpath_s *xpath = arg;
2593 if (!xpath)
2594 return;
2596 req_free (xpath->req);
2598 if (xpath->buf)
2599 xmlBufferFree (xpath->buf);
2601 if (xpath->result)
2602 xmlXPathFreeObject (xpath->result);
2604 if (xpath->xp)
2605 xmlXPathFreeContext (xpath->xp);
2608 static gpg_error_t
2609 do_xpath (assuan_context_t ctx, char *line)
2611 gpg_error_t rc;
2612 struct client_s *client = assuan_get_pointer (ctx);
2613 struct xpath_s _x = { 0 };
2614 struct xpath_s *xpath = &_x;
2616 if (!line || !*line)
2617 return GPG_ERR_SYNTAX;
2619 if ((xpath->req = str_split (line, "\t", 2)) == NULL)
2621 if (strv_printf (&xpath->req, "%s", line) == 0)
2622 return GPG_ERR_ENOMEM;
2625 xpath->xp = xmlXPathNewContext (client->doc);
2626 if (!xpath->xp)
2628 rc = GPG_ERR_BAD_DATA;
2629 goto fail;
2632 xpath->result =
2633 xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2634 if (!xpath->result)
2636 rc = GPG_ERR_BAD_DATA;
2637 goto fail;
2640 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2642 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2643 goto fail;
2646 rc = xml_recurse_xpath_nodeset (client, client->doc,
2647 xpath->result->nodesetval,
2648 (xmlChar *) xpath->req[1], &xpath->buf, 0,
2649 NULL);
2650 if (rc)
2651 goto fail;
2652 else if (!xpath->req[1] && !xmlBufferLength (xpath->buf))
2654 rc = GPG_ERR_NO_DATA;
2655 goto fail;
2657 else if (xpath->req[1])
2659 rc = 0;
2660 goto fail;
2663 pthread_cleanup_push ((void *)xpath_command_free, &xpath);
2664 rc = xfer_data (ctx, (char *) xmlBufferContent (xpath->buf),
2665 xmlBufferLength (xpath->buf));
2666 pthread_cleanup_pop (0);
2667 fail:
2668 xpath_command_free (xpath);
2669 return rc;
2672 static gpg_error_t
2673 xpath_command (assuan_context_t ctx, char *line)
2675 struct client_s *client = assuan_get_pointer (ctx);
2676 gpg_error_t rc;
2677 struct argv_s *args[] = {
2678 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2679 NULL
2682 if (disable_list_and_dump == 1)
2683 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2685 rc = peer_is_invoker(client);
2686 if (rc)
2687 return send_error (ctx, rc);
2689 rc = parse_options (&line, args, client, 1);
2690 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2691 rc = GPG_ERR_SYNTAX;
2692 if (rc)
2693 return send_error (ctx, rc);
2695 if (client->opts & OPT_INQUIRE)
2697 unsigned char *result;
2698 size_t len;
2700 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2701 if (rc)
2702 return send_error (ctx, rc);
2704 pthread_cleanup_push ((void *)xfree, result);
2705 rc = do_xpath (ctx, (char *)result);
2706 pthread_cleanup_pop (1);
2708 else
2709 rc = do_xpath (ctx, line);
2711 return send_error (ctx, rc);
2714 static gpg_error_t
2715 do_xpathattr (assuan_context_t ctx, char *line)
2717 struct client_s *client = assuan_get_pointer (ctx);
2718 gpg_error_t rc;
2719 char **req = NULL;
2720 int cmd = 0; //SET
2721 struct xpath_s _x = { 0 };
2722 struct xpath_s *xpath = &_x;
2724 if (!line || !*line)
2725 return GPG_ERR_SYNTAX;
2727 if ((req = str_split (line, " ", 3)) == NULL)
2728 return GPG_ERR_ENOMEM;
2730 if (!req[0])
2732 rc = GPG_ERR_SYNTAX;
2733 goto fail;
2736 if (!strcasecmp (req[0], "SET"))
2737 cmd = 0;
2738 else if (!strcasecmp (req[0], "DELETE"))
2739 cmd = 1;
2740 else
2742 rc = GPG_ERR_SYNTAX;
2743 goto fail;
2746 if (!req[1] || !req[2])
2748 rc = GPG_ERR_SYNTAX;
2749 goto fail;
2752 if ((xpath->req = str_split (req[2], "\t", 3)) == NULL)
2754 rc = GPG_ERR_ENOMEM;
2755 goto fail;
2758 if (!xpath->req[0] || (!xpath->req[1] && !cmd) || (xpath->req[1] && cmd))
2760 rc = GPG_ERR_SYNTAX;
2761 goto fail;
2764 xpath->xp = xmlXPathNewContext (client->doc);
2765 if (!xpath->xp)
2767 rc = GPG_ERR_BAD_DATA;
2768 goto fail;
2771 xpath->result = xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2772 if (!xpath->result)
2774 rc = GPG_ERR_BAD_DATA;
2775 goto fail;
2778 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2780 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2781 goto fail;
2784 rc = xml_recurse_xpath_nodeset (client, client->doc,
2785 xpath->result->nodesetval,
2786 (xmlChar *) xpath->req[1], &xpath->buf, cmd,
2787 (xmlChar *) req[1]);
2789 fail:
2790 xpath_command_free (xpath);
2791 strv_free (req);
2792 return rc;
2795 /* XPATHATTR SET|DELETE <name> <expression>[<TAB>[value]] */
2796 static gpg_error_t
2797 xpathattr_command (assuan_context_t ctx, char *line)
2799 struct client_s *client = assuan_get_pointer (ctx);
2800 gpg_error_t rc;
2801 struct argv_s *args[] = {
2802 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2803 NULL
2806 if (disable_list_and_dump == 1)
2807 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2809 rc = peer_is_invoker(client);
2810 if (rc)
2811 return send_error (ctx, rc);
2813 rc = parse_options (&line, args, client, 1);
2814 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2815 rc = GPG_ERR_SYNTAX;
2816 if (rc)
2817 return send_error (ctx, rc);
2819 if (client->opts & OPT_INQUIRE)
2821 unsigned char *result;
2822 size_t len;
2824 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2825 if (rc)
2826 return send_error (ctx, rc);
2828 pthread_cleanup_push ((void *)xfree, result);
2829 rc = do_xpathattr (ctx, (char *)result);
2830 pthread_cleanup_pop (1);
2832 else
2833 rc = do_xpathattr (ctx, line);
2835 return send_error (ctx, rc);
2838 static gpg_error_t
2839 do_import (struct client_s *client, const char *root_element,
2840 unsigned char *content)
2842 xmlDocPtr doc = NULL;
2843 xmlNodePtr n = NULL, root;
2844 gpg_error_t rc;
2845 struct string_s *str = NULL, *tstr = NULL;
2846 struct xml_request_s *req = NULL;
2848 if (!content || !*content)
2849 return GPG_ERR_SYNTAX;
2851 if (root_element)
2853 rc = xml_new_request (client, root_element, XML_CMD_STORE, &req);
2854 if (rc)
2856 xfree (content);
2857 return rc;
2860 if (!xml_valid_element_path (req->args, 0))
2862 xml_free_request (req);
2863 xfree (content);
2864 return GPG_ERR_INV_VALUE;
2868 str = string_new_content ((char *)content);
2869 tstr = string_prepend (str, "<pwmd>");
2870 if (tstr)
2872 str = tstr;
2873 tstr = string_append (str, "</pwmd>");
2874 if (!tstr)
2875 rc = GPG_ERR_ENOMEM;
2877 else
2878 rc = GPG_ERR_ENOMEM;
2880 if (rc)
2881 goto fail;
2883 doc = xmlReadDoc ((xmlChar *) str->str, NULL, "UTF-8", XML_PARSE_NOBLANKS);
2884 string_free (str, 1);
2885 if (!doc)
2887 rc = GPG_ERR_BAD_DATA;
2888 goto fail;
2891 root = xmlDocGetRootElement (doc);
2892 root = root->children;
2893 if (root->type != XML_ELEMENT_NODE)
2895 rc = GPG_ERR_BAD_DATA;
2896 goto fail;
2899 rc = xml_validate_import (client, root);
2900 if (rc)
2901 goto fail;
2903 if (req)
2905 /* Create the new specified root element path, if needed. */
2906 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc),
2907 &rc);
2908 if (rc)
2909 goto fail;
2911 /* Overwrite the children of the specified root element path. */
2912 (void)xml_unlink_node (client, n->children);
2913 n->children = NULL;
2915 else
2916 n = xmlDocGetRootElement (client->doc);
2918 if (n)
2920 xmlNodePtr copy;
2921 xmlChar *name = xml_attribute_value (root, (xmlChar *)"_name");
2923 if (!name)
2924 rc = GPG_ERR_BAD_DATA;
2925 else if (!req)
2927 /* No --root argument passed. Overwrite the current documents' root
2928 * element matching the root element of the imported data. */
2929 xml_free_request (req);
2930 req = NULL;
2931 rc = xml_new_request (client, (char *)name, XML_CMD_DELETE, &req);
2932 xmlFree (name);
2933 if (!rc)
2935 xmlNodePtr tmp;
2937 tmp = xml_find_elements (client, req,
2938 xmlDocGetRootElement (req->doc), &rc);
2939 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2940 goto fail;
2942 if (!rc)
2943 (void)xml_unlink_node (client, tmp);
2945 rc = 0;
2949 if (!rc)
2951 copy = xmlCopyNodeList (root);
2952 if (!copy)
2953 rc = GPG_ERR_ENOMEM;
2954 else
2956 n = xmlAddChildList (n, copy);
2957 if (!n)
2958 rc = GPG_ERR_ENOMEM;
2963 if (!rc && n && n->parent)
2964 rc = xml_update_element_mtime (client, n->parent);
2966 fail:
2967 xml_free_request (req);
2969 if (doc)
2970 xmlFreeDoc (doc);
2972 return rc;
2975 static gpg_error_t
2976 parse_import_opt_root (void *data, void *value)
2978 struct client_s *client = data;
2980 client->import_root = str_dup (value);
2981 return client->import_root ? 0 : GPG_ERR_ENOMEM;
2984 static gpg_error_t
2985 import_command (assuan_context_t ctx, char *line)
2987 gpg_error_t rc;
2988 struct client_s *client = assuan_get_pointer (ctx);
2989 unsigned char *result;
2990 size_t len;
2991 struct argv_s *args[] = {
2992 &(struct argv_s) {"root", OPTION_TYPE_ARG, parse_import_opt_root},
2993 NULL
2996 xfree (client->import_root);
2997 client->import_root = NULL;
2998 rc = parse_options (&line, args, client, 0);
2999 if (rc)
3000 return send_error (ctx, rc);
3002 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3003 if (rc)
3005 xfree (client->import_root);
3006 client->import_root = NULL;
3007 return send_error (ctx, rc);
3010 rc = do_import (client, client->import_root, result);
3011 xfree (client->import_root);
3012 client->import_root = NULL;
3013 return send_error (ctx, rc);
3016 static gpg_error_t
3017 do_lock (struct client_s *client, int add)
3019 gpg_error_t rc = lock_file_mutex (client, add);
3021 if (!rc)
3022 client->flags |= FLAG_LOCK_CMD;
3024 return rc;
3027 static gpg_error_t
3028 lock_command (assuan_context_t ctx, char *line)
3030 struct client_s *client = assuan_get_pointer (ctx);
3031 gpg_error_t rc;
3033 if (line && *line)
3034 return send_error (ctx, GPG_ERR_SYNTAX);
3036 rc = do_lock (client, 0);
3037 return send_error (ctx, rc);
3040 static gpg_error_t
3041 unlock_command (assuan_context_t ctx, char *line)
3043 struct client_s *client = assuan_get_pointer (ctx);
3044 gpg_error_t rc;
3046 if (line && *line)
3047 return send_error (ctx, GPG_ERR_SYNTAX);
3049 rc = unlock_file_mutex (client, 0);
3050 return send_error (ctx, rc);
3053 static void
3054 get_set_env (const char *name, const char *value)
3056 if (value && *value)
3057 setenv (name, value, 1);
3058 else
3059 unsetenv (name);
3062 static gpg_error_t
3063 option_command (assuan_context_t ctx, char *line)
3065 struct client_s *client = assuan_get_pointer (ctx);
3066 gpg_error_t rc = 0;
3067 char namebuf[255] = { 0 };
3068 char *name = namebuf;
3069 char *value = NULL, *p, *tmp = NULL;
3071 p = strchr (line, '=');
3072 if (!p)
3074 strncpy (namebuf, line, sizeof(namebuf));
3075 namebuf[sizeof(namebuf)-1] = 0;
3077 else
3079 strncpy (namebuf, line, strlen (line)-strlen (p));
3080 namebuf[sizeof(namebuf)-1] = 0;
3081 value = p+1;
3084 log_write2 ("OPTION name='%s' value='%s'", name, value);
3086 if (strcasecmp (name, (char *) "lock-timeout") == 0)
3088 long n = 0;
3090 if (value)
3092 n = strtol (value, &tmp, 10);
3093 if (tmp && *tmp)
3094 return send_error (ctx, GPG_ERR_INV_VALUE);
3097 client->lock_timeout = n;
3099 else if (strcasecmp (name, (char *) "client-state") == 0)
3101 long n = 0;
3103 if (value)
3105 n = strtol (value, &tmp, 10);
3106 if ((tmp && *tmp) || (n < 0 || n > 1))
3107 return send_error (ctx, GPG_ERR_INV_VALUE);
3108 client->client_state = n;
3110 else
3111 client->client_state = 0;
3113 else if (strcasecmp (name, (char *) "NAME") == 0)
3115 if (value && strchr (value, ' '))
3116 rc = GPG_ERR_INV_VALUE;
3117 else
3119 tmp = pthread_getspecific (thread_name_key);
3120 pthread_setspecific (thread_name_key, NULL);
3121 xfree (tmp);
3122 MUTEX_LOCK (&cn_mutex);
3124 if (value && *value)
3125 pthread_setspecific (thread_name_key, str_dup (value));
3127 MUTEX_UNLOCK (&cn_mutex);
3130 else if (strcasecmp (name, "disable-pinentry") == 0)
3132 int n = 1;
3134 if (value && *value)
3136 n = (int) strtol (value, &tmp, 10);
3137 if (*tmp || n < 0 || n > 1)
3138 return send_error (ctx, GPG_ERR_INV_VALUE);
3141 if (n)
3142 client->flags |= FLAG_NO_PINENTRY;
3143 else
3144 client->flags &= ~FLAG_NO_PINENTRY;
3146 else if (strcasecmp (name, "ttyname") == 0)
3148 get_set_env ("GPG_TTY", value);
3150 else if (strcasecmp (name, "ttytype") == 0)
3152 get_set_env ("TERM", value);
3154 else if (strcasecmp (name, "display") == 0)
3156 get_set_env ("DISPLAY", value);
3158 else if (strcasecmp (name, "lc_messages") == 0)
3161 else if (strcasecmp (name, "lc_ctype") == 0)
3164 else if (strcasecmp (name, "desc") == 0)
3167 else if (strcasecmp (name, "pinentry-timeout") == 0)
3170 else
3171 rc = GPG_ERR_UNKNOWN_OPTION;
3173 return send_error (ctx, rc);
3176 static gpg_error_t
3177 do_rename (assuan_context_t ctx, char *line)
3179 struct client_s *client = assuan_get_pointer (ctx);
3180 char **args, *p;
3181 xmlNodePtr src, dst;
3182 struct string_s *str = NULL, *tstr;
3183 struct xml_request_s *req;
3184 gpg_error_t rc;
3186 args = str_split (line, " ", 0);
3187 if (!args || strv_length (args) != 2)
3189 strv_free (args);
3190 return GPG_ERR_SYNTAX;
3193 if (!xml_valid_element ((xmlChar *) args[1]))
3195 strv_free (args);
3196 return GPG_ERR_INV_VALUE;
3199 rc = xml_new_request (client, args[0], XML_CMD_RENAME, &req);
3200 if (rc)
3202 strv_free (args);
3203 return rc;
3206 src = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3207 if (rc)
3208 goto fail;
3210 rc = xml_is_element_owner (client, src);
3211 if (rc)
3212 goto fail;
3214 xmlChar *a = xmlGetProp (src, (xmlChar *) "_name");
3215 if (!a)
3217 rc = GPG_ERR_ENOMEM;
3218 goto fail;
3221 /* To prevent unwanted effects:
3223 * <element _name="a"><element _name="b"/></element>
3225 * RENAME a<TAB>b b
3227 if (xmlStrEqual (a, (xmlChar *) args[1]))
3229 xmlFree (a);
3230 rc = GPG_ERR_EEXIST;
3231 goto fail;
3234 xmlFree (a);
3235 str = string_new (args[0]);
3236 if (!str)
3238 rc = GPG_ERR_ENOMEM;
3239 goto fail;
3242 p = strrchr (str->str, '\t');
3243 if (p)
3244 tstr = string_truncate (str, strlen (str->str)-strlen (p));
3245 else
3246 tstr = string_truncate (str, 0);
3248 if (!tstr)
3250 string_free (str, 1);
3251 rc = GPG_ERR_ENOMEM;
3252 goto fail;
3255 str = tstr;
3256 tstr = string_append_printf (str, "%s%s", str->len ? "\t" : "", args[1]);
3257 if (!tstr)
3259 string_free (str, 1);
3260 rc = GPG_ERR_ENOMEM;
3261 goto fail;
3264 str = tstr;
3265 xml_free_request (req);
3266 rc = xml_new_request (client, str->str, XML_CMD_RENAME, &req);
3267 string_free (str, 1);
3268 if (rc)
3270 req = NULL;
3271 goto fail;
3274 dst = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3275 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3276 goto fail;
3278 rc = 0;
3280 /* Target may exist:
3282 * <element _name="a"/>
3283 * <element _name="b" target="a"/>
3285 * RENAME b a
3287 if (src == dst)
3289 rc = GPG_ERR_EEXIST;
3290 goto fail;
3293 if (dst)
3295 rc = xml_is_element_owner (client, dst);
3296 if (rc)
3297 goto fail;
3299 rc = xml_add_attribute (client, src, "_name", args[1]);
3300 if (!rc)
3301 xml_unlink_node (client, dst);
3303 else
3304 rc = xml_add_attribute (client, src, "_name", args[1]);
3306 fail:
3307 xml_free_request (req);
3308 strv_free (args);
3309 return rc;
3312 static gpg_error_t
3313 rename_command (assuan_context_t ctx, char *line)
3315 struct client_s *client = assuan_get_pointer (ctx);
3316 gpg_error_t rc;
3317 struct argv_s *args[] = {
3318 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3319 NULL
3322 rc = parse_options (&line, args, client, 1);
3323 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3324 rc = GPG_ERR_SYNTAX;
3325 if (rc)
3326 return send_error (ctx, rc);
3328 if (client->opts & OPT_INQUIRE)
3330 unsigned char *result;
3331 size_t len;
3333 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3334 if (rc)
3335 return send_error (ctx, rc);
3337 pthread_cleanup_push ((void *)xfree, result);
3338 rc = do_rename (ctx, (char *)result);
3339 pthread_cleanup_pop (1);
3341 else
3342 rc = do_rename (ctx, line);
3344 return send_error (ctx, rc);
3347 static gpg_error_t
3348 do_copy (assuan_context_t ctx, char *line)
3350 struct client_s *client = assuan_get_pointer (ctx);
3351 char **args, **targs;
3352 xmlNodePtr src, dst, tree = NULL;
3353 struct xml_request_s *req;
3354 gpg_error_t rc;
3356 args = str_split (line, " ", 0);
3357 if (!args || strv_length (args) != 2)
3359 strv_free (args);
3360 return GPG_ERR_SYNTAX;
3363 targs = str_split (args[1], "\t", 0);
3364 if (!targs)
3366 strv_free (args);
3367 return GPG_ERR_SYNTAX;
3370 if (!xml_valid_element_path (targs, 0))
3372 strv_free (args);
3373 strv_free (targs);
3374 return GPG_ERR_INV_VALUE;
3376 strv_free (targs);
3378 rc = xml_new_request (client, args[0], XML_CMD_NONE, &req);
3379 if (rc)
3381 strv_free (args);
3382 return rc;
3385 src = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3386 if (rc)
3387 goto fail;
3389 tree = xmlCopyNodeList (src);
3390 if (!tree)
3392 rc = GPG_ERR_ENOMEM;
3393 goto fail;
3396 xml_free_request (req);
3397 /* Create the destination element path if it does not exist. */
3398 rc = xml_new_request (client, args[1], XML_CMD_STORE, &req);
3399 if (rc)
3401 req = NULL;
3402 goto fail;
3405 dst = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3406 if (rc)
3407 goto fail;
3409 rc = xml_is_element_owner (client, dst);
3410 if (rc)
3411 goto fail;
3413 rc = xml_validate_target (client, req->doc, args[1], src);
3414 if (rc || src == dst)
3416 rc = rc ? rc : GPG_ERR_EEXIST;
3417 goto fail;
3420 /* Merge any attributes from the src node to the initial dst node. */
3421 for (xmlAttrPtr attr = tree->properties; attr; attr = attr->next)
3423 if (xmlStrEqual (attr->name, (xmlChar *) "_name"))
3424 continue;
3426 xmlAttrPtr a = xmlHasProp (dst, attr->name);
3427 if (a)
3428 xmlRemoveProp (a);
3430 xmlChar *tmp = xmlNodeGetContent (attr->children);
3431 xmlNewProp (dst, attr->name, tmp);
3432 xmlFree (tmp);
3433 /* Create the default attributes. */
3434 rc = xml_add_attribute (client, dst, NULL, NULL);
3437 xmlNodePtr n = dst->children;
3438 (void)xml_unlink_node (client, n);
3439 dst->children = NULL;
3441 if (tree->children)
3443 n = xmlCopyNodeList (tree->children);
3444 if (!n)
3446 rc = GPG_ERR_ENOMEM;
3447 goto fail;
3450 n = xmlAddChildList (dst, n);
3451 if (!n)
3453 rc = GPG_ERR_ENOMEM;
3454 goto fail;
3457 rc = xml_update_element_mtime (client, xmlDocGetRootElement (client->doc)
3458 == dst->parent ? dst : dst->parent);
3461 fail:
3462 if (tree)
3463 (void)xml_unlink_node (client, tree);
3465 xml_free_request (req);
3466 strv_free (args);
3467 return rc;
3470 static gpg_error_t
3471 copy_command (assuan_context_t ctx, char *line)
3473 struct client_s *client = assuan_get_pointer (ctx);
3474 gpg_error_t rc;
3475 struct argv_s *args[] = {
3476 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3477 NULL
3480 rc = parse_options (&line, args, client, 1);
3481 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3482 rc = GPG_ERR_SYNTAX;
3483 if (rc)
3484 return send_error (ctx, rc);
3486 if (client->opts & OPT_INQUIRE)
3488 unsigned char *result;
3489 size_t len;
3491 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3492 if (rc)
3493 return send_error (ctx, rc);
3495 pthread_cleanup_push ((void *)xfree, result);
3496 rc = do_copy (ctx, (char *)result);
3497 pthread_cleanup_pop (1);
3499 else
3500 rc = do_copy (ctx, line);
3502 return send_error (ctx, rc);
3505 static gpg_error_t
3506 do_move (assuan_context_t ctx, char *line)
3508 struct client_s *client = assuan_get_pointer (ctx);
3509 char **args;
3510 xmlNodePtr src, dst;
3511 struct xml_request_s *req;
3512 gpg_error_t rc;
3514 args = str_split (line, " ", 0);
3515 if (!args || strv_length (args) != 2)
3517 strv_free (args);
3518 return GPG_ERR_SYNTAX;
3521 if (*args[1])
3523 char **targs = str_split (args[1], "\t", 0);
3524 if (!targs)
3526 strv_free (args);
3527 return GPG_ERR_ENOMEM;
3530 if (!xml_valid_element_path (targs, 0))
3532 strv_free (targs);
3533 strv_free (args);
3534 return GPG_ERR_INV_VALUE;
3537 strv_free (targs);
3540 rc = xml_new_request (client, args[0], XML_CMD_MOVE, &req);
3541 if (rc)
3543 strv_free (args);
3544 return rc;
3547 src = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3548 if (rc)
3549 goto fail;
3551 rc = xml_is_element_owner (client, src);
3552 if (rc)
3553 goto fail;
3555 xml_free_request (req);
3556 req = NULL;
3557 if (*args[1])
3559 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
3560 if (rc)
3561 goto fail;
3563 dst = xml_find_elements (client, req, xmlDocGetRootElement (req->doc),
3564 &rc);
3566 else
3567 dst = xmlDocGetRootElement (client->doc);
3569 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3570 goto fail;
3572 rc = 0;
3574 for (xmlNodePtr n = dst; n; n = n->parent)
3576 if (n == src)
3578 rc = GPG_ERR_EEXIST;
3579 goto fail;
3583 if (dst)
3585 xmlChar *a = xml_attribute_value (src, (xmlChar *) "_name");
3586 xmlNodePtr dup = xml_find_element (client, dst->children, (char *) a, &rc);
3588 xmlFree (a);
3589 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3590 goto fail;
3592 rc = 0;
3594 if (dup)
3596 if (dup == src)
3598 rc = GPG_ERR_EEXIST;
3599 goto fail;
3602 if (dst == xmlDocGetRootElement (client->doc))
3604 xmlNodePtr n = src;
3605 int match = 0;
3607 while (n->parent && n->parent != dst)
3608 n = n->parent;
3610 a = xml_attribute_value (n, (xmlChar *) "_name");
3611 xmlChar *b = xml_attribute_value (src, (xmlChar *) "_name");
3613 if (xmlStrEqual (a, b))
3615 match = 1;
3616 xmlUnlinkNode (src);
3617 (void)xml_unlink_node (client, n);
3620 xmlFree (a);
3621 xmlFree (b);
3623 if (!match)
3624 (void)xml_unlink_node (client, dup);
3626 else
3627 xmlUnlinkNode (dup);
3631 if (!dst && *req->args)
3633 struct xml_request_s *nreq = NULL;
3634 xmlChar *name = xml_attribute_value (src, (xmlChar *) "_name");
3636 if (src->parent == xmlDocGetRootElement (client->doc)
3637 && !strcmp ((char *) name, *req->args))
3639 xmlFree (name);
3640 rc = GPG_ERR_EEXIST;
3641 goto fail;
3644 xmlFree (name);
3645 rc = xml_new_request (client, args[1], XML_CMD_STORE, &nreq);
3646 if (!rc)
3648 dst = xml_find_elements (client, nreq,
3649 xmlDocGetRootElement (nreq->doc), &rc);
3650 xml_free_request (nreq);
3653 if (rc)
3654 goto fail;
3657 xml_update_element_mtime (client, src->parent);
3658 xmlUnlinkNode (src);
3660 dst = xmlAddChildList (dst, src);
3661 if (!dst)
3662 rc = GPG_ERR_ENOMEM;
3663 else
3664 xml_update_element_mtime (client, dst->parent);
3666 fail:
3667 xml_free_request (req);
3668 strv_free (args);
3669 return rc;
3672 static gpg_error_t
3673 move_command (assuan_context_t ctx, char *line)
3675 struct client_s *client = assuan_get_pointer (ctx);
3676 gpg_error_t rc;
3677 struct argv_s *args[] = {
3678 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3679 NULL
3682 rc = parse_options (&line, args, client, 1);
3683 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3684 rc = GPG_ERR_SYNTAX;
3685 if (rc)
3686 return send_error (ctx, rc);
3688 if (client->opts & OPT_INQUIRE)
3690 unsigned char *result;
3691 size_t len;
3693 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3694 if (rc)
3695 return send_error (ctx, rc);
3697 pthread_cleanup_push ((void *)xfree, result);
3698 rc = do_move (ctx, (char *)result);
3699 pthread_cleanup_pop (1);
3701 else
3702 rc = do_move (ctx, line);
3704 return send_error (ctx, rc);
3707 static gpg_error_t
3708 ls_command (assuan_context_t ctx, char *line)
3710 gpg_error_t rc;
3711 char *tmp;
3712 char *dir;
3713 DIR *d;
3715 if (line && *line)
3716 return send_error (ctx, GPG_ERR_SYNTAX);
3718 tmp = str_asprintf ("%s/data", homedir);
3719 dir = expand_homedir (tmp);
3720 xfree (tmp);
3721 d = opendir (dir);
3722 rc = gpg_error_from_errno (errno);
3724 if (!d)
3726 xfree (dir);
3727 return send_error (ctx, rc);
3730 size_t len =
3731 offsetof (struct dirent, d_name) +pathconf (dir, _PC_NAME_MAX) + 1;
3732 struct dirent *p = xmalloc (len), *cur = NULL;
3733 char *list = NULL;
3735 xfree (dir);
3736 pthread_cleanup_push ((void *)xfree, p);
3737 pthread_cleanup_push ((void *)(void *)(void *)closedir, d);
3738 rc = 0;
3740 while (!readdir_r (d, p, &cur) && cur)
3742 rc = open_check_file (cur->d_name, NULL, NULL, 1);
3743 if (rc)
3744 continue;
3746 tmp = str_asprintf ("%s%s\n", list ? list : "", cur->d_name);
3748 if (!tmp)
3750 if (list)
3751 xfree (list);
3753 rc = GPG_ERR_ENOMEM;
3754 break;
3757 xfree (list);
3758 list = tmp;
3761 pthread_cleanup_pop (1); // closedir (d)
3762 pthread_cleanup_pop (1); // xfree (p)
3764 if (rc)
3765 return send_error (ctx, rc);
3767 if (!list)
3768 return send_error (ctx, GPG_ERR_NO_DATA);
3770 list[strlen (list) - 1] = 0;
3771 pthread_cleanup_push ((void *)xfree, list);
3772 rc = xfer_data (ctx, list, strlen (list));
3773 pthread_cleanup_pop (1);
3774 return send_error (ctx, rc);
3777 static gpg_error_t
3778 bye_notify (assuan_context_t ctx, char *line)
3780 struct client_s *cl = assuan_get_pointer (ctx);
3781 gpg_error_t ret = 0;
3783 (void)line;
3784 update_client_state (cl, CLIENT_STATE_DISCON);
3786 #ifdef WITH_GNUTLS
3787 cl->disco = 1;
3788 if (cl->thd->remote)
3790 int rc;
3794 struct timeval tv = { 0, 50000 };
3796 rc = gnutls_bye (cl->thd->tls->ses, GNUTLS_SHUT_RDWR);
3797 if (rc == GNUTLS_E_AGAIN)
3798 select (0, NULL, NULL, NULL, &tv);
3800 while (rc == GNUTLS_E_AGAIN);
3802 #endif
3804 /* This will let assuan_process_next() return. */
3805 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
3807 cl->last_rc = gpg_error_from_errno (errno);
3808 ret = cl->last_rc;
3811 cl->last_rc = 0; // BYE command result
3812 return ret;
3815 static gpg_error_t
3816 reset_notify (assuan_context_t ctx, char *line)
3818 struct client_s *client = assuan_get_pointer (ctx);
3820 (void)line;
3821 if (client)
3822 reset_client (client);
3824 return 0;
3828 * This is called before every Assuan command.
3830 static gpg_error_t
3831 command_startup (assuan_context_t ctx, const char *name)
3833 struct client_s *client = assuan_get_pointer (ctx);
3834 gpg_error_t rc;
3835 struct command_table_s *cmd = NULL;
3837 log_write2 ("command='%s'", name);
3838 client->last_rc = client->opts = 0;
3840 for (int i = 0; command_table[i]; i++)
3842 if (!strcasecmp (name, command_table[i]->name))
3844 if (command_table[i]->ignore_startup)
3845 return 0;
3846 cmd = command_table[i];
3847 break;
3851 if (!cmd)
3852 return GPG_ERR_UNKNOWN_COMMAND;
3854 client->last_rc = rc = gpg_error (file_modified (client, cmd));
3855 if (!rc)
3856 update_client_state (client, CLIENT_STATE_COMMAND);
3858 return rc;
3862 * This is called after every Assuan command.
3864 static void
3865 command_finalize (assuan_context_t ctx, gpg_error_t rc)
3867 struct client_s *client = assuan_get_pointer (ctx);
3869 if (!(client->flags & FLAG_LOCK_CMD))
3870 unlock_file_mutex (client, 0);
3872 unlock_flock (&client->flock_fd);
3873 log_write2 (_("command completed: rc=%u"), rc ? rc : client->last_rc);
3874 client->last_rc = gpg_error (GPG_ERR_UNKNOWN_COMMAND);
3875 #ifdef WITH_GNUTLS
3876 client->thd->buffer_timeout = client->thd->last_buffer_size = 0;
3877 #endif
3878 if (client->thd->state != CLIENT_STATE_DISCON)
3879 update_client_state (client, CLIENT_STATE_IDLE);
3882 static gpg_error_t
3883 parse_help_opt_html (void *data, void *value)
3885 struct client_s *client = data;
3887 (void) value;
3888 client->opts |= OPT_HTML;
3889 return 0;
3892 static gpg_error_t
3893 help_command (assuan_context_t ctx, char *line)
3895 gpg_error_t rc;
3896 int i;
3897 struct client_s *client = assuan_get_pointer (ctx);
3898 struct argv_s *args[] = {
3899 &(struct argv_s) {"html", OPTION_TYPE_NOARG, parse_help_opt_html},
3900 NULL
3903 rc = parse_options (&line, args, client, 1);
3904 if (rc)
3905 return send_error (ctx, rc);
3907 if (!line || !*line)
3909 char *tmp;
3910 char *help = str_dup (_("Usage: HELP [--html] [<COMMAND>]\n"
3911 "For commands that take an element path as an argument, each element is "
3912 "separated with an ASCII @key{TAB} character (ASCII 0x09)."
3913 "@*@*COMMANDS:"));
3915 for (i = 0; command_table[i]; i++)
3917 if (!command_table[i]->help)
3918 continue;
3920 /* @npxref{} won't put a "See " or "see " in front of the command.
3921 * It's not a texinfo command but needed for --html. */
3922 tmp = str_asprintf ("%s %s%s%s", help,
3923 client->opts & OPT_HTML ? "@npxref{" : "",
3924 command_table[i]->name,
3925 client->opts & OPT_HTML ? "}" : "");
3926 xfree (help);
3927 help = tmp;
3930 tmp = strip_texi_and_wrap (help, client->opts & OPT_HTML);
3931 xfree (help);
3932 pthread_cleanup_push ((void *)xfree, tmp);
3933 rc = xfer_data (ctx, tmp, strlen (tmp));
3934 pthread_cleanup_pop (1);
3935 return send_error (ctx, rc);
3938 for (i = 0; command_table[i]; i++)
3940 if (!strcasecmp (line, command_table[i]->name))
3942 char *help, *tmp;
3944 if (!command_table[i]->help)
3945 break;
3947 help = strip_texi_and_wrap (command_table[i]->help,
3948 client->opts & OPT_HTML);
3949 tmp = str_asprintf ("%s%s",
3950 (client->opts & OPT_HTML) ? "" : _("Usage: "),
3951 help);
3952 xfree (help);
3953 pthread_cleanup_push ((void *)xfree, tmp);
3954 rc = xfer_data (ctx, tmp, strlen (tmp));
3955 pthread_cleanup_pop (1);
3956 return send_error (ctx, rc);
3960 return send_error (ctx, GPG_ERR_INV_NAME);
3963 static void
3964 new_command (const char *name, int ignore, int unlock, int flock_type,
3965 gpg_error_t (*handler) (assuan_context_t, char *),
3966 const char *help)
3968 int i = 0;
3969 struct command_table_s **tmp;
3971 if (command_table)
3972 for (i = 0; command_table[i]; i++);
3974 tmp = xrealloc (command_table, (i + 2) * sizeof (struct command_table_s *));
3975 assert (tmp);
3976 command_table = tmp;
3977 command_table[i] = xcalloc (1, sizeof (struct command_table_s));
3978 command_table[i]->name = name;
3979 command_table[i]->handler = handler;
3980 command_table[i]->ignore_startup = ignore;
3981 command_table[i]->unlock = unlock;
3982 command_table[i]->flock_type = flock_type;
3983 command_table[i++]->help = help;
3984 command_table[i] = NULL;
3987 void
3988 deinit_commands ()
3990 int i;
3992 for (i = 0; command_table[i]; i++)
3993 xfree (command_table[i]);
3995 xfree (command_table);
3998 static int
3999 sort_commands (const void *arg1, const void *arg2)
4001 struct command_table_s *const *a = arg1;
4002 struct command_table_s *const *b = arg2;
4004 if (!*a || !*b)
4005 return 0;
4006 else if (*a && !*b)
4007 return 1;
4008 else if (!*a && *b)
4009 return -1;
4011 return strcmp ((*a)->name, (*b)->name);
4014 static gpg_error_t
4015 passwd_command (assuan_context_t ctx, char *line)
4017 struct client_s *client = assuan_get_pointer (ctx);
4018 gpg_error_t rc;
4020 (void)line;
4021 rc = peer_is_invoker (client);
4022 if (rc == GPG_ERR_EACCES)
4023 return send_error (ctx, GPG_ERR_FORBIDDEN);
4024 else if (rc)
4025 return send_error (ctx, rc);
4027 if (client->flags & FLAG_NEW)
4028 return send_error (ctx, GPG_ERR_INV_STATE);
4030 client->crypto->keyfile = config_get_string (client->filename,
4031 "passphrase_file");
4032 rc = crypto_init_ctx (client->crypto, client->flags & FLAG_NO_PINENTRY,
4033 client->crypto->keyfile);
4034 if (rc)
4035 return send_error (ctx, rc);
4037 if (!rc)
4038 rc = crypto_passwd (client, client->crypto);
4040 crypto_free_non_keys (client->crypto);
4041 return send_error (ctx, rc);
4044 static gpg_error_t
4045 parse_opt_data (void *data, void *value)
4047 struct client_s *client = data;
4049 (void) value;
4050 client->opts |= OPT_DATA;
4051 return 0;
4054 static gpg_error_t
4055 send_client_list (assuan_context_t ctx)
4057 struct client_s *client = assuan_get_pointer (ctx);
4058 gpg_error_t rc = 0;
4060 if (client->opts & OPT_VERBOSE)
4062 unsigned i, t;
4063 char **list = NULL;
4064 char *line;
4066 MUTEX_LOCK (&cn_mutex);
4067 pthread_cleanup_push ((void *)release_mutex_cb, &cn_mutex);
4068 t = slist_length (cn_thread_list);
4070 for (i = 0; i < t; i++)
4072 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
4073 char *tmp;
4075 if (thd->state == CLIENT_STATE_UNKNOWN)
4076 continue;
4078 tmp = build_client_info_line (thd, 0);
4079 if (tmp)
4081 char **l = strv_cat (list, tmp);
4082 if (!l)
4083 rc = GPG_ERR_ENOMEM;
4084 else
4085 list = l;
4087 else
4088 rc = GPG_ERR_ENOMEM;
4090 if (rc)
4092 strv_free (list);
4093 break;
4097 pthread_cleanup_pop (1);
4098 if (rc)
4099 return rc;
4101 line = strv_join ("\n", list);
4102 strv_free (list);
4103 pthread_cleanup_push ((void *)xfree, line);
4104 rc = xfer_data (ctx, line, strlen (line));
4105 pthread_cleanup_pop (1);
4106 return rc;
4109 if (client->opts & OPT_DATA)
4111 char buf[ASSUAN_LINELENGTH];
4113 MUTEX_LOCK (&cn_mutex);
4114 snprintf (buf, sizeof (buf), "%u", slist_length (cn_thread_list));
4115 MUTEX_UNLOCK (&cn_mutex);
4116 rc = xfer_data (ctx, buf, strlen (buf));
4118 else
4119 rc = send_status (ctx, STATUS_CLIENTS, NULL);
4121 return rc;
4124 static gpg_error_t
4125 getinfo_command (assuan_context_t ctx, char *line)
4127 struct client_s *client = assuan_get_pointer (ctx);
4128 gpg_error_t rc;
4129 char buf[ASSUAN_LINELENGTH];
4130 struct argv_s *args[] = {
4131 &(struct argv_s) {"data", OPTION_TYPE_NOARG, parse_opt_data},
4132 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_opt_verbose},
4133 NULL
4136 rc = parse_options (&line, args, client, 1);
4137 if (rc)
4138 return send_error (ctx, rc);
4140 if (!strcasecmp (line, "clients"))
4142 rc = send_client_list (ctx);
4144 else if (!strcasecmp (line, "cache"))
4146 if (client->opts & OPT_DATA)
4148 snprintf (buf, sizeof (buf), "%u", cache_file_count ());
4149 rc = xfer_data (ctx, buf, strlen (buf));
4151 else
4152 rc = send_status (ctx, STATUS_CACHE, NULL);
4154 else if (!strcasecmp (line, "pid"))
4156 pid_t pid = getpid ();
4158 snprintf (buf, sizeof (buf), "%u", pid);
4159 rc = xfer_data (ctx, buf, strlen (buf));
4161 else if (!strcasecmp (line, "version"))
4163 char *tmp = str_asprintf ("0x%06x %s", VERSION_HEX,
4164 #ifdef WITH_GNUTLS
4165 "GNUTLS "
4166 #endif
4167 #ifdef WITH_LIBACL
4168 "ACL "
4169 #endif
4170 "");
4171 pthread_cleanup_push (xfree, tmp);
4172 rc = xfer_data (ctx, tmp, strlen (tmp));
4173 pthread_cleanup_pop (1);
4175 else if (!strcasecmp (line, "last_error"))
4177 if (client->last_error)
4178 rc = xfer_data (ctx, client->last_error, strlen (client->last_error));
4179 else
4180 rc = GPG_ERR_NO_DATA;
4182 else if (!strcasecmp (line, "user"))
4184 char *user = NULL;
4186 #ifdef WITH_GNUTLS
4187 if (client->thd->remote)
4188 user = str_asprintf ("#%s", client->thd->tls->fp);
4189 else
4190 user = get_username (client->thd->peer->uid);
4191 #else
4192 user = get_username (client->thd->peer->uid);
4193 #endif
4194 if (user)
4196 pthread_cleanup_push ((void *)xfree, user);
4197 rc = xfer_data (ctx, user, strlen (user));
4198 pthread_cleanup_pop (1);
4200 else
4201 rc = GPG_ERR_NO_DATA;
4203 else
4204 rc = gpg_error (GPG_ERR_SYNTAX);
4206 return send_error (ctx, rc);
4209 static gpg_error_t
4210 parse_listkeys_opt_secret_only (void *data, void *value)
4212 struct client_s *client = data;
4214 (void) value;
4215 client->opts |= OPT_SECRET_ONLY;
4216 return 0;
4219 static gpg_error_t
4220 parse_keyinfo_opt_learn (void *data, void *value)
4222 struct client_s *client = data;
4224 (void)value;
4225 client->opts |= OPT_KEYINFO_LEARN;
4226 return 0;
4229 static gpg_error_t
4230 keyinfo_command (assuan_context_t ctx, char *line)
4232 struct client_s *client = assuan_get_pointer (ctx);
4233 gpg_error_t rc = 0;
4234 char **keys = NULL, **p = NULL;
4235 int sym = 0;
4236 struct argv_s *args[] = {
4237 &(struct argv_s) {"learn", OPTION_TYPE_NOARG, parse_keyinfo_opt_learn},
4238 NULL
4241 rc = parse_options (&line, args, client, 0);
4242 if (rc)
4243 return send_error (ctx, rc);
4245 if (line && *line)
4246 return send_error (ctx, GPG_ERR_SYNTAX);
4248 if (!(client->flags & FLAG_OPEN))
4249 return send_error (ctx, GPG_ERR_INV_STATE);
4251 if (client->opts & OPT_KEYINFO_LEARN)
4253 rc = cache_agent_command ("LEARN");
4254 return send_error (ctx, rc);
4257 if (client->flags & FLAG_NEW)
4258 return send_error (ctx, GPG_ERR_NO_DATA);
4260 rc = lock_flock (ctx, client->filename, FLOCK_TYPE_SH, &client->flock_fd);
4261 if (rc)
4262 return send_error (ctx, rc);
4264 rc = crypto_is_symmetric (client->filename);
4265 unlock_flock (&client->flock_fd);
4266 if (!rc)
4267 sym = 1;
4268 else if (rc != GPG_ERR_BAD_DATA)
4269 return send_error (ctx, rc);
4271 rc = 0;
4272 if (!sym)
4274 p = strv_catv(keys, client->crypto->pubkey);
4275 if (!p)
4276 rc = GPG_ERR_ENOMEM;
4279 if (!rc)
4281 keys = p;
4282 for (p = client->crypto->sigkey; p && *p; p++)
4284 if (!strv_printf(&keys, "S%s", *p))
4286 strv_free (keys);
4287 return send_error (ctx, GPG_ERR_ENOMEM);
4291 else
4292 rc = GPG_ERR_ENOMEM;
4294 if (!rc)
4296 if (keys)
4298 line = strv_join ("\n", keys);
4299 strv_free (keys);
4300 pthread_cleanup_push ((void *)xfree, line);
4301 if (line)
4302 rc = xfer_data (ctx, line, strlen (line));
4303 else
4304 rc = GPG_ERR_ENOMEM;
4306 pthread_cleanup_pop (1);
4308 else
4309 rc = GPG_ERR_NO_DATA;
4311 else
4312 strv_free (keys);
4314 return send_error (ctx, rc);
4317 static gpg_error_t
4318 kill_command (assuan_context_t ctx, char *line)
4320 struct client_s *client = assuan_get_pointer (ctx);
4321 gpg_error_t rc;
4322 unsigned i, t;
4324 if (!line || !*line)
4325 return send_error (ctx, GPG_ERR_SYNTAX);
4327 MUTEX_LOCK (&cn_mutex);
4328 pthread_cleanup_push ((void *)release_mutex_cb, &cn_mutex);
4329 t = slist_length (cn_thread_list);
4330 rc = GPG_ERR_ESRCH;
4332 for (i = 0; i < t; i++)
4334 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
4335 char *tmp = str_asprintf ("%p", thd->tid);
4337 if (strcmp (line, tmp))
4339 xfree (tmp);
4340 continue;
4343 xfree (tmp);
4344 rc = peer_is_invoker (client);
4345 if (!rc)
4347 #ifdef HAVE_PTHREAD_CANCEL
4348 pthread_cancel (thd->tid);
4349 #else
4350 pthread_kill (thd->tid, SIGUSR2);
4351 #endif
4352 break;
4354 else if (rc == GPG_ERR_EACCES)
4355 rc = GPG_ERR_FORBIDDEN;
4356 else if (rc)
4357 break;
4359 if (config_get_boolean ("global", "strict_kill"))
4360 break;
4362 #ifdef WITH_GNUTLS
4363 if (client->thd->remote && thd->remote)
4365 if (!thd->tls || !thd->tls->fp)
4367 rc = GPG_ERR_INV_STATE;
4368 break;
4370 if (!strcmp (client->thd->tls->fp, thd->tls->fp))
4372 #ifdef HAVE_PTHREAD_CANCEL
4373 pthread_cancel (thd->tid);
4374 #else
4375 pthread_kill (thd->tid, SIGUSR2);
4376 #endif
4377 break;
4380 else if (!client->thd->remote && !thd->remote)
4381 #endif
4383 if (client->thd->peer->uid == thd->peer->uid)
4385 #ifdef HAVE_PTHREAD_CANCEL
4386 pthread_cancel (thd->tid);
4387 #else
4388 pthread_kill (thd->tid, SIGUSR2);
4389 #endif
4392 break;
4395 pthread_cleanup_pop (1);
4396 return send_error (ctx, rc);
4399 static gpg_error_t
4400 listkeys_command (assuan_context_t ctx, char *line)
4402 struct client_s *client = assuan_get_pointer (ctx);
4403 struct crypto_s *crypto = NULL;
4404 char **pattern = NULL;
4405 gpgme_key_t *keys = NULL;
4406 char **result = NULL;
4407 gpg_error_t rc;
4408 struct argv_s *args[] = {
4409 &(struct argv_s) {"secret-only", OPTION_TYPE_NOARG,
4410 parse_listkeys_opt_secret_only },
4411 NULL
4414 rc = parse_options (&line, args, client, 1);
4415 if (rc)
4416 return send_error (ctx, rc);
4418 rc = crypto_init (&crypto, client->ctx, client->filename,
4419 client->flags & FLAG_NO_PINENTRY, NULL);
4420 if (rc)
4421 return send_error (ctx, rc);
4423 pthread_cleanup_push ((void *)crypto_free, crypto);
4424 pattern = str_split (line, ",", 0);
4425 pthread_cleanup_push ((void *)(void *)strv_free, pattern);
4426 rc = crypto_list_keys (crypto, pattern, client->opts & OPT_SECRET_ONLY,
4427 &keys);
4428 pthread_cleanup_pop (1);
4429 pthread_cleanup_pop (1);
4430 if (!rc)
4432 int i;
4434 for (i = 0; keys[i]; i++)
4436 char *p = crypto_key_info (keys[i]);
4437 char **r;
4439 if (!p)
4441 rc = GPG_ERR_ENOMEM;
4442 break;
4445 r = strv_cat (result, p);
4446 if (!r)
4448 rc = GPG_ERR_ENOMEM;
4449 break;
4452 result = r;
4455 if (!i)
4456 rc = GPG_ERR_NO_DATA;
4458 crypto_free_key_list (keys);
4461 if (!rc)
4463 line = strv_join ("\n", result);
4464 strv_free (result);
4465 pthread_cleanup_push ((void *)xfree, line);
4466 if (!line)
4467 rc = GPG_ERR_ENOMEM;
4468 else
4469 rc = xfer_data (ctx, line, strlen (line));
4471 pthread_cleanup_pop (1);
4473 else
4474 strv_free (result);
4476 if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
4477 || gpg_err_code (rc) == GPG_ERR_NO_SECKEY)
4478 rc = GPG_ERR_NO_DATA;
4480 return send_error (ctx, rc);
4483 void
4484 init_commands ()
4486 /* !BEGIN-HELP-TEXT!
4488 * This comment is used as a marker to generate the offline documentation
4489 * found in doc/pwmd.info. The indentation needs to be kept for the awk
4490 * script to determine where commands begin and end.
4492 new_command("HELP", 1, 1, 0, help_command, _(
4493 "HELP [--html] [<COMMAND>]\n"
4494 "Show available commands or command specific help text."
4495 "@*@*"
4496 "The @option{--html} option will output the help text in HTML format."
4499 new_command("KILL", 1, 0, 0, kill_command, _(
4500 "KILL <thread_id>\n"
4501 "Terminates the client identified by @var{thread_id} and releases any file "
4502 "lock or other resources it has held. See @code{GETINFO} (@pxref{GETINFO}) "
4503 "for details about listing connected clients. An @code{invoking_user} "
4504 "(@pxref{Configuration}) may kill any client while others may only kill "
4505 "clients of the same @code{UID} or @abbr{TLS} fingerprint."
4508 new_command("LISTKEYS", 0, 0, 0, listkeys_command, _(
4509 "LISTKEYS [--secret-only] [pattern[,<pattern>]]\n"
4510 "Returns a new line separated list of key information matching a comma "
4511 "separated list of @var{pattern}'s. When option @option{--secret-only} is "
4512 "specified, only keys matching @var{pattern} that also have a secret key "
4513 "available will be returned."
4516 new_command("KEYINFO", 1, 0, 0, keyinfo_command, _(
4517 "KEYINFO [--learn]\n"
4518 "Returns a new line separated list of key ID's that the currently opened "
4519 "data file has recipients and signers for. If the key is a signing key it "
4520 "will be prefixed with an @code{S}. If the file is a new one, or has no "
4521 "signers in the case of being symmetrically encrypted, the error code "
4522 "@code{GPG_ERR_NO_DATA} is returned."
4523 "@*@*"
4524 "When the @option{--learn} option is passed, keys on a smartcard will be "
4525 "imported."
4528 new_command("GETINFO", 1, 1, 0, getinfo_command, _(
4529 "GETINFO [--data] [--verbose] CACHE | CLIENTS | PID | USER | LAST_ERROR | VERSION\n"
4530 "Get server and other information. The information is returned via a status "
4531 "message (@pxref{Status Messages}) unless otherwise noted or @option{--data} "
4532 "is specified."
4533 "@*@*"
4534 "@var{CACHE} returns the number of cached documents."
4535 "@*@*"
4536 "@var{CLIENTS} returns the number of "
4537 "connected clients via a status message or a list of connected clients when "
4538 "the @option{--verbose} parameter is used (implies @option{--data}). A "
4539 "verbose line of a client list contains "
4540 "space delimited "
4541 "fields: the thread ID, client name, opened file (@code{/} if none opened), "
4542 "IP address if remote, file lock status, whether the current client is self "
4543 "or not, client state (see below), "
4544 "user ID or TLS fingerprint of the connected client, username if the "
4545 "client is a local one else @code{-}, and finally the time stamp of when the "
4546 "client connected."
4547 "@*@*"
4548 "Client state @code{0} is an unknown client state, state @code{1} indicates "
4549 "the client has connected but hasn't completed initializing, state @code{2} "
4550 "indicates that the client is idle, state @code{3} means the "
4551 "client is in a command and state @code{4} means the client is disconnecting. "
4552 "@*@*"
4553 "@var{PID} returns the process ID number of the server via a data response."
4554 "@*@*"
4555 "@var{VERSION} returns the server version number and compile-time features "
4556 "via a data response with each being space delimited."
4557 "@*@*"
4558 "@var{LAST_ERROR} returns a detailed description of the last failed command "
4559 "via a data response, when available."
4560 "@*@*"
4561 "@var{USER} returns the username or @abbr{TLS} hash of the connected client "
4562 "via a data response."
4565 new_command("PASSWD", 0, 0, FLOCK_TYPE_EX|FLOCK_TYPE_KEEP, passwd_command, _(
4566 "PASSWD\n"
4567 "Changes the passphrase of the secret key required to open the current "
4568 "data file. If the data file is symmetrically encrypted, the error "
4569 "@code{GPG_ERR_NOT_SUPPORTED} is returned. When symmetrically encrypted, "
4570 "the @code{SAVE} command (@pxref{SAVE}) should be used instead to prevent "
4571 "this command saving any unwanted changes to the @abbr{XML} document."
4572 "@*@*"
4573 "This command is not available to non-invoking clients "
4574 "(@pxref{Access Control})."
4577 new_command("OPEN", 1, 1, FLOCK_TYPE_SH|FLOCK_TYPE_KEEP, open_command, _(
4578 "OPEN [--lock] <filename>\n"
4579 "Opens @var{filename}. When the @var{filename} is not found on the "
4580 "file-system then a new in-memory document will be created. If the file is "
4581 "found, it is looked for in the file cache and when found no passphrase will "
4582 "be required to open it. When not cached, @cite{pinentry(1)} will be used to "
4583 "retrieve the passphrase for decryption unless @option{disable-pinentry} "
4584 "(@pxref{OPTION}) was specified in which case @command{pwmd} will "
4585 "@emph{INQUIRE} the client for the passphrase."
4586 "@*@*"
4587 "When the @option{--lock} option is passed then the file mutex will be "
4588 "locked as if the @code{LOCK} command (@pxref{LOCK}) had been sent after the "
4589 "file had been opened."
4592 new_command("SAVE", 0, 0, FLOCK_TYPE_EX|FLOCK_TYPE_KEEP, save_command, _(
4593 "SAVE [--symmetric] [--inquire-keyparam] [--keyid=<fpr>[,..] | [--inquire-keyid]] [--sign-keyid=<fpr>[,..] | [--inquire-sign-keyid]]\n"
4594 "Writes the in-memory @abbr{XML} document to disk. The file written to is the "
4595 "file that was opened using the @code{OPEN} command (@pxref{OPEN}). If the "
4596 "file is a new one or the option @option{--inquire-keyparam} was passed, a "
4597 "new keypair will be generated and @cite{pinentry(1)} will be used to prompt "
4598 "for the passphrase of the secret key used for signing."
4599 "@*@*"
4600 "The @option{--inquire-keyparam} option will send an "
4601 "@emph{INQUIRE} to the client to obtain the key parameters to use for "
4602 "generating the new keypair. The inquired data is expected to be in "
4603 "@cite{gnupg} @abbr{XML} format. See the @cite{gnupg} documentation for "
4604 "details. Note that when this option is specified a new keypair will be "
4605 "generated reguardless if the file is a new one and that the passphrase for "
4606 "the current file will be required before generating the new keypair. This "
4607 "option is available to non-invoking clients (@pxref{Access Control}) only "
4608 "when the file is a new one."
4609 "@*@*"
4610 "You can encrypt the data file to a recipient other than the one that it "
4611 "was encrypted with by passing the @option{--keyid} or "
4612 "@option{--inquire-keyid} option with "
4613 "the fingerprint of a public encryption key as its argument. Use the "
4614 "@command{LISTKEYS} command (@pxref{LISTKEYS}) to show key information by "
4615 "pattern. The @option{--sign-keyid} or @option{--inquire-sign-keyid} option "
4616 "may also be used to sign the data "
4617 "file with an alternate key by specifying the fingerprint of a secret key. "
4618 "A passphrase to decrypt the data file "
4619 "will be required when one or more of the original encryption or signing keys "
4620 "are not found in either of these two options' arguments or when the data "
4621 "file is symmetrically encrypted, reguardless of the @code{require_save_key} "
4622 "configuration parameter. The original encryption or signing keys will be "
4623 "used when either of these options are not specified."
4624 "@*@*"
4625 "The @option{--keyid} and @option{--sign-keyid} options are not available "
4626 "for non-invoking clients "
4627 "(@pxref{Access Control}) when the recipients or signers do not match those "
4628 "that were used when the file was @code{OPEN}'ed."
4629 "@*@*"
4630 "The @option{--symmetric} option specifies that a new data file be "
4631 "conventionally encrypted. These types of data files do not use a recipient "
4632 "public key but may be signed by using the @option{--sign-keyid} or "
4633 "@option{--inquire-sign-keyid} options. To remove all signers from a "
4634 "symmtrically encrypted data file, leave the option value empty. Note that "
4635 "you cannot change encryption schemes once a data file has been saved."
4638 new_command("ISCACHED", 1, 0, 0, iscached_command, _(
4639 "ISCACHED [--lock] [--agent [--sign]] <filename>\n"
4640 "Determines the file cache status of the specified @var{filename}. "
4641 "The default is to test whether the filename is cached in memory. Passing "
4642 "option @option{--agent} will test the @command{gpg-agent} cache for at most "
4643 "one cached key used for opening the data file (@pxref{OPEN}). To test if "
4644 "a signing key is cached, pass @option{--sign} along with @option{--agent}. "
4645 "Both the @option{--agent} and @option{--sign} options require an opened data "
4646 "file."
4647 "@*@*"
4648 "An @emph{OK} response is returned if the specified @var{filename} is found "
4649 "in the cache. If not found in the cache but exists on the filesystem "
4650 "then @code{GPG_ERR_NO_DATA} is returned. Otherwise a filesystem error is "
4651 "returned."
4652 "@*@*"
4653 "The @option{--lock} option will lock the file mutex of @var{filename} when "
4654 "the file exists; it does not need to be opened nor cached. The lock will be "
4655 "released when the client exits or sends the @code{UNLOCK} command "
4656 "(@pxref{UNLOCK}). When this option is passed the current data file is closed."
4659 new_command("CLEARCACHE", 1, 1, 0, clearcache_command, _(
4660 "CLEARCACHE [<filename>]\n"
4661 "Clears a file cache entry for all or the specified @var{filename}. Note that "
4662 "this will also clear any @command{gpg-agent} cached keys which may cause "
4663 "problems if another data file shares the same keys as @var{filename}."
4664 "@*@*"
4665 "When clearing all cache entries a permissions test is done against the "
4666 "current client based on the @var{allowed} configuration parameter in a "
4667 "@var{filename} section. Both a cache entry may be cleared and an error "
4668 "returned depending on cached data files and client permissions."
4671 new_command("CACHETIMEOUT", 1, 1, 0, cachetimeout_command, _(
4672 "CACHETIMEOUT <filename> <seconds>\n"
4673 "The time in @var{seconds} until @var{filename} will be removed from the "
4674 "cache. @code{-1} will keep the cache entry forever, @code{0} will require "
4675 "the passphrase for each @code{OPEN} command (@pxref{OPEN}) or @code{SAVE} "
4676 "(@pxref{SAVE}) command. @xref{Configuration}, and the @code{cache_timeout} "
4677 "parameter."
4680 new_command("LIST", 0, 1, 0, list_command, _(
4681 "LIST [--inquire] [--recurse] [element[<TAB>child[..]]]\n"
4682 "If no element path is given then a newline separated list of root elements "
4683 "is returned with a data response. If given, then children of the specified "
4684 "element path are returned."
4685 "@*@*"
4686 "Each element path "
4687 "returned will have zero or more flags appened to it. These flags are "
4688 "delimited from the element path by a single space character. A flag itself "
4689 "is a single character. Flag @code{P} indicates that access to the element "
4690 "is denied. Flag @code{+} indicates that there are child nodes of "
4691 "the current element path. Flag @code{E} indicates that an element of the "
4692 "element path contained in a @var{target} attribute could not be found. Flag "
4693 "@code{O} indicates that a @var{target} attribute recursion limit was reached "
4694 "(@pxref{Configuration}). Flag @code{T}, followed by a single space character, "
4695 "then an element path, is the element path of the @var{target} attribute "
4696 "contained in the current element."
4697 "@*@*"
4698 "When a specified element path contains an error, beit from the final "
4699 "element in the path or any previous element, the path is still shown but "
4700 "will contain the error flag for the element with the error. Determining "
4701 "the actual element which contains the error is up to the client. This can be "
4702 "done by traversing the final element up to parent elements that contain the "
4703 "same error flag."
4704 "@*@*"
4705 "The option @option{--recurse} may be used to list the entire element tree "
4706 "for a specified element path or the entire tree for all root elements."
4707 "@*@*"
4708 "When the @option{--inquire} option is passed then all remaining non-option "
4709 "arguments are retrieved via a server @emph{INQUIRE}."
4712 new_command("REALPATH", 0, 1, 0, realpath_command, _(
4713 "REALPATH [--inquire] element[<TAB>child[..]]\n"
4714 "Resolves all @code{target} attributes of the specified element path and "
4715 "returns the result with a data response. @xref{Target Attribute}, for details."
4716 "@*@*"
4717 "When the @option{--inquire} option is passed then all remaining non-option "
4718 "arguments are retrieved via a server @emph{INQUIRE}."
4721 new_command("STORE", 0, 1, 0, store_command, _(
4722 "STORE element[<TAB>child[..]]<TAB>[content]\n"
4723 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
4724 "@*@*"
4725 "Creates a new element path or modifies the @var{content} of an existing "
4726 "element. If only a single element is specified then a new root element is "
4727 "created. Otherwise, elements are @key{TAB} delimited and the content will be "
4728 "set to the final @key{TAB} delimited element. If no @var{content} is "
4729 "specified after the final @key{TAB}, then the content of the existing "
4730 "element will be removed; or will be empty if creating a new element."
4731 "@*@*"
4732 "The only restriction of an element name is that it not contain whitespace "
4733 "characters. There is no other whitespace between the @key{TAB} delimited "
4734 "elements. It is recommended that the content of an element be base64 encoded "
4735 "when it contains control or @key{TAB} characters to prevent @abbr{XML} "
4736 "parsing and @command{pwmd} syntax errors."
4739 new_command("RENAME", 0, 1, 0, rename_command, _(
4740 "RENAME [--inquire] element[<TAB>child[..]] <value>\n"
4741 "Renames the specified @var{element} to the new @var{value}. If an element of "
4742 "the same name as the @var{value} already exists it will be overwritten."
4743 "@*@*"
4744 "When the @option{--inquire} option is passed then all remaining non-option "
4745 "arguments are retrieved via a server @emph{INQUIRE}."
4748 new_command("COPY", 0, 1, 0, copy_command, _(
4749 "COPY [--inquire] source[<TAB>child[..]] dest[<TAB>child[..]]\n"
4750 "Copies the entire element tree starting from the child node of the source "
4751 "element, to the destination element path. If the destination element path "
4752 "does not exist then it will be created; otherwise it is overwritten."
4753 "@*@*"
4754 "Note that attributes from the source element are merged into the "
4755 "destination element when the destination element path exists. When an "
4756 "attribute of the same name exists in both the source and destination "
4757 "elements then the destination attribute will be updated to the source "
4758 "attribute value."
4759 "@*@*"
4760 "When the @option{--inquire} option is passed then all remaining non-option "
4761 "arguments are retrieved via a server @emph{INQUIRE}."
4764 new_command("MOVE", 0, 1, 0, move_command, _(
4765 "MOVE [--inquire] source[<TAB>child[..]] [dest[<TAB>child[..]]]\n"
4766 "Moves the source element path to the destination element path. If the "
4767 "destination is not specified then it will be moved to the root node of the "
4768 "document. If the destination is specified and exists then it will be "
4769 "overwritten; otherwise non-existing elements of the destination element "
4770 "path will be created."
4771 "@*@*"
4772 "When the @option{--inquire} option is passed then all remaining non-option "
4773 "arguments are retrieved via a server @emph{INQUIRE}."
4776 new_command("DELETE", 0, 1, 0, delete_command, _(
4777 "DELETE [--inquire] element[<TAB>child[..]]\n"
4778 "Removes the specified element path and all of its children. This may break "
4779 "an element with a @code{target} attribute (@pxref{Target Attribute}) that "
4780 "refers to this element or any of its children."
4781 "@*@*"
4782 "When the @option{--inquire} option is passed then all remaining non-option "
4783 "arguments are retrieved via a server @emph{INQUIRE}."
4786 new_command("GET", 0, 1, 0, get_command, _(
4787 "GET [--inquire] element[<TAB>child[..]]\n"
4788 "Retrieves the content of the specified element. The content is returned "
4789 "with a data response."
4790 "@*@*"
4791 "When the @option{--inquire} option is passed then all remaining non-option "
4792 "arguments are retrieved via a server @emph{INQUIRE}."
4795 new_command("ATTR", 0, 1, 0, attr_command, _(
4796 "ATTR [--inquire] SET|GET|DELETE|LIST [<attribute>] element[<TAB>child[..]] ..\n"
4797 "@table @asis\n"
4798 "@item ATTR SET attribute element[<TAB>child[..]] [value]\n"
4799 " Stores or updates an @var{attribute} name and optional @var{value} of an "
4800 "element. When no @var{value} is specified any existing value will be removed."
4801 "@*@*"
4802 "@item ATTR DELETE attribute element[<TAB>child[..]]\n"
4803 " Removes an attribute from an element. If @var{attribute} is @code{_name} "
4804 "or @code{target} an error is returned. Use the @command{DELETE} command "
4805 "(@pxref{DELETE}) instead."
4806 "@*@*"
4807 "@item ATTR LIST element[<TAB>child[..]]\n"
4808 " Retrieves a newline separated list of attributes names and values "
4809 "from the specified element. Each attribute name and value is space delimited."
4810 "@*@*"
4811 "@item ATTR GET attribute element[<TAB>child[..]]\n"
4812 " Retrieves the value of an @var{attribute} from an element."
4813 "@end table\n"
4814 "@*@*"
4815 "When the @option{--inquire} option is passed then all remaining non-option "
4816 "arguments are retrieved via a server @emph{INQUIRE}."
4817 "@*@*"
4818 "@xref{Target Attribute}, for details about this special attribute and also "
4819 "@pxref{Other Attributes} for other attributes that are handled specially "
4820 "by @command{pwmd}."
4823 new_command("XPATH", 0, 1, 0, xpath_command, _(
4824 "XPATH [--inquire] <expression>[<TAB>[value]]\n"
4825 "Evaluates an XPath @var{expression}. If no @var{value} argument is "
4826 "specified it is assumed the expression is a request to return a result. "
4827 "Otherwise, the result is set to the @var{value} argument and the document is "
4828 "updated. If there is no @var{value} after the @key{TAB} character, the value "
4829 "is assumed to be empty and the document is updated. For example:"
4830 "@sp 1\n"
4831 "@example\n"
4832 "XPATH //element[@@_name='password']@key{TAB}\n"
4833 "@end example\n"
4834 "@sp 1\n"
4835 "would clear the content of all @var{password} elements in the data file "
4836 "while leaving off the trailing @key{TAB} would return all @var{password} "
4837 "elements in @abbr{XML} format."
4838 "@*@*"
4839 "When the @option{--inquire} option is passed then all remaining non-option "
4840 "arguments are retrieved via a server @emph{INQUIRE}."
4841 "@*@*"
4842 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
4843 "expression syntax."
4846 new_command("XPATHATTR", 0, 1, 0, xpathattr_command, _(
4847 "XPATHATTR [--inquire] SET|DELETE <name> <expression>[<TAB>[<value>]]\n"
4848 "Like the @code{XPATH} command (@pxref{XPATH}) but operates on element "
4849 "attributes and does not return a result. For the @var{SET} operation the "
4850 "@var{value} is optional but the field is required. If not specified then "
4851 "the attribute value will be empty. For example:"
4852 "@sp 1\n"
4853 "@example\n"
4854 "XPATHATTR SET password //element[@@_name='password']@key{TAB}\n"
4855 "@end example\n"
4856 "@sp 1\n"
4857 "would create a @var{password} attribute for each @var{password} element "
4858 "found in the document. The attribute value will be empty but still exist."
4859 "@*@*"
4860 "When the @option{--inquire} option is passed then all remaining non-option "
4861 "arguments are retrieved via a server @emph{INQUIRE}."
4862 "@*@*"
4863 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
4864 "expression syntax."
4867 new_command("IMPORT", 0, 1, 0, import_command, _(
4868 "IMPORT [--root=element[<TAB>child[..]]]\n"
4869 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
4870 "@*@*"
4871 "Like the @code{STORE} command (@pxref{STORE}), but the @var{content} "
4872 "argument is raw @abbr{XML} data. The content is created as a child of "
4873 "the element path specified with the @option{--root} option or at the "
4874 "document root when not specified. Existing elements of the same name will "
4875 "be overwritten."
4876 "@*@*"
4877 "The content must begin with an @abbr{XML} element node. @xref{Introduction}, "
4878 "for details."
4881 new_command("DUMP", 0, 1, 0, dump_command, _(
4882 "DUMP\n"
4883 "Shows the in memory @abbr{XML} document with indenting. @xref{XPATH}, for "
4884 "dumping a specific node."
4887 new_command("LOCK", 0, 0, 0, lock_command, _(
4888 "LOCK\n"
4889 "Locks the mutex associated with the opened file. This prevents other clients "
4890 "from sending commands to the same opened file until the client "
4891 "that sent this command either disconnects or sends the @code{UNLOCK} "
4892 "command. @xref{UNLOCK}."
4895 new_command("UNLOCK", 1, 0, 0, unlock_command, _(
4896 "UNLOCK\n"
4897 "Unlocks the file mutex which was locked with the @code{LOCK} command or "
4898 "a commands' @option{--lock} option (@pxref{LOCK}, @pxref{OPEN}, "
4899 "@pxref{ISCACHED})."
4902 new_command("GETCONFIG", 1, 1, 0, getconfig_command, _(
4903 "GETCONFIG [filename] <parameter>\n"
4904 "Returns the value of a @command{pwmd} configuration @var{parameter} with a "
4905 "data response. If no file has been opened then the value for @var{filename} "
4906 "or the default from the @var{global} section will be returned. If a file "
4907 "has been opened and no @var{filename} is specified, the value previously "
4908 "set with the @code{OPTION} command (@pxref{OPTION}) will be returned."
4911 new_command("OPTION", 1, 1, 0, option_command, _(
4912 "OPTION <NAME>=[<VALUE>]\n"
4913 "Sets a client option @var{name} to @var{value}. The value for an option is "
4914 "kept for the duration of the connection with the exception of the "
4915 "@command{pinentry} options which are defaults for all future connections "
4916 "(@pxref{Pinentry}). When @var{value} is empty the option is unset."
4917 "@*@*"
4918 "@table @asis\n"
4919 "@item DISABLE-PINENTRY\n"
4920 "Disable use of @command{pinentry} for passphrase retrieval. When @code{1}, a "
4921 "server inquire is sent to the client to obtain the passphrase. This option "
4922 "may be set as needed before the @code{OPEN} (@pxref{OPEN}), @code{PASSWD} "
4923 "(@pxref{PASSWD}) and @code{SAVE} (@pxref{SAVE}) commands. Set to @code{0} "
4924 "to use a @command{pinentry}."
4925 "@*@*"
4926 "@item DISPLAY\n"
4927 "Set or unset the X11 display to use when prompting for a passphrase."
4928 "@*@*"
4929 "@item TTYNAME\n"
4930 "Set the terminal device path to use when prompting for a passphrase."
4931 "@*@*"
4932 "@item TTYTYPE\n"
4933 "Set the terminal type for use with @option{TTYNAME}."
4934 "@*@*"
4935 "@item NAME\n"
4936 "Associates the thread ID of the connection with the specified textual "
4937 "representation. Useful for debugging log messages. May not contain whitespace."
4938 "@*@*"
4939 "@item LOCK-TIMEOUT\n"
4940 "When not @code{0}, the duration in tenths of a second to wait for the file "
4941 "mutex which has been locked by another thread to be released before returning "
4942 "an error. When @code{-1} the error will be returned immediately."
4943 "@*@*"
4944 "@item CLIENT-STATE\n"
4945 "When set to @code{1} then client state status messages for other clients are "
4946 "sent to the current client. The default is @code{0}."
4947 "@end table\n"
4950 new_command("LS", 1, 1, 0, ls_command, _(
4951 "LS\n"
4952 "Returns a newline separated list of data files stored in the data directory "
4953 "@file{HOMEDIR/data} (@pxref{Invoking}) with a data response."
4956 new_command("RESET", 1, 1, 0, NULL, _(
4957 "RESET\n"
4958 "Closes the currently opened file but keeps any previously set client options "
4959 "(@pxref{OPTION})."
4962 new_command("NOP", 1, 1, 0, NULL, _(
4963 "NOP\n"
4964 "Does nothing. Always returns successfully."
4967 /* !END-HELP-TEXT! */
4968 new_command ("CANCEL", 1, 1, 0, NULL, NULL);
4969 new_command ("END", 1, 1, 0, NULL, NULL);
4970 new_command ("BYE", 1, 1, 0, NULL, NULL);
4972 int i;
4973 for (i = 0; command_table[i]; i++);
4974 qsort (command_table, i - 1, sizeof (struct command_table_s *),
4975 sort_commands);
4978 gpg_error_t
4979 register_commands (assuan_context_t ctx)
4981 int i = 0, rc;
4983 for (; command_table[i]; i++)
4985 if (!command_table[i]->handler)
4986 continue;
4988 rc = assuan_register_command (ctx, command_table[i]->name,
4989 command_table[i]->handler,
4990 command_table[i]->help);
4991 if (rc)
4992 return rc;
4995 rc = assuan_register_bye_notify (ctx, bye_notify);
4996 if (rc)
4997 return rc;
4999 rc = assuan_register_reset_notify (ctx, reset_notify);
5000 if (rc)
5001 return rc;
5003 rc = assuan_register_pre_cmd_notify (ctx, command_startup);
5004 if (rc)
5005 return rc;
5007 return assuan_register_post_cmd_notify (ctx, command_finalize);