Disallow non-ASCII characters in an XML element attribute name.
[pwmd.git] / src / commands.c
blob83c1b8700e34789c25d6519990bddebf62047af3
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 assuan_peercred_t peer;
626 struct argv_s *args[] = {
627 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_open_opt_lock},
628 NULL
631 rc = parse_options (&line, args, client);
632 if (rc)
633 return send_error (ctx, rc);
635 req = str_split (line, " ", 2);
636 if (!req)
637 return send_error (ctx, GPG_ERR_SYNTAX);
639 rc = do_validate_peer (ctx, req[0], &peer);
640 if (rc)
642 strv_free (req);
643 return send_error (ctx, rc);
646 pthread_cleanup_push (req_cleanup, req);
647 filename = req[0];
648 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
649 /* This client may have locked a different file with ISCACHED --lock than
650 * the current filename. This will remove that lock. */
651 same_file = !memcmp (md5file, client->md5file, 16) ? 1 : 0;
652 if (client->flags & FLAG_OPEN ||
653 (client->flags & FLAG_HAS_LOCK && !same_file))
655 typeof (client->opts) opts = client->opts;
656 typeof (client->flags) flags = client->flags;
658 if (same_file)
659 client->flags |= FLAG_KEEP_LOCK;
661 cleanup_client (client);
662 client->opts = opts;
663 client->flags |= flags;
664 client->flags &= ~(FLAG_LOCK_CMD);
665 if (!same_file)
666 client->flags &= ~(FLAG_HAS_LOCK | FLAG_NEW);
669 /* Need to lock the mutex here because file_modified() cannot without
670 * knowing the filename. */
671 memcpy (client->md5file, md5file, 16);
672 rc = lock_file_mutex (client, 1);
673 if (!rc)
675 password = req[1] && *req[1] ? req[1] : NULL;
676 #ifdef WITH_AGENT
677 if (IS_PKI (client->crypto))
678 rc = set_pinentry_mode (client->crypto->agent,
679 (client->flags & FLAG_NO_PINENTRY) ? "loopback"
680 : "ask");
681 #endif
682 if (!rc)
684 rc = do_open (ctx, filename, password);
685 if (rc)
686 cleanup_client (client);
688 cleanup_crypto_stage1 (client->crypto);
692 pthread_cleanup_pop (1);
694 if (!rc && client->flags & FLAG_NEW)
695 rc = send_status (ctx, STATUS_NEWFILE, NULL);
697 #ifdef WITH_AGENT
698 (void) kill_scd (client->crypto->agent);
699 #endif
700 return send_error (ctx, rc);
703 static gpg_error_t
704 parse_opt_no_passphrase (void *data, void *value)
706 struct client_s *client = data;
708 (void) value;
709 client->opts |= OPT_NO_PASSPHRASE;
710 return 0;
713 static gpg_error_t
714 parse_save_opt_no_agent (void *data, void *value)
716 struct client_s *client = data;
718 client->opts |= OPT_NO_AGENT;
719 return 0;
722 static gpg_error_t
723 parse_save_opt_cipher (void *data, void *value)
725 struct client_s *client = data;
726 int algo = cipher_string_to_gcrypt ((char *) value);
727 file_header_t *hdr = &client->crypto->save.hdr;
729 if (algo == -1)
730 return GPG_ERR_INV_VALUE;
732 hdr->flags = set_cipher_flag (hdr->flags, algo);
733 return 0;
736 static gpg_error_t
737 parse_save_opt_keygrip (void *data, void *value)
739 struct client_s *client = data;
741 if (!IS_PKI (client->crypto))
742 return GPG_ERR_INV_ARG;
744 #ifdef WITH_AGENT
745 if (client->crypto->save.pkey)
746 gcry_sexp_release (client->crypto->save.pkey);
748 client->crypto->save.pkey = NULL;
749 return get_pubkey (client->crypto, value, &client->crypto->save.pkey);
750 #else
751 return GPG_ERR_INV_ARG;
752 #endif
755 static gpg_error_t
756 parse_save_opt_sign_keygrip (void *data, void *value)
758 struct client_s *client = data;
760 if (!IS_PKI (client->crypto))
761 return GPG_ERR_INV_ARG;
763 #ifdef WITH_AGENT
764 if (client->crypto->save.sigpkey)
765 gcry_sexp_release (client->crypto->save.sigpkey);
767 client->crypto->save.sigpkey = NULL;
768 return get_pubkey (client->crypto, value, &client->crypto->save.sigpkey);
769 #else
770 return GPG_ERR_INV_ARG;
771 #endif
774 static gpg_error_t
775 parse_opt_s2k_count (void *data, void *value)
777 struct client_s *client = data;
778 char *v = value;
780 if (!v || !*v)
781 return GPG_ERR_INV_VALUE;
783 client->crypto->save.s2k_count = strtoul (v, NULL, 10);
784 return 0;
787 static gpg_error_t
788 parse_save_opt_iterations (void *data, void *value)
790 struct client_s *client = data;
791 char *v = value, *p;
792 uint64_t n;
794 if (!v || !*v)
795 return GPG_ERR_INV_VALUE;
797 errno = 0;
798 n = strtoull (v, &p, 10);
799 if (n == UINT64_MAX && errno)
800 return gpg_error_from_errno (errno);
801 else if (p && *p)
802 return GPG_ERR_INV_VALUE;
804 client->crypto->save.hdr.iterations = n;
805 return 0;
808 static gpg_error_t
809 save_finalize (assuan_context_t ctx)
811 struct client_s *client = assuan_get_pointer (ctx);
812 gpg_error_t rc = 0;
813 xmlChar *xmlbuf = NULL;
814 int xmlbuflen;
815 void *key = NULL;
816 size_t keylen = 0;
818 xmlDocDumpFormatMemory (client->doc, &xmlbuf, &xmlbuflen, 0);
819 if (!xmlbuf)
820 return GPG_ERR_ENOMEM;
822 pthread_cleanup_push (xmlFree, xmlbuf);
824 if (!use_agent || ((client->flags & FLAG_NEW)
825 && (client->opts & OPT_NO_AGENT))
826 || !(client->crypto->hdr.flags & PWMD_FLAG_PKI))
828 rc = export_common (ctx, client->flags & FLAG_NO_PINENTRY,
829 client->crypto, xmlbuf, xmlbuflen, client->filename,
830 NULL, &key, &keylen, 1, 1,
831 (client->opts & OPT_NO_PASSPHRASE));
833 #ifdef WITH_AGENT
834 else
836 gcry_sexp_t pubkey = client->crypto->save.pkey;
837 gcry_sexp_t sigkey = client->crypto->save.sigpkey;
839 if (!pubkey)
840 pubkey = client->crypto->pkey_sexp;
842 if (!sigkey)
844 sigkey = client->crypto->sigpkey_sexp;
845 if (!sigkey)
847 gcry_sexp_build (&client->crypto->save.sigpkey, 0, "%S", pubkey);
848 sigkey = client->crypto->save.sigpkey;
852 rc = encrypt_data_file (client->ctx, client->crypto, pubkey, sigkey,
853 client->filename, xmlbuf, xmlbuflen);
854 if (pubkey == client->crypto->save.pkey)
856 if (!rc)
858 gcry_sexp_release (client->crypto->pkey_sexp);
859 client->crypto->pkey_sexp = client->crypto->save.pkey;
860 gcry_pk_get_keygrip (client->crypto->pkey_sexp,
861 client->crypto->grip);
863 else
864 gcry_sexp_release (pubkey);
866 client->crypto->save.pkey = NULL;
869 if (!rc)
870 gcry_pk_get_keygrip (sigkey, client->crypto->sign_grip);
872 if (sigkey == client->crypto->save.sigpkey)
874 if (!rc)
876 if (client->crypto->sigpkey_sexp)
877 gcry_sexp_release (client->crypto->sigpkey_sexp);
879 client->crypto->sigpkey_sexp = client->crypto->save.sigpkey;
880 gcry_pk_get_keygrip (client->crypto->sigpkey_sexp,
881 client->crypto->sign_grip);
883 else
884 gcry_sexp_release (sigkey);
886 client->crypto->save.sigpkey = NULL;
889 #endif
891 if (!rc)
893 int cached;
895 rc = save_common (client->filename, client->crypto, xmlbuf, xmlbuflen,
896 key, keylen, &cached, client->opts & OPT_NO_AGENT);
897 if (rc)
898 gcry_free (key);
900 if (!rc && (!cached || (client->flags & FLAG_NEW)))
901 send_status_all (STATUS_CACHE, NULL);
903 if (!rc)
905 rc = update_checksum (client);
906 client->flags &= ~(FLAG_NEW);
910 pthread_cleanup_pop (1); // xmlFree
911 return rc;
914 static gpg_error_t
915 parse_opt_reset (void *data, void *value)
917 struct client_s *client = data;
919 (void) value;
920 client->opts |= OPT_RESET;
921 return 0;
924 static gpg_error_t
925 save_command (assuan_context_t ctx, char *line)
927 struct client_s *client = assuan_get_pointer (ctx);
928 gpg_error_t rc;
929 struct stat st;
930 struct argv_s *args[] = {
931 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG,
932 parse_opt_no_passphrase},
933 &(struct argv_s) {"cipher", OPTION_TYPE_ARG, parse_save_opt_cipher},
934 &(struct argv_s) {"inquire-keyparam", OPTION_TYPE_NOARG,
935 parse_opt_inquire},
936 &(struct argv_s) {"keygrip", OPTION_TYPE_ARG, parse_save_opt_keygrip},
937 &(struct argv_s) {"sign-keygrip", OPTION_TYPE_ARG,
938 parse_save_opt_sign_keygrip},
939 &(struct argv_s) {"s2k-count", OPTION_TYPE_ARG, parse_opt_s2k_count},
940 &(struct argv_s) {"reset", OPTION_TYPE_NOARG, parse_opt_reset},
941 &(struct argv_s) {"cipher-iterations", OPTION_TYPE_ARG,
942 parse_save_opt_iterations},
943 &(struct argv_s) {"no-agent", OPTION_TYPE_NOARG,
944 parse_save_opt_no_agent},
945 NULL
948 cleanup_save (&client->crypto->save);
949 memcpy (&client->crypto->save.hdr, &client->crypto->hdr,
950 sizeof (file_header_t));
951 client->crypto->save.s2k_count =
952 config_get_ulong (client->filename, "s2k_count");
954 if (client->flags & FLAG_NEW)
955 client->crypto->save.hdr.iterations =
956 config_get_ulonglong (client->filename, "cipher_iterations");
958 rc = parse_options (&line, args, client);
959 if (rc)
960 return send_error (ctx, rc);
962 if (!(client->flags & FLAG_NEW))
963 client->opts &= ~OPT_NO_AGENT;
964 else if (client->opts & OPT_NO_AGENT)
966 client->crypto->save.hdr.flags &= ~PWMD_FLAG_PKI;
967 client->crypto->hdr.flags &= ~PWMD_FLAG_PKI;
970 if ((client->opts & OPT_NO_PASSPHRASE) && !(client->flags & FLAG_NEW)
971 && !(client->opts & OPT_INQUIRE))
972 return send_error (ctx, GPG_ERR_WRONG_KEY_USAGE);
974 if (lstat (client->filename, &st) == -1 && errno != ENOENT)
975 return send_error (ctx, gpg_error_from_errno (errno));
977 if (errno != ENOENT && !S_ISREG (st.st_mode))
979 log_write ("%s: %s", client->filename, pwmd_strerror (GPG_ERR_ENOANO));
980 return send_error (ctx, GPG_ERR_ENOANO);
983 int defer = 0;
984 rc = cache_iscached (client->filename, &defer);
985 if (gpg_err_code (rc) == GPG_ERR_ENOENT && client->flags & FLAG_NEW)
986 rc = 0;
987 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
988 rc = 0;
990 if ((!rc && defer) || config_get_boolean ("global", "require_save_key"))
991 client->opts |= OPT_RESET;
993 if (!rc && (client->opts & OPT_RESET))
995 rc = cache_clear (client->md5file);
996 if (rc)
997 return send_error (ctx, rc);
999 log_write ("%s: %s", client->filename,
1000 pwmd_strerror (GPG_ERR_KEY_EXPIRED));
1001 send_status_all (STATUS_CACHE, NULL);
1004 if (!rc)
1005 rc = update_element_mtime (xmlDocGetRootElement (client->doc));
1007 if (rc)
1008 return send_error (ctx, rc);
1010 #ifdef WITH_AGENT
1011 if (!rc && use_agent && !client->crypto->save.pkey &&
1012 (client->flags & FLAG_NEW || client->opts & OPT_INQUIRE)
1013 && !(client->opts & OPT_NO_AGENT))
1015 rc = set_pinentry_mode (client->crypto->agent,
1016 (client->flags & FLAG_NO_PINENTRY) ? "loopback"
1017 : "ask");
1019 if (!(client->flags & FLAG_NEW))
1021 struct crypto_s *crypto;
1022 char *key = NULL;
1023 size_t keylen = 0;
1025 /* Wanting to generate a new key. Require the key to open the
1026 current file before proceeding reguardless of the
1027 require_save_key configuration parameter. */
1028 rc = cache_clear (client->md5file);
1029 if (!rc)
1031 rc = init_client_crypto (&crypto);
1032 if (!rc)
1033 crypto->client_ctx = client->ctx;
1036 if (!rc)
1037 rc = decrypt_common (client->ctx, client->opts&OPT_INQUIRE, crypto,
1038 client->filename, &key, &keylen);
1040 xfree (key);
1041 cleanup_crypto (&crypto);
1044 if (!rc)
1045 rc = send_status (client->ctx, STATUS_GENKEY, NULL);
1047 if (!rc)
1049 struct inquire_data_s idata = { 0 };
1050 char *params = client->opts & OPT_INQUIRE
1051 ? NULL : default_key_params (client->crypto);
1053 pthread_cleanup_push (xfree, params);
1054 idata.crypto = client->crypto;
1056 if (params)
1058 idata.line = params;
1059 idata.len = strlen (params);
1061 else
1062 idata.preset = 1;
1064 client->crypto->agent->inquire_data = &idata;
1065 client->crypto->agent->inquire_cb = NULL;
1066 rc = generate_key (client->crypto, params,
1067 (client->opts & OPT_NO_PASSPHRASE), 1);
1068 pthread_cleanup_pop (1);
1071 #endif
1073 if (!rc)
1074 rc = save_finalize (ctx);
1076 cleanup_crypto_stage1 (client->crypto);
1077 #ifdef WITH_AGENT
1078 (void) kill_scd (client->crypto->agent);
1079 #endif
1080 return send_error (ctx, rc);
1083 static gpg_error_t
1084 do_delete (assuan_context_t ctx, char *line)
1086 struct client_s *client = assuan_get_pointer (ctx);
1087 gpg_error_t rc;
1088 char **req;
1089 xmlNodePtr n;
1091 if (strchr (line, '\t'))
1092 req = str_split (line, "\t", 0);
1093 else
1094 req = str_split (line, " ", 0);
1096 if (!req || !*req)
1097 return GPG_ERR_SYNTAX;
1099 n = find_root_element (client->doc, &req, &rc, NULL, 0, 0);
1100 if (!n)
1102 strv_free (req);
1103 return rc;
1107 * No sub-node defined. Remove the entire node (root element).
1109 if (!req[1])
1111 if (n)
1113 rc = unlink_node (n);
1114 xmlFreeNode (n);
1117 strv_free (req);
1118 return rc;
1122 find_elements (client->doc, n->children, req + 1, &rc, NULL, NULL, NULL,
1123 0, 0, NULL, 0);
1124 strv_free (req);
1125 if (!n)
1126 return rc;
1128 if (n)
1130 rc = unlink_node (n);
1131 xmlFreeNode (n);
1134 return rc;
1137 static gpg_error_t
1138 delete_command (assuan_context_t ctx, char *line)
1140 struct client_s *client = assuan_get_pointer (ctx);
1141 gpg_error_t rc;
1142 struct argv_s *args[] = {
1143 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1144 NULL
1147 rc = parse_options (&line, args, client);
1148 if (rc)
1149 return send_error (ctx, rc);
1151 if (client->opts & OPT_INQUIRE)
1153 unsigned char *result;
1154 size_t len;
1156 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1157 if (rc)
1158 return send_error (ctx, rc);
1160 line = (char *) result;
1163 rc = do_delete (ctx, line);
1165 if (client->opts & OPT_INQUIRE)
1166 xfree (line);
1168 return send_error (ctx, rc);
1171 static gpg_error_t
1172 store_command (assuan_context_t ctx, char *line)
1174 struct client_s *client = assuan_get_pointer (ctx);
1175 gpg_error_t rc;
1176 size_t len;
1177 unsigned char *result;
1178 char **req;
1179 xmlNodePtr n, parent;
1180 int has_content;
1181 char *content = NULL;
1183 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1184 if (rc)
1185 return send_error (ctx, rc);
1187 req = str_split ((char *) result, "\t", 0);
1188 xfree (result);
1190 if (!req || !*req)
1191 return send_error (ctx, GPG_ERR_SYNTAX);
1193 len = strv_length (req);
1194 has_content = line[strlen (line) - 1] != '\t' && len > 1;
1195 if (*(req + 1) && !valid_element_path (req, has_content))
1197 strv_free (req);
1198 return send_error (ctx, GPG_ERR_INV_VALUE);
1201 if (has_content || !*req[len - 1])
1203 has_content = 1;
1204 content = req[len - 1];
1205 req[len - 1] = NULL;
1208 again:
1209 n = find_root_element (client->doc, &req, &rc, NULL, 0, 0);
1210 if (rc && rc == GPG_ERR_ELEMENT_NOT_FOUND)
1212 rc = new_root_element (client->doc, *req);
1213 if (rc)
1215 strv_free (req);
1216 return send_error (ctx, GPG_ERR_SYNTAX);
1219 goto again;
1222 if (!n)
1224 strv_free (req);
1225 return send_error (ctx, rc);
1228 parent = n;
1230 if (req[1] && *req[1])
1232 if (!n->children)
1233 parent = create_elements_cb (n, req + 1, &rc, NULL);
1234 else
1235 parent = find_elements (client->doc, n->children, req + 1, &rc,
1236 NULL, NULL, create_elements_cb, 0, 0, NULL,
1240 if (!rc && len > 1)
1242 n = find_text_node (parent->children);
1243 if (n)
1244 xmlNodeSetContent (n, (xmlChar *) content);
1245 else
1246 xmlNodeAddContent (parent, (xmlChar *) content);
1248 update_element_mtime (parent);
1251 xfree (content);
1252 strv_free (req);
1253 return send_error (ctx, rc);
1256 static gpg_error_t
1257 xfer_data (assuan_context_t ctx, const char *line, int total)
1259 int to_send;
1260 int sent = 0;
1261 gpg_error_t rc;
1262 int progress = config_get_integer ("global", "xfer_progress");
1263 int flush = 0;
1265 progress =
1266 progress > 0 ? (progress / ASSUAN_LINELENGTH) * ASSUAN_LINELENGTH : 0;
1267 to_send = total < ASSUAN_LINELENGTH ? total : ASSUAN_LINELENGTH;
1268 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1270 if (rc)
1271 return rc;
1273 again:
1276 if (sent + to_send > total)
1277 to_send = total - sent;
1279 rc = assuan_send_data (ctx, flush ? NULL : (char *) line + sent,
1280 flush ? 0 : to_send);
1281 if (!rc)
1283 sent += flush ? 0 : to_send;
1285 if ((progress && !(sent % progress) && sent != total) ||
1286 (sent == total && flush))
1287 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1289 if (!flush && !rc && sent == total)
1291 flush = 1;
1292 goto again;
1296 while (!rc && sent < total);
1298 return rc;
1301 static gpg_error_t
1302 do_get (assuan_context_t ctx, char *line)
1304 struct client_s *client = assuan_get_pointer (ctx);
1305 gpg_error_t rc;
1306 char **req;
1307 xmlNodePtr n;
1309 req = str_split (line, "\t", 0);
1311 if (!req || !*req)
1313 strv_free (req);
1314 return GPG_ERR_SYNTAX;
1317 n = find_root_element (client->doc, &req, &rc, NULL, 0, 0);
1318 if (!n)
1320 strv_free (req);
1321 return rc;
1324 if (req[1])
1326 find_elements (client->doc, n->children, req + 1, &rc, NULL, NULL, NULL,
1327 0, 0, NULL, 0);
1329 strv_free (req);
1330 if (rc)
1331 return rc;
1333 if (!n || !n->children)
1334 return GPG_ERR_NO_DATA;
1336 n = find_text_node (n->children);
1337 if (!n || !n->content || !*n->content)
1338 return GPG_ERR_NO_DATA;
1340 rc = xfer_data (ctx, (char *) n->content, xmlStrlen (n->content));
1341 return rc;
1344 static gpg_error_t
1345 get_command (assuan_context_t ctx, char *line)
1347 struct client_s *client = assuan_get_pointer (ctx);
1348 gpg_error_t rc;
1349 struct argv_s *args[] = {
1350 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1351 NULL
1354 rc = parse_options (&line, args, client);
1355 if (rc)
1356 return send_error (ctx, rc);
1358 if (client->opts & OPT_INQUIRE)
1360 unsigned char *result;
1361 size_t len;
1363 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1364 if (rc)
1365 return send_error (ctx, rc);
1367 line = (char *) result;
1370 rc = do_get (ctx, line);
1372 if (client->opts & OPT_INQUIRE)
1373 xfree (line);
1375 return send_error (ctx, rc);
1378 static void list_command_cleanup1 (void *arg);
1379 static gpg_error_t
1380 realpath_command (assuan_context_t ctx, char *line)
1382 struct string_s *string = NULL;
1383 gpg_error_t rc;
1384 struct client_s *client = assuan_get_pointer (ctx);
1385 struct argv_s *args[] = {
1386 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1387 NULL
1390 rc = parse_options (&line, args, client);
1391 if (rc)
1392 return send_error (ctx, rc);
1394 if (client->opts & OPT_INQUIRE)
1396 unsigned char *result;
1397 size_t len;
1399 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1400 if (rc)
1401 return send_error (ctx, rc);
1403 line = (char *) result;
1406 rc = build_realpath (client->doc, line, &string);
1407 if (!rc)
1409 pthread_cleanup_push (list_command_cleanup1, string);
1410 rc = xfer_data (ctx, string->str, string->len);
1411 pthread_cleanup_pop (1);
1414 if (client->opts & OPT_INQUIRE)
1415 xfree (line);
1417 return send_error (ctx, rc);
1420 static void
1421 list_command_cleanup1 (void *arg)
1423 if (arg)
1424 string_free ((struct string_s *) arg, 1);
1427 static void
1428 list_command_cleanup2 (void *arg)
1430 struct element_list_s *elements = arg;
1432 if (elements)
1434 if (elements->list)
1436 int total = slist_length (elements->list);
1437 int i;
1439 for (i = 0; i < total; i++)
1441 char *tmp = slist_nth_data (elements->list, i);
1442 xfree (tmp);
1445 slist_free (elements->list);
1448 if (elements->prefix)
1449 xfree (elements->prefix);
1451 if (elements->req)
1452 strv_free (elements->req);
1454 xfree (elements);
1458 static gpg_error_t
1459 parse_list_opt_norecurse (void *data, void *value)
1461 struct client_s *client = data;
1463 client->opts &= ~(OPT_LIST_RECURSE);
1464 return 0;
1467 static gpg_error_t
1468 parse_list_opt_verbose (void *data, void *value)
1470 struct client_s *client = data;
1472 client->opts |= OPT_LIST_VERBOSE;
1473 return 0;
1476 static gpg_error_t
1477 parse_list_opt_target (void *data, void *value)
1479 struct client_s *client = data;
1481 client->opts |= OPT_LIST_WITH_TARGET;
1482 return 0;
1485 static gpg_error_t
1486 parse_list_opt_all (void *data, void *value)
1488 struct client_s *client = data;
1490 client->opts |= OPT_LIST_ALL;
1491 return 0;
1494 static gpg_error_t
1495 list_path_once (struct client_s *client, char *line,
1496 struct element_list_s *elements, struct string_s *result)
1498 gpg_error_t rc;
1500 elements->req = str_split (line, " ", 0);
1501 if (!elements->req)
1502 strv_printf (&elements->req, "%s", line);
1504 rc = create_path_list (client->doc, elements, *elements->req);
1505 if (rc == GPG_ERR_ELOOP && elements->verbose)
1506 rc = 0;
1508 if (!rc)
1510 int total = slist_length (elements->list);
1511 int i;
1513 if (!total)
1514 rc = GPG_ERR_NO_DATA;
1516 if (!rc)
1518 if (!rc)
1520 for (i = 0; i < total; i++)
1522 char *tmp = slist_nth_data (elements->list, i);
1524 string_append_printf (result, "%s%s", tmp,
1525 i + 1 == total ? "" : "\n");
1529 else
1530 rc = GPG_ERR_NO_DATA;
1533 return rc;
1536 static int
1537 has_list_flag (char *path, char *flags)
1539 char *p = path;
1541 while (*p && *++p != ' ');
1543 if (!*p)
1544 return 0;
1546 for (; *p; p++)
1548 char *f;
1550 for (f = flags; *f && *f != ' '; f++)
1552 if (*p == *f)
1553 return 1;
1557 return 0;
1560 static gpg_error_t
1561 do_list (assuan_context_t ctx, char *line)
1563 struct client_s *client = assuan_get_pointer (ctx);
1564 gpg_error_t rc;
1565 struct element_list_s *elements = NULL;
1567 elements = xcalloc (1, sizeof (struct element_list_s));
1568 if (!elements)
1569 return GPG_ERR_ENOMEM;
1571 elements->recurse = client->opts & OPT_LIST_RECURSE;
1572 elements->verbose =
1573 (client->opts & OPT_LIST_VERBOSE) | (client->opts & OPT_LIST_WITH_TARGET);
1574 elements->with_target = client->opts & OPT_LIST_WITH_TARGET;
1576 if (!line || !*line)
1578 struct string_s *str = NULL;
1580 pthread_cleanup_push (list_command_cleanup2, elements);
1581 rc = list_root_elements (client->doc, &str, elements->verbose,
1582 elements->with_target);
1583 pthread_cleanup_pop (1);
1584 pthread_cleanup_push (list_command_cleanup1, str);
1586 if (!rc)
1588 if (client->opts & OPT_LIST_ALL)
1590 char **roots = str_split (str->str, "\n", 0);
1591 char **p;
1593 pthread_cleanup_push (req_cleanup, roots);
1594 string_truncate (str, 0);
1596 for (p = roots; *p; p++)
1598 if (strchr (*p, ' '))
1600 if (has_list_flag (*p, "EO"))
1602 string_append_printf (str, "%s%s", *p,
1603 *(p + 1) ? "\n" : "");
1604 continue;
1608 elements = xcalloc (1, sizeof (struct element_list_s));
1609 if (!elements)
1611 rc = GPG_ERR_ENOMEM;
1612 break;
1615 elements->recurse = client->opts & OPT_LIST_RECURSE;
1616 elements->verbose =
1617 (client->opts & OPT_LIST_VERBOSE) | (client->opts &
1618 OPT_LIST_WITH_TARGET);
1619 elements->with_target = client->opts & OPT_LIST_WITH_TARGET;
1620 pthread_cleanup_push (list_command_cleanup2, elements);
1621 rc = list_path_once (client, *p, elements, str);
1622 pthread_cleanup_pop (1);
1623 if (rc)
1624 break;
1626 if (*(p + 1))
1627 string_append (str, "\n");
1630 pthread_cleanup_pop (1);
1633 if (!rc)
1634 rc = xfer_data (ctx, str->str, str->len);
1637 pthread_cleanup_pop (1);
1638 return rc;
1641 pthread_cleanup_push (list_command_cleanup2, elements);
1642 struct string_s *str = string_new (NULL);
1643 pthread_cleanup_push (list_command_cleanup1, str);
1644 rc = list_path_once (client, line, elements, str);
1645 if (!rc)
1646 rc = xfer_data (ctx, str->str, str->len);
1648 pthread_cleanup_pop (1);
1649 pthread_cleanup_pop (1);
1650 return rc;
1653 static gpg_error_t
1654 list_command (assuan_context_t ctx, char *line)
1656 struct client_s *client = assuan_get_pointer (ctx);
1657 gpg_error_t rc;
1658 struct argv_s *args[] = {
1659 &(struct argv_s) {"no-recurse", OPTION_TYPE_NOARG,
1660 parse_list_opt_norecurse},
1661 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_list_opt_verbose},
1662 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1663 &(struct argv_s) {"with-target", OPTION_TYPE_NOARG,
1664 parse_list_opt_target},
1665 &(struct argv_s) {"all", OPTION_TYPE_NOARG, parse_list_opt_all},
1666 NULL
1669 if (disable_list_and_dump == 1)
1670 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
1672 client->opts |= OPT_LIST_RECURSE;
1673 rc = parse_options (&line, args, client);
1674 if (rc)
1675 return send_error (ctx, rc);
1677 if (client->opts & OPT_LIST_ALL)
1678 client->opts |= OPT_LIST_RECURSE | OPT_LIST_VERBOSE;
1680 if (client->opts & OPT_INQUIRE)
1682 unsigned char *result;
1683 size_t len;
1685 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1686 if (rc)
1687 return send_error (ctx, rc);
1689 line = (char *) result;
1692 rc = do_list (ctx, line);
1694 if (client->opts & OPT_INQUIRE)
1695 xfree (line);
1697 return send_error (ctx, rc);
1701 * req[0] - element path
1703 static gpg_error_t
1704 attribute_list (assuan_context_t ctx, char **req)
1706 struct client_s *client = assuan_get_pointer (ctx);
1707 char **attrlist = NULL;
1708 int i = 0;
1709 char **path = NULL;
1710 xmlAttrPtr a;
1711 xmlNodePtr n, an;
1712 char *line;
1713 gpg_error_t rc;
1715 if (!req || !req[0])
1716 return GPG_ERR_SYNTAX;
1718 if ((path = str_split (req[0], "\t", 0)) == NULL)
1721 * The first argument may be only a root element.
1723 if ((path = str_split (req[0], " ", 0)) == NULL)
1724 return GPG_ERR_SYNTAX;
1727 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
1729 if (!n)
1731 strv_free (path);
1732 return rc;
1735 if (path[1])
1737 n = find_elements (client->doc, n->children, path + 1, &rc,
1738 NULL, NULL, NULL, 0, 0, NULL, 0);
1740 if (!n)
1742 strv_free (path);
1743 return rc;
1747 strv_free (path);
1749 for (a = n->properties; a; a = a->next)
1751 char **pa;
1753 if ((pa = xrealloc (attrlist, (i + 2) * sizeof (char *))) == NULL)
1755 if (attrlist)
1756 strv_free (attrlist);
1758 log_write ("%s(%i): %s", __FILE__, __LINE__,
1759 pwmd_strerror (GPG_ERR_ENOMEM));
1760 return GPG_ERR_ENOMEM;
1763 attrlist = pa;
1764 an = a->children;
1765 attrlist[i] = str_asprintf ("%s %s", (char *) a->name,
1767 && an->content ? (char *) an->content : "");
1769 if (!attrlist[i])
1771 strv_free (attrlist);
1772 log_write ("%s(%i): %s", __FILE__, __LINE__,
1773 pwmd_strerror (GPG_ERR_ENOMEM));
1774 return GPG_ERR_ENOMEM;
1777 attrlist[++i] = NULL;
1780 if (!attrlist)
1781 return GPG_ERR_NO_DATA;
1783 line = strv_join ("\n", attrlist);
1785 if (!line)
1787 log_write ("%s(%i): %s", __FILE__, __LINE__,
1788 pwmd_strerror (GPG_ERR_ENOMEM));
1789 strv_free (attrlist);
1790 return GPG_ERR_ENOMEM;
1793 pthread_cleanup_push (xfree, line);
1794 pthread_cleanup_push (req_cleanup, attrlist);
1795 rc = xfer_data (ctx, line, strlen (line));
1796 pthread_cleanup_pop (1);
1797 pthread_cleanup_pop (1);
1798 return rc;
1802 * req[0] - attribute
1803 * req[1] - element path
1805 static gpg_error_t
1806 attribute_delete (struct client_s *client, char **req)
1808 xmlNodePtr n;
1809 char **path = NULL;
1810 gpg_error_t rc;
1812 if (!req || !req[0] || !req[1])
1813 return GPG_ERR_SYNTAX;
1815 if (!strcmp (req[0], "_name"))
1816 return GPG_ERR_INV_ATTR;
1818 if ((path = str_split (req[1], "\t", 0)) == NULL)
1821 * The first argument may be only a root element.
1823 if ((path = str_split (req[1], " ", 0)) == NULL)
1824 return GPG_ERR_SYNTAX;
1827 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
1828 if (!n)
1829 goto fail;
1831 if (path[1])
1833 n = find_elements (client->doc, n->children, path + 1, &rc,
1834 NULL, NULL, NULL, 0, 0, NULL, 0);
1835 if (!n)
1836 goto fail;
1839 rc = delete_attribute (n, (xmlChar *) req[0]);
1841 fail:
1842 strv_free (path);
1843 return rc;
1846 static xmlNodePtr
1847 create_element_path (struct client_s *client,
1848 char ***elements, gpg_error_t * rc, xmlNodePtr parent)
1850 char **req = *elements;
1851 char **req_orig = strv_dup (req);
1852 xmlNodePtr n = NULL;
1854 *rc = 0;
1856 if (!req_orig)
1858 *rc = GPG_ERR_ENOMEM;
1859 log_write ("%s(%i): %s", __FILE__, __LINE__,
1860 pwmd_strerror (GPG_ERR_ENOMEM));
1861 goto fail;
1864 again:
1865 n = find_root_element (client->doc, &req, rc, NULL, 0, 0);
1866 if (!n)
1868 if (*rc != GPG_ERR_ELEMENT_NOT_FOUND)
1869 goto fail;
1871 *rc = new_root_element (client->doc, req[0]);
1872 if (*rc)
1873 goto fail;
1875 goto again;
1877 else if (n == parent)
1879 *rc = GPG_ERR_CONFLICT;
1880 goto fail;
1883 if (req[1])
1885 if (!n->children)
1886 n = create_target_elements_cb (n, req + 1, rc, NULL);
1887 else
1888 n = find_elements (client->doc, n->children, req + 1, rc, NULL, NULL,
1889 create_target_elements_cb, 0, 0, parent, 0);
1891 if (!n)
1892 goto fail;
1895 * Reset the position of the element tree now that the elements
1896 * have been created.
1898 strv_free (req);
1899 req = req_orig;
1900 req_orig = NULL;
1901 n = find_root_element (client->doc, &req, rc, NULL, 0, 0);
1902 if (!n)
1903 goto fail;
1905 n = find_elements (client->doc, n->children, req + 1, rc,
1906 NULL, NULL, NULL, 0, 0, NULL, 0);
1907 if (!n)
1908 goto fail;
1911 fail:
1912 if (req_orig)
1913 strv_free (req_orig);
1915 *elements = req;
1916 return n;
1920 * Creates a "target" attribute. When other commands encounter an element with
1921 * this attribute, the element path is modified to the target value. If the
1922 * source element path doesn't exist when using 'ATTR SET target', it is
1923 * created, but the destination element path must exist.
1925 * req[0] - source element path
1926 * req[1] - destination element path
1928 static gpg_error_t
1929 target_attribute (struct client_s *client, char **req)
1931 char **src, **dst, *line = NULL, **odst = NULL;
1932 gpg_error_t rc;
1933 xmlNodePtr n;
1935 if (!req || !req[0] || !req[1])
1936 return GPG_ERR_SYNTAX;
1938 if ((src = str_split (req[0], "\t", 0)) == NULL)
1941 * The first argument may be only a root element.
1943 if ((src = str_split (req[0], " ", 0)) == NULL)
1944 return GPG_ERR_SYNTAX;
1947 if (!valid_element_path (src, 0))
1948 return GPG_ERR_INV_VALUE;
1950 if ((dst = str_split (req[1], "\t", 0)) == NULL)
1953 * The first argument may be only a root element.
1955 if ((dst = str_split (req[1], " ", 0)) == NULL)
1957 rc = GPG_ERR_SYNTAX;
1958 goto fail;
1962 odst = strv_dup (dst);
1963 if (!odst)
1965 rc = GPG_ERR_ENOMEM;
1966 goto fail;
1969 n = find_root_element (client->doc, &dst, &rc, NULL, 0, 0);
1971 * Make sure the destination element path exists.
1973 if (!n)
1974 goto fail;
1976 if (dst[1])
1978 n = find_elements (client->doc, n->children, dst + 1, &rc,
1979 NULL, NULL, NULL, 0, 0, NULL, 0);
1980 if (!n)
1981 goto fail;
1984 rc = validate_target_attribute (client->doc, req[0], n);
1985 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
1986 goto fail;
1988 n = create_element_path (client, &src, &rc, NULL);
1989 if (rc)
1990 goto fail;
1992 line = strv_join ("\t", odst);
1993 if (!line)
1995 rc = GPG_ERR_ENOMEM;
1996 goto fail;
1999 rc = add_attribute (n, "target", line);
2001 fail:
2002 xfree (line);
2003 strv_free (src);
2004 strv_free (dst);
2005 strv_free (odst);
2006 return rc;
2010 * req[0] - attribute
2011 * req[1] - element path
2013 static gpg_error_t
2014 attribute_get (assuan_context_t ctx, char **req)
2016 struct client_s *client = assuan_get_pointer (ctx);
2017 xmlNodePtr n;
2018 xmlChar *a;
2019 char **path = NULL;
2020 gpg_error_t rc;
2022 if (!req || !req[0] || !req[1])
2023 return GPG_ERR_SYNTAX;
2025 if (strchr (req[1], '\t'))
2027 if ((path = str_split (req[1], "\t", 0)) == NULL)
2028 return GPG_ERR_SYNTAX;
2030 else
2032 if ((path = str_split (req[1], " ", 0)) == NULL)
2033 return GPG_ERR_SYNTAX;
2036 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
2038 if (!n)
2039 goto fail;
2041 if (path[1])
2043 n = find_elements (client->doc, n->children, path + 1, &rc,
2044 NULL, NULL, NULL, 0, 0, NULL, 0);
2046 if (!n)
2047 goto fail;
2050 strv_free (path);
2052 if ((a = xmlGetProp (n, (xmlChar *) req[0])) == NULL)
2053 return GPG_ERR_NOT_FOUND;
2055 pthread_cleanup_push (xmlFree, a);
2057 if (*a)
2058 rc = xfer_data (ctx, (char *) a, xmlStrlen (a));
2059 else
2060 rc = GPG_ERR_NO_DATA;
2062 pthread_cleanup_pop (1);
2063 return rc;
2065 fail:
2066 strv_free (path);
2067 return rc;
2071 * req[0] - attribute
2072 * req[1] - element path
2073 * req[2] - value
2075 static gpg_error_t
2076 attribute_set (struct client_s *client, char **req)
2078 char **path = NULL;
2079 gpg_error_t rc;
2080 xmlNodePtr n;
2082 if (!req || !req[0] || !req[1])
2083 return GPG_ERR_SYNTAX;
2086 * Reserved attribute names.
2088 if (!strcmp (req[0], "_name"))
2089 return GPG_ERR_INV_ATTR;
2090 else if (!strcmp (req[0], "target"))
2091 return target_attribute (client, req + 1);
2092 else if (!valid_xml_attribute (req[0]))
2093 return GPG_ERR_INV_VALUE;
2095 if ((path = str_split (req[1], "\t", 0)) == NULL)
2098 * The first argument may be only a root element.
2100 if ((path = str_split (req[1], " ", 0)) == NULL)
2101 return GPG_ERR_SYNTAX;
2104 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
2106 if (!n)
2107 goto fail;
2109 if (path[1])
2111 n = find_elements (client->doc, n->children, path + 1, &rc,
2112 NULL, NULL, NULL, 0, 0, NULL, 0);
2114 if (!n)
2115 goto fail;
2118 rc = add_attribute (n, req[0], req[2]);
2120 fail:
2121 strv_free (path);
2122 return rc;
2126 * req[0] - command
2127 * req[1] - attribute name or element path if command is LIST
2128 * req[2] - element path
2129 * req[2] - element path or value
2132 static gpg_error_t
2133 do_attr (assuan_context_t ctx, char *line)
2135 struct client_s *client = assuan_get_pointer (ctx);
2136 gpg_error_t rc = 0;
2137 char **req;
2139 req = str_split (line, " ", 4);
2140 if (!req || !req[0] || !req[1])
2142 strv_free (req);
2143 return GPG_ERR_SYNTAX;
2146 pthread_cleanup_push (req_cleanup, req);
2148 if (strcasecmp (req[0], "SET") == 0)
2149 rc = attribute_set (client, req + 1);
2150 else if (strcasecmp (req[0], "GET") == 0)
2151 rc = attribute_get (ctx, req + 1);
2152 else if (strcasecmp (req[0], "DELETE") == 0)
2153 rc = attribute_delete (client, req + 1);
2154 else if (strcasecmp (req[0], "LIST") == 0)
2155 rc = attribute_list (ctx, req + 1);
2156 else
2157 rc = GPG_ERR_SYNTAX;
2159 pthread_cleanup_pop (1);
2160 return rc;
2163 static gpg_error_t
2164 attr_command (assuan_context_t ctx, char *line)
2166 struct client_s *client = assuan_get_pointer (ctx);
2167 gpg_error_t rc;
2168 struct argv_s *args[] = {
2169 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2170 NULL
2173 rc = parse_options (&line, args, client);
2174 if (rc)
2175 return send_error (ctx, rc);
2177 if (client->opts & OPT_INQUIRE)
2179 unsigned char *result;
2180 size_t len;
2182 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2183 if (rc)
2184 return send_error (ctx, rc);
2186 line = (char *) result;
2189 rc = do_attr (ctx, line);
2191 if (client->opts & OPT_INQUIRE)
2192 xfree (line);
2194 return send_error (ctx, rc);
2197 static gpg_error_t
2198 parse_iscached_opt_lock (void *data, void *value)
2200 struct client_s *client = data;
2202 (void) value;
2203 client->opts |= OPT_LOCK;
2204 return 0;
2207 static gpg_error_t
2208 iscached_command (assuan_context_t ctx, char *line)
2210 struct client_s *client = assuan_get_pointer (ctx);
2211 gpg_error_t rc;
2212 unsigned char md5file[16];
2213 struct argv_s *args[] = {
2214 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_iscached_opt_lock},
2215 NULL
2218 if (!line || !*line)
2219 return send_error (ctx, GPG_ERR_SYNTAX);
2221 rc = parse_options (&line, args, client);
2222 if (rc)
2223 return send_error (ctx, rc);
2224 else if (!valid_filename (line))
2225 return send_error (ctx, GPG_ERR_INV_VALUE);
2227 rc = cache_iscached (line, NULL);
2228 if (client->opts & OPT_LOCK
2229 && (!rc || gpg_err_code (rc) == GPG_ERR_NO_DATA))
2231 gpg_error_t trc = rc;
2232 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2233 if (memcmp (md5file, client->md5file, 16))
2234 cleanup_client (client);
2236 memcpy (client->md5file, md5file, 16);
2237 rc = do_lock (client, 1);
2238 if (!rc)
2239 rc = trc;
2242 return send_error (ctx, rc);
2245 static gpg_error_t
2246 clearcache_command (assuan_context_t ctx, char *line)
2248 gpg_error_t rc = 0, all_rc = 0;
2249 unsigned char md5file[16];
2250 int i;
2251 int t;
2252 int all = 0;
2253 struct client_thread_s *once = NULL;
2255 cache_lock ();
2256 MUTEX_LOCK (&cn_mutex);
2257 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
2259 if (!line || !*line)
2260 all = 1;
2262 t = slist_length (cn_thread_list);
2264 for (i = 0; i < t; i++)
2266 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2267 assuan_peercred_t peer;
2269 if (!thd->cl)
2270 continue;
2272 /* Lock each connected clients' file mutex to prevent any other client
2273 * from accessing the cache entry (the file mutex is locked upon
2274 * command startup). The cache for the entry is not cleared if the
2275 * file mutex is locked by another client to prevent this function
2276 * from blocking.
2278 if (all)
2280 if (thd->cl->filename)
2282 rc = do_validate_peer (ctx, thd->cl->filename, &peer);
2283 all_rc = !all_rc ? rc : all_rc;
2284 if (rc)
2286 rc = 0;
2287 continue;
2291 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0, -1);
2292 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2294 if (pthread_equal (pthread_self (), thd->tid))
2295 rc = 0;
2296 else
2298 if (!thd->cl->filename ||
2299 cache_iscached (thd->cl->filename,
2300 NULL) == GPG_ERR_NO_DATA)
2302 rc = 0;
2303 continue;
2306 cache_defer_clear (thd->cl->md5file);
2309 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
2311 rc = 0;
2312 continue;
2315 if (!rc)
2317 rc = cache_clear (thd->cl->md5file);
2318 cache_unlock_mutex (thd->cl->md5file, 0);
2321 if (rc)
2322 all_rc = rc;
2324 rc = 0;
2326 /* A single data filename was specified. Lock only this data file
2327 * mutex and free the cache entry. */
2328 else
2330 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2331 rc = do_validate_peer (ctx, line, &peer);
2333 if (!rc && !memcmp (thd->cl->md5file, md5file, sizeof (md5file)))
2335 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0,
2336 -1);
2337 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2339 if (pthread_equal (pthread_self (), thd->tid))
2340 rc = 0;
2343 if (!rc)
2345 once = thd;
2346 rc = cache_clear (thd->cl->md5file);
2347 cache_unlock_mutex (thd->cl->md5file, 0);
2349 else
2351 cache_defer_clear (thd->cl->md5file);
2354 break;
2359 /* Only connected clients' cache entries have been cleared. Now clear any
2360 * remaining cache entries without clients but only if there wasn't an
2361 * error from above since this would defeat the locking check of the
2362 * remaining entries. */
2363 if (!all_rc && all)
2365 cache_clear (NULL);
2368 /* No clients are using the specified file. */
2369 else if (!all_rc && !rc && !once)
2371 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2372 rc = cache_clear (md5file);
2375 /* Release the connection mutex. */
2376 pthread_cleanup_pop (1);
2377 cache_unlock ();
2379 if (!rc)
2380 send_status_all (STATUS_CACHE, NULL);
2382 /* One or more files were locked while clearing all cache entries. */
2383 if (all_rc)
2384 rc = all_rc;
2386 return send_error (ctx, rc);
2389 static gpg_error_t
2390 cachetimeout_command (assuan_context_t ctx, char *line)
2392 unsigned char md5file[16];
2393 int timeout;
2394 char **req = str_split (line, " ", 0);
2395 char *p;
2396 gpg_error_t rc = 0;
2397 assuan_peercred_t peer;
2399 if (!req || !*req || !req[1])
2401 strv_free (req);
2402 return send_error (ctx, GPG_ERR_SYNTAX);
2405 errno = 0;
2406 timeout = (int) strtol (req[1], &p, 10);
2407 if (errno != 0 || *p || timeout < -1)
2409 strv_free (req);
2410 return send_error (ctx, GPG_ERR_SYNTAX);
2413 rc = do_validate_peer (ctx, req[0], &peer);
2414 if (!rc)
2416 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, req[0], strlen (req[0]));
2417 rc = cache_set_timeout (md5file, timeout);
2418 if (!rc || gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
2420 rc = 0;
2421 MUTEX_LOCK (&rcfile_mutex);
2422 config_set_int_param (&global_config, req[0], "cache_timeout",
2423 req[1]);
2424 MUTEX_UNLOCK (&rcfile_mutex);
2428 strv_free (req);
2429 return send_error (ctx, rc);
2432 static gpg_error_t
2433 dump_command (assuan_context_t ctx, char *line)
2435 xmlChar *xml;
2436 int len;
2437 struct client_s *client = assuan_get_pointer (ctx);
2438 gpg_error_t rc;
2440 if (disable_list_and_dump == 1)
2441 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2443 xmlDocDumpFormatMemory (client->doc, &xml, &len, 1);
2445 if (!xml)
2447 log_write ("%s(%i): %s", __FILE__, __LINE__,
2448 pwmd_strerror (GPG_ERR_ENOMEM));
2449 return send_error (ctx, GPG_ERR_ENOMEM);
2452 pthread_cleanup_push (xmlFree, xml);
2453 rc = xfer_data (ctx, (char *) xml, len);
2454 pthread_cleanup_pop (1);
2455 return send_error (ctx, rc);
2458 static gpg_error_t
2459 getconfig_command (assuan_context_t ctx, char *line)
2461 struct client_s *client = assuan_get_pointer (ctx);
2462 gpg_error_t rc = 0;
2463 char filename[255] = { 0 }, param[747] = { 0 };
2464 char *p, *tmp = NULL, *fp = client->filename, *paramp = line;
2466 if (!line || !*line)
2467 return send_error (ctx, GPG_ERR_SYNTAX);
2469 if (strchr (line, ' '))
2471 sscanf (line, " %254[^ ] %746c", filename, param);
2472 paramp = param;
2473 fp = filename;
2476 if (fp && !valid_filename (fp))
2477 return send_error (ctx, GPG_ERR_INV_VALUE);
2479 paramp = str_down (paramp);
2480 if (!strcmp (paramp, "cipher") && fp)
2482 struct crypto_s *crypto = NULL;
2484 rc = init_client_crypto (&crypto);
2485 if (!rc)
2487 rc = read_data_header (fp, &crypto->hdr, NULL, NULL);
2488 if (!rc)
2490 const char *t =
2491 gcry_cipher_algo_name (cipher_to_gcrypt (crypto->hdr.flags));
2492 if (t)
2494 tmp = str_dup (t);
2495 if (tmp)
2496 str_down (tmp);
2501 UPDATE_AGENT_CTX (client, crypto);
2502 cleanup_crypto (&crypto);
2503 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
2504 return send_error (ctx, rc);
2506 if (!rc && tmp)
2507 goto done;
2509 else if (!strcmp (paramp, "cipher_iterations") && fp)
2511 struct crypto_s *crypto = NULL;
2513 rc = init_client_crypto (&crypto);
2514 if (!rc)
2516 rc = read_data_header (fp, &crypto->hdr, NULL, NULL);
2517 if (!rc)
2519 tmp = str_asprintf ("%llu",
2520 (unsigned long long) crypto->hdr.
2521 iterations);
2522 if (!tmp)
2523 rc = GPG_ERR_ENOMEM;
2527 UPDATE_AGENT_CTX (client, crypto);
2528 cleanup_crypto (&crypto);
2529 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
2530 return send_error (ctx, rc);
2532 if (!rc && tmp)
2533 goto done;
2535 else if (!strcmp (paramp, "passphrase"))
2536 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2538 p = config_get_value (fp ? fp : "global", paramp);
2539 if (!p)
2540 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2542 tmp = expand_homedir (p);
2543 xfree (p);
2544 if (!tmp)
2546 log_write ("%s(%i): %s", __FILE__, __LINE__,
2547 pwmd_strerror (GPG_ERR_ENOMEM));
2548 return send_error (ctx, GPG_ERR_ENOMEM);
2551 done:
2552 p = tmp;
2553 pthread_cleanup_push (xfree, p);
2554 rc = xfer_data (ctx, p, strlen (p));
2555 pthread_cleanup_pop (1);
2556 return send_error (ctx, rc);
2559 struct xpath_s
2561 xmlXPathContextPtr xp;
2562 xmlXPathObjectPtr result;
2563 xmlBufferPtr buf;
2564 char **req;
2567 static void
2568 xpath_command_cleanup (void *arg)
2570 struct xpath_s *xpath = arg;
2572 if (!xpath)
2573 return;
2575 req_cleanup (xpath->req);
2577 if (xpath->buf)
2578 xmlBufferFree (xpath->buf);
2580 if (xpath->result)
2581 xmlXPathFreeObject (xpath->result);
2583 if (xpath->xp)
2584 xmlXPathFreeContext (xpath->xp);
2587 static gpg_error_t
2588 do_xpath (assuan_context_t ctx, char *line)
2590 gpg_error_t rc;
2591 struct client_s *client = assuan_get_pointer (ctx);
2592 struct xpath_s _x = { 0 };
2593 struct xpath_s *xpath = &_x;
2595 if ((xpath->req = str_split (line, "\t", 2)) == NULL)
2597 if (strv_printf (&xpath->req, "%s", line) == 0)
2598 return GPG_ERR_ENOMEM;
2601 xpath->xp = xmlXPathNewContext (client->doc);
2602 if (!xpath->xp)
2604 rc = GPG_ERR_BAD_DATA;
2605 goto fail;
2608 xpath->result =
2609 xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2610 if (!xpath->result)
2612 rc = GPG_ERR_BAD_DATA;
2613 goto fail;
2616 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2618 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2619 goto fail;
2622 rc = recurse_xpath_nodeset (client->doc, xpath->result->nodesetval,
2623 (xmlChar *) xpath->req[1], &xpath->buf, 0,
2624 NULL);
2625 if (rc)
2626 goto fail;
2627 else if (!xpath->req[1] && !xmlBufferLength (xpath->buf))
2629 rc = GPG_ERR_NO_DATA;
2630 goto fail;
2632 else if (xpath->req[1])
2634 rc = 0;
2635 goto fail;
2638 pthread_cleanup_push (xpath_command_cleanup, &xpath);
2639 rc = xfer_data (ctx, (char *) xmlBufferContent (xpath->buf),
2640 xmlBufferLength (xpath->buf));
2641 pthread_cleanup_pop (0);
2642 fail:
2643 xpath_command_cleanup (xpath);
2644 return rc;
2647 static gpg_error_t
2648 xpath_command (assuan_context_t ctx, char *line)
2650 struct client_s *client = assuan_get_pointer (ctx);
2651 gpg_error_t rc;
2652 struct argv_s *args[] = {
2653 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2654 NULL
2657 if (disable_list_and_dump == 1)
2658 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2660 rc = parse_options (&line, args, client);
2661 if (rc)
2662 return send_error (ctx, rc);
2664 if (client->opts & OPT_INQUIRE)
2666 unsigned char *result;
2667 size_t len;
2669 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2670 if (rc)
2671 return send_error (ctx, rc);
2673 line = (char *) result;
2676 if (!line || !*line)
2677 rc = GPG_ERR_SYNTAX;
2679 if (!rc)
2680 rc = do_xpath (ctx, line);
2682 if (client->opts & OPT_INQUIRE)
2683 xfree (line);
2685 return send_error (ctx, rc);
2688 static gpg_error_t
2689 do_xpathattr (assuan_context_t ctx, char *line)
2691 struct client_s *client = assuan_get_pointer (ctx);
2692 gpg_error_t rc;
2693 char **req = NULL;
2694 int cmd = 0; //SET
2695 struct xpath_s _x = { 0 };
2696 struct xpath_s *xpath = &_x;
2698 if ((req = str_split (line, " ", 3)) == NULL)
2699 return GPG_ERR_ENOMEM;
2701 if (!req[0])
2703 rc = GPG_ERR_SYNTAX;
2704 goto fail;
2707 if (!strcasecmp (req[0], "SET"))
2708 cmd = 0;
2709 else if (!strcasecmp (req[0], "DELETE"))
2710 cmd = 1;
2711 else
2713 rc = GPG_ERR_SYNTAX;
2714 goto fail;
2717 if (!req[1] || !req[2])
2719 rc = GPG_ERR_SYNTAX;
2720 goto fail;
2723 if ((xpath->req = str_split (req[2], "\t", 3)) == NULL)
2725 rc = GPG_ERR_ENOMEM;
2726 goto fail;
2729 if (!xpath->req[0] || (!xpath->req[1] && !cmd) || (xpath->req[1] && cmd))
2731 rc = GPG_ERR_SYNTAX;
2732 goto fail;
2735 xpath->xp = xmlXPathNewContext (client->doc);
2736 if (!xpath->xp)
2738 rc = GPG_ERR_BAD_DATA;
2739 goto fail;
2742 xpath->result = xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2743 if (!xpath->result)
2745 rc = GPG_ERR_BAD_DATA;
2746 goto fail;
2749 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2751 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2752 goto fail;
2755 rc = recurse_xpath_nodeset (client->doc, xpath->result->nodesetval,
2756 (xmlChar *) xpath->req[1], &xpath->buf, cmd,
2757 (xmlChar *) req[1]);
2759 fail:
2760 xpath_command_cleanup (xpath);
2761 strv_free (req);
2762 return rc;
2765 /* XPATHATTR SET|DELETE <name> <expression>[<TAB>[value]] */
2766 static gpg_error_t
2767 xpathattr_command (assuan_context_t ctx, char *line)
2769 struct client_s *client = assuan_get_pointer (ctx);
2770 gpg_error_t rc;
2771 struct argv_s *args[] = {
2772 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2773 NULL
2776 if (disable_list_and_dump == 1)
2777 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2779 rc = parse_options (&line, args, client);
2780 if (rc)
2781 return send_error (ctx, rc);
2783 if (client->opts & OPT_INQUIRE)
2785 unsigned char *result;
2786 size_t len;
2788 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2789 if (rc)
2790 return send_error (ctx, rc);
2792 line = (char *) result;
2795 if (!line || !*line)
2796 rc = GPG_ERR_SYNTAX;
2798 if (!rc)
2799 rc = do_xpathattr (ctx, line);
2801 if (client->opts & OPT_INQUIRE)
2802 xfree (line);
2804 return send_error (ctx, rc);
2807 static gpg_error_t
2808 do_import (struct client_s *client, const char *root_element,
2809 unsigned char *content)
2811 char **dst_path = NULL;
2812 xmlDocPtr doc = NULL;
2813 xmlNodePtr n, root, copy;
2814 gpg_error_t rc;
2816 if (!content || !*content)
2818 xfree (content);
2819 return GPG_ERR_SYNTAX;
2822 if (root_element)
2823 dst_path = str_split (root_element, "\t", 0);
2825 if (dst_path && !valid_element_path (dst_path, 0))
2827 if (dst_path)
2828 strv_free (dst_path);
2830 return GPG_ERR_INV_VALUE;
2833 struct string_s *str = string_new_content ((char *)content);
2834 str = string_prepend (str, "<pwmd>");
2835 str = string_append (str, "</pwmd>");
2836 doc = xmlReadDoc ((xmlChar *) str->str, NULL, "UTF-8", XML_PARSE_NOBLANKS);
2837 string_free (str, 1);
2838 if (!doc)
2840 rc = GPG_ERR_BAD_DATA;
2841 goto fail;
2844 root = xmlDocGetRootElement (doc);
2845 xmlNodePtr root_orig = root->children;
2846 root = root->children;
2847 rc = validate_import (root);
2848 if (rc)
2849 goto fail;
2853 again:
2854 if (dst_path)
2856 char **path = strv_dup (dst_path);
2857 if (!path)
2859 log_write ("%s(%i): %s", __FILE__, __LINE__,
2860 pwmd_strerror (GPG_ERR_ENOMEM));
2861 rc = GPG_ERR_ENOMEM;
2862 goto fail;
2865 xmlChar *a = xmlGetProp (root, (xmlChar *) "_name");
2866 if (!a)
2868 strv_free (path);
2869 rc = GPG_ERR_ENOMEM;
2870 goto fail;
2873 if (strv_printf (&path, "%s", (char *) a) == 0)
2875 xmlFree (a);
2876 rc = GPG_ERR_ENOMEM;
2877 goto fail;
2880 xmlFree (a);
2881 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
2882 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2884 strv_free (path);
2885 goto fail;
2888 if (!rc)
2890 n = find_elements (client->doc, n->children, path + 1, &rc,
2891 NULL, NULL, NULL, 0, 0, NULL, 1);
2892 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2894 strv_free (path);
2895 goto fail;
2897 else if (!rc)
2899 xmlUnlinkNode (n);
2900 xmlFreeNode (n);
2901 strv_free (path);
2902 path = NULL;
2903 goto again;
2907 if (rc == GPG_ERR_ELEMENT_NOT_FOUND)
2909 n = create_element_path (client, &path, &rc, NULL);
2910 if (rc)
2911 goto fail;
2914 if (root->children)
2916 copy = xmlCopyNodeList (root->children);
2917 n = xmlAddChildList (n, copy);
2918 if (!n)
2919 rc = GPG_ERR_ENOMEM;
2922 strv_free (path);
2924 else
2926 char **path = NULL;
2928 /* Check if the content root element can create a DTD root element. */
2929 if (!xmlStrEqual ((xmlChar *) "element", root->name))
2931 rc = GPG_ERR_SYNTAX;
2932 goto fail;
2935 xmlChar *a;
2937 if ((a = xmlGetProp (root, (xmlChar *) "_name")) == NULL)
2939 rc = GPG_ERR_SYNTAX;
2940 goto fail;
2943 char *tmp = str_dup ((char *) a);
2944 xmlFree (a);
2945 int literal = is_literal_element (&tmp);
2947 if (!valid_xml_element ((xmlChar *) tmp) || literal)
2949 xfree (tmp);
2950 rc = GPG_ERR_INV_VALUE;
2951 goto fail;
2954 if (strv_printf (&path, "%s", tmp) == 0)
2956 xfree (tmp);
2957 rc = GPG_ERR_ENOMEM;
2958 goto fail;
2961 xfree (tmp);
2962 n = find_root_element (client->doc, &path, &rc, NULL, 0, 1);
2963 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2965 rc = GPG_ERR_BAD_DATA;
2966 goto fail;
2969 /* Overwriting the existing tree. */
2970 if (!rc)
2972 xmlUnlinkNode (n);
2973 xmlFreeNodeList (n);
2976 rc = 0;
2977 xmlSetProp (root, (xmlChar *) "_name", (xmlChar *) path[0]);
2978 n = xmlCopyNode (root, 1);
2979 n = xmlAddChildList (xmlDocGetRootElement (client->doc), n);
2980 strv_free (path);
2983 if (n && !rc)
2984 rc = update_element_mtime (n->parent);
2986 for (root = root_orig->next; root; root = root->next)
2988 if (root->type == XML_ELEMENT_NODE)
2989 break;
2992 root_orig = root;
2994 while (root);
2996 fail:
2997 if (doc)
2998 xmlFreeDoc (doc);
3000 if (dst_path)
3001 strv_free (dst_path);
3003 return rc;
3006 static gpg_error_t
3007 parse_import_opt_root (void *data, void *value)
3009 struct client_s *client = data;
3011 client->import_root = str_dup (value);
3012 return client->import_root ? 0 : GPG_ERR_ENOMEM;
3015 static gpg_error_t
3016 import_command (assuan_context_t ctx, char *line)
3018 gpg_error_t rc;
3019 struct client_s *client = assuan_get_pointer (ctx);
3020 unsigned char *result;
3021 size_t len;
3022 struct argv_s *args[] = {
3023 &(struct argv_s) {"root", OPTION_TYPE_ARG, parse_import_opt_root},
3024 NULL
3027 xfree (client->import_root);
3028 client->import_root = NULL;
3029 rc = parse_options (&line, args, client);
3030 if (rc)
3031 return send_error (ctx, rc);
3033 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3034 if (rc)
3035 return send_error (ctx, rc);
3037 rc = do_import (client, client->import_root, result);
3038 xfree (client->import_root);
3039 client->import_root = NULL;
3040 return send_error (ctx, rc);
3043 static gpg_error_t
3044 do_lock (struct client_s *client, int add)
3046 gpg_error_t rc = lock_file_mutex (client, add);
3048 if (!rc)
3049 client->flags |= FLAG_LOCK_CMD;
3051 return rc;
3054 static gpg_error_t
3055 lock_command (assuan_context_t ctx, char *line)
3057 struct client_s *client = assuan_get_pointer (ctx);
3058 gpg_error_t rc = do_lock (client, 0);
3060 return send_error (ctx, rc);
3063 static gpg_error_t
3064 unlock_command (assuan_context_t ctx, char *line)
3066 struct client_s *client = assuan_get_pointer (ctx);
3067 gpg_error_t rc;
3069 rc = unlock_file_mutex (client, 0);
3070 return send_error (ctx, rc);
3073 static gpg_error_t
3074 option_command (assuan_context_t ctx, char *line)
3076 struct client_s *client = assuan_get_pointer (ctx);
3077 gpg_error_t rc = 0;
3078 struct pinentry_option_s *pin_opts = &client->pinentry_opts;
3079 #ifdef WITH_AGENT
3080 struct agent_s *agent = client->crypto->agent;
3081 #endif
3082 char namebuf[255] = { 0 };
3083 char *name = namebuf;
3084 char *value = NULL, *p;
3086 p = strchr (line, '=');
3087 if (!p)
3088 strncpy (namebuf, line, sizeof(namebuf));
3089 else
3091 strncpy (namebuf, line, strlen (line)-strlen (p));
3092 value = p+1;
3095 log_write1 ("OPTION name='%s' value='%s'", name, value);
3097 if (strcasecmp (name, (char *) "log_level") == 0)
3099 long l = 0;
3101 if (value)
3103 l = strtol (value, NULL, 10);
3105 if (l < 0 || l > 2)
3106 return send_error (ctx, GPG_ERR_INV_VALUE);
3109 MUTEX_LOCK (&rcfile_mutex);
3110 config_set_int_param (&global_config, "global", "log_level", value);
3111 MUTEX_UNLOCK (&rcfile_mutex);
3112 goto done;
3114 else if (strcasecmp (name, (char *) "lock-timeout") == 0)
3116 long n = 0;
3117 char *p = NULL;
3119 if (value)
3121 n = strtol (value, &p, 10);
3122 if (p && *p)
3123 return send_error (ctx, GPG_ERR_INV_VALUE);
3126 client->lock_timeout = n;
3127 goto done;
3129 else if (strcasecmp (name, (char *) "NAME") == 0)
3131 char *tmp = pthread_getspecific (thread_name_key);
3133 if (tmp)
3134 xfree (tmp);
3136 if (!value || !*value)
3138 pthread_setspecific (thread_name_key, str_dup (""));
3139 goto done;
3142 pthread_setspecific (thread_name_key, str_dup (value));
3143 goto done;
3145 else if (strcasecmp (name, (char *) "lc-messages") == 0)
3147 xfree (pin_opts->lc_messages);
3148 pin_opts->lc_messages = NULL;
3149 if (value && *value)
3150 pin_opts->lc_messages = str_dup (value);
3151 #ifdef WITH_AGENT
3152 if (use_agent)
3153 rc = set_agent_option (client->crypto->agent, "lc-messages", value);
3154 #endif
3156 else if (strcasecmp (name, (char *) "lc-ctype") == 0)
3158 xfree (pin_opts->lc_ctype);
3159 pin_opts->lc_ctype = NULL;
3160 if (value && *value)
3161 pin_opts->lc_ctype = str_dup (value);
3162 #ifdef WITH_AGENT
3163 if (use_agent)
3164 rc = set_agent_option (client->crypto->agent, "lc-ctype", value);
3165 #endif
3167 else if (strcasecmp (name, (char *) "ttyname") == 0)
3169 xfree (pin_opts->ttyname);
3170 pin_opts->ttyname = NULL;
3171 if (value && *value)
3172 pin_opts->ttyname = str_dup (value);
3173 #ifdef WITH_AGENT
3174 if (use_agent)
3175 rc = set_agent_option (client->crypto->agent, "ttyname", value);
3176 #endif
3178 else if (strcasecmp (name, (char *) "ttytype") == 0)
3180 xfree (pin_opts->ttytype);
3181 pin_opts->ttytype = NULL;
3182 if (value && *value)
3183 pin_opts->ttytype = str_dup (value);
3184 #ifdef WITH_AGENT
3185 if (use_agent)
3186 rc = set_agent_option (client->crypto->agent, "ttytype", value);
3187 #endif
3189 else if (strcasecmp (name, (char *) "display") == 0)
3191 xfree (pin_opts->display);
3192 pin_opts->display = NULL;
3193 if (value && *value)
3194 pin_opts->display = str_dup (value);
3195 #ifdef WITH_AGENT
3196 if (use_agent)
3197 rc = set_agent_option (client->crypto->agent, "display", value);
3198 #endif
3200 else if (strcasecmp (name, (char *) "pinentry-desc") == 0)
3202 xfree (pin_opts->desc);
3203 pin_opts->desc = NULL;
3204 if (value && *value)
3205 pin_opts->desc = str_dup (value);
3207 else if (strcasecmp (name, (char *) "pinentry-title") == 0)
3209 xfree (pin_opts->title);
3210 pin_opts->title = NULL;
3211 if (value && *value)
3212 pin_opts->title = str_dup (value);
3214 else if (strcasecmp (name, (char *) "pinentry-prompt") == 0)
3216 xfree (pin_opts->prompt);
3217 pin_opts->prompt = NULL;
3218 if (value && *value)
3219 pin_opts->prompt = str_dup (value);
3222 else if (strcasecmp (name, "pinentry-timeout") == 0)
3224 char *p = NULL;
3225 int n;
3227 if (!value)
3228 goto done;
3230 n = (int) strtol (value, &p, 10);
3232 if (*p || n < 0)
3233 return send_error (ctx, GPG_ERR_INV_VALUE);
3235 pin_opts->timeout = n;
3236 MUTEX_LOCK (&rcfile_mutex);
3237 config_set_int_param (&global_config,
3238 client->filename ? client->filename : "global",
3239 "pinentry_timeout", value);
3240 MUTEX_UNLOCK (&rcfile_mutex);
3241 goto done;
3243 else if (strcasecmp (name, "disable-pinentry") == 0)
3245 char *p = NULL;
3246 int n = 1;
3248 if (value && *value)
3250 n = (int) strtol (value, &p, 10);
3251 if (*p || n < 0 || n > 1)
3252 return send_error (ctx, GPG_ERR_INV_VALUE);
3255 if (n)
3256 client->flags |= FLAG_NO_PINENTRY;
3257 else
3258 client->flags &= ~FLAG_NO_PINENTRY;
3260 #ifdef WITH_AGENT
3261 if (use_agent)
3263 if (client->flags & FLAG_NO_PINENTRY)
3264 rc = set_agent_option (client->crypto->agent, "pinentry-mode",
3265 "loopback");
3266 else
3267 rc = set_agent_option (client->crypto->agent, "pinentry-mode",
3268 "ask");
3270 if (rc)
3271 return send_error (ctx, rc);
3273 #endif
3275 else
3276 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
3278 done:
3279 #ifdef WITH_AGENT
3280 if (!rc && use_agent && agent)
3282 rc = pinentry_merge_options (&client->crypto->agent->pinentry_opts,
3283 pin_opts);
3285 #endif
3287 return send_error (ctx, rc);
3290 static gpg_error_t
3291 do_rename (assuan_context_t ctx, char *line)
3293 struct client_s *client = assuan_get_pointer (ctx);
3294 gpg_error_t rc;
3295 char **req, **src, *dst;
3296 xmlNodePtr n, ndst;
3298 req = str_split (line, " ", 0);
3300 if (!req || !req[0] || !req[1])
3302 strv_free (req);
3303 return GPG_ERR_SYNTAX;
3306 dst = req[1];
3307 is_literal_element (&dst);
3309 if (!valid_xml_element ((xmlChar *) dst))
3311 strv_free (req);
3312 return GPG_ERR_INV_VALUE;
3315 if (strchr (req[0], '\t'))
3316 src = str_split (req[0], "\t", 0);
3317 else
3318 src = str_split (req[0], " ", 0);
3320 if (!src || !*src)
3322 rc = GPG_ERR_SYNTAX;
3323 goto fail;
3326 n = find_root_element (client->doc, &src, &rc, NULL, 0, 0);
3327 if (src[1] && n)
3328 n = find_elements (client->doc, n->children, src + 1, &rc, NULL, NULL,
3329 NULL, 0, 0, NULL, 0);
3331 if (!n)
3332 goto fail;
3334 xmlChar *a = xmlGetProp (n, (xmlChar *) "_name");
3335 if (!a)
3337 rc = GPG_ERR_ENOMEM;
3338 goto fail;
3341 /* To prevent unwanted effects:
3343 * <root name="a"><b/></root>
3345 * RENAME a<TAB>b b
3347 if (xmlStrEqual (a, (xmlChar *) dst))
3349 xmlFree (a);
3350 rc = GPG_ERR_AMBIGUOUS_NAME;
3351 goto fail;
3354 xmlFree (a);
3355 char **tmp = NULL;
3356 if (src[1])
3358 char **p;
3360 for (p = src; *p; p++)
3362 if (!*(p + 1))
3363 break;
3364 strv_printf (&tmp, "%s", *p);
3368 strv_printf (&tmp, "!%s", dst);
3369 ndst = find_root_element (client->doc, &tmp, &rc, NULL, 0, 0);
3370 if (!ndst && rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3372 strv_free (tmp);
3373 goto fail;
3376 if (tmp[1] && ndst)
3377 ndst = find_elements (client->doc, ndst->children, tmp + 1, &rc, NULL,
3378 NULL, NULL, 0, 0, NULL, 0);
3380 strv_free (tmp);
3381 if (!ndst && rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3382 goto fail;
3384 rc = 0;
3386 /* Target may exist:
3388 * <root name="a"/>
3389 * <root name="b" target="a"/>
3391 * RENAME b a
3393 * Would need to do:
3394 * RENAME !b a
3396 if (ndst == n)
3398 rc = GPG_ERR_AMBIGUOUS_NAME;
3399 goto fail;
3402 if (ndst)
3404 unlink_node (ndst);
3405 xmlFreeNodeList (ndst);
3408 rc = add_attribute (n, "_name", dst);
3410 fail:
3411 strv_free (req);
3412 strv_free (src);
3413 return rc;
3416 static gpg_error_t
3417 rename_command (assuan_context_t ctx, char *line)
3419 struct client_s *client = assuan_get_pointer (ctx);
3420 gpg_error_t rc;
3421 struct argv_s *args[] = {
3422 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3423 NULL
3426 rc = parse_options (&line, args, client);
3427 if (rc)
3428 return send_error (ctx, rc);
3430 if (client->opts & OPT_INQUIRE)
3432 unsigned char *result;
3433 size_t len;
3435 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3436 if (rc)
3437 return send_error (ctx, rc);
3439 line = (char *) result;
3442 rc = do_rename (ctx, line);
3444 if (client->opts & OPT_INQUIRE)
3445 xfree (line);
3447 return send_error (ctx, rc);
3450 static gpg_error_t
3451 do_copy (assuan_context_t ctx, char *line)
3453 struct client_s *client = assuan_get_pointer (ctx);
3454 gpg_error_t rc;
3455 char **req, **src = NULL, **dst = NULL;
3456 xmlNodePtr nsrc, ndst, new = NULL;
3458 req = str_split (line, " ", 0);
3459 if (!req || !req[0] || !req[1])
3461 strv_free (req);
3462 return GPG_ERR_SYNTAX;
3465 if (strchr (req[0], '\t'))
3466 src = str_split (req[0], "\t", 0);
3467 else
3468 src = str_split (req[0], " ", 0);
3470 if (!src || !*src)
3472 rc = GPG_ERR_SYNTAX;
3473 goto fail;
3476 if (strchr (req[1], '\t'))
3477 dst = str_split (req[1], "\t", 0);
3478 else
3479 dst = str_split (req[1], " ", 0);
3481 if (!dst || !*dst)
3483 rc = GPG_ERR_SYNTAX;
3484 goto fail;
3487 if (!valid_element_path (dst, 0))
3489 rc = GPG_ERR_INV_VALUE;
3490 goto fail;
3493 nsrc = find_root_element (client->doc, &src, &rc, NULL, 0, 0);
3494 if (nsrc && src[1])
3495 nsrc = find_elements (client->doc, nsrc->children, src + 1, &rc, NULL,
3496 NULL, NULL, 0, 0, NULL, 0);
3498 if (!nsrc)
3499 goto fail;
3501 new = xmlCopyNodeList (nsrc);
3502 if (!new)
3504 rc = GPG_ERR_ENOMEM;
3505 goto fail;
3508 int create = 0;
3509 ndst = find_root_element (client->doc, &dst, &rc, NULL, 0, 0);
3510 if (ndst && dst[1])
3512 if (ndst->children)
3513 ndst = find_elements (client->doc, ndst->children, dst + 1, &rc, NULL,
3514 NULL, create_target_elements_cb, 0, 0, NULL, 0);
3515 else
3516 create = 1;
3518 else
3519 create = 1;
3521 if (!ndst && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3522 goto fail;
3523 else if (!ndst || create)
3525 ndst = create_element_path (client, &dst, &rc, NULL);
3526 if (!ndst)
3527 goto fail;
3530 /* Merge any attributes from the src node to the initial dst node. */
3531 for (xmlAttrPtr attr = new->properties; attr; attr = attr->next)
3533 if (xmlStrEqual (attr->name, (xmlChar *) "_name"))
3534 continue;
3536 xmlAttrPtr a = xmlHasProp (ndst, attr->name);
3537 if (a)
3538 xmlRemoveProp (a);
3540 xmlChar *tmp = xmlNodeGetContent (attr->children);
3541 xmlNewProp (ndst, attr->name, tmp);
3542 xmlFree (tmp);
3543 rc = add_attribute (ndst, NULL, NULL);
3546 xmlNodePtr n = ndst->children;
3547 xmlUnlinkNode (n);
3548 xmlFreeNodeList (n);
3549 ndst->children = NULL;
3551 if (new->children)
3553 n = xmlCopyNodeList (new->children);
3554 if (!n)
3556 rc = GPG_ERR_ENOMEM;
3557 goto fail;
3560 n = xmlAddChildList (ndst, n);
3561 if (!n)
3563 rc = GPG_ERR_ENOMEM;
3564 goto fail;
3567 rc = update_element_mtime (xmlDocGetRootElement (client->doc) ==
3568 ndst->parent ? ndst : ndst->parent);
3571 fail:
3572 if (new)
3574 xmlUnlinkNode (new);
3575 xmlFreeNodeList (new);
3578 if (req)
3579 strv_free (req);
3581 if (src)
3582 strv_free (src);
3584 if (dst)
3585 strv_free (dst);
3587 return rc;
3590 static gpg_error_t
3591 copy_command (assuan_context_t ctx, char *line)
3593 struct client_s *client = assuan_get_pointer (ctx);
3594 gpg_error_t rc;
3595 struct argv_s *args[] = {
3596 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3597 NULL
3600 rc = parse_options (&line, args, client);
3601 if (rc)
3602 return send_error (ctx, rc);
3604 if (client->opts & OPT_INQUIRE)
3606 unsigned char *result;
3607 size_t len;
3609 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3610 if (rc)
3611 return send_error (ctx, rc);
3613 line = (char *) result;
3616 rc = do_copy (ctx, line);
3618 if (client->opts & OPT_INQUIRE)
3619 xfree (line);
3621 return send_error (ctx, rc);
3624 static gpg_error_t
3625 do_move (assuan_context_t ctx, char *line)
3627 struct client_s *client = assuan_get_pointer (ctx);
3628 gpg_error_t rc;
3629 char **req, **src = NULL, **dst = NULL;
3630 xmlNodePtr nsrc, ndst = NULL;
3632 req = str_split (line, " ", 0);
3634 if (!req || !req[0] || !req[1])
3636 strv_free (req);
3637 return GPG_ERR_SYNTAX;
3640 if (strchr (req[0], '\t'))
3641 src = str_split (req[0], "\t", 0);
3642 else
3643 src = str_split (req[0], " ", 0);
3645 if (!src || !*src)
3647 rc = GPG_ERR_SYNTAX;
3648 goto fail;
3651 if (strchr (req[1], '\t'))
3652 dst = str_split (req[1], "\t", 0);
3653 else
3654 dst = str_split (req[1], " ", 0);
3656 nsrc = find_root_element (client->doc, &src, &rc, NULL, 0, 0);
3657 if (nsrc && src[1])
3658 nsrc = find_elements (client->doc, nsrc->children, src + 1, &rc, NULL,
3659 NULL, NULL, 0, 0, NULL, 0);
3661 if (!nsrc)
3662 goto fail;
3664 if (dst)
3666 if (!valid_element_path (dst, 0))
3668 rc = GPG_ERR_INV_VALUE;
3669 goto fail;
3672 ndst = find_root_element (client->doc, &dst, &rc, NULL, 0, 0);
3673 if (ndst && dst[1])
3674 ndst = find_elements (client->doc, ndst->children, dst + 1, &rc, NULL,
3675 NULL, NULL, 0, 0, NULL, 0);
3677 else
3678 ndst = xmlDocGetRootElement (client->doc);
3680 for (xmlNodePtr n = ndst; n; n = n->parent)
3682 if (n == nsrc)
3684 rc = GPG_ERR_CONFLICT;
3685 goto fail;
3689 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3690 goto fail;
3692 rc = 0;
3694 if (ndst)
3696 xmlChar *a = node_has_attribute (nsrc, (xmlChar *) "_name");
3697 xmlNodePtr dup = find_element (ndst->children, (char *) a, NULL);
3699 xmlFree (a);
3700 if (dup)
3702 if (dup == nsrc)
3703 goto fail;
3705 if (ndst == xmlDocGetRootElement (client->doc))
3707 xmlNodePtr n = nsrc;
3708 int match = 0;
3710 while (n->parent && n->parent != ndst)
3711 n = n->parent;
3713 xmlChar *a = node_has_attribute (n, (xmlChar *) "_name");
3714 xmlChar *b = node_has_attribute (nsrc, (xmlChar *) "_name");
3716 if (xmlStrEqual (a, b))
3718 match = 1;
3719 xmlUnlinkNode (nsrc);
3720 xmlUnlinkNode (n);
3721 xmlFreeNodeList (n);
3724 xmlFree (a);
3725 xmlFree (b);
3727 if (!match)
3729 xmlUnlinkNode (dup);
3730 xmlFreeNodeList (dup);
3733 else
3734 xmlUnlinkNode (dup);
3738 if (!ndst && dst)
3740 xmlChar *name = node_has_attribute (nsrc, (xmlChar *) "_name");
3742 if (nsrc->parent == xmlDocGetRootElement (client->doc)
3743 && !strcmp ((char *) name, *dst))
3745 xmlFree (name);
3746 rc = GPG_ERR_CONFLICT;
3747 goto fail;
3750 xmlFree (name);
3751 ndst = create_element_path (client, &dst, &rc, nsrc);
3754 if (!ndst)
3755 goto fail;
3757 update_element_mtime (nsrc->parent);
3758 xmlUnlinkNode (nsrc);
3759 ndst = xmlAddChildList (ndst, nsrc);
3761 if (!ndst)
3762 rc = GPG_ERR_ENOMEM;
3763 else
3764 update_element_mtime (ndst->parent);
3766 fail:
3767 if (req)
3768 strv_free (req);
3770 if (src)
3771 strv_free (src);
3773 if (dst)
3774 strv_free (dst);
3776 return rc;
3779 static gpg_error_t
3780 move_command (assuan_context_t ctx, char *line)
3782 struct client_s *client = assuan_get_pointer (ctx);
3783 gpg_error_t rc;
3784 struct argv_s *args[] = {
3785 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3786 NULL
3789 rc = parse_options (&line, args, client);
3790 if (rc)
3791 return send_error (ctx, rc);
3793 if (client->opts & OPT_INQUIRE)
3795 unsigned char *result;
3796 size_t len;
3798 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3799 if (rc)
3800 return send_error (ctx, rc);
3802 line = (char *) result;
3805 rc = do_move (ctx, line);
3807 if (client->opts & OPT_INQUIRE)
3808 xfree (line);
3810 return send_error (ctx, rc);
3813 static gpg_error_t
3814 ls_command (assuan_context_t ctx, char *line)
3816 gpg_error_t rc;
3817 char *tmp = str_asprintf ("%s/data", homedir);
3818 char *dir = expand_homedir (tmp);
3819 DIR *d = opendir (dir);
3821 rc = gpg_error_from_errno (errno);
3822 xfree (tmp);
3824 if (!d)
3826 xfree (dir);
3827 return send_error (ctx, rc);
3830 size_t len =
3831 offsetof (struct dirent, d_name) +pathconf (dir, _PC_NAME_MAX) + 1;
3832 struct dirent *p = xmalloc (len), *cur = NULL;
3833 char *list = NULL;
3835 xfree (dir);
3836 rc = 0;
3838 while (!readdir_r (d, p, &cur) && cur)
3840 if (cur->d_name[0] == '.' && cur->d_name[1] == '\0')
3841 continue;
3842 else if (cur->d_name[0] == '.' && cur->d_name[1] == '.'
3843 && cur->d_name[2] == '\0')
3844 continue;
3846 tmp = str_asprintf ("%s%s\n", list ? list : "", cur->d_name);
3848 if (!tmp)
3850 if (list)
3851 xfree (list);
3853 rc = GPG_ERR_ENOMEM;
3854 break;
3857 xfree (list);
3858 list = tmp;
3861 closedir (d);
3862 xfree (p);
3864 if (rc)
3865 return send_error (ctx, rc);
3867 if (!list)
3868 return send_error (ctx, GPG_ERR_NO_DATA);
3870 list[strlen (list) - 1] = 0;
3871 rc = xfer_data (ctx, list, strlen (list));
3872 xfree (list);
3873 return send_error (ctx, rc);
3876 static gpg_error_t
3877 bye_notify (assuan_context_t ctx, char *line)
3879 struct client_s *cl = assuan_get_pointer (ctx);
3881 #ifdef WITH_GNUTLS
3882 if (cl->thd->remote)
3884 int rc;
3888 struct timeval tv = { 0, 50000 };
3890 rc = gnutls_bye (cl->thd->tls->ses, GNUTLS_SHUT_RDWR);
3891 if (rc == GNUTLS_E_AGAIN)
3892 select (0, NULL, NULL, NULL, &tv);
3894 while (rc == GNUTLS_E_AGAIN);
3896 #endif
3898 /* This will let assuan_process_next() return. */
3899 fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK);
3900 cl->last_rc = 0; // BYE command result
3901 return 0;
3904 static gpg_error_t
3905 reset_notify (assuan_context_t ctx, char *line)
3907 struct client_s *client = assuan_get_pointer (ctx);
3909 if (client)
3910 cleanup_client (client);
3912 return 0;
3916 * This is called before every Assuan command.
3918 static gpg_error_t
3919 command_startup (assuan_context_t ctx, const char *name)
3921 struct client_s *client = assuan_get_pointer (ctx);
3922 gpg_error_t rc;
3923 struct command_table_s *cmd = NULL;
3925 log_write1 ("command='%s'", name);
3926 client->last_rc = client->opts = 0;
3928 for (int i = 0; command_table[i]; i++)
3930 if (!strcasecmp (name, command_table[i]->name))
3932 if (command_table[i]->ignore_startup)
3933 return 0;
3934 cmd = command_table[i];
3935 break;
3939 client->last_rc = rc = gpg_error (file_modified (client, cmd));
3940 return rc;
3944 * This is called after every Assuan command.
3946 static void
3947 command_finalize (assuan_context_t ctx, gpg_error_t rc)
3949 struct client_s *client = assuan_get_pointer (ctx);
3951 if (!(client->flags & FLAG_LOCK_CMD))
3952 unlock_file_mutex (client, 0);
3954 log_write1 (_("command completed: rc=%u"), client->last_rc);
3955 client->last_rc = gpg_error (GPG_ERR_UNKNOWN_COMMAND);
3956 #ifdef WITH_GNUTLS
3957 client->thd->buffer_timeout = client->thd->last_buffer_size = 0;
3958 #endif
3961 static gpg_error_t
3962 help_command (assuan_context_t ctx, char *line)
3964 gpg_error_t rc;
3965 int i;
3967 if (!line || !*line)
3969 char *tmp;
3970 char *help = str_dup (_("Usage: HELP [<COMMAND>]\n"
3971 "For commands that take an element path as an argument, each element is "
3972 "separated with an ASCII @key{TAB} character (ASCII 0x09)."
3973 "\n" "COMMANDS:"));
3975 for (i = 0; command_table[i]; i++)
3977 if (!command_table[i]->help)
3978 continue;
3980 tmp = str_asprintf ("%s %s", help, command_table[i]->name);
3981 xfree (help);
3982 help = tmp;
3985 tmp = strip_texi_and_wrap (help);
3986 xfree (help);
3987 rc = xfer_data (ctx, tmp, strlen (tmp));
3988 xfree (tmp);
3989 return send_error (ctx, rc);
3992 for (i = 0; command_table[i]; i++)
3994 if (!strcasecmp (line, command_table[i]->name))
3996 char *help, *tmp;
3998 if (!command_table[i]->help)
3999 break;
4001 help = strip_texi_and_wrap (command_table[i]->help);
4002 tmp = str_asprintf (_("Usage: %s"), help);
4003 xfree (help);
4004 rc = xfer_data (ctx, tmp, strlen (tmp));
4005 xfree (tmp);
4006 return send_error (ctx, rc);
4010 return send_error (ctx, GPG_ERR_INV_NAME);
4013 static void
4014 new_command (const char *name, int ignore, int unlock,
4015 gpg_error_t (*handler) (assuan_context_t, char *),
4016 const char *help)
4018 int i = 0;
4020 if (command_table)
4021 for (i = 0; command_table[i]; i++);
4023 command_table =
4024 xrealloc (command_table, (i + 2) * sizeof (struct command_table_s *));
4025 command_table[i] = xcalloc (1, sizeof (struct command_table_s));
4026 command_table[i]->name = name;
4027 command_table[i]->handler = handler;
4028 command_table[i]->ignore_startup = ignore;
4029 command_table[i]->unlock = unlock;
4030 command_table[i++]->help = help;
4031 command_table[i] = NULL;
4034 void
4035 deinit_commands ()
4037 int i;
4039 for (i = 0; command_table[i]; i++)
4040 xfree (command_table[i]);
4042 xfree (command_table);
4045 static int
4046 sort_commands (const void *arg1, const void *arg2)
4048 struct command_table_s *const *a = arg1;
4049 struct command_table_s *const *b = arg2;
4051 if (!*a || !*b)
4052 return 0;
4053 else if (*a && !*b)
4054 return 1;
4055 else if (!*a && *b)
4056 return -1;
4058 return strcmp ((*a)->name, (*b)->name);
4061 static gpg_error_t
4062 passwd_command (assuan_context_t ctx, char *line)
4064 struct client_s *client = assuan_get_pointer (ctx);
4065 gpg_error_t rc;
4066 struct argv_s *args[] = {
4067 &(struct argv_s) {"reset", OPTION_TYPE_NOARG, parse_opt_reset},
4068 &(struct argv_s) {"s2k-count", OPTION_TYPE_ARG, parse_opt_s2k_count},
4069 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG, parse_opt_no_passphrase},
4070 NULL
4073 if (client->flags & FLAG_NEW)
4074 return send_error (ctx, GPG_ERR_INV_STATE);
4076 client->crypto->save.s2k_count =
4077 config_get_ulong (client->filename, "s2k_count");
4078 rc = parse_options (&line, args, client);
4079 if (rc)
4080 return send_error (ctx, rc);
4082 if (!rc && client->opts & OPT_RESET)
4084 rc = cache_clear (client->md5file);
4085 if (!rc)
4086 send_status_all (STATUS_CACHE, NULL);
4089 if (!rc)
4091 if (!IS_PKI (client->crypto))
4093 struct crypto_s *crypto;
4095 xfree (client->crypto->filename);
4096 client->crypto->filename = str_dup (client->filename);
4097 rc = change_passwd (ctx, client->filename,
4098 client->flags & FLAG_NO_PINENTRY, &crypto,
4099 (client->opts & OPT_NO_PASSPHRASE));
4100 if (!rc)
4102 cleanup_crypto (&client->crypto);
4103 client->crypto = crypto;
4104 update_checksum (client);
4105 cleanup_crypto_stage1 (client->crypto);
4108 #ifdef WITH_AGENT
4109 else
4111 if (client->crypto->save.s2k_count)
4112 rc = send_to_agent (client->crypto->agent, NULL, NULL,
4113 "OPTION s2k-count=%lu",
4114 client->crypto->save.s2k_count);
4116 if (!rc)
4117 rc = agent_passwd (client->crypto);
4119 #endif
4122 return send_error (ctx, rc);
4125 static gpg_error_t
4126 parse_keygrip_opt_sign (void *data, void *value)
4128 struct client_s *client = data;
4130 (void) value;
4131 client->opts |= OPT_SIGN;
4132 return 0;
4135 static gpg_error_t
4136 keygrip_command (assuan_context_t ctx, char *line)
4138 struct client_s *client = assuan_get_pointer (ctx);
4139 gpg_error_t rc;
4140 struct crypto_s *crypto = NULL;
4141 struct argv_s *args[] = {
4142 &(struct argv_s) {"sign", OPTION_TYPE_NOARG, parse_keygrip_opt_sign},
4143 NULL
4146 if (!line || !*line)
4147 return send_error (ctx, GPG_ERR_SYNTAX);
4149 rc = parse_options (&line, args, client);
4150 if (rc)
4151 return send_error (ctx, rc);
4153 if (!valid_filename (line))
4154 return send_error (ctx, GPG_ERR_INV_VALUE);
4156 rc = init_client_crypto (&crypto);
4157 if (rc)
4158 return send_error (ctx, rc);
4160 rc = read_data_file (line, crypto);
4161 if (!rc)
4163 char *hexgrip = NULL;
4165 if (!IS_PKI (crypto))
4167 cleanup_crypto (&crypto);
4168 return send_error (ctx, GPG_ERR_NOT_SUPPORTED);
4171 if (client->opts & OPT_SIGN)
4173 if (valid_keygrip (crypto->sign_grip, sizeof (crypto->sign_grip)))
4174 hexgrip = bin2hex (crypto->sign_grip, sizeof (crypto->sign_grip));
4177 if (!hexgrip)
4178 hexgrip = bin2hex (crypto->grip, sizeof (crypto->grip));
4180 if (!hexgrip)
4181 rc = GPG_ERR_ENOMEM;
4182 else
4183 rc = xfer_data (ctx, hexgrip, strlen (hexgrip));
4185 xfree (hexgrip);
4188 UPDATE_AGENT_CTX (client, crypto);
4189 cleanup_crypto (&crypto);
4190 return send_error (ctx, rc);
4193 static gpg_error_t
4194 parse_opt_data (void *data, void *value)
4196 struct client_s *client = data;
4198 (void) value;
4199 client->opts |= OPT_DATA;
4200 return 0;
4203 static gpg_error_t
4204 getinfo_command (assuan_context_t ctx, char *line)
4206 struct client_s *client = assuan_get_pointer (ctx);
4207 gpg_error_t rc;
4208 char buf[ASSUAN_LINELENGTH];
4209 struct argv_s *args[] = {
4210 &(struct argv_s) {"data", OPTION_TYPE_NOARG, parse_opt_data},
4211 NULL
4214 rc = parse_options (&line, args, client);
4215 if (rc)
4216 return send_error (ctx, rc);
4218 if (!strcasecmp (line, "clients"))
4220 if (client->opts & OPT_DATA)
4222 MUTEX_LOCK (&cn_mutex);
4223 snprintf (buf, sizeof (buf), "%i", slist_length (cn_thread_list));
4224 MUTEX_UNLOCK (&cn_mutex);
4225 rc = xfer_data (ctx, buf, strlen (buf));
4227 else
4228 rc = send_status (ctx, STATUS_CLIENTS, NULL);
4230 else if (!strcasecmp (line, "cache"))
4232 if (client->opts & OPT_DATA)
4234 snprintf (buf, sizeof (buf), "%u", cache_file_count ());
4235 rc = xfer_data (ctx, buf, strlen (buf));
4237 else
4238 rc = send_status (ctx, STATUS_CACHE, NULL);
4240 else if (!strcasecmp (line, "pid"))
4242 char buf[32];
4243 pid_t pid = getpid ();
4245 snprintf (buf, sizeof (buf), "%i", pid);
4246 rc = xfer_data (ctx, buf, strlen (buf));
4248 else if (!strcasecmp (line, "version"))
4250 char *buf = str_asprintf ("0x%06x %s%s", VERSION_HEX,
4251 #ifdef WITH_LIBACL
4252 "ACL "
4253 #endif
4254 #ifdef WITH_GNUTLS
4255 "GNUTLS "
4256 #endif
4257 #ifdef WITH_QUALITY
4258 "QUALITY "
4259 #endif
4260 "", use_agent ? "AGENT" : "");
4261 rc = xfer_data (ctx, buf, strlen (buf));
4262 xfree (buf);
4264 else if (!strcasecmp (line, "last_error"))
4266 if (client->last_error)
4267 rc = xfer_data (ctx, client->last_error, strlen (client->last_error));
4268 else
4269 rc = GPG_ERR_NO_DATA;
4271 else
4272 rc = gpg_error (GPG_ERR_SYNTAX);
4274 return send_error (ctx, rc);
4277 #ifdef WITH_AGENT
4278 static gpg_error_t
4279 send_data_cb (void *user, const void *buf, size_t len)
4281 assuan_context_t ctx = user;
4283 return assuan_send_data (ctx, buf, len);
4286 static gpg_error_t
4287 send_status_cb (void *user, const char *line)
4289 assuan_context_t ctx = user;
4290 char keyword[200], *k;
4291 const char *p;
4293 for (p = line, k = keyword; *p; p++)
4295 if (isspace (*p))
4296 break;
4298 *k++ = *p;
4301 *k = 0;
4302 if (*p == '#')
4303 p++;
4305 while (isspace (*p))
4306 p++;
4308 return assuan_write_status (ctx, keyword, *p ? p : NULL);
4310 #endif
4312 static gpg_error_t
4313 agent_command (assuan_context_t ctx, char *line)
4315 gpg_error_t rc = 0;
4317 if (!use_agent)
4318 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
4320 #ifdef WITH_AGENT
4321 struct client_s *client = assuan_get_pointer (ctx);
4323 if (!line || !*line)
4324 return send_error (ctx, GPG_ERR_SYNTAX);
4326 assuan_set_flag (client->crypto->agent->ctx, ASSUAN_CONVEY_COMMENTS, 1);
4327 rc = assuan_transact (client->crypto->agent->ctx, line, send_data_cb,
4328 client->ctx, agent_loopback_cb, client->crypto,
4329 send_status_cb, client->ctx);
4330 if (gpg_err_code (rc) == GPG_ERR_ASS_CANCELED)
4332 char *line;
4333 size_t len;
4335 rc = assuan_write_line (client->crypto->agent->ctx, "CAN");
4336 if (!rc)
4338 rc = assuan_read_line (client->crypto->agent->ctx, &line, &len);
4339 if (!rc)
4340 rc = gpg_error (GPG_ERR_ASS_CANCELED);
4344 assuan_set_flag (client->crypto->agent->ctx, ASSUAN_CONVEY_COMMENTS, 0);
4345 #endif
4346 return send_error (ctx, rc);
4349 void
4350 init_commands ()
4352 /* !BEGIN-HELP-TEXT!
4354 * This comment is used as a marker to generate the offline documentation
4355 * found in doc/pwmd.info. The indentation needs to be kept for the awk
4356 * script to determine where commands begin and end.
4358 new_command("HELP", 1, 1, help_command, _(
4359 "HELP [<COMMAND>]\n"
4360 "Show available commands or command specific help text."
4363 new_command("AGENT", 1, 1, agent_command, _(
4364 "AGENT <command>\n"
4365 "Send a @command{gpg-agent} protocol @var{command} directly to the "
4366 "@command{gpg-agent}."
4369 new_command("GETINFO", 1, 1, getinfo_command, _(
4370 "GETINFO [--data] CACHE | CLIENTS | PID | LAST_ERROR | VERSION\n"
4371 "Get server and other information: @var{cache} returns the number of cached "
4372 "documents via a status message. @var{clients} returns the number of "
4373 "connected clients via a status message. @var{pid} returns the process ID "
4374 "number of the server via a data response. @var{VERSION} returns the server "
4375 "version number and compile-time features with a data response with each "
4376 "being space delimited. @var{LAST_ERROR} returns a detailed description of "
4377 "the last failed command when available. @xref{Status Messages}. "
4378 "\n"
4379 "When the @option{--data} option is specified then the result will be sent "
4380 "via a data response rather than a status message."
4383 new_command("PASSWD", 0, 0, passwd_command, _(
4384 "PASSWD [--reset] [--s2k-count=N] [--no-passphrase]\n"
4385 "Changes the passphrase of the secret key required to open the current "
4386 "file or the passphrase of a symmetrically encrypted data file. When the "
4387 "@option{--reset} option is passed then the cache entry for the current "
4388 "file will be reset and the passphrase, if any, will be required during the "
4389 "next @code{OPEN}. @xref{OPEN}."
4390 "\n"
4391 "The @option{--s2k-count} option sets number of hash iterations for a "
4392 "passphrase and must be either @code{0} to use the calibrated count of the "
4393 "machine (the default), or a value greater than or equal to @code{65536}. "
4394 "@xref{SAVE}. This option has no effect for symmetrically encrypted data "
4395 "files."
4396 "\n"
4397 "The @option{--no-passphrase} option will prevent requiring a passphrase for "
4398 "the data file, although a passphrase may be required when changing it."
4401 new_command("KEYGRIP", 1, 1, keygrip_command, _(
4402 "KEYGRIP [--sign] <filename>\n"
4403 "Returns the hex encoded keygrip of the specified @var{filename} with a "
4404 "data response."
4405 "\n"
4406 "When the @option{--sign} option is specified then the key used for signing "
4407 "of the specified @var{filename} will be returned."
4408 "\n"
4409 "For symmetrically encrypted data files this command returns the error "
4410 "GPG_ERR_NOT_SUPPORTED."
4413 new_command("OPEN", 1, 1, open_command, _(
4414 "OPEN [--lock] <filename> [<passphrase>]\n"
4415 "Opens @var{filename} using @var{passphrase}. When the filename is not "
4416 "found on the file-system then a new document will be created. If the file "
4417 "is found, it is looked for in the file cache. If cached and no "
4418 "@var{passphrase} was specified then the cached document is opened. When not "
4419 "cached, @cite{pinentry(1)} will be used to retrieve the passphrase to use "
4420 "for decryption unless @option{disable-pinentry} (@pxref{OPTION}) was "
4421 "specified."
4422 "\n"
4423 "When the @option{--lock} option is passed then the file mutex will be "
4424 "locked as if the @code{LOCK} command (@pxref{LOCK}) had been sent after the "
4425 "file has been opened."
4428 new_command("SAVE", 0, 0, save_command, _(
4429 "SAVE [--no-passphrase] [--reset] [--no-agent] [--s2k-count=N] [--cipher=<algo>] [--cipher-iterations=N] [--inquire-keyparam] [--keygrip=hexstring] [--sign-keygrip=hexstring]\n"
4430 "Writes the @abbr{XML} document to disk. The file written to is the file that "
4431 "was opened using the @code{OPEN} command (@pxref{OPEN}). If the file is a "
4432 "new one or the option @option{--inquire-keyparam} was passed, then a new "
4433 "keypair will be generated and a pinentry will be used to prompt for the "
4434 "passphrase to encrypt with unless the @option{--no-passphrase} option was "
4435 "passed in which case the data file will not be passphrase protected. "
4436 "\n"
4437 "The @option{--no-agent} option disables use of @command{gpg-agent} for "
4438 "passphrase retrieval and caching of new files when @command{gpg-agent} "
4439 "use is enabled. The datafile will be symmetrically encrypted and will not "
4440 "use or generate any keypair."
4441 "\n"
4442 "The @option{--reset} option will clear the cache entry for the current file "
4443 "and require a passphrase, if needed, before saving."
4444 "\n"
4445 "The @option{--cipher} option can be used to encrypt the @abbr{XML} data to "
4446 "an alternate cipher. The default is @code{aes256}. See the Configuration "
4447 "(@pxref{Configuration}) for available ciphers."
4448 "\n"
4449 "The @option{--cipher-iterations} option specifies the number of times to "
4450 "encrypt the XML data. The default is 0 although 1 iteration is still done."
4451 "\n"
4452 "The @option{--inquire-keyparam} option will send a server @emph{INQUIRE} to "
4453 "the client to obtain the key paramaters to use when generating a new "
4454 "keypair. The inquired data is expected to be an S-expression. If not "
4455 "specified then an @samp{RSA} key of @samp{2048} bits will be generated "
4456 "unless otherwise set in the configuration file (@pxref{Configuration}). Note "
4457 "that when this option is specified a new keypair will be generated "
4458 "reguardless if the file is a new one and that if the data file is protected "
4459 "the passphrase to open it will be required before generating the new keypair."
4460 "\n"
4461 "You can encrypt the data file to a public key other than the one that it "
4462 "was originally encrypted with by passing the @option{--keygrip} option with "
4463 "the hex encoded keygrip of the public key as its argument. The keygrip may "
4464 "be of any key that @command{gpg-agent} knows about. The "
4465 "@option{--sign-keygrip} option may also be used to sign with an alternate "
4466 "secret key. This option may be needed when using a smartcard. This option "
4467 "has no effect with symmetrically encrypted data files."
4468 "\n"
4469 "The @option{--s2k-count} option sets number of hash iterations for a "
4470 "passphrase. A value less-than @code{65536} will use the machine calibrated "
4471 "value and is the default. This setting only affects new files. To change "
4472 "the setting use the @code{PASSWD} command (@pxref{PASSWD}). This option "
4473 "has no effect with symmetrically encrypted data files."
4476 new_command("ISCACHED", 1, 0, iscached_command, _(
4477 "ISCACHED [--lock] <filename>\n"
4478 "An @emph{OK} response is returned if the specified @var{filename} is found "
4479 "in the file cache. If not found in the cache but exists on the filesystem "
4480 "then @var{GPG_ERR_NO_DATA} is returned. Otherwise a filesystem error is "
4481 "returned."
4482 "\n"
4483 "The @option{lock} option will lock the file mutex of @var{filename} when the "
4484 "file exists; it does not need to be opened nor cached."
4487 new_command("CLEARCACHE", 1, 1, clearcache_command, _(
4488 "CLEARCACHE [<filename>]\n"
4489 "Clears a file cache entry for all or the specified @var{filename}."
4492 new_command("CACHETIMEOUT", 1, 1, cachetimeout_command, _(
4493 "CACHETIMEOUT <filename> <seconds>\n"
4494 "The time in @var{seconds} until @var{filename} will be removed from the "
4495 "cache. @code{-1} will keep the cache entry forever, @code{0} will require "
4496 "the passphrase for each @code{OPEN} or @code{SAVE} command (@pxref{OPEN}, "
4497 "@pxref{SAVE}). @xref{Configuration}, and the @code{cache_timeout} "
4498 "parameter."
4501 new_command("LIST", 0, 1, list_command, _(
4502 "LIST [--inquire] [--no-recurse] [--verbose] [--with-target] [--all] [[!]element[<TAB>[!]child[..]]]\n"
4503 "If no element path is given then a newline separated list of root elements "
4504 "is returned with a data response. If given, then all reachable elements "
4505 "of the specified element path are returned unless the @option{--no-recurse} "
4506 "option is specified. If specified, only the child elements of the element "
4507 "path are returned without recursing into grandchildren. Each resulting "
4508 "element is prefixed with the literal @code{!} character when the element "
4509 "contains no @code{target} attribute. @xref{Target Attribute}, for details."
4510 "\n"
4511 "When the @option{--verbose} option is passed then each element path "
4512 "returned will have zero or more flags appened to it. These flags are "
4513 "delimited from the element path by a single space character. A flag itself "
4514 "is a single character. Flag @code{+} indicates that there are child nodes of "
4515 "the current element path. Flag @code{E} indicates that an element of an "
4516 "element path contained in a @var{target} attribute could not be found. Flag "
4517 "@code{O} indicates that a @var{target} attribute recursion limit was reached "
4518 "(@pxref{Configuration}). Flag @code{T} will append the resolved element path "
4519 "of the @var{target} attribute contained in the current element (see below)."
4520 "\n"
4521 "The @option{--with-target} option implies @option{--verbose} and will append "
4522 "an additional flag @code{T} followed by a single space then an element path. "
4523 "The appended element path is the resolved path (@pxref{REALPATH}) of the "
4524 "current element when it contains a @var{target} attribute. When no "
4525 "@var{target} attribute is found then no flag will be appended."
4526 "\n"
4527 "The @option{--no-recurse} option limits the amount of data returned to only "
4528 "the listing of children of the specified element path and not any "
4529 "grandchildren."
4530 "\n"
4531 "The @option{--all} option lists the entire element tree for each root "
4532 "element. This option also implies option @option{--verbose}."
4533 "\n"
4534 "When the @option{--inquire} option is passed then all remaining non-option "
4535 "arguments are retrieved via a server @emph{INQUIRE}."
4538 new_command("REALPATH", 0, 1, realpath_command, _(
4539 "REALPATH [--inquire] [!]element[<TAB>[!]child[..]]\n"
4540 "Resolves all @code{target} attributes of the specified element path and "
4541 "returns the result with a data response. @xref{Target Attribute}, for details."
4542 "\n"
4543 "When the @option{--inquire} option is passed then all remaining non-option "
4544 "arguments are retrieved via a server @emph{INQUIRE}."
4547 new_command("STORE", 0, 1, store_command, _(
4548 "STORE [!]element[<TAB>[!]child[..]]<TAB>[content]\n"
4549 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
4550 "\n"
4551 "Creates a new element path or modifies the @var{content} of an existing "
4552 "element. If only a single element is specified then a new root element is "
4553 "created. Otherwise, elements are @key{TAB} delimited and the content will be "
4554 "set to the final @key{TAB} delimited element. If no @var{content} is "
4555 "specified after the final @key{TAB}, then the content of the element will "
4556 "be removed, or empty when creating a new element."
4557 "\n"
4558 "The only restriction of an element name is that it not contain whitespace "
4559 "or begin with the literal element character @code{!} unless specifying a "
4560 "literal element (@pxref{Target Attribute}). There is no whitespace between "
4561 "the @key{TAB} delimited elements. It is recommended that the content of an "
4562 "element be base64 encoded when it contains control or @key{TAB} characters "
4563 "to prevent @abbr{XML} parsing and @command{pwmd} syntax errors."
4566 new_command("RENAME", 0, 1, rename_command, _(
4567 "RENAME [--inquire] [!]element[<TAB>[!]child[..]] <value>\n"
4568 "Renames the specified @var{element} to the new @var{value}. If an element of "
4569 "the same name as the @var{value} already exists it will be overwritten."
4570 "\n"
4571 "When the @option{--inquire} option is passed then all remaining non-option "
4572 "arguments are retrieved via a server @emph{INQUIRE}."
4575 new_command("COPY", 0, 1, copy_command, _(
4576 "COPY [--inquire] [!]source[<TAB>[!]child[..]] [!]dest[<TAB>[!]child[..]]\n"
4577 "Copies the entire element tree starting from the child node of the source "
4578 "element, to the destination element path. If the destination element path "
4579 "does not exist then it will be created; otherwise it is overwritten."
4580 "\n"
4581 "Note that attributes from the source element are merged into the "
4582 "destination element when the destination element path exists. When an "
4583 "attribute of the same name exists in both the source and destination "
4584 "elements then the destination attribute will be updated to the source "
4585 "attribute value."
4586 "\n"
4587 "When the @option{--inquire} option is passed then all remaining non-option "
4588 "arguments are retrieved via a server @emph{INQUIRE}."
4591 new_command("MOVE", 0, 1, move_command, _(
4592 "MOVE [--inquire] [!]source[<TAB>[!]child[..]] [[!]dest[<TAB>[!]child[..]]]\n"
4593 "Moves the source element path to the destination element path. If the "
4594 "destination is not specified then it will be moved to the root node of the "
4595 "document. If the destination is specified and exists then it will be "
4596 "overwritten; otherwise non-existing elements of the destination element "
4597 "path will be created."
4598 "\n"
4599 "When the @option{--inquire} option is passed then all remaining non-option "
4600 "arguments are retrieved via a server @emph{INQUIRE}."
4603 new_command("DELETE", 0, 1, delete_command, _(
4604 "DELETE [--inquire] [!]element[<TAB>[!]child[..]]\n"
4605 "Removes the specified element path and all of its children. This may break "
4606 "an element with a @code{target} attribute (@pxref{Target Attribute}) that "
4607 "refers to this element or any of its children."
4608 "\n"
4609 "When the @option{--inquire} option is passed then all remaining non-option "
4610 "arguments are retrieved via a server @emph{INQUIRE}."
4613 new_command("GET", 0, 1, get_command, _(
4614 "GET [--inquire] [!]element[<TAB>[!]child[..]]\n"
4615 "Retrieves the content of the specified element. The content is returned "
4616 "with a data response."
4617 "\n"
4618 "When the @option{--inquire} option is passed then all remaining non-option "
4619 "arguments are retrieved via a server @emph{INQUIRE}."
4622 new_command("ATTR", 0, 1, attr_command, _(
4623 "ATTR [--inquire] SET|GET|DELETE|LIST [<attribute>] [!]element[<TAB>[!]child[..]] ..\n"
4624 "@table @asis\n"
4625 "@item ATTR SET attribute [!]element[<TAB>[!]child[..]] [value]\n"
4626 "\n"
4627 " Stores or updates an @var{attribute} name and optional @var{value} of an "
4628 "element. When no @var{value} is specified any existing value will be removed."
4629 "\n"
4630 "@item ATTR DELETE attribute [!]element[<TAB>[!]child[..]]\n"
4631 "\n"
4632 " Removes an @var{attribute} from an element."
4633 "\n"
4634 "@item ATTR LIST [!]element[<TAB>[!]child[..]]\n"
4635 "\n"
4636 " Retrieves a newline separated list of attributes names and values "
4637 "from the specified element. Each attribute name and value is space delimited."
4638 "\n"
4639 "@item ATTR GET attribute [!]element[<TAB>[!]child[..]]\n"
4640 "\n"
4641 " Retrieves the value of an @var{attribute} from an element."
4642 "@end table\n"
4643 "\n"
4644 "The @code{_name} attribute (case sensitive) cannot be removed nor modified. "
4645 "Use the @code{DELETE} (@pxref{DELETE}) or @code{RENAME} (@pxref{RENAME}) "
4646 "commands instead."
4647 "\n"
4648 "The @code{_mtime} attribute is updated each time an element is modified by "
4649 "either storing content, editing attributes or by deleting a child element. "
4650 "The @code{_ctime} attribute is created for each new element in an element "
4651 "path."
4652 "\n"
4653 "When the @option{--inquire} option is passed then all remaining non-option "
4654 "arguments are retrieved via a server @emph{INQUIRE}."
4655 "\n"
4656 "@xref{Target Attribute}, for details about this special attribute."
4659 new_command("XPATH", 0, 1, xpath_command, _(
4660 "XPATH [--inquire] <expression>[<TAB>[value]]\n"
4661 "Evaluates an XPath @var{expression}. If no @var{value} argument is "
4662 "specified it is assumed the expression is a request to return a result. "
4663 "Otherwise, the result is set to the @var{value} argument and the document is "
4664 "updated. If there is no @var{value} after the @key{TAB} character, the value "
4665 "is assumed to be empty and the document is updated. For example:"
4666 "@sp 1\n"
4667 "@example\n"
4668 "XPATH //element[@@_name='password']@key{TAB}\n"
4669 "@end example\n"
4670 "@sp 1"
4671 "would clear the content of all @code{password} elements in the data file "
4672 "while leaving off the trailing @key{TAB} would return all @code{password} "
4673 "elements in @abbr{XML} format."
4674 "\n"
4675 "When the @option{--inquire} option is passed then all remaining non-option "
4676 "arguments are retrieved via a server @emph{INQUIRE}."
4677 "\n"
4678 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
4679 "expression syntax."
4682 new_command("XPATHATTR", 0, 1, xpathattr_command, _(
4683 "XPATHATTR [--inquire] SET|DELETE <name> <expression>[<TAB>[<value>]]\n"
4684 "Like the @code{XPATH} command (@pxref{XPATH}) but operates on element "
4685 "attributes and does not return a result. For the @var{SET} operation the "
4686 "@var{value} is optional but the field is required. If not specified then "
4687 "the attribute value will be empty. For example:"
4688 "@sp 1"
4689 "@example\n"
4690 "XPATHATTR SET password //element[@@_name='password']@key{TAB}\n"
4691 "@end example\n"
4692 "@sp 1"
4693 "would create an @code{password} attribute for each @code{password} element "
4694 "found in the document. The attribute value will be empty but still exist."
4695 "\n"
4696 "When the @option{--inquire} option is passed then all remaining non-option "
4697 "arguments are retrieved via a server @emph{INQUIRE}."
4698 "\n"
4699 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
4700 "expression syntax."
4703 new_command("IMPORT", 0, 1, import_command, _(
4704 "IMPORT [--root [!]element[<TAB>[!]child[..]]] <content>\n"
4705 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
4706 "\n"
4707 "Like the @code{STORE} command (@pxref{STORE}), but the @var{content} "
4708 "argument is raw @abbr{XML} data. The content is created as a child of "
4709 "the element path specified with the @option{--root} option or at the "
4710 "document root when not specified. Existing elements of the same name will "
4711 "be overwritten."
4712 "\n"
4713 "The content must begin with an @abbr{XML} element node. @xref{Introduction}, "
4714 "for details."
4717 new_command("DUMP", 0, 1, dump_command, _(
4718 "DUMP\n"
4719 "Shows the in memory @abbr{XML} document with indenting. @xref{XPATH}, for "
4720 "dumping a specific node."
4723 new_command("LOCK", 0, 0, lock_command, _(
4724 "LOCK\n"
4725 "Locks the mutex associated with the opened file. This prevents other clients "
4726 "from sending commands to the same opened file until the client "
4727 "that sent this command either disconnects or sends the @code{UNLOCK} "
4728 "command. @xref{UNLOCK}."
4731 new_command("UNLOCK", 1, 0, unlock_command, _(
4732 "UNLOCK\n"
4733 "Unlocks the file mutex which was locked with the @code{LOCK} command or "
4734 "a commands' @option{--lock} option (@pxref{LOCK}, @pxref{OPEN}, "
4735 "@pxref{ISCACHED})."
4738 new_command("GETCONFIG", 1, 1, getconfig_command, _(
4739 "GETCONFIG [filename] <parameter>\n"
4740 "Returns the value of a @command{pwmd} configuration @var{parameter} with a "
4741 "data response. If no file has been opened then the value for @var{filename} "
4742 "or the default from the @samp{global} section will be returned. If a file "
4743 "has been opened and no @var{filename} is specified, a value previously "
4744 "set with the @code{OPTION} command (@pxref{OPTION}) will be returned."
4747 new_command("OPTION", 1, 1, option_command, _(
4748 "OPTION <NAME>=<VALUE>\n"
4749 "Sets a client option @var{name} to @var{value}. The value for an option is "
4750 "kept for the duration of the connection."
4751 "\n"
4752 "@table @asis\n"
4753 "@item DISABLE-PINENTRY\n"
4754 "Disable use of @command{pinentry} for passphrase retrieval. When set, a "
4755 "server inquire is sent to the client to obtain the passphrase. This option "
4756 "may be set as needed before the @pxref{OPEN}, @pxref{PASSWD}, and "
4757 "@pxref{SAVE} commands."
4758 "\n"
4759 "@item PINENTRY-TIMEOUT\n"
4760 "Sets the number of seconds before a pinentry prompt will return an error "
4761 "while waiting for user input."
4762 "\n"
4763 "@item TTYNAME\n"
4764 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4765 "\n"
4766 "@item TTYTYPE\n"
4767 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4768 "\n"
4769 "@item DISPLAY\n"
4770 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4771 "\n"
4772 "@item PINENTRY-DESC\n"
4773 "Sets the description string of the @command{gpg-agent} and @command{pinentry} dialog."
4774 "\n"
4775 "@item PINENTRY-TITLE\n"
4776 "Sets the title string of the @command{gpg-agent} and @command{pinentry} dialog."
4777 "\n"
4778 "@item PINENTRY-PROMPT\n"
4779 "Sets the prompt string of the @command{gpg-agent} and @command{pinentry} dialog."
4780 "\n"
4781 "@item LC-CTYPE\n"
4782 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4783 "\n"
4784 "@item LC-MESSAGES\n"
4785 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4786 "\n"
4787 "@item NAME\n"
4788 "Associates the thread ID of the connection with the specified textual "
4789 "representation. Useful for debugging log messages."
4790 "\n"
4791 "@item LOCK-TIMEOUT\n"
4792 "When not @code{0}, the duration in tenths of a second to wait for the file "
4793 "mutex which has been locked by another thread to be released before returning "
4794 "an error. When @code{-1}, then an error will be returned immediately."
4795 "\n"
4796 "@item LOG-LEVEL\n"
4797 "An integer specifiying the logging level."
4798 "@end table\n"
4801 new_command("LS", 1, 1, ls_command, _(
4802 "LS\n"
4803 "Lists the available data files stored in the data directory "
4804 "(@file{~/.pwmd/data}). The result is a newline separated list of filenames."
4807 new_command("RESET", 1, 1, NULL, _(
4808 "RESET\n"
4809 "Closes the currently opened file but keeps any previously set client options."
4812 new_command("NOP", 1, 1, NULL, _(
4813 "NOP\n"
4814 "Does nothing. Always returns successfully."
4817 /* !END-HELP-TEXT! */
4818 new_command ("CANCEL", 1, 1, NULL, NULL);
4819 new_command ("END", 1, 1, NULL, NULL);
4820 new_command ("BYE", 1, 1, NULL, NULL);
4822 int i;
4823 for (i = 0; command_table[i]; i++);
4824 qsort (command_table, i - 1, sizeof (struct command_table_s *),
4825 sort_commands);
4828 gpg_error_t
4829 register_commands (assuan_context_t ctx)
4831 int i = 0, rc;
4833 for (; command_table[i]; i++)
4835 if (!command_table[i]->handler)
4836 continue;
4838 rc = assuan_register_command (ctx, command_table[i]->name,
4839 command_table[i]->handler,
4840 command_table[i]->help);
4841 if (rc)
4842 return rc;
4845 rc = assuan_register_bye_notify (ctx, bye_notify);
4846 if (rc)
4847 return rc;
4849 rc = assuan_register_reset_notify (ctx, reset_notify);
4850 if (rc)
4851 return rc;
4853 rc = assuan_register_pre_cmd_notify (ctx, command_startup);
4854 if (rc)
4855 return rc;
4857 return assuan_register_post_cmd_notify (ctx, command_finalize);