Fix caching issue in commit 1175663.
[pwmd.git] / src / commands.c
blob88959bc9fb8206d211dcd15619ed01cb0c62e0f6
1 /*
2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013
3 Ben Kibbey <bjk@luxsci.net>
5 This file is part of pwmd.
7 Pwmd is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 2 of the License, or
10 (at your option) any later version.
12 Pwmd is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
20 #ifdef HAVE_CONFIG_H
21 #include <config.h>
22 #endif
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <unistd.h>
27 #include <err.h>
28 #include <errno.h>
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <fcntl.h>
32 #include <ctype.h>
33 #include <dirent.h>
34 #include <pthread.h>
35 #include <stdint.h>
37 #ifdef WITH_LIBACL
38 #include <sys/acl.h>
39 #endif
41 #include "pwmd-error.h"
42 #include <gcrypt.h>
44 #include "mem.h"
45 #include "xml.h"
46 #include "util-misc.h"
47 #include "common.h"
48 #include "rcfile.h"
49 #include "cache.h"
50 #include "commands.h"
51 #include "mutex.h"
52 #include "crypto.h"
53 #include "pinentry.h"
55 /* Flags needed to be retained for a client across commands. */
56 #define FLAG_NEW 0x0001
57 #define FLAG_HAS_LOCK 0x0002
58 #define FLAG_LOCK_CMD 0x0004
59 #define FLAG_NO_PINENTRY 0x0008
60 #define FLAG_OPEN 0x0010
61 #define FLAG_KEEP_LOCK 0x0020
63 /* These are command option flags. */
64 #define OPT_INQUIRE 0x0001
65 #define OPT_NO_PASSPHRASE 0x0002
66 #define OPT_RESET 0x0004
67 #define OPT_LIST_RECURSE 0x0008
68 #define OPT_LIST_VERBOSE 0x0010
69 #define OPT_LOCK 0x0020
70 #define OPT_LOCK_ON_OPEN 0x0040
71 #define OPT_SIGN 0x0080
72 #define OPT_LIST_ALL 0x0100
73 #define OPT_LIST_WITH_TARGET 0x0200
74 #define OPT_DATA 0x0400
75 #define OPT_NO_AGENT 0x0800
77 #ifdef WITH_AGENT
78 /* The GETCONFIG command, for example, may fail because pwmd lost the
79 * gpg-agent connection. Update the recovered agent ctx. */
80 #define UPDATE_AGENT_CTX(client, crypto) do { \
81 if (crypto && crypto->agent && crypto->agent->did_restart \
82 && client->crypto && client->crypto->agent \
83 && client->crypto->agent->ctx && \
84 crypto->agent->ctx != client->crypto->agent->ctx) \
85 { \
86 client->crypto->agent->ctx = crypto->agent->ctx; \
87 crypto->agent->ctx = NULL; \
88 } \
89 } while (0)
90 #else
91 #define UPDATE_AGENT_CTX(client, crypto)
92 #endif
94 struct command_table_s
96 const char *name;
97 gpg_error_t (*handler) (assuan_context_t, char *line);
98 const char *help;
99 int ignore_startup;
100 int unlock; // unlock the file mutex after validating the checksum
103 static struct command_table_s **command_table;
105 static gpg_error_t do_lock (struct client_s *client, int add);
106 static gpg_error_t validate_checksum (struct client_s *,
107 struct cache_data_s *);
108 static gpg_error_t update_checksum (struct client_s *client);
110 static gpg_error_t
111 unlock_file_mutex (struct client_s *client, int remove)
113 gpg_error_t rc = 0;
115 // OPEN: keep the lock for the same file being reopened.
116 if (client->flags & FLAG_KEEP_LOCK && client->flags & FLAG_HAS_LOCK)
117 return 0;
119 if (!(client->flags & FLAG_HAS_LOCK))
120 return GPG_ERR_NOT_LOCKED;
122 rc = cache_unlock_mutex (client->md5file, remove);
123 if (rc)
124 rc = GPG_ERR_INV_STATE;
125 else
126 client->flags &= ~(FLAG_HAS_LOCK | FLAG_LOCK_CMD);
128 return rc;
131 static gpg_error_t
132 lock_file_mutex (struct client_s *client, int add)
134 gpg_error_t rc = 0;
135 int timeout = config_get_integer (client->filename, "cache_timeout");
137 if (client->flags & FLAG_HAS_LOCK)
138 return 0;
140 rc = cache_lock_mutex (client->ctx, client->md5file,
141 client->lock_timeout, add, timeout);
142 if (!rc)
143 client->flags |= FLAG_HAS_LOCK;
145 return rc;
148 static gpg_error_t
149 file_modified (struct client_s *client, struct command_table_s *cmd)
151 gpg_error_t rc = 0;
153 if (!(client->flags & FLAG_OPEN))
154 return GPG_ERR_INV_STATE;
156 rc = lock_file_mutex (client, 0);
157 if (!rc || rc == GPG_ERR_NO_DATA)
159 rc = validate_checksum (client, NULL);
160 if (gpg_err_code (rc) == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
161 rc = 0;
162 else if (rc)
163 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
166 if ((cmd->unlock && !(client->flags & FLAG_HAS_LOCK)) || rc)
167 unlock_file_mutex (client, 0);
169 return rc;
172 static gpg_error_t
173 parse_xml (assuan_context_t ctx, int new)
175 struct client_s *client = assuan_get_pointer (ctx);
176 int cached = client->doc != NULL;
178 if (new)
180 client->doc = new_document ();
181 if (client->doc)
183 xmlChar *result;
184 int len;
186 xmlDocDumpFormatMemory (client->doc, &result, &len, 0);
187 client->crypto->plaintext = result;
188 client->crypto->plaintext_len = len;
189 if (!client->crypto->plaintext)
191 xmlFreeDoc (client->doc);
192 client->doc = NULL;
196 else if (!cached)
197 client->doc = parse_doc ((char *) client->crypto->plaintext,
198 client->crypto->plaintext_len);
200 return !client->doc ? GPG_ERR_ENOMEM : 0;
203 static void
204 free_client (struct client_s *client)
206 if (client->doc)
207 xmlFreeDoc (client->doc);
209 xfree (client->crc);
210 xfree (client->filename);
211 xfree (client->last_error);
213 if (client->crypto)
215 cleanup_crypto_stage2 (client->crypto);
216 if (client->crypto->pkey_sexp)
217 gcry_sexp_release (client->crypto->pkey_sexp);
219 client->crypto->pkey_sexp = NULL;
220 memset (client->crypto->sign_grip, 0,
221 sizeof (client->crypto->sign_grip));
222 memset (client->crypto->grip, 0, sizeof(client->crypto->grip));
225 if (client->xml_error)
226 xmlResetError (client->xml_error);
229 void
230 cleanup_client (struct client_s *client)
232 assuan_context_t ctx = client->ctx;
233 struct client_thread_s *thd = client->thd;
234 struct crypto_s *crypto = client->crypto;
235 long lock_timeout = client->lock_timeout;
236 int no_pinentry = (client->flags & FLAG_NO_PINENTRY);
237 struct pinentry_option_s pin_opts;
238 #ifdef WITH_AGENT
239 struct pinentry_option_s agent_pin_opts;
241 if (crypto && crypto->agent)
242 memcpy (&agent_pin_opts, &crypto->agent->pinentry_opts,
243 sizeof(struct pinentry_option_s));
244 #endif
246 memcpy (&pin_opts, &client->pinentry_opts, sizeof(struct pinentry_option_s));
247 unlock_file_mutex (client, client->flags & FLAG_NEW);
248 free_client (client);
249 memset (client, 0, sizeof (struct client_s));
250 client->crypto = crypto;
251 client->ctx = ctx;
252 client->thd = thd;
253 client->lock_timeout = lock_timeout;
254 memcpy (&client->pinentry_opts, &pin_opts, sizeof(struct pinentry_option_s));
255 client->flags |= no_pinentry ? FLAG_NO_PINENTRY : 0;
256 #ifdef WITH_AGENT
257 if (crypto && crypto->agent)
258 memcpy (&crypto->agent->pinentry_opts, &agent_pin_opts,
259 sizeof(struct pinentry_option_s));
260 #endif
263 static gpg_error_t
264 open_finalize (assuan_context_t ctx, char *key, size_t keylen)
266 struct client_s *client = assuan_get_pointer (ctx);
267 gpg_error_t rc = 0;
268 struct cache_data_s *cdata = cache_get_data (client->md5file);
269 int cached = 0, keyarg = key ? 1 : 0;
270 size_t keysize;
271 unsigned char *salted_key = NULL;
272 int algo;
273 int pin_try = 1;
274 int pin_tries = 3;
275 char *pin_title = client->pinentry_opts.title;
277 client->crypto->filename = str_dup (client->filename);
278 if (cdata || client->flags & FLAG_NEW)
280 if (cdata && !(client->flags & FLAG_NEW))
282 rc = decrypt_cache (client->crypto, cdata->doc, cdata->doclen);
283 if (rc)
284 return rc;
287 cached = cdata != NULL;
288 goto done;
291 if (!key && !IS_PKI (client->crypto)
292 && !(client->crypto->hdr.flags & PWMD_FLAG_NO_PASSPHRASE))
294 if (client->flags & FLAG_NO_PINENTRY)
296 rc = inquire_passphrase (ctx, "PASSPHRASE", (unsigned char **)&key,
297 &keylen);
298 if (rc)
299 return rc;
301 else
303 client->pinentry_opts.timeout = config_get_integer (client->filename,
304 "pinentry_timeout");
305 pin_again:
306 rc = getpin_common (client->ctx, client->filename, PINENTRY_OPEN,
307 &key, &keylen);
308 if (rc)
309 return rc;
313 if (!IS_PKI (client->crypto))
315 if (client->crypto->hdr.flags & PWMD_FLAG_NO_PASSPHRASE)
317 keylen = 1;
318 key = gcry_malloc (keylen);
319 memset (key, 0, keylen);
322 algo = cipher_to_gcrypt (client->crypto->hdr.flags);
323 rc = hash_key (algo, client->crypto->hdr.salt,
324 sizeof(client->crypto->hdr.salt), key, keylen,
325 (void **)&salted_key, &keysize);
326 if (!keyarg)
327 gcry_free (key);
329 if (!rc)
331 rc = decrypt_data (client->ctx, client->crypto, salted_key, keysize);
332 if (gpg_err_code (rc) == GPG_ERR_BAD_PASSPHRASE
333 && ++pin_try <= pin_tries && !(client->flags & FLAG_NO_PINENTRY))
335 gcry_free (salted_key);
336 salted_key = NULL;
337 key = NULL;
338 keylen = 0;
339 client->pinentry_opts.title = str_asprintf (_ ("Bad passphrase (try %i of %i)"), pin_try, pin_tries);
340 goto pin_again;
344 if (client->pinentry_opts.title != pin_title)
345 xfree (client->pinentry_opts.title);
347 client->pinentry_opts.title = pin_title;
348 if (rc)
350 gcry_free (salted_key);
351 return rc;
354 cdata = xcalloc (1, sizeof (struct cache_data_s));
355 if (!cdata)
357 gcry_free (salted_key);
358 return GPG_ERR_ENOMEM;
361 cdata->key = salted_key;
362 cdata->keylen = keysize;
364 else
365 rc = decrypt_data (client->ctx, client->crypto, NULL, 0);
367 done:
368 if (!rc)
370 rc = parse_xml (ctx, client->flags & FLAG_NEW);
371 if (!rc)
373 int timeout = config_get_integer (client->filename,
374 "cache_timeout");
376 if (!cached)
378 if (!cdata)
379 cdata = xcalloc (1, sizeof (struct cache_data_s));
381 rc = encrypt_xml (NULL, cache_key, cache_keysize,
382 GCRY_CIPHER_AES, client->crypto->plaintext,
383 client->crypto->plaintext_len, &cdata->doc,
384 &cdata->doclen, &cache_iv, &cache_blocksize,
386 if (!rc && !(client->flags & FLAG_NEW) && IS_PKI (client->crypto))
388 rc = gcry_sexp_build ((gcry_sexp_t *) & cdata->pubkey, NULL,
389 "%S", client->crypto->pkey_sexp);
393 if (cdata->sigkey)
394 gcry_sexp_release (cdata->sigkey);
396 cdata->sigkey = NULL;
397 if (!rc && IS_PKI (client->crypto))
398 rc = gcry_sexp_build ((gcry_sexp_t *) &cdata->sigkey, NULL,
399 "%S", client->crypto->sigpkey_sexp);
401 if (!rc && !cache_add_file (client->md5file,
402 (client->flags & FLAG_NEW)
403 ? NULL
404 : client->crypto->grip, cdata, timeout))
406 if (!cached)
408 free_cache_data_once (cdata);
409 xmlFreeDoc (client->doc);
410 client->doc = NULL;
412 rc = GPG_ERR_ENOMEM;
415 if (!rc)
416 client->flags |= FLAG_OPEN;
420 if (!rc)
421 update_checksum (client);
423 if (!rc && (client->opts & OPT_LOCK_ON_OPEN))
424 rc = do_lock (client, 0);
426 return rc;
429 static void
430 req_cleanup (void *arg)
432 if (!arg)
433 return;
435 strv_free ((char **) arg);
438 static gpg_error_t
439 parse_open_opt_lock (void *data, void *value)
441 struct client_s *client = data;
443 client->opts |= OPT_LOCK_ON_OPEN;
444 return 0;
447 static gpg_error_t
448 parse_opt_inquire (void *data, void *value)
450 struct client_s *client = data;
452 (void) value;
453 client->opts |= OPT_INQUIRE;
454 return 0;
457 static gpg_error_t
458 update_checksum (struct client_s *client)
460 unsigned char *crc;
461 size_t len;
462 struct cache_data_s *cdata;
463 gpg_error_t rc = get_checksum (client->filename, &crc, &len);
465 if (rc)
466 return rc;
468 xfree (client->crc);
469 client->crc = crc;
470 cdata = cache_get_data (client->md5file);
471 if (cdata)
473 xfree (cdata->crc);
474 cdata->crc = xmalloc (len);
475 memcpy (cdata->crc, crc, len);
478 return 0;
481 static gpg_error_t
482 validate_checksum (struct client_s *client, struct cache_data_s *cdata)
484 unsigned char *crc;
485 size_t len;
486 gpg_error_t rc;
487 int n = 0;
489 if (cdata && !cdata->crc)
490 return GPG_ERR_CHECKSUM;
492 rc = get_checksum (client->filename, &crc, &len);
493 if (rc)
494 return rc;
496 if (cdata)
497 n = memcmp (cdata->crc, crc, len);
498 else if (client->crc)
499 n = memcmp (client->crc, crc, len);
501 xfree (crc);
502 return n ? GPG_ERR_CHECKSUM : 0;
505 static gpg_error_t
506 do_open (assuan_context_t ctx, const char *filename, const char *password)
508 struct client_s *client = assuan_get_pointer (ctx);
509 struct cache_data_s *cdata;
510 gpg_error_t rc = 0;
511 int done = 0;
513 if (!valid_filename (filename))
514 return GPG_ERR_INV_VALUE;
516 gcry_md_hash_buffer (GCRY_MD_MD5, client->md5file, filename,
517 strlen (filename));
518 client->filename = str_dup (filename);
519 if (!client->filename)
520 return GPG_ERR_ENOMEM;
522 // Cached document?
523 cdata = cache_get_data (client->md5file);
524 if (cdata && cdata->doc)
526 int defer = 0;
528 /* This will check that the key is cached in the agent which needs to
529 * be determined for files that share a keygrip. */
530 if (!rc)
532 rc = cache_iscached (client->filename, &defer);
533 if ((!rc || rc == GPG_ERR_ENOENT) && defer)
534 rc = GPG_ERR_KEY_EXPIRED;
537 if (!rc && !(client->flags & FLAG_NEW))
538 rc = validate_checksum (client, cdata);
540 #ifdef WITH_GNUTLS
541 if (!rc && client->thd->remote
542 && config_get_boolean (client->filename, "tcp_require_key"))
543 rc = GPG_ERR_KEY_EXPIRED;
544 #endif
546 if (!rc && !password)
548 rc = read_data_header (client->filename, &client->crypto->hdr,
549 NULL, NULL);
550 if (!rc)
552 if (IS_PKI (client->crypto))
554 gcry_sexp_build (&client->crypto->pkey_sexp, NULL, "%S",
555 cdata->pubkey);
556 gcry_pk_get_keygrip (client->crypto->pkey_sexp,
557 client->crypto->grip);
558 gcry_sexp_build (&client->crypto->sigpkey_sexp, NULL, "%S",
559 cdata->sigkey);
560 gcry_pk_get_keygrip (client->crypto->sigpkey_sexp,
561 client->crypto->sign_grip);
564 if (!rc)
566 rc = open_finalize (ctx, NULL, 0);
567 done = 1;
572 /* There was an error accessing the file so clear the cache entry. The
573 * real error will be returned from read_data_file() since the file
574 * may have only disappeared. */
575 if (!done)
577 log_write ("%s: %s", filename, pwmd_strerror (rc));
578 rc = cache_clear (client->md5file);
579 send_status_all (STATUS_CACHE, NULL);
583 if (done || rc)
584 return rc;
586 rc = read_data_file (client->filename, client->crypto);
587 if (rc)
589 if (gpg_err_source (rc) != GPG_ERR_SOURCE_DEFAULT ||
590 gpg_err_code (rc) != GPG_ERR_ENOENT)
592 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
593 return rc;
596 client->flags |= FLAG_NEW;
597 memset (client->crypto->grip, 0, sizeof (client->crypto->grip));
598 memset (client->crypto->sign_grip, 0,
599 sizeof (client->crypto->sign_grip));
600 rc = open_finalize (ctx, NULL, 0);
601 return rc;
604 if (password && IS_PKI (client->crypto))
606 #ifdef WITH_AGENT
607 rc = set_agent_passphrase (client->crypto, password, strlen (password));
608 if (rc)
609 return rc;
610 #endif
613 rc = open_finalize (ctx, (char *)password, password ? strlen (password) : 0);
614 return rc;
617 static gpg_error_t
618 open_command (assuan_context_t ctx, char *line)
620 gpg_error_t rc;
621 struct client_s *client = assuan_get_pointer (ctx);
622 char **req, *password = NULL, *filename;
623 unsigned char md5file[16];
624 int same_file = 0;
625 struct argv_s *args[] = {
626 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_open_opt_lock},
627 NULL
630 rc = parse_options (&line, args, client);
631 if (rc)
632 return send_error (ctx, rc);
634 req = str_split (line, " ", 2);
635 if (!req)
636 return send_error (ctx, GPG_ERR_SYNTAX);
638 #ifdef WITH_GNUTLS
639 if (client->thd->remote)
641 rc = tls_validate_access (client, req[0]);
642 if (rc)
644 if (rc == GPG_ERR_INV_USER_ID)
645 log_write (_("client validation failed for file '%s'"), req[0]);
646 strv_free (req);
647 return send_error (ctx, rc);
650 /* Remote pinentries are not supported. */
651 client->flags |= FLAG_NO_PINENTRY;
653 else
655 #endif
656 assuan_peercred_t peer;
657 rc = do_validate_peer (ctx, req[0], &peer);
658 if (rc)
660 strv_free (req);
661 return send_error (ctx, rc);
663 #ifdef WITH_GNUTLS
665 #endif
667 pthread_cleanup_push (req_cleanup, req);
668 filename = req[0];
669 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
670 /* This client may have locked a different file with ISCACHED --lock than
671 * the current filename. This will remove that lock. */
672 same_file = !memcmp (md5file, client->md5file, 16) ? 1 : 0;
673 if (client->flags & FLAG_OPEN ||
674 (client->flags & FLAG_HAS_LOCK && !same_file))
676 typeof (client->opts) opts = client->opts;
677 typeof (client->flags) flags = client->flags;
679 if (same_file)
680 client->flags |= FLAG_KEEP_LOCK;
682 cleanup_client (client);
683 client->opts = opts;
684 client->flags |= flags;
685 client->flags &= ~(FLAG_LOCK_CMD);
686 if (!same_file)
687 client->flags &= ~(FLAG_HAS_LOCK | FLAG_NEW);
690 /* Need to lock the mutex here because file_modified() cannot without
691 * knowing the filename. */
692 memcpy (client->md5file, md5file, 16);
693 rc = lock_file_mutex (client, 1);
694 if (!rc)
696 password = req[1] && *req[1] ? req[1] : NULL;
697 #ifdef WITH_AGENT
698 if (IS_PKI (client->crypto))
699 rc = set_pinentry_mode (client->crypto->agent,
700 (client->flags & FLAG_NO_PINENTRY) ? "loopback"
701 : "ask");
702 #endif
703 if (!rc)
705 rc = do_open (ctx, filename, password);
706 if (rc)
707 cleanup_client (client);
709 cleanup_crypto_stage1 (client->crypto);
713 pthread_cleanup_pop (1);
715 if (!rc && client->flags & FLAG_NEW)
716 rc = send_status (ctx, STATUS_NEWFILE, NULL);
718 #ifdef WITH_AGENT
719 (void) kill_scd (client->crypto->agent);
720 #endif
721 return send_error (ctx, rc);
724 static gpg_error_t
725 parse_opt_no_passphrase (void *data, void *value)
727 struct client_s *client = data;
729 (void) value;
730 client->opts |= OPT_NO_PASSPHRASE;
731 return 0;
734 static gpg_error_t
735 parse_save_opt_no_agent (void *data, void *value)
737 struct client_s *client = data;
739 client->opts |= OPT_NO_AGENT;
740 return 0;
743 static gpg_error_t
744 parse_save_opt_cipher (void *data, void *value)
746 struct client_s *client = data;
747 int algo = cipher_string_to_gcrypt ((char *) value);
748 file_header_t *hdr = &client->crypto->save.hdr;
750 if (algo == -1)
751 return GPG_ERR_INV_VALUE;
753 hdr->flags = set_cipher_flag (hdr->flags, algo);
754 return 0;
757 static gpg_error_t
758 parse_save_opt_keygrip (void *data, void *value)
760 struct client_s *client = data;
762 if (!IS_PKI (client->crypto))
763 return GPG_ERR_INV_ARG;
765 #ifdef WITH_AGENT
766 if (client->crypto->save.pkey)
767 gcry_sexp_release (client->crypto->save.pkey);
769 client->crypto->save.pkey = NULL;
770 return get_pubkey (client->crypto, value, &client->crypto->save.pkey);
771 #else
772 return GPG_ERR_INV_ARG;
773 #endif
776 static gpg_error_t
777 parse_save_opt_sign_keygrip (void *data, void *value)
779 struct client_s *client = data;
781 if (!IS_PKI (client->crypto))
782 return GPG_ERR_INV_ARG;
784 #ifdef WITH_AGENT
785 if (client->crypto->save.sigpkey)
786 gcry_sexp_release (client->crypto->save.sigpkey);
788 client->crypto->save.sigpkey = NULL;
789 return get_pubkey (client->crypto, value, &client->crypto->save.sigpkey);
790 #else
791 return GPG_ERR_INV_ARG;
792 #endif
795 static gpg_error_t
796 parse_opt_s2k_count (void *data, void *value)
798 struct client_s *client = data;
799 char *v = value;
801 if (!v || !*v)
802 return GPG_ERR_INV_VALUE;
804 client->crypto->save.s2k_count = strtoul (v, NULL, 10);
805 return 0;
808 static gpg_error_t
809 parse_save_opt_iterations (void *data, void *value)
811 struct client_s *client = data;
812 char *v = value, *p;
813 uint64_t n;
815 if (!v || !*v)
816 return GPG_ERR_INV_VALUE;
818 errno = 0;
819 n = strtoull (v, &p, 10);
820 if (n == UINT64_MAX && errno)
821 return gpg_error_from_errno (errno);
822 else if (p && *p)
823 return GPG_ERR_INV_VALUE;
825 client->crypto->save.hdr.iterations = n;
826 return 0;
829 static gpg_error_t
830 save_finalize (assuan_context_t ctx)
832 struct client_s *client = assuan_get_pointer (ctx);
833 gpg_error_t rc = 0;
834 xmlChar *xmlbuf = NULL;
835 int xmlbuflen;
836 void *key = NULL;
837 size_t keylen = 0;
839 xmlDocDumpFormatMemory (client->doc, &xmlbuf, &xmlbuflen, 0);
840 if (!xmlbuf)
841 return GPG_ERR_ENOMEM;
843 pthread_cleanup_push (xmlFree, xmlbuf);
845 if (!use_agent || ((client->flags & FLAG_NEW)
846 && (client->opts & OPT_NO_AGENT))
847 || !(client->crypto->hdr.flags & PWMD_FLAG_PKI))
849 rc = export_common (ctx, client->flags & FLAG_NO_PINENTRY,
850 client->crypto, xmlbuf, xmlbuflen, client->filename,
851 NULL, &key, &keylen, 1, 1,
852 (client->opts & OPT_NO_PASSPHRASE));
854 #ifdef WITH_AGENT
855 else
857 gcry_sexp_t pubkey = client->crypto->save.pkey;
858 gcry_sexp_t sigkey = client->crypto->save.sigpkey;
860 if (!pubkey)
861 pubkey = client->crypto->pkey_sexp;
863 if (!sigkey)
865 sigkey = client->crypto->sigpkey_sexp;
866 if (!sigkey)
868 gcry_sexp_build (&client->crypto->save.sigpkey, 0, "%S", pubkey);
869 sigkey = client->crypto->save.sigpkey;
873 rc = encrypt_data_file (client->ctx, client->crypto, pubkey, sigkey,
874 client->filename, xmlbuf, xmlbuflen);
875 if (pubkey == client->crypto->save.pkey)
877 if (!rc)
879 gcry_sexp_release (client->crypto->pkey_sexp);
880 client->crypto->pkey_sexp = client->crypto->save.pkey;
881 gcry_pk_get_keygrip (client->crypto->pkey_sexp,
882 client->crypto->grip);
884 else
885 gcry_sexp_release (pubkey);
887 client->crypto->save.pkey = NULL;
890 if (!rc)
891 gcry_pk_get_keygrip (sigkey, client->crypto->sign_grip);
893 if (sigkey == client->crypto->save.sigpkey)
895 if (!rc)
897 if (client->crypto->sigpkey_sexp)
898 gcry_sexp_release (client->crypto->sigpkey_sexp);
900 client->crypto->sigpkey_sexp = client->crypto->save.sigpkey;
901 gcry_pk_get_keygrip (client->crypto->sigpkey_sexp,
902 client->crypto->sign_grip);
904 else
905 gcry_sexp_release (sigkey);
907 client->crypto->save.sigpkey = NULL;
910 #endif
912 if (!rc)
914 int cached;
916 rc = save_common (client->filename, client->crypto, xmlbuf, xmlbuflen,
917 key, keylen, &cached, client->opts & OPT_NO_AGENT);
918 if (rc)
919 gcry_free (key);
921 if (!rc && (!cached || (client->flags & FLAG_NEW)))
922 send_status_all (STATUS_CACHE, NULL);
924 if (!rc)
926 rc = update_checksum (client);
927 client->flags &= ~(FLAG_NEW);
931 pthread_cleanup_pop (1); // xmlFree
932 return rc;
935 static gpg_error_t
936 parse_opt_reset (void *data, void *value)
938 struct client_s *client = data;
940 (void) value;
941 client->opts |= OPT_RESET;
942 return 0;
945 static gpg_error_t
946 save_command (assuan_context_t ctx, char *line)
948 struct client_s *client = assuan_get_pointer (ctx);
949 gpg_error_t rc;
950 struct stat st;
951 struct argv_s *args[] = {
952 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG,
953 parse_opt_no_passphrase},
954 &(struct argv_s) {"cipher", OPTION_TYPE_ARG, parse_save_opt_cipher},
955 &(struct argv_s) {"inquire-keyparam", OPTION_TYPE_NOARG,
956 parse_opt_inquire},
957 &(struct argv_s) {"keygrip", OPTION_TYPE_ARG, parse_save_opt_keygrip},
958 &(struct argv_s) {"sign-keygrip", OPTION_TYPE_ARG,
959 parse_save_opt_sign_keygrip},
960 &(struct argv_s) {"s2k-count", OPTION_TYPE_ARG, parse_opt_s2k_count},
961 &(struct argv_s) {"reset", OPTION_TYPE_NOARG, parse_opt_reset},
962 &(struct argv_s) {"cipher-iterations", OPTION_TYPE_ARG,
963 parse_save_opt_iterations},
964 &(struct argv_s) {"no-agent", OPTION_TYPE_NOARG,
965 parse_save_opt_no_agent},
966 NULL
969 cleanup_save (&client->crypto->save);
970 memcpy (&client->crypto->save.hdr, &client->crypto->hdr,
971 sizeof (file_header_t));
972 client->crypto->save.s2k_count =
973 config_get_ulong (client->filename, "s2k_count");
975 if (client->flags & FLAG_NEW)
976 client->crypto->save.hdr.iterations =
977 config_get_ulonglong (client->filename, "cipher_iterations");
979 rc = parse_options (&line, args, client);
980 if (rc)
981 return send_error (ctx, rc);
983 if (!(client->flags & FLAG_NEW))
984 client->opts &= ~OPT_NO_AGENT;
985 else if (client->opts & OPT_NO_AGENT)
987 client->crypto->save.hdr.flags &= ~PWMD_FLAG_PKI;
988 client->crypto->hdr.flags &= ~PWMD_FLAG_PKI;
991 if ((client->opts & OPT_NO_PASSPHRASE) && !(client->flags & FLAG_NEW)
992 && !(client->opts & OPT_INQUIRE))
993 return send_error (ctx, GPG_ERR_WRONG_KEY_USAGE);
995 if (lstat (client->filename, &st) == -1 && errno != ENOENT)
996 return send_error (ctx, gpg_error_from_errno (errno));
998 if (errno != ENOENT && !S_ISREG (st.st_mode))
1000 log_write ("%s: %s", client->filename, pwmd_strerror (GPG_ERR_ENOANO));
1001 return send_error (ctx, GPG_ERR_ENOANO);
1004 int defer = 0;
1005 rc = cache_iscached (client->filename, &defer);
1006 if (gpg_err_code (rc) == GPG_ERR_ENOENT && client->flags & FLAG_NEW)
1007 rc = 0;
1008 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
1009 rc = 0;
1011 if ((!rc && defer) || config_get_boolean ("global", "require_save_key"))
1012 client->opts |= OPT_RESET;
1014 if (!rc && (client->opts & OPT_RESET))
1016 rc = cache_clear (client->md5file);
1017 if (rc)
1018 return send_error (ctx, rc);
1020 log_write ("%s: %s", client->filename,
1021 pwmd_strerror (GPG_ERR_KEY_EXPIRED));
1022 send_status_all (STATUS_CACHE, NULL);
1025 if (!rc)
1026 rc = update_element_mtime (xmlDocGetRootElement (client->doc));
1028 if (rc)
1029 return send_error (ctx, rc);
1031 #ifdef WITH_AGENT
1032 if (!rc && use_agent && !client->crypto->save.pkey &&
1033 (client->flags & FLAG_NEW || client->opts & OPT_INQUIRE)
1034 && !(client->opts & OPT_NO_AGENT))
1036 rc = set_pinentry_mode (client->crypto->agent,
1037 (client->flags & FLAG_NO_PINENTRY) ? "loopback"
1038 : "ask");
1040 if (!(client->flags & FLAG_NEW))
1042 struct crypto_s *crypto;
1043 char *key = NULL;
1044 size_t keylen = 0;
1046 /* Wanting to generate a new key. Require the key to open the
1047 current file before proceeding reguardless of the
1048 require_save_key configuration parameter. */
1049 rc = cache_clear (client->md5file);
1050 if (!rc)
1052 rc = init_client_crypto (&crypto);
1053 if (!rc)
1054 crypto->client_ctx = client->ctx;
1057 if (!rc)
1058 rc = decrypt_common (client->ctx, client->opts&OPT_INQUIRE, crypto,
1059 client->filename, &key, &keylen);
1061 xfree (key);
1062 cleanup_crypto (&crypto);
1065 if (!rc)
1066 rc = send_status (client->ctx, STATUS_GENKEY, NULL);
1068 if (!rc)
1070 struct inquire_data_s idata = { 0 };
1071 char *params = client->opts & OPT_INQUIRE
1072 ? NULL : default_key_params (client->crypto);
1074 pthread_cleanup_push (xfree, params);
1075 idata.crypto = client->crypto;
1077 if (params)
1079 idata.line = params;
1080 idata.len = strlen (params);
1082 else
1083 idata.preset = 1;
1085 client->crypto->agent->inquire_data = &idata;
1086 client->crypto->agent->inquire_cb = NULL;
1087 rc = generate_key (client->crypto, params,
1088 (client->opts & OPT_NO_PASSPHRASE), 1);
1089 pthread_cleanup_pop (1);
1092 #endif
1094 if (!rc)
1095 rc = save_finalize (ctx);
1097 cleanup_crypto_stage1 (client->crypto);
1098 #ifdef WITH_AGENT
1099 (void) kill_scd (client->crypto->agent);
1100 #endif
1101 return send_error (ctx, rc);
1104 static gpg_error_t
1105 do_delete (assuan_context_t ctx, char *line)
1107 struct client_s *client = assuan_get_pointer (ctx);
1108 gpg_error_t rc;
1109 char **req;
1110 xmlNodePtr n;
1112 if (strchr (line, '\t'))
1113 req = str_split (line, "\t", 0);
1114 else
1115 req = str_split (line, " ", 0);
1117 if (!req || !*req)
1118 return GPG_ERR_SYNTAX;
1120 n = find_root_element (client->doc, &req, &rc, NULL, 0, 0);
1121 if (!n)
1123 strv_free (req);
1124 return rc;
1128 * No sub-node defined. Remove the entire node (root element).
1130 if (!req[1])
1132 if (n)
1134 rc = unlink_node (n);
1135 xmlFreeNode (n);
1138 strv_free (req);
1139 return rc;
1143 find_elements (client->doc, n->children, req + 1, &rc, NULL, NULL, NULL,
1144 0, 0, NULL, 0);
1145 strv_free (req);
1146 if (!n)
1147 return rc;
1149 if (n)
1151 rc = unlink_node (n);
1152 xmlFreeNode (n);
1155 return rc;
1158 static gpg_error_t
1159 delete_command (assuan_context_t ctx, char *line)
1161 struct client_s *client = assuan_get_pointer (ctx);
1162 gpg_error_t rc;
1163 struct argv_s *args[] = {
1164 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1165 NULL
1168 rc = parse_options (&line, args, client);
1169 if (rc)
1170 return send_error (ctx, rc);
1172 if (client->opts & OPT_INQUIRE)
1174 unsigned char *result;
1175 size_t len;
1177 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1178 if (rc)
1179 return send_error (ctx, rc);
1181 line = (char *) result;
1184 rc = do_delete (ctx, line);
1186 if (client->opts & OPT_INQUIRE)
1187 xfree (line);
1189 return send_error (ctx, rc);
1192 static gpg_error_t
1193 store_command (assuan_context_t ctx, char *line)
1195 struct client_s *client = assuan_get_pointer (ctx);
1196 gpg_error_t rc;
1197 size_t len;
1198 unsigned char *result;
1199 char **req;
1200 xmlNodePtr n, parent;
1201 int has_content;
1202 char *content = NULL;
1204 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1205 if (rc)
1206 return send_error (ctx, rc);
1208 req = str_split ((char *) result, "\t", 0);
1209 xfree (result);
1211 if (!req || !*req)
1212 return send_error (ctx, GPG_ERR_SYNTAX);
1214 len = strv_length (req);
1215 has_content = line[strlen (line) - 1] != '\t' && len > 1;
1216 if (*(req + 1) && !valid_element_path (req, has_content))
1218 strv_free (req);
1219 return send_error (ctx, GPG_ERR_INV_VALUE);
1222 if (has_content || !*req[len - 1])
1224 has_content = 1;
1225 content = req[len - 1];
1226 req[len - 1] = NULL;
1229 again:
1230 n = find_root_element (client->doc, &req, &rc, NULL, 0, 0);
1231 if (rc && rc == GPG_ERR_ELEMENT_NOT_FOUND)
1233 rc = new_root_element (client->doc, *req);
1234 if (rc)
1236 strv_free (req);
1237 return send_error (ctx, GPG_ERR_SYNTAX);
1240 goto again;
1243 if (!n)
1245 strv_free (req);
1246 return send_error (ctx, rc);
1249 parent = n;
1251 if (req[1] && *req[1])
1253 if (!n->children)
1254 parent = create_elements_cb (n, req + 1, &rc, NULL);
1255 else
1256 parent = find_elements (client->doc, n->children, req + 1, &rc,
1257 NULL, NULL, create_elements_cb, 0, 0, NULL,
1261 if (!rc && len > 1)
1263 n = find_text_node (parent->children);
1264 if (n)
1265 xmlNodeSetContent (n, (xmlChar *) content);
1266 else
1267 xmlNodeAddContent (parent, (xmlChar *) content);
1269 update_element_mtime (parent);
1272 xfree (content);
1273 strv_free (req);
1274 return send_error (ctx, rc);
1277 static gpg_error_t
1278 xfer_data (assuan_context_t ctx, const char *line, int total)
1280 int to_send;
1281 int sent = 0;
1282 gpg_error_t rc;
1283 int progress = config_get_integer ("global", "xfer_progress");
1284 int flush = 0;
1286 progress =
1287 progress > 0 ? (progress / ASSUAN_LINELENGTH) * ASSUAN_LINELENGTH : 0;
1288 to_send = total < ASSUAN_LINELENGTH ? total : ASSUAN_LINELENGTH;
1289 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1291 if (rc)
1292 return rc;
1294 again:
1297 if (sent + to_send > total)
1298 to_send = total - sent;
1300 rc = assuan_send_data (ctx, flush ? NULL : (char *) line + sent,
1301 flush ? 0 : to_send);
1302 if (!rc)
1304 sent += flush ? 0 : to_send;
1306 if ((progress && !(sent % progress) && sent != total) ||
1307 (sent == total && flush))
1308 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1310 if (!flush && !rc && sent == total)
1312 flush = 1;
1313 goto again;
1317 while (!rc && sent < total);
1319 return rc;
1322 static gpg_error_t
1323 do_get (assuan_context_t ctx, char *line)
1325 struct client_s *client = assuan_get_pointer (ctx);
1326 gpg_error_t rc;
1327 char **req;
1328 xmlNodePtr n;
1330 req = str_split (line, "\t", 0);
1332 if (!req || !*req)
1334 strv_free (req);
1335 return GPG_ERR_SYNTAX;
1338 n = find_root_element (client->doc, &req, &rc, NULL, 0, 0);
1339 if (!n)
1341 strv_free (req);
1342 return rc;
1345 if (req[1])
1347 find_elements (client->doc, n->children, req + 1, &rc, NULL, NULL, NULL,
1348 0, 0, NULL, 0);
1350 strv_free (req);
1351 if (rc)
1352 return rc;
1354 if (!n || !n->children)
1355 return GPG_ERR_NO_DATA;
1357 n = find_text_node (n->children);
1358 if (!n || !n->content || !*n->content)
1359 return GPG_ERR_NO_DATA;
1361 rc = xfer_data (ctx, (char *) n->content, xmlStrlen (n->content));
1362 return rc;
1365 static gpg_error_t
1366 get_command (assuan_context_t ctx, char *line)
1368 struct client_s *client = assuan_get_pointer (ctx);
1369 gpg_error_t rc;
1370 struct argv_s *args[] = {
1371 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1372 NULL
1375 rc = parse_options (&line, args, client);
1376 if (rc)
1377 return send_error (ctx, rc);
1379 if (client->opts & OPT_INQUIRE)
1381 unsigned char *result;
1382 size_t len;
1384 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1385 if (rc)
1386 return send_error (ctx, rc);
1388 line = (char *) result;
1391 rc = do_get (ctx, line);
1393 if (client->opts & OPT_INQUIRE)
1394 xfree (line);
1396 return send_error (ctx, rc);
1399 static void list_command_cleanup1 (void *arg);
1400 static gpg_error_t
1401 realpath_command (assuan_context_t ctx, char *line)
1403 struct string_s *string = NULL;
1404 gpg_error_t rc;
1405 struct client_s *client = assuan_get_pointer (ctx);
1406 struct argv_s *args[] = {
1407 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1408 NULL
1411 rc = parse_options (&line, args, client);
1412 if (rc)
1413 return send_error (ctx, rc);
1415 if (client->opts & OPT_INQUIRE)
1417 unsigned char *result;
1418 size_t len;
1420 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1421 if (rc)
1422 return send_error (ctx, rc);
1424 line = (char *) result;
1427 rc = build_realpath (client->doc, line, &string);
1428 if (!rc)
1430 pthread_cleanup_push (list_command_cleanup1, string);
1431 rc = xfer_data (ctx, string->str, string->len);
1432 pthread_cleanup_pop (1);
1435 if (client->opts & OPT_INQUIRE)
1436 xfree (line);
1438 return send_error (ctx, rc);
1441 static void
1442 list_command_cleanup1 (void *arg)
1444 if (arg)
1445 string_free ((struct string_s *) arg, 1);
1448 static void
1449 list_command_cleanup2 (void *arg)
1451 struct element_list_s *elements = arg;
1453 if (elements)
1455 if (elements->list)
1457 int total = slist_length (elements->list);
1458 int i;
1460 for (i = 0; i < total; i++)
1462 char *tmp = slist_nth_data (elements->list, i);
1463 xfree (tmp);
1466 slist_free (elements->list);
1469 if (elements->prefix)
1470 xfree (elements->prefix);
1472 if (elements->req)
1473 strv_free (elements->req);
1475 xfree (elements);
1479 static gpg_error_t
1480 parse_list_opt_norecurse (void *data, void *value)
1482 struct client_s *client = data;
1484 client->opts &= ~(OPT_LIST_RECURSE);
1485 return 0;
1488 static gpg_error_t
1489 parse_list_opt_verbose (void *data, void *value)
1491 struct client_s *client = data;
1493 client->opts |= OPT_LIST_VERBOSE;
1494 return 0;
1497 static gpg_error_t
1498 parse_list_opt_target (void *data, void *value)
1500 struct client_s *client = data;
1502 client->opts |= OPT_LIST_WITH_TARGET;
1503 return 0;
1506 static gpg_error_t
1507 parse_list_opt_all (void *data, void *value)
1509 struct client_s *client = data;
1511 client->opts |= OPT_LIST_ALL;
1512 return 0;
1515 static gpg_error_t
1516 list_path_once (struct client_s *client, char *line,
1517 struct element_list_s *elements, struct string_s *result)
1519 gpg_error_t rc;
1521 elements->req = str_split (line, " ", 0);
1522 if (!elements->req)
1523 strv_printf (&elements->req, "%s", line);
1525 rc = create_path_list (client->doc, elements, *elements->req);
1526 if (rc == GPG_ERR_ELOOP && elements->verbose)
1527 rc = 0;
1529 if (!rc)
1531 int total = slist_length (elements->list);
1532 int i;
1534 if (!total)
1535 rc = GPG_ERR_NO_DATA;
1537 if (!rc)
1539 if (!rc)
1541 for (i = 0; i < total; i++)
1543 char *tmp = slist_nth_data (elements->list, i);
1545 string_append_printf (result, "%s%s", tmp,
1546 i + 1 == total ? "" : "\n");
1550 else
1551 rc = GPG_ERR_NO_DATA;
1554 return rc;
1557 static int
1558 has_list_flag (char *path, char *flags)
1560 char *p = path;
1562 while (*p && *++p != ' ');
1564 if (!*p)
1565 return 0;
1567 for (; *p; p++)
1569 char *f;
1571 for (f = flags; *f && *f != ' '; f++)
1573 if (*p == *f)
1574 return 1;
1578 return 0;
1581 static gpg_error_t
1582 do_list (assuan_context_t ctx, char *line)
1584 struct client_s *client = assuan_get_pointer (ctx);
1585 gpg_error_t rc;
1586 struct element_list_s *elements = NULL;
1588 elements = xcalloc (1, sizeof (struct element_list_s));
1589 if (!elements)
1590 return GPG_ERR_ENOMEM;
1592 elements->recurse = client->opts & OPT_LIST_RECURSE;
1593 elements->verbose =
1594 (client->opts & OPT_LIST_VERBOSE) | (client->opts & OPT_LIST_WITH_TARGET);
1595 elements->with_target = client->opts & OPT_LIST_WITH_TARGET;
1597 if (!line || !*line)
1599 struct string_s *str = NULL;
1601 pthread_cleanup_push (list_command_cleanup2, elements);
1602 rc = list_root_elements (client->doc, &str, elements->verbose,
1603 elements->with_target);
1604 pthread_cleanup_pop (1);
1605 pthread_cleanup_push (list_command_cleanup1, str);
1607 if (!rc)
1609 if (client->opts & OPT_LIST_ALL)
1611 char **roots = str_split (str->str, "\n", 0);
1612 char **p;
1614 pthread_cleanup_push (req_cleanup, roots);
1615 string_truncate (str, 0);
1617 for (p = roots; *p; p++)
1619 if (strchr (*p, ' '))
1621 if (has_list_flag (*p, "EO"))
1623 string_append_printf (str, "%s%s", *p,
1624 *(p + 1) ? "\n" : "");
1625 continue;
1629 elements = xcalloc (1, sizeof (struct element_list_s));
1630 if (!elements)
1632 rc = GPG_ERR_ENOMEM;
1633 break;
1636 elements->recurse = client->opts & OPT_LIST_RECURSE;
1637 elements->verbose =
1638 (client->opts & OPT_LIST_VERBOSE) | (client->opts &
1639 OPT_LIST_WITH_TARGET);
1640 elements->with_target = client->opts & OPT_LIST_WITH_TARGET;
1641 pthread_cleanup_push (list_command_cleanup2, elements);
1642 rc = list_path_once (client, *p, elements, str);
1643 pthread_cleanup_pop (1);
1644 if (rc)
1645 break;
1647 if (*(p + 1))
1648 string_append (str, "\n");
1651 pthread_cleanup_pop (1);
1654 if (!rc)
1655 rc = xfer_data (ctx, str->str, str->len);
1658 pthread_cleanup_pop (1);
1659 return rc;
1662 pthread_cleanup_push (list_command_cleanup2, elements);
1663 struct string_s *str = string_new (NULL);
1664 pthread_cleanup_push (list_command_cleanup1, str);
1665 rc = list_path_once (client, line, elements, str);
1666 if (!rc)
1667 rc = xfer_data (ctx, str->str, str->len);
1669 pthread_cleanup_pop (1);
1670 pthread_cleanup_pop (1);
1671 return rc;
1674 static gpg_error_t
1675 list_command (assuan_context_t ctx, char *line)
1677 struct client_s *client = assuan_get_pointer (ctx);
1678 gpg_error_t rc;
1679 struct argv_s *args[] = {
1680 &(struct argv_s) {"no-recurse", OPTION_TYPE_NOARG,
1681 parse_list_opt_norecurse},
1682 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_list_opt_verbose},
1683 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1684 &(struct argv_s) {"with-target", OPTION_TYPE_NOARG,
1685 parse_list_opt_target},
1686 &(struct argv_s) {"all", OPTION_TYPE_NOARG, parse_list_opt_all},
1687 NULL
1690 if (disable_list_and_dump == 1)
1691 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
1693 client->opts |= OPT_LIST_RECURSE;
1694 rc = parse_options (&line, args, client);
1695 if (rc)
1696 return send_error (ctx, rc);
1698 if (client->opts & OPT_LIST_ALL)
1699 client->opts |= OPT_LIST_RECURSE | OPT_LIST_VERBOSE;
1701 if (client->opts & OPT_INQUIRE)
1703 unsigned char *result;
1704 size_t len;
1706 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1707 if (rc)
1708 return send_error (ctx, rc);
1710 line = (char *) result;
1713 rc = do_list (ctx, line);
1715 if (client->opts & OPT_INQUIRE)
1716 xfree (line);
1718 return send_error (ctx, rc);
1722 * req[0] - element path
1724 static gpg_error_t
1725 attribute_list (assuan_context_t ctx, char **req)
1727 struct client_s *client = assuan_get_pointer (ctx);
1728 char **attrlist = NULL;
1729 int i = 0;
1730 char **path = NULL;
1731 xmlAttrPtr a;
1732 xmlNodePtr n, an;
1733 char *line;
1734 gpg_error_t rc;
1736 if (!req || !req[0])
1737 return GPG_ERR_SYNTAX;
1739 if ((path = str_split (req[0], "\t", 0)) == NULL)
1742 * The first argument may be only a root element.
1744 if ((path = str_split (req[0], " ", 0)) == NULL)
1745 return GPG_ERR_SYNTAX;
1748 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
1750 if (!n)
1752 strv_free (path);
1753 return rc;
1756 if (path[1])
1758 n = find_elements (client->doc, n->children, path + 1, &rc,
1759 NULL, NULL, NULL, 0, 0, NULL, 0);
1761 if (!n)
1763 strv_free (path);
1764 return rc;
1768 strv_free (path);
1770 for (a = n->properties; a; a = a->next)
1772 char **pa;
1774 if ((pa = xrealloc (attrlist, (i + 2) * sizeof (char *))) == NULL)
1776 if (attrlist)
1777 strv_free (attrlist);
1779 log_write ("%s(%i): %s", __FILE__, __LINE__,
1780 pwmd_strerror (GPG_ERR_ENOMEM));
1781 return GPG_ERR_ENOMEM;
1784 attrlist = pa;
1785 an = a->children;
1786 attrlist[i] = str_asprintf ("%s %s", (char *) a->name,
1788 && an->content ? (char *) an->content : "");
1790 if (!attrlist[i])
1792 strv_free (attrlist);
1793 log_write ("%s(%i): %s", __FILE__, __LINE__,
1794 pwmd_strerror (GPG_ERR_ENOMEM));
1795 return GPG_ERR_ENOMEM;
1798 attrlist[++i] = NULL;
1801 if (!attrlist)
1802 return GPG_ERR_NO_DATA;
1804 line = strv_join ("\n", attrlist);
1806 if (!line)
1808 log_write ("%s(%i): %s", __FILE__, __LINE__,
1809 pwmd_strerror (GPG_ERR_ENOMEM));
1810 strv_free (attrlist);
1811 return GPG_ERR_ENOMEM;
1814 pthread_cleanup_push (xfree, line);
1815 pthread_cleanup_push (req_cleanup, attrlist);
1816 rc = xfer_data (ctx, line, strlen (line));
1817 pthread_cleanup_pop (1);
1818 pthread_cleanup_pop (1);
1819 return rc;
1823 * req[0] - attribute
1824 * req[1] - element path
1826 static gpg_error_t
1827 attribute_delete (struct client_s *client, char **req)
1829 xmlNodePtr n;
1830 char **path = NULL;
1831 gpg_error_t rc;
1833 if (!req || !req[0] || !req[1])
1834 return GPG_ERR_SYNTAX;
1836 if (!strcmp (req[0], "_name"))
1837 return GPG_ERR_INV_ATTR;
1839 if ((path = str_split (req[1], "\t", 0)) == NULL)
1842 * The first argument may be only a root element.
1844 if ((path = str_split (req[1], " ", 0)) == NULL)
1845 return GPG_ERR_SYNTAX;
1848 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
1849 if (!n)
1850 goto fail;
1852 if (path[1])
1854 n = find_elements (client->doc, n->children, path + 1, &rc,
1855 NULL, NULL, NULL, 0, 0, NULL, 0);
1856 if (!n)
1857 goto fail;
1860 rc = delete_attribute (n, (xmlChar *) req[0]);
1862 fail:
1863 strv_free (path);
1864 return rc;
1867 static xmlNodePtr
1868 create_element_path (struct client_s *client,
1869 char ***elements, gpg_error_t * rc, xmlNodePtr parent)
1871 char **req = *elements;
1872 char **req_orig = strv_dup (req);
1873 xmlNodePtr n = NULL;
1875 *rc = 0;
1877 if (!req_orig)
1879 *rc = GPG_ERR_ENOMEM;
1880 log_write ("%s(%i): %s", __FILE__, __LINE__,
1881 pwmd_strerror (GPG_ERR_ENOMEM));
1882 goto fail;
1885 again:
1886 n = find_root_element (client->doc, &req, rc, NULL, 0, 0);
1887 if (!n)
1889 if (*rc != GPG_ERR_ELEMENT_NOT_FOUND)
1890 goto fail;
1892 *rc = new_root_element (client->doc, req[0]);
1893 if (*rc)
1894 goto fail;
1896 goto again;
1898 else if (n == parent)
1900 *rc = GPG_ERR_CONFLICT;
1901 goto fail;
1904 if (req[1])
1906 if (!n->children)
1907 n = create_target_elements_cb (n, req + 1, rc, NULL);
1908 else
1909 n = find_elements (client->doc, n->children, req + 1, rc, NULL, NULL,
1910 create_target_elements_cb, 0, 0, parent, 0);
1912 if (!n)
1913 goto fail;
1916 * Reset the position of the element tree now that the elements
1917 * have been created.
1919 strv_free (req);
1920 req = req_orig;
1921 req_orig = NULL;
1922 n = find_root_element (client->doc, &req, rc, NULL, 0, 0);
1923 if (!n)
1924 goto fail;
1926 n = find_elements (client->doc, n->children, req + 1, rc,
1927 NULL, NULL, NULL, 0, 0, NULL, 0);
1928 if (!n)
1929 goto fail;
1932 fail:
1933 if (req_orig)
1934 strv_free (req_orig);
1936 *elements = req;
1937 return n;
1941 * Creates a "target" attribute. When other commands encounter an element with
1942 * this attribute, the element path is modified to the target value. If the
1943 * source element path doesn't exist when using 'ATTR SET target', it is
1944 * created, but the destination element path must exist.
1946 * req[0] - source element path
1947 * req[1] - destination element path
1949 static gpg_error_t
1950 target_attribute (struct client_s *client, char **req)
1952 char **src, **dst, *line = NULL, **odst = NULL;
1953 gpg_error_t rc;
1954 xmlNodePtr n;
1956 if (!req || !req[0] || !req[1])
1957 return GPG_ERR_SYNTAX;
1959 if ((src = str_split (req[0], "\t", 0)) == NULL)
1962 * The first argument may be only a root element.
1964 if ((src = str_split (req[0], " ", 0)) == NULL)
1965 return GPG_ERR_SYNTAX;
1968 if (!valid_element_path (src, 0))
1969 return GPG_ERR_INV_VALUE;
1971 if ((dst = str_split (req[1], "\t", 0)) == NULL)
1974 * The first argument may be only a root element.
1976 if ((dst = str_split (req[1], " ", 0)) == NULL)
1978 rc = GPG_ERR_SYNTAX;
1979 goto fail;
1983 odst = strv_dup (dst);
1984 if (!odst)
1986 rc = GPG_ERR_ENOMEM;
1987 goto fail;
1990 n = find_root_element (client->doc, &dst, &rc, NULL, 0, 0);
1992 * Make sure the destination element path exists.
1994 if (!n)
1995 goto fail;
1997 if (dst[1])
1999 n = find_elements (client->doc, n->children, dst + 1, &rc,
2000 NULL, NULL, NULL, 0, 0, NULL, 0);
2001 if (!n)
2002 goto fail;
2005 rc = validate_target_attribute (client->doc, req[0], n);
2006 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2007 goto fail;
2009 n = create_element_path (client, &src, &rc, NULL);
2010 if (rc)
2011 goto fail;
2013 line = strv_join ("\t", odst);
2014 if (!line)
2016 rc = GPG_ERR_ENOMEM;
2017 goto fail;
2020 rc = add_attribute (n, "target", line);
2022 fail:
2023 xfree (line);
2024 strv_free (src);
2025 strv_free (dst);
2026 strv_free (odst);
2027 return rc;
2031 * req[0] - attribute
2032 * req[1] - element path
2034 static gpg_error_t
2035 attribute_get (assuan_context_t ctx, char **req)
2037 struct client_s *client = assuan_get_pointer (ctx);
2038 xmlNodePtr n;
2039 xmlChar *a;
2040 char **path = NULL;
2041 gpg_error_t rc;
2043 if (!req || !req[0] || !req[1])
2044 return GPG_ERR_SYNTAX;
2046 if (strchr (req[1], '\t'))
2048 if ((path = str_split (req[1], "\t", 0)) == NULL)
2049 return GPG_ERR_SYNTAX;
2051 else
2053 if ((path = str_split (req[1], " ", 0)) == NULL)
2054 return GPG_ERR_SYNTAX;
2057 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
2059 if (!n)
2060 goto fail;
2062 if (path[1])
2064 n = find_elements (client->doc, n->children, path + 1, &rc,
2065 NULL, NULL, NULL, 0, 0, NULL, 0);
2067 if (!n)
2068 goto fail;
2071 strv_free (path);
2073 if ((a = xmlGetProp (n, (xmlChar *) req[0])) == NULL)
2074 return GPG_ERR_NOT_FOUND;
2076 pthread_cleanup_push (xmlFree, a);
2078 if (*a)
2079 rc = xfer_data (ctx, (char *) a, xmlStrlen (a));
2080 else
2081 rc = GPG_ERR_NO_DATA;
2083 pthread_cleanup_pop (1);
2084 return rc;
2086 fail:
2087 strv_free (path);
2088 return rc;
2092 * req[0] - attribute
2093 * req[1] - element path
2094 * req[2] - value
2096 static gpg_error_t
2097 attribute_set (struct client_s *client, char **req)
2099 char **path = NULL;
2100 gpg_error_t rc;
2101 xmlNodePtr n;
2103 if (!req || !req[0] || !req[1])
2104 return GPG_ERR_SYNTAX;
2107 * Reserved attribute names.
2109 if (!strcmp (req[0], "_name"))
2110 return GPG_ERR_INV_ATTR;
2111 else if (!strcmp (req[0], "target"))
2112 return target_attribute (client, req + 1);
2114 if ((path = str_split (req[1], "\t", 0)) == NULL)
2117 * The first argument may be only a root element.
2119 if ((path = str_split (req[1], " ", 0)) == NULL)
2120 return GPG_ERR_SYNTAX;
2123 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
2125 if (!n)
2126 goto fail;
2128 if (path[1])
2130 n = find_elements (client->doc, n->children, path + 1, &rc,
2131 NULL, NULL, NULL, 0, 0, NULL, 0);
2133 if (!n)
2134 goto fail;
2137 rc = add_attribute (n, req[0], req[2]);
2139 fail:
2140 strv_free (path);
2141 return rc;
2145 * req[0] - command
2146 * req[1] - attribute name or element path if command is LIST
2147 * req[2] - element path
2148 * req[2] - element path or value
2151 static gpg_error_t
2152 do_attr (assuan_context_t ctx, char *line)
2154 struct client_s *client = assuan_get_pointer (ctx);
2155 gpg_error_t rc = 0;
2156 char **req;
2158 req = str_split (line, " ", 4);
2159 if (!req || !req[0] || !req[1])
2161 strv_free (req);
2162 return GPG_ERR_SYNTAX;
2165 pthread_cleanup_push (req_cleanup, req);
2167 if (strcasecmp (req[0], "SET") == 0)
2168 rc = attribute_set (client, req + 1);
2169 else if (strcasecmp (req[0], "GET") == 0)
2170 rc = attribute_get (ctx, req + 1);
2171 else if (strcasecmp (req[0], "DELETE") == 0)
2172 rc = attribute_delete (client, req + 1);
2173 else if (strcasecmp (req[0], "LIST") == 0)
2174 rc = attribute_list (ctx, req + 1);
2175 else
2176 rc = GPG_ERR_SYNTAX;
2178 pthread_cleanup_pop (1);
2179 return rc;
2182 static gpg_error_t
2183 attr_command (assuan_context_t ctx, char *line)
2185 struct client_s *client = assuan_get_pointer (ctx);
2186 gpg_error_t rc;
2187 struct argv_s *args[] = {
2188 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2189 NULL
2192 rc = parse_options (&line, args, client);
2193 if (rc)
2194 return send_error (ctx, rc);
2196 if (client->opts & OPT_INQUIRE)
2198 unsigned char *result;
2199 size_t len;
2201 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2202 if (rc)
2203 return send_error (ctx, rc);
2205 line = (char *) result;
2208 rc = do_attr (ctx, line);
2210 if (client->opts & OPT_INQUIRE)
2211 xfree (line);
2213 return send_error (ctx, rc);
2216 static gpg_error_t
2217 parse_iscached_opt_lock (void *data, void *value)
2219 struct client_s *client = data;
2221 (void) value;
2222 client->opts |= OPT_LOCK;
2223 return 0;
2226 static gpg_error_t
2227 iscached_command (assuan_context_t ctx, char *line)
2229 struct client_s *client = assuan_get_pointer (ctx);
2230 gpg_error_t rc;
2231 unsigned char md5file[16];
2232 struct argv_s *args[] = {
2233 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_iscached_opt_lock},
2234 NULL
2237 if (!line || !*line)
2238 return send_error (ctx, GPG_ERR_SYNTAX);
2240 rc = parse_options (&line, args, client);
2241 if (rc)
2242 return send_error (ctx, rc);
2243 else if (!valid_filename (line))
2244 return send_error (ctx, GPG_ERR_INV_VALUE);
2246 rc = cache_iscached (line, NULL);
2247 if (client->opts & OPT_LOCK
2248 && (!rc || gpg_err_code (rc) == GPG_ERR_NO_DATA))
2250 gpg_error_t trc = rc;
2251 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2252 if (memcmp (md5file, client->md5file, 16))
2253 cleanup_client (client);
2255 memcpy (client->md5file, md5file, 16);
2256 rc = do_lock (client, 1);
2257 if (!rc)
2258 rc = trc;
2261 return send_error (ctx, rc);
2264 static gpg_error_t
2265 clearcache_command (assuan_context_t ctx, char *line)
2267 gpg_error_t rc = 0, all_rc = 0;
2268 unsigned char md5file[16];
2269 int i;
2270 int t;
2271 int all = 0;
2272 struct client_thread_s *once = NULL;
2274 cache_lock ();
2275 MUTEX_LOCK (&cn_mutex);
2276 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
2278 if (!line || !*line)
2279 all = 1;
2281 t = slist_length (cn_thread_list);
2283 for (i = 0; i < t; i++)
2285 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2286 assuan_peercred_t peer;
2288 if (!thd->cl)
2289 continue;
2291 /* Lock each connected clients' file mutex to prevent any other client
2292 * from accessing the cache entry (the file mutex is locked upon
2293 * command startup). The cache for the entry is not cleared if the
2294 * file mutex is locked by another client to prevent this function
2295 * from blocking.
2297 if (all)
2299 if (thd->cl->filename)
2301 rc = do_validate_peer (ctx, thd->cl->filename, &peer);
2302 all_rc = !all_rc ? rc : all_rc;
2303 if (rc)
2305 rc = 0;
2306 continue;
2310 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0, -1);
2311 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2313 if (pthread_equal (pthread_self (), thd->tid))
2314 rc = 0;
2315 else
2317 if (!thd->cl->filename ||
2318 cache_iscached (thd->cl->filename,
2319 NULL) == GPG_ERR_NO_DATA)
2321 rc = 0;
2322 continue;
2325 cache_defer_clear (thd->cl->md5file);
2328 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
2330 rc = 0;
2331 continue;
2334 if (!rc)
2336 rc = cache_clear (thd->cl->md5file);
2337 cache_unlock_mutex (thd->cl->md5file, 0);
2340 if (rc)
2341 all_rc = rc;
2343 rc = 0;
2345 /* A single data filename was specified. Lock only this data file
2346 * mutex and free the cache entry. */
2347 else
2349 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2350 rc = do_validate_peer (ctx, line, &peer);
2352 if (!rc && !memcmp (thd->cl->md5file, md5file, sizeof (md5file)))
2354 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0,
2355 -1);
2356 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2358 if (pthread_equal (pthread_self (), thd->tid))
2359 rc = 0;
2362 if (!rc)
2364 once = thd;
2365 rc = cache_clear (thd->cl->md5file);
2366 cache_unlock_mutex (thd->cl->md5file, 0);
2368 else
2370 cache_defer_clear (thd->cl->md5file);
2373 break;
2378 /* Only connected clients' cache entries have been cleared. Now clear any
2379 * remaining cache entries without clients but only if there wasn't an
2380 * error from above since this would defeat the locking check of the
2381 * remaining entries. */
2382 if (!all_rc && all)
2384 cache_clear (NULL);
2387 /* No clients are using the specified file. */
2388 else if (!all_rc && !rc && !once)
2390 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2391 rc = cache_clear (md5file);
2394 /* Release the connection mutex. */
2395 pthread_cleanup_pop (1);
2396 cache_unlock ();
2398 if (!rc)
2399 send_status_all (STATUS_CACHE, NULL);
2401 /* One or more files were locked while clearing all cache entries. */
2402 if (all_rc)
2403 rc = all_rc;
2405 return send_error (ctx, rc);
2408 static gpg_error_t
2409 cachetimeout_command (assuan_context_t ctx, char *line)
2411 unsigned char md5file[16];
2412 int timeout;
2413 char **req = str_split (line, " ", 0);
2414 char *p;
2415 gpg_error_t rc = 0;
2416 assuan_peercred_t peer;
2418 if (!req || !*req || !req[1])
2420 strv_free (req);
2421 return send_error (ctx, GPG_ERR_SYNTAX);
2424 errno = 0;
2425 timeout = (int) strtol (req[1], &p, 10);
2426 if (errno != 0 || *p || timeout < -1)
2428 strv_free (req);
2429 return send_error (ctx, GPG_ERR_SYNTAX);
2432 rc = do_validate_peer (ctx, req[0], &peer);
2433 if (!rc)
2435 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, req[0], strlen (req[0]));
2436 rc = cache_set_timeout (md5file, timeout);
2437 if (!rc || gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
2439 rc = 0;
2440 MUTEX_LOCK (&rcfile_mutex);
2441 config_set_int_param (&global_config, req[0], "cache_timeout",
2442 req[1]);
2443 MUTEX_UNLOCK (&rcfile_mutex);
2447 strv_free (req);
2448 return send_error (ctx, rc);
2451 static gpg_error_t
2452 dump_command (assuan_context_t ctx, char *line)
2454 xmlChar *xml;
2455 int len;
2456 struct client_s *client = assuan_get_pointer (ctx);
2457 gpg_error_t rc;
2459 if (disable_list_and_dump == 1)
2460 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2462 xmlDocDumpFormatMemory (client->doc, &xml, &len, 1);
2464 if (!xml)
2466 log_write ("%s(%i): %s", __FILE__, __LINE__,
2467 pwmd_strerror (GPG_ERR_ENOMEM));
2468 return send_error (ctx, GPG_ERR_ENOMEM);
2471 pthread_cleanup_push (xmlFree, xml);
2472 rc = xfer_data (ctx, (char *) xml, len);
2473 pthread_cleanup_pop (1);
2474 return send_error (ctx, rc);
2477 static gpg_error_t
2478 getconfig_command (assuan_context_t ctx, char *line)
2480 struct client_s *client = assuan_get_pointer (ctx);
2481 gpg_error_t rc = 0;
2482 char filename[255] = { 0 }, param[747] = { 0 };
2483 char *p, *tmp = NULL, *fp = client->filename, *paramp = line;
2485 if (!line || !*line)
2486 return send_error (ctx, GPG_ERR_SYNTAX);
2488 if (strchr (line, ' '))
2490 sscanf (line, " %254[^ ] %746c", filename, param);
2491 paramp = param;
2492 fp = filename;
2495 if (fp && !valid_filename (fp))
2496 return send_error (ctx, GPG_ERR_INV_VALUE);
2498 paramp = str_down (paramp);
2499 if (!strcmp (paramp, "cipher") && fp)
2501 struct crypto_s *crypto = NULL;
2503 rc = init_client_crypto (&crypto);
2504 if (!rc)
2506 rc = read_data_header (fp, &crypto->hdr, NULL, NULL);
2507 if (!rc)
2509 const char *t =
2510 gcry_cipher_algo_name (cipher_to_gcrypt (crypto->hdr.flags));
2511 if (t)
2513 tmp = str_dup (t);
2514 if (tmp)
2515 str_down (tmp);
2520 UPDATE_AGENT_CTX (client, crypto);
2521 cleanup_crypto (&crypto);
2522 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
2523 return send_error (ctx, rc);
2525 if (!rc && tmp)
2526 goto done;
2528 else if (!strcmp (paramp, "cipher_iterations") && fp)
2530 struct crypto_s *crypto = NULL;
2532 rc = init_client_crypto (&crypto);
2533 if (!rc)
2535 rc = read_data_header (fp, &crypto->hdr, NULL, NULL);
2536 if (!rc)
2538 tmp = str_asprintf ("%llu",
2539 (unsigned long long) crypto->hdr.
2540 iterations);
2541 if (!tmp)
2542 rc = GPG_ERR_ENOMEM;
2546 UPDATE_AGENT_CTX (client, crypto);
2547 cleanup_crypto (&crypto);
2548 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
2549 return send_error (ctx, rc);
2551 if (!rc && tmp)
2552 goto done;
2554 else if (!strcmp (paramp, "passphrase"))
2555 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2557 p = config_get_value (fp ? fp : "global", paramp);
2558 if (!p)
2559 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2561 tmp = expand_homedir (p);
2562 xfree (p);
2563 if (!tmp)
2565 log_write ("%s(%i): %s", __FILE__, __LINE__,
2566 pwmd_strerror (GPG_ERR_ENOMEM));
2567 return send_error (ctx, GPG_ERR_ENOMEM);
2570 done:
2571 p = tmp;
2572 pthread_cleanup_push (xfree, p);
2573 rc = xfer_data (ctx, p, strlen (p));
2574 pthread_cleanup_pop (1);
2575 return send_error (ctx, rc);
2578 struct xpath_s
2580 xmlXPathContextPtr xp;
2581 xmlXPathObjectPtr result;
2582 xmlBufferPtr buf;
2583 char **req;
2586 static void
2587 xpath_command_cleanup (void *arg)
2589 struct xpath_s *xpath = arg;
2591 if (!xpath)
2592 return;
2594 req_cleanup (xpath->req);
2596 if (xpath->buf)
2597 xmlBufferFree (xpath->buf);
2599 if (xpath->result)
2600 xmlXPathFreeObject (xpath->result);
2602 if (xpath->xp)
2603 xmlXPathFreeContext (xpath->xp);
2606 static gpg_error_t
2607 do_xpath (assuan_context_t ctx, char *line)
2609 gpg_error_t rc;
2610 struct client_s *client = assuan_get_pointer (ctx);
2611 struct xpath_s _x = { 0 };
2612 struct xpath_s *xpath = &_x;
2614 if ((xpath->req = str_split (line, "\t", 2)) == NULL)
2616 if (strv_printf (&xpath->req, "%s", line) == 0)
2617 return GPG_ERR_ENOMEM;
2620 xpath->xp = xmlXPathNewContext (client->doc);
2621 if (!xpath->xp)
2623 rc = GPG_ERR_BAD_DATA;
2624 goto fail;
2627 xpath->result =
2628 xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2629 if (!xpath->result)
2631 rc = GPG_ERR_BAD_DATA;
2632 goto fail;
2635 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2637 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2638 goto fail;
2641 rc = recurse_xpath_nodeset (client->doc, xpath->result->nodesetval,
2642 (xmlChar *) xpath->req[1], &xpath->buf, 0,
2643 NULL);
2644 if (rc)
2645 goto fail;
2646 else if (!xpath->req[1] && !xmlBufferLength (xpath->buf))
2648 rc = GPG_ERR_NO_DATA;
2649 goto fail;
2651 else if (xpath->req[1])
2653 rc = 0;
2654 goto fail;
2657 pthread_cleanup_push (xpath_command_cleanup, &xpath);
2658 rc = xfer_data (ctx, (char *) xmlBufferContent (xpath->buf),
2659 xmlBufferLength (xpath->buf));
2660 pthread_cleanup_pop (0);
2661 fail:
2662 xpath_command_cleanup (xpath);
2663 return rc;
2666 static gpg_error_t
2667 xpath_command (assuan_context_t ctx, char *line)
2669 struct client_s *client = assuan_get_pointer (ctx);
2670 gpg_error_t rc;
2671 struct argv_s *args[] = {
2672 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2673 NULL
2676 if (disable_list_and_dump == 1)
2677 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2679 rc = parse_options (&line, args, client);
2680 if (rc)
2681 return send_error (ctx, rc);
2683 if (client->opts & OPT_INQUIRE)
2685 unsigned char *result;
2686 size_t len;
2688 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2689 if (rc)
2690 return send_error (ctx, rc);
2692 line = (char *) result;
2695 if (!line || !*line)
2696 rc = GPG_ERR_SYNTAX;
2698 if (!rc)
2699 rc = do_xpath (ctx, line);
2701 if (client->opts & OPT_INQUIRE)
2702 xfree (line);
2704 return send_error (ctx, rc);
2707 static gpg_error_t
2708 do_xpathattr (assuan_context_t ctx, char *line)
2710 struct client_s *client = assuan_get_pointer (ctx);
2711 gpg_error_t rc;
2712 char **req = NULL;
2713 int cmd = 0; //SET
2714 struct xpath_s _x = { 0 };
2715 struct xpath_s *xpath = &_x;
2717 if ((req = str_split (line, " ", 3)) == NULL)
2718 return GPG_ERR_ENOMEM;
2720 if (!req[0])
2722 rc = GPG_ERR_SYNTAX;
2723 goto fail;
2726 if (!strcasecmp (req[0], "SET"))
2727 cmd = 0;
2728 else if (!strcasecmp (req[0], "DELETE"))
2729 cmd = 1;
2730 else
2732 rc = GPG_ERR_SYNTAX;
2733 goto fail;
2736 if (!req[1] || !req[2])
2738 rc = GPG_ERR_SYNTAX;
2739 goto fail;
2742 if ((xpath->req = str_split (req[2], "\t", 3)) == NULL)
2744 rc = GPG_ERR_ENOMEM;
2745 goto fail;
2748 if (!xpath->req[0] || (!xpath->req[1] && !cmd) || (xpath->req[1] && cmd))
2750 rc = GPG_ERR_SYNTAX;
2751 goto fail;
2754 xpath->xp = xmlXPathNewContext (client->doc);
2755 if (!xpath->xp)
2757 rc = GPG_ERR_BAD_DATA;
2758 goto fail;
2761 xpath->result = xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2762 if (!xpath->result)
2764 rc = GPG_ERR_BAD_DATA;
2765 goto fail;
2768 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2770 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2771 goto fail;
2774 rc = recurse_xpath_nodeset (client->doc, xpath->result->nodesetval,
2775 (xmlChar *) xpath->req[1], &xpath->buf, cmd,
2776 (xmlChar *) req[1]);
2778 fail:
2779 xpath_command_cleanup (xpath);
2780 strv_free (req);
2781 return rc;
2784 /* XPATHATTR SET|DELETE <name> <expression>[<TAB>[value]] */
2785 static gpg_error_t
2786 xpathattr_command (assuan_context_t ctx, char *line)
2788 struct client_s *client = assuan_get_pointer (ctx);
2789 gpg_error_t rc;
2790 struct argv_s *args[] = {
2791 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2792 NULL
2795 if (disable_list_and_dump == 1)
2796 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2798 rc = parse_options (&line, args, client);
2799 if (rc)
2800 return send_error (ctx, rc);
2802 if (client->opts & OPT_INQUIRE)
2804 unsigned char *result;
2805 size_t len;
2807 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2808 if (rc)
2809 return send_error (ctx, rc);
2811 line = (char *) result;
2814 if (!line || !*line)
2815 rc = GPG_ERR_SYNTAX;
2817 if (!rc)
2818 rc = do_xpathattr (ctx, line);
2820 if (client->opts & OPT_INQUIRE)
2821 xfree (line);
2823 return send_error (ctx, rc);
2826 static gpg_error_t
2827 do_import (struct client_s *client, const char *root_element,
2828 unsigned char *content)
2830 char **dst_path = NULL;
2831 xmlDocPtr doc = NULL;
2832 xmlNodePtr n, root, copy;
2833 gpg_error_t rc;
2835 if (!content || !*content)
2837 xfree (content);
2838 return GPG_ERR_SYNTAX;
2841 if (root_element)
2842 dst_path = str_split (root_element, "\t", 0);
2844 if (dst_path && !valid_element_path (dst_path, 0))
2846 if (dst_path)
2847 strv_free (dst_path);
2849 return GPG_ERR_INV_VALUE;
2852 struct string_s *str = string_new_content ((char *)content);
2853 str = string_prepend (str, "<pwmd>");
2854 str = string_append (str, "</pwmd>");
2855 doc = xmlReadDoc ((xmlChar *) str->str, NULL, "UTF-8", XML_PARSE_NOBLANKS);
2856 string_free (str, 1);
2857 if (!doc)
2859 rc = GPG_ERR_BAD_DATA;
2860 goto fail;
2863 root = xmlDocGetRootElement (doc);
2864 xmlNodePtr root_orig = root->children;
2865 root = root->children;
2866 rc = validate_import (root);
2867 if (rc)
2868 goto fail;
2872 again:
2873 if (dst_path)
2875 char **path = strv_dup (dst_path);
2876 if (!path)
2878 log_write ("%s(%i): %s", __FILE__, __LINE__,
2879 pwmd_strerror (GPG_ERR_ENOMEM));
2880 rc = GPG_ERR_ENOMEM;
2881 goto fail;
2884 xmlChar *a = xmlGetProp (root, (xmlChar *) "_name");
2885 if (!a)
2887 strv_free (path);
2888 rc = GPG_ERR_ENOMEM;
2889 goto fail;
2892 if (strv_printf (&path, "%s", (char *) a) == 0)
2894 xmlFree (a);
2895 rc = GPG_ERR_ENOMEM;
2896 goto fail;
2899 xmlFree (a);
2900 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
2901 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2903 strv_free (path);
2904 goto fail;
2907 if (!rc)
2909 n = find_elements (client->doc, n->children, path + 1, &rc,
2910 NULL, NULL, NULL, 0, 0, NULL, 1);
2911 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2913 strv_free (path);
2914 goto fail;
2916 else if (!rc)
2918 xmlUnlinkNode (n);
2919 xmlFreeNode (n);
2920 strv_free (path);
2921 path = NULL;
2922 goto again;
2926 if (rc == GPG_ERR_ELEMENT_NOT_FOUND)
2928 n = create_element_path (client, &path, &rc, NULL);
2929 if (rc)
2930 goto fail;
2933 if (root->children)
2935 copy = xmlCopyNodeList (root->children);
2936 n = xmlAddChildList (n, copy);
2937 if (!n)
2938 rc = GPG_ERR_ENOMEM;
2941 strv_free (path);
2943 else
2945 char **path = NULL;
2947 /* Check if the content root element can create a DTD root element. */
2948 if (!xmlStrEqual ((xmlChar *) "element", root->name))
2950 rc = GPG_ERR_SYNTAX;
2951 goto fail;
2954 xmlChar *a;
2956 if ((a = xmlGetProp (root, (xmlChar *) "_name")) == NULL)
2958 rc = GPG_ERR_SYNTAX;
2959 goto fail;
2962 char *tmp = str_dup ((char *) a);
2963 xmlFree (a);
2964 int literal = is_literal_element (&tmp);
2966 if (!valid_xml_element ((xmlChar *) tmp) || literal)
2968 xfree (tmp);
2969 rc = GPG_ERR_INV_VALUE;
2970 goto fail;
2973 if (strv_printf (&path, "%s", tmp) == 0)
2975 xfree (tmp);
2976 rc = GPG_ERR_ENOMEM;
2977 goto fail;
2980 xfree (tmp);
2981 n = find_root_element (client->doc, &path, &rc, NULL, 0, 1);
2982 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2984 rc = GPG_ERR_BAD_DATA;
2985 goto fail;
2988 /* Overwriting the existing tree. */
2989 if (!rc)
2991 xmlUnlinkNode (n);
2992 xmlFreeNodeList (n);
2995 rc = 0;
2996 xmlSetProp (root, (xmlChar *) "_name", (xmlChar *) path[0]);
2997 n = xmlCopyNode (root, 1);
2998 n = xmlAddChildList (xmlDocGetRootElement (client->doc), n);
2999 strv_free (path);
3002 if (n && !rc)
3003 rc = update_element_mtime (n->parent);
3005 for (root = root_orig->next; root; root = root->next)
3007 if (root->type == XML_ELEMENT_NODE)
3008 break;
3011 root_orig = root;
3013 while (root);
3015 fail:
3016 if (doc)
3017 xmlFreeDoc (doc);
3019 if (dst_path)
3020 strv_free (dst_path);
3022 return rc;
3025 static gpg_error_t
3026 parse_import_opt_root (void *data, void *value)
3028 struct client_s *client = data;
3030 client->import_root = str_dup (value);
3031 return client->import_root ? 0 : GPG_ERR_ENOMEM;
3034 static gpg_error_t
3035 import_command (assuan_context_t ctx, char *line)
3037 gpg_error_t rc;
3038 struct client_s *client = assuan_get_pointer (ctx);
3039 unsigned char *result;
3040 size_t len;
3041 struct argv_s *args[] = {
3042 &(struct argv_s) {"root", OPTION_TYPE_ARG, parse_import_opt_root},
3043 NULL
3046 xfree (client->import_root);
3047 client->import_root = NULL;
3048 rc = parse_options (&line, args, client);
3049 if (rc)
3050 return send_error (ctx, rc);
3052 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3053 if (rc)
3054 return send_error (ctx, rc);
3056 rc = do_import (client, client->import_root, result);
3057 xfree (client->import_root);
3058 client->import_root = NULL;
3059 return send_error (ctx, rc);
3062 static gpg_error_t
3063 do_lock (struct client_s *client, int add)
3065 gpg_error_t rc = lock_file_mutex (client, add);
3067 if (!rc)
3068 client->flags |= FLAG_LOCK_CMD;
3070 return rc;
3073 static gpg_error_t
3074 lock_command (assuan_context_t ctx, char *line)
3076 struct client_s *client = assuan_get_pointer (ctx);
3077 gpg_error_t rc = do_lock (client, 0);
3079 return send_error (ctx, rc);
3082 static gpg_error_t
3083 unlock_command (assuan_context_t ctx, char *line)
3085 struct client_s *client = assuan_get_pointer (ctx);
3086 gpg_error_t rc;
3088 rc = unlock_file_mutex (client, 0);
3089 return send_error (ctx, rc);
3092 static gpg_error_t
3093 option_command (assuan_context_t ctx, char *line)
3095 struct client_s *client = assuan_get_pointer (ctx);
3096 gpg_error_t rc = 0;
3097 struct pinentry_option_s *pin_opts = &client->pinentry_opts;
3098 #ifdef WITH_AGENT
3099 struct agent_s *agent = client->crypto->agent;
3100 #endif
3101 char namebuf[255] = { 0 };
3102 char *name = namebuf;
3103 char *value = NULL, *p;
3105 p = strchr (line, '=');
3106 if (!p)
3107 strncpy (namebuf, line, sizeof(namebuf));
3108 else
3110 strncpy (namebuf, line, strlen (line)-strlen (p));
3111 value = p+1;
3114 log_write1 ("OPTION name='%s' value='%s'", name, value);
3116 if (strcasecmp (name, (char *) "log_level") == 0)
3118 long l = 0;
3120 if (value)
3122 l = strtol (value, NULL, 10);
3124 if (l < 0 || l > 2)
3125 return send_error (ctx, GPG_ERR_INV_VALUE);
3128 MUTEX_LOCK (&rcfile_mutex);
3129 config_set_int_param (&global_config, "global", "log_level", value);
3130 MUTEX_UNLOCK (&rcfile_mutex);
3131 goto done;
3133 else if (strcasecmp (name, (char *) "lock-timeout") == 0)
3135 long n = 0;
3136 char *p = NULL;
3138 if (value)
3140 n = strtol (value, &p, 10);
3141 if (p && *p)
3142 return send_error (ctx, GPG_ERR_INV_VALUE);
3145 client->lock_timeout = n;
3146 goto done;
3148 else if (strcasecmp (name, (char *) "NAME") == 0)
3150 char *tmp = pthread_getspecific (thread_name_key);
3152 if (tmp)
3153 xfree (tmp);
3155 if (!value || !*value)
3157 pthread_setspecific (thread_name_key, str_dup (""));
3158 goto done;
3161 pthread_setspecific (thread_name_key, str_dup (value));
3162 goto done;
3164 else if (strcasecmp (name, (char *) "lc-messages") == 0)
3166 xfree (pin_opts->lc_messages);
3167 pin_opts->lc_messages = NULL;
3168 if (value && *value)
3169 pin_opts->lc_messages = str_dup (value);
3170 #ifdef WITH_AGENT
3171 if (use_agent)
3172 rc = set_agent_option (client->crypto->agent, "lc-messages", value);
3173 #endif
3175 else if (strcasecmp (name, (char *) "lc-ctype") == 0)
3177 xfree (pin_opts->lc_ctype);
3178 pin_opts->lc_ctype = NULL;
3179 if (value && *value)
3180 pin_opts->lc_ctype = str_dup (value);
3181 #ifdef WITH_AGENT
3182 if (use_agent)
3183 rc = set_agent_option (client->crypto->agent, "lc-ctype", value);
3184 #endif
3186 else if (strcasecmp (name, (char *) "ttyname") == 0)
3188 xfree (pin_opts->ttyname);
3189 pin_opts->ttyname = NULL;
3190 if (value && *value)
3191 pin_opts->ttyname = str_dup (value);
3192 #ifdef WITH_AGENT
3193 if (use_agent)
3194 rc = set_agent_option (client->crypto->agent, "ttyname", value);
3195 #endif
3197 else if (strcasecmp (name, (char *) "ttytype") == 0)
3199 xfree (pin_opts->ttytype);
3200 pin_opts->ttytype = NULL;
3201 if (value && *value)
3202 pin_opts->ttytype = str_dup (value);
3203 #ifdef WITH_AGENT
3204 if (use_agent)
3205 rc = set_agent_option (client->crypto->agent, "ttytype", value);
3206 #endif
3208 else if (strcasecmp (name, (char *) "display") == 0)
3210 xfree (pin_opts->display);
3211 pin_opts->display = NULL;
3212 if (value && *value)
3213 pin_opts->display = str_dup (value);
3214 #ifdef WITH_AGENT
3215 if (use_agent)
3216 rc = set_agent_option (client->crypto->agent, "display", value);
3217 #endif
3219 else if (strcasecmp (name, (char *) "pinentry-desc") == 0)
3221 xfree (pin_opts->desc);
3222 pin_opts->desc = NULL;
3223 if (value && *value)
3224 pin_opts->desc = str_dup (value);
3226 else if (strcasecmp (name, (char *) "pinentry-title") == 0)
3228 xfree (pin_opts->title);
3229 pin_opts->title = NULL;
3230 if (value && *value)
3231 pin_opts->title = str_dup (value);
3233 else if (strcasecmp (name, (char *) "pinentry-prompt") == 0)
3235 xfree (pin_opts->prompt);
3236 pin_opts->prompt = NULL;
3237 if (value && *value)
3238 pin_opts->prompt = str_dup (value);
3241 else if (strcasecmp (name, "pinentry-timeout") == 0)
3243 char *p = NULL;
3244 int n;
3246 if (!value)
3247 goto done;
3249 n = (int) strtol (value, &p, 10);
3251 if (*p || n < 0)
3252 return send_error (ctx, GPG_ERR_INV_VALUE);
3254 pin_opts->timeout = n;
3255 MUTEX_LOCK (&rcfile_mutex);
3256 config_set_int_param (&global_config,
3257 client->filename ? client->filename : "global",
3258 "pinentry_timeout", value);
3259 MUTEX_UNLOCK (&rcfile_mutex);
3260 goto done;
3262 else if (strcasecmp (name, "disable-pinentry") == 0)
3264 char *p = NULL;
3265 int n = 1;
3267 if (value && *value)
3269 n = (int) strtol (value, &p, 10);
3270 if (*p || n < 0 || n > 1)
3271 return send_error (ctx, GPG_ERR_INV_VALUE);
3274 if (n)
3275 client->flags |= FLAG_NO_PINENTRY;
3276 else
3277 client->flags &= ~FLAG_NO_PINENTRY;
3279 else
3280 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
3282 done:
3283 #ifdef WITH_AGENT
3284 if (!rc && use_agent && agent)
3286 rc = pinentry_merge_options (&client->crypto->agent->pinentry_opts,
3287 pin_opts);
3289 #endif
3291 return send_error (ctx, rc);
3294 static gpg_error_t
3295 do_rename (assuan_context_t ctx, char *line)
3297 struct client_s *client = assuan_get_pointer (ctx);
3298 gpg_error_t rc;
3299 char **req, **src, *dst;
3300 xmlNodePtr n, ndst;
3302 req = str_split (line, " ", 0);
3304 if (!req || !req[0] || !req[1])
3306 strv_free (req);
3307 return GPG_ERR_SYNTAX;
3310 dst = req[1];
3311 is_literal_element (&dst);
3313 if (!valid_xml_element ((xmlChar *) dst))
3315 strv_free (req);
3316 return GPG_ERR_INV_VALUE;
3319 if (strchr (req[0], '\t'))
3320 src = str_split (req[0], "\t", 0);
3321 else
3322 src = str_split (req[0], " ", 0);
3324 if (!src || !*src)
3326 rc = GPG_ERR_SYNTAX;
3327 goto fail;
3330 n = find_root_element (client->doc, &src, &rc, NULL, 0, 0);
3331 if (src[1] && n)
3332 n = find_elements (client->doc, n->children, src + 1, &rc, NULL, NULL,
3333 NULL, 0, 0, NULL, 0);
3335 if (!n)
3336 goto fail;
3338 xmlChar *a = xmlGetProp (n, (xmlChar *) "_name");
3339 if (!a)
3341 rc = GPG_ERR_ENOMEM;
3342 goto fail;
3345 /* To prevent unwanted effects:
3347 * <root name="a"><b/></root>
3349 * RENAME a<TAB>b b
3351 if (xmlStrEqual (a, (xmlChar *) dst))
3353 xmlFree (a);
3354 rc = GPG_ERR_AMBIGUOUS_NAME;
3355 goto fail;
3358 xmlFree (a);
3359 char **tmp = NULL;
3360 if (src[1])
3362 char **p;
3364 for (p = src; *p; p++)
3366 if (!*(p + 1))
3367 break;
3368 strv_printf (&tmp, "%s", *p);
3372 strv_printf (&tmp, "!%s", dst);
3373 ndst = find_root_element (client->doc, &tmp, &rc, NULL, 0, 0);
3374 if (!ndst && rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3376 strv_free (tmp);
3377 goto fail;
3380 if (tmp[1] && ndst)
3381 ndst = find_elements (client->doc, ndst->children, tmp + 1, &rc, NULL,
3382 NULL, NULL, 0, 0, NULL, 0);
3384 strv_free (tmp);
3385 if (!ndst && rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3386 goto fail;
3388 rc = 0;
3390 /* Target may exist:
3392 * <root name="a"/>
3393 * <root name="b" target="a"/>
3395 * RENAME b a
3397 * Would need to do:
3398 * RENAME !b a
3400 if (ndst == n)
3402 rc = GPG_ERR_AMBIGUOUS_NAME;
3403 goto fail;
3406 if (ndst)
3408 unlink_node (ndst);
3409 xmlFreeNodeList (ndst);
3412 rc = add_attribute (n, "_name", dst);
3414 fail:
3415 strv_free (req);
3416 strv_free (src);
3417 return rc;
3420 static gpg_error_t
3421 rename_command (assuan_context_t ctx, char *line)
3423 struct client_s *client = assuan_get_pointer (ctx);
3424 gpg_error_t rc;
3425 struct argv_s *args[] = {
3426 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3427 NULL
3430 rc = parse_options (&line, args, client);
3431 if (rc)
3432 return send_error (ctx, rc);
3434 if (client->opts & OPT_INQUIRE)
3436 unsigned char *result;
3437 size_t len;
3439 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3440 if (rc)
3441 return send_error (ctx, rc);
3443 line = (char *) result;
3446 rc = do_rename (ctx, line);
3448 if (client->opts & OPT_INQUIRE)
3449 xfree (line);
3451 return send_error (ctx, rc);
3454 static gpg_error_t
3455 do_copy (assuan_context_t ctx, char *line)
3457 struct client_s *client = assuan_get_pointer (ctx);
3458 gpg_error_t rc;
3459 char **req, **src = NULL, **dst = NULL;
3460 xmlNodePtr nsrc, ndst, new = NULL;
3462 req = str_split (line, " ", 0);
3463 if (!req || !req[0] || !req[1])
3465 strv_free (req);
3466 return GPG_ERR_SYNTAX;
3469 if (strchr (req[0], '\t'))
3470 src = str_split (req[0], "\t", 0);
3471 else
3472 src = str_split (req[0], " ", 0);
3474 if (!src || !*src)
3476 rc = GPG_ERR_SYNTAX;
3477 goto fail;
3480 if (strchr (req[1], '\t'))
3481 dst = str_split (req[1], "\t", 0);
3482 else
3483 dst = str_split (req[1], " ", 0);
3485 if (!dst || !*dst)
3487 rc = GPG_ERR_SYNTAX;
3488 goto fail;
3491 if (!valid_element_path (dst, 0))
3493 rc = GPG_ERR_INV_VALUE;
3494 goto fail;
3497 nsrc = find_root_element (client->doc, &src, &rc, NULL, 0, 0);
3498 if (nsrc && src[1])
3499 nsrc = find_elements (client->doc, nsrc->children, src + 1, &rc, NULL,
3500 NULL, NULL, 0, 0, NULL, 0);
3502 if (!nsrc)
3503 goto fail;
3505 new = xmlCopyNodeList (nsrc);
3506 if (!new)
3508 rc = GPG_ERR_ENOMEM;
3509 goto fail;
3512 int create = 0;
3513 ndst = find_root_element (client->doc, &dst, &rc, NULL, 0, 0);
3514 if (ndst && dst[1])
3516 if (ndst->children)
3517 ndst = find_elements (client->doc, ndst->children, dst + 1, &rc, NULL,
3518 NULL, create_target_elements_cb, 0, 0, NULL, 0);
3519 else
3520 create = 1;
3522 else
3523 create = 1;
3525 if (!ndst && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3526 goto fail;
3527 else if (!ndst || create)
3529 ndst = create_element_path (client, &dst, &rc, NULL);
3530 if (!ndst)
3531 goto fail;
3534 /* Merge any attributes from the src node to the initial dst node. */
3535 for (xmlAttrPtr attr = new->properties; attr; attr = attr->next)
3537 if (xmlStrEqual (attr->name, (xmlChar *) "_name"))
3538 continue;
3540 xmlAttrPtr a = xmlHasProp (ndst, attr->name);
3541 if (a)
3542 xmlRemoveProp (a);
3544 xmlChar *tmp = xmlNodeGetContent (attr->children);
3545 xmlNewProp (ndst, attr->name, tmp);
3546 xmlFree (tmp);
3547 rc = add_attribute (ndst, NULL, NULL);
3550 xmlNodePtr n = ndst->children;
3551 xmlUnlinkNode (n);
3552 xmlFreeNodeList (n);
3553 ndst->children = NULL;
3555 if (new->children)
3557 n = xmlCopyNodeList (new->children);
3558 if (!n)
3560 rc = GPG_ERR_ENOMEM;
3561 goto fail;
3564 n = xmlAddChildList (ndst, n);
3565 if (!n)
3567 rc = GPG_ERR_ENOMEM;
3568 goto fail;
3571 rc = update_element_mtime (xmlDocGetRootElement (client->doc) ==
3572 ndst->parent ? ndst : ndst->parent);
3575 fail:
3576 if (new)
3578 xmlUnlinkNode (new);
3579 xmlFreeNodeList (new);
3582 if (req)
3583 strv_free (req);
3585 if (src)
3586 strv_free (src);
3588 if (dst)
3589 strv_free (dst);
3591 return rc;
3594 static gpg_error_t
3595 copy_command (assuan_context_t ctx, char *line)
3597 struct client_s *client = assuan_get_pointer (ctx);
3598 gpg_error_t rc;
3599 struct argv_s *args[] = {
3600 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3601 NULL
3604 rc = parse_options (&line, args, client);
3605 if (rc)
3606 return send_error (ctx, rc);
3608 if (client->opts & OPT_INQUIRE)
3610 unsigned char *result;
3611 size_t len;
3613 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3614 if (rc)
3615 return send_error (ctx, rc);
3617 line = (char *) result;
3620 rc = do_copy (ctx, line);
3622 if (client->opts & OPT_INQUIRE)
3623 xfree (line);
3625 return send_error (ctx, rc);
3628 static gpg_error_t
3629 do_move (assuan_context_t ctx, char *line)
3631 struct client_s *client = assuan_get_pointer (ctx);
3632 gpg_error_t rc;
3633 char **req, **src = NULL, **dst = NULL;
3634 xmlNodePtr nsrc, ndst = NULL;
3636 req = str_split (line, " ", 0);
3638 if (!req || !req[0] || !req[1])
3640 strv_free (req);
3641 return GPG_ERR_SYNTAX;
3644 if (strchr (req[0], '\t'))
3645 src = str_split (req[0], "\t", 0);
3646 else
3647 src = str_split (req[0], " ", 0);
3649 if (!src || !*src)
3651 rc = GPG_ERR_SYNTAX;
3652 goto fail;
3655 if (strchr (req[1], '\t'))
3656 dst = str_split (req[1], "\t", 0);
3657 else
3658 dst = str_split (req[1], " ", 0);
3660 nsrc = find_root_element (client->doc, &src, &rc, NULL, 0, 0);
3661 if (nsrc && src[1])
3662 nsrc = find_elements (client->doc, nsrc->children, src + 1, &rc, NULL,
3663 NULL, NULL, 0, 0, NULL, 0);
3665 if (!nsrc)
3666 goto fail;
3668 if (dst)
3670 if (!valid_element_path (dst, 0))
3672 rc = GPG_ERR_INV_VALUE;
3673 goto fail;
3676 ndst = find_root_element (client->doc, &dst, &rc, NULL, 0, 0);
3677 if (ndst && dst[1])
3678 ndst = find_elements (client->doc, ndst->children, dst + 1, &rc, NULL,
3679 NULL, NULL, 0, 0, NULL, 0);
3681 else
3682 ndst = xmlDocGetRootElement (client->doc);
3684 for (xmlNodePtr n = ndst; n; n = n->parent)
3686 if (n == nsrc)
3688 rc = GPG_ERR_CONFLICT;
3689 goto fail;
3693 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3694 goto fail;
3696 rc = 0;
3698 if (ndst)
3700 xmlChar *a = node_has_attribute (nsrc, (xmlChar *) "_name");
3701 xmlNodePtr dup = find_element (ndst->children, (char *) a, NULL);
3703 xmlFree (a);
3704 if (dup)
3706 if (dup == nsrc)
3707 goto fail;
3709 if (ndst == xmlDocGetRootElement (client->doc))
3711 xmlNodePtr n = nsrc;
3712 int match = 0;
3714 while (n->parent && n->parent != ndst)
3715 n = n->parent;
3717 xmlChar *a = node_has_attribute (n, (xmlChar *) "_name");
3718 xmlChar *b = node_has_attribute (nsrc, (xmlChar *) "_name");
3720 if (xmlStrEqual (a, b))
3722 match = 1;
3723 xmlUnlinkNode (nsrc);
3724 xmlUnlinkNode (n);
3725 xmlFreeNodeList (n);
3728 xmlFree (a);
3729 xmlFree (b);
3731 if (!match)
3733 xmlUnlinkNode (dup);
3734 xmlFreeNodeList (dup);
3737 else
3738 xmlUnlinkNode (dup);
3742 if (!ndst && dst)
3744 xmlChar *name = node_has_attribute (nsrc, (xmlChar *) "_name");
3746 if (nsrc->parent == xmlDocGetRootElement (client->doc)
3747 && !strcmp ((char *) name, *dst))
3749 xmlFree (name);
3750 rc = GPG_ERR_CONFLICT;
3751 goto fail;
3754 xmlFree (name);
3755 ndst = create_element_path (client, &dst, &rc, nsrc);
3758 if (!ndst)
3759 goto fail;
3761 update_element_mtime (nsrc->parent);
3762 xmlUnlinkNode (nsrc);
3763 ndst = xmlAddChildList (ndst, nsrc);
3765 if (!ndst)
3766 rc = GPG_ERR_ENOMEM;
3767 else
3768 update_element_mtime (ndst->parent);
3770 fail:
3771 if (req)
3772 strv_free (req);
3774 if (src)
3775 strv_free (src);
3777 if (dst)
3778 strv_free (dst);
3780 return rc;
3783 static gpg_error_t
3784 move_command (assuan_context_t ctx, char *line)
3786 struct client_s *client = assuan_get_pointer (ctx);
3787 gpg_error_t rc;
3788 struct argv_s *args[] = {
3789 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3790 NULL
3793 rc = parse_options (&line, args, client);
3794 if (rc)
3795 return send_error (ctx, rc);
3797 if (client->opts & OPT_INQUIRE)
3799 unsigned char *result;
3800 size_t len;
3802 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3803 if (rc)
3804 return send_error (ctx, rc);
3806 line = (char *) result;
3809 rc = do_move (ctx, line);
3811 if (client->opts & OPT_INQUIRE)
3812 xfree (line);
3814 return send_error (ctx, rc);
3817 static gpg_error_t
3818 ls_command (assuan_context_t ctx, char *line)
3820 gpg_error_t rc;
3821 char *tmp = str_asprintf ("%s/data", homedir);
3822 char *dir = expand_homedir (tmp);
3823 DIR *d = opendir (dir);
3825 rc = gpg_error_from_errno (errno);
3826 xfree (tmp);
3828 if (!d)
3830 xfree (dir);
3831 return send_error (ctx, rc);
3834 size_t len =
3835 offsetof (struct dirent, d_name) +pathconf (dir, _PC_NAME_MAX) + 1;
3836 struct dirent *p = xmalloc (len), *cur = NULL;
3837 char *list = NULL;
3839 xfree (dir);
3840 rc = 0;
3842 while (!readdir_r (d, p, &cur) && cur)
3844 if (cur->d_name[0] == '.' && cur->d_name[1] == '\0')
3845 continue;
3846 else if (cur->d_name[0] == '.' && cur->d_name[1] == '.'
3847 && cur->d_name[2] == '\0')
3848 continue;
3850 tmp = str_asprintf ("%s%s\n", list ? list : "", cur->d_name);
3852 if (!tmp)
3854 if (list)
3855 xfree (list);
3857 rc = GPG_ERR_ENOMEM;
3858 break;
3861 xfree (list);
3862 list = tmp;
3865 closedir (d);
3866 xfree (p);
3868 if (rc)
3869 return send_error (ctx, rc);
3871 if (!list)
3872 return send_error (ctx, GPG_ERR_NO_DATA);
3874 list[strlen (list) - 1] = 0;
3875 rc = xfer_data (ctx, list, strlen (list));
3876 xfree (list);
3877 return send_error (ctx, rc);
3880 static gpg_error_t
3881 bye_notify (assuan_context_t ctx, char *line)
3883 struct client_s *cl = assuan_get_pointer (ctx);
3885 #ifdef WITH_GNUTLS
3886 if (cl->thd->remote)
3888 int rc;
3892 struct timeval tv = { 0, 50000 };
3894 rc = gnutls_bye (cl->thd->tls->ses, GNUTLS_SHUT_RDWR);
3895 if (rc == GNUTLS_E_AGAIN)
3896 select (0, NULL, NULL, NULL, &tv);
3898 while (rc == GNUTLS_E_AGAIN);
3900 #endif
3902 /* This will let assuan_process_next() return. */
3903 fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK);
3904 cl->last_rc = 0; // BYE command result
3905 return 0;
3908 static gpg_error_t
3909 reset_notify (assuan_context_t ctx, char *line)
3911 struct client_s *client = assuan_get_pointer (ctx);
3913 if (client)
3914 cleanup_client (client);
3916 return 0;
3920 * This is called before every Assuan command.
3922 static gpg_error_t
3923 command_startup (assuan_context_t ctx, const char *name)
3925 struct client_s *client = assuan_get_pointer (ctx);
3926 gpg_error_t rc;
3927 struct command_table_s *cmd = NULL;
3929 log_write1 ("command='%s'", name);
3930 client->last_rc = client->opts = 0;
3932 for (int i = 0; command_table[i]; i++)
3934 if (!strcasecmp (name, command_table[i]->name))
3936 if (command_table[i]->ignore_startup)
3937 return 0;
3938 cmd = command_table[i];
3939 break;
3943 client->last_rc = rc = gpg_error (file_modified (client, cmd));
3944 return rc;
3948 * This is called after every Assuan command.
3950 static void
3951 command_finalize (assuan_context_t ctx, gpg_error_t rc)
3953 struct client_s *client = assuan_get_pointer (ctx);
3955 if (!(client->flags & FLAG_LOCK_CMD))
3956 unlock_file_mutex (client, 0);
3958 log_write1 (_("command completed: rc=%u"), client->last_rc);
3959 client->last_rc = gpg_error (GPG_ERR_UNKNOWN_COMMAND);
3960 #ifdef WITH_GNUTLS
3961 client->thd->buffer_timeout = client->thd->last_buffer_size = 0;
3962 #endif
3965 static gpg_error_t
3966 help_command (assuan_context_t ctx, char *line)
3968 gpg_error_t rc;
3969 int i;
3971 if (!line || !*line)
3973 char *tmp;
3974 char *help = str_dup (_("Usage: HELP [<COMMAND>]\n"
3975 "For commands that take an element path as an argument, each element is "
3976 "separated with an ASCII @key{TAB} character (ASCII 0x09)."
3977 "\n" "COMMANDS:"));
3979 for (i = 0; command_table[i]; i++)
3981 if (!command_table[i]->help)
3982 continue;
3984 tmp = str_asprintf ("%s %s", help, command_table[i]->name);
3985 xfree (help);
3986 help = tmp;
3989 tmp = strip_texi_and_wrap (help);
3990 xfree (help);
3991 rc = xfer_data (ctx, tmp, strlen (tmp));
3992 xfree (tmp);
3993 return send_error (ctx, rc);
3996 for (i = 0; command_table[i]; i++)
3998 if (!strcasecmp (line, command_table[i]->name))
4000 char *help, *tmp;
4002 if (!command_table[i]->help)
4003 break;
4005 help = strip_texi_and_wrap (command_table[i]->help);
4006 tmp = str_asprintf (_("Usage: %s"), help);
4007 xfree (help);
4008 rc = xfer_data (ctx, tmp, strlen (tmp));
4009 xfree (tmp);
4010 return send_error (ctx, rc);
4014 return send_error (ctx, GPG_ERR_INV_NAME);
4017 static void
4018 new_command (const char *name, int ignore, int unlock,
4019 gpg_error_t (*handler) (assuan_context_t, char *),
4020 const char *help)
4022 int i = 0;
4024 if (command_table)
4025 for (i = 0; command_table[i]; i++);
4027 command_table =
4028 xrealloc (command_table, (i + 2) * sizeof (struct command_table_s *));
4029 command_table[i] = xcalloc (1, sizeof (struct command_table_s));
4030 command_table[i]->name = name;
4031 command_table[i]->handler = handler;
4032 command_table[i]->ignore_startup = ignore;
4033 command_table[i]->unlock = unlock;
4034 command_table[i++]->help = help;
4035 command_table[i] = NULL;
4038 void
4039 deinit_commands ()
4041 int i;
4043 for (i = 0; command_table[i]; i++)
4044 xfree (command_table[i]);
4046 xfree (command_table);
4049 static int
4050 sort_commands (const void *arg1, const void *arg2)
4052 struct command_table_s *const *a = arg1;
4053 struct command_table_s *const *b = arg2;
4055 if (!*a || !*b)
4056 return 0;
4057 else if (*a && !*b)
4058 return 1;
4059 else if (!*a && *b)
4060 return -1;
4062 return strcmp ((*a)->name, (*b)->name);
4065 static gpg_error_t
4066 passwd_command (assuan_context_t ctx, char *line)
4068 struct client_s *client = assuan_get_pointer (ctx);
4069 gpg_error_t rc;
4070 struct argv_s *args[] = {
4071 &(struct argv_s) {"reset", OPTION_TYPE_NOARG, parse_opt_reset},
4072 &(struct argv_s) {"s2k-count", OPTION_TYPE_ARG, parse_opt_s2k_count},
4073 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG, parse_opt_no_passphrase},
4074 NULL
4077 if (client->flags & FLAG_NEW)
4078 return send_error (ctx, GPG_ERR_INV_STATE);
4080 client->crypto->save.s2k_count =
4081 config_get_ulong (client->filename, "s2k_count");
4082 rc = parse_options (&line, args, client);
4083 if (rc)
4084 return send_error (ctx, rc);
4086 if (!rc && client->opts & OPT_RESET)
4088 rc = cache_clear (client->md5file);
4089 if (!rc)
4090 send_status_all (STATUS_CACHE, NULL);
4093 if (!rc)
4095 if (!IS_PKI (client->crypto))
4097 struct crypto_s *crypto;
4099 xfree (client->crypto->filename);
4100 client->crypto->filename = str_dup (client->filename);
4101 rc = change_passwd (ctx, client->filename,
4102 client->flags & FLAG_NO_PINENTRY, &crypto,
4103 (client->opts & OPT_NO_PASSPHRASE));
4104 if (!rc)
4106 cleanup_crypto (&client->crypto);
4107 client->crypto = crypto;
4108 update_checksum (client);
4109 cleanup_crypto_stage1 (client->crypto);
4112 #ifdef WITH_AGENT
4113 else
4115 if (client->crypto->save.s2k_count)
4116 rc = send_to_agent (client->crypto->agent, NULL, NULL,
4117 "OPTION s2k-count=%lu",
4118 client->crypto->save.s2k_count);
4120 if (!rc)
4121 rc = agent_passwd (client->crypto);
4123 #endif
4126 return send_error (ctx, rc);
4129 static gpg_error_t
4130 parse_keygrip_opt_sign (void *data, void *value)
4132 struct client_s *client = data;
4134 (void) value;
4135 client->opts |= OPT_SIGN;
4136 return 0;
4139 static gpg_error_t
4140 keygrip_command (assuan_context_t ctx, char *line)
4142 struct client_s *client = assuan_get_pointer (ctx);
4143 gpg_error_t rc;
4144 struct crypto_s *crypto = NULL;
4145 struct argv_s *args[] = {
4146 &(struct argv_s) {"sign", OPTION_TYPE_NOARG, parse_keygrip_opt_sign},
4147 NULL
4150 if (!line || !*line)
4151 return send_error (ctx, GPG_ERR_SYNTAX);
4153 rc = parse_options (&line, args, client);
4154 if (rc)
4155 return send_error (ctx, rc);
4157 if (!valid_filename (line))
4158 return send_error (ctx, GPG_ERR_INV_VALUE);
4160 rc = init_client_crypto (&crypto);
4161 if (rc)
4162 return send_error (ctx, rc);
4164 rc = read_data_file (line, crypto);
4165 if (!rc)
4167 char *hexgrip = NULL;
4169 if (!IS_PKI (crypto))
4171 cleanup_crypto (&crypto);
4172 return send_error (ctx, GPG_ERR_NOT_SUPPORTED);
4175 if (client->opts & OPT_SIGN)
4177 if (valid_keygrip (crypto->sign_grip, sizeof (crypto->sign_grip)))
4178 hexgrip = bin2hex (crypto->sign_grip, sizeof (crypto->sign_grip));
4181 if (!hexgrip)
4182 hexgrip = bin2hex (crypto->grip, sizeof (crypto->grip));
4184 if (!hexgrip)
4185 rc = GPG_ERR_ENOMEM;
4186 else
4187 rc = xfer_data (ctx, hexgrip, strlen (hexgrip));
4189 xfree (hexgrip);
4192 UPDATE_AGENT_CTX (client, crypto);
4193 cleanup_crypto (&crypto);
4194 return send_error (ctx, rc);
4197 static gpg_error_t
4198 parse_opt_data (void *data, void *value)
4200 struct client_s *client = data;
4202 (void) value;
4203 client->opts |= OPT_DATA;
4204 return 0;
4207 static gpg_error_t
4208 getinfo_command (assuan_context_t ctx, char *line)
4210 struct client_s *client = assuan_get_pointer (ctx);
4211 gpg_error_t rc;
4212 char buf[ASSUAN_LINELENGTH];
4213 struct argv_s *args[] = {
4214 &(struct argv_s) {"data", OPTION_TYPE_NOARG, parse_opt_data},
4215 NULL
4218 rc = parse_options (&line, args, client);
4219 if (rc)
4220 return send_error (ctx, rc);
4222 if (!strcasecmp (line, "clients"))
4224 if (client->opts & OPT_DATA)
4226 MUTEX_LOCK (&cn_mutex);
4227 snprintf (buf, sizeof (buf), "%i", slist_length (cn_thread_list));
4228 MUTEX_UNLOCK (&cn_mutex);
4229 rc = xfer_data (ctx, buf, strlen (buf));
4231 else
4232 rc = send_status (ctx, STATUS_CLIENTS, NULL);
4234 else if (!strcasecmp (line, "cache"))
4236 if (client->opts & OPT_DATA)
4238 snprintf (buf, sizeof (buf), "%u", cache_file_count ());
4239 rc = xfer_data (ctx, buf, strlen (buf));
4241 else
4242 rc = send_status (ctx, STATUS_CACHE, NULL);
4244 else if (!strcasecmp (line, "pid"))
4246 char buf[32];
4247 pid_t pid = getpid ();
4249 snprintf (buf, sizeof (buf), "%i", pid);
4250 rc = xfer_data (ctx, buf, strlen (buf));
4252 else if (!strcasecmp (line, "version"))
4254 char *buf = str_asprintf ("0x%06x %s%s", VERSION_HEX,
4255 #ifdef WITH_LIBACL
4256 "ACL "
4257 #endif
4258 #ifdef WITH_GNUTLS
4259 "GNUTLS "
4260 #endif
4261 #ifdef WITH_QUALITY
4262 "QUALITY "
4263 #endif
4264 "", use_agent ? "AGENT" : "");
4265 rc = xfer_data (ctx, buf, strlen (buf));
4266 xfree (buf);
4268 else if (!strcasecmp (line, "last_error"))
4270 if (client->last_error)
4271 rc = xfer_data (ctx, client->last_error, strlen (client->last_error));
4272 else
4273 rc = GPG_ERR_NO_DATA;
4275 else
4276 rc = gpg_error (GPG_ERR_SYNTAX);
4278 return send_error (ctx, rc);
4281 #ifdef WITH_AGENT
4282 static gpg_error_t
4283 send_data_cb (void *user, const void *buf, size_t len)
4285 assuan_context_t ctx = user;
4287 return assuan_send_data (ctx, buf, len);
4290 static gpg_error_t
4291 send_status_cb (void *user, const char *line)
4293 assuan_context_t ctx = user;
4294 char keyword[200], *k;
4295 const char *p;
4297 for (p = line, k = keyword; *p; p++)
4299 if (isspace (*p))
4300 break;
4302 *k++ = *p;
4305 *k = 0;
4306 if (*p == '#')
4307 p++;
4309 while (isspace (*p))
4310 p++;
4312 return assuan_write_status (ctx, keyword, *p ? p : NULL);
4314 #endif
4316 static gpg_error_t
4317 agent_command (assuan_context_t ctx, char *line)
4319 gpg_error_t rc = 0;
4321 if (!use_agent)
4322 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
4324 #ifdef WITH_AGENT
4325 struct client_s *client = assuan_get_pointer (ctx);
4327 if (!line || !*line)
4328 return send_error (ctx, GPG_ERR_SYNTAX);
4330 assuan_set_flag (client->crypto->agent->ctx, ASSUAN_CONVEY_COMMENTS, 1);
4331 rc = assuan_transact (client->crypto->agent->ctx, line, send_data_cb,
4332 client->ctx, agent_loopback_cb, client->crypto,
4333 send_status_cb, client->ctx);
4334 if (gpg_err_code (rc) == GPG_ERR_ASS_CANCELED)
4336 char *line;
4337 size_t len;
4339 rc = assuan_write_line (client->crypto->agent->ctx, "CAN");
4340 if (!rc)
4342 rc = assuan_read_line (client->crypto->agent->ctx, &line, &len);
4343 if (!rc)
4344 rc = gpg_error (GPG_ERR_ASS_CANCELED);
4348 assuan_set_flag (client->crypto->agent->ctx, ASSUAN_CONVEY_COMMENTS, 0);
4349 #endif
4350 return send_error (ctx, rc);
4353 void
4354 init_commands ()
4356 /* !BEGIN-HELP-TEXT!
4358 * This comment is used as a marker to generate the offline documentation
4359 * found in doc/pwmd.info. The indentation needs to be kept for the awk
4360 * script to determine where commands begin and end.
4362 new_command("HELP", 1, 1, help_command, _(
4363 "HELP [<COMMAND>]\n"
4364 "Show available commands or command specific help text."
4367 new_command("AGENT", 1, 1, agent_command, _(
4368 "AGENT <command>\n"
4369 "Send a @command{gpg-agent} protocol @var{command} directly to the "
4370 "@command{gpg-agent}."
4373 new_command("GETINFO", 1, 1, getinfo_command, _(
4374 "GETINFO [--data] CACHE | CLIENTS | PID | LAST_ERROR | VERSION\n"
4375 "Get server and other information: @var{cache} returns the number of cached "
4376 "documents via a status message. @var{clients} returns the number of "
4377 "connected clients via a status message. @var{pid} returns the process ID "
4378 "number of the server via a data response. @var{VERSION} returns the server "
4379 "version number and compile-time features with a data response with each "
4380 "being space delimited. @var{LAST_ERROR} returns a detailed description of "
4381 "the last failed command when available. @xref{Status Messages}. "
4382 "\n"
4383 "When the @option{--data} option is specified then the result will be sent "
4384 "via a data response rather than a status message."
4387 new_command("PASSWD", 0, 0, passwd_command, _(
4388 "PASSWD [--reset] [--s2k-count=N] [--no-passphrase]\n"
4389 "Changes the passphrase of the secret key required to open the current "
4390 "file or the passphrase of a symmetrically encrypted data file. When the "
4391 "@option{--reset} option is passed then the cache entry for the current "
4392 "file will be reset and the passphrase, if any, will be required during the "
4393 "next @code{OPEN}. @xref{OPEN}."
4394 "\n"
4395 "The @option{--s2k-count} option sets number of hash iterations for a "
4396 "passphrase and must be either @code{0} to use the calibrated count of the "
4397 "machine (the default), or a value greater than or equal to @code{65536}. "
4398 "@xref{SAVE}. This option has no effect for symmetrically encrypted data "
4399 "files."
4400 "\n"
4401 "The @option{--no-passphrase} option will prevent requiring a passphrase for "
4402 "the data file, although a passphrase may be required when changing it."
4405 new_command("KEYGRIP", 1, 1, keygrip_command, _(
4406 "KEYGRIP [--sign] <filename>\n"
4407 "Returns the hex encoded keygrip of the specified @var{filename} with a "
4408 "data response."
4409 "\n"
4410 "When the @option{--sign} option is specified then the key used for signing "
4411 "of the specified @var{filename} will be returned."
4412 "\n"
4413 "For symmetrically encrypted data files this command returns the error "
4414 "GPG_ERR_NOT_SUPPORTED."
4417 new_command("OPEN", 1, 1, open_command, _(
4418 "OPEN [--lock] <filename> [<passphrase>]\n"
4419 "Opens @var{filename} using @var{passphrase}. When the filename is not "
4420 "found on the file-system then a new document will be created. If the file "
4421 "is found, it is looked for in the file cache. If cached and no "
4422 "@var{passphrase} was specified then the cached document is opened. When not "
4423 "cached, @cite{pinentry(1)} will be used to retrieve the passphrase to use "
4424 "for decryption unless @option{disable-pinentry} (@pxref{OPTION}) was "
4425 "specified."
4426 "\n"
4427 "When the @option{--lock} option is passed then the file mutex will be "
4428 "locked as if the @code{LOCK} command (@pxref{LOCK}) had been sent after the "
4429 "file has been opened."
4432 new_command("SAVE", 0, 0, save_command, _(
4433 "SAVE [--no-passphrase] [--reset] [--no-agent] [--s2k-count=N] [--cipher=<algo>] [--cipher-iterations=N] [--inquire-keyparam] [--keygrip=hexstring] [--sign-keygrip=hexstring]\n"
4434 "Writes the @abbr{XML} document to disk. The file written to is the file that "
4435 "was opened using the @code{OPEN} command (@pxref{OPEN}). If the file is a "
4436 "new one or the option @option{--inquire-keyparam} was passed, then a new "
4437 "keypair will be generated and a pinentry will be used to prompt for the "
4438 "passphrase to encrypt with unless the @option{--no-passphrase} option was "
4439 "passed in which case the data file will not be passphrase protected. "
4440 "\n"
4441 "The @option{--no-agent} option disables use of @command{gpg-agent} for "
4442 "passphrase retrieval and caching of new files when @command{gpg-agent} "
4443 "use is enabled. The datafile will be symmetrically encrypted and will not "
4444 "use or generate any keypair."
4445 "\n"
4446 "The @option{--reset} option will clear the cache entry for the current file "
4447 "and require a passphrase, if needed, before saving."
4448 "\n"
4449 "The @option{--cipher} option can be used to encrypt the @abbr{XML} data to "
4450 "an alternate cipher. The default is @code{aes256}. See the Configuration "
4451 "(@pxref{Configuration}) for available ciphers."
4452 "\n"
4453 "The @option{--cipher-iterations} option specifies the number of times to "
4454 "encrypt the XML data. The default is 0 although 1 iteration is still done."
4455 "\n"
4456 "The @option{--inquire-keyparam} option will send a server @emph{INQUIRE} to "
4457 "the client to obtain the key paramaters to use when generating a new "
4458 "keypair. The inquired data is expected to be an S-expression. If not "
4459 "specified then an @samp{RSA} key of @samp{2048} bits will be generated "
4460 "unless otherwise set in the configuration file (@pxref{Configuration}). Note "
4461 "that when this option is specified a new keypair will be generated "
4462 "reguardless if the file is a new one and that if the data file is protected "
4463 "the passphrase to open it will be required before generating the new keypair."
4464 "\n"
4465 "You can encrypt the data file to a public key other than the one that it "
4466 "was originally encrypted with by passing the @option{--keygrip} option with "
4467 "the hex encoded keygrip of the public key as its argument. The keygrip may "
4468 "be of any key that @command{gpg-agent} knows about. The "
4469 "@option{--sign-keygrip} option may also be used to sign with an alternate "
4470 "secret key. This option may be needed when using a smartcard. This option "
4471 "has no effect with symmetrically encrypted data files."
4472 "\n"
4473 "The @option{--s2k-count} option sets number of hash iterations for a "
4474 "passphrase. A value less-than @code{65536} will use the machine calibrated "
4475 "value and is the default. This setting only affects new files. To change "
4476 "the setting use the @code{PASSWD} command (@pxref{PASSWD}). This option "
4477 "has no effect with symmetrically encrypted data files."
4480 new_command("ISCACHED", 1, 0, iscached_command, _(
4481 "ISCACHED [--lock] <filename>\n"
4482 "An @emph{OK} response is returned if the specified @var{filename} is found "
4483 "in the file cache. If not found in the cache but exists on the filesystem "
4484 "then @var{GPG_ERR_NO_DATA} is returned. Otherwise a filesystem error is "
4485 "returned."
4486 "\n"
4487 "The @option{lock} option will lock the file mutex of @var{filename} when the "
4488 "file exists; it does not need to be opened nor cached."
4491 new_command("CLEARCACHE", 1, 1, clearcache_command, _(
4492 "CLEARCACHE [<filename>]\n"
4493 "Clears a file cache entry for all or the specified @var{filename}."
4496 new_command("CACHETIMEOUT", 1, 1, cachetimeout_command, _(
4497 "CACHETIMEOUT <filename> <seconds>\n"
4498 "The time in @var{seconds} until @var{filename} will be removed from the "
4499 "cache. @code{-1} will keep the cache entry forever, @code{0} will require "
4500 "the passphrase for each @code{OPEN} or @code{SAVE} command (@pxref{OPEN}, "
4501 "@pxref{SAVE}). @xref{Configuration}, and the @code{cache_timeout} "
4502 "parameter."
4505 new_command("LIST", 0, 1, list_command, _(
4506 "LIST [--inquire] [--no-recurse] [--verbose] [--with-target] [--all] [[!]element[<TAB>[!]child[..]]]\n"
4507 "If no element path is given then a newline separated list of root elements "
4508 "is returned with a data response. If given, then all reachable elements "
4509 "of the specified element path are returned unless the @option{--no-recurse} "
4510 "option is specified. If specified, only the child elements of the element "
4511 "path are returned without recursing into grandchildren. Each resulting "
4512 "element is prefixed with the literal @code{!} character when the element "
4513 "contains no @code{target} attribute. @xref{Target Attribute}, for details."
4514 "\n"
4515 "When the @option{--verbose} option is passed then each element path "
4516 "returned will have zero or more flags appened to it. These flags are "
4517 "delimited from the element path by a single space character. A flag itself "
4518 "is a single character. Flag @code{+} indicates that there are child nodes of "
4519 "the current element path. Flag @code{E} indicates that an element of an "
4520 "element path contained in a @var{target} attribute could not be found. Flag "
4521 "@code{O} indicates that a @var{target} attribute recursion limit was reached "
4522 "(@pxref{Configuration}). Flag @code{T} will append the resolved element path "
4523 "of the @var{target} attribute contained in the current element (see below)."
4524 "\n"
4525 "The @option{--with-target} option implies @option{--verbose} and will append "
4526 "an additional flag @code{T} followed by a single space then an element path. "
4527 "The appended element path is the resolved path (@pxref{REALPATH}) of the "
4528 "current element when it contains a @var{target} attribute. When no "
4529 "@var{target} attribute is found then no flag will be appended."
4530 "\n"
4531 "The @option{--no-recurse} option limits the amount of data returned to only "
4532 "the listing of children of the specified element path and not any "
4533 "grandchildren."
4534 "\n"
4535 "The @option{--all} option lists the entire element tree for each root "
4536 "element. This option also implies option @option{--verbose}."
4537 "\n"
4538 "When the @option{--inquire} option is passed then all remaining non-option "
4539 "arguments are retrieved via a server @emph{INQUIRE}."
4542 new_command("REALPATH", 0, 1, realpath_command, _(
4543 "REALPATH [--inquire] [!]element[<TAB>[!]child[..]]\n"
4544 "Resolves all @code{target} attributes of the specified element path and "
4545 "returns the result with a data response. @xref{Target Attribute}, for details."
4546 "\n"
4547 "When the @option{--inquire} option is passed then all remaining non-option "
4548 "arguments are retrieved via a server @emph{INQUIRE}."
4551 new_command("STORE", 0, 1, store_command, _(
4552 "STORE [!]element[<TAB>[!]child[..]]<TAB>[content]\n"
4553 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
4554 "\n"
4555 "Creates a new element path or modifies the @var{content} of an existing "
4556 "element. If only a single element is specified then a new root element is "
4557 "created. Otherwise, elements are @key{TAB} delimited and the content will be "
4558 "set to the final @key{TAB} delimited element. If no @var{content} is "
4559 "specified after the final @key{TAB}, then the content of the element will "
4560 "be removed, or empty when creating a new element."
4561 "\n"
4562 "The only restriction of an element name is that it not contain whitespace "
4563 "or begin with the literal element character @code{!} unless specifying a "
4564 "literal element (@pxref{Target Attribute}). There is no whitespace between "
4565 "the @key{TAB} delimited elements. It is recommended that the content of an "
4566 "element be base64 encoded when it contains control or @key{TAB} characters "
4567 "to prevent @abbr{XML} parsing and @command{pwmd} syntax errors."
4570 new_command("RENAME", 0, 1, rename_command, _(
4571 "RENAME [--inquire] [!]element[<TAB>[!]child[..]] <value>\n"
4572 "Renames the specified @var{element} to the new @var{value}. If an element of "
4573 "the same name as the @var{value} already exists it will be overwritten."
4574 "\n"
4575 "When the @option{--inquire} option is passed then all remaining non-option "
4576 "arguments are retrieved via a server @emph{INQUIRE}."
4579 new_command("COPY", 0, 1, copy_command, _(
4580 "COPY [--inquire] [!]source[<TAB>[!]child[..]] [!]dest[<TAB>[!]child[..]]\n"
4581 "Copies the entire element tree starting from the child node of the source "
4582 "element, to the destination element path. If the destination element path "
4583 "does not exist then it will be created; otherwise it is overwritten."
4584 "\n"
4585 "Note that attributes from the source element are merged into the "
4586 "destination element when the destination element path exists. When an "
4587 "attribute of the same name exists in both the source and destination "
4588 "elements then the destination attribute will be updated to the source "
4589 "attribute value."
4590 "\n"
4591 "When the @option{--inquire} option is passed then all remaining non-option "
4592 "arguments are retrieved via a server @emph{INQUIRE}."
4595 new_command("MOVE", 0, 1, move_command, _(
4596 "MOVE [--inquire] [!]source[<TAB>[!]child[..]] [[!]dest[<TAB>[!]child[..]]]\n"
4597 "Moves the source element path to the destination element path. If the "
4598 "destination is not specified then it will be moved to the root node of the "
4599 "document. If the destination is specified and exists then it will be "
4600 "overwritten; otherwise non-existing elements of the destination element "
4601 "path will be created."
4602 "\n"
4603 "When the @option{--inquire} option is passed then all remaining non-option "
4604 "arguments are retrieved via a server @emph{INQUIRE}."
4607 new_command("DELETE", 0, 1, delete_command, _(
4608 "DELETE [--inquire] [!]element[<TAB>[!]child[..]]\n"
4609 "Removes the specified element path and all of its children. This may break "
4610 "an element with a @code{target} attribute (@pxref{Target Attribute}) that "
4611 "refers to this element or any of its children."
4612 "\n"
4613 "When the @option{--inquire} option is passed then all remaining non-option "
4614 "arguments are retrieved via a server @emph{INQUIRE}."
4617 new_command("GET", 0, 1, get_command, _(
4618 "GET [--inquire] [!]element[<TAB>[!]child[..]]\n"
4619 "Retrieves the content of the specified element. The content is returned "
4620 "with a data response."
4621 "\n"
4622 "When the @option{--inquire} option is passed then all remaining non-option "
4623 "arguments are retrieved via a server @emph{INQUIRE}."
4626 new_command("ATTR", 0, 1, attr_command, _(
4627 "ATTR [--inquire] SET|GET|DELETE|LIST [<attribute>] [!]element[<TAB>[!]child[..]] ..\n"
4628 "@table @asis\n"
4629 "@item ATTR SET attribute [!]element[<TAB>[!]child[..]] [value]\n"
4630 "\n"
4631 " Stores or updates an @var{attribute} name and optional @var{value} of an "
4632 "element. When no @var{value} is specified any existing value will be removed."
4633 "\n"
4634 "@item ATTR DELETE attribute [!]element[<TAB>[!]child[..]]\n"
4635 "\n"
4636 " Removes an @var{attribute} from an element."
4637 "\n"
4638 "@item ATTR LIST [!]element[<TAB>[!]child[..]]\n"
4639 "\n"
4640 " Retrieves a newline separated list of attributes names and values "
4641 "from the specified element. Each attribute name and value is space delimited."
4642 "\n"
4643 "@item ATTR GET attribute [!]element[<TAB>[!]child[..]]\n"
4644 "\n"
4645 " Retrieves the value of an @var{attribute} from an element."
4646 "@end table\n"
4647 "\n"
4648 "The @code{_name} attribute (case sensitive) cannot be removed nor modified. "
4649 "Use the @code{DELETE} (@pxref{DELETE}) or @code{RENAME} (@pxref{RENAME}) "
4650 "commands instead."
4651 "\n"
4652 "The @code{_mtime} attribute is updated each time an element is modified by "
4653 "either storing content, editing attributes or by deleting a child element. "
4654 "The @code{_ctime} attribute is created for each new element in an element "
4655 "path."
4656 "\n"
4657 "When the @option{--inquire} option is passed then all remaining non-option "
4658 "arguments are retrieved via a server @emph{INQUIRE}."
4659 "\n"
4660 "@xref{Target Attribute}, for details about this special attribute."
4663 new_command("XPATH", 0, 1, xpath_command, _(
4664 "XPATH [--inquire] <expression>[<TAB>[value]]\n"
4665 "Evaluates an XPath @var{expression}. If no @var{value} argument is "
4666 "specified it is assumed the expression is a request to return a result. "
4667 "Otherwise, the result is set to the @var{value} argument and the document is "
4668 "updated. If there is no @var{value} after the @key{TAB} character, the value "
4669 "is assumed to be empty and the document is updated. For example:"
4670 "@sp 1\n"
4671 "@example\n"
4672 "XPATH //element[@@_name='password']@key{TAB}\n"
4673 "@end example\n"
4674 "@sp 1"
4675 "would clear the content of all @code{password} elements in the data file "
4676 "while leaving off the trailing @key{TAB} would return all @code{password} "
4677 "elements in @abbr{XML} format."
4678 "\n"
4679 "When the @option{--inquire} option is passed then all remaining non-option "
4680 "arguments are retrieved via a server @emph{INQUIRE}."
4681 "\n"
4682 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
4683 "expression syntax."
4686 new_command("XPATHATTR", 0, 1, xpathattr_command, _(
4687 "XPATHATTR [--inquire] SET|DELETE <name> <expression>[<TAB>[<value>]]\n"
4688 "Like the @code{XPATH} command (@pxref{XPATH}) but operates on element "
4689 "attributes and does not return a result. For the @var{SET} operation the "
4690 "@var{value} is optional but the field is required. If not specified then "
4691 "the attribute value will be empty. For example:"
4692 "@sp 1"
4693 "@example\n"
4694 "XPATHATTR SET password //element[@@_name='password']@key{TAB}\n"
4695 "@end example\n"
4696 "@sp 1"
4697 "would create an @code{password} attribute for each @code{password} element "
4698 "found in the document. The attribute value will be empty but still exist."
4699 "\n"
4700 "When the @option{--inquire} option is passed then all remaining non-option "
4701 "arguments are retrieved via a server @emph{INQUIRE}."
4702 "\n"
4703 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
4704 "expression syntax."
4707 new_command("IMPORT", 0, 1, import_command, _(
4708 "IMPORT [--root [!]element[<TAB>[!]child[..]]] <content>\n"
4709 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
4710 "\n"
4711 "Like the @code{STORE} command (@pxref{STORE}), but the @var{content} "
4712 "argument is raw @abbr{XML} data. The content is created as a child of "
4713 "the element path specified with the @option{--root} option or at the "
4714 "document root when not specified. Existing elements of the same name will "
4715 "be overwritten."
4716 "\n"
4717 "The content must begin with an @abbr{XML} element node. @xref{Introduction}, "
4718 "for details."
4721 new_command("DUMP", 0, 1, dump_command, _(
4722 "DUMP\n"
4723 "Shows the in memory @abbr{XML} document with indenting. @xref{XPATH}, for "
4724 "dumping a specific node."
4727 new_command("LOCK", 0, 0, lock_command, _(
4728 "LOCK\n"
4729 "Locks the mutex associated with the opened file. This prevents other clients "
4730 "from sending commands to the same opened file until the client "
4731 "that sent this command either disconnects or sends the @code{UNLOCK} "
4732 "command. @xref{UNLOCK}."
4735 new_command("UNLOCK", 1, 0, unlock_command, _(
4736 "UNLOCK\n"
4737 "Unlocks the file mutex which was locked with the @code{LOCK} command or "
4738 "a commands' @option{--lock} option (@pxref{LOCK}, @pxref{OPEN}, "
4739 "@pxref{ISCACHED})."
4742 new_command("GETCONFIG", 1, 1, getconfig_command, _(
4743 "GETCONFIG [filename] <parameter>\n"
4744 "Returns the value of a @command{pwmd} configuration @var{parameter} with a "
4745 "data response. If no file has been opened then the value for @var{filename} "
4746 "or the default from the @samp{global} section will be returned. If a file "
4747 "has been opened and no @var{filename} is specified, a value previously "
4748 "set with the @code{OPTION} command (@pxref{OPTION}) will be returned."
4751 new_command("OPTION", 1, 1, option_command, _(
4752 "OPTION <NAME>=<VALUE>\n"
4753 "Sets a client option @var{name} to @var{value}. The value for an option is "
4754 "kept for the duration of the connection."
4755 "\n"
4756 "@table @asis\n"
4757 "@item DISABLE-PINENTRY\n"
4758 "Disable use of @command{pinentry} for passphrase retrieval. When set, a "
4759 "server inquire is sent to the client to obtain the passphrase. This option "
4760 "may be set as needed before the @pxref{OPEN}, @pxref{PASSWD}, and "
4761 "@pxref{SAVE} commands."
4762 "\n"
4763 "@item PINENTRY-TIMEOUT\n"
4764 "Sets the number of seconds before a pinentry prompt will return an error "
4765 "while waiting for user input."
4766 "\n"
4767 "@item TTYNAME\n"
4768 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4769 "\n"
4770 "@item TTYTYPE\n"
4771 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4772 "\n"
4773 "@item DISPLAY\n"
4774 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4775 "\n"
4776 "@item PINENTRY-DESC\n"
4777 "Sets the description string of the @command{gpg-agent} and @command{pinentry} dialog."
4778 "\n"
4779 "@item PINENTRY-TITLE\n"
4780 "Sets the title string of the @command{gpg-agent} and @command{pinentry} dialog."
4781 "\n"
4782 "@item PINENTRY-PROMPT\n"
4783 "Sets the prompt string of the @command{gpg-agent} and @command{pinentry} dialog."
4784 "\n"
4785 "@item LC-CTYPE\n"
4786 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4787 "\n"
4788 "@item LC-MESSAGES\n"
4789 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4790 "\n"
4791 "@item NAME\n"
4792 "Associates the thread ID of the connection with the specified textual "
4793 "representation. Useful for debugging log messages."
4794 "\n"
4795 "@item LOCK-TIMEOUT\n"
4796 "When not @code{0}, the duration in tenths of a second to wait for the file "
4797 "mutex which has been locked by another thread to be released before returning "
4798 "an error. When @code{-1}, then an error will be returned immediately."
4799 "\n"
4800 "@item LOG-LEVEL\n"
4801 "An integer specifiying the logging level."
4802 "@end table\n"
4805 new_command("LS", 1, 1, ls_command, _(
4806 "LS\n"
4807 "Lists the available data files stored in the data directory "
4808 "(@file{~/.pwmd/data}). The result is a newline separated list of filenames."
4811 new_command("RESET", 1, 1, NULL, _(
4812 "RESET\n"
4813 "Closes the currently opened file but keeps any previously set client options."
4816 new_command("NOP", 1, 1, NULL, _(
4817 "NOP\n"
4818 "Does nothing. Always returns successfully."
4821 /* !END-HELP-TEXT! */
4822 new_command ("CANCEL", 1, 1, NULL, NULL);
4823 new_command ("END", 1, 1, NULL, NULL);
4824 new_command ("BYE", 1, 1, NULL, NULL);
4826 int i;
4827 for (i = 0; command_table[i]; i++);
4828 qsort (command_table, i - 1, sizeof (struct command_table_s *),
4829 sort_commands);
4832 gpg_error_t
4833 register_commands (assuan_context_t ctx)
4835 int i = 0, rc;
4837 for (; command_table[i]; i++)
4839 if (!command_table[i]->handler)
4840 continue;
4842 rc = assuan_register_command (ctx, command_table[i]->name,
4843 command_table[i]->handler,
4844 command_table[i]->help);
4845 if (rc)
4846 return rc;
4849 rc = assuan_register_bye_notify (ctx, bye_notify);
4850 if (rc)
4851 return rc;
4853 rc = assuan_register_reset_notify (ctx, reset_notify);
4854 if (rc)
4855 return rc;
4857 rc = assuan_register_pre_cmd_notify (ctx, command_startup);
4858 if (rc)
4859 return rc;
4861 return assuan_register_post_cmd_notify (ctx, command_finalize);