Let the CLEARCACHE and CACHETIMEOUT commands work with remote connections.
[pwmd.git] / src / commands.c
blob15c1a79bc8e5990d84a5662a13969e9c082b3cf6
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);
2093 if ((path = str_split (req[1], "\t", 0)) == NULL)
2096 * The first argument may be only a root element.
2098 if ((path = str_split (req[1], " ", 0)) == NULL)
2099 return GPG_ERR_SYNTAX;
2102 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
2104 if (!n)
2105 goto fail;
2107 if (path[1])
2109 n = find_elements (client->doc, n->children, path + 1, &rc,
2110 NULL, NULL, NULL, 0, 0, NULL, 0);
2112 if (!n)
2113 goto fail;
2116 rc = add_attribute (n, req[0], req[2]);
2118 fail:
2119 strv_free (path);
2120 return rc;
2124 * req[0] - command
2125 * req[1] - attribute name or element path if command is LIST
2126 * req[2] - element path
2127 * req[2] - element path or value
2130 static gpg_error_t
2131 do_attr (assuan_context_t ctx, char *line)
2133 struct client_s *client = assuan_get_pointer (ctx);
2134 gpg_error_t rc = 0;
2135 char **req;
2137 req = str_split (line, " ", 4);
2138 if (!req || !req[0] || !req[1])
2140 strv_free (req);
2141 return GPG_ERR_SYNTAX;
2144 pthread_cleanup_push (req_cleanup, req);
2146 if (strcasecmp (req[0], "SET") == 0)
2147 rc = attribute_set (client, req + 1);
2148 else if (strcasecmp (req[0], "GET") == 0)
2149 rc = attribute_get (ctx, req + 1);
2150 else if (strcasecmp (req[0], "DELETE") == 0)
2151 rc = attribute_delete (client, req + 1);
2152 else if (strcasecmp (req[0], "LIST") == 0)
2153 rc = attribute_list (ctx, req + 1);
2154 else
2155 rc = GPG_ERR_SYNTAX;
2157 pthread_cleanup_pop (1);
2158 return rc;
2161 static gpg_error_t
2162 attr_command (assuan_context_t ctx, char *line)
2164 struct client_s *client = assuan_get_pointer (ctx);
2165 gpg_error_t rc;
2166 struct argv_s *args[] = {
2167 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2168 NULL
2171 rc = parse_options (&line, args, client);
2172 if (rc)
2173 return send_error (ctx, rc);
2175 if (client->opts & OPT_INQUIRE)
2177 unsigned char *result;
2178 size_t len;
2180 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2181 if (rc)
2182 return send_error (ctx, rc);
2184 line = (char *) result;
2187 rc = do_attr (ctx, line);
2189 if (client->opts & OPT_INQUIRE)
2190 xfree (line);
2192 return send_error (ctx, rc);
2195 static gpg_error_t
2196 parse_iscached_opt_lock (void *data, void *value)
2198 struct client_s *client = data;
2200 (void) value;
2201 client->opts |= OPT_LOCK;
2202 return 0;
2205 static gpg_error_t
2206 iscached_command (assuan_context_t ctx, char *line)
2208 struct client_s *client = assuan_get_pointer (ctx);
2209 gpg_error_t rc;
2210 unsigned char md5file[16];
2211 struct argv_s *args[] = {
2212 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_iscached_opt_lock},
2213 NULL
2216 if (!line || !*line)
2217 return send_error (ctx, GPG_ERR_SYNTAX);
2219 rc = parse_options (&line, args, client);
2220 if (rc)
2221 return send_error (ctx, rc);
2222 else if (!valid_filename (line))
2223 return send_error (ctx, GPG_ERR_INV_VALUE);
2225 rc = cache_iscached (line, NULL);
2226 if (client->opts & OPT_LOCK
2227 && (!rc || gpg_err_code (rc) == GPG_ERR_NO_DATA))
2229 gpg_error_t trc = rc;
2230 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2231 if (memcmp (md5file, client->md5file, 16))
2232 cleanup_client (client);
2234 memcpy (client->md5file, md5file, 16);
2235 rc = do_lock (client, 1);
2236 if (!rc)
2237 rc = trc;
2240 return send_error (ctx, rc);
2243 static gpg_error_t
2244 clearcache_command (assuan_context_t ctx, char *line)
2246 gpg_error_t rc = 0, all_rc = 0;
2247 unsigned char md5file[16];
2248 int i;
2249 int t;
2250 int all = 0;
2251 struct client_thread_s *once = NULL;
2253 cache_lock ();
2254 MUTEX_LOCK (&cn_mutex);
2255 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
2257 if (!line || !*line)
2258 all = 1;
2260 t = slist_length (cn_thread_list);
2262 for (i = 0; i < t; i++)
2264 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2265 assuan_peercred_t peer;
2267 if (!thd->cl)
2268 continue;
2270 /* Lock each connected clients' file mutex to prevent any other client
2271 * from accessing the cache entry (the file mutex is locked upon
2272 * command startup). The cache for the entry is not cleared if the
2273 * file mutex is locked by another client to prevent this function
2274 * from blocking.
2276 if (all)
2278 if (thd->cl->filename)
2280 rc = do_validate_peer (ctx, thd->cl->filename, &peer);
2281 all_rc = !all_rc ? rc : all_rc;
2282 if (rc)
2284 rc = 0;
2285 continue;
2289 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0, -1);
2290 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2292 if (pthread_equal (pthread_self (), thd->tid))
2293 rc = 0;
2294 else
2296 if (!thd->cl->filename ||
2297 cache_iscached (thd->cl->filename,
2298 NULL) == GPG_ERR_NO_DATA)
2300 rc = 0;
2301 continue;
2304 cache_defer_clear (thd->cl->md5file);
2307 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
2309 rc = 0;
2310 continue;
2313 if (!rc)
2315 rc = cache_clear (thd->cl->md5file);
2316 cache_unlock_mutex (thd->cl->md5file, 0);
2319 if (rc)
2320 all_rc = rc;
2322 rc = 0;
2324 /* A single data filename was specified. Lock only this data file
2325 * mutex and free the cache entry. */
2326 else
2328 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2329 rc = do_validate_peer (ctx, line, &peer);
2331 if (!rc && !memcmp (thd->cl->md5file, md5file, sizeof (md5file)))
2333 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0,
2334 -1);
2335 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2337 if (pthread_equal (pthread_self (), thd->tid))
2338 rc = 0;
2341 if (!rc)
2343 once = thd;
2344 rc = cache_clear (thd->cl->md5file);
2345 cache_unlock_mutex (thd->cl->md5file, 0);
2347 else
2349 cache_defer_clear (thd->cl->md5file);
2352 break;
2357 /* Only connected clients' cache entries have been cleared. Now clear any
2358 * remaining cache entries without clients but only if there wasn't an
2359 * error from above since this would defeat the locking check of the
2360 * remaining entries. */
2361 if (!all_rc && all)
2363 cache_clear (NULL);
2366 /* No clients are using the specified file. */
2367 else if (!all_rc && !rc && !once)
2369 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2370 rc = cache_clear (md5file);
2373 /* Release the connection mutex. */
2374 pthread_cleanup_pop (1);
2375 cache_unlock ();
2377 if (!rc)
2378 send_status_all (STATUS_CACHE, NULL);
2380 /* One or more files were locked while clearing all cache entries. */
2381 if (all_rc)
2382 rc = all_rc;
2384 return send_error (ctx, rc);
2387 static gpg_error_t
2388 cachetimeout_command (assuan_context_t ctx, char *line)
2390 unsigned char md5file[16];
2391 int timeout;
2392 char **req = str_split (line, " ", 0);
2393 char *p;
2394 gpg_error_t rc = 0;
2395 assuan_peercred_t peer;
2397 if (!req || !*req || !req[1])
2399 strv_free (req);
2400 return send_error (ctx, GPG_ERR_SYNTAX);
2403 errno = 0;
2404 timeout = (int) strtol (req[1], &p, 10);
2405 if (errno != 0 || *p || timeout < -1)
2407 strv_free (req);
2408 return send_error (ctx, GPG_ERR_SYNTAX);
2411 rc = do_validate_peer (ctx, req[0], &peer);
2412 if (!rc)
2414 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, req[0], strlen (req[0]));
2415 rc = cache_set_timeout (md5file, timeout);
2416 if (!rc || gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
2418 rc = 0;
2419 MUTEX_LOCK (&rcfile_mutex);
2420 config_set_int_param (&global_config, req[0], "cache_timeout",
2421 req[1]);
2422 MUTEX_UNLOCK (&rcfile_mutex);
2426 strv_free (req);
2427 return send_error (ctx, rc);
2430 static gpg_error_t
2431 dump_command (assuan_context_t ctx, char *line)
2433 xmlChar *xml;
2434 int len;
2435 struct client_s *client = assuan_get_pointer (ctx);
2436 gpg_error_t rc;
2438 if (disable_list_and_dump == 1)
2439 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2441 xmlDocDumpFormatMemory (client->doc, &xml, &len, 1);
2443 if (!xml)
2445 log_write ("%s(%i): %s", __FILE__, __LINE__,
2446 pwmd_strerror (GPG_ERR_ENOMEM));
2447 return send_error (ctx, GPG_ERR_ENOMEM);
2450 pthread_cleanup_push (xmlFree, xml);
2451 rc = xfer_data (ctx, (char *) xml, len);
2452 pthread_cleanup_pop (1);
2453 return send_error (ctx, rc);
2456 static gpg_error_t
2457 getconfig_command (assuan_context_t ctx, char *line)
2459 struct client_s *client = assuan_get_pointer (ctx);
2460 gpg_error_t rc = 0;
2461 char filename[255] = { 0 }, param[747] = { 0 };
2462 char *p, *tmp = NULL, *fp = client->filename, *paramp = line;
2464 if (!line || !*line)
2465 return send_error (ctx, GPG_ERR_SYNTAX);
2467 if (strchr (line, ' '))
2469 sscanf (line, " %254[^ ] %746c", filename, param);
2470 paramp = param;
2471 fp = filename;
2474 if (fp && !valid_filename (fp))
2475 return send_error (ctx, GPG_ERR_INV_VALUE);
2477 paramp = str_down (paramp);
2478 if (!strcmp (paramp, "cipher") && fp)
2480 struct crypto_s *crypto = NULL;
2482 rc = init_client_crypto (&crypto);
2483 if (!rc)
2485 rc = read_data_header (fp, &crypto->hdr, NULL, NULL);
2486 if (!rc)
2488 const char *t =
2489 gcry_cipher_algo_name (cipher_to_gcrypt (crypto->hdr.flags));
2490 if (t)
2492 tmp = str_dup (t);
2493 if (tmp)
2494 str_down (tmp);
2499 UPDATE_AGENT_CTX (client, crypto);
2500 cleanup_crypto (&crypto);
2501 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
2502 return send_error (ctx, rc);
2504 if (!rc && tmp)
2505 goto done;
2507 else if (!strcmp (paramp, "cipher_iterations") && fp)
2509 struct crypto_s *crypto = NULL;
2511 rc = init_client_crypto (&crypto);
2512 if (!rc)
2514 rc = read_data_header (fp, &crypto->hdr, NULL, NULL);
2515 if (!rc)
2517 tmp = str_asprintf ("%llu",
2518 (unsigned long long) crypto->hdr.
2519 iterations);
2520 if (!tmp)
2521 rc = GPG_ERR_ENOMEM;
2525 UPDATE_AGENT_CTX (client, crypto);
2526 cleanup_crypto (&crypto);
2527 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
2528 return send_error (ctx, rc);
2530 if (!rc && tmp)
2531 goto done;
2533 else if (!strcmp (paramp, "passphrase"))
2534 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2536 p = config_get_value (fp ? fp : "global", paramp);
2537 if (!p)
2538 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2540 tmp = expand_homedir (p);
2541 xfree (p);
2542 if (!tmp)
2544 log_write ("%s(%i): %s", __FILE__, __LINE__,
2545 pwmd_strerror (GPG_ERR_ENOMEM));
2546 return send_error (ctx, GPG_ERR_ENOMEM);
2549 done:
2550 p = tmp;
2551 pthread_cleanup_push (xfree, p);
2552 rc = xfer_data (ctx, p, strlen (p));
2553 pthread_cleanup_pop (1);
2554 return send_error (ctx, rc);
2557 struct xpath_s
2559 xmlXPathContextPtr xp;
2560 xmlXPathObjectPtr result;
2561 xmlBufferPtr buf;
2562 char **req;
2565 static void
2566 xpath_command_cleanup (void *arg)
2568 struct xpath_s *xpath = arg;
2570 if (!xpath)
2571 return;
2573 req_cleanup (xpath->req);
2575 if (xpath->buf)
2576 xmlBufferFree (xpath->buf);
2578 if (xpath->result)
2579 xmlXPathFreeObject (xpath->result);
2581 if (xpath->xp)
2582 xmlXPathFreeContext (xpath->xp);
2585 static gpg_error_t
2586 do_xpath (assuan_context_t ctx, char *line)
2588 gpg_error_t rc;
2589 struct client_s *client = assuan_get_pointer (ctx);
2590 struct xpath_s _x = { 0 };
2591 struct xpath_s *xpath = &_x;
2593 if ((xpath->req = str_split (line, "\t", 2)) == NULL)
2595 if (strv_printf (&xpath->req, "%s", line) == 0)
2596 return GPG_ERR_ENOMEM;
2599 xpath->xp = xmlXPathNewContext (client->doc);
2600 if (!xpath->xp)
2602 rc = GPG_ERR_BAD_DATA;
2603 goto fail;
2606 xpath->result =
2607 xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2608 if (!xpath->result)
2610 rc = GPG_ERR_BAD_DATA;
2611 goto fail;
2614 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2616 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2617 goto fail;
2620 rc = recurse_xpath_nodeset (client->doc, xpath->result->nodesetval,
2621 (xmlChar *) xpath->req[1], &xpath->buf, 0,
2622 NULL);
2623 if (rc)
2624 goto fail;
2625 else if (!xpath->req[1] && !xmlBufferLength (xpath->buf))
2627 rc = GPG_ERR_NO_DATA;
2628 goto fail;
2630 else if (xpath->req[1])
2632 rc = 0;
2633 goto fail;
2636 pthread_cleanup_push (xpath_command_cleanup, &xpath);
2637 rc = xfer_data (ctx, (char *) xmlBufferContent (xpath->buf),
2638 xmlBufferLength (xpath->buf));
2639 pthread_cleanup_pop (0);
2640 fail:
2641 xpath_command_cleanup (xpath);
2642 return rc;
2645 static gpg_error_t
2646 xpath_command (assuan_context_t ctx, char *line)
2648 struct client_s *client = assuan_get_pointer (ctx);
2649 gpg_error_t rc;
2650 struct argv_s *args[] = {
2651 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2652 NULL
2655 if (disable_list_and_dump == 1)
2656 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2658 rc = parse_options (&line, args, client);
2659 if (rc)
2660 return send_error (ctx, rc);
2662 if (client->opts & OPT_INQUIRE)
2664 unsigned char *result;
2665 size_t len;
2667 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2668 if (rc)
2669 return send_error (ctx, rc);
2671 line = (char *) result;
2674 if (!line || !*line)
2675 rc = GPG_ERR_SYNTAX;
2677 if (!rc)
2678 rc = do_xpath (ctx, line);
2680 if (client->opts & OPT_INQUIRE)
2681 xfree (line);
2683 return send_error (ctx, rc);
2686 static gpg_error_t
2687 do_xpathattr (assuan_context_t ctx, char *line)
2689 struct client_s *client = assuan_get_pointer (ctx);
2690 gpg_error_t rc;
2691 char **req = NULL;
2692 int cmd = 0; //SET
2693 struct xpath_s _x = { 0 };
2694 struct xpath_s *xpath = &_x;
2696 if ((req = str_split (line, " ", 3)) == NULL)
2697 return GPG_ERR_ENOMEM;
2699 if (!req[0])
2701 rc = GPG_ERR_SYNTAX;
2702 goto fail;
2705 if (!strcasecmp (req[0], "SET"))
2706 cmd = 0;
2707 else if (!strcasecmp (req[0], "DELETE"))
2708 cmd = 1;
2709 else
2711 rc = GPG_ERR_SYNTAX;
2712 goto fail;
2715 if (!req[1] || !req[2])
2717 rc = GPG_ERR_SYNTAX;
2718 goto fail;
2721 if ((xpath->req = str_split (req[2], "\t", 3)) == NULL)
2723 rc = GPG_ERR_ENOMEM;
2724 goto fail;
2727 if (!xpath->req[0] || (!xpath->req[1] && !cmd) || (xpath->req[1] && cmd))
2729 rc = GPG_ERR_SYNTAX;
2730 goto fail;
2733 xpath->xp = xmlXPathNewContext (client->doc);
2734 if (!xpath->xp)
2736 rc = GPG_ERR_BAD_DATA;
2737 goto fail;
2740 xpath->result = xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2741 if (!xpath->result)
2743 rc = GPG_ERR_BAD_DATA;
2744 goto fail;
2747 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2749 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2750 goto fail;
2753 rc = recurse_xpath_nodeset (client->doc, xpath->result->nodesetval,
2754 (xmlChar *) xpath->req[1], &xpath->buf, cmd,
2755 (xmlChar *) req[1]);
2757 fail:
2758 xpath_command_cleanup (xpath);
2759 strv_free (req);
2760 return rc;
2763 /* XPATHATTR SET|DELETE <name> <expression>[<TAB>[value]] */
2764 static gpg_error_t
2765 xpathattr_command (assuan_context_t ctx, char *line)
2767 struct client_s *client = assuan_get_pointer (ctx);
2768 gpg_error_t rc;
2769 struct argv_s *args[] = {
2770 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2771 NULL
2774 if (disable_list_and_dump == 1)
2775 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2777 rc = parse_options (&line, args, client);
2778 if (rc)
2779 return send_error (ctx, rc);
2781 if (client->opts & OPT_INQUIRE)
2783 unsigned char *result;
2784 size_t len;
2786 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2787 if (rc)
2788 return send_error (ctx, rc);
2790 line = (char *) result;
2793 if (!line || !*line)
2794 rc = GPG_ERR_SYNTAX;
2796 if (!rc)
2797 rc = do_xpathattr (ctx, line);
2799 if (client->opts & OPT_INQUIRE)
2800 xfree (line);
2802 return send_error (ctx, rc);
2805 static gpg_error_t
2806 do_import (struct client_s *client, const char *root_element,
2807 unsigned char *content)
2809 char **dst_path = NULL;
2810 xmlDocPtr doc = NULL;
2811 xmlNodePtr n, root, copy;
2812 gpg_error_t rc;
2814 if (!content || !*content)
2816 xfree (content);
2817 return GPG_ERR_SYNTAX;
2820 if (root_element)
2821 dst_path = str_split (root_element, "\t", 0);
2823 if (dst_path && !valid_element_path (dst_path, 0))
2825 if (dst_path)
2826 strv_free (dst_path);
2828 return GPG_ERR_INV_VALUE;
2831 struct string_s *str = string_new_content ((char *)content);
2832 str = string_prepend (str, "<pwmd>");
2833 str = string_append (str, "</pwmd>");
2834 doc = xmlReadDoc ((xmlChar *) str->str, NULL, "UTF-8", XML_PARSE_NOBLANKS);
2835 string_free (str, 1);
2836 if (!doc)
2838 rc = GPG_ERR_BAD_DATA;
2839 goto fail;
2842 root = xmlDocGetRootElement (doc);
2843 xmlNodePtr root_orig = root->children;
2844 root = root->children;
2845 rc = validate_import (root);
2846 if (rc)
2847 goto fail;
2851 again:
2852 if (dst_path)
2854 char **path = strv_dup (dst_path);
2855 if (!path)
2857 log_write ("%s(%i): %s", __FILE__, __LINE__,
2858 pwmd_strerror (GPG_ERR_ENOMEM));
2859 rc = GPG_ERR_ENOMEM;
2860 goto fail;
2863 xmlChar *a = xmlGetProp (root, (xmlChar *) "_name");
2864 if (!a)
2866 strv_free (path);
2867 rc = GPG_ERR_ENOMEM;
2868 goto fail;
2871 if (strv_printf (&path, "%s", (char *) a) == 0)
2873 xmlFree (a);
2874 rc = GPG_ERR_ENOMEM;
2875 goto fail;
2878 xmlFree (a);
2879 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
2880 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2882 strv_free (path);
2883 goto fail;
2886 if (!rc)
2888 n = find_elements (client->doc, n->children, path + 1, &rc,
2889 NULL, NULL, NULL, 0, 0, NULL, 1);
2890 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2892 strv_free (path);
2893 goto fail;
2895 else if (!rc)
2897 xmlUnlinkNode (n);
2898 xmlFreeNode (n);
2899 strv_free (path);
2900 path = NULL;
2901 goto again;
2905 if (rc == GPG_ERR_ELEMENT_NOT_FOUND)
2907 n = create_element_path (client, &path, &rc, NULL);
2908 if (rc)
2909 goto fail;
2912 if (root->children)
2914 copy = xmlCopyNodeList (root->children);
2915 n = xmlAddChildList (n, copy);
2916 if (!n)
2917 rc = GPG_ERR_ENOMEM;
2920 strv_free (path);
2922 else
2924 char **path = NULL;
2926 /* Check if the content root element can create a DTD root element. */
2927 if (!xmlStrEqual ((xmlChar *) "element", root->name))
2929 rc = GPG_ERR_SYNTAX;
2930 goto fail;
2933 xmlChar *a;
2935 if ((a = xmlGetProp (root, (xmlChar *) "_name")) == NULL)
2937 rc = GPG_ERR_SYNTAX;
2938 goto fail;
2941 char *tmp = str_dup ((char *) a);
2942 xmlFree (a);
2943 int literal = is_literal_element (&tmp);
2945 if (!valid_xml_element ((xmlChar *) tmp) || literal)
2947 xfree (tmp);
2948 rc = GPG_ERR_INV_VALUE;
2949 goto fail;
2952 if (strv_printf (&path, "%s", tmp) == 0)
2954 xfree (tmp);
2955 rc = GPG_ERR_ENOMEM;
2956 goto fail;
2959 xfree (tmp);
2960 n = find_root_element (client->doc, &path, &rc, NULL, 0, 1);
2961 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2963 rc = GPG_ERR_BAD_DATA;
2964 goto fail;
2967 /* Overwriting the existing tree. */
2968 if (!rc)
2970 xmlUnlinkNode (n);
2971 xmlFreeNodeList (n);
2974 rc = 0;
2975 xmlSetProp (root, (xmlChar *) "_name", (xmlChar *) path[0]);
2976 n = xmlCopyNode (root, 1);
2977 n = xmlAddChildList (xmlDocGetRootElement (client->doc), n);
2978 strv_free (path);
2981 if (n && !rc)
2982 rc = update_element_mtime (n->parent);
2984 for (root = root_orig->next; root; root = root->next)
2986 if (root->type == XML_ELEMENT_NODE)
2987 break;
2990 root_orig = root;
2992 while (root);
2994 fail:
2995 if (doc)
2996 xmlFreeDoc (doc);
2998 if (dst_path)
2999 strv_free (dst_path);
3001 return rc;
3004 static gpg_error_t
3005 parse_import_opt_root (void *data, void *value)
3007 struct client_s *client = data;
3009 client->import_root = str_dup (value);
3010 return client->import_root ? 0 : GPG_ERR_ENOMEM;
3013 static gpg_error_t
3014 import_command (assuan_context_t ctx, char *line)
3016 gpg_error_t rc;
3017 struct client_s *client = assuan_get_pointer (ctx);
3018 unsigned char *result;
3019 size_t len;
3020 struct argv_s *args[] = {
3021 &(struct argv_s) {"root", OPTION_TYPE_ARG, parse_import_opt_root},
3022 NULL
3025 xfree (client->import_root);
3026 client->import_root = NULL;
3027 rc = parse_options (&line, args, client);
3028 if (rc)
3029 return send_error (ctx, rc);
3031 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3032 if (rc)
3033 return send_error (ctx, rc);
3035 rc = do_import (client, client->import_root, result);
3036 xfree (client->import_root);
3037 client->import_root = NULL;
3038 return send_error (ctx, rc);
3041 static gpg_error_t
3042 do_lock (struct client_s *client, int add)
3044 gpg_error_t rc = lock_file_mutex (client, add);
3046 if (!rc)
3047 client->flags |= FLAG_LOCK_CMD;
3049 return rc;
3052 static gpg_error_t
3053 lock_command (assuan_context_t ctx, char *line)
3055 struct client_s *client = assuan_get_pointer (ctx);
3056 gpg_error_t rc = do_lock (client, 0);
3058 return send_error (ctx, rc);
3061 static gpg_error_t
3062 unlock_command (assuan_context_t ctx, char *line)
3064 struct client_s *client = assuan_get_pointer (ctx);
3065 gpg_error_t rc;
3067 rc = unlock_file_mutex (client, 0);
3068 return send_error (ctx, rc);
3071 static gpg_error_t
3072 option_command (assuan_context_t ctx, char *line)
3074 struct client_s *client = assuan_get_pointer (ctx);
3075 gpg_error_t rc = 0;
3076 struct pinentry_option_s *pin_opts = &client->pinentry_opts;
3077 #ifdef WITH_AGENT
3078 struct agent_s *agent = client->crypto->agent;
3079 #endif
3080 char namebuf[255] = { 0 };
3081 char *name = namebuf;
3082 char *value = NULL, *p;
3084 p = strchr (line, '=');
3085 if (!p)
3086 strncpy (namebuf, line, sizeof(namebuf));
3087 else
3089 strncpy (namebuf, line, strlen (line)-strlen (p));
3090 value = p+1;
3093 log_write1 ("OPTION name='%s' value='%s'", name, value);
3095 if (strcasecmp (name, (char *) "log_level") == 0)
3097 long l = 0;
3099 if (value)
3101 l = strtol (value, NULL, 10);
3103 if (l < 0 || l > 2)
3104 return send_error (ctx, GPG_ERR_INV_VALUE);
3107 MUTEX_LOCK (&rcfile_mutex);
3108 config_set_int_param (&global_config, "global", "log_level", value);
3109 MUTEX_UNLOCK (&rcfile_mutex);
3110 goto done;
3112 else if (strcasecmp (name, (char *) "lock-timeout") == 0)
3114 long n = 0;
3115 char *p = NULL;
3117 if (value)
3119 n = strtol (value, &p, 10);
3120 if (p && *p)
3121 return send_error (ctx, GPG_ERR_INV_VALUE);
3124 client->lock_timeout = n;
3125 goto done;
3127 else if (strcasecmp (name, (char *) "NAME") == 0)
3129 char *tmp = pthread_getspecific (thread_name_key);
3131 if (tmp)
3132 xfree (tmp);
3134 if (!value || !*value)
3136 pthread_setspecific (thread_name_key, str_dup (""));
3137 goto done;
3140 pthread_setspecific (thread_name_key, str_dup (value));
3141 goto done;
3143 else if (strcasecmp (name, (char *) "lc-messages") == 0)
3145 xfree (pin_opts->lc_messages);
3146 pin_opts->lc_messages = NULL;
3147 if (value && *value)
3148 pin_opts->lc_messages = str_dup (value);
3149 #ifdef WITH_AGENT
3150 if (use_agent)
3151 rc = set_agent_option (client->crypto->agent, "lc-messages", value);
3152 #endif
3154 else if (strcasecmp (name, (char *) "lc-ctype") == 0)
3156 xfree (pin_opts->lc_ctype);
3157 pin_opts->lc_ctype = NULL;
3158 if (value && *value)
3159 pin_opts->lc_ctype = str_dup (value);
3160 #ifdef WITH_AGENT
3161 if (use_agent)
3162 rc = set_agent_option (client->crypto->agent, "lc-ctype", value);
3163 #endif
3165 else if (strcasecmp (name, (char *) "ttyname") == 0)
3167 xfree (pin_opts->ttyname);
3168 pin_opts->ttyname = NULL;
3169 if (value && *value)
3170 pin_opts->ttyname = str_dup (value);
3171 #ifdef WITH_AGENT
3172 if (use_agent)
3173 rc = set_agent_option (client->crypto->agent, "ttyname", value);
3174 #endif
3176 else if (strcasecmp (name, (char *) "ttytype") == 0)
3178 xfree (pin_opts->ttytype);
3179 pin_opts->ttytype = NULL;
3180 if (value && *value)
3181 pin_opts->ttytype = str_dup (value);
3182 #ifdef WITH_AGENT
3183 if (use_agent)
3184 rc = set_agent_option (client->crypto->agent, "ttytype", value);
3185 #endif
3187 else if (strcasecmp (name, (char *) "display") == 0)
3189 xfree (pin_opts->display);
3190 pin_opts->display = NULL;
3191 if (value && *value)
3192 pin_opts->display = str_dup (value);
3193 #ifdef WITH_AGENT
3194 if (use_agent)
3195 rc = set_agent_option (client->crypto->agent, "display", value);
3196 #endif
3198 else if (strcasecmp (name, (char *) "pinentry-desc") == 0)
3200 xfree (pin_opts->desc);
3201 pin_opts->desc = NULL;
3202 if (value && *value)
3203 pin_opts->desc = str_dup (value);
3205 else if (strcasecmp (name, (char *) "pinentry-title") == 0)
3207 xfree (pin_opts->title);
3208 pin_opts->title = NULL;
3209 if (value && *value)
3210 pin_opts->title = str_dup (value);
3212 else if (strcasecmp (name, (char *) "pinentry-prompt") == 0)
3214 xfree (pin_opts->prompt);
3215 pin_opts->prompt = NULL;
3216 if (value && *value)
3217 pin_opts->prompt = str_dup (value);
3220 else if (strcasecmp (name, "pinentry-timeout") == 0)
3222 char *p = NULL;
3223 int n;
3225 if (!value)
3226 goto done;
3228 n = (int) strtol (value, &p, 10);
3230 if (*p || n < 0)
3231 return send_error (ctx, GPG_ERR_INV_VALUE);
3233 pin_opts->timeout = n;
3234 MUTEX_LOCK (&rcfile_mutex);
3235 config_set_int_param (&global_config,
3236 client->filename ? client->filename : "global",
3237 "pinentry_timeout", value);
3238 MUTEX_UNLOCK (&rcfile_mutex);
3239 goto done;
3241 else if (strcasecmp (name, "disable-pinentry") == 0)
3243 char *p = NULL;
3244 int n = 1;
3246 if (value && *value)
3248 n = (int) strtol (value, &p, 10);
3249 if (*p || n < 0 || n > 1)
3250 return send_error (ctx, GPG_ERR_INV_VALUE);
3253 if (n)
3254 client->flags |= FLAG_NO_PINENTRY;
3255 else
3256 client->flags &= ~FLAG_NO_PINENTRY;
3258 #ifdef WITH_AGENT
3259 if (use_agent)
3261 if (client->flags & FLAG_NO_PINENTRY)
3262 rc = set_agent_option (client->crypto->agent, "pinentry-mode",
3263 "loopback");
3264 else
3265 rc = set_agent_option (client->crypto->agent, "pinentry-mode",
3266 "ask");
3268 if (rc)
3269 return send_error (ctx, rc);
3271 #endif
3273 else
3274 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
3276 done:
3277 #ifdef WITH_AGENT
3278 if (!rc && use_agent && agent)
3280 rc = pinentry_merge_options (&client->crypto->agent->pinentry_opts,
3281 pin_opts);
3283 #endif
3285 return send_error (ctx, rc);
3288 static gpg_error_t
3289 do_rename (assuan_context_t ctx, char *line)
3291 struct client_s *client = assuan_get_pointer (ctx);
3292 gpg_error_t rc;
3293 char **req, **src, *dst;
3294 xmlNodePtr n, ndst;
3296 req = str_split (line, " ", 0);
3298 if (!req || !req[0] || !req[1])
3300 strv_free (req);
3301 return GPG_ERR_SYNTAX;
3304 dst = req[1];
3305 is_literal_element (&dst);
3307 if (!valid_xml_element ((xmlChar *) dst))
3309 strv_free (req);
3310 return GPG_ERR_INV_VALUE;
3313 if (strchr (req[0], '\t'))
3314 src = str_split (req[0], "\t", 0);
3315 else
3316 src = str_split (req[0], " ", 0);
3318 if (!src || !*src)
3320 rc = GPG_ERR_SYNTAX;
3321 goto fail;
3324 n = find_root_element (client->doc, &src, &rc, NULL, 0, 0);
3325 if (src[1] && n)
3326 n = find_elements (client->doc, n->children, src + 1, &rc, NULL, NULL,
3327 NULL, 0, 0, NULL, 0);
3329 if (!n)
3330 goto fail;
3332 xmlChar *a = xmlGetProp (n, (xmlChar *) "_name");
3333 if (!a)
3335 rc = GPG_ERR_ENOMEM;
3336 goto fail;
3339 /* To prevent unwanted effects:
3341 * <root name="a"><b/></root>
3343 * RENAME a<TAB>b b
3345 if (xmlStrEqual (a, (xmlChar *) dst))
3347 xmlFree (a);
3348 rc = GPG_ERR_AMBIGUOUS_NAME;
3349 goto fail;
3352 xmlFree (a);
3353 char **tmp = NULL;
3354 if (src[1])
3356 char **p;
3358 for (p = src; *p; p++)
3360 if (!*(p + 1))
3361 break;
3362 strv_printf (&tmp, "%s", *p);
3366 strv_printf (&tmp, "!%s", dst);
3367 ndst = find_root_element (client->doc, &tmp, &rc, NULL, 0, 0);
3368 if (!ndst && rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3370 strv_free (tmp);
3371 goto fail;
3374 if (tmp[1] && ndst)
3375 ndst = find_elements (client->doc, ndst->children, tmp + 1, &rc, NULL,
3376 NULL, NULL, 0, 0, NULL, 0);
3378 strv_free (tmp);
3379 if (!ndst && rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3380 goto fail;
3382 rc = 0;
3384 /* Target may exist:
3386 * <root name="a"/>
3387 * <root name="b" target="a"/>
3389 * RENAME b a
3391 * Would need to do:
3392 * RENAME !b a
3394 if (ndst == n)
3396 rc = GPG_ERR_AMBIGUOUS_NAME;
3397 goto fail;
3400 if (ndst)
3402 unlink_node (ndst);
3403 xmlFreeNodeList (ndst);
3406 rc = add_attribute (n, "_name", dst);
3408 fail:
3409 strv_free (req);
3410 strv_free (src);
3411 return rc;
3414 static gpg_error_t
3415 rename_command (assuan_context_t ctx, char *line)
3417 struct client_s *client = assuan_get_pointer (ctx);
3418 gpg_error_t rc;
3419 struct argv_s *args[] = {
3420 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3421 NULL
3424 rc = parse_options (&line, args, client);
3425 if (rc)
3426 return send_error (ctx, rc);
3428 if (client->opts & OPT_INQUIRE)
3430 unsigned char *result;
3431 size_t len;
3433 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3434 if (rc)
3435 return send_error (ctx, rc);
3437 line = (char *) result;
3440 rc = do_rename (ctx, line);
3442 if (client->opts & OPT_INQUIRE)
3443 xfree (line);
3445 return send_error (ctx, rc);
3448 static gpg_error_t
3449 do_copy (assuan_context_t ctx, char *line)
3451 struct client_s *client = assuan_get_pointer (ctx);
3452 gpg_error_t rc;
3453 char **req, **src = NULL, **dst = NULL;
3454 xmlNodePtr nsrc, ndst, new = NULL;
3456 req = str_split (line, " ", 0);
3457 if (!req || !req[0] || !req[1])
3459 strv_free (req);
3460 return GPG_ERR_SYNTAX;
3463 if (strchr (req[0], '\t'))
3464 src = str_split (req[0], "\t", 0);
3465 else
3466 src = str_split (req[0], " ", 0);
3468 if (!src || !*src)
3470 rc = GPG_ERR_SYNTAX;
3471 goto fail;
3474 if (strchr (req[1], '\t'))
3475 dst = str_split (req[1], "\t", 0);
3476 else
3477 dst = str_split (req[1], " ", 0);
3479 if (!dst || !*dst)
3481 rc = GPG_ERR_SYNTAX;
3482 goto fail;
3485 if (!valid_element_path (dst, 0))
3487 rc = GPG_ERR_INV_VALUE;
3488 goto fail;
3491 nsrc = find_root_element (client->doc, &src, &rc, NULL, 0, 0);
3492 if (nsrc && src[1])
3493 nsrc = find_elements (client->doc, nsrc->children, src + 1, &rc, NULL,
3494 NULL, NULL, 0, 0, NULL, 0);
3496 if (!nsrc)
3497 goto fail;
3499 new = xmlCopyNodeList (nsrc);
3500 if (!new)
3502 rc = GPG_ERR_ENOMEM;
3503 goto fail;
3506 int create = 0;
3507 ndst = find_root_element (client->doc, &dst, &rc, NULL, 0, 0);
3508 if (ndst && dst[1])
3510 if (ndst->children)
3511 ndst = find_elements (client->doc, ndst->children, dst + 1, &rc, NULL,
3512 NULL, create_target_elements_cb, 0, 0, NULL, 0);
3513 else
3514 create = 1;
3516 else
3517 create = 1;
3519 if (!ndst && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3520 goto fail;
3521 else if (!ndst || create)
3523 ndst = create_element_path (client, &dst, &rc, NULL);
3524 if (!ndst)
3525 goto fail;
3528 /* Merge any attributes from the src node to the initial dst node. */
3529 for (xmlAttrPtr attr = new->properties; attr; attr = attr->next)
3531 if (xmlStrEqual (attr->name, (xmlChar *) "_name"))
3532 continue;
3534 xmlAttrPtr a = xmlHasProp (ndst, attr->name);
3535 if (a)
3536 xmlRemoveProp (a);
3538 xmlChar *tmp = xmlNodeGetContent (attr->children);
3539 xmlNewProp (ndst, attr->name, tmp);
3540 xmlFree (tmp);
3541 rc = add_attribute (ndst, NULL, NULL);
3544 xmlNodePtr n = ndst->children;
3545 xmlUnlinkNode (n);
3546 xmlFreeNodeList (n);
3547 ndst->children = NULL;
3549 if (new->children)
3551 n = xmlCopyNodeList (new->children);
3552 if (!n)
3554 rc = GPG_ERR_ENOMEM;
3555 goto fail;
3558 n = xmlAddChildList (ndst, n);
3559 if (!n)
3561 rc = GPG_ERR_ENOMEM;
3562 goto fail;
3565 rc = update_element_mtime (xmlDocGetRootElement (client->doc) ==
3566 ndst->parent ? ndst : ndst->parent);
3569 fail:
3570 if (new)
3572 xmlUnlinkNode (new);
3573 xmlFreeNodeList (new);
3576 if (req)
3577 strv_free (req);
3579 if (src)
3580 strv_free (src);
3582 if (dst)
3583 strv_free (dst);
3585 return rc;
3588 static gpg_error_t
3589 copy_command (assuan_context_t ctx, char *line)
3591 struct client_s *client = assuan_get_pointer (ctx);
3592 gpg_error_t rc;
3593 struct argv_s *args[] = {
3594 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3595 NULL
3598 rc = parse_options (&line, args, client);
3599 if (rc)
3600 return send_error (ctx, rc);
3602 if (client->opts & OPT_INQUIRE)
3604 unsigned char *result;
3605 size_t len;
3607 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3608 if (rc)
3609 return send_error (ctx, rc);
3611 line = (char *) result;
3614 rc = do_copy (ctx, line);
3616 if (client->opts & OPT_INQUIRE)
3617 xfree (line);
3619 return send_error (ctx, rc);
3622 static gpg_error_t
3623 do_move (assuan_context_t ctx, char *line)
3625 struct client_s *client = assuan_get_pointer (ctx);
3626 gpg_error_t rc;
3627 char **req, **src = NULL, **dst = NULL;
3628 xmlNodePtr nsrc, ndst = NULL;
3630 req = str_split (line, " ", 0);
3632 if (!req || !req[0] || !req[1])
3634 strv_free (req);
3635 return GPG_ERR_SYNTAX;
3638 if (strchr (req[0], '\t'))
3639 src = str_split (req[0], "\t", 0);
3640 else
3641 src = str_split (req[0], " ", 0);
3643 if (!src || !*src)
3645 rc = GPG_ERR_SYNTAX;
3646 goto fail;
3649 if (strchr (req[1], '\t'))
3650 dst = str_split (req[1], "\t", 0);
3651 else
3652 dst = str_split (req[1], " ", 0);
3654 nsrc = find_root_element (client->doc, &src, &rc, NULL, 0, 0);
3655 if (nsrc && src[1])
3656 nsrc = find_elements (client->doc, nsrc->children, src + 1, &rc, NULL,
3657 NULL, NULL, 0, 0, NULL, 0);
3659 if (!nsrc)
3660 goto fail;
3662 if (dst)
3664 if (!valid_element_path (dst, 0))
3666 rc = GPG_ERR_INV_VALUE;
3667 goto fail;
3670 ndst = find_root_element (client->doc, &dst, &rc, NULL, 0, 0);
3671 if (ndst && dst[1])
3672 ndst = find_elements (client->doc, ndst->children, dst + 1, &rc, NULL,
3673 NULL, NULL, 0, 0, NULL, 0);
3675 else
3676 ndst = xmlDocGetRootElement (client->doc);
3678 for (xmlNodePtr n = ndst; n; n = n->parent)
3680 if (n == nsrc)
3682 rc = GPG_ERR_CONFLICT;
3683 goto fail;
3687 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3688 goto fail;
3690 rc = 0;
3692 if (ndst)
3694 xmlChar *a = node_has_attribute (nsrc, (xmlChar *) "_name");
3695 xmlNodePtr dup = find_element (ndst->children, (char *) a, NULL);
3697 xmlFree (a);
3698 if (dup)
3700 if (dup == nsrc)
3701 goto fail;
3703 if (ndst == xmlDocGetRootElement (client->doc))
3705 xmlNodePtr n = nsrc;
3706 int match = 0;
3708 while (n->parent && n->parent != ndst)
3709 n = n->parent;
3711 xmlChar *a = node_has_attribute (n, (xmlChar *) "_name");
3712 xmlChar *b = node_has_attribute (nsrc, (xmlChar *) "_name");
3714 if (xmlStrEqual (a, b))
3716 match = 1;
3717 xmlUnlinkNode (nsrc);
3718 xmlUnlinkNode (n);
3719 xmlFreeNodeList (n);
3722 xmlFree (a);
3723 xmlFree (b);
3725 if (!match)
3727 xmlUnlinkNode (dup);
3728 xmlFreeNodeList (dup);
3731 else
3732 xmlUnlinkNode (dup);
3736 if (!ndst && dst)
3738 xmlChar *name = node_has_attribute (nsrc, (xmlChar *) "_name");
3740 if (nsrc->parent == xmlDocGetRootElement (client->doc)
3741 && !strcmp ((char *) name, *dst))
3743 xmlFree (name);
3744 rc = GPG_ERR_CONFLICT;
3745 goto fail;
3748 xmlFree (name);
3749 ndst = create_element_path (client, &dst, &rc, nsrc);
3752 if (!ndst)
3753 goto fail;
3755 update_element_mtime (nsrc->parent);
3756 xmlUnlinkNode (nsrc);
3757 ndst = xmlAddChildList (ndst, nsrc);
3759 if (!ndst)
3760 rc = GPG_ERR_ENOMEM;
3761 else
3762 update_element_mtime (ndst->parent);
3764 fail:
3765 if (req)
3766 strv_free (req);
3768 if (src)
3769 strv_free (src);
3771 if (dst)
3772 strv_free (dst);
3774 return rc;
3777 static gpg_error_t
3778 move_command (assuan_context_t ctx, char *line)
3780 struct client_s *client = assuan_get_pointer (ctx);
3781 gpg_error_t rc;
3782 struct argv_s *args[] = {
3783 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3784 NULL
3787 rc = parse_options (&line, args, client);
3788 if (rc)
3789 return send_error (ctx, rc);
3791 if (client->opts & OPT_INQUIRE)
3793 unsigned char *result;
3794 size_t len;
3796 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3797 if (rc)
3798 return send_error (ctx, rc);
3800 line = (char *) result;
3803 rc = do_move (ctx, line);
3805 if (client->opts & OPT_INQUIRE)
3806 xfree (line);
3808 return send_error (ctx, rc);
3811 static gpg_error_t
3812 ls_command (assuan_context_t ctx, char *line)
3814 gpg_error_t rc;
3815 char *tmp = str_asprintf ("%s/data", homedir);
3816 char *dir = expand_homedir (tmp);
3817 DIR *d = opendir (dir);
3819 rc = gpg_error_from_errno (errno);
3820 xfree (tmp);
3822 if (!d)
3824 xfree (dir);
3825 return send_error (ctx, rc);
3828 size_t len =
3829 offsetof (struct dirent, d_name) +pathconf (dir, _PC_NAME_MAX) + 1;
3830 struct dirent *p = xmalloc (len), *cur = NULL;
3831 char *list = NULL;
3833 xfree (dir);
3834 rc = 0;
3836 while (!readdir_r (d, p, &cur) && cur)
3838 if (cur->d_name[0] == '.' && cur->d_name[1] == '\0')
3839 continue;
3840 else if (cur->d_name[0] == '.' && cur->d_name[1] == '.'
3841 && cur->d_name[2] == '\0')
3842 continue;
3844 tmp = str_asprintf ("%s%s\n", list ? list : "", cur->d_name);
3846 if (!tmp)
3848 if (list)
3849 xfree (list);
3851 rc = GPG_ERR_ENOMEM;
3852 break;
3855 xfree (list);
3856 list = tmp;
3859 closedir (d);
3860 xfree (p);
3862 if (rc)
3863 return send_error (ctx, rc);
3865 if (!list)
3866 return send_error (ctx, GPG_ERR_NO_DATA);
3868 list[strlen (list) - 1] = 0;
3869 rc = xfer_data (ctx, list, strlen (list));
3870 xfree (list);
3871 return send_error (ctx, rc);
3874 static gpg_error_t
3875 bye_notify (assuan_context_t ctx, char *line)
3877 struct client_s *cl = assuan_get_pointer (ctx);
3879 #ifdef WITH_GNUTLS
3880 if (cl->thd->remote)
3882 int rc;
3886 struct timeval tv = { 0, 50000 };
3888 rc = gnutls_bye (cl->thd->tls->ses, GNUTLS_SHUT_RDWR);
3889 if (rc == GNUTLS_E_AGAIN)
3890 select (0, NULL, NULL, NULL, &tv);
3892 while (rc == GNUTLS_E_AGAIN);
3894 #endif
3896 /* This will let assuan_process_next() return. */
3897 fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK);
3898 cl->last_rc = 0; // BYE command result
3899 return 0;
3902 static gpg_error_t
3903 reset_notify (assuan_context_t ctx, char *line)
3905 struct client_s *client = assuan_get_pointer (ctx);
3907 if (client)
3908 cleanup_client (client);
3910 return 0;
3914 * This is called before every Assuan command.
3916 static gpg_error_t
3917 command_startup (assuan_context_t ctx, const char *name)
3919 struct client_s *client = assuan_get_pointer (ctx);
3920 gpg_error_t rc;
3921 struct command_table_s *cmd = NULL;
3923 log_write1 ("command='%s'", name);
3924 client->last_rc = client->opts = 0;
3926 for (int i = 0; command_table[i]; i++)
3928 if (!strcasecmp (name, command_table[i]->name))
3930 if (command_table[i]->ignore_startup)
3931 return 0;
3932 cmd = command_table[i];
3933 break;
3937 client->last_rc = rc = gpg_error (file_modified (client, cmd));
3938 return rc;
3942 * This is called after every Assuan command.
3944 static void
3945 command_finalize (assuan_context_t ctx, gpg_error_t rc)
3947 struct client_s *client = assuan_get_pointer (ctx);
3949 if (!(client->flags & FLAG_LOCK_CMD))
3950 unlock_file_mutex (client, 0);
3952 log_write1 (_("command completed: rc=%u"), client->last_rc);
3953 client->last_rc = gpg_error (GPG_ERR_UNKNOWN_COMMAND);
3954 #ifdef WITH_GNUTLS
3955 client->thd->buffer_timeout = client->thd->last_buffer_size = 0;
3956 #endif
3959 static gpg_error_t
3960 help_command (assuan_context_t ctx, char *line)
3962 gpg_error_t rc;
3963 int i;
3965 if (!line || !*line)
3967 char *tmp;
3968 char *help = str_dup (_("Usage: HELP [<COMMAND>]\n"
3969 "For commands that take an element path as an argument, each element is "
3970 "separated with an ASCII @key{TAB} character (ASCII 0x09)."
3971 "\n" "COMMANDS:"));
3973 for (i = 0; command_table[i]; i++)
3975 if (!command_table[i]->help)
3976 continue;
3978 tmp = str_asprintf ("%s %s", help, command_table[i]->name);
3979 xfree (help);
3980 help = tmp;
3983 tmp = strip_texi_and_wrap (help);
3984 xfree (help);
3985 rc = xfer_data (ctx, tmp, strlen (tmp));
3986 xfree (tmp);
3987 return send_error (ctx, rc);
3990 for (i = 0; command_table[i]; i++)
3992 if (!strcasecmp (line, command_table[i]->name))
3994 char *help, *tmp;
3996 if (!command_table[i]->help)
3997 break;
3999 help = strip_texi_and_wrap (command_table[i]->help);
4000 tmp = str_asprintf (_("Usage: %s"), help);
4001 xfree (help);
4002 rc = xfer_data (ctx, tmp, strlen (tmp));
4003 xfree (tmp);
4004 return send_error (ctx, rc);
4008 return send_error (ctx, GPG_ERR_INV_NAME);
4011 static void
4012 new_command (const char *name, int ignore, int unlock,
4013 gpg_error_t (*handler) (assuan_context_t, char *),
4014 const char *help)
4016 int i = 0;
4018 if (command_table)
4019 for (i = 0; command_table[i]; i++);
4021 command_table =
4022 xrealloc (command_table, (i + 2) * sizeof (struct command_table_s *));
4023 command_table[i] = xcalloc (1, sizeof (struct command_table_s));
4024 command_table[i]->name = name;
4025 command_table[i]->handler = handler;
4026 command_table[i]->ignore_startup = ignore;
4027 command_table[i]->unlock = unlock;
4028 command_table[i++]->help = help;
4029 command_table[i] = NULL;
4032 void
4033 deinit_commands ()
4035 int i;
4037 for (i = 0; command_table[i]; i++)
4038 xfree (command_table[i]);
4040 xfree (command_table);
4043 static int
4044 sort_commands (const void *arg1, const void *arg2)
4046 struct command_table_s *const *a = arg1;
4047 struct command_table_s *const *b = arg2;
4049 if (!*a || !*b)
4050 return 0;
4051 else if (*a && !*b)
4052 return 1;
4053 else if (!*a && *b)
4054 return -1;
4056 return strcmp ((*a)->name, (*b)->name);
4059 static gpg_error_t
4060 passwd_command (assuan_context_t ctx, char *line)
4062 struct client_s *client = assuan_get_pointer (ctx);
4063 gpg_error_t rc;
4064 struct argv_s *args[] = {
4065 &(struct argv_s) {"reset", OPTION_TYPE_NOARG, parse_opt_reset},
4066 &(struct argv_s) {"s2k-count", OPTION_TYPE_ARG, parse_opt_s2k_count},
4067 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG, parse_opt_no_passphrase},
4068 NULL
4071 if (client->flags & FLAG_NEW)
4072 return send_error (ctx, GPG_ERR_INV_STATE);
4074 client->crypto->save.s2k_count =
4075 config_get_ulong (client->filename, "s2k_count");
4076 rc = parse_options (&line, args, client);
4077 if (rc)
4078 return send_error (ctx, rc);
4080 if (!rc && client->opts & OPT_RESET)
4082 rc = cache_clear (client->md5file);
4083 if (!rc)
4084 send_status_all (STATUS_CACHE, NULL);
4087 if (!rc)
4089 if (!IS_PKI (client->crypto))
4091 struct crypto_s *crypto;
4093 xfree (client->crypto->filename);
4094 client->crypto->filename = str_dup (client->filename);
4095 rc = change_passwd (ctx, client->filename,
4096 client->flags & FLAG_NO_PINENTRY, &crypto,
4097 (client->opts & OPT_NO_PASSPHRASE));
4098 if (!rc)
4100 cleanup_crypto (&client->crypto);
4101 client->crypto = crypto;
4102 update_checksum (client);
4103 cleanup_crypto_stage1 (client->crypto);
4106 #ifdef WITH_AGENT
4107 else
4109 if (client->crypto->save.s2k_count)
4110 rc = send_to_agent (client->crypto->agent, NULL, NULL,
4111 "OPTION s2k-count=%lu",
4112 client->crypto->save.s2k_count);
4114 if (!rc)
4115 rc = agent_passwd (client->crypto);
4117 #endif
4120 return send_error (ctx, rc);
4123 static gpg_error_t
4124 parse_keygrip_opt_sign (void *data, void *value)
4126 struct client_s *client = data;
4128 (void) value;
4129 client->opts |= OPT_SIGN;
4130 return 0;
4133 static gpg_error_t
4134 keygrip_command (assuan_context_t ctx, char *line)
4136 struct client_s *client = assuan_get_pointer (ctx);
4137 gpg_error_t rc;
4138 struct crypto_s *crypto = NULL;
4139 struct argv_s *args[] = {
4140 &(struct argv_s) {"sign", OPTION_TYPE_NOARG, parse_keygrip_opt_sign},
4141 NULL
4144 if (!line || !*line)
4145 return send_error (ctx, GPG_ERR_SYNTAX);
4147 rc = parse_options (&line, args, client);
4148 if (rc)
4149 return send_error (ctx, rc);
4151 if (!valid_filename (line))
4152 return send_error (ctx, GPG_ERR_INV_VALUE);
4154 rc = init_client_crypto (&crypto);
4155 if (rc)
4156 return send_error (ctx, rc);
4158 rc = read_data_file (line, crypto);
4159 if (!rc)
4161 char *hexgrip = NULL;
4163 if (!IS_PKI (crypto))
4165 cleanup_crypto (&crypto);
4166 return send_error (ctx, GPG_ERR_NOT_SUPPORTED);
4169 if (client->opts & OPT_SIGN)
4171 if (valid_keygrip (crypto->sign_grip, sizeof (crypto->sign_grip)))
4172 hexgrip = bin2hex (crypto->sign_grip, sizeof (crypto->sign_grip));
4175 if (!hexgrip)
4176 hexgrip = bin2hex (crypto->grip, sizeof (crypto->grip));
4178 if (!hexgrip)
4179 rc = GPG_ERR_ENOMEM;
4180 else
4181 rc = xfer_data (ctx, hexgrip, strlen (hexgrip));
4183 xfree (hexgrip);
4186 UPDATE_AGENT_CTX (client, crypto);
4187 cleanup_crypto (&crypto);
4188 return send_error (ctx, rc);
4191 static gpg_error_t
4192 parse_opt_data (void *data, void *value)
4194 struct client_s *client = data;
4196 (void) value;
4197 client->opts |= OPT_DATA;
4198 return 0;
4201 static gpg_error_t
4202 getinfo_command (assuan_context_t ctx, char *line)
4204 struct client_s *client = assuan_get_pointer (ctx);
4205 gpg_error_t rc;
4206 char buf[ASSUAN_LINELENGTH];
4207 struct argv_s *args[] = {
4208 &(struct argv_s) {"data", OPTION_TYPE_NOARG, parse_opt_data},
4209 NULL
4212 rc = parse_options (&line, args, client);
4213 if (rc)
4214 return send_error (ctx, rc);
4216 if (!strcasecmp (line, "clients"))
4218 if (client->opts & OPT_DATA)
4220 MUTEX_LOCK (&cn_mutex);
4221 snprintf (buf, sizeof (buf), "%i", slist_length (cn_thread_list));
4222 MUTEX_UNLOCK (&cn_mutex);
4223 rc = xfer_data (ctx, buf, strlen (buf));
4225 else
4226 rc = send_status (ctx, STATUS_CLIENTS, NULL);
4228 else if (!strcasecmp (line, "cache"))
4230 if (client->opts & OPT_DATA)
4232 snprintf (buf, sizeof (buf), "%u", cache_file_count ());
4233 rc = xfer_data (ctx, buf, strlen (buf));
4235 else
4236 rc = send_status (ctx, STATUS_CACHE, NULL);
4238 else if (!strcasecmp (line, "pid"))
4240 char buf[32];
4241 pid_t pid = getpid ();
4243 snprintf (buf, sizeof (buf), "%i", pid);
4244 rc = xfer_data (ctx, buf, strlen (buf));
4246 else if (!strcasecmp (line, "version"))
4248 char *buf = str_asprintf ("0x%06x %s%s", VERSION_HEX,
4249 #ifdef WITH_LIBACL
4250 "ACL "
4251 #endif
4252 #ifdef WITH_GNUTLS
4253 "GNUTLS "
4254 #endif
4255 #ifdef WITH_QUALITY
4256 "QUALITY "
4257 #endif
4258 "", use_agent ? "AGENT" : "");
4259 rc = xfer_data (ctx, buf, strlen (buf));
4260 xfree (buf);
4262 else if (!strcasecmp (line, "last_error"))
4264 if (client->last_error)
4265 rc = xfer_data (ctx, client->last_error, strlen (client->last_error));
4266 else
4267 rc = GPG_ERR_NO_DATA;
4269 else
4270 rc = gpg_error (GPG_ERR_SYNTAX);
4272 return send_error (ctx, rc);
4275 #ifdef WITH_AGENT
4276 static gpg_error_t
4277 send_data_cb (void *user, const void *buf, size_t len)
4279 assuan_context_t ctx = user;
4281 return assuan_send_data (ctx, buf, len);
4284 static gpg_error_t
4285 send_status_cb (void *user, const char *line)
4287 assuan_context_t ctx = user;
4288 char keyword[200], *k;
4289 const char *p;
4291 for (p = line, k = keyword; *p; p++)
4293 if (isspace (*p))
4294 break;
4296 *k++ = *p;
4299 *k = 0;
4300 if (*p == '#')
4301 p++;
4303 while (isspace (*p))
4304 p++;
4306 return assuan_write_status (ctx, keyword, *p ? p : NULL);
4308 #endif
4310 static gpg_error_t
4311 agent_command (assuan_context_t ctx, char *line)
4313 gpg_error_t rc = 0;
4315 if (!use_agent)
4316 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
4318 #ifdef WITH_AGENT
4319 struct client_s *client = assuan_get_pointer (ctx);
4321 if (!line || !*line)
4322 return send_error (ctx, GPG_ERR_SYNTAX);
4324 assuan_set_flag (client->crypto->agent->ctx, ASSUAN_CONVEY_COMMENTS, 1);
4325 rc = assuan_transact (client->crypto->agent->ctx, line, send_data_cb,
4326 client->ctx, agent_loopback_cb, client->crypto,
4327 send_status_cb, client->ctx);
4328 if (gpg_err_code (rc) == GPG_ERR_ASS_CANCELED)
4330 char *line;
4331 size_t len;
4333 rc = assuan_write_line (client->crypto->agent->ctx, "CAN");
4334 if (!rc)
4336 rc = assuan_read_line (client->crypto->agent->ctx, &line, &len);
4337 if (!rc)
4338 rc = gpg_error (GPG_ERR_ASS_CANCELED);
4342 assuan_set_flag (client->crypto->agent->ctx, ASSUAN_CONVEY_COMMENTS, 0);
4343 #endif
4344 return send_error (ctx, rc);
4347 void
4348 init_commands ()
4350 /* !BEGIN-HELP-TEXT!
4352 * This comment is used as a marker to generate the offline documentation
4353 * found in doc/pwmd.info. The indentation needs to be kept for the awk
4354 * script to determine where commands begin and end.
4356 new_command("HELP", 1, 1, help_command, _(
4357 "HELP [<COMMAND>]\n"
4358 "Show available commands or command specific help text."
4361 new_command("AGENT", 1, 1, agent_command, _(
4362 "AGENT <command>\n"
4363 "Send a @command{gpg-agent} protocol @var{command} directly to the "
4364 "@command{gpg-agent}."
4367 new_command("GETINFO", 1, 1, getinfo_command, _(
4368 "GETINFO [--data] CACHE | CLIENTS | PID | LAST_ERROR | VERSION\n"
4369 "Get server and other information: @var{cache} returns the number of cached "
4370 "documents via a status message. @var{clients} returns the number of "
4371 "connected clients via a status message. @var{pid} returns the process ID "
4372 "number of the server via a data response. @var{VERSION} returns the server "
4373 "version number and compile-time features with a data response with each "
4374 "being space delimited. @var{LAST_ERROR} returns a detailed description of "
4375 "the last failed command when available. @xref{Status Messages}. "
4376 "\n"
4377 "When the @option{--data} option is specified then the result will be sent "
4378 "via a data response rather than a status message."
4381 new_command("PASSWD", 0, 0, passwd_command, _(
4382 "PASSWD [--reset] [--s2k-count=N] [--no-passphrase]\n"
4383 "Changes the passphrase of the secret key required to open the current "
4384 "file or the passphrase of a symmetrically encrypted data file. When the "
4385 "@option{--reset} option is passed then the cache entry for the current "
4386 "file will be reset and the passphrase, if any, will be required during the "
4387 "next @code{OPEN}. @xref{OPEN}."
4388 "\n"
4389 "The @option{--s2k-count} option sets number of hash iterations for a "
4390 "passphrase and must be either @code{0} to use the calibrated count of the "
4391 "machine (the default), or a value greater than or equal to @code{65536}. "
4392 "@xref{SAVE}. This option has no effect for symmetrically encrypted data "
4393 "files."
4394 "\n"
4395 "The @option{--no-passphrase} option will prevent requiring a passphrase for "
4396 "the data file, although a passphrase may be required when changing it."
4399 new_command("KEYGRIP", 1, 1, keygrip_command, _(
4400 "KEYGRIP [--sign] <filename>\n"
4401 "Returns the hex encoded keygrip of the specified @var{filename} with a "
4402 "data response."
4403 "\n"
4404 "When the @option{--sign} option is specified then the key used for signing "
4405 "of the specified @var{filename} will be returned."
4406 "\n"
4407 "For symmetrically encrypted data files this command returns the error "
4408 "GPG_ERR_NOT_SUPPORTED."
4411 new_command("OPEN", 1, 1, open_command, _(
4412 "OPEN [--lock] <filename> [<passphrase>]\n"
4413 "Opens @var{filename} using @var{passphrase}. When the filename is not "
4414 "found on the file-system then a new document will be created. If the file "
4415 "is found, it is looked for in the file cache. If cached and no "
4416 "@var{passphrase} was specified then the cached document is opened. When not "
4417 "cached, @cite{pinentry(1)} will be used to retrieve the passphrase to use "
4418 "for decryption unless @option{disable-pinentry} (@pxref{OPTION}) was "
4419 "specified."
4420 "\n"
4421 "When the @option{--lock} option is passed then the file mutex will be "
4422 "locked as if the @code{LOCK} command (@pxref{LOCK}) had been sent after the "
4423 "file has been opened."
4426 new_command("SAVE", 0, 0, save_command, _(
4427 "SAVE [--no-passphrase] [--reset] [--no-agent] [--s2k-count=N] [--cipher=<algo>] [--cipher-iterations=N] [--inquire-keyparam] [--keygrip=hexstring] [--sign-keygrip=hexstring]\n"
4428 "Writes the @abbr{XML} document to disk. The file written to is the file that "
4429 "was opened using the @code{OPEN} command (@pxref{OPEN}). If the file is a "
4430 "new one or the option @option{--inquire-keyparam} was passed, then a new "
4431 "keypair will be generated and a pinentry will be used to prompt for the "
4432 "passphrase to encrypt with unless the @option{--no-passphrase} option was "
4433 "passed in which case the data file will not be passphrase protected. "
4434 "\n"
4435 "The @option{--no-agent} option disables use of @command{gpg-agent} for "
4436 "passphrase retrieval and caching of new files when @command{gpg-agent} "
4437 "use is enabled. The datafile will be symmetrically encrypted and will not "
4438 "use or generate any keypair."
4439 "\n"
4440 "The @option{--reset} option will clear the cache entry for the current file "
4441 "and require a passphrase, if needed, before saving."
4442 "\n"
4443 "The @option{--cipher} option can be used to encrypt the @abbr{XML} data to "
4444 "an alternate cipher. The default is @code{aes256}. See the Configuration "
4445 "(@pxref{Configuration}) for available ciphers."
4446 "\n"
4447 "The @option{--cipher-iterations} option specifies the number of times to "
4448 "encrypt the XML data. The default is 0 although 1 iteration is still done."
4449 "\n"
4450 "The @option{--inquire-keyparam} option will send a server @emph{INQUIRE} to "
4451 "the client to obtain the key paramaters to use when generating a new "
4452 "keypair. The inquired data is expected to be an S-expression. If not "
4453 "specified then an @samp{RSA} key of @samp{2048} bits will be generated "
4454 "unless otherwise set in the configuration file (@pxref{Configuration}). Note "
4455 "that when this option is specified a new keypair will be generated "
4456 "reguardless if the file is a new one and that if the data file is protected "
4457 "the passphrase to open it will be required before generating the new keypair."
4458 "\n"
4459 "You can encrypt the data file to a public key other than the one that it "
4460 "was originally encrypted with by passing the @option{--keygrip} option with "
4461 "the hex encoded keygrip of the public key as its argument. The keygrip may "
4462 "be of any key that @command{gpg-agent} knows about. The "
4463 "@option{--sign-keygrip} option may also be used to sign with an alternate "
4464 "secret key. This option may be needed when using a smartcard. This option "
4465 "has no effect with symmetrically encrypted data files."
4466 "\n"
4467 "The @option{--s2k-count} option sets number of hash iterations for a "
4468 "passphrase. A value less-than @code{65536} will use the machine calibrated "
4469 "value and is the default. This setting only affects new files. To change "
4470 "the setting use the @code{PASSWD} command (@pxref{PASSWD}). This option "
4471 "has no effect with symmetrically encrypted data files."
4474 new_command("ISCACHED", 1, 0, iscached_command, _(
4475 "ISCACHED [--lock] <filename>\n"
4476 "An @emph{OK} response is returned if the specified @var{filename} is found "
4477 "in the file cache. If not found in the cache but exists on the filesystem "
4478 "then @var{GPG_ERR_NO_DATA} is returned. Otherwise a filesystem error is "
4479 "returned."
4480 "\n"
4481 "The @option{lock} option will lock the file mutex of @var{filename} when the "
4482 "file exists; it does not need to be opened nor cached."
4485 new_command("CLEARCACHE", 1, 1, clearcache_command, _(
4486 "CLEARCACHE [<filename>]\n"
4487 "Clears a file cache entry for all or the specified @var{filename}."
4490 new_command("CACHETIMEOUT", 1, 1, cachetimeout_command, _(
4491 "CACHETIMEOUT <filename> <seconds>\n"
4492 "The time in @var{seconds} until @var{filename} will be removed from the "
4493 "cache. @code{-1} will keep the cache entry forever, @code{0} will require "
4494 "the passphrase for each @code{OPEN} or @code{SAVE} command (@pxref{OPEN}, "
4495 "@pxref{SAVE}). @xref{Configuration}, and the @code{cache_timeout} "
4496 "parameter."
4499 new_command("LIST", 0, 1, list_command, _(
4500 "LIST [--inquire] [--no-recurse] [--verbose] [--with-target] [--all] [[!]element[<TAB>[!]child[..]]]\n"
4501 "If no element path is given then a newline separated list of root elements "
4502 "is returned with a data response. If given, then all reachable elements "
4503 "of the specified element path are returned unless the @option{--no-recurse} "
4504 "option is specified. If specified, only the child elements of the element "
4505 "path are returned without recursing into grandchildren. Each resulting "
4506 "element is prefixed with the literal @code{!} character when the element "
4507 "contains no @code{target} attribute. @xref{Target Attribute}, for details."
4508 "\n"
4509 "When the @option{--verbose} option is passed then each element path "
4510 "returned will have zero or more flags appened to it. These flags are "
4511 "delimited from the element path by a single space character. A flag itself "
4512 "is a single character. Flag @code{+} indicates that there are child nodes of "
4513 "the current element path. Flag @code{E} indicates that an element of an "
4514 "element path contained in a @var{target} attribute could not be found. Flag "
4515 "@code{O} indicates that a @var{target} attribute recursion limit was reached "
4516 "(@pxref{Configuration}). Flag @code{T} will append the resolved element path "
4517 "of the @var{target} attribute contained in the current element (see below)."
4518 "\n"
4519 "The @option{--with-target} option implies @option{--verbose} and will append "
4520 "an additional flag @code{T} followed by a single space then an element path. "
4521 "The appended element path is the resolved path (@pxref{REALPATH}) of the "
4522 "current element when it contains a @var{target} attribute. When no "
4523 "@var{target} attribute is found then no flag will be appended."
4524 "\n"
4525 "The @option{--no-recurse} option limits the amount of data returned to only "
4526 "the listing of children of the specified element path and not any "
4527 "grandchildren."
4528 "\n"
4529 "The @option{--all} option lists the entire element tree for each root "
4530 "element. This option also implies option @option{--verbose}."
4531 "\n"
4532 "When the @option{--inquire} option is passed then all remaining non-option "
4533 "arguments are retrieved via a server @emph{INQUIRE}."
4536 new_command("REALPATH", 0, 1, realpath_command, _(
4537 "REALPATH [--inquire] [!]element[<TAB>[!]child[..]]\n"
4538 "Resolves all @code{target} attributes of the specified element path and "
4539 "returns the result with a data response. @xref{Target Attribute}, for details."
4540 "\n"
4541 "When the @option{--inquire} option is passed then all remaining non-option "
4542 "arguments are retrieved via a server @emph{INQUIRE}."
4545 new_command("STORE", 0, 1, store_command, _(
4546 "STORE [!]element[<TAB>[!]child[..]]<TAB>[content]\n"
4547 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
4548 "\n"
4549 "Creates a new element path or modifies the @var{content} of an existing "
4550 "element. If only a single element is specified then a new root element is "
4551 "created. Otherwise, elements are @key{TAB} delimited and the content will be "
4552 "set to the final @key{TAB} delimited element. If no @var{content} is "
4553 "specified after the final @key{TAB}, then the content of the element will "
4554 "be removed, or empty when creating a new element."
4555 "\n"
4556 "The only restriction of an element name is that it not contain whitespace "
4557 "or begin with the literal element character @code{!} unless specifying a "
4558 "literal element (@pxref{Target Attribute}). There is no whitespace between "
4559 "the @key{TAB} delimited elements. It is recommended that the content of an "
4560 "element be base64 encoded when it contains control or @key{TAB} characters "
4561 "to prevent @abbr{XML} parsing and @command{pwmd} syntax errors."
4564 new_command("RENAME", 0, 1, rename_command, _(
4565 "RENAME [--inquire] [!]element[<TAB>[!]child[..]] <value>\n"
4566 "Renames the specified @var{element} to the new @var{value}. If an element of "
4567 "the same name as the @var{value} already exists it will be overwritten."
4568 "\n"
4569 "When the @option{--inquire} option is passed then all remaining non-option "
4570 "arguments are retrieved via a server @emph{INQUIRE}."
4573 new_command("COPY", 0, 1, copy_command, _(
4574 "COPY [--inquire] [!]source[<TAB>[!]child[..]] [!]dest[<TAB>[!]child[..]]\n"
4575 "Copies the entire element tree starting from the child node of the source "
4576 "element, to the destination element path. If the destination element path "
4577 "does not exist then it will be created; otherwise it is overwritten."
4578 "\n"
4579 "Note that attributes from the source element are merged into the "
4580 "destination element when the destination element path exists. When an "
4581 "attribute of the same name exists in both the source and destination "
4582 "elements then the destination attribute will be updated to the source "
4583 "attribute value."
4584 "\n"
4585 "When the @option{--inquire} option is passed then all remaining non-option "
4586 "arguments are retrieved via a server @emph{INQUIRE}."
4589 new_command("MOVE", 0, 1, move_command, _(
4590 "MOVE [--inquire] [!]source[<TAB>[!]child[..]] [[!]dest[<TAB>[!]child[..]]]\n"
4591 "Moves the source element path to the destination element path. If the "
4592 "destination is not specified then it will be moved to the root node of the "
4593 "document. If the destination is specified and exists then it will be "
4594 "overwritten; otherwise non-existing elements of the destination element "
4595 "path will be created."
4596 "\n"
4597 "When the @option{--inquire} option is passed then all remaining non-option "
4598 "arguments are retrieved via a server @emph{INQUIRE}."
4601 new_command("DELETE", 0, 1, delete_command, _(
4602 "DELETE [--inquire] [!]element[<TAB>[!]child[..]]\n"
4603 "Removes the specified element path and all of its children. This may break "
4604 "an element with a @code{target} attribute (@pxref{Target Attribute}) that "
4605 "refers to this element or any of its children."
4606 "\n"
4607 "When the @option{--inquire} option is passed then all remaining non-option "
4608 "arguments are retrieved via a server @emph{INQUIRE}."
4611 new_command("GET", 0, 1, get_command, _(
4612 "GET [--inquire] [!]element[<TAB>[!]child[..]]\n"
4613 "Retrieves the content of the specified element. The content is returned "
4614 "with a data response."
4615 "\n"
4616 "When the @option{--inquire} option is passed then all remaining non-option "
4617 "arguments are retrieved via a server @emph{INQUIRE}."
4620 new_command("ATTR", 0, 1, attr_command, _(
4621 "ATTR [--inquire] SET|GET|DELETE|LIST [<attribute>] [!]element[<TAB>[!]child[..]] ..\n"
4622 "@table @asis\n"
4623 "@item ATTR SET attribute [!]element[<TAB>[!]child[..]] [value]\n"
4624 "\n"
4625 " Stores or updates an @var{attribute} name and optional @var{value} of an "
4626 "element. When no @var{value} is specified any existing value will be removed."
4627 "\n"
4628 "@item ATTR DELETE attribute [!]element[<TAB>[!]child[..]]\n"
4629 "\n"
4630 " Removes an @var{attribute} from an element."
4631 "\n"
4632 "@item ATTR LIST [!]element[<TAB>[!]child[..]]\n"
4633 "\n"
4634 " Retrieves a newline separated list of attributes names and values "
4635 "from the specified element. Each attribute name and value is space delimited."
4636 "\n"
4637 "@item ATTR GET attribute [!]element[<TAB>[!]child[..]]\n"
4638 "\n"
4639 " Retrieves the value of an @var{attribute} from an element."
4640 "@end table\n"
4641 "\n"
4642 "The @code{_name} attribute (case sensitive) cannot be removed nor modified. "
4643 "Use the @code{DELETE} (@pxref{DELETE}) or @code{RENAME} (@pxref{RENAME}) "
4644 "commands instead."
4645 "\n"
4646 "The @code{_mtime} attribute is updated each time an element is modified by "
4647 "either storing content, editing attributes or by deleting a child element. "
4648 "The @code{_ctime} attribute is created for each new element in an element "
4649 "path."
4650 "\n"
4651 "When the @option{--inquire} option is passed then all remaining non-option "
4652 "arguments are retrieved via a server @emph{INQUIRE}."
4653 "\n"
4654 "@xref{Target Attribute}, for details about this special attribute."
4657 new_command("XPATH", 0, 1, xpath_command, _(
4658 "XPATH [--inquire] <expression>[<TAB>[value]]\n"
4659 "Evaluates an XPath @var{expression}. If no @var{value} argument is "
4660 "specified it is assumed the expression is a request to return a result. "
4661 "Otherwise, the result is set to the @var{value} argument and the document is "
4662 "updated. If there is no @var{value} after the @key{TAB} character, the value "
4663 "is assumed to be empty and the document is updated. For example:"
4664 "@sp 1\n"
4665 "@example\n"
4666 "XPATH //element[@@_name='password']@key{TAB}\n"
4667 "@end example\n"
4668 "@sp 1"
4669 "would clear the content of all @code{password} elements in the data file "
4670 "while leaving off the trailing @key{TAB} would return all @code{password} "
4671 "elements in @abbr{XML} format."
4672 "\n"
4673 "When the @option{--inquire} option is passed then all remaining non-option "
4674 "arguments are retrieved via a server @emph{INQUIRE}."
4675 "\n"
4676 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
4677 "expression syntax."
4680 new_command("XPATHATTR", 0, 1, xpathattr_command, _(
4681 "XPATHATTR [--inquire] SET|DELETE <name> <expression>[<TAB>[<value>]]\n"
4682 "Like the @code{XPATH} command (@pxref{XPATH}) but operates on element "
4683 "attributes and does not return a result. For the @var{SET} operation the "
4684 "@var{value} is optional but the field is required. If not specified then "
4685 "the attribute value will be empty. For example:"
4686 "@sp 1"
4687 "@example\n"
4688 "XPATHATTR SET password //element[@@_name='password']@key{TAB}\n"
4689 "@end example\n"
4690 "@sp 1"
4691 "would create an @code{password} attribute for each @code{password} element "
4692 "found in the document. The attribute value will be empty but still exist."
4693 "\n"
4694 "When the @option{--inquire} option is passed then all remaining non-option "
4695 "arguments are retrieved via a server @emph{INQUIRE}."
4696 "\n"
4697 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
4698 "expression syntax."
4701 new_command("IMPORT", 0, 1, import_command, _(
4702 "IMPORT [--root [!]element[<TAB>[!]child[..]]] <content>\n"
4703 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
4704 "\n"
4705 "Like the @code{STORE} command (@pxref{STORE}), but the @var{content} "
4706 "argument is raw @abbr{XML} data. The content is created as a child of "
4707 "the element path specified with the @option{--root} option or at the "
4708 "document root when not specified. Existing elements of the same name will "
4709 "be overwritten."
4710 "\n"
4711 "The content must begin with an @abbr{XML} element node. @xref{Introduction}, "
4712 "for details."
4715 new_command("DUMP", 0, 1, dump_command, _(
4716 "DUMP\n"
4717 "Shows the in memory @abbr{XML} document with indenting. @xref{XPATH}, for "
4718 "dumping a specific node."
4721 new_command("LOCK", 0, 0, lock_command, _(
4722 "LOCK\n"
4723 "Locks the mutex associated with the opened file. This prevents other clients "
4724 "from sending commands to the same opened file until the client "
4725 "that sent this command either disconnects or sends the @code{UNLOCK} "
4726 "command. @xref{UNLOCK}."
4729 new_command("UNLOCK", 1, 0, unlock_command, _(
4730 "UNLOCK\n"
4731 "Unlocks the file mutex which was locked with the @code{LOCK} command or "
4732 "a commands' @option{--lock} option (@pxref{LOCK}, @pxref{OPEN}, "
4733 "@pxref{ISCACHED})."
4736 new_command("GETCONFIG", 1, 1, getconfig_command, _(
4737 "GETCONFIG [filename] <parameter>\n"
4738 "Returns the value of a @command{pwmd} configuration @var{parameter} with a "
4739 "data response. If no file has been opened then the value for @var{filename} "
4740 "or the default from the @samp{global} section will be returned. If a file "
4741 "has been opened and no @var{filename} is specified, a value previously "
4742 "set with the @code{OPTION} command (@pxref{OPTION}) will be returned."
4745 new_command("OPTION", 1, 1, option_command, _(
4746 "OPTION <NAME>=<VALUE>\n"
4747 "Sets a client option @var{name} to @var{value}. The value for an option is "
4748 "kept for the duration of the connection."
4749 "\n"
4750 "@table @asis\n"
4751 "@item DISABLE-PINENTRY\n"
4752 "Disable use of @command{pinentry} for passphrase retrieval. When set, a "
4753 "server inquire is sent to the client to obtain the passphrase. This option "
4754 "may be set as needed before the @pxref{OPEN}, @pxref{PASSWD}, and "
4755 "@pxref{SAVE} commands."
4756 "\n"
4757 "@item PINENTRY-TIMEOUT\n"
4758 "Sets the number of seconds before a pinentry prompt will return an error "
4759 "while waiting for user input."
4760 "\n"
4761 "@item TTYNAME\n"
4762 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4763 "\n"
4764 "@item TTYTYPE\n"
4765 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4766 "\n"
4767 "@item DISPLAY\n"
4768 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4769 "\n"
4770 "@item PINENTRY-DESC\n"
4771 "Sets the description string of the @command{gpg-agent} and @command{pinentry} dialog."
4772 "\n"
4773 "@item PINENTRY-TITLE\n"
4774 "Sets the title string of the @command{gpg-agent} and @command{pinentry} dialog."
4775 "\n"
4776 "@item PINENTRY-PROMPT\n"
4777 "Sets the prompt string of the @command{gpg-agent} and @command{pinentry} dialog."
4778 "\n"
4779 "@item LC-CTYPE\n"
4780 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4781 "\n"
4782 "@item LC-MESSAGES\n"
4783 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4784 "\n"
4785 "@item NAME\n"
4786 "Associates the thread ID of the connection with the specified textual "
4787 "representation. Useful for debugging log messages."
4788 "\n"
4789 "@item LOCK-TIMEOUT\n"
4790 "When not @code{0}, the duration in tenths of a second to wait for the file "
4791 "mutex which has been locked by another thread to be released before returning "
4792 "an error. When @code{-1}, then an error will be returned immediately."
4793 "\n"
4794 "@item LOG-LEVEL\n"
4795 "An integer specifiying the logging level."
4796 "@end table\n"
4799 new_command("LS", 1, 1, ls_command, _(
4800 "LS\n"
4801 "Lists the available data files stored in the data directory "
4802 "(@file{~/.pwmd/data}). The result is a newline separated list of filenames."
4805 new_command("RESET", 1, 1, NULL, _(
4806 "RESET\n"
4807 "Closes the currently opened file but keeps any previously set client options."
4810 new_command("NOP", 1, 1, NULL, _(
4811 "NOP\n"
4812 "Does nothing. Always returns successfully."
4815 /* !END-HELP-TEXT! */
4816 new_command ("CANCEL", 1, 1, NULL, NULL);
4817 new_command ("END", 1, 1, NULL, NULL);
4818 new_command ("BYE", 1, 1, NULL, NULL);
4820 int i;
4821 for (i = 0; command_table[i]; i++);
4822 qsort (command_table, i - 1, sizeof (struct command_table_s *),
4823 sort_commands);
4826 gpg_error_t
4827 register_commands (assuan_context_t ctx)
4829 int i = 0, rc;
4831 for (; command_table[i]; i++)
4833 if (!command_table[i]->handler)
4834 continue;
4836 rc = assuan_register_command (ctx, command_table[i]->name,
4837 command_table[i]->handler,
4838 command_table[i]->help);
4839 if (rc)
4840 return rc;
4843 rc = assuan_register_bye_notify (ctx, bye_notify);
4844 if (rc)
4845 return rc;
4847 rc = assuan_register_reset_notify (ctx, reset_notify);
4848 if (rc)
4849 return rc;
4851 rc = assuan_register_pre_cmd_notify (ctx, command_startup);
4852 if (rc)
4853 return rc;
4855 return assuan_register_post_cmd_notify (ctx, command_finalize);