Require the key to decrypt before generating a new keypair.
[pwmd.git] / src / commands.c
blob0e65ec93d2f56e7e717c673e754d0daa5fa070e7
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)
161 rc = 0;
164 if ((cmd->unlock && !(client->flags & FLAG_HAS_LOCK)) || rc)
165 unlock_file_mutex (client, 0);
167 return rc;
170 static gpg_error_t
171 parse_xml (assuan_context_t ctx, int new)
173 struct client_s *client = assuan_get_pointer (ctx);
174 int cached = client->doc != NULL;
176 if (new)
178 client->doc = new_document ();
179 if (client->doc)
181 xmlChar *result;
182 int len;
184 xmlDocDumpFormatMemory (client->doc, &result, &len, 0);
185 client->crypto->plaintext = result;
186 client->crypto->plaintext_len = len;
187 if (!client->crypto->plaintext)
189 xmlFreeDoc (client->doc);
190 client->doc = NULL;
194 else if (!cached)
195 client->doc = parse_doc ((char *) client->crypto->plaintext,
196 client->crypto->plaintext_len);
198 return !client->doc ? GPG_ERR_ENOMEM : 0;
201 static void
202 free_client (struct client_s *client)
204 if (client->doc)
205 xmlFreeDoc (client->doc);
207 xfree (client->crc);
208 xfree (client->filename);
209 xfree (client->last_error);
211 if (client->crypto)
213 cleanup_crypto_stage2 (client->crypto);
214 if (client->crypto->pkey_sexp)
215 gcry_sexp_release (client->crypto->pkey_sexp);
217 client->crypto->pkey_sexp = NULL;
218 memset (client->crypto->sign_grip, 0,
219 sizeof (client->crypto->sign_grip));
220 memset (client->crypto->grip, 0, sizeof(client->crypto->grip));
223 if (client->xml_error)
224 xmlResetError (client->xml_error);
227 void
228 cleanup_client (struct client_s *client)
230 assuan_context_t ctx = client->ctx;
231 struct client_thread_s *thd = client->thd;
232 struct crypto_s *crypto = client->crypto;
233 long lock_timeout = client->lock_timeout;
234 int no_pinentry = (client->flags & FLAG_NO_PINENTRY);
235 struct pinentry_option_s pin_opts;
236 #ifdef WITH_AGENT
237 struct pinentry_option_s agent_pin_opts;
239 if (crypto && crypto->agent)
240 memcpy (&agent_pin_opts, &crypto->agent->pinentry_opts,
241 sizeof(struct pinentry_option_s));
242 #endif
244 memcpy (&pin_opts, &client->pinentry_opts, sizeof(struct pinentry_option_s));
245 unlock_file_mutex (client, client->flags & FLAG_NEW);
246 free_client (client);
247 memset (client, 0, sizeof (struct client_s));
248 client->crypto = crypto;
249 client->ctx = ctx;
250 client->thd = thd;
251 client->lock_timeout = lock_timeout;
252 memcpy (&client->pinentry_opts, &pin_opts, sizeof(struct pinentry_option_s));
253 client->flags |= no_pinentry ? FLAG_NO_PINENTRY : 0;
254 #ifdef WITH_AGENT
255 if (crypto && crypto->agent)
256 memcpy (&crypto->agent->pinentry_opts, &agent_pin_opts,
257 sizeof(struct pinentry_option_s));
258 #endif
261 static gpg_error_t
262 open_finalize (assuan_context_t ctx, char *key, size_t keylen)
264 struct client_s *client = assuan_get_pointer (ctx);
265 gpg_error_t rc = 0;
266 struct cache_data_s *cdata = cache_get_data (client->md5file);
267 int cached = 0, keyarg = key ? 1 : 0;
268 size_t keysize;
269 unsigned char *salted_key = NULL;
270 int algo;
271 int pin_try = 1;
272 int pin_tries = 3;
273 char *pin_title = client->pinentry_opts.title;
275 client->crypto->filename = str_dup (client->filename);
276 if (cdata || client->flags & FLAG_NEW)
278 if (cdata && !(client->flags & FLAG_NEW))
280 rc = decrypt_xml (client->crypto, cdata->doc, cdata->doclen);
281 if (rc)
282 return rc;
285 cached = cdata != NULL;
286 goto done;
289 if (!key && !IS_PKI (client->crypto))
291 if (client->flags & FLAG_NO_PINENTRY)
293 rc = inquire_passphrase (ctx, "PASSPHRASE", (unsigned char **)&key,
294 &keylen);
295 if (rc)
296 return rc;
298 else
300 client->pinentry_opts.timeout = config_get_integer (client->filename,
301 "pinentry_timeout");
302 pin_again:
303 rc = getpin_common (client->ctx, client->filename, PINENTRY_OPEN,
304 &key, &keylen);
305 if (rc)
306 return rc;
310 if (!IS_PKI (client->crypto))
312 algo = cipher_to_gcrypt (client->crypto->hdr.flags);
313 rc = hash_key (algo, client->crypto->hdr.salt,
314 sizeof(client->crypto->hdr.salt), key, keylen,
315 (void **)&salted_key, &keysize);
316 if (!keyarg)
317 gcry_free (key);
319 if (!rc)
321 rc = decrypt_data (client->ctx, client->crypto, salted_key, keysize);
322 if (gpg_err_code (rc) == GPG_ERR_BAD_PASSPHRASE
323 && ++pin_try <= pin_tries && !(client->flags & FLAG_NO_PINENTRY))
325 gcry_free (salted_key);
326 salted_key = NULL;
327 key = NULL;
328 keylen = 0;
329 client->pinentry_opts.title = str_asprintf (_ ("Bad passphrase (try %i of %i)"), pin_try, pin_tries);
330 goto pin_again;
334 if (client->pinentry_opts.title != pin_title)
335 xfree (client->pinentry_opts.title);
337 client->pinentry_opts.title = pin_title;
338 if (rc)
339 return rc;
341 cdata = xcalloc (1, sizeof (struct cache_data_s));
342 if (!cdata)
343 return GPG_ERR_ENOMEM;
345 cdata->key = salted_key;
346 cdata->keylen = keysize;
348 else
349 rc = decrypt_data (client->ctx, client->crypto, NULL, 0);
351 done:
352 if (!rc)
354 rc = parse_xml (ctx, client->flags & FLAG_NEW);
355 if (!rc)
357 int timeout = config_get_integer (client->filename,
358 "cache_timeout");
360 if (!cached)
362 if (!cdata)
363 cdata = xcalloc (1, sizeof (struct cache_data_s));
365 rc = encrypt_xml (NULL, cache_key, cache_keysize,
366 GCRY_CIPHER_AES, client->crypto->plaintext,
367 client->crypto->plaintext_len, &cdata->doc,
368 &cdata->doclen, &cache_iv, &cache_blocksize,
370 if (!rc && !(client->flags & FLAG_NEW) && IS_PKI (client->crypto))
372 rc = gcry_sexp_build ((gcry_sexp_t *) & cdata->pubkey, NULL,
373 "%S", client->crypto->pkey_sexp);
377 if (cdata->sigkey)
378 gcry_sexp_release (cdata->sigkey);
380 cdata->sigkey = NULL;
382 if (!rc && IS_PKI (client->crypto))
383 rc = gcry_sexp_build ((gcry_sexp_t *) &cdata->sigkey, NULL,
384 "%S", client->crypto->sigpkey_sexp);
386 if (!rc
387 && !cache_add_file (client->md5file, (client->flags & FLAG_NEW)
388 ? NULL : client->crypto->grip, cdata, timeout))
390 if (!cached)
392 free_cache_data_once (cdata);
393 xmlFreeDoc (client->doc);
394 client->doc = NULL;
396 rc = GPG_ERR_ENOMEM;
399 if (!rc)
400 client->flags |= FLAG_OPEN;
404 if (!rc)
405 update_checksum (client);
407 if (!rc && (client->opts & OPT_LOCK_ON_OPEN))
408 rc = do_lock (client, 0);
410 return rc;
413 static void
414 req_cleanup (void *arg)
416 if (!arg)
417 return;
419 strv_free ((char **) arg);
422 static gpg_error_t
423 parse_open_opt_lock (void *data, void *value)
425 struct client_s *client = data;
427 client->opts |= OPT_LOCK_ON_OPEN;
428 return 0;
431 static gpg_error_t
432 parse_opt_inquire (void *data, void *value)
434 struct client_s *client = data;
436 (void) value;
437 client->opts |= OPT_INQUIRE;
438 return 0;
441 static gpg_error_t
442 update_checksum (struct client_s *client)
444 unsigned char *crc;
445 size_t len;
446 struct cache_data_s *cdata;
447 gpg_error_t rc = get_checksum (client->filename, &crc, &len);
449 if (rc)
450 return rc;
452 xfree (client->crc);
453 client->crc = crc;
454 cdata = cache_get_data (client->md5file);
455 if (cdata)
457 xfree (cdata->crc);
458 cdata->crc = xmalloc (len);
459 memcpy (cdata->crc, crc, len);
462 return 0;
465 static gpg_error_t
466 validate_checksum (struct client_s *client, struct cache_data_s *cdata)
468 unsigned char *crc;
469 size_t len;
470 gpg_error_t rc;
471 int n = 0;
473 if (cdata && !cdata->crc)
474 return GPG_ERR_CHECKSUM;
476 rc = get_checksum (client->filename, &crc, &len);
477 if (rc)
478 return rc;
480 if (cdata)
481 n = memcmp (cdata->crc, crc, len);
482 else if (client->crc)
483 n = memcmp (client->crc, crc, len);
485 xfree (crc);
486 return n ? GPG_ERR_CHECKSUM : 0;
489 static gpg_error_t
490 do_open (assuan_context_t ctx, const char *filename, const char *password)
492 struct client_s *client = assuan_get_pointer (ctx);
493 struct cache_data_s *cdata;
494 gpg_error_t rc = 0;
495 int done = 0;
497 if (!valid_filename (filename))
498 return GPG_ERR_INV_VALUE;
500 gcry_md_hash_buffer (GCRY_MD_MD5, client->md5file, filename,
501 strlen (filename));
502 client->filename = str_dup (filename);
503 if (!client->filename)
504 return GPG_ERR_ENOMEM;
506 // Cached document?
507 cdata = cache_get_data (client->md5file);
508 if (cdata && cdata->doc)
510 int defer;
512 rc = validate_checksum (client, cdata);
513 /* This will check that the key is cached in the agent which needs to
514 * be determined for files that share a keygrip. */
515 if (!rc)
517 rc = cache_iscached (client->filename, &defer);
518 if (!rc && defer)
519 rc = GPG_ERR_KEY_EXPIRED;
522 #ifdef WITH_GNUTLS
523 if (!rc && client->thd->remote
524 && config_get_boolean (client->filename, "tcp_require_key"))
525 rc = GPG_ERR_KEY_EXPIRED;
526 #endif
528 if (!rc && !password)
530 rc = read_data_header (client->filename, &client->crypto->hdr,
531 NULL, NULL);
532 if (!rc)
534 if (IS_PKI (client->crypto))
536 gcry_sexp_build (&client->crypto->pkey_sexp, NULL, "%S",
537 cdata->pubkey);
538 gcry_pk_get_keygrip (client->crypto->pkey_sexp,
539 client->crypto->grip);
540 gcry_sexp_build (&client->crypto->sigpkey_sexp, NULL, "%S",
541 cdata->sigkey);
542 gcry_pk_get_keygrip (client->crypto->sigpkey_sexp,
543 client->crypto->sign_grip);
546 if (!rc)
548 rc = open_finalize (ctx, NULL, 0);
549 done = 1;
554 /* There was an error accessing the file so clear the cache entry. The
555 * real error will be returned from read_data_file() since the file
556 * may have only disappeared. */
557 if (!done)
559 log_write ("%s: %s", filename, pwmd_strerror (rc));
560 rc = cache_clear (client->md5file);
561 send_status_all (STATUS_CACHE, NULL);
565 if (done || rc)
566 return rc;
568 rc = read_data_file (client->filename, client->crypto);
569 if (rc)
571 if (gpg_err_source (rc) != GPG_ERR_SOURCE_DEFAULT ||
572 gpg_err_code (rc) != GPG_ERR_ENOENT)
574 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
575 return rc;
578 client->flags |= FLAG_NEW;
579 memset (client->crypto->grip, 0, sizeof (client->crypto->grip));
580 memset (client->crypto->sign_grip, 0,
581 sizeof (client->crypto->sign_grip));
582 rc = open_finalize (ctx, NULL, 0);
583 return rc;
586 if (password && IS_PKI (client->crypto))
588 #ifdef WITH_AGENT
589 rc = set_agent_passphrase (client->crypto, password, strlen (password));
590 if (rc)
591 return rc;
592 #endif
595 rc = open_finalize (ctx, (char *)password, password ? strlen (password) : 0);
596 return rc;
599 static gpg_error_t
600 open_command (assuan_context_t ctx, char *line)
602 gpg_error_t rc;
603 struct client_s *client = assuan_get_pointer (ctx);
604 char **req, *password = NULL, *filename;
605 unsigned char md5file[16];
606 int same_file = 0;
607 struct argv_s *args[] = {
608 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_open_opt_lock},
609 NULL
612 rc = parse_options (&line, args, client);
613 if (rc)
614 return send_error (ctx, rc);
616 req = str_split (line, " ", 2);
617 if (!req)
618 return send_error (ctx, GPG_ERR_SYNTAX);
620 #ifdef WITH_GNUTLS
621 if (client->thd->remote)
623 rc = tls_validate_access (client, req[0]);
624 if (rc)
626 if (rc == GPG_ERR_INV_USER_ID)
627 log_write (_("client validation failed for file '%s'"), req[0]);
628 strv_free (req);
629 return send_error (ctx, rc);
632 /* Remote pinentries are not supported. */
633 client->flags |= FLAG_NO_PINENTRY;
635 #endif
637 pthread_cleanup_push (req_cleanup, req);
638 filename = req[0];
639 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
640 /* This client may have locked a different file with ISCACHED --lock than
641 * the current filename. This will remove that lock. */
642 same_file = !memcmp (md5file, client->md5file, 16) ? 1 : 0;
643 if (client->flags & FLAG_OPEN ||
644 (client->flags & FLAG_HAS_LOCK && !same_file))
646 typeof (client->opts) opts = client->opts;
647 typeof (client->flags) flags = client->flags;
649 if (same_file)
650 client->flags |= FLAG_KEEP_LOCK;
652 cleanup_client (client);
653 client->opts = opts;
654 client->flags |= flags;
655 client->flags &= ~(FLAG_LOCK_CMD | FLAG_NEW);
656 if (!same_file)
657 client->flags &= ~(FLAG_HAS_LOCK);
660 /* Need to lock the mutex here because file_modified() cannot without
661 * knowing the filename. */
662 memcpy (client->md5file, md5file, 16);
663 rc = lock_file_mutex (client, 1);
664 if (!rc)
666 password = req[1] && *req[1] ? req[1] : NULL;
667 #ifdef WITH_AGENT
668 if (IS_PKI (client->crypto))
669 rc = set_pinentry_mode (client->crypto->agent,
670 (client->flags & FLAG_NO_PINENTRY) ? "loopback"
671 : "ask");
672 #endif
673 if (!rc)
675 rc = do_open (ctx, filename, password);
676 if (rc)
677 cleanup_client (client);
679 cleanup_crypto_stage1 (client->crypto);
683 pthread_cleanup_pop (1);
685 if (!rc && client->flags & FLAG_NEW)
686 rc = send_status (ctx, STATUS_NEWFILE, NULL);
688 #ifdef WITH_AGENT
689 (void) kill_scd (client->crypto->agent);
690 #endif
691 return send_error (ctx, rc);
694 static gpg_error_t
695 parse_save_opt_no_passphrase (void *data, void *value)
697 struct client_s *client = data;
699 (void) value;
700 client->opts |= OPT_NO_PASSPHRASE;
701 return 0;
704 static gpg_error_t
705 parse_save_opt_no_agent (void *data, void *value)
707 struct client_s *client = data;
709 client->opts |= OPT_NO_AGENT;
710 return 0;
713 static gpg_error_t
714 parse_save_opt_cipher (void *data, void *value)
716 struct client_s *client = data;
717 int algo = cipher_string_to_gcrypt ((char *) value);
718 file_header_t *hdr = &client->crypto->save.hdr;
720 if (algo == -1)
721 return GPG_ERR_INV_VALUE;
723 hdr->flags = set_cipher_flag (hdr->flags, algo);
724 return 0;
727 static gpg_error_t
728 parse_save_opt_keygrip (void *data, void *value)
730 struct client_s *client = data;
732 if (!IS_PKI (client->crypto))
733 return GPG_ERR_INV_ARG;
735 #ifdef WITH_AGENT
736 if (client->crypto->save.pkey)
737 gcry_sexp_release (client->crypto->save.pkey);
739 client->crypto->save.pkey = NULL;
740 return get_pubkey (client->crypto, value, &client->crypto->save.pkey);
741 #else
742 return GPG_ERR_INV_ARG;
743 #endif
746 static gpg_error_t
747 parse_save_opt_sign_keygrip (void *data, void *value)
749 struct client_s *client = data;
751 if (!IS_PKI (client->crypto))
752 return GPG_ERR_INV_ARG;
754 #ifdef WITH_AGENT
755 if (client->crypto->save.sigpkey)
756 gcry_sexp_release (client->crypto->save.sigpkey);
758 client->crypto->save.sigpkey = NULL;
759 return get_pubkey (client->crypto, value, &client->crypto->save.sigpkey);
760 #else
761 return GPG_ERR_INV_ARG;
762 #endif
765 static gpg_error_t
766 parse_opt_s2k_count (void *data, void *value)
768 struct client_s *client = data;
769 char *v = value;
771 if (!v || !*v)
772 return GPG_ERR_INV_VALUE;
774 client->crypto->save.s2k_count = strtoul (v, NULL, 10);
775 return 0;
778 static gpg_error_t
779 parse_save_opt_iterations (void *data, void *value)
781 struct client_s *client = data;
782 char *v = value, *p;
783 uint64_t n;
785 if (!v || !*v)
786 return GPG_ERR_INV_VALUE;
788 errno = 0;
789 n = strtoull (v, &p, 10);
790 if (n == UINT64_MAX && errno)
791 return gpg_error_from_syserror ();
792 else if (p && *p)
793 return GPG_ERR_INV_VALUE;
795 client->crypto->save.hdr.iterations = n;
796 return 0;
799 static gpg_error_t
800 save_finalize (assuan_context_t ctx)
802 struct client_s *client = assuan_get_pointer (ctx);
803 gpg_error_t rc = 0;
804 xmlChar *xmlbuf = NULL;
805 int xmlbuflen;
806 void *key = NULL;
807 size_t keylen = 0;
809 xmlDocDumpFormatMemory (client->doc, &xmlbuf, &xmlbuflen, 0);
810 if (!xmlbuf)
811 return GPG_ERR_ENOMEM;
813 pthread_cleanup_push (xmlFree, xmlbuf);
815 if (!use_agent || ((client->flags & FLAG_NEW)
816 && (client->opts & OPT_NO_AGENT))
817 || !(client->crypto->hdr.flags & PWMD_FLAG_PKI))
819 rc = export_common (ctx, client->flags & FLAG_NO_PINENTRY,
820 client->crypto, xmlbuf, xmlbuflen, client->filename,
821 NULL, &key, &keylen, 1, 1);
823 #ifdef WITH_AGENT
824 else
826 gcry_sexp_t pubkey = client->crypto->save.pkey;
827 gcry_sexp_t sigkey = client->crypto->save.sigpkey;
829 if (!pubkey)
830 pubkey = client->crypto->pkey_sexp;
832 if (!sigkey)
834 sigkey = client->crypto->sigpkey_sexp;
835 if (!sigkey)
837 gcry_sexp_build (&client->crypto->save.sigpkey, 0, "%S", pubkey);
838 sigkey = client->crypto->save.sigpkey;
842 rc = encrypt_data_file (client->ctx, client->crypto, pubkey, sigkey,
843 client->filename, xmlbuf, xmlbuflen);
844 if (pubkey == client->crypto->save.pkey)
846 if (!rc)
848 gcry_sexp_release (client->crypto->pkey_sexp);
849 client->crypto->pkey_sexp = client->crypto->save.pkey;
850 gcry_pk_get_keygrip (client->crypto->pkey_sexp,
851 client->crypto->grip);
853 else
854 gcry_sexp_release (pubkey);
856 client->crypto->save.pkey = NULL;
859 if (!rc)
860 gcry_pk_get_keygrip (sigkey, client->crypto->sign_grip);
862 if (sigkey == client->crypto->save.sigpkey)
864 if (!rc)
866 if (client->crypto->sigpkey_sexp)
867 gcry_sexp_release (client->crypto->sigpkey_sexp);
869 client->crypto->sigpkey_sexp = client->crypto->save.sigpkey;
870 gcry_pk_get_keygrip (client->crypto->sigpkey_sexp,
871 client->crypto->sign_grip);
873 else
874 gcry_sexp_release (sigkey);
876 client->crypto->save.sigpkey = NULL;
879 #endif
881 if (!rc)
883 int cached;
885 rc = save_common (client->filename, client->crypto, xmlbuf, xmlbuflen,
886 key, keylen, &cached, client->opts & OPT_NO_AGENT);
887 if (rc)
888 gcry_free (key);
890 if (!rc && (!cached || (client->flags & FLAG_NEW)))
891 send_status_all (STATUS_CACHE, NULL);
893 if (!rc)
895 update_checksum (client);
896 client->flags &= ~(FLAG_NEW);
898 else
899 rc = GPG_ERR_ENOMEM;
902 pthread_cleanup_pop (1); // xmlFree
903 return rc;
906 static gpg_error_t
907 parse_opt_reset (void *data, void *value)
909 struct client_s *client = data;
911 (void) value;
912 client->opts |= OPT_RESET;
913 return 0;
916 static gpg_error_t
917 save_command (assuan_context_t ctx, char *line)
919 struct client_s *client = assuan_get_pointer (ctx);
920 gpg_error_t rc;
921 struct stat st;
922 struct argv_s *args[] = {
923 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG,
924 parse_save_opt_no_passphrase},
925 &(struct argv_s) {"cipher", OPTION_TYPE_ARG, parse_save_opt_cipher},
926 &(struct argv_s) {"inquire-keyparam", OPTION_TYPE_NOARG,
927 parse_opt_inquire},
928 &(struct argv_s) {"keygrip", OPTION_TYPE_ARG, parse_save_opt_keygrip},
929 &(struct argv_s) {"sign-keygrip", OPTION_TYPE_ARG,
930 parse_save_opt_sign_keygrip},
931 &(struct argv_s) {"s2k-count", OPTION_TYPE_ARG, parse_opt_s2k_count},
932 &(struct argv_s) {"reset", OPTION_TYPE_NOARG, parse_opt_reset},
933 &(struct argv_s) {"cipher-iterations", OPTION_TYPE_ARG,
934 parse_save_opt_iterations},
935 &(struct argv_s) {"no-agent", OPTION_TYPE_NOARG,
936 parse_save_opt_no_agent},
937 NULL
940 cleanup_save (&client->crypto->save);
941 memcpy (&client->crypto->save.hdr, &client->crypto->hdr,
942 sizeof (file_header_t));
943 client->crypto->save.s2k_count =
944 config_get_ulong (client->filename, "s2k_count");
946 if (client->flags & FLAG_NEW)
947 client->crypto->save.hdr.iterations =
948 config_get_ulonglong (client->filename, "cipher_iterations");
950 rc = parse_options (&line, args, client);
951 if (rc)
952 return send_error (ctx, rc);
954 if (!(client->flags & FLAG_NEW))
955 client->opts &= ~OPT_NO_AGENT;
956 else if (client->opts & OPT_NO_AGENT)
958 client->crypto->save.hdr.flags &= ~PWMD_FLAG_PKI;
959 client->crypto->hdr.flags &= ~PWMD_FLAG_PKI;
962 if ((client->opts & OPT_NO_PASSPHRASE) && !(client->flags & FLAG_NEW)
963 && !(client->opts & OPT_INQUIRE))
964 return send_error (ctx, GPG_ERR_WRONG_KEY_USAGE);
966 if (lstat (client->filename, &st) == -1 && errno != ENOENT)
967 return send_error (ctx, gpg_error_from_syserror ());
969 if (errno != ENOENT && !S_ISREG (st.st_mode))
971 log_write ("%s: %s", client->filename, pwmd_strerror (GPG_ERR_ENOANO));
972 return send_error (ctx, GPG_ERR_ENOANO);
975 int defer;
976 rc = cache_iscached (client->filename, &defer);
977 if (!rc && defer)
979 log_write ("%s: %s", client->filename,
980 pwmd_strerror (GPG_ERR_KEY_EXPIRED));
981 client->opts |= OPT_RESET;
984 if (client->opts & OPT_RESET)
986 rc = cache_clear (client->md5file);
987 if (rc)
988 return send_error (ctx, rc);
990 send_status_all (STATUS_CACHE, NULL);
993 rc = update_element_mtime (xmlDocGetRootElement (client->doc));
994 if (rc)
995 return send_error (ctx, rc);
997 #ifdef WITH_AGENT
998 if (!rc && use_agent && !client->crypto->save.pkey &&
999 (client->flags & FLAG_NEW || client->opts & OPT_INQUIRE)
1000 && !(client->opts & OPT_NO_AGENT))
1002 rc = set_pinentry_mode (client->crypto->agent,
1003 (client->flags & FLAG_NO_PINENTRY) ? "loopback"
1004 : "ask");
1006 if (!(client->flags & FLAG_NEW))
1008 struct crypto_s *crypto;
1009 char *key = NULL;
1010 size_t keylen = 0;
1012 /* Wanting to generate a new key. Require the key to open the
1013 current file before proceeding. */
1014 rc = cache_clear (client->md5file);
1015 if (!rc)
1017 rc = init_client_crypto (&crypto);
1018 if (!rc)
1019 crypto->client_ctx = client->ctx;
1022 if (!rc)
1023 rc = decrypt_common (client->ctx, client->opts&OPT_INQUIRE, crypto,
1024 client->filename, &key, &keylen);
1026 xfree (key);
1027 cleanup_crypto (&crypto);
1030 if (!rc)
1031 rc = send_status (client->ctx, STATUS_GENKEY, NULL);
1033 if (!rc)
1035 struct inquire_data_s idata = { 0 };
1036 char *params = client->opts & OPT_INQUIRE ? NULL
1037 : default_key_params (client->crypto);
1039 pthread_cleanup_push (xfree, params);
1040 idata.crypto = client->crypto;
1042 if (params)
1044 idata.line = params;
1045 idata.len = strlen (params);
1047 else
1048 idata.preset = 1;
1050 client->crypto->agent->inquire_data = &idata;
1051 client->crypto->agent->inquire_cb = NULL;
1052 rc = generate_key (client->crypto, params,
1053 (client->opts & OPT_NO_PASSPHRASE), 1);
1054 pthread_cleanup_pop (1);
1057 #endif
1059 if (!rc)
1060 rc = save_finalize (ctx);
1062 cleanup_crypto_stage1 (client->crypto);
1063 #ifdef WITH_AGENT
1064 (void) kill_scd (client->crypto->agent);
1065 #endif
1066 return send_error (ctx, rc);
1069 static gpg_error_t
1070 do_delete (assuan_context_t ctx, char *line)
1072 struct client_s *client = assuan_get_pointer (ctx);
1073 gpg_error_t rc;
1074 char **req;
1075 xmlNodePtr n;
1077 if (strchr (line, '\t'))
1078 req = str_split (line, "\t", 0);
1079 else
1080 req = str_split (line, " ", 0);
1082 if (!req || !*req)
1083 return GPG_ERR_SYNTAX;
1085 n = find_root_element (client->doc, &req, &rc, NULL, 0, 0);
1086 if (!n)
1088 strv_free (req);
1089 return rc;
1093 * No sub-node defined. Remove the entire node (root element).
1095 if (!req[1])
1097 if (n)
1099 rc = unlink_node (n);
1100 xmlFreeNode (n);
1103 strv_free (req);
1104 return rc;
1108 find_elements (client->doc, n->children, req + 1, &rc, NULL, NULL, NULL,
1109 0, 0, NULL, 0);
1110 strv_free (req);
1111 if (!n)
1112 return rc;
1114 if (n)
1116 rc = unlink_node (n);
1117 xmlFreeNode (n);
1120 return rc;
1123 static gpg_error_t
1124 delete_command (assuan_context_t ctx, char *line)
1126 struct client_s *client = assuan_get_pointer (ctx);
1127 gpg_error_t rc;
1128 struct argv_s *args[] = {
1129 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1130 NULL
1133 rc = parse_options (&line, args, client);
1134 if (rc)
1135 return send_error (ctx, rc);
1137 if (client->opts & OPT_INQUIRE)
1139 unsigned char *result;
1140 size_t len;
1142 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1143 if (rc)
1144 return send_error (ctx, rc);
1146 line = (char *) result;
1149 rc = do_delete (ctx, line);
1151 if (client->opts & OPT_INQUIRE)
1152 xfree (line);
1154 return send_error (ctx, rc);
1157 static gpg_error_t
1158 store_command (assuan_context_t ctx, char *line)
1160 struct client_s *client = assuan_get_pointer (ctx);
1161 gpg_error_t rc;
1162 size_t len;
1163 unsigned char *result;
1164 char **req;
1165 xmlNodePtr n, parent;
1166 int has_content;
1167 char *content = NULL;
1169 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1170 if (rc)
1171 return send_error (ctx, rc);
1173 req = str_split ((char *) result, "\t", 0);
1174 xfree (result);
1176 if (!req || !*req)
1177 return send_error (ctx, GPG_ERR_SYNTAX);
1179 len = strv_length (req);
1180 has_content = line[strlen (line) - 1] != '\t' && len > 1;
1181 if (*(req + 1) && !valid_element_path (req, has_content))
1183 strv_free (req);
1184 return send_error (ctx, GPG_ERR_INV_VALUE);
1187 if (has_content || !*req[len - 1])
1189 has_content = 1;
1190 content = req[len - 1];
1191 req[len - 1] = NULL;
1194 again:
1195 n = find_root_element (client->doc, &req, &rc, NULL, 0, 0);
1196 if (rc && rc == GPG_ERR_ELEMENT_NOT_FOUND)
1198 rc = new_root_element (client->doc, *req);
1199 if (rc)
1201 strv_free (req);
1202 return send_error (ctx, GPG_ERR_SYNTAX);
1205 goto again;
1208 if (!n)
1210 strv_free (req);
1211 return send_error (ctx, rc);
1214 parent = n;
1216 if (req[1] && *req[1])
1218 if (!n->children)
1219 parent = create_elements_cb (n, req + 1, &rc, NULL);
1220 else
1221 parent = find_elements (client->doc, n->children, req + 1, &rc,
1222 NULL, NULL, create_elements_cb, 0, 0, NULL,
1226 if (!rc && len > 1)
1228 n = find_text_node (parent->children);
1229 if (n)
1230 xmlNodeSetContent (n, (xmlChar *) content);
1231 else
1232 xmlNodeAddContent (parent, (xmlChar *) content);
1234 update_element_mtime (parent);
1237 xfree (content);
1238 strv_free (req);
1239 return send_error (ctx, rc);
1242 static gpg_error_t
1243 xfer_data (assuan_context_t ctx, const char *line, int total)
1245 int to_send;
1246 int sent = 0;
1247 gpg_error_t rc;
1248 int progress = config_get_integer ("global", "xfer_progress");
1249 int flush = 0;
1251 progress =
1252 progress > 0 ? (progress / ASSUAN_LINELENGTH) * ASSUAN_LINELENGTH : 0;
1253 to_send = total < ASSUAN_LINELENGTH ? total : ASSUAN_LINELENGTH;
1254 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1256 if (rc)
1257 return rc;
1259 again:
1262 if (sent + to_send > total)
1263 to_send = total - sent;
1265 rc = assuan_send_data (ctx, flush ? NULL : (char *) line + sent,
1266 flush ? 0 : to_send);
1267 if (!rc)
1269 sent += flush ? 0 : to_send;
1271 if ((progress && !(sent % progress) && sent != total) ||
1272 (sent == total && flush))
1273 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1275 if (!flush && !rc && sent == total)
1277 flush = 1;
1278 goto again;
1282 while (!rc && sent < total);
1284 return rc;
1287 static gpg_error_t
1288 do_get (assuan_context_t ctx, char *line)
1290 struct client_s *client = assuan_get_pointer (ctx);
1291 gpg_error_t rc;
1292 char **req;
1293 xmlNodePtr n;
1295 req = str_split (line, "\t", 0);
1297 if (!req || !*req)
1299 strv_free (req);
1300 return GPG_ERR_SYNTAX;
1303 n = find_root_element (client->doc, &req, &rc, NULL, 0, 0);
1304 if (!n)
1306 strv_free (req);
1307 return rc;
1310 if (req[1])
1312 find_elements (client->doc, n->children, req + 1, &rc, NULL, NULL, NULL,
1313 0, 0, NULL, 0);
1315 strv_free (req);
1316 if (rc)
1317 return rc;
1319 if (!n || !n->children)
1320 return GPG_ERR_NO_DATA;
1322 n = find_text_node (n->children);
1323 if (!n || !n->content || !*n->content)
1324 return GPG_ERR_NO_DATA;
1326 rc = xfer_data (ctx, (char *) n->content, xmlStrlen (n->content));
1327 return rc;
1330 static gpg_error_t
1331 get_command (assuan_context_t ctx, char *line)
1333 struct client_s *client = assuan_get_pointer (ctx);
1334 gpg_error_t rc;
1335 struct argv_s *args[] = {
1336 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1337 NULL
1340 rc = parse_options (&line, args, client);
1341 if (rc)
1342 return send_error (ctx, rc);
1344 if (client->opts & OPT_INQUIRE)
1346 unsigned char *result;
1347 size_t len;
1349 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1350 if (rc)
1351 return send_error (ctx, rc);
1353 line = (char *) result;
1356 rc = do_get (ctx, line);
1358 if (client->opts & OPT_INQUIRE)
1359 xfree (line);
1361 return send_error (ctx, rc);
1364 static void list_command_cleanup1 (void *arg);
1365 static gpg_error_t
1366 realpath_command (assuan_context_t ctx, char *line)
1368 struct string_s *string = NULL;
1369 gpg_error_t rc;
1370 struct client_s *client = assuan_get_pointer (ctx);
1371 struct argv_s *args[] = {
1372 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1373 NULL
1376 rc = parse_options (&line, args, client);
1377 if (rc)
1378 return send_error (ctx, rc);
1380 if (client->opts & OPT_INQUIRE)
1382 unsigned char *result;
1383 size_t len;
1385 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1386 if (rc)
1387 return send_error (ctx, rc);
1389 line = (char *) result;
1392 rc = build_realpath (client->doc, line, &string);
1393 if (!rc)
1395 pthread_cleanup_push (list_command_cleanup1, string);
1396 rc = xfer_data (ctx, string->str, string->len);
1397 pthread_cleanup_pop (1);
1400 if (client->opts & OPT_INQUIRE)
1401 xfree (line);
1403 return send_error (ctx, rc);
1406 static void
1407 list_command_cleanup1 (void *arg)
1409 if (arg)
1410 string_free ((struct string_s *) arg, 1);
1413 static void
1414 list_command_cleanup2 (void *arg)
1416 struct element_list_s *elements = arg;
1418 if (elements)
1420 if (elements->list)
1422 int total = slist_length (elements->list);
1423 int i;
1425 for (i = 0; i < total; i++)
1427 char *tmp = slist_nth_data (elements->list, i);
1428 xfree (tmp);
1431 slist_free (elements->list);
1434 if (elements->prefix)
1435 xfree (elements->prefix);
1437 if (elements->req)
1438 strv_free (elements->req);
1440 xfree (elements);
1444 static gpg_error_t
1445 parse_list_opt_norecurse (void *data, void *value)
1447 struct client_s *client = data;
1449 client->opts &= ~(OPT_LIST_RECURSE);
1450 return 0;
1453 static gpg_error_t
1454 parse_list_opt_verbose (void *data, void *value)
1456 struct client_s *client = data;
1458 client->opts |= OPT_LIST_VERBOSE;
1459 return 0;
1462 static gpg_error_t
1463 parse_list_opt_target (void *data, void *value)
1465 struct client_s *client = data;
1467 client->opts |= OPT_LIST_WITH_TARGET;
1468 return 0;
1471 static gpg_error_t
1472 parse_list_opt_all (void *data, void *value)
1474 struct client_s *client = data;
1476 client->opts |= OPT_LIST_ALL;
1477 return 0;
1480 static gpg_error_t
1481 list_path_once (struct client_s *client, char *line,
1482 struct element_list_s *elements, struct string_s *result)
1484 gpg_error_t rc;
1486 elements->req = str_split (line, " ", 0);
1487 if (!elements->req)
1488 strv_printf (&elements->req, "%s", line);
1490 rc = create_path_list (client->doc, elements, *elements->req);
1491 if (rc == GPG_ERR_ELOOP && elements->verbose)
1492 rc = 0;
1494 if (!rc)
1496 int total = slist_length (elements->list);
1497 int i;
1499 if (!total)
1500 rc = GPG_ERR_NO_DATA;
1502 if (!rc)
1504 if (!rc)
1506 for (i = 0; i < total; i++)
1508 char *tmp = slist_nth_data (elements->list, i);
1510 string_append_printf (result, "%s%s", tmp,
1511 i + 1 == total ? "" : "\n");
1515 else
1516 rc = GPG_ERR_NO_DATA;
1519 return rc;
1522 static int
1523 has_list_flag (char *path, char *flags)
1525 char *p = path;
1527 while (*p && *++p != ' ');
1529 if (!*p)
1530 return 0;
1532 for (; *p; p++)
1534 char *f;
1536 for (f = flags; *f && *f != ' '; f++)
1538 if (*p == *f)
1539 return 1;
1543 return 0;
1546 static gpg_error_t
1547 do_list (assuan_context_t ctx, char *line)
1549 struct client_s *client = assuan_get_pointer (ctx);
1550 gpg_error_t rc;
1551 struct element_list_s *elements = NULL;
1553 elements = xcalloc (1, sizeof (struct element_list_s));
1554 if (!elements)
1555 return GPG_ERR_ENOMEM;
1557 elements->recurse = client->opts & OPT_LIST_RECURSE;
1558 elements->verbose =
1559 (client->opts & OPT_LIST_VERBOSE) | (client->opts & OPT_LIST_WITH_TARGET);
1560 elements->with_target = client->opts & OPT_LIST_WITH_TARGET;
1562 if (!line || !*line)
1564 struct string_s *str = NULL;
1566 pthread_cleanup_push (list_command_cleanup2, elements);
1567 rc = list_root_elements (client->doc, &str, elements->verbose,
1568 elements->with_target);
1569 pthread_cleanup_pop (1);
1570 pthread_cleanup_push (list_command_cleanup1, str);
1572 if (!rc)
1574 if (client->opts & OPT_LIST_ALL)
1576 char **roots = str_split (str->str, "\n", 0);
1577 char **p;
1579 pthread_cleanup_push (req_cleanup, roots);
1580 string_truncate (str, 0);
1582 for (p = roots; *p; p++)
1584 if (strchr (*p, ' '))
1586 if (has_list_flag (*p, "EO"))
1588 string_append_printf (str, "%s%s", *p,
1589 *(p + 1) ? "\n" : "");
1590 continue;
1594 elements = xcalloc (1, sizeof (struct element_list_s));
1595 if (!elements)
1597 rc = GPG_ERR_ENOMEM;
1598 break;
1601 elements->recurse = client->opts & OPT_LIST_RECURSE;
1602 elements->verbose =
1603 (client->opts & OPT_LIST_VERBOSE) | (client->opts &
1604 OPT_LIST_WITH_TARGET);
1605 elements->with_target = client->opts & OPT_LIST_WITH_TARGET;
1606 pthread_cleanup_push (list_command_cleanup2, elements);
1607 rc = list_path_once (client, *p, elements, str);
1608 pthread_cleanup_pop (1);
1609 if (rc)
1610 break;
1612 if (*(p + 1))
1613 string_append (str, "\n");
1616 pthread_cleanup_pop (1);
1619 if (!rc)
1620 rc = xfer_data (ctx, str->str, str->len);
1623 pthread_cleanup_pop (1);
1624 return rc;
1627 pthread_cleanup_push (list_command_cleanup2, elements);
1628 struct string_s *str = string_new (NULL);
1629 pthread_cleanup_push (list_command_cleanup1, str);
1630 rc = list_path_once (client, line, elements, str);
1631 if (!rc)
1632 rc = xfer_data (ctx, str->str, str->len);
1634 pthread_cleanup_pop (1);
1635 pthread_cleanup_pop (1);
1636 return rc;
1639 static gpg_error_t
1640 list_command (assuan_context_t ctx, char *line)
1642 struct client_s *client = assuan_get_pointer (ctx);
1643 gpg_error_t rc;
1644 struct argv_s *args[] = {
1645 &(struct argv_s) {"no-recurse", OPTION_TYPE_NOARG,
1646 parse_list_opt_norecurse},
1647 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_list_opt_verbose},
1648 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1649 &(struct argv_s) {"with-target", OPTION_TYPE_NOARG,
1650 parse_list_opt_target},
1651 &(struct argv_s) {"all", OPTION_TYPE_NOARG, parse_list_opt_all},
1652 NULL
1655 if (disable_list_and_dump == 1)
1656 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
1658 client->opts |= OPT_LIST_RECURSE;
1659 rc = parse_options (&line, args, client);
1660 if (rc)
1661 return send_error (ctx, rc);
1663 if (client->opts & OPT_LIST_ALL)
1664 client->opts |= OPT_LIST_RECURSE | OPT_LIST_VERBOSE;
1666 if (client->opts & OPT_INQUIRE)
1668 unsigned char *result;
1669 size_t len;
1671 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1672 if (rc)
1673 return send_error (ctx, rc);
1675 line = (char *) result;
1678 rc = do_list (ctx, line);
1680 if (client->opts & OPT_INQUIRE)
1681 xfree (line);
1683 return send_error (ctx, rc);
1687 * req[0] - element path
1689 static gpg_error_t
1690 attribute_list (assuan_context_t ctx, char **req)
1692 struct client_s *client = assuan_get_pointer (ctx);
1693 char **attrlist = NULL;
1694 int i = 0;
1695 char **path = NULL;
1696 xmlAttrPtr a;
1697 xmlNodePtr n, an;
1698 char *line;
1699 gpg_error_t rc;
1701 if (!req || !req[0])
1702 return GPG_ERR_SYNTAX;
1704 if ((path = str_split (req[0], "\t", 0)) == NULL)
1707 * The first argument may be only a root element.
1709 if ((path = str_split (req[0], " ", 0)) == NULL)
1710 return GPG_ERR_SYNTAX;
1713 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
1715 if (!n)
1717 strv_free (path);
1718 return rc;
1721 if (path[1])
1723 n = find_elements (client->doc, n->children, path + 1, &rc,
1724 NULL, NULL, NULL, 0, 0, NULL, 0);
1726 if (!n)
1728 strv_free (path);
1729 return rc;
1733 strv_free (path);
1735 for (a = n->properties; a; a = a->next)
1737 char **pa;
1739 if ((pa = xrealloc (attrlist, (i + 2) * sizeof (char *))) == NULL)
1741 if (attrlist)
1742 strv_free (attrlist);
1744 log_write ("%s(%i): %s", __FILE__, __LINE__,
1745 pwmd_strerror (GPG_ERR_ENOMEM));
1746 return GPG_ERR_ENOMEM;
1749 attrlist = pa;
1750 an = a->children;
1751 attrlist[i] = str_asprintf ("%s %s", (char *) a->name,
1753 && an->content ? (char *) an->content : "");
1755 if (!attrlist[i])
1757 strv_free (attrlist);
1758 log_write ("%s(%i): %s", __FILE__, __LINE__,
1759 pwmd_strerror (GPG_ERR_ENOMEM));
1760 return GPG_ERR_ENOMEM;
1763 attrlist[++i] = NULL;
1766 if (!attrlist)
1767 return GPG_ERR_NO_DATA;
1769 line = strv_join ("\n", attrlist);
1771 if (!line)
1773 log_write ("%s(%i): %s", __FILE__, __LINE__,
1774 pwmd_strerror (GPG_ERR_ENOMEM));
1775 strv_free (attrlist);
1776 return GPG_ERR_ENOMEM;
1779 pthread_cleanup_push (xfree, line);
1780 pthread_cleanup_push (req_cleanup, attrlist);
1781 rc = xfer_data (ctx, line, strlen (line));
1782 pthread_cleanup_pop (1);
1783 pthread_cleanup_pop (1);
1784 return rc;
1788 * req[0] - attribute
1789 * req[1] - element path
1791 static gpg_error_t
1792 attribute_delete (struct client_s *client, char **req)
1794 xmlNodePtr n;
1795 char **path = NULL;
1796 gpg_error_t rc;
1798 if (!req || !req[0] || !req[1])
1799 return GPG_ERR_SYNTAX;
1801 if (!strcmp (req[0], "_name"))
1802 return GPG_ERR_INV_ATTR;
1804 if ((path = str_split (req[1], "\t", 0)) == NULL)
1807 * The first argument may be only a root element.
1809 if ((path = str_split (req[1], " ", 0)) == NULL)
1810 return GPG_ERR_SYNTAX;
1813 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
1814 if (!n)
1815 goto fail;
1817 if (path[1])
1819 n = find_elements (client->doc, n->children, path + 1, &rc,
1820 NULL, NULL, NULL, 0, 0, NULL, 0);
1821 if (!n)
1822 goto fail;
1825 rc = delete_attribute (n, (xmlChar *) req[0]);
1827 fail:
1828 strv_free (path);
1829 return rc;
1832 static xmlNodePtr
1833 create_element_path (struct client_s *client,
1834 char ***elements, gpg_error_t * rc, xmlNodePtr parent)
1836 char **req = *elements;
1837 char **req_orig = strv_dup (req);
1838 xmlNodePtr n = NULL;
1840 *rc = 0;
1842 if (!req_orig)
1844 *rc = GPG_ERR_ENOMEM;
1845 log_write ("%s(%i): %s", __FILE__, __LINE__,
1846 pwmd_strerror (GPG_ERR_ENOMEM));
1847 goto fail;
1850 again:
1851 n = find_root_element (client->doc, &req, rc, NULL, 0, 0);
1852 if (!n)
1854 if (*rc != GPG_ERR_ELEMENT_NOT_FOUND)
1855 goto fail;
1857 *rc = new_root_element (client->doc, req[0]);
1858 if (*rc)
1859 goto fail;
1861 goto again;
1863 else if (n == parent)
1865 *rc = GPG_ERR_CONFLICT;
1866 goto fail;
1869 if (req[1])
1871 if (!n->children)
1872 n = create_target_elements_cb (n, req + 1, rc, NULL);
1873 else
1874 n = find_elements (client->doc, n->children, req + 1, rc, NULL, NULL,
1875 create_target_elements_cb, 0, 0, parent, 0);
1877 if (!n)
1878 goto fail;
1881 * Reset the position of the element tree now that the elements
1882 * have been created.
1884 strv_free (req);
1885 req = req_orig;
1886 req_orig = NULL;
1887 n = find_root_element (client->doc, &req, rc, NULL, 0, 0);
1888 if (!n)
1889 goto fail;
1891 n = find_elements (client->doc, n->children, req + 1, rc,
1892 NULL, NULL, NULL, 0, 0, NULL, 0);
1893 if (!n)
1894 goto fail;
1897 fail:
1898 if (req_orig)
1899 strv_free (req_orig);
1901 *elements = req;
1902 return n;
1906 * Creates a "target" attribute. When other commands encounter an element with
1907 * this attribute, the element path is modified to the target value. If the
1908 * source element path doesn't exist when using 'ATTR SET target', it is
1909 * created, but the destination element path must exist.
1911 * req[0] - source element path
1912 * req[1] - destination element path
1914 static gpg_error_t
1915 target_attribute (struct client_s *client, char **req)
1917 char **src, **dst, *line = NULL, **odst = NULL;
1918 gpg_error_t rc;
1919 xmlNodePtr n;
1921 if (!req || !req[0] || !req[1])
1922 return GPG_ERR_SYNTAX;
1924 if ((src = str_split (req[0], "\t", 0)) == NULL)
1927 * The first argument may be only a root element.
1929 if ((src = str_split (req[0], " ", 0)) == NULL)
1930 return GPG_ERR_SYNTAX;
1933 if (!valid_element_path (src, 0))
1934 return GPG_ERR_INV_VALUE;
1936 if ((dst = str_split (req[1], "\t", 0)) == NULL)
1939 * The first argument may be only a root element.
1941 if ((dst = str_split (req[1], " ", 0)) == NULL)
1943 rc = GPG_ERR_SYNTAX;
1944 goto fail;
1948 odst = strv_dup (dst);
1949 if (!odst)
1951 rc = GPG_ERR_ENOMEM;
1952 goto fail;
1955 n = find_root_element (client->doc, &dst, &rc, NULL, 0, 0);
1957 * Make sure the destination element path exists.
1959 if (!n)
1960 goto fail;
1962 if (dst[1])
1964 n = find_elements (client->doc, n->children, dst + 1, &rc,
1965 NULL, NULL, NULL, 0, 0, NULL, 0);
1966 if (!n)
1967 goto fail;
1970 rc = validate_target_attribute (client->doc, req[0], n);
1971 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
1972 goto fail;
1974 n = create_element_path (client, &src, &rc, NULL);
1975 if (rc)
1976 goto fail;
1978 line = strv_join ("\t", odst);
1979 if (!line)
1981 rc = GPG_ERR_ENOMEM;
1982 goto fail;
1985 rc = add_attribute (n, "target", line);
1987 fail:
1988 xfree (line);
1989 strv_free (src);
1990 strv_free (dst);
1991 strv_free (odst);
1992 return rc;
1996 * req[0] - attribute
1997 * req[1] - element path
1999 static gpg_error_t
2000 attribute_get (assuan_context_t ctx, char **req)
2002 struct client_s *client = assuan_get_pointer (ctx);
2003 xmlNodePtr n;
2004 xmlChar *a;
2005 char **path = NULL;
2006 gpg_error_t rc;
2008 if (!req || !req[0] || !req[1])
2009 return GPG_ERR_SYNTAX;
2011 if (strchr (req[1], '\t'))
2013 if ((path = str_split (req[1], "\t", 0)) == NULL)
2014 return GPG_ERR_SYNTAX;
2016 else
2018 if ((path = str_split (req[1], " ", 0)) == NULL)
2019 return GPG_ERR_SYNTAX;
2022 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
2024 if (!n)
2025 goto fail;
2027 if (path[1])
2029 n = find_elements (client->doc, n->children, path + 1, &rc,
2030 NULL, NULL, NULL, 0, 0, NULL, 0);
2032 if (!n)
2033 goto fail;
2036 strv_free (path);
2038 if ((a = xmlGetProp (n, (xmlChar *) req[0])) == NULL)
2039 return GPG_ERR_NOT_FOUND;
2041 pthread_cleanup_push (xmlFree, a);
2043 if (*a)
2044 rc = xfer_data (ctx, (char *) a, xmlStrlen (a));
2045 else
2046 rc = GPG_ERR_NO_DATA;
2048 pthread_cleanup_pop (1);
2049 return rc;
2051 fail:
2052 strv_free (path);
2053 return rc;
2057 * req[0] - attribute
2058 * req[1] - element path
2059 * req[2] - value
2061 static gpg_error_t
2062 attribute_set (struct client_s *client, char **req)
2064 char **path = NULL;
2065 gpg_error_t rc;
2066 xmlNodePtr n;
2068 if (!req || !req[0] || !req[1])
2069 return GPG_ERR_SYNTAX;
2072 * Reserved attribute names.
2074 if (!strcmp (req[0], "_name"))
2075 return GPG_ERR_INV_ATTR;
2076 else if (!strcmp (req[0], "target"))
2077 return target_attribute (client, req + 1);
2079 if ((path = str_split (req[1], "\t", 0)) == NULL)
2082 * The first argument may be only a root element.
2084 if ((path = str_split (req[1], " ", 0)) == NULL)
2085 return GPG_ERR_SYNTAX;
2088 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
2090 if (!n)
2091 goto fail;
2093 if (path[1])
2095 n = find_elements (client->doc, n->children, path + 1, &rc,
2096 NULL, NULL, NULL, 0, 0, NULL, 0);
2098 if (!n)
2099 goto fail;
2102 rc = add_attribute (n, req[0], req[2]);
2104 fail:
2105 strv_free (path);
2106 return rc;
2110 * req[0] - command
2111 * req[1] - attribute name or element path if command is LIST
2112 * req[2] - element path
2113 * req[2] - element path or value
2116 static gpg_error_t
2117 do_attr (assuan_context_t ctx, char *line)
2119 struct client_s *client = assuan_get_pointer (ctx);
2120 gpg_error_t rc = 0;
2121 char **req;
2123 req = str_split (line, " ", 4);
2124 if (!req || !req[0] || !req[1])
2126 strv_free (req);
2127 return GPG_ERR_SYNTAX;
2130 pthread_cleanup_push (req_cleanup, req);
2132 if (strcasecmp (req[0], "SET") == 0)
2133 rc = attribute_set (client, req + 1);
2134 else if (strcasecmp (req[0], "GET") == 0)
2135 rc = attribute_get (ctx, req + 1);
2136 else if (strcasecmp (req[0], "DELETE") == 0)
2137 rc = attribute_delete (client, req + 1);
2138 else if (strcasecmp (req[0], "LIST") == 0)
2139 rc = attribute_list (ctx, req + 1);
2140 else
2141 rc = GPG_ERR_SYNTAX;
2143 pthread_cleanup_pop (1);
2144 return rc;
2147 static gpg_error_t
2148 attr_command (assuan_context_t ctx, char *line)
2150 struct client_s *client = assuan_get_pointer (ctx);
2151 gpg_error_t rc;
2152 struct argv_s *args[] = {
2153 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2154 NULL
2157 rc = parse_options (&line, args, client);
2158 if (rc)
2159 return send_error (ctx, rc);
2161 if (client->opts & OPT_INQUIRE)
2163 unsigned char *result;
2164 size_t len;
2166 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2167 if (rc)
2168 return send_error (ctx, rc);
2170 line = (char *) result;
2173 rc = do_attr (ctx, line);
2175 if (client->opts & OPT_INQUIRE)
2176 xfree (line);
2178 return send_error (ctx, rc);
2181 static gpg_error_t
2182 parse_iscached_opt_lock (void *data, void *value)
2184 struct client_s *client = data;
2186 (void) value;
2187 client->opts |= OPT_LOCK;
2188 return 0;
2191 static gpg_error_t
2192 iscached_command (assuan_context_t ctx, char *line)
2194 struct client_s *client = assuan_get_pointer (ctx);
2195 gpg_error_t rc;
2196 unsigned char md5file[16];
2197 struct argv_s *args[] = {
2198 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_iscached_opt_lock},
2199 NULL
2202 if (!line || !*line)
2203 return send_error (ctx, GPG_ERR_SYNTAX);
2205 rc = parse_options (&line, args, client);
2206 if (rc)
2207 return send_error (ctx, rc);
2208 else if (!valid_filename (line))
2209 return send_error (ctx, GPG_ERR_INV_VALUE);
2211 rc = cache_iscached (line, NULL);
2212 if (client->opts & OPT_LOCK
2213 && (!rc || gpg_err_code (rc) == GPG_ERR_NO_DATA))
2215 gpg_error_t trc = rc;
2216 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2217 if (memcmp (md5file, client->md5file, 16))
2218 cleanup_client (client);
2220 memcpy (client->md5file, md5file, 16);
2221 rc = do_lock (client, 1);
2222 if (!rc)
2223 rc = trc;
2226 return send_error (ctx, rc);
2229 static gpg_error_t
2230 clearcache_command (assuan_context_t ctx, char *line)
2232 gpg_error_t rc = 0, all_rc = 0;
2233 unsigned char md5file[16];
2234 int i;
2235 int t;
2236 int all = 0;
2237 struct client_thread_s *once = NULL;
2239 cache_lock ();
2240 MUTEX_LOCK (&cn_mutex);
2241 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
2243 if (!line || !*line)
2244 all = 1;
2246 t = slist_length (cn_thread_list);
2248 for (i = 0; i < t; i++)
2250 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2252 if (!thd->cl)
2253 continue;
2255 /* Lock each connected clients' file mutex to prevent any other client
2256 * from accessing the cache entry (the file mutex is locked upon
2257 * command startup). The cache for the entry is not cleared if the
2258 * file mutex is locked by another client to prevent this function
2259 * from blocking.
2261 if (all)
2263 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0, -1);
2264 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2266 if (pthread_equal (pthread_self (), thd->tid))
2267 rc = 0;
2268 else
2270 if (!thd->cl->filename ||
2271 cache_iscached (thd->cl->filename,
2272 NULL) == GPG_ERR_NO_DATA)
2274 rc = 0;
2275 continue;
2278 cache_defer_clear (thd->cl->md5file);
2281 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
2283 rc = 0;
2284 continue;
2287 if (!rc)
2289 rc = cache_clear (thd->cl->md5file);
2290 if (rc)
2291 all_rc = rc;
2293 cache_unlock_mutex (thd->cl->md5file, 0);
2295 else
2296 all_rc = rc;
2298 rc = 0;
2300 /* A single data filename was specified. Lock only this data file
2301 * mutex and free the cache entry. */
2302 else
2304 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2306 if (!memcmp (thd->cl->md5file, md5file, sizeof (md5file)))
2308 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0,
2309 -1);
2310 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2312 if (pthread_equal (pthread_self (), thd->tid))
2313 rc = 0;
2316 if (!rc)
2318 once = thd;
2319 rc = cache_clear (thd->cl->md5file);
2320 cache_unlock_mutex (thd->cl->md5file, 0);
2322 else
2324 cache_defer_clear (thd->cl->md5file);
2327 break;
2332 /* Only connected clients' cache entries have been cleared. Now clear any
2333 * remaining cache entries without clients but only if there wasn't an
2334 * error from above since this would defeat the locking check of the
2335 * remaining entries. */
2336 if (!all_rc && all)
2338 cache_clear (NULL);
2341 /* No clients are using the specified file. */
2342 else if (!all_rc && !rc && !once)
2344 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2345 rc = cache_clear (md5file);
2348 /* Release the connection mutex. */
2349 pthread_cleanup_pop (1);
2350 cache_unlock ();
2352 if (!rc)
2353 send_status_all (STATUS_CACHE, NULL);
2355 /* One or more files were locked while clearing all cache entries. */
2356 if (all_rc)
2357 rc = all_rc;
2359 return send_error (ctx, rc);
2362 static gpg_error_t
2363 cachetimeout_command (assuan_context_t ctx, char *line)
2365 unsigned char md5file[16];
2366 int timeout;
2367 char **req = str_split (line, " ", 0);
2368 char *p;
2369 gpg_error_t rc = 0;
2371 if (!req || !*req || !req[1])
2373 strv_free (req);
2374 return send_error (ctx, GPG_ERR_SYNTAX);
2377 errno = 0;
2378 timeout = (int) strtol (req[1], &p, 10);
2379 if (errno != 0 || *p || timeout < -1)
2381 strv_free (req);
2382 return send_error (ctx, GPG_ERR_SYNTAX);
2385 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, req[0], strlen (req[0]));
2386 rc = cache_set_timeout (md5file, timeout);
2387 if (!rc || gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
2389 rc = 0;
2390 MUTEX_LOCK (&rcfile_mutex);
2391 config_set_int_param (&global_config, req[0], "cache_timeout", req[1]);
2392 MUTEX_UNLOCK (&rcfile_mutex);
2395 strv_free (req);
2396 return send_error (ctx, rc);
2399 static gpg_error_t
2400 dump_command (assuan_context_t ctx, char *line)
2402 xmlChar *xml;
2403 int len;
2404 struct client_s *client = assuan_get_pointer (ctx);
2405 gpg_error_t rc;
2407 if (disable_list_and_dump == 1)
2408 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2410 xmlDocDumpFormatMemory (client->doc, &xml, &len, 1);
2412 if (!xml)
2414 log_write ("%s(%i): %s", __FILE__, __LINE__,
2415 pwmd_strerror (GPG_ERR_ENOMEM));
2416 return send_error (ctx, GPG_ERR_ENOMEM);
2419 pthread_cleanup_push (xmlFree, xml);
2420 rc = xfer_data (ctx, (char *) xml, len);
2421 pthread_cleanup_pop (1);
2422 return send_error (ctx, rc);
2425 static gpg_error_t
2426 getconfig_command (assuan_context_t ctx, char *line)
2428 struct client_s *client = assuan_get_pointer (ctx);
2429 gpg_error_t rc = 0;
2430 char filename[255] = { 0 }, param[747] = { 0 };
2431 char *p, *tmp = NULL, *fp = client->filename, *paramp = line;
2433 if (!line || !*line)
2434 return send_error (ctx, GPG_ERR_SYNTAX);
2436 if (strchr (line, ' '))
2438 sscanf (line, " %254[^ ] %746c", filename, param);
2439 paramp = param;
2440 fp = filename;
2443 if (fp && !valid_filename (fp))
2444 return send_error (ctx, GPG_ERR_INV_VALUE);
2446 paramp = str_down (paramp);
2447 if (!strcmp (paramp, "cipher") && fp)
2449 struct crypto_s *crypto = NULL;
2451 rc = init_client_crypto (&crypto);
2452 if (!rc)
2454 rc = read_data_header (fp, &crypto->hdr, NULL, NULL);
2455 if (!rc)
2457 const char *t =
2458 gcry_cipher_algo_name (cipher_to_gcrypt (crypto->hdr.flags));
2459 if (t)
2461 tmp = str_dup (t);
2462 if (tmp)
2463 str_down (tmp);
2468 UPDATE_AGENT_CTX (client, crypto);
2469 cleanup_crypto (&crypto);
2470 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
2471 return send_error (ctx, rc);
2473 if (!rc && tmp)
2474 goto done;
2476 else if (!strcmp (paramp, "cipher_iterations") && fp)
2478 struct crypto_s *crypto = NULL;
2480 rc = init_client_crypto (&crypto);
2481 if (!rc)
2483 rc = read_data_header (fp, &crypto->hdr, NULL, NULL);
2484 if (!rc)
2486 tmp = str_asprintf ("%llu",
2487 (unsigned long long) crypto->hdr.
2488 iterations);
2489 if (!tmp)
2490 rc = GPG_ERR_ENOMEM;
2494 UPDATE_AGENT_CTX (client, crypto);
2495 cleanup_crypto (&crypto);
2496 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
2497 return send_error (ctx, rc);
2499 if (!rc && tmp)
2500 goto done;
2502 else if (!strcmp (paramp, "passphrase"))
2503 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2505 p = config_get_value (fp ? fp : "global", paramp);
2506 if (!p)
2507 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2509 tmp = expand_homedir (p);
2510 xfree (p);
2511 if (!tmp)
2513 log_write ("%s(%i): %s", __FILE__, __LINE__,
2514 pwmd_strerror (GPG_ERR_ENOMEM));
2515 return send_error (ctx, GPG_ERR_ENOMEM);
2518 done:
2519 p = tmp;
2520 pthread_cleanup_push (xfree, p);
2521 rc = xfer_data (ctx, p, strlen (p));
2522 pthread_cleanup_pop (1);
2523 return send_error (ctx, rc);
2526 struct xpath_s
2528 xmlXPathContextPtr xp;
2529 xmlXPathObjectPtr result;
2530 xmlBufferPtr buf;
2531 char **req;
2534 static void
2535 xpath_command_cleanup (void *arg)
2537 struct xpath_s *xpath = arg;
2539 if (!xpath)
2540 return;
2542 req_cleanup (xpath->req);
2544 if (xpath->buf)
2545 xmlBufferFree (xpath->buf);
2547 if (xpath->result)
2548 xmlXPathFreeObject (xpath->result);
2550 if (xpath->xp)
2551 xmlXPathFreeContext (xpath->xp);
2554 static gpg_error_t
2555 do_xpath (assuan_context_t ctx, char *line)
2557 gpg_error_t rc;
2558 struct client_s *client = assuan_get_pointer (ctx);
2559 struct xpath_s _x = { 0 };
2560 struct xpath_s *xpath = &_x;
2562 if ((xpath->req = str_split (line, "\t", 2)) == NULL)
2564 if (strv_printf (&xpath->req, "%s", line) == 0)
2565 return GPG_ERR_ENOMEM;
2568 xpath->xp = xmlXPathNewContext (client->doc);
2569 if (!xpath->xp)
2571 rc = GPG_ERR_BAD_DATA;
2572 goto fail;
2575 xpath->result =
2576 xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2577 if (!xpath->result)
2579 rc = GPG_ERR_BAD_DATA;
2580 goto fail;
2583 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2585 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2586 goto fail;
2589 rc = recurse_xpath_nodeset (client->doc, xpath->result->nodesetval,
2590 (xmlChar *) xpath->req[1], &xpath->buf, 0,
2591 NULL);
2592 if (rc)
2593 goto fail;
2594 else if (!xpath->req[1] && !xmlBufferLength (xpath->buf))
2596 rc = GPG_ERR_NO_DATA;
2597 goto fail;
2599 else if (xpath->req[1])
2601 rc = 0;
2602 goto fail;
2605 pthread_cleanup_push (xpath_command_cleanup, &xpath);
2606 rc = xfer_data (ctx, (char *) xmlBufferContent (xpath->buf),
2607 xmlBufferLength (xpath->buf));
2608 pthread_cleanup_pop (0);
2609 fail:
2610 xpath_command_cleanup (xpath);
2611 return rc;
2614 static gpg_error_t
2615 xpath_command (assuan_context_t ctx, char *line)
2617 struct client_s *client = assuan_get_pointer (ctx);
2618 gpg_error_t rc;
2619 struct argv_s *args[] = {
2620 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2621 NULL
2624 if (disable_list_and_dump == 1)
2625 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2627 rc = parse_options (&line, args, client);
2628 if (rc)
2629 return send_error (ctx, rc);
2631 if (client->opts & OPT_INQUIRE)
2633 unsigned char *result;
2634 size_t len;
2636 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2637 if (rc)
2638 return send_error (ctx, rc);
2640 line = (char *) result;
2643 if (!line || !*line)
2644 rc = GPG_ERR_SYNTAX;
2646 if (!rc)
2647 rc = do_xpath (ctx, line);
2649 if (client->opts & OPT_INQUIRE)
2650 xfree (line);
2652 return send_error (ctx, rc);
2655 static gpg_error_t
2656 do_xpathattr (assuan_context_t ctx, char *line)
2658 struct client_s *client = assuan_get_pointer (ctx);
2659 gpg_error_t rc;
2660 char **req = NULL;
2661 int cmd = 0; //SET
2662 struct xpath_s _x = { 0 };
2663 struct xpath_s *xpath = &_x;
2665 if ((req = str_split (line, " ", 3)) == NULL)
2666 return GPG_ERR_ENOMEM;
2668 if (!req[0])
2670 rc = GPG_ERR_SYNTAX;
2671 goto fail;
2674 if (!strcasecmp (req[0], "SET"))
2675 cmd = 0;
2676 else if (!strcasecmp (req[0], "DELETE"))
2677 cmd = 1;
2678 else
2680 rc = GPG_ERR_SYNTAX;
2681 goto fail;
2684 if (!req[1] || !req[2])
2686 rc = GPG_ERR_SYNTAX;
2687 goto fail;
2690 if ((xpath->req = str_split (req[2], "\t", 3)) == NULL)
2692 rc = GPG_ERR_ENOMEM;
2693 goto fail;
2696 if (!xpath->req[0] || (!xpath->req[1] && !cmd) || (xpath->req[1] && cmd))
2698 rc = GPG_ERR_SYNTAX;
2699 goto fail;
2702 xpath->xp = xmlXPathNewContext (client->doc);
2703 if (!xpath->xp)
2705 rc = GPG_ERR_BAD_DATA;
2706 goto fail;
2709 xpath->result = xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2710 if (!xpath->result)
2712 rc = GPG_ERR_BAD_DATA;
2713 goto fail;
2716 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2718 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2719 goto fail;
2722 rc = recurse_xpath_nodeset (client->doc, xpath->result->nodesetval,
2723 (xmlChar *) xpath->req[1], &xpath->buf, cmd,
2724 (xmlChar *) req[1]);
2726 fail:
2727 xpath_command_cleanup (xpath);
2728 strv_free (req);
2729 return rc;
2732 /* XPATHATTR SET|DELETE <name> <expression>[<TAB>[value]] */
2733 static gpg_error_t
2734 xpathattr_command (assuan_context_t ctx, char *line)
2736 struct client_s *client = assuan_get_pointer (ctx);
2737 gpg_error_t rc;
2738 struct argv_s *args[] = {
2739 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2740 NULL
2743 if (disable_list_and_dump == 1)
2744 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2746 rc = parse_options (&line, args, client);
2747 if (rc)
2748 return send_error (ctx, rc);
2750 if (client->opts & OPT_INQUIRE)
2752 unsigned char *result;
2753 size_t len;
2755 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2756 if (rc)
2757 return send_error (ctx, rc);
2759 line = (char *) result;
2762 if (!line || !*line)
2763 rc = GPG_ERR_SYNTAX;
2765 if (!rc)
2766 rc = do_xpathattr (ctx, line);
2768 if (client->opts & OPT_INQUIRE)
2769 xfree (line);
2771 return send_error (ctx, rc);
2774 static gpg_error_t
2775 do_import (struct client_s *client, const char *root_element,
2776 unsigned char *content)
2778 char **dst_path = NULL;
2779 xmlDocPtr doc = NULL;
2780 xmlNodePtr n, root, copy;
2781 gpg_error_t rc;
2783 if (!content || !*content)
2785 xfree (content);
2786 return GPG_ERR_SYNTAX;
2789 if (root_element)
2790 dst_path = str_split (root_element, "\t", 0);
2792 if (dst_path && !valid_element_path (dst_path, 0))
2794 if (dst_path)
2795 strv_free (dst_path);
2797 return GPG_ERR_INV_VALUE;
2800 struct string_s *str = string_new_content ((char *)content);
2801 str = string_prepend (str, "<pwmd>");
2802 str = string_append (str, "</pwmd>");
2803 doc = xmlReadDoc ((xmlChar *) str->str, NULL, "UTF-8", XML_PARSE_NOBLANKS);
2804 string_free (str, 1);
2805 if (!doc)
2807 rc = GPG_ERR_BAD_DATA;
2808 goto fail;
2811 root = xmlDocGetRootElement (doc);
2812 xmlNodePtr root_orig = root->children;
2813 root = root->children;
2814 rc = validate_import (root);
2815 if (rc)
2816 goto fail;
2820 again:
2821 if (dst_path)
2823 char **path = strv_dup (dst_path);
2824 if (!path)
2826 log_write ("%s(%i): %s", __FILE__, __LINE__,
2827 pwmd_strerror (GPG_ERR_ENOMEM));
2828 rc = GPG_ERR_ENOMEM;
2829 goto fail;
2832 xmlChar *a = xmlGetProp (root, (xmlChar *) "_name");
2833 if (!a)
2835 strv_free (path);
2836 rc = GPG_ERR_ENOMEM;
2837 goto fail;
2840 if (strv_printf (&path, "%s", (char *) a) == 0)
2842 xmlFree (a);
2843 rc = GPG_ERR_ENOMEM;
2844 goto fail;
2847 xmlFree (a);
2848 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
2849 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2851 strv_free (path);
2852 goto fail;
2855 if (!rc)
2857 n = find_elements (client->doc, n->children, path + 1, &rc,
2858 NULL, NULL, NULL, 0, 0, NULL, 1);
2859 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2861 strv_free (path);
2862 goto fail;
2864 else if (!rc)
2866 xmlUnlinkNode (n);
2867 xmlFreeNode (n);
2868 strv_free (path);
2869 path = NULL;
2870 goto again;
2874 if (rc == GPG_ERR_ELEMENT_NOT_FOUND)
2876 n = create_element_path (client, &path, &rc, NULL);
2877 if (rc)
2878 goto fail;
2881 if (root->children)
2883 copy = xmlCopyNodeList (root->children);
2884 n = xmlAddChildList (n, copy);
2885 if (!n)
2886 rc = GPG_ERR_ENOMEM;
2889 strv_free (path);
2891 else
2893 char **path = NULL;
2895 /* Check if the content root element can create a DTD root element. */
2896 if (!xmlStrEqual ((xmlChar *) "element", root->name))
2898 rc = GPG_ERR_SYNTAX;
2899 goto fail;
2902 xmlChar *a;
2904 if ((a = xmlGetProp (root, (xmlChar *) "_name")) == NULL)
2906 rc = GPG_ERR_SYNTAX;
2907 goto fail;
2910 char *tmp = str_dup ((char *) a);
2911 xmlFree (a);
2912 int literal = is_literal_element (&tmp);
2914 if (!valid_xml_element ((xmlChar *) tmp) || literal)
2916 xfree (tmp);
2917 rc = GPG_ERR_INV_VALUE;
2918 goto fail;
2921 if (strv_printf (&path, "%s", tmp) == 0)
2923 xfree (tmp);
2924 rc = GPG_ERR_ENOMEM;
2925 goto fail;
2928 xfree (tmp);
2929 n = find_root_element (client->doc, &path, &rc, NULL, 0, 1);
2930 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2932 rc = GPG_ERR_BAD_DATA;
2933 goto fail;
2936 /* Overwriting the existing tree. */
2937 if (!rc)
2939 xmlUnlinkNode (n);
2940 xmlFreeNodeList (n);
2943 rc = 0;
2944 xmlSetProp (root, (xmlChar *) "_name", (xmlChar *) path[0]);
2945 n = xmlCopyNode (root, 1);
2946 n = xmlAddChildList (xmlDocGetRootElement (client->doc), n);
2947 strv_free (path);
2950 if (n && !rc)
2951 rc = update_element_mtime (n->parent);
2953 for (root = root_orig->next; root; root = root->next)
2955 if (root->type == XML_ELEMENT_NODE)
2956 break;
2959 root_orig = root;
2961 while (root);
2963 fail:
2964 if (doc)
2965 xmlFreeDoc (doc);
2967 if (dst_path)
2968 strv_free (dst_path);
2970 return rc;
2973 static gpg_error_t
2974 parse_import_opt_root (void *data, void *value)
2976 struct client_s *client = data;
2978 client->import_root = str_dup (value);
2979 return client->import_root ? 0 : GPG_ERR_ENOMEM;
2982 static gpg_error_t
2983 import_command (assuan_context_t ctx, char *line)
2985 gpg_error_t rc;
2986 struct client_s *client = assuan_get_pointer (ctx);
2987 unsigned char *result;
2988 size_t len;
2989 struct argv_s *args[] = {
2990 &(struct argv_s) {"root", OPTION_TYPE_ARG, parse_import_opt_root},
2991 NULL
2994 xfree (client->import_root);
2995 client->import_root = NULL;
2996 rc = parse_options (&line, args, client);
2997 if (rc)
2998 return send_error (ctx, rc);
3000 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3001 if (rc)
3002 return send_error (ctx, rc);
3004 rc = do_import (client, client->import_root, result);
3005 xfree (client->import_root);
3006 client->import_root = NULL;
3007 return send_error (ctx, rc);
3010 static gpg_error_t
3011 do_lock (struct client_s *client, int add)
3013 gpg_error_t rc = lock_file_mutex (client, add);
3015 if (!rc)
3016 client->flags |= FLAG_LOCK_CMD;
3018 return rc;
3021 static gpg_error_t
3022 lock_command (assuan_context_t ctx, char *line)
3024 struct client_s *client = assuan_get_pointer (ctx);
3025 gpg_error_t rc = do_lock (client, 0);
3027 return send_error (ctx, rc);
3030 static gpg_error_t
3031 unlock_command (assuan_context_t ctx, char *line)
3033 struct client_s *client = assuan_get_pointer (ctx);
3034 gpg_error_t rc;
3036 rc = unlock_file_mutex (client, 0);
3037 return send_error (ctx, rc);
3040 static gpg_error_t
3041 option_command (assuan_context_t ctx, char *line)
3043 struct client_s *client = assuan_get_pointer (ctx);
3044 gpg_error_t rc = 0;
3045 struct pinentry_option_s *pin_opts = &client->pinentry_opts;
3046 #ifdef WITH_AGENT
3047 struct agent_s *agent = client->crypto->agent;
3048 #endif
3049 char namebuf[255] = { 0 };
3050 char *name = namebuf;
3051 char *value = NULL, *p;
3053 p = strchr (line, '=');
3054 if (!p)
3055 strncpy (namebuf, line, sizeof(namebuf));
3056 else
3058 strncpy (namebuf, line, strlen (line)-strlen (p));
3059 value = p+1;
3062 log_write1 ("OPTION name='%s' value='%s'", name, value);
3064 if (strcasecmp (name, (char *) "log_level") == 0)
3066 long l = 0;
3068 if (value)
3070 l = strtol (value, NULL, 10);
3072 if (l < 0 || l > 2)
3073 return send_error (ctx, GPG_ERR_INV_VALUE);
3076 MUTEX_LOCK (&rcfile_mutex);
3077 config_set_int_param (&global_config, "global", "log_level", value);
3078 MUTEX_UNLOCK (&rcfile_mutex);
3079 goto done;
3081 else if (strcasecmp (name, (char *) "lock-timeout") == 0)
3083 long n = 0;
3084 char *p = NULL;
3086 if (value)
3088 n = strtol (value, &p, 10);
3089 if (p && *p)
3090 return send_error (ctx, GPG_ERR_INV_VALUE);
3093 client->lock_timeout = n;
3094 goto done;
3096 else if (strcasecmp (name, (char *) "NAME") == 0)
3098 char *tmp = pthread_getspecific (thread_name_key);
3100 if (tmp)
3101 xfree (tmp);
3103 if (!value || !*value)
3105 pthread_setspecific (thread_name_key, str_dup (""));
3106 goto done;
3109 pthread_setspecific (thread_name_key, str_dup (value));
3110 goto done;
3112 else if (strcasecmp (name, (char *) "lc-messages") == 0)
3114 xfree (pin_opts->lc_messages);
3115 pin_opts->lc_messages = NULL;
3116 if (value && *value)
3117 pin_opts->lc_messages = str_dup (value);
3118 #ifdef WITH_AGENT
3119 if (use_agent)
3120 rc = set_agent_option (client->crypto->agent, "lc-messages", value);
3121 #endif
3123 else if (strcasecmp (name, (char *) "lc-ctype") == 0)
3125 xfree (pin_opts->lc_ctype);
3126 pin_opts->lc_ctype = NULL;
3127 if (value && *value)
3128 pin_opts->lc_ctype = str_dup (value);
3129 #ifdef WITH_AGENT
3130 if (use_agent)
3131 rc = set_agent_option (client->crypto->agent, "lc-ctype", value);
3132 #endif
3134 else if (strcasecmp (name, (char *) "ttyname") == 0)
3136 xfree (pin_opts->ttyname);
3137 pin_opts->ttyname = NULL;
3138 if (value && *value)
3139 pin_opts->ttyname = str_dup (value);
3140 #ifdef WITH_AGENT
3141 if (use_agent)
3142 rc = set_agent_option (client->crypto->agent, "ttyname", value);
3143 #endif
3145 else if (strcasecmp (name, (char *) "ttytype") == 0)
3147 xfree (pin_opts->ttytype);
3148 pin_opts->ttytype = NULL;
3149 if (value && *value)
3150 pin_opts->ttytype = str_dup (value);
3151 #ifdef WITH_AGENT
3152 if (use_agent)
3153 rc = set_agent_option (client->crypto->agent, "ttytype", value);
3154 #endif
3156 else if (strcasecmp (name, (char *) "display") == 0)
3158 xfree (pin_opts->display);
3159 pin_opts->display = NULL;
3160 if (value && *value)
3161 pin_opts->display = str_dup (value);
3162 #ifdef WITH_AGENT
3163 if (use_agent)
3164 rc = set_agent_option (client->crypto->agent, "display", value);
3165 #endif
3167 else if (strcasecmp (name, (char *) "pinentry-desc") == 0)
3169 xfree (pin_opts->desc);
3170 pin_opts->desc = NULL;
3171 if (value && *value)
3172 pin_opts->desc = str_dup (value);
3174 else if (strcasecmp (name, (char *) "pinentry-title") == 0)
3176 xfree (pin_opts->title);
3177 pin_opts->title = NULL;
3178 if (value && *value)
3179 pin_opts->title = str_dup (value);
3181 else if (strcasecmp (name, (char *) "pinentry-prompt") == 0)
3183 xfree (pin_opts->prompt);
3184 pin_opts->prompt = NULL;
3185 if (value && *value)
3186 pin_opts->prompt = str_dup (value);
3189 else if (strcasecmp (name, "pinentry-timeout") == 0)
3191 char *p = NULL;
3192 int n;
3194 if (!value)
3195 goto done;
3197 n = (int) strtol (value, &p, 10);
3199 if (*p || n < 0)
3200 return send_error (ctx, GPG_ERR_INV_VALUE);
3202 pin_opts->timeout = n;
3203 MUTEX_LOCK (&rcfile_mutex);
3204 config_set_int_param (&global_config,
3205 client->filename ? client->filename : "global",
3206 "pinentry_timeout", value);
3207 MUTEX_UNLOCK (&rcfile_mutex);
3208 goto done;
3210 else if (strcasecmp (name, "disable-pinentry") == 0)
3212 char *p = NULL;
3213 int n = 1;
3215 if (value && *value)
3217 n = (int) strtol (value, &p, 10);
3218 if (*p || n < 0 || n > 1)
3219 return send_error (ctx, GPG_ERR_INV_VALUE);
3222 if (n)
3223 client->flags |= FLAG_NO_PINENTRY;
3224 else
3225 client->flags &= ~FLAG_NO_PINENTRY;
3227 else
3228 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
3230 done:
3231 #ifdef WITH_AGENT
3232 if (!rc && use_agent && agent)
3234 rc = pinentry_merge_options (&client->crypto->agent->pinentry_opts,
3235 pin_opts);
3237 #endif
3239 return send_error (ctx, rc);
3242 static gpg_error_t
3243 do_rename (assuan_context_t ctx, char *line)
3245 struct client_s *client = assuan_get_pointer (ctx);
3246 gpg_error_t rc;
3247 char **req, **src, *dst;
3248 xmlNodePtr n, ndst;
3250 req = str_split (line, " ", 0);
3252 if (!req || !req[0] || !req[1])
3254 strv_free (req);
3255 return GPG_ERR_SYNTAX;
3258 dst = req[1];
3259 is_literal_element (&dst);
3261 if (!valid_xml_element ((xmlChar *) dst))
3263 strv_free (req);
3264 return GPG_ERR_INV_VALUE;
3267 if (strchr (req[0], '\t'))
3268 src = str_split (req[0], "\t", 0);
3269 else
3270 src = str_split (req[0], " ", 0);
3272 if (!src || !*src)
3274 rc = GPG_ERR_SYNTAX;
3275 goto fail;
3278 n = find_root_element (client->doc, &src, &rc, NULL, 0, 0);
3279 if (src[1] && n)
3280 n = find_elements (client->doc, n->children, src + 1, &rc, NULL, NULL,
3281 NULL, 0, 0, NULL, 0);
3283 if (!n)
3284 goto fail;
3286 xmlChar *a = xmlGetProp (n, (xmlChar *) "_name");
3287 if (!a)
3289 rc = GPG_ERR_ENOMEM;
3290 goto fail;
3293 /* To prevent unwanted effects:
3295 * <root name="a"><b/></root>
3297 * RENAME a<TAB>b b
3299 if (xmlStrEqual (a, (xmlChar *) dst))
3301 xmlFree (a);
3302 rc = GPG_ERR_AMBIGUOUS_NAME;
3303 goto fail;
3306 xmlFree (a);
3307 char **tmp = NULL;
3308 if (src[1])
3310 char **p;
3312 for (p = src; *p; p++)
3314 if (!*(p + 1))
3315 break;
3316 strv_printf (&tmp, "%s", *p);
3320 strv_printf (&tmp, "!%s", dst);
3321 ndst = find_root_element (client->doc, &tmp, &rc, NULL, 0, 0);
3322 if (!ndst && rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3324 strv_free (tmp);
3325 goto fail;
3328 if (tmp[1] && ndst)
3329 ndst = find_elements (client->doc, ndst->children, tmp + 1, &rc, NULL,
3330 NULL, NULL, 0, 0, NULL, 0);
3332 strv_free (tmp);
3333 if (!ndst && rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3334 goto fail;
3336 rc = 0;
3338 /* Target may exist:
3340 * <root name="a"/>
3341 * <root name="b" target="a"/>
3343 * RENAME b a
3345 * Would need to do:
3346 * RENAME !b a
3348 if (ndst == n)
3350 rc = GPG_ERR_AMBIGUOUS_NAME;
3351 goto fail;
3354 if (ndst)
3356 unlink_node (ndst);
3357 xmlFreeNodeList (ndst);
3360 rc = add_attribute (n, "_name", dst);
3362 fail:
3363 strv_free (req);
3364 strv_free (src);
3365 return rc;
3368 static gpg_error_t
3369 rename_command (assuan_context_t ctx, char *line)
3371 struct client_s *client = assuan_get_pointer (ctx);
3372 gpg_error_t rc;
3373 struct argv_s *args[] = {
3374 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3375 NULL
3378 rc = parse_options (&line, args, client);
3379 if (rc)
3380 return send_error (ctx, rc);
3382 if (client->opts & OPT_INQUIRE)
3384 unsigned char *result;
3385 size_t len;
3387 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3388 if (rc)
3389 return send_error (ctx, rc);
3391 line = (char *) result;
3394 rc = do_rename (ctx, line);
3396 if (client->opts & OPT_INQUIRE)
3397 xfree (line);
3399 return send_error (ctx, rc);
3402 static gpg_error_t
3403 do_copy (assuan_context_t ctx, char *line)
3405 struct client_s *client = assuan_get_pointer (ctx);
3406 gpg_error_t rc;
3407 char **req, **src = NULL, **dst = NULL;
3408 xmlNodePtr nsrc, ndst, new = NULL;
3410 req = str_split (line, " ", 0);
3411 if (!req || !req[0] || !req[1])
3413 strv_free (req);
3414 return GPG_ERR_SYNTAX;
3417 if (strchr (req[0], '\t'))
3418 src = str_split (req[0], "\t", 0);
3419 else
3420 src = str_split (req[0], " ", 0);
3422 if (!src || !*src)
3424 rc = GPG_ERR_SYNTAX;
3425 goto fail;
3428 if (strchr (req[1], '\t'))
3429 dst = str_split (req[1], "\t", 0);
3430 else
3431 dst = str_split (req[1], " ", 0);
3433 if (!dst || !*dst)
3435 rc = GPG_ERR_SYNTAX;
3436 goto fail;
3439 if (!valid_element_path (dst, 0))
3441 rc = GPG_ERR_INV_VALUE;
3442 goto fail;
3445 nsrc = find_root_element (client->doc, &src, &rc, NULL, 0, 0);
3446 if (nsrc && src[1])
3447 nsrc = find_elements (client->doc, nsrc->children, src + 1, &rc, NULL,
3448 NULL, NULL, 0, 0, NULL, 0);
3450 if (!nsrc)
3451 goto fail;
3453 new = xmlCopyNodeList (nsrc);
3454 if (!new)
3456 rc = GPG_ERR_ENOMEM;
3457 goto fail;
3460 int create = 0;
3461 ndst = find_root_element (client->doc, &dst, &rc, NULL, 0, 0);
3462 if (ndst && dst[1])
3464 if (ndst->children)
3465 ndst = find_elements (client->doc, ndst->children, dst + 1, &rc, NULL,
3466 NULL, create_target_elements_cb, 0, 0, NULL, 0);
3467 else
3468 create = 1;
3470 else
3471 create = 1;
3473 if (!ndst && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3474 goto fail;
3475 else if (!ndst || create)
3477 ndst = create_element_path (client, &dst, &rc, NULL);
3478 if (!ndst)
3479 goto fail;
3482 /* Merge any attributes from the src node to the initial dst node. */
3483 for (xmlAttrPtr attr = new->properties; attr; attr = attr->next)
3485 if (xmlStrEqual (attr->name, (xmlChar *) "_name"))
3486 continue;
3488 xmlAttrPtr a = xmlHasProp (ndst, attr->name);
3489 if (a)
3490 xmlRemoveProp (a);
3492 xmlChar *tmp = xmlNodeGetContent (attr->children);
3493 xmlNewProp (ndst, attr->name, tmp);
3494 xmlFree (tmp);
3495 rc = add_attribute (ndst, NULL, NULL);
3498 xmlNodePtr n = ndst->children;
3499 xmlUnlinkNode (n);
3500 xmlFreeNodeList (n);
3501 ndst->children = NULL;
3503 if (new->children)
3505 n = xmlCopyNodeList (new->children);
3506 if (!n)
3508 rc = GPG_ERR_ENOMEM;
3509 goto fail;
3512 n = xmlAddChildList (ndst, n);
3513 if (!n)
3515 rc = GPG_ERR_ENOMEM;
3516 goto fail;
3519 rc = update_element_mtime (xmlDocGetRootElement (client->doc) ==
3520 ndst->parent ? ndst : ndst->parent);
3523 fail:
3524 if (new)
3526 xmlUnlinkNode (new);
3527 xmlFreeNodeList (new);
3530 if (req)
3531 strv_free (req);
3533 if (src)
3534 strv_free (src);
3536 if (dst)
3537 strv_free (dst);
3539 return rc;
3542 static gpg_error_t
3543 copy_command (assuan_context_t ctx, char *line)
3545 struct client_s *client = assuan_get_pointer (ctx);
3546 gpg_error_t rc;
3547 struct argv_s *args[] = {
3548 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3549 NULL
3552 rc = parse_options (&line, args, client);
3553 if (rc)
3554 return send_error (ctx, rc);
3556 if (client->opts & OPT_INQUIRE)
3558 unsigned char *result;
3559 size_t len;
3561 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3562 if (rc)
3563 return send_error (ctx, rc);
3565 line = (char *) result;
3568 rc = do_copy (ctx, line);
3570 if (client->opts & OPT_INQUIRE)
3571 xfree (line);
3573 return send_error (ctx, rc);
3576 static gpg_error_t
3577 do_move (assuan_context_t ctx, char *line)
3579 struct client_s *client = assuan_get_pointer (ctx);
3580 gpg_error_t rc;
3581 char **req, **src = NULL, **dst = NULL;
3582 xmlNodePtr nsrc, ndst = NULL;
3584 req = str_split (line, " ", 0);
3586 if (!req || !req[0] || !req[1])
3588 strv_free (req);
3589 return GPG_ERR_SYNTAX;
3592 if (strchr (req[0], '\t'))
3593 src = str_split (req[0], "\t", 0);
3594 else
3595 src = str_split (req[0], " ", 0);
3597 if (!src || !*src)
3599 rc = GPG_ERR_SYNTAX;
3600 goto fail;
3603 if (strchr (req[1], '\t'))
3604 dst = str_split (req[1], "\t", 0);
3605 else
3606 dst = str_split (req[1], " ", 0);
3608 nsrc = find_root_element (client->doc, &src, &rc, NULL, 0, 0);
3609 if (nsrc && src[1])
3610 nsrc = find_elements (client->doc, nsrc->children, src + 1, &rc, NULL,
3611 NULL, NULL, 0, 0, NULL, 0);
3613 if (!nsrc)
3614 goto fail;
3616 if (dst)
3618 if (!valid_element_path (dst, 0))
3620 rc = GPG_ERR_INV_VALUE;
3621 goto fail;
3624 ndst = find_root_element (client->doc, &dst, &rc, NULL, 0, 0);
3625 if (ndst && dst[1])
3626 ndst = find_elements (client->doc, ndst->children, dst + 1, &rc, NULL,
3627 NULL, NULL, 0, 0, NULL, 0);
3629 else
3630 ndst = xmlDocGetRootElement (client->doc);
3632 for (xmlNodePtr n = ndst; n; n = n->parent)
3634 if (n == nsrc)
3636 rc = GPG_ERR_CONFLICT;
3637 goto fail;
3641 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3642 goto fail;
3644 rc = 0;
3646 if (ndst)
3648 xmlChar *a = node_has_attribute (nsrc, (xmlChar *) "_name");
3649 xmlNodePtr dup = find_element (ndst->children, (char *) a, NULL);
3651 xmlFree (a);
3652 if (dup)
3654 if (dup == nsrc)
3655 goto fail;
3657 if (ndst == xmlDocGetRootElement (client->doc))
3659 xmlNodePtr n = nsrc;
3660 int match = 0;
3662 while (n->parent && n->parent != ndst)
3663 n = n->parent;
3665 xmlChar *a = node_has_attribute (n, (xmlChar *) "_name");
3666 xmlChar *b = node_has_attribute (nsrc, (xmlChar *) "_name");
3668 if (xmlStrEqual (a, b))
3670 match = 1;
3671 xmlUnlinkNode (nsrc);
3672 xmlUnlinkNode (n);
3673 xmlFreeNodeList (n);
3676 xmlFree (a);
3677 xmlFree (b);
3679 if (!match)
3681 xmlUnlinkNode (dup);
3682 xmlFreeNodeList (dup);
3685 else
3686 xmlUnlinkNode (dup);
3690 if (!ndst && dst)
3692 xmlChar *name = node_has_attribute (nsrc, (xmlChar *) "_name");
3694 if (nsrc->parent == xmlDocGetRootElement (client->doc)
3695 && !strcmp ((char *) name, *dst))
3697 xmlFree (name);
3698 rc = GPG_ERR_CONFLICT;
3699 goto fail;
3702 xmlFree (name);
3703 ndst = create_element_path (client, &dst, &rc, nsrc);
3706 if (!ndst)
3707 goto fail;
3709 update_element_mtime (nsrc->parent);
3710 xmlUnlinkNode (nsrc);
3711 ndst = xmlAddChildList (ndst, nsrc);
3713 if (!ndst)
3714 rc = GPG_ERR_ENOMEM;
3715 else
3716 update_element_mtime (ndst->parent);
3718 fail:
3719 if (req)
3720 strv_free (req);
3722 if (src)
3723 strv_free (src);
3725 if (dst)
3726 strv_free (dst);
3728 return rc;
3731 static gpg_error_t
3732 move_command (assuan_context_t ctx, char *line)
3734 struct client_s *client = assuan_get_pointer (ctx);
3735 gpg_error_t rc;
3736 struct argv_s *args[] = {
3737 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3738 NULL
3741 rc = parse_options (&line, args, client);
3742 if (rc)
3743 return send_error (ctx, rc);
3745 if (client->opts & OPT_INQUIRE)
3747 unsigned char *result;
3748 size_t len;
3750 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3751 if (rc)
3752 return send_error (ctx, rc);
3754 line = (char *) result;
3757 rc = do_move (ctx, line);
3759 if (client->opts & OPT_INQUIRE)
3760 xfree (line);
3762 return send_error (ctx, rc);
3765 static gpg_error_t
3766 ls_command (assuan_context_t ctx, char *line)
3768 gpg_error_t rc;
3769 char *tmp = str_asprintf ("%s/data", homedir);
3770 char *dir = expand_homedir (tmp);
3771 DIR *d = opendir (dir);
3773 rc = gpg_error_from_syserror ();
3774 xfree (tmp);
3776 if (!d)
3778 xfree (dir);
3779 return send_error (ctx, rc);
3782 size_t len =
3783 offsetof (struct dirent, d_name) +pathconf (dir, _PC_NAME_MAX) + 1;
3784 struct dirent *p = xmalloc (len), *cur = NULL;
3785 char *list = NULL;
3787 xfree (dir);
3788 rc = 0;
3790 while (!readdir_r (d, p, &cur) && cur)
3792 if (cur->d_name[0] == '.' && cur->d_name[1] == '\0')
3793 continue;
3794 else if (cur->d_name[0] == '.' && cur->d_name[1] == '.'
3795 && cur->d_name[2] == '\0')
3796 continue;
3798 tmp = str_asprintf ("%s%s\n", list ? list : "", cur->d_name);
3800 if (!tmp)
3802 if (list)
3803 xfree (list);
3805 rc = GPG_ERR_ENOMEM;
3806 break;
3809 xfree (list);
3810 list = tmp;
3813 closedir (d);
3814 xfree (p);
3816 if (rc)
3817 return send_error (ctx, rc);
3819 if (!list)
3820 return send_error (ctx, GPG_ERR_NO_DATA);
3822 list[strlen (list) - 1] = 0;
3823 rc = xfer_data (ctx, list, strlen (list));
3824 xfree (list);
3825 return send_error (ctx, rc);
3828 static gpg_error_t
3829 bye_notify (assuan_context_t ctx, char *line)
3831 struct client_s *cl = assuan_get_pointer (ctx);
3833 #ifdef WITH_GNUTLS
3834 if (cl->thd->remote)
3836 int rc;
3840 struct timeval tv = { 0, 50000 };
3842 rc = gnutls_bye (cl->thd->tls->ses, GNUTLS_SHUT_RDWR);
3843 if (rc == GNUTLS_E_AGAIN)
3844 select (0, NULL, NULL, NULL, &tv);
3846 while (rc == GNUTLS_E_AGAIN);
3848 #endif
3850 /* This will let assuan_process_next() return. */
3851 fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK);
3852 cl->last_rc = 0; // BYE command result
3853 return 0;
3856 static gpg_error_t
3857 reset_notify (assuan_context_t ctx, char *line)
3859 struct client_s *client = assuan_get_pointer (ctx);
3861 if (client)
3862 cleanup_client (client);
3864 return 0;
3868 * This is called before every Assuan command.
3870 static gpg_error_t
3871 command_startup (assuan_context_t ctx, const char *name)
3873 struct client_s *client = assuan_get_pointer (ctx);
3874 gpg_error_t rc;
3875 struct command_table_s *cmd = NULL;
3877 log_write1 ("command='%s'", name);
3878 client->last_rc = client->opts = 0;
3880 for (int i = 0; command_table[i]; i++)
3882 if (!strcasecmp (name, command_table[i]->name))
3884 if (command_table[i]->ignore_startup)
3885 return 0;
3886 cmd = command_table[i];
3887 break;
3891 client->last_rc = rc = gpg_error (file_modified (client, cmd));
3892 return rc;
3896 * This is called after every Assuan command.
3898 static void
3899 command_finalize (assuan_context_t ctx, gpg_error_t rc)
3901 struct client_s *client = assuan_get_pointer (ctx);
3903 if (!(client->flags & FLAG_LOCK_CMD))
3904 unlock_file_mutex (client, 0);
3906 log_write1 (_("command completed: rc=%u"), client->last_rc);
3907 client->last_rc = gpg_error (GPG_ERR_UNKNOWN_COMMAND);
3908 #ifdef WITH_GNUTLS
3909 client->thd->buffer_timeout = client->thd->last_buffer_size = 0;
3910 #endif
3913 static gpg_error_t
3914 help_command (assuan_context_t ctx, char *line)
3916 gpg_error_t rc;
3917 int i;
3919 if (!line || !*line)
3921 char *tmp;
3922 char *help = str_dup (_("Usage: HELP [<COMMAND>]\n"
3923 "For commands that take an element path as an argument, each element is "
3924 "separated with an ASCII @key{TAB} character (ASCII 0x09)."
3925 "\n" "COMMANDS:"));
3927 for (i = 0; command_table[i]; i++)
3929 if (!command_table[i]->help)
3930 continue;
3932 tmp = str_asprintf ("%s %s", help, command_table[i]->name);
3933 xfree (help);
3934 help = tmp;
3937 tmp = strip_texi_and_wrap (help);
3938 xfree (help);
3939 rc = xfer_data (ctx, tmp, strlen (tmp));
3940 xfree (tmp);
3941 return send_error (ctx, rc);
3944 for (i = 0; command_table[i]; i++)
3946 if (!strcasecmp (line, command_table[i]->name))
3948 char *help, *tmp;
3950 if (!command_table[i]->help)
3951 break;
3953 help = strip_texi_and_wrap (command_table[i]->help);
3954 tmp = str_asprintf (_("Usage: %s"), help);
3955 xfree (help);
3956 rc = xfer_data (ctx, tmp, strlen (tmp));
3957 xfree (tmp);
3958 return send_error (ctx, rc);
3962 return send_error (ctx, GPG_ERR_INV_NAME);
3965 static void
3966 new_command (const char *name, int ignore, int unlock,
3967 gpg_error_t (*handler) (assuan_context_t, char *),
3968 const char *help)
3970 int i = 0;
3972 if (command_table)
3973 for (i = 0; command_table[i]; i++);
3975 command_table =
3976 xrealloc (command_table, (i + 2) * sizeof (struct command_table_s *));
3977 command_table[i] = xcalloc (1, sizeof (struct command_table_s));
3978 command_table[i]->name = name;
3979 command_table[i]->handler = handler;
3980 command_table[i]->ignore_startup = ignore;
3981 command_table[i]->unlock = unlock;
3982 command_table[i++]->help = help;
3983 command_table[i] = NULL;
3986 void
3987 deinit_commands ()
3989 int i;
3991 for (i = 0; command_table[i]; i++)
3992 xfree (command_table[i]);
3994 xfree (command_table);
3997 static int
3998 sort_commands (const void *arg1, const void *arg2)
4000 struct command_table_s *const *a = arg1;
4001 struct command_table_s *const *b = arg2;
4003 if (!*a || !*b)
4004 return 0;
4005 else if (*a && !*b)
4006 return 1;
4007 else if (!*a && *b)
4008 return -1;
4010 return strcmp ((*a)->name, (*b)->name);
4013 static gpg_error_t
4014 passwd_command (assuan_context_t ctx, char *line)
4016 struct client_s *client = assuan_get_pointer (ctx);
4017 gpg_error_t rc;
4018 struct argv_s *args[] = {
4019 &(struct argv_s) {"reset", OPTION_TYPE_NOARG, parse_opt_reset},
4020 &(struct argv_s) {"s2k-count", OPTION_TYPE_ARG, parse_opt_s2k_count},
4021 NULL
4024 if (client->flags & FLAG_NEW)
4025 return send_error (ctx, GPG_ERR_INV_STATE);
4027 client->crypto->save.s2k_count =
4028 config_get_ulong (client->filename, "s2k_count");
4029 rc = parse_options (&line, args, client);
4030 if (rc)
4031 return send_error (ctx, rc);
4033 if (!rc && client->opts & OPT_RESET)
4035 rc = cache_clear (client->md5file);
4036 if (!rc)
4037 send_status_all (STATUS_CACHE, NULL);
4040 if (!rc)
4042 if (!IS_PKI (client->crypto))
4044 struct crypto_s *crypto;
4046 xfree (client->crypto->filename);
4047 client->crypto->filename = str_dup (client->filename);
4048 rc = change_passwd (ctx, client->filename,
4049 client->flags & FLAG_NO_PINENTRY, &crypto);
4050 if (!rc)
4052 cleanup_crypto (&client->crypto);
4053 client->crypto = crypto;
4054 update_checksum (client);
4055 cleanup_crypto_stage1 (client->crypto);
4058 #ifdef WITH_AGENT
4059 else
4061 if (client->crypto->save.s2k_count)
4062 rc = send_to_agent (client->crypto->agent, NULL, NULL,
4063 "OPTION s2k-count=%lu",
4064 client->crypto->save.s2k_count);
4066 if (!rc)
4067 rc = agent_passwd (client->crypto);
4069 #endif
4072 return send_error (ctx, rc);
4075 static gpg_error_t
4076 parse_keygrip_opt_sign (void *data, void *value)
4078 struct client_s *client = data;
4080 (void) value;
4081 client->opts |= OPT_SIGN;
4082 return 0;
4085 static gpg_error_t
4086 keygrip_command (assuan_context_t ctx, char *line)
4088 struct client_s *client = assuan_get_pointer (ctx);
4089 gpg_error_t rc;
4090 struct crypto_s *crypto = NULL;
4091 struct argv_s *args[] = {
4092 &(struct argv_s) {"sign", OPTION_TYPE_NOARG, parse_keygrip_opt_sign},
4093 NULL
4096 if (!line || !*line)
4097 return send_error (ctx, GPG_ERR_SYNTAX);
4099 rc = parse_options (&line, args, client);
4100 if (rc)
4101 return send_error (ctx, rc);
4103 if (!valid_filename (line))
4104 return send_error (ctx, GPG_ERR_INV_VALUE);
4106 rc = init_client_crypto (&crypto);
4107 if (rc)
4108 return send_error (ctx, rc);
4110 rc = read_data_file (line, crypto);
4111 if (!rc)
4113 char *hexgrip = NULL;
4115 if (!IS_PKI (crypto))
4117 cleanup_crypto (&crypto);
4118 return send_error (ctx, GPG_ERR_NOT_SUPPORTED);
4121 if (client->opts & OPT_SIGN)
4123 if (valid_keygrip (crypto->sign_grip, sizeof (crypto->sign_grip)))
4124 hexgrip = bin2hex (crypto->sign_grip, sizeof (crypto->sign_grip));
4127 if (!hexgrip)
4128 hexgrip = bin2hex (crypto->grip, sizeof (crypto->grip));
4130 if (!hexgrip)
4131 rc = GPG_ERR_ENOMEM;
4132 else
4133 rc = xfer_data (ctx, hexgrip, strlen (hexgrip));
4135 xfree (hexgrip);
4138 UPDATE_AGENT_CTX (client, crypto);
4139 cleanup_crypto (&crypto);
4140 return send_error (ctx, rc);
4143 static gpg_error_t
4144 parse_opt_data (void *data, void *value)
4146 struct client_s *client = data;
4148 (void) value;
4149 client->opts |= OPT_DATA;
4150 return 0;
4153 static gpg_error_t
4154 getinfo_command (assuan_context_t ctx, char *line)
4156 struct client_s *client = assuan_get_pointer (ctx);
4157 gpg_error_t rc;
4158 char buf[ASSUAN_LINELENGTH];
4159 struct argv_s *args[] = {
4160 &(struct argv_s) {"data", OPTION_TYPE_NOARG, parse_opt_data},
4161 NULL
4164 rc = parse_options (&line, args, client);
4165 if (rc)
4166 return send_error (ctx, rc);
4168 if (!strcasecmp (line, "clients"))
4170 if (client->opts & OPT_DATA)
4172 MUTEX_LOCK (&cn_mutex);
4173 snprintf (buf, sizeof (buf), "%i", slist_length (cn_thread_list));
4174 MUTEX_UNLOCK (&cn_mutex);
4175 rc = xfer_data (ctx, buf, strlen (buf));
4177 else
4178 rc = send_status (ctx, STATUS_CLIENTS, NULL);
4180 else if (!strcasecmp (line, "cache"))
4182 if (client->opts & OPT_DATA)
4184 snprintf (buf, sizeof (buf), "%u", cache_file_count ());
4185 rc = xfer_data (ctx, buf, strlen (buf));
4187 else
4188 rc = send_status (ctx, STATUS_CACHE, NULL);
4190 else if (!strcasecmp (line, "pid"))
4192 char buf[32];
4193 pid_t pid = getpid ();
4195 snprintf (buf, sizeof (buf), "%i", pid);
4196 rc = xfer_data (ctx, buf, strlen (buf));
4198 else if (!strcasecmp (line, "version"))
4200 char *buf = str_asprintf ("0x%06x %s%s", VERSION_HEX,
4201 #ifdef WITH_LIBACL
4202 "ACL "
4203 #endif
4204 #ifdef WITH_GNUTLS
4205 "GNUTLS "
4206 #endif
4207 #ifdef WITH_QUALITY
4208 "QUALITY "
4209 #endif
4210 "", use_agent ? "AGENT" : "");
4211 rc = xfer_data (ctx, buf, strlen (buf));
4212 xfree (buf);
4214 else if (!strcasecmp (line, "last_error"))
4216 if (client->last_error)
4217 rc = xfer_data (ctx, client->last_error, strlen (client->last_error));
4218 else
4219 rc = GPG_ERR_NO_DATA;
4221 else
4222 rc = gpg_error (GPG_ERR_SYNTAX);
4224 return send_error (ctx, rc);
4227 #ifdef WITH_AGENT
4228 static gpg_error_t
4229 send_data_cb (void *user, const void *buf, size_t len)
4231 assuan_context_t ctx = user;
4233 return assuan_send_data (ctx, buf, len);
4236 static gpg_error_t
4237 send_status_cb (void *user, const char *line)
4239 assuan_context_t ctx = user;
4240 char keyword[200], *k;
4241 const char *p;
4243 for (p = line, k = keyword; *p; p++)
4245 if (isspace (*p))
4246 break;
4248 *k++ = *p;
4251 *k = 0;
4252 if (*p == '#')
4253 p++;
4255 while (isspace (*p))
4256 p++;
4258 return assuan_write_status (ctx, keyword, *p ? p : NULL);
4260 #endif
4262 static gpg_error_t
4263 agent_command (assuan_context_t ctx, char *line)
4265 gpg_error_t rc = 0;
4267 if (!use_agent)
4268 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
4270 #ifdef WITH_AGENT
4271 struct client_s *client = assuan_get_pointer (ctx);
4273 if (!line || !*line)
4274 return send_error (ctx, GPG_ERR_SYNTAX);
4276 assuan_set_flag (client->crypto->agent->ctx, ASSUAN_CONVEY_COMMENTS, 1);
4277 rc = assuan_transact (client->crypto->agent->ctx, line, send_data_cb,
4278 client->ctx, agent_loopback_cb, client->crypto,
4279 send_status_cb, client->ctx);
4280 if (gpg_err_code (rc) == GPG_ERR_ASS_CANCELED)
4282 char *line;
4283 size_t len;
4285 rc = assuan_write_line (client->crypto->agent->ctx, "CAN");
4286 if (!rc)
4288 rc = assuan_read_line (client->crypto->agent->ctx, &line, &len);
4289 if (!rc)
4290 rc = gpg_error (GPG_ERR_ASS_CANCELED);
4294 assuan_set_flag (client->crypto->agent->ctx, ASSUAN_CONVEY_COMMENTS, 0);
4295 #endif
4296 return send_error (ctx, rc);
4299 void
4300 init_commands ()
4302 /* !BEGIN-HELP-TEXT!
4304 * This comment is used as a marker to generate the offline documentation
4305 * found in doc/pwmd.info. The indentation needs to be kept for the awk
4306 * script to determine where commands begin and end.
4308 new_command("HELP", 1, 1, help_command, _(
4309 "HELP [<COMMAND>]\n"
4310 "Show available commands or command specific help text."
4313 new_command("AGENT", 1, 1, agent_command, _(
4314 "AGENT <command>\n"
4315 "Send a @command{gpg-agent} protocol @var{command} directly to the "
4316 "@command{gpg-agent}."
4319 new_command("GETINFO", 1, 1, getinfo_command, _(
4320 "GETINFO [--data] CACHE | CLIENTS | PID | LAST_ERROR | VERSION\n"
4321 "Get server and other information: @var{cache} returns the number of cached "
4322 "documents via a status message. @var{clients} returns the number of "
4323 "connected clients via a status message. @var{pid} returns the process ID "
4324 "number of the server via a data response. @var{VERSION} returns the server "
4325 "version number and compile-time features with a data response with each "
4326 "being space delimited. @var{LAST_ERROR} returns a detailed description of "
4327 "the last failed command when available. @xref{Status Messages}. "
4328 "\n"
4329 "When the @option{--data} option is specified then the result will be sent "
4330 "via a data response rather than a status message."
4333 new_command("PASSWD", 0, 0, passwd_command, _(
4334 "PASSWD [--reset] [--s2k-count=N]\n"
4335 "Changes the passphrase of the secret key required to open the current "
4336 "file or the passphrase of a symmetrically encrypted data file. When the "
4337 "@option{--reset} option is passed then the cache entry for the current "
4338 "file will be reset and the passphrase, if any, will be required during the "
4339 "next @code{OPEN}. @xref{OPEN}."
4340 "\n"
4341 "The @option{--s2k-count} option sets number of hash iterations for a "
4342 "passphrase and must be either @code{0} to use the calibrated count of the "
4343 "machine (the default), or a value greater than or equal to @code{65536}. "
4344 "@xref{SAVE}. This option has no effect for symmetrically encrypted data "
4345 "files."
4348 new_command("KEYGRIP", 1, 1, keygrip_command, _(
4349 "KEYGRIP [--sign] <filename>\n"
4350 "Returns the hex encoded keygrip of the specified @var{filename} with a "
4351 "data response."
4352 "\n"
4353 "When the @option{--sign} option is specified then the key used for signing "
4354 "of the specified @var{filename} will be returned."
4355 "\n"
4356 "For symmetrically encrypted data files this command returns the error "
4357 "GPG_ERR_NOT_SUPPORTED."
4360 new_command("OPEN", 1, 1, open_command, _(
4361 "OPEN [--lock] <filename> [<passphrase>]\n"
4362 "Opens @var{filename} using @var{passphrase}. When the filename is not "
4363 "found on the file-system then a new document will be created. If the file "
4364 "is found, it is looked for in the file cache. If cached and no "
4365 "@var{passphrase} was specified then the cached document is opened. When not "
4366 "cached, @cite{pinentry(1)} will be used to retrieve the passphrase to use "
4367 "for decryption unless @option{disable-pinentry} (@pxref{OPTION}) was "
4368 "specified."
4369 "\n"
4370 "When the @option{--lock} option is passed then the file mutex will be "
4371 "locked as if the @code{LOCK} command (@pxref{LOCK}) had been sent after the "
4372 "file has been opened."
4375 new_command("SAVE", 0, 0, save_command, _(
4376 "SAVE [--no-passphrase] [--reset] [--no-agent] [--s2k-count=N] [--cipher=<algo>] [--cipher-iterations=N] [--inquire-keyparam] [--keygrip=hexstring [--sign-keygrip=hexstring]]\n"
4377 "Writes the @abbr{XML} document to disk. The file written to is the file that "
4378 "was opened using the @code{OPEN} command (@pxref{OPEN}). If the file is a "
4379 "new one or the option @option{--inquire-keyparam} was passed, then a new "
4380 "keypair will be generated and a pinentry will be used to prompt for the "
4381 "passphrase to encrypt with unless the @option{--no-passphrase} option was "
4382 "passed, in which case the data file will not be passphrase protected."
4383 "\n"
4384 "The @option{--no-agent} option disables use of @command{gpg-agent} for "
4385 "passphrase retrieval and caching of new files when @command{gpg-agent} "
4386 "use is enabled. The datafile will be symmetrically encrypted and will not "
4387 "use or generate any keypair."
4388 "\n"
4389 "The @option{--reset} option will clear the cache entry for the current file "
4390 "and require a passphrase, if needed, before saving."
4391 "\n"
4392 "The @option{--cipher} option can be used to encrypt the @abbr{XML} data to "
4393 "an alternate cipher. The default is @code{aes256}. See the Configuration "
4394 "(@pxref{Configuration}) for available ciphers."
4395 "\n"
4396 "The @option{--cipher-iterations} option specifies the number of times to "
4397 "encrypt the XML data. The default is 0 although 1 iteration is still done."
4398 "\n"
4399 "The @option{--inquire-keyparam} option will send a server @emph{INQUIRE} to "
4400 "the client to obtain the key paramaters to use when generating a new "
4401 "keypair. The inquired data is expected to be an S-expression. If not "
4402 "specified then an @samp{RSA} key of @samp{2048} bits will be generated "
4403 "unless otherwise set in the configuration file (@pxref{Configuration}). Note "
4404 "that when this option is specified a new keypair will be generated "
4405 "reguardless if the file is a new one or not."
4406 "\n"
4407 "You can encrypt the data file to a public key other than the one that it "
4408 "was originally encrypted with by passing the @option{--keygrip} option with "
4409 "the hex encoded keygrip of the public key as its argument. The keygrip may "
4410 "be of any key that @command{gpg-agent} knows about. The "
4411 "@option{--sign-keygrip} option may also be used to sign with an alternate "
4412 "secret key. This option may be needed when using a smartcard. This option "
4413 "has no effect with symmetrically encrypted data files."
4414 "\n"
4415 "The @option{--s2k-count} option sets number of hash iterations for a "
4416 "passphrase. A value less-than @code{65536} will use the machine calibrated "
4417 "value which is the default. This setting only affects new files. To change "
4418 "the setting, use the @code{PASSWD} command (@pxref{PASSWD}). This option "
4419 "has no effect with symmetrically encrypted data files."
4422 new_command("ISCACHED", 1, 0, iscached_command, _(
4423 "ISCACHED [--lock] <filename>\n"
4424 "An @emph{OK} response is returned if the specified @var{filename} is found "
4425 "in the file cache. If not found in the cache but exists on the filesystem "
4426 "then @var{GPG_ERR_NO_DATA} is returned. Otherwise a filesystem error is "
4427 "returned."
4428 "\n"
4429 "The @option{lock} option will lock the file mutex of @var{filename} when the "
4430 "file exists; it does not need to be opened nor cached."
4433 new_command("CLEARCACHE", 1, 1, clearcache_command, _(
4434 "CLEARCACHE [<filename>]\n"
4435 "Clears a file cache entry for all or the specified @var{filename}."
4438 new_command("CACHETIMEOUT", 1, 1, cachetimeout_command, _(
4439 "CACHETIMEOUT <filename> <seconds>\n"
4440 "The time in @var{seconds} until @var{filename} will be removed from the "
4441 "cache. @code{-1} will keep the cache entry forever, @code{0} will require "
4442 "the passphrase for each @code{OPEN} or @code{SAVE} command (@pxref{OPEN}, "
4443 "@pxref{SAVE}). @xref{Configuration}, and the @code{cache_timeout} "
4444 "parameter."
4447 new_command("LIST", 0, 1, list_command, _(
4448 "LIST [--inquire] [--no-recurse] [--verbose] [--with-target] [--all] [[!]element[<TAB>[!]child[..]]]\n"
4449 "If no element path is given then a newline separated list of root elements "
4450 "is returned with a data response. If given, then all reachable elements "
4451 "of the specified element path are returned unless the @option{--no-recurse} "
4452 "option is specified. If specified, only the child elements of the element "
4453 "path are returned without recursing into grandchildren. Each resulting "
4454 "element is prefixed with the literal @code{!} character when the element "
4455 "contains no @code{target} attribute. @xref{Target Attribute}, for details."
4456 "\n"
4457 "When the @option{--verbose} option is passed then each element path "
4458 "returned will have zero or more flags appened to it. These flags are "
4459 "delimited from the element path by a single space character. A flag itself "
4460 "is a single character. Flag @code{+} indicates that there are child nodes of "
4461 "the current element path. Flag @code{E} indicates that an element of an "
4462 "element path contained in a @var{target} attribute could not be found. Flag "
4463 "@code{O} indicates that a @var{target} attribute recursion limit was reached "
4464 "(@pxref{Configuration}). Flag @code{T} will append the resolved element path "
4465 "of the @var{target} attribute contained in the current element (see below)."
4466 "\n"
4467 "The @option{--with-target} option implies @option{--verbose} and will append "
4468 "an additional flag @code{T} followed by a single space then an element path. "
4469 "The appended element path is the resolved path (@pxref{REALPATH}) of the "
4470 "current element when it contains a @var{target} attribute. When no "
4471 "@var{target} attribute is found then no flag will be appended."
4472 "\n"
4473 "The @option{--no-recurse} option limits the amount of data returned to only "
4474 "the listing of children of the specified element path and not any "
4475 "grandchildren."
4476 "\n"
4477 "The @option{--all} option lists the entire element tree for each root "
4478 "element. This option also implies option @option{--verbose}."
4479 "\n"
4480 "When the @option{--inquire} option is passed then all remaining non-option "
4481 "arguments are retrieved via a server @emph{INQUIRE}."
4484 new_command("REALPATH", 0, 1, realpath_command, _(
4485 "REALPATH [--inquire] [!]element[<TAB>[!]child[..]]\n"
4486 "Resolves all @code{target} attributes of the specified element path and "
4487 "returns the result with a data response. @xref{Target Attribute}, for details."
4488 "\n"
4489 "When the @option{--inquire} option is passed then all remaining non-option "
4490 "arguments are retrieved via a server @emph{INQUIRE}."
4493 new_command("STORE", 0, 1, store_command, _(
4494 "STORE [!]element[<TAB>[!]child[..]]<TAB>[content]\n"
4495 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
4496 "\n"
4497 "Creates a new element path or modifies the @var{content} of an existing "
4498 "element. If only a single element is specified then a new root element is "
4499 "created. Otherwise, elements are @key{TAB} delimited and the content will be "
4500 "set to the final @key{TAB} delimited element. If no @var{content} is "
4501 "specified after the final @key{TAB}, then the content of the element will "
4502 "be removed, or empty when creating a new element."
4503 "\n"
4504 "The only restriction of an element name is that it not contain whitespace "
4505 "or begin with the literal element character @code{!} unless specifying a "
4506 "literal element (@pxref{Target Attribute}). There is no whitespace between "
4507 "the @key{TAB} delimited elements. It is recommended that the content of an "
4508 "element be base64 encoded when it contains control or @key{TAB} characters "
4509 "to prevent @abbr{XML} parsing and @command{pwmd} syntax errors."
4512 new_command("RENAME", 0, 1, rename_command, _(
4513 "RENAME [--inquire] [!]element[<TAB>[!]child[..]] <value>\n"
4514 "Renames the specified @var{element} to the new @var{value}. If an element of "
4515 "the same name as the @var{value} already exists it will be overwritten."
4516 "\n"
4517 "When the @option{--inquire} option is passed then all remaining non-option "
4518 "arguments are retrieved via a server @emph{INQUIRE}."
4521 new_command("COPY", 0, 1, copy_command, _(
4522 "COPY [--inquire] [!]source[<TAB>[!]child[..]] [!]dest[<TAB>[!]child[..]]\n"
4523 "Copies the entire element tree starting from the child node of the source "
4524 "element, to the destination element path. If the destination element path "
4525 "does not exist then it will be created; otherwise it is overwritten."
4526 "\n"
4527 "Note that attributes from the source element are merged into the "
4528 "destination element when the destination element path exists. When an "
4529 "attribute of the same name exists in both the source and destination "
4530 "elements then the destination attribute will be updated to the source "
4531 "attribute value."
4532 "\n"
4533 "When the @option{--inquire} option is passed then all remaining non-option "
4534 "arguments are retrieved via a server @emph{INQUIRE}."
4537 new_command("MOVE", 0, 1, move_command, _(
4538 "MOVE [--inquire] [!]source[<TAB>[!]child[..]] [[!]dest[<TAB>[!]child[..]]]\n"
4539 "Moves the source element path to the destination element path. If the "
4540 "destination is not specified then it will be moved to the root node of the "
4541 "document. If the destination is specified and exists then it will be "
4542 "overwritten; otherwise non-existing elements of the destination element "
4543 "path will be created."
4544 "\n"
4545 "When the @option{--inquire} option is passed then all remaining non-option "
4546 "arguments are retrieved via a server @emph{INQUIRE}."
4549 new_command("DELETE", 0, 1, delete_command, _(
4550 "DELETE [--inquire] [!]element[<TAB>[!]child[..]]\n"
4551 "Removes the specified element path and all of its children. This may break "
4552 "an element with a @code{target} attribute (@pxref{Target Attribute}) that "
4553 "refers to this element or any of its children."
4554 "\n"
4555 "When the @option{--inquire} option is passed then all remaining non-option "
4556 "arguments are retrieved via a server @emph{INQUIRE}."
4559 new_command("GET", 0, 1, get_command, _(
4560 "GET [--inquire] [!]element[<TAB>[!]child[..]]\n"
4561 "Retrieves the content of the specified element. The content is returned "
4562 "with a data response."
4563 "\n"
4564 "When the @option{--inquire} option is passed then all remaining non-option "
4565 "arguments are retrieved via a server @emph{INQUIRE}."
4568 new_command("ATTR", 0, 1, attr_command, _(
4569 "ATTR [--inquire] SET|GET|DELETE|LIST [<attribute>] [!]element[<TAB>[!]child[..]] ..\n"
4570 "@table @asis\n"
4571 "@item ATTR SET attribute [!]element[<TAB>[!]child[..]] [value]\n"
4572 "\n"
4573 " Stores or updates an @var{attribute} name and optional @var{value} of an "
4574 "element. When no @var{value} is specified any existing value will be removed."
4575 "\n"
4576 "@item ATTR DELETE attribute [!]element[<TAB>[!]child[..]]\n"
4577 "\n"
4578 " Removes an @var{attribute} from an element."
4579 "\n"
4580 "@item ATTR LIST [!]element[<TAB>[!]child[..]]\n"
4581 "\n"
4582 " Retrieves a newline separated list of attributes names and values "
4583 "from the specified element. Each attribute name and value is space delimited."
4584 "\n"
4585 "@item ATTR GET attribute [!]element[<TAB>[!]child[..]]\n"
4586 "\n"
4587 " Retrieves the value of an @var{attribute} from an element."
4588 "@end table\n"
4589 "\n"
4590 "The @code{_name} attribute (case sensitive) cannot be removed nor modified. "
4591 "Use the @code{DELETE} (@pxref{DELETE}) or @code{RENAME} (@pxref{RENAME}) "
4592 "commands instead."
4593 "\n"
4594 "The @code{_mtime} attribute is updated each time an element is modified by "
4595 "either storing content, editing attributes or by deleting a child element. "
4596 "The @code{_ctime} attribute is created for each new element in an element "
4597 "path."
4598 "\n"
4599 "When the @option{--inquire} option is passed then all remaining non-option "
4600 "arguments are retrieved via a server @emph{INQUIRE}."
4601 "\n"
4602 "@xref{Target Attribute}, for details about this special attribute."
4605 new_command("XPATH", 0, 1, xpath_command, _(
4606 "XPATH [--inquire] <expression>[<TAB>[value]]\n"
4607 "Evaluates an XPath @var{expression}. If no @var{value} argument is "
4608 "specified, it is assumed the expression is a request to return a result. "
4609 "Otherwise, the result is set to the @var{value} argument and the document is "
4610 "updated. If there is no @var{value} after the @key{TAB} character, the value "
4611 "is assumed to be empty and the document is updated. For example:"
4612 "@sp 1\n"
4613 "@example\n"
4614 "XPATH //element[@@_name='password']@key{TAB}\n"
4615 "@end example\n"
4616 "@sp 1"
4617 "would clear the content of all @code{password} elements in the data file "
4618 "while leaving off the trailing @key{TAB} would return all @code{password} "
4619 "elements in @abbr{XML} format."
4620 "\n"
4621 "When the @option{--inquire} option is passed then all remaining non-option "
4622 "arguments are retrieved via a server @emph{INQUIRE}."
4623 "\n"
4624 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
4625 "expression syntax."
4628 new_command("XPATHATTR", 0, 1, xpathattr_command, _(
4629 "XPATHATTR [--inquire] SET|DELETE <name> <expression>[<TAB>[<value>]]\n"
4630 "Like the @code{XPATH} command (@pxref{XPATH}) but operates on element "
4631 "attributes and does not return a result. For the @var{SET} operation the "
4632 "@var{value} is optional but the field is required. If not specified then "
4633 "the attribute value will be empty. For example:"
4634 "@sp 1"
4635 "@example\n"
4636 "XPATHATTR SET password //element[@@_name='password']@key{TAB}\n"
4637 "@end example\n"
4638 "@sp 1"
4639 "would create an @code{password} attribute for each @code{password} element "
4640 "found in the document. The attribute value will be empty but still exist."
4641 "\n"
4642 "When the @option{--inquire} option is passed then all remaining non-option "
4643 "arguments are retrieved via a server @emph{INQUIRE}."
4644 "\n"
4645 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
4646 "expression syntax."
4649 new_command("IMPORT", 0, 1, import_command, _(
4650 "IMPORT [--root [!]element[<TAB>[!]child[..]]] <content>\n"
4651 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
4652 "\n"
4653 "Like the @code{STORE} command (@pxref{STORE}), but the @var{content} "
4654 "argument is raw @abbr{XML} data. The content is created as a child of "
4655 "the element path specified with the @option{--root} option or at the "
4656 "document root when not specified. Existing elements of the same name will "
4657 "be overwritten."
4658 "\n"
4659 "The content must begin with an @abbr{XML} element node. @xref{Introduction}, "
4660 "for details."
4663 new_command("DUMP", 0, 1, dump_command, _(
4664 "DUMP\n"
4665 "Shows the in memory @abbr{XML} document with indenting. @xref{XPATH}, for "
4666 "dumping a specific node."
4669 new_command("LOCK", 0, 0, lock_command, _(
4670 "LOCK\n"
4671 "Locks the mutex associated with the opened file. This prevents other clients "
4672 "from sending commands to the same opened file until the client "
4673 "that sent this command either disconnects or sends the @code{UNLOCK} "
4674 "command. @xref{UNLOCK}."
4677 new_command("UNLOCK", 1, 0, unlock_command, _(
4678 "UNLOCK\n"
4679 "Unlocks the file mutex which was locked with the @code{LOCK} command or "
4680 "a commands' @option{--lock} option (@pxref{LOCK}, @pxref{OPEN}, "
4681 "@pxref{ISCACHED})."
4684 new_command("GETCONFIG", 1, 1, getconfig_command, _(
4685 "GETCONFIG [filename] <parameter>\n"
4686 "Returns the value of a @command{pwmd} configuration @var{parameter} with a "
4687 "data response. If no file has been opened then the value for @var{filename} "
4688 "or the default from the @samp{global} section will be returned. If a file "
4689 "has been opened and no @var{filename} is specified, a value previously "
4690 "set with the @code{OPTION} command (@pxref{OPTION}) will be returned."
4693 new_command("OPTION", 1, 1, option_command, _(
4694 "OPTION <NAME>=<VALUE>\n"
4695 "Sets a client option @var{name} to @var{value}. The value for an option is "
4696 "kept for the duration of the connection."
4697 "\n"
4698 "@table @asis\n"
4699 "@item DISABLE-PINENTRY\n"
4700 " Disable use of @command{pinentry} for passphrase retrieval. When set, a "
4701 " server inquire is sent to the client to obtain the passphrase. This option "
4702 " may be set as needed before the @pxref{OPEN}, @pxref{PASSWD}, and "
4703 " @pxref{SAVE} commands."
4704 "\n"
4705 "@item TTYNAME\n"
4706 " Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4707 "\n"
4708 "@item TTYTYPE\n"
4709 " Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4710 "\n"
4711 "@item DISPLAY\n"
4712 " Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4713 "\n"
4714 "@item PINENTRY-DESC\n"
4715 " Sets the description string of the @command{gpg-agent} and @command{pinentry} dialog."
4716 "\n"
4717 "@item PINENTRY-TITLE\n"
4718 " Sets the title string of the @command{gpg-agent} and @command{pinentry} dialog."
4719 "\n"
4720 "@item PINENTRY-PROMPT\n"
4721 " Sets the prompt string of the @command{gpg-agent} and @command{pinentry} dialog."
4722 "\n"
4723 "@item LC-CTYPE\n"
4724 " Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4725 "\n"
4726 "@item LC-MESSAGES\n"
4727 " Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4728 "\n"
4729 "@item NAME\n"
4730 " Associates the thread ID of the connection with the specified textual "
4731 "representation. Useful for debugging log messages."
4732 "\n"
4733 "@item LOCK-TIMEOUT\n"
4734 " When not @code{0}, the duration in tenths of a second to wait for the file "
4735 "mutex which has been locked by another thread to be released before returning "
4736 "an error. When @code{-1}, then an error will be returned immediately."
4737 "@end table\n"
4740 new_command("LS", 1, 1, ls_command, _(
4741 "LS\n"
4742 "Lists the available data files stored in the data directory "
4743 "(@file{~/.pwmd/data}). The result is a newline separated list of filenames."
4746 new_command("RESET", 1, 1, NULL, _(
4747 "RESET\n"
4748 "Closes the currently opened file but keeps any previously set client options."
4751 new_command("NOP", 1, 1, NULL, _(
4752 "NOP\n"
4753 "Does nothing. Always returns successfully."
4756 /* !END-HELP-TEXT! */
4757 new_command ("CANCEL", 1, 1, NULL, NULL);
4758 new_command ("END", 1, 1, NULL, NULL);
4759 new_command ("BYE", 1, 1, NULL, NULL);
4761 int i;
4762 for (i = 0; command_table[i]; i++);
4763 qsort (command_table, i - 1, sizeof (struct command_table_s *),
4764 sort_commands);
4767 gpg_error_t
4768 register_commands (assuan_context_t ctx)
4770 int i = 0, rc;
4772 for (; command_table[i]; i++)
4774 if (!command_table[i]->handler)
4775 continue;
4777 rc = assuan_register_command (ctx, command_table[i]->name,
4778 command_table[i]->handler,
4779 command_table[i]->help);
4780 if (rc)
4781 return rc;
4784 rc = assuan_register_bye_notify (ctx, bye_notify);
4785 if (rc)
4786 return rc;
4788 rc = assuan_register_reset_notify (ctx, reset_notify);
4789 if (rc)
4790 return rc;
4792 rc = assuan_register_pre_cmd_notify (ctx, command_startup);
4793 if (rc)
4794 return rc;
4796 return assuan_register_post_cmd_notify (ctx, command_finalize);