Fix some memory leaks.
[pwmd.git] / src / commands.c
blobf7ed066aea5eb13f399038031a78560835f8da98
1 /*
2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013
3 Ben Kibbey <bjk@luxsci.net>
5 This file is part of pwmd.
7 Pwmd is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 2 of the License, or
10 (at your option) any later version.
12 Pwmd is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
20 #ifdef HAVE_CONFIG_H
21 #include <config.h>
22 #endif
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <unistd.h>
27 #include <err.h>
28 #include <errno.h>
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <fcntl.h>
32 #include <ctype.h>
33 #include <dirent.h>
34 #include <pthread.h>
35 #include <stdint.h>
37 #ifdef WITH_LIBACL
38 #include <sys/acl.h>
39 #endif
41 #include "pwmd-error.h"
42 #include <gcrypt.h>
44 #include "mem.h"
45 #include "xml.h"
46 #include "util-misc.h"
47 #include "common.h"
48 #include "rcfile.h"
49 #include "cache.h"
50 #include "commands.h"
51 #include "mutex.h"
52 #include "crypto.h"
53 #include "pinentry.h"
55 /* Flags needed to be retained for a client across commands. */
56 #define FLAG_NEW 0x0001
57 #define FLAG_HAS_LOCK 0x0002
58 #define FLAG_LOCK_CMD 0x0004
59 #define FLAG_NO_PINENTRY 0x0008
60 #define FLAG_OPEN 0x0010
61 #define FLAG_KEEP_LOCK 0x0020
63 /* These are command option flags. */
64 #define OPT_INQUIRE 0x0001
65 #define OPT_NO_PASSPHRASE 0x0002
66 #define OPT_RESET 0x0004
67 #define OPT_LIST_RECURSE 0x0008
68 #define OPT_LIST_VERBOSE 0x0010
69 #define OPT_LOCK 0x0020
70 #define OPT_LOCK_ON_OPEN 0x0040
71 #define OPT_SIGN 0x0080
72 #define OPT_LIST_ALL 0x0100
73 #define OPT_LIST_WITH_TARGET 0x0200
74 #define OPT_DATA 0x0400
75 #define OPT_NO_AGENT 0x0800
77 #ifdef WITH_AGENT
78 /* The GETCONFIG command, for example, may fail because pwmd lost the
79 * gpg-agent connection. Update the recovered agent ctx. */
80 #define UPDATE_AGENT_CTX(client, crypto) do { \
81 if (crypto && crypto->agent && crypto->agent->did_restart \
82 && client->crypto && client->crypto->agent \
83 && client->crypto->agent->ctx && \
84 crypto->agent->ctx != client->crypto->agent->ctx) \
85 { \
86 client->crypto->agent->ctx = crypto->agent->ctx; \
87 crypto->agent->ctx = NULL; \
88 } \
89 } while (0)
90 #else
91 #define UPDATE_AGENT_CTX(client, crypto)
92 #endif
94 struct command_table_s
96 const char *name;
97 gpg_error_t (*handler) (assuan_context_t, char *line);
98 const char *help;
99 int ignore_startup;
100 int unlock; // unlock the file mutex after validating the checksum
103 static struct command_table_s **command_table;
105 static gpg_error_t do_lock (struct client_s *client, int add);
106 static gpg_error_t validate_checksum (struct client_s *,
107 struct cache_data_s *);
108 static gpg_error_t update_checksum (struct client_s *client);
110 static gpg_error_t
111 unlock_file_mutex (struct client_s *client, int remove)
113 gpg_error_t rc = 0;
115 // OPEN: keep the lock for the same file being reopened.
116 if (client->flags & FLAG_KEEP_LOCK && client->flags & FLAG_HAS_LOCK)
117 return 0;
119 if (!(client->flags & FLAG_HAS_LOCK))
120 return GPG_ERR_NOT_LOCKED;
122 rc = cache_unlock_mutex (client->md5file, remove);
123 if (rc)
124 rc = GPG_ERR_INV_STATE;
125 else
126 client->flags &= ~(FLAG_HAS_LOCK | FLAG_LOCK_CMD);
128 return rc;
131 static gpg_error_t
132 lock_file_mutex (struct client_s *client, int add)
134 gpg_error_t rc = 0;
135 int timeout = config_get_integer (client->filename, "cache_timeout");
137 if (client->flags & FLAG_HAS_LOCK)
138 return 0;
140 rc = cache_lock_mutex (client->ctx, client->md5file,
141 client->lock_timeout, add, timeout);
142 if (!rc)
143 client->flags |= FLAG_HAS_LOCK;
145 return rc;
148 static gpg_error_t
149 file_modified (struct client_s *client, struct command_table_s *cmd)
151 gpg_error_t rc = 0;
153 if (!(client->flags & FLAG_OPEN))
154 return GPG_ERR_INV_STATE;
156 rc = lock_file_mutex (client, 0);
157 if (!rc || rc == GPG_ERR_NO_DATA)
159 rc = validate_checksum (client, NULL);
160 if (gpg_err_code (rc) == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
161 rc = 0;
162 else if (rc)
163 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
166 if ((cmd->unlock && !(client->flags & FLAG_HAS_LOCK)) || rc)
167 unlock_file_mutex (client, 0);
169 return rc;
172 static gpg_error_t
173 parse_xml (assuan_context_t ctx, int new)
175 struct client_s *client = assuan_get_pointer (ctx);
176 int cached = client->doc != NULL;
178 if (new)
180 client->doc = new_document ();
181 if (client->doc)
183 xmlChar *result;
184 int len;
186 xmlDocDumpFormatMemory (client->doc, &result, &len, 0);
187 client->crypto->plaintext = result;
188 client->crypto->plaintext_len = len;
189 if (!client->crypto->plaintext)
191 xmlFreeDoc (client->doc);
192 client->doc = NULL;
196 else if (!cached)
197 client->doc = parse_doc ((char *) client->crypto->plaintext,
198 client->crypto->plaintext_len);
200 return !client->doc ? GPG_ERR_ENOMEM : 0;
203 static void
204 free_client (struct client_s *client)
206 if (client->doc)
207 xmlFreeDoc (client->doc);
209 xfree (client->crc);
210 xfree (client->filename);
211 xfree (client->last_error);
213 if (client->crypto)
215 cleanup_crypto_stage2 (client->crypto);
216 if (client->crypto->pkey_sexp)
217 gcry_sexp_release (client->crypto->pkey_sexp);
219 client->crypto->pkey_sexp = NULL;
220 memset (client->crypto->sign_grip, 0,
221 sizeof (client->crypto->sign_grip));
222 memset (client->crypto->grip, 0, sizeof(client->crypto->grip));
225 if (client->xml_error)
226 xmlResetError (client->xml_error);
229 void
230 cleanup_client (struct client_s *client)
232 assuan_context_t ctx = client->ctx;
233 struct client_thread_s *thd = client->thd;
234 struct crypto_s *crypto = client->crypto;
235 long lock_timeout = client->lock_timeout;
236 int no_pinentry = (client->flags & FLAG_NO_PINENTRY);
237 struct pinentry_option_s pin_opts;
238 #ifdef WITH_AGENT
239 struct pinentry_option_s agent_pin_opts;
241 if (crypto && crypto->agent)
242 memcpy (&agent_pin_opts, &crypto->agent->pinentry_opts,
243 sizeof(struct pinentry_option_s));
244 #endif
246 memcpy (&pin_opts, &client->pinentry_opts, sizeof(struct pinentry_option_s));
247 unlock_file_mutex (client, client->flags & FLAG_NEW);
248 free_client (client);
249 memset (client, 0, sizeof (struct client_s));
250 client->crypto = crypto;
251 client->ctx = ctx;
252 client->thd = thd;
253 client->lock_timeout = lock_timeout;
254 memcpy (&client->pinentry_opts, &pin_opts, sizeof(struct pinentry_option_s));
255 client->flags |= no_pinentry ? FLAG_NO_PINENTRY : 0;
256 #ifdef WITH_AGENT
257 if (crypto && crypto->agent)
258 memcpy (&crypto->agent->pinentry_opts, &agent_pin_opts,
259 sizeof(struct pinentry_option_s));
260 #endif
263 static gpg_error_t
264 open_finalize (assuan_context_t ctx, char *key, size_t keylen)
266 struct client_s *client = assuan_get_pointer (ctx);
267 gpg_error_t rc = 0;
268 struct cache_data_s *cdata = cache_get_data (client->md5file);
269 int cached = 0, keyarg = key ? 1 : 0;
270 size_t keysize;
271 unsigned char *salted_key = NULL;
272 int algo;
273 int pin_try = 1;
274 int pin_tries = 3;
275 char *pin_title = client->pinentry_opts.title;
277 client->crypto->filename = str_dup (client->filename);
278 if (cdata || client->flags & FLAG_NEW)
280 if (cdata && !(client->flags & FLAG_NEW))
282 rc = decrypt_cache (client->crypto, cdata->doc, cdata->doclen);
283 if (rc)
284 return rc;
287 cached = cdata != NULL;
288 goto done;
291 if (!key && !IS_PKI (client->crypto)
292 && !(client->crypto->hdr.flags & PWMD_FLAG_NO_PASSPHRASE))
294 if (client->flags & FLAG_NO_PINENTRY)
296 rc = inquire_passphrase (ctx, "PASSPHRASE", (unsigned char **)&key,
297 &keylen);
298 if (rc)
299 return rc;
301 else
303 client->pinentry_opts.timeout = config_get_integer (client->filename,
304 "pinentry_timeout");
305 pin_again:
306 rc = getpin_common (client->ctx, client->filename, PINENTRY_OPEN,
307 &key, &keylen);
308 if (rc)
309 return rc;
313 if (!IS_PKI (client->crypto))
315 if (client->crypto->hdr.flags & PWMD_FLAG_NO_PASSPHRASE)
317 keylen = 1;
318 key = gcry_malloc (keylen);
319 memset (key, 0, keylen);
322 algo = cipher_to_gcrypt (client->crypto->hdr.flags);
323 rc = hash_key (algo, client->crypto->hdr.salt,
324 sizeof(client->crypto->hdr.salt), key, keylen,
325 (void **)&salted_key, &keysize);
326 if (!keyarg)
327 gcry_free (key);
329 if (!rc)
331 rc = decrypt_data (client->ctx, client->crypto, salted_key, keysize);
332 if (gpg_err_code (rc) == GPG_ERR_BAD_PASSPHRASE
333 && ++pin_try <= pin_tries && !(client->flags & FLAG_NO_PINENTRY))
335 gcry_free (salted_key);
336 salted_key = NULL;
337 key = NULL;
338 keylen = 0;
339 client->pinentry_opts.title = str_asprintf (_ ("Bad passphrase (try %i of %i)"), pin_try, pin_tries);
340 goto pin_again;
344 gcry_free (salted_key);
345 salted_key = NULL;
347 if (client->pinentry_opts.title != pin_title)
348 xfree (client->pinentry_opts.title);
350 client->pinentry_opts.title = pin_title;
351 if (rc)
352 return rc;
354 cdata = xcalloc (1, sizeof (struct cache_data_s));
355 if (!cdata)
356 return GPG_ERR_ENOMEM;
358 cdata->key = salted_key;
359 cdata->keylen = keysize;
361 else
362 rc = decrypt_data (client->ctx, client->crypto, NULL, 0);
364 done:
365 if (!rc)
367 rc = parse_xml (ctx, client->flags & FLAG_NEW);
368 if (!rc)
370 int timeout = config_get_integer (client->filename,
371 "cache_timeout");
373 if (!cached)
375 if (!cdata)
376 cdata = xcalloc (1, sizeof (struct cache_data_s));
378 rc = encrypt_xml (NULL, cache_key, cache_keysize,
379 GCRY_CIPHER_AES, client->crypto->plaintext,
380 client->crypto->plaintext_len, &cdata->doc,
381 &cdata->doclen, &cache_iv, &cache_blocksize,
383 if (!rc && !(client->flags & FLAG_NEW) && IS_PKI (client->crypto))
385 rc = gcry_sexp_build ((gcry_sexp_t *) & cdata->pubkey, NULL,
386 "%S", client->crypto->pkey_sexp);
390 if (cdata->sigkey)
391 gcry_sexp_release (cdata->sigkey);
393 cdata->sigkey = NULL;
394 if (!rc && IS_PKI (client->crypto))
395 rc = gcry_sexp_build ((gcry_sexp_t *) &cdata->sigkey, NULL,
396 "%S", client->crypto->sigpkey_sexp);
398 if (!rc && !cache_add_file (client->md5file,
399 (client->flags & FLAG_NEW)
400 ? NULL
401 : client->crypto->grip, cdata, timeout))
403 if (!cached)
405 free_cache_data_once (cdata);
406 xmlFreeDoc (client->doc);
407 client->doc = NULL;
409 rc = GPG_ERR_ENOMEM;
412 if (!rc)
413 client->flags |= FLAG_OPEN;
417 if (!rc)
418 update_checksum (client);
420 if (!rc && (client->opts & OPT_LOCK_ON_OPEN))
421 rc = do_lock (client, 0);
423 return rc;
426 static void
427 req_cleanup (void *arg)
429 if (!arg)
430 return;
432 strv_free ((char **) arg);
435 static gpg_error_t
436 parse_open_opt_lock (void *data, void *value)
438 struct client_s *client = data;
440 client->opts |= OPT_LOCK_ON_OPEN;
441 return 0;
444 static gpg_error_t
445 parse_opt_inquire (void *data, void *value)
447 struct client_s *client = data;
449 (void) value;
450 client->opts |= OPT_INQUIRE;
451 return 0;
454 static gpg_error_t
455 update_checksum (struct client_s *client)
457 unsigned char *crc;
458 size_t len;
459 struct cache_data_s *cdata;
460 gpg_error_t rc = get_checksum (client->filename, &crc, &len);
462 if (rc)
463 return rc;
465 xfree (client->crc);
466 client->crc = crc;
467 cdata = cache_get_data (client->md5file);
468 if (cdata)
470 xfree (cdata->crc);
471 cdata->crc = xmalloc (len);
472 memcpy (cdata->crc, crc, len);
475 return 0;
478 static gpg_error_t
479 validate_checksum (struct client_s *client, struct cache_data_s *cdata)
481 unsigned char *crc;
482 size_t len;
483 gpg_error_t rc;
484 int n = 0;
486 if (cdata && !cdata->crc)
487 return GPG_ERR_CHECKSUM;
489 rc = get_checksum (client->filename, &crc, &len);
490 if (rc)
491 return rc;
493 if (cdata)
494 n = memcmp (cdata->crc, crc, len);
495 else if (client->crc)
496 n = memcmp (client->crc, crc, len);
498 xfree (crc);
499 return n ? GPG_ERR_CHECKSUM : 0;
502 static gpg_error_t
503 do_open (assuan_context_t ctx, const char *filename, const char *password)
505 struct client_s *client = assuan_get_pointer (ctx);
506 struct cache_data_s *cdata;
507 gpg_error_t rc = 0;
508 int done = 0;
510 if (!valid_filename (filename))
511 return GPG_ERR_INV_VALUE;
513 gcry_md_hash_buffer (GCRY_MD_MD5, client->md5file, filename,
514 strlen (filename));
515 client->filename = str_dup (filename);
516 if (!client->filename)
517 return GPG_ERR_ENOMEM;
519 // Cached document?
520 cdata = cache_get_data (client->md5file);
521 if (cdata && cdata->doc)
523 int defer = 0;
525 /* This will check that the key is cached in the agent which needs to
526 * be determined for files that share a keygrip. */
527 if (!rc)
529 rc = cache_iscached (client->filename, &defer);
530 if ((!rc || rc == GPG_ERR_ENOENT) && defer)
531 rc = GPG_ERR_KEY_EXPIRED;
534 if (!rc && !(client->flags & FLAG_NEW))
535 rc = validate_checksum (client, cdata);
537 #ifdef WITH_GNUTLS
538 if (!rc && client->thd->remote
539 && config_get_boolean (client->filename, "tcp_require_key"))
540 rc = GPG_ERR_KEY_EXPIRED;
541 #endif
543 if (!rc && !password)
545 rc = read_data_header (client->filename, &client->crypto->hdr,
546 NULL, NULL);
547 if (!rc)
549 if (IS_PKI (client->crypto))
551 gcry_sexp_build (&client->crypto->pkey_sexp, NULL, "%S",
552 cdata->pubkey);
553 gcry_pk_get_keygrip (client->crypto->pkey_sexp,
554 client->crypto->grip);
555 gcry_sexp_build (&client->crypto->sigpkey_sexp, NULL, "%S",
556 cdata->sigkey);
557 gcry_pk_get_keygrip (client->crypto->sigpkey_sexp,
558 client->crypto->sign_grip);
561 if (!rc)
563 rc = open_finalize (ctx, NULL, 0);
564 done = 1;
569 /* There was an error accessing the file so clear the cache entry. The
570 * real error will be returned from read_data_file() since the file
571 * may have only disappeared. */
572 if (!done)
574 log_write ("%s: %s", filename, pwmd_strerror (rc));
575 rc = cache_clear (client->md5file);
576 send_status_all (STATUS_CACHE, NULL);
580 if (done || rc)
581 return rc;
583 rc = read_data_file (client->filename, client->crypto);
584 if (rc)
586 if (gpg_err_source (rc) != GPG_ERR_SOURCE_DEFAULT ||
587 gpg_err_code (rc) != GPG_ERR_ENOENT)
589 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
590 return rc;
593 client->flags |= FLAG_NEW;
594 memset (client->crypto->grip, 0, sizeof (client->crypto->grip));
595 memset (client->crypto->sign_grip, 0,
596 sizeof (client->crypto->sign_grip));
597 rc = open_finalize (ctx, NULL, 0);
598 return rc;
601 if (password && IS_PKI (client->crypto))
603 #ifdef WITH_AGENT
604 rc = set_agent_passphrase (client->crypto, password, strlen (password));
605 if (rc)
606 return rc;
607 #endif
610 rc = open_finalize (ctx, (char *)password, password ? strlen (password) : 0);
611 return rc;
614 static gpg_error_t
615 open_command (assuan_context_t ctx, char *line)
617 gpg_error_t rc;
618 struct client_s *client = assuan_get_pointer (ctx);
619 char **req, *password = NULL, *filename;
620 unsigned char md5file[16];
621 int same_file = 0;
622 struct argv_s *args[] = {
623 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_open_opt_lock},
624 NULL
627 rc = parse_options (&line, args, client);
628 if (rc)
629 return send_error (ctx, rc);
631 req = str_split (line, " ", 2);
632 if (!req)
633 return send_error (ctx, GPG_ERR_SYNTAX);
635 #ifdef WITH_GNUTLS
636 if (client->thd->remote)
638 rc = tls_validate_access (client, req[0]);
639 if (rc)
641 if (rc == GPG_ERR_INV_USER_ID)
642 log_write (_("client validation failed for file '%s'"), req[0]);
643 strv_free (req);
644 return send_error (ctx, rc);
647 /* Remote pinentries are not supported. */
648 client->flags |= FLAG_NO_PINENTRY;
650 else
652 #endif
653 assuan_peercred_t peer;
654 rc = do_validate_peer (ctx, req[0], &peer);
655 if (rc)
657 strv_free (req);
658 return send_error (ctx, rc);
660 #ifdef WITH_GNUTLS
662 #endif
664 pthread_cleanup_push (req_cleanup, req);
665 filename = req[0];
666 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
667 /* This client may have locked a different file with ISCACHED --lock than
668 * the current filename. This will remove that lock. */
669 same_file = !memcmp (md5file, client->md5file, 16) ? 1 : 0;
670 if (client->flags & FLAG_OPEN ||
671 (client->flags & FLAG_HAS_LOCK && !same_file))
673 typeof (client->opts) opts = client->opts;
674 typeof (client->flags) flags = client->flags;
676 if (same_file)
677 client->flags |= FLAG_KEEP_LOCK;
679 cleanup_client (client);
680 client->opts = opts;
681 client->flags |= flags;
682 client->flags &= ~(FLAG_LOCK_CMD);
683 if (!same_file)
684 client->flags &= ~(FLAG_HAS_LOCK | FLAG_NEW);
687 /* Need to lock the mutex here because file_modified() cannot without
688 * knowing the filename. */
689 memcpy (client->md5file, md5file, 16);
690 rc = lock_file_mutex (client, 1);
691 if (!rc)
693 password = req[1] && *req[1] ? req[1] : NULL;
694 #ifdef WITH_AGENT
695 if (IS_PKI (client->crypto))
696 rc = set_pinentry_mode (client->crypto->agent,
697 (client->flags & FLAG_NO_PINENTRY) ? "loopback"
698 : "ask");
699 #endif
700 if (!rc)
702 rc = do_open (ctx, filename, password);
703 if (rc)
704 cleanup_client (client);
706 cleanup_crypto_stage1 (client->crypto);
710 pthread_cleanup_pop (1);
712 if (!rc && client->flags & FLAG_NEW)
713 rc = send_status (ctx, STATUS_NEWFILE, NULL);
715 #ifdef WITH_AGENT
716 (void) kill_scd (client->crypto->agent);
717 #endif
718 return send_error (ctx, rc);
721 static gpg_error_t
722 parse_opt_no_passphrase (void *data, void *value)
724 struct client_s *client = data;
726 (void) value;
727 client->opts |= OPT_NO_PASSPHRASE;
728 return 0;
731 static gpg_error_t
732 parse_save_opt_no_agent (void *data, void *value)
734 struct client_s *client = data;
736 client->opts |= OPT_NO_AGENT;
737 return 0;
740 static gpg_error_t
741 parse_save_opt_cipher (void *data, void *value)
743 struct client_s *client = data;
744 int algo = cipher_string_to_gcrypt ((char *) value);
745 file_header_t *hdr = &client->crypto->save.hdr;
747 if (algo == -1)
748 return GPG_ERR_INV_VALUE;
750 hdr->flags = set_cipher_flag (hdr->flags, algo);
751 return 0;
754 static gpg_error_t
755 parse_save_opt_keygrip (void *data, void *value)
757 struct client_s *client = data;
759 if (!IS_PKI (client->crypto))
760 return GPG_ERR_INV_ARG;
762 #ifdef WITH_AGENT
763 if (client->crypto->save.pkey)
764 gcry_sexp_release (client->crypto->save.pkey);
766 client->crypto->save.pkey = NULL;
767 return get_pubkey (client->crypto, value, &client->crypto->save.pkey);
768 #else
769 return GPG_ERR_INV_ARG;
770 #endif
773 static gpg_error_t
774 parse_save_opt_sign_keygrip (void *data, void *value)
776 struct client_s *client = data;
778 if (!IS_PKI (client->crypto))
779 return GPG_ERR_INV_ARG;
781 #ifdef WITH_AGENT
782 if (client->crypto->save.sigpkey)
783 gcry_sexp_release (client->crypto->save.sigpkey);
785 client->crypto->save.sigpkey = NULL;
786 return get_pubkey (client->crypto, value, &client->crypto->save.sigpkey);
787 #else
788 return GPG_ERR_INV_ARG;
789 #endif
792 static gpg_error_t
793 parse_opt_s2k_count (void *data, void *value)
795 struct client_s *client = data;
796 char *v = value;
798 if (!v || !*v)
799 return GPG_ERR_INV_VALUE;
801 client->crypto->save.s2k_count = strtoul (v, NULL, 10);
802 return 0;
805 static gpg_error_t
806 parse_save_opt_iterations (void *data, void *value)
808 struct client_s *client = data;
809 char *v = value, *p;
810 uint64_t n;
812 if (!v || !*v)
813 return GPG_ERR_INV_VALUE;
815 errno = 0;
816 n = strtoull (v, &p, 10);
817 if (n == UINT64_MAX && errno)
818 return gpg_error_from_errno (errno);
819 else if (p && *p)
820 return GPG_ERR_INV_VALUE;
822 client->crypto->save.hdr.iterations = n;
823 return 0;
826 static gpg_error_t
827 save_finalize (assuan_context_t ctx)
829 struct client_s *client = assuan_get_pointer (ctx);
830 gpg_error_t rc = 0;
831 xmlChar *xmlbuf = NULL;
832 int xmlbuflen;
833 void *key = NULL;
834 size_t keylen = 0;
836 xmlDocDumpFormatMemory (client->doc, &xmlbuf, &xmlbuflen, 0);
837 if (!xmlbuf)
838 return GPG_ERR_ENOMEM;
840 pthread_cleanup_push (xmlFree, xmlbuf);
842 if (!use_agent || ((client->flags & FLAG_NEW)
843 && (client->opts & OPT_NO_AGENT))
844 || !(client->crypto->hdr.flags & PWMD_FLAG_PKI))
846 rc = export_common (ctx, client->flags & FLAG_NO_PINENTRY,
847 client->crypto, xmlbuf, xmlbuflen, client->filename,
848 NULL, &key, &keylen, 1, 1,
849 (client->opts & OPT_NO_PASSPHRASE));
851 #ifdef WITH_AGENT
852 else
854 gcry_sexp_t pubkey = client->crypto->save.pkey;
855 gcry_sexp_t sigkey = client->crypto->save.sigpkey;
857 if (!pubkey)
858 pubkey = client->crypto->pkey_sexp;
860 if (!sigkey)
862 sigkey = client->crypto->sigpkey_sexp;
863 if (!sigkey)
865 gcry_sexp_build (&client->crypto->save.sigpkey, 0, "%S", pubkey);
866 sigkey = client->crypto->save.sigpkey;
870 rc = encrypt_data_file (client->ctx, client->crypto, pubkey, sigkey,
871 client->filename, xmlbuf, xmlbuflen);
872 if (pubkey == client->crypto->save.pkey)
874 if (!rc)
876 gcry_sexp_release (client->crypto->pkey_sexp);
877 client->crypto->pkey_sexp = client->crypto->save.pkey;
878 gcry_pk_get_keygrip (client->crypto->pkey_sexp,
879 client->crypto->grip);
881 else
882 gcry_sexp_release (pubkey);
884 client->crypto->save.pkey = NULL;
887 if (!rc)
888 gcry_pk_get_keygrip (sigkey, client->crypto->sign_grip);
890 if (sigkey == client->crypto->save.sigpkey)
892 if (!rc)
894 if (client->crypto->sigpkey_sexp)
895 gcry_sexp_release (client->crypto->sigpkey_sexp);
897 client->crypto->sigpkey_sexp = client->crypto->save.sigpkey;
898 gcry_pk_get_keygrip (client->crypto->sigpkey_sexp,
899 client->crypto->sign_grip);
901 else
902 gcry_sexp_release (sigkey);
904 client->crypto->save.sigpkey = NULL;
907 #endif
909 if (!rc)
911 int cached;
913 rc = save_common (client->filename, client->crypto, xmlbuf, xmlbuflen,
914 key, keylen, &cached, client->opts & OPT_NO_AGENT);
915 if (rc)
916 gcry_free (key);
918 if (!rc && (!cached || (client->flags & FLAG_NEW)))
919 send_status_all (STATUS_CACHE, NULL);
921 if (!rc)
923 rc = update_checksum (client);
924 client->flags &= ~(FLAG_NEW);
928 pthread_cleanup_pop (1); // xmlFree
929 return rc;
932 static gpg_error_t
933 parse_opt_reset (void *data, void *value)
935 struct client_s *client = data;
937 (void) value;
938 client->opts |= OPT_RESET;
939 return 0;
942 static gpg_error_t
943 save_command (assuan_context_t ctx, char *line)
945 struct client_s *client = assuan_get_pointer (ctx);
946 gpg_error_t rc;
947 struct stat st;
948 struct argv_s *args[] = {
949 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG,
950 parse_opt_no_passphrase},
951 &(struct argv_s) {"cipher", OPTION_TYPE_ARG, parse_save_opt_cipher},
952 &(struct argv_s) {"inquire-keyparam", OPTION_TYPE_NOARG,
953 parse_opt_inquire},
954 &(struct argv_s) {"keygrip", OPTION_TYPE_ARG, parse_save_opt_keygrip},
955 &(struct argv_s) {"sign-keygrip", OPTION_TYPE_ARG,
956 parse_save_opt_sign_keygrip},
957 &(struct argv_s) {"s2k-count", OPTION_TYPE_ARG, parse_opt_s2k_count},
958 &(struct argv_s) {"reset", OPTION_TYPE_NOARG, parse_opt_reset},
959 &(struct argv_s) {"cipher-iterations", OPTION_TYPE_ARG,
960 parse_save_opt_iterations},
961 &(struct argv_s) {"no-agent", OPTION_TYPE_NOARG,
962 parse_save_opt_no_agent},
963 NULL
966 cleanup_save (&client->crypto->save);
967 memcpy (&client->crypto->save.hdr, &client->crypto->hdr,
968 sizeof (file_header_t));
969 client->crypto->save.s2k_count =
970 config_get_ulong (client->filename, "s2k_count");
972 if (client->flags & FLAG_NEW)
973 client->crypto->save.hdr.iterations =
974 config_get_ulonglong (client->filename, "cipher_iterations");
976 rc = parse_options (&line, args, client);
977 if (rc)
978 return send_error (ctx, rc);
980 if (!(client->flags & FLAG_NEW))
981 client->opts &= ~OPT_NO_AGENT;
982 else if (client->opts & OPT_NO_AGENT)
984 client->crypto->save.hdr.flags &= ~PWMD_FLAG_PKI;
985 client->crypto->hdr.flags &= ~PWMD_FLAG_PKI;
988 if ((client->opts & OPT_NO_PASSPHRASE) && !(client->flags & FLAG_NEW)
989 && !(client->opts & OPT_INQUIRE))
990 return send_error (ctx, GPG_ERR_WRONG_KEY_USAGE);
992 if (lstat (client->filename, &st) == -1 && errno != ENOENT)
993 return send_error (ctx, gpg_error_from_errno (errno));
995 if (errno != ENOENT && !S_ISREG (st.st_mode))
997 log_write ("%s: %s", client->filename, pwmd_strerror (GPG_ERR_ENOANO));
998 return send_error (ctx, GPG_ERR_ENOANO);
1001 int defer = 0;
1002 rc = cache_iscached (client->filename, &defer);
1003 if (gpg_err_code (rc) == GPG_ERR_ENOENT && client->flags & FLAG_NEW)
1004 rc = 0;
1005 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
1006 rc = 0;
1008 if ((!rc && defer) || config_get_boolean ("global", "require_save_key"))
1009 client->opts |= OPT_RESET;
1011 if (!rc && (client->opts & OPT_RESET))
1013 rc = cache_clear (client->md5file);
1014 if (rc)
1015 return send_error (ctx, rc);
1017 log_write ("%s: %s", client->filename,
1018 pwmd_strerror (GPG_ERR_KEY_EXPIRED));
1019 send_status_all (STATUS_CACHE, NULL);
1022 if (!rc)
1023 rc = update_element_mtime (xmlDocGetRootElement (client->doc));
1025 if (rc)
1026 return send_error (ctx, rc);
1028 #ifdef WITH_AGENT
1029 if (!rc && use_agent && !client->crypto->save.pkey &&
1030 (client->flags & FLAG_NEW || client->opts & OPT_INQUIRE)
1031 && !(client->opts & OPT_NO_AGENT))
1033 rc = set_pinentry_mode (client->crypto->agent,
1034 (client->flags & FLAG_NO_PINENTRY) ? "loopback"
1035 : "ask");
1037 if (!(client->flags & FLAG_NEW))
1039 struct crypto_s *crypto;
1040 char *key = NULL;
1041 size_t keylen = 0;
1043 /* Wanting to generate a new key. Require the key to open the
1044 current file before proceeding reguardless of the
1045 require_save_key configuration parameter. */
1046 rc = cache_clear (client->md5file);
1047 if (!rc)
1049 rc = init_client_crypto (&crypto);
1050 if (!rc)
1051 crypto->client_ctx = client->ctx;
1054 if (!rc)
1055 rc = decrypt_common (client->ctx, client->opts&OPT_INQUIRE, crypto,
1056 client->filename, &key, &keylen);
1058 xfree (key);
1059 cleanup_crypto (&crypto);
1062 if (!rc)
1063 rc = send_status (client->ctx, STATUS_GENKEY, NULL);
1065 if (!rc)
1067 struct inquire_data_s idata = { 0 };
1068 char *params = client->opts & OPT_INQUIRE
1069 ? NULL : default_key_params (client->crypto);
1071 pthread_cleanup_push (xfree, params);
1072 idata.crypto = client->crypto;
1074 if (params)
1076 idata.line = params;
1077 idata.len = strlen (params);
1079 else
1080 idata.preset = 1;
1082 client->crypto->agent->inquire_data = &idata;
1083 client->crypto->agent->inquire_cb = NULL;
1084 rc = generate_key (client->crypto, params,
1085 (client->opts & OPT_NO_PASSPHRASE), 1);
1086 pthread_cleanup_pop (1);
1089 #endif
1091 if (!rc)
1092 rc = save_finalize (ctx);
1094 cleanup_crypto_stage1 (client->crypto);
1095 #ifdef WITH_AGENT
1096 (void) kill_scd (client->crypto->agent);
1097 #endif
1098 return send_error (ctx, rc);
1101 static gpg_error_t
1102 do_delete (assuan_context_t ctx, char *line)
1104 struct client_s *client = assuan_get_pointer (ctx);
1105 gpg_error_t rc;
1106 char **req;
1107 xmlNodePtr n;
1109 if (strchr (line, '\t'))
1110 req = str_split (line, "\t", 0);
1111 else
1112 req = str_split (line, " ", 0);
1114 if (!req || !*req)
1115 return GPG_ERR_SYNTAX;
1117 n = find_root_element (client->doc, &req, &rc, NULL, 0, 0);
1118 if (!n)
1120 strv_free (req);
1121 return rc;
1125 * No sub-node defined. Remove the entire node (root element).
1127 if (!req[1])
1129 if (n)
1131 rc = unlink_node (n);
1132 xmlFreeNode (n);
1135 strv_free (req);
1136 return rc;
1140 find_elements (client->doc, n->children, req + 1, &rc, NULL, NULL, NULL,
1141 0, 0, NULL, 0);
1142 strv_free (req);
1143 if (!n)
1144 return rc;
1146 if (n)
1148 rc = unlink_node (n);
1149 xmlFreeNode (n);
1152 return rc;
1155 static gpg_error_t
1156 delete_command (assuan_context_t ctx, char *line)
1158 struct client_s *client = assuan_get_pointer (ctx);
1159 gpg_error_t rc;
1160 struct argv_s *args[] = {
1161 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1162 NULL
1165 rc = parse_options (&line, args, client);
1166 if (rc)
1167 return send_error (ctx, rc);
1169 if (client->opts & OPT_INQUIRE)
1171 unsigned char *result;
1172 size_t len;
1174 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1175 if (rc)
1176 return send_error (ctx, rc);
1178 line = (char *) result;
1181 rc = do_delete (ctx, line);
1183 if (client->opts & OPT_INQUIRE)
1184 xfree (line);
1186 return send_error (ctx, rc);
1189 static gpg_error_t
1190 store_command (assuan_context_t ctx, char *line)
1192 struct client_s *client = assuan_get_pointer (ctx);
1193 gpg_error_t rc;
1194 size_t len;
1195 unsigned char *result;
1196 char **req;
1197 xmlNodePtr n, parent;
1198 int has_content;
1199 char *content = NULL;
1201 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1202 if (rc)
1203 return send_error (ctx, rc);
1205 req = str_split ((char *) result, "\t", 0);
1206 xfree (result);
1208 if (!req || !*req)
1209 return send_error (ctx, GPG_ERR_SYNTAX);
1211 len = strv_length (req);
1212 has_content = line[strlen (line) - 1] != '\t' && len > 1;
1213 if (*(req + 1) && !valid_element_path (req, has_content))
1215 strv_free (req);
1216 return send_error (ctx, GPG_ERR_INV_VALUE);
1219 if (has_content || !*req[len - 1])
1221 has_content = 1;
1222 content = req[len - 1];
1223 req[len - 1] = NULL;
1226 again:
1227 n = find_root_element (client->doc, &req, &rc, NULL, 0, 0);
1228 if (rc && rc == GPG_ERR_ELEMENT_NOT_FOUND)
1230 rc = new_root_element (client->doc, *req);
1231 if (rc)
1233 strv_free (req);
1234 return send_error (ctx, GPG_ERR_SYNTAX);
1237 goto again;
1240 if (!n)
1242 strv_free (req);
1243 return send_error (ctx, rc);
1246 parent = n;
1248 if (req[1] && *req[1])
1250 if (!n->children)
1251 parent = create_elements_cb (n, req + 1, &rc, NULL);
1252 else
1253 parent = find_elements (client->doc, n->children, req + 1, &rc,
1254 NULL, NULL, create_elements_cb, 0, 0, NULL,
1258 if (!rc && len > 1)
1260 n = find_text_node (parent->children);
1261 if (n)
1262 xmlNodeSetContent (n, (xmlChar *) content);
1263 else
1264 xmlNodeAddContent (parent, (xmlChar *) content);
1266 update_element_mtime (parent);
1269 xfree (content);
1270 strv_free (req);
1271 return send_error (ctx, rc);
1274 static gpg_error_t
1275 xfer_data (assuan_context_t ctx, const char *line, int total)
1277 int to_send;
1278 int sent = 0;
1279 gpg_error_t rc;
1280 int progress = config_get_integer ("global", "xfer_progress");
1281 int flush = 0;
1283 progress =
1284 progress > 0 ? (progress / ASSUAN_LINELENGTH) * ASSUAN_LINELENGTH : 0;
1285 to_send = total < ASSUAN_LINELENGTH ? total : ASSUAN_LINELENGTH;
1286 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1288 if (rc)
1289 return rc;
1291 again:
1294 if (sent + to_send > total)
1295 to_send = total - sent;
1297 rc = assuan_send_data (ctx, flush ? NULL : (char *) line + sent,
1298 flush ? 0 : to_send);
1299 if (!rc)
1301 sent += flush ? 0 : to_send;
1303 if ((progress && !(sent % progress) && sent != total) ||
1304 (sent == total && flush))
1305 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1307 if (!flush && !rc && sent == total)
1309 flush = 1;
1310 goto again;
1314 while (!rc && sent < total);
1316 return rc;
1319 static gpg_error_t
1320 do_get (assuan_context_t ctx, char *line)
1322 struct client_s *client = assuan_get_pointer (ctx);
1323 gpg_error_t rc;
1324 char **req;
1325 xmlNodePtr n;
1327 req = str_split (line, "\t", 0);
1329 if (!req || !*req)
1331 strv_free (req);
1332 return GPG_ERR_SYNTAX;
1335 n = find_root_element (client->doc, &req, &rc, NULL, 0, 0);
1336 if (!n)
1338 strv_free (req);
1339 return rc;
1342 if (req[1])
1344 find_elements (client->doc, n->children, req + 1, &rc, NULL, NULL, NULL,
1345 0, 0, NULL, 0);
1347 strv_free (req);
1348 if (rc)
1349 return rc;
1351 if (!n || !n->children)
1352 return GPG_ERR_NO_DATA;
1354 n = find_text_node (n->children);
1355 if (!n || !n->content || !*n->content)
1356 return GPG_ERR_NO_DATA;
1358 rc = xfer_data (ctx, (char *) n->content, xmlStrlen (n->content));
1359 return rc;
1362 static gpg_error_t
1363 get_command (assuan_context_t ctx, char *line)
1365 struct client_s *client = assuan_get_pointer (ctx);
1366 gpg_error_t rc;
1367 struct argv_s *args[] = {
1368 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1369 NULL
1372 rc = parse_options (&line, args, client);
1373 if (rc)
1374 return send_error (ctx, rc);
1376 if (client->opts & OPT_INQUIRE)
1378 unsigned char *result;
1379 size_t len;
1381 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1382 if (rc)
1383 return send_error (ctx, rc);
1385 line = (char *) result;
1388 rc = do_get (ctx, line);
1390 if (client->opts & OPT_INQUIRE)
1391 xfree (line);
1393 return send_error (ctx, rc);
1396 static void list_command_cleanup1 (void *arg);
1397 static gpg_error_t
1398 realpath_command (assuan_context_t ctx, char *line)
1400 struct string_s *string = NULL;
1401 gpg_error_t rc;
1402 struct client_s *client = assuan_get_pointer (ctx);
1403 struct argv_s *args[] = {
1404 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1405 NULL
1408 rc = parse_options (&line, args, client);
1409 if (rc)
1410 return send_error (ctx, rc);
1412 if (client->opts & OPT_INQUIRE)
1414 unsigned char *result;
1415 size_t len;
1417 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1418 if (rc)
1419 return send_error (ctx, rc);
1421 line = (char *) result;
1424 rc = build_realpath (client->doc, line, &string);
1425 if (!rc)
1427 pthread_cleanup_push (list_command_cleanup1, string);
1428 rc = xfer_data (ctx, string->str, string->len);
1429 pthread_cleanup_pop (1);
1432 if (client->opts & OPT_INQUIRE)
1433 xfree (line);
1435 return send_error (ctx, rc);
1438 static void
1439 list_command_cleanup1 (void *arg)
1441 if (arg)
1442 string_free ((struct string_s *) arg, 1);
1445 static void
1446 list_command_cleanup2 (void *arg)
1448 struct element_list_s *elements = arg;
1450 if (elements)
1452 if (elements->list)
1454 int total = slist_length (elements->list);
1455 int i;
1457 for (i = 0; i < total; i++)
1459 char *tmp = slist_nth_data (elements->list, i);
1460 xfree (tmp);
1463 slist_free (elements->list);
1466 if (elements->prefix)
1467 xfree (elements->prefix);
1469 if (elements->req)
1470 strv_free (elements->req);
1472 xfree (elements);
1476 static gpg_error_t
1477 parse_list_opt_norecurse (void *data, void *value)
1479 struct client_s *client = data;
1481 client->opts &= ~(OPT_LIST_RECURSE);
1482 return 0;
1485 static gpg_error_t
1486 parse_list_opt_verbose (void *data, void *value)
1488 struct client_s *client = data;
1490 client->opts |= OPT_LIST_VERBOSE;
1491 return 0;
1494 static gpg_error_t
1495 parse_list_opt_target (void *data, void *value)
1497 struct client_s *client = data;
1499 client->opts |= OPT_LIST_WITH_TARGET;
1500 return 0;
1503 static gpg_error_t
1504 parse_list_opt_all (void *data, void *value)
1506 struct client_s *client = data;
1508 client->opts |= OPT_LIST_ALL;
1509 return 0;
1512 static gpg_error_t
1513 list_path_once (struct client_s *client, char *line,
1514 struct element_list_s *elements, struct string_s *result)
1516 gpg_error_t rc;
1518 elements->req = str_split (line, " ", 0);
1519 if (!elements->req)
1520 strv_printf (&elements->req, "%s", line);
1522 rc = create_path_list (client->doc, elements, *elements->req);
1523 if (rc == GPG_ERR_ELOOP && elements->verbose)
1524 rc = 0;
1526 if (!rc)
1528 int total = slist_length (elements->list);
1529 int i;
1531 if (!total)
1532 rc = GPG_ERR_NO_DATA;
1534 if (!rc)
1536 if (!rc)
1538 for (i = 0; i < total; i++)
1540 char *tmp = slist_nth_data (elements->list, i);
1542 string_append_printf (result, "%s%s", tmp,
1543 i + 1 == total ? "" : "\n");
1547 else
1548 rc = GPG_ERR_NO_DATA;
1551 return rc;
1554 static int
1555 has_list_flag (char *path, char *flags)
1557 char *p = path;
1559 while (*p && *++p != ' ');
1561 if (!*p)
1562 return 0;
1564 for (; *p; p++)
1566 char *f;
1568 for (f = flags; *f && *f != ' '; f++)
1570 if (*p == *f)
1571 return 1;
1575 return 0;
1578 static gpg_error_t
1579 do_list (assuan_context_t ctx, char *line)
1581 struct client_s *client = assuan_get_pointer (ctx);
1582 gpg_error_t rc;
1583 struct element_list_s *elements = NULL;
1585 elements = xcalloc (1, sizeof (struct element_list_s));
1586 if (!elements)
1587 return GPG_ERR_ENOMEM;
1589 elements->recurse = client->opts & OPT_LIST_RECURSE;
1590 elements->verbose =
1591 (client->opts & OPT_LIST_VERBOSE) | (client->opts & OPT_LIST_WITH_TARGET);
1592 elements->with_target = client->opts & OPT_LIST_WITH_TARGET;
1594 if (!line || !*line)
1596 struct string_s *str = NULL;
1598 pthread_cleanup_push (list_command_cleanup2, elements);
1599 rc = list_root_elements (client->doc, &str, elements->verbose,
1600 elements->with_target);
1601 pthread_cleanup_pop (1);
1602 pthread_cleanup_push (list_command_cleanup1, str);
1604 if (!rc)
1606 if (client->opts & OPT_LIST_ALL)
1608 char **roots = str_split (str->str, "\n", 0);
1609 char **p;
1611 pthread_cleanup_push (req_cleanup, roots);
1612 string_truncate (str, 0);
1614 for (p = roots; *p; p++)
1616 if (strchr (*p, ' '))
1618 if (has_list_flag (*p, "EO"))
1620 string_append_printf (str, "%s%s", *p,
1621 *(p + 1) ? "\n" : "");
1622 continue;
1626 elements = xcalloc (1, sizeof (struct element_list_s));
1627 if (!elements)
1629 rc = GPG_ERR_ENOMEM;
1630 break;
1633 elements->recurse = client->opts & OPT_LIST_RECURSE;
1634 elements->verbose =
1635 (client->opts & OPT_LIST_VERBOSE) | (client->opts &
1636 OPT_LIST_WITH_TARGET);
1637 elements->with_target = client->opts & OPT_LIST_WITH_TARGET;
1638 pthread_cleanup_push (list_command_cleanup2, elements);
1639 rc = list_path_once (client, *p, elements, str);
1640 pthread_cleanup_pop (1);
1641 if (rc)
1642 break;
1644 if (*(p + 1))
1645 string_append (str, "\n");
1648 pthread_cleanup_pop (1);
1651 if (!rc)
1652 rc = xfer_data (ctx, str->str, str->len);
1655 pthread_cleanup_pop (1);
1656 return rc;
1659 pthread_cleanup_push (list_command_cleanup2, elements);
1660 struct string_s *str = string_new (NULL);
1661 pthread_cleanup_push (list_command_cleanup1, str);
1662 rc = list_path_once (client, line, elements, str);
1663 if (!rc)
1664 rc = xfer_data (ctx, str->str, str->len);
1666 pthread_cleanup_pop (1);
1667 pthread_cleanup_pop (1);
1668 return rc;
1671 static gpg_error_t
1672 list_command (assuan_context_t ctx, char *line)
1674 struct client_s *client = assuan_get_pointer (ctx);
1675 gpg_error_t rc;
1676 struct argv_s *args[] = {
1677 &(struct argv_s) {"no-recurse", OPTION_TYPE_NOARG,
1678 parse_list_opt_norecurse},
1679 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_list_opt_verbose},
1680 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1681 &(struct argv_s) {"with-target", OPTION_TYPE_NOARG,
1682 parse_list_opt_target},
1683 &(struct argv_s) {"all", OPTION_TYPE_NOARG, parse_list_opt_all},
1684 NULL
1687 if (disable_list_and_dump == 1)
1688 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
1690 client->opts |= OPT_LIST_RECURSE;
1691 rc = parse_options (&line, args, client);
1692 if (rc)
1693 return send_error (ctx, rc);
1695 if (client->opts & OPT_LIST_ALL)
1696 client->opts |= OPT_LIST_RECURSE | OPT_LIST_VERBOSE;
1698 if (client->opts & OPT_INQUIRE)
1700 unsigned char *result;
1701 size_t len;
1703 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1704 if (rc)
1705 return send_error (ctx, rc);
1707 line = (char *) result;
1710 rc = do_list (ctx, line);
1712 if (client->opts & OPT_INQUIRE)
1713 xfree (line);
1715 return send_error (ctx, rc);
1719 * req[0] - element path
1721 static gpg_error_t
1722 attribute_list (assuan_context_t ctx, char **req)
1724 struct client_s *client = assuan_get_pointer (ctx);
1725 char **attrlist = NULL;
1726 int i = 0;
1727 char **path = NULL;
1728 xmlAttrPtr a;
1729 xmlNodePtr n, an;
1730 char *line;
1731 gpg_error_t rc;
1733 if (!req || !req[0])
1734 return GPG_ERR_SYNTAX;
1736 if ((path = str_split (req[0], "\t", 0)) == NULL)
1739 * The first argument may be only a root element.
1741 if ((path = str_split (req[0], " ", 0)) == NULL)
1742 return GPG_ERR_SYNTAX;
1745 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
1747 if (!n)
1749 strv_free (path);
1750 return rc;
1753 if (path[1])
1755 n = find_elements (client->doc, n->children, path + 1, &rc,
1756 NULL, NULL, NULL, 0, 0, NULL, 0);
1758 if (!n)
1760 strv_free (path);
1761 return rc;
1765 strv_free (path);
1767 for (a = n->properties; a; a = a->next)
1769 char **pa;
1771 if ((pa = xrealloc (attrlist, (i + 2) * sizeof (char *))) == NULL)
1773 if (attrlist)
1774 strv_free (attrlist);
1776 log_write ("%s(%i): %s", __FILE__, __LINE__,
1777 pwmd_strerror (GPG_ERR_ENOMEM));
1778 return GPG_ERR_ENOMEM;
1781 attrlist = pa;
1782 an = a->children;
1783 attrlist[i] = str_asprintf ("%s %s", (char *) a->name,
1785 && an->content ? (char *) an->content : "");
1787 if (!attrlist[i])
1789 strv_free (attrlist);
1790 log_write ("%s(%i): %s", __FILE__, __LINE__,
1791 pwmd_strerror (GPG_ERR_ENOMEM));
1792 return GPG_ERR_ENOMEM;
1795 attrlist[++i] = NULL;
1798 if (!attrlist)
1799 return GPG_ERR_NO_DATA;
1801 line = strv_join ("\n", attrlist);
1803 if (!line)
1805 log_write ("%s(%i): %s", __FILE__, __LINE__,
1806 pwmd_strerror (GPG_ERR_ENOMEM));
1807 strv_free (attrlist);
1808 return GPG_ERR_ENOMEM;
1811 pthread_cleanup_push (xfree, line);
1812 pthread_cleanup_push (req_cleanup, attrlist);
1813 rc = xfer_data (ctx, line, strlen (line));
1814 pthread_cleanup_pop (1);
1815 pthread_cleanup_pop (1);
1816 return rc;
1820 * req[0] - attribute
1821 * req[1] - element path
1823 static gpg_error_t
1824 attribute_delete (struct client_s *client, char **req)
1826 xmlNodePtr n;
1827 char **path = NULL;
1828 gpg_error_t rc;
1830 if (!req || !req[0] || !req[1])
1831 return GPG_ERR_SYNTAX;
1833 if (!strcmp (req[0], "_name"))
1834 return GPG_ERR_INV_ATTR;
1836 if ((path = str_split (req[1], "\t", 0)) == NULL)
1839 * The first argument may be only a root element.
1841 if ((path = str_split (req[1], " ", 0)) == NULL)
1842 return GPG_ERR_SYNTAX;
1845 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
1846 if (!n)
1847 goto fail;
1849 if (path[1])
1851 n = find_elements (client->doc, n->children, path + 1, &rc,
1852 NULL, NULL, NULL, 0, 0, NULL, 0);
1853 if (!n)
1854 goto fail;
1857 rc = delete_attribute (n, (xmlChar *) req[0]);
1859 fail:
1860 strv_free (path);
1861 return rc;
1864 static xmlNodePtr
1865 create_element_path (struct client_s *client,
1866 char ***elements, gpg_error_t * rc, xmlNodePtr parent)
1868 char **req = *elements;
1869 char **req_orig = strv_dup (req);
1870 xmlNodePtr n = NULL;
1872 *rc = 0;
1874 if (!req_orig)
1876 *rc = GPG_ERR_ENOMEM;
1877 log_write ("%s(%i): %s", __FILE__, __LINE__,
1878 pwmd_strerror (GPG_ERR_ENOMEM));
1879 goto fail;
1882 again:
1883 n = find_root_element (client->doc, &req, rc, NULL, 0, 0);
1884 if (!n)
1886 if (*rc != GPG_ERR_ELEMENT_NOT_FOUND)
1887 goto fail;
1889 *rc = new_root_element (client->doc, req[0]);
1890 if (*rc)
1891 goto fail;
1893 goto again;
1895 else if (n == parent)
1897 *rc = GPG_ERR_CONFLICT;
1898 goto fail;
1901 if (req[1])
1903 if (!n->children)
1904 n = create_target_elements_cb (n, req + 1, rc, NULL);
1905 else
1906 n = find_elements (client->doc, n->children, req + 1, rc, NULL, NULL,
1907 create_target_elements_cb, 0, 0, parent, 0);
1909 if (!n)
1910 goto fail;
1913 * Reset the position of the element tree now that the elements
1914 * have been created.
1916 strv_free (req);
1917 req = req_orig;
1918 req_orig = NULL;
1919 n = find_root_element (client->doc, &req, rc, NULL, 0, 0);
1920 if (!n)
1921 goto fail;
1923 n = find_elements (client->doc, n->children, req + 1, rc,
1924 NULL, NULL, NULL, 0, 0, NULL, 0);
1925 if (!n)
1926 goto fail;
1929 fail:
1930 if (req_orig)
1931 strv_free (req_orig);
1933 *elements = req;
1934 return n;
1938 * Creates a "target" attribute. When other commands encounter an element with
1939 * this attribute, the element path is modified to the target value. If the
1940 * source element path doesn't exist when using 'ATTR SET target', it is
1941 * created, but the destination element path must exist.
1943 * req[0] - source element path
1944 * req[1] - destination element path
1946 static gpg_error_t
1947 target_attribute (struct client_s *client, char **req)
1949 char **src, **dst, *line = NULL, **odst = NULL;
1950 gpg_error_t rc;
1951 xmlNodePtr n;
1953 if (!req || !req[0] || !req[1])
1954 return GPG_ERR_SYNTAX;
1956 if ((src = str_split (req[0], "\t", 0)) == NULL)
1959 * The first argument may be only a root element.
1961 if ((src = str_split (req[0], " ", 0)) == NULL)
1962 return GPG_ERR_SYNTAX;
1965 if (!valid_element_path (src, 0))
1966 return GPG_ERR_INV_VALUE;
1968 if ((dst = str_split (req[1], "\t", 0)) == NULL)
1971 * The first argument may be only a root element.
1973 if ((dst = str_split (req[1], " ", 0)) == NULL)
1975 rc = GPG_ERR_SYNTAX;
1976 goto fail;
1980 odst = strv_dup (dst);
1981 if (!odst)
1983 rc = GPG_ERR_ENOMEM;
1984 goto fail;
1987 n = find_root_element (client->doc, &dst, &rc, NULL, 0, 0);
1989 * Make sure the destination element path exists.
1991 if (!n)
1992 goto fail;
1994 if (dst[1])
1996 n = find_elements (client->doc, n->children, dst + 1, &rc,
1997 NULL, NULL, NULL, 0, 0, NULL, 0);
1998 if (!n)
1999 goto fail;
2002 rc = validate_target_attribute (client->doc, req[0], n);
2003 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2004 goto fail;
2006 n = create_element_path (client, &src, &rc, NULL);
2007 if (rc)
2008 goto fail;
2010 line = strv_join ("\t", odst);
2011 if (!line)
2013 rc = GPG_ERR_ENOMEM;
2014 goto fail;
2017 rc = add_attribute (n, "target", line);
2019 fail:
2020 xfree (line);
2021 strv_free (src);
2022 strv_free (dst);
2023 strv_free (odst);
2024 return rc;
2028 * req[0] - attribute
2029 * req[1] - element path
2031 static gpg_error_t
2032 attribute_get (assuan_context_t ctx, char **req)
2034 struct client_s *client = assuan_get_pointer (ctx);
2035 xmlNodePtr n;
2036 xmlChar *a;
2037 char **path = NULL;
2038 gpg_error_t rc;
2040 if (!req || !req[0] || !req[1])
2041 return GPG_ERR_SYNTAX;
2043 if (strchr (req[1], '\t'))
2045 if ((path = str_split (req[1], "\t", 0)) == NULL)
2046 return GPG_ERR_SYNTAX;
2048 else
2050 if ((path = str_split (req[1], " ", 0)) == NULL)
2051 return GPG_ERR_SYNTAX;
2054 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
2056 if (!n)
2057 goto fail;
2059 if (path[1])
2061 n = find_elements (client->doc, n->children, path + 1, &rc,
2062 NULL, NULL, NULL, 0, 0, NULL, 0);
2064 if (!n)
2065 goto fail;
2068 strv_free (path);
2070 if ((a = xmlGetProp (n, (xmlChar *) req[0])) == NULL)
2071 return GPG_ERR_NOT_FOUND;
2073 pthread_cleanup_push (xmlFree, a);
2075 if (*a)
2076 rc = xfer_data (ctx, (char *) a, xmlStrlen (a));
2077 else
2078 rc = GPG_ERR_NO_DATA;
2080 pthread_cleanup_pop (1);
2081 return rc;
2083 fail:
2084 strv_free (path);
2085 return rc;
2089 * req[0] - attribute
2090 * req[1] - element path
2091 * req[2] - value
2093 static gpg_error_t
2094 attribute_set (struct client_s *client, char **req)
2096 char **path = NULL;
2097 gpg_error_t rc;
2098 xmlNodePtr n;
2100 if (!req || !req[0] || !req[1])
2101 return GPG_ERR_SYNTAX;
2104 * Reserved attribute names.
2106 if (!strcmp (req[0], "_name"))
2107 return GPG_ERR_INV_ATTR;
2108 else if (!strcmp (req[0], "target"))
2109 return target_attribute (client, req + 1);
2111 if ((path = str_split (req[1], "\t", 0)) == NULL)
2114 * The first argument may be only a root element.
2116 if ((path = str_split (req[1], " ", 0)) == NULL)
2117 return GPG_ERR_SYNTAX;
2120 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
2122 if (!n)
2123 goto fail;
2125 if (path[1])
2127 n = find_elements (client->doc, n->children, path + 1, &rc,
2128 NULL, NULL, NULL, 0, 0, NULL, 0);
2130 if (!n)
2131 goto fail;
2134 rc = add_attribute (n, req[0], req[2]);
2136 fail:
2137 strv_free (path);
2138 return rc;
2142 * req[0] - command
2143 * req[1] - attribute name or element path if command is LIST
2144 * req[2] - element path
2145 * req[2] - element path or value
2148 static gpg_error_t
2149 do_attr (assuan_context_t ctx, char *line)
2151 struct client_s *client = assuan_get_pointer (ctx);
2152 gpg_error_t rc = 0;
2153 char **req;
2155 req = str_split (line, " ", 4);
2156 if (!req || !req[0] || !req[1])
2158 strv_free (req);
2159 return GPG_ERR_SYNTAX;
2162 pthread_cleanup_push (req_cleanup, req);
2164 if (strcasecmp (req[0], "SET") == 0)
2165 rc = attribute_set (client, req + 1);
2166 else if (strcasecmp (req[0], "GET") == 0)
2167 rc = attribute_get (ctx, req + 1);
2168 else if (strcasecmp (req[0], "DELETE") == 0)
2169 rc = attribute_delete (client, req + 1);
2170 else if (strcasecmp (req[0], "LIST") == 0)
2171 rc = attribute_list (ctx, req + 1);
2172 else
2173 rc = GPG_ERR_SYNTAX;
2175 pthread_cleanup_pop (1);
2176 return rc;
2179 static gpg_error_t
2180 attr_command (assuan_context_t ctx, char *line)
2182 struct client_s *client = assuan_get_pointer (ctx);
2183 gpg_error_t rc;
2184 struct argv_s *args[] = {
2185 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2186 NULL
2189 rc = parse_options (&line, args, client);
2190 if (rc)
2191 return send_error (ctx, rc);
2193 if (client->opts & OPT_INQUIRE)
2195 unsigned char *result;
2196 size_t len;
2198 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2199 if (rc)
2200 return send_error (ctx, rc);
2202 line = (char *) result;
2205 rc = do_attr (ctx, line);
2207 if (client->opts & OPT_INQUIRE)
2208 xfree (line);
2210 return send_error (ctx, rc);
2213 static gpg_error_t
2214 parse_iscached_opt_lock (void *data, void *value)
2216 struct client_s *client = data;
2218 (void) value;
2219 client->opts |= OPT_LOCK;
2220 return 0;
2223 static gpg_error_t
2224 iscached_command (assuan_context_t ctx, char *line)
2226 struct client_s *client = assuan_get_pointer (ctx);
2227 gpg_error_t rc;
2228 unsigned char md5file[16];
2229 struct argv_s *args[] = {
2230 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_iscached_opt_lock},
2231 NULL
2234 if (!line || !*line)
2235 return send_error (ctx, GPG_ERR_SYNTAX);
2237 rc = parse_options (&line, args, client);
2238 if (rc)
2239 return send_error (ctx, rc);
2240 else if (!valid_filename (line))
2241 return send_error (ctx, GPG_ERR_INV_VALUE);
2243 rc = cache_iscached (line, NULL);
2244 if (client->opts & OPT_LOCK
2245 && (!rc || gpg_err_code (rc) == GPG_ERR_NO_DATA))
2247 gpg_error_t trc = rc;
2248 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2249 if (memcmp (md5file, client->md5file, 16))
2250 cleanup_client (client);
2252 memcpy (client->md5file, md5file, 16);
2253 rc = do_lock (client, 1);
2254 if (!rc)
2255 rc = trc;
2258 return send_error (ctx, rc);
2261 static gpg_error_t
2262 clearcache_command (assuan_context_t ctx, char *line)
2264 gpg_error_t rc = 0, all_rc = 0;
2265 unsigned char md5file[16];
2266 int i;
2267 int t;
2268 int all = 0;
2269 struct client_thread_s *once = NULL;
2271 cache_lock ();
2272 MUTEX_LOCK (&cn_mutex);
2273 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
2275 if (!line || !*line)
2276 all = 1;
2278 t = slist_length (cn_thread_list);
2280 for (i = 0; i < t; i++)
2282 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2283 assuan_peercred_t peer;
2285 if (!thd->cl)
2286 continue;
2288 /* Lock each connected clients' file mutex to prevent any other client
2289 * from accessing the cache entry (the file mutex is locked upon
2290 * command startup). The cache for the entry is not cleared if the
2291 * file mutex is locked by another client to prevent this function
2292 * from blocking.
2294 if (all)
2296 if (thd->cl->filename)
2298 rc = do_validate_peer (ctx, thd->cl->filename, &peer);
2299 all_rc = !all_rc ? rc : all_rc;
2300 if (rc)
2302 rc = 0;
2303 continue;
2307 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0, -1);
2308 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2310 if (pthread_equal (pthread_self (), thd->tid))
2311 rc = 0;
2312 else
2314 if (!thd->cl->filename ||
2315 cache_iscached (thd->cl->filename,
2316 NULL) == GPG_ERR_NO_DATA)
2318 rc = 0;
2319 continue;
2322 cache_defer_clear (thd->cl->md5file);
2325 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
2327 rc = 0;
2328 continue;
2331 if (!rc)
2333 rc = cache_clear (thd->cl->md5file);
2334 cache_unlock_mutex (thd->cl->md5file, 0);
2337 if (rc)
2338 all_rc = rc;
2340 rc = 0;
2342 /* A single data filename was specified. Lock only this data file
2343 * mutex and free the cache entry. */
2344 else
2346 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2347 rc = do_validate_peer (ctx, line, &peer);
2349 if (!rc && !memcmp (thd->cl->md5file, md5file, sizeof (md5file)))
2351 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0,
2352 -1);
2353 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2355 if (pthread_equal (pthread_self (), thd->tid))
2356 rc = 0;
2359 if (!rc)
2361 once = thd;
2362 rc = cache_clear (thd->cl->md5file);
2363 cache_unlock_mutex (thd->cl->md5file, 0);
2365 else
2367 cache_defer_clear (thd->cl->md5file);
2370 break;
2375 /* Only connected clients' cache entries have been cleared. Now clear any
2376 * remaining cache entries without clients but only if there wasn't an
2377 * error from above since this would defeat the locking check of the
2378 * remaining entries. */
2379 if (!all_rc && all)
2381 cache_clear (NULL);
2384 /* No clients are using the specified file. */
2385 else if (!all_rc && !rc && !once)
2387 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2388 rc = cache_clear (md5file);
2391 /* Release the connection mutex. */
2392 pthread_cleanup_pop (1);
2393 cache_unlock ();
2395 if (!rc)
2396 send_status_all (STATUS_CACHE, NULL);
2398 /* One or more files were locked while clearing all cache entries. */
2399 if (all_rc)
2400 rc = all_rc;
2402 return send_error (ctx, rc);
2405 static gpg_error_t
2406 cachetimeout_command (assuan_context_t ctx, char *line)
2408 unsigned char md5file[16];
2409 int timeout;
2410 char **req = str_split (line, " ", 0);
2411 char *p;
2412 gpg_error_t rc = 0;
2413 assuan_peercred_t peer;
2415 if (!req || !*req || !req[1])
2417 strv_free (req);
2418 return send_error (ctx, GPG_ERR_SYNTAX);
2421 errno = 0;
2422 timeout = (int) strtol (req[1], &p, 10);
2423 if (errno != 0 || *p || timeout < -1)
2425 strv_free (req);
2426 return send_error (ctx, GPG_ERR_SYNTAX);
2429 rc = do_validate_peer (ctx, req[0], &peer);
2430 if (!rc)
2432 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, req[0], strlen (req[0]));
2433 rc = cache_set_timeout (md5file, timeout);
2434 if (!rc || gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
2436 rc = 0;
2437 MUTEX_LOCK (&rcfile_mutex);
2438 config_set_int_param (&global_config, req[0], "cache_timeout",
2439 req[1]);
2440 MUTEX_UNLOCK (&rcfile_mutex);
2444 strv_free (req);
2445 return send_error (ctx, rc);
2448 static gpg_error_t
2449 dump_command (assuan_context_t ctx, char *line)
2451 xmlChar *xml;
2452 int len;
2453 struct client_s *client = assuan_get_pointer (ctx);
2454 gpg_error_t rc;
2456 if (disable_list_and_dump == 1)
2457 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2459 xmlDocDumpFormatMemory (client->doc, &xml, &len, 1);
2461 if (!xml)
2463 log_write ("%s(%i): %s", __FILE__, __LINE__,
2464 pwmd_strerror (GPG_ERR_ENOMEM));
2465 return send_error (ctx, GPG_ERR_ENOMEM);
2468 pthread_cleanup_push (xmlFree, xml);
2469 rc = xfer_data (ctx, (char *) xml, len);
2470 pthread_cleanup_pop (1);
2471 return send_error (ctx, rc);
2474 static gpg_error_t
2475 getconfig_command (assuan_context_t ctx, char *line)
2477 struct client_s *client = assuan_get_pointer (ctx);
2478 gpg_error_t rc = 0;
2479 char filename[255] = { 0 }, param[747] = { 0 };
2480 char *p, *tmp = NULL, *fp = client->filename, *paramp = line;
2482 if (!line || !*line)
2483 return send_error (ctx, GPG_ERR_SYNTAX);
2485 if (strchr (line, ' '))
2487 sscanf (line, " %254[^ ] %746c", filename, param);
2488 paramp = param;
2489 fp = filename;
2492 if (fp && !valid_filename (fp))
2493 return send_error (ctx, GPG_ERR_INV_VALUE);
2495 paramp = str_down (paramp);
2496 if (!strcmp (paramp, "cipher") && fp)
2498 struct crypto_s *crypto = NULL;
2500 rc = init_client_crypto (&crypto);
2501 if (!rc)
2503 rc = read_data_header (fp, &crypto->hdr, NULL, NULL);
2504 if (!rc)
2506 const char *t =
2507 gcry_cipher_algo_name (cipher_to_gcrypt (crypto->hdr.flags));
2508 if (t)
2510 tmp = str_dup (t);
2511 if (tmp)
2512 str_down (tmp);
2517 UPDATE_AGENT_CTX (client, crypto);
2518 cleanup_crypto (&crypto);
2519 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
2520 return send_error (ctx, rc);
2522 if (!rc && tmp)
2523 goto done;
2525 else if (!strcmp (paramp, "cipher_iterations") && fp)
2527 struct crypto_s *crypto = NULL;
2529 rc = init_client_crypto (&crypto);
2530 if (!rc)
2532 rc = read_data_header (fp, &crypto->hdr, NULL, NULL);
2533 if (!rc)
2535 tmp = str_asprintf ("%llu",
2536 (unsigned long long) crypto->hdr.
2537 iterations);
2538 if (!tmp)
2539 rc = GPG_ERR_ENOMEM;
2543 UPDATE_AGENT_CTX (client, crypto);
2544 cleanup_crypto (&crypto);
2545 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
2546 return send_error (ctx, rc);
2548 if (!rc && tmp)
2549 goto done;
2551 else if (!strcmp (paramp, "passphrase"))
2552 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2554 p = config_get_value (fp ? fp : "global", paramp);
2555 if (!p)
2556 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2558 tmp = expand_homedir (p);
2559 xfree (p);
2560 if (!tmp)
2562 log_write ("%s(%i): %s", __FILE__, __LINE__,
2563 pwmd_strerror (GPG_ERR_ENOMEM));
2564 return send_error (ctx, GPG_ERR_ENOMEM);
2567 done:
2568 p = tmp;
2569 pthread_cleanup_push (xfree, p);
2570 rc = xfer_data (ctx, p, strlen (p));
2571 pthread_cleanup_pop (1);
2572 return send_error (ctx, rc);
2575 struct xpath_s
2577 xmlXPathContextPtr xp;
2578 xmlXPathObjectPtr result;
2579 xmlBufferPtr buf;
2580 char **req;
2583 static void
2584 xpath_command_cleanup (void *arg)
2586 struct xpath_s *xpath = arg;
2588 if (!xpath)
2589 return;
2591 req_cleanup (xpath->req);
2593 if (xpath->buf)
2594 xmlBufferFree (xpath->buf);
2596 if (xpath->result)
2597 xmlXPathFreeObject (xpath->result);
2599 if (xpath->xp)
2600 xmlXPathFreeContext (xpath->xp);
2603 static gpg_error_t
2604 do_xpath (assuan_context_t ctx, char *line)
2606 gpg_error_t rc;
2607 struct client_s *client = assuan_get_pointer (ctx);
2608 struct xpath_s _x = { 0 };
2609 struct xpath_s *xpath = &_x;
2611 if ((xpath->req = str_split (line, "\t", 2)) == NULL)
2613 if (strv_printf (&xpath->req, "%s", line) == 0)
2614 return GPG_ERR_ENOMEM;
2617 xpath->xp = xmlXPathNewContext (client->doc);
2618 if (!xpath->xp)
2620 rc = GPG_ERR_BAD_DATA;
2621 goto fail;
2624 xpath->result =
2625 xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2626 if (!xpath->result)
2628 rc = GPG_ERR_BAD_DATA;
2629 goto fail;
2632 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2634 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2635 goto fail;
2638 rc = recurse_xpath_nodeset (client->doc, xpath->result->nodesetval,
2639 (xmlChar *) xpath->req[1], &xpath->buf, 0,
2640 NULL);
2641 if (rc)
2642 goto fail;
2643 else if (!xpath->req[1] && !xmlBufferLength (xpath->buf))
2645 rc = GPG_ERR_NO_DATA;
2646 goto fail;
2648 else if (xpath->req[1])
2650 rc = 0;
2651 goto fail;
2654 pthread_cleanup_push (xpath_command_cleanup, &xpath);
2655 rc = xfer_data (ctx, (char *) xmlBufferContent (xpath->buf),
2656 xmlBufferLength (xpath->buf));
2657 pthread_cleanup_pop (0);
2658 fail:
2659 xpath_command_cleanup (xpath);
2660 return rc;
2663 static gpg_error_t
2664 xpath_command (assuan_context_t ctx, char *line)
2666 struct client_s *client = assuan_get_pointer (ctx);
2667 gpg_error_t rc;
2668 struct argv_s *args[] = {
2669 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2670 NULL
2673 if (disable_list_and_dump == 1)
2674 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2676 rc = parse_options (&line, args, client);
2677 if (rc)
2678 return send_error (ctx, rc);
2680 if (client->opts & OPT_INQUIRE)
2682 unsigned char *result;
2683 size_t len;
2685 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2686 if (rc)
2687 return send_error (ctx, rc);
2689 line = (char *) result;
2692 if (!line || !*line)
2693 rc = GPG_ERR_SYNTAX;
2695 if (!rc)
2696 rc = do_xpath (ctx, line);
2698 if (client->opts & OPT_INQUIRE)
2699 xfree (line);
2701 return send_error (ctx, rc);
2704 static gpg_error_t
2705 do_xpathattr (assuan_context_t ctx, char *line)
2707 struct client_s *client = assuan_get_pointer (ctx);
2708 gpg_error_t rc;
2709 char **req = NULL;
2710 int cmd = 0; //SET
2711 struct xpath_s _x = { 0 };
2712 struct xpath_s *xpath = &_x;
2714 if ((req = str_split (line, " ", 3)) == NULL)
2715 return GPG_ERR_ENOMEM;
2717 if (!req[0])
2719 rc = GPG_ERR_SYNTAX;
2720 goto fail;
2723 if (!strcasecmp (req[0], "SET"))
2724 cmd = 0;
2725 else if (!strcasecmp (req[0], "DELETE"))
2726 cmd = 1;
2727 else
2729 rc = GPG_ERR_SYNTAX;
2730 goto fail;
2733 if (!req[1] || !req[2])
2735 rc = GPG_ERR_SYNTAX;
2736 goto fail;
2739 if ((xpath->req = str_split (req[2], "\t", 3)) == NULL)
2741 rc = GPG_ERR_ENOMEM;
2742 goto fail;
2745 if (!xpath->req[0] || (!xpath->req[1] && !cmd) || (xpath->req[1] && cmd))
2747 rc = GPG_ERR_SYNTAX;
2748 goto fail;
2751 xpath->xp = xmlXPathNewContext (client->doc);
2752 if (!xpath->xp)
2754 rc = GPG_ERR_BAD_DATA;
2755 goto fail;
2758 xpath->result = xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2759 if (!xpath->result)
2761 rc = GPG_ERR_BAD_DATA;
2762 goto fail;
2765 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2767 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2768 goto fail;
2771 rc = recurse_xpath_nodeset (client->doc, xpath->result->nodesetval,
2772 (xmlChar *) xpath->req[1], &xpath->buf, cmd,
2773 (xmlChar *) req[1]);
2775 fail:
2776 xpath_command_cleanup (xpath);
2777 strv_free (req);
2778 return rc;
2781 /* XPATHATTR SET|DELETE <name> <expression>[<TAB>[value]] */
2782 static gpg_error_t
2783 xpathattr_command (assuan_context_t ctx, char *line)
2785 struct client_s *client = assuan_get_pointer (ctx);
2786 gpg_error_t rc;
2787 struct argv_s *args[] = {
2788 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2789 NULL
2792 if (disable_list_and_dump == 1)
2793 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2795 rc = parse_options (&line, args, client);
2796 if (rc)
2797 return send_error (ctx, rc);
2799 if (client->opts & OPT_INQUIRE)
2801 unsigned char *result;
2802 size_t len;
2804 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2805 if (rc)
2806 return send_error (ctx, rc);
2808 line = (char *) result;
2811 if (!line || !*line)
2812 rc = GPG_ERR_SYNTAX;
2814 if (!rc)
2815 rc = do_xpathattr (ctx, line);
2817 if (client->opts & OPT_INQUIRE)
2818 xfree (line);
2820 return send_error (ctx, rc);
2823 static gpg_error_t
2824 do_import (struct client_s *client, const char *root_element,
2825 unsigned char *content)
2827 char **dst_path = NULL;
2828 xmlDocPtr doc = NULL;
2829 xmlNodePtr n, root, copy;
2830 gpg_error_t rc;
2832 if (!content || !*content)
2834 xfree (content);
2835 return GPG_ERR_SYNTAX;
2838 if (root_element)
2839 dst_path = str_split (root_element, "\t", 0);
2841 if (dst_path && !valid_element_path (dst_path, 0))
2843 if (dst_path)
2844 strv_free (dst_path);
2846 return GPG_ERR_INV_VALUE;
2849 struct string_s *str = string_new_content ((char *)content);
2850 str = string_prepend (str, "<pwmd>");
2851 str = string_append (str, "</pwmd>");
2852 doc = xmlReadDoc ((xmlChar *) str->str, NULL, "UTF-8", XML_PARSE_NOBLANKS);
2853 string_free (str, 1);
2854 if (!doc)
2856 rc = GPG_ERR_BAD_DATA;
2857 goto fail;
2860 root = xmlDocGetRootElement (doc);
2861 xmlNodePtr root_orig = root->children;
2862 root = root->children;
2863 rc = validate_import (root);
2864 if (rc)
2865 goto fail;
2869 again:
2870 if (dst_path)
2872 char **path = strv_dup (dst_path);
2873 if (!path)
2875 log_write ("%s(%i): %s", __FILE__, __LINE__,
2876 pwmd_strerror (GPG_ERR_ENOMEM));
2877 rc = GPG_ERR_ENOMEM;
2878 goto fail;
2881 xmlChar *a = xmlGetProp (root, (xmlChar *) "_name");
2882 if (!a)
2884 strv_free (path);
2885 rc = GPG_ERR_ENOMEM;
2886 goto fail;
2889 if (strv_printf (&path, "%s", (char *) a) == 0)
2891 xmlFree (a);
2892 rc = GPG_ERR_ENOMEM;
2893 goto fail;
2896 xmlFree (a);
2897 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
2898 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2900 strv_free (path);
2901 goto fail;
2904 if (!rc)
2906 n = find_elements (client->doc, n->children, path + 1, &rc,
2907 NULL, NULL, NULL, 0, 0, NULL, 1);
2908 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2910 strv_free (path);
2911 goto fail;
2913 else if (!rc)
2915 xmlUnlinkNode (n);
2916 xmlFreeNode (n);
2917 strv_free (path);
2918 path = NULL;
2919 goto again;
2923 if (rc == GPG_ERR_ELEMENT_NOT_FOUND)
2925 n = create_element_path (client, &path, &rc, NULL);
2926 if (rc)
2927 goto fail;
2930 if (root->children)
2932 copy = xmlCopyNodeList (root->children);
2933 n = xmlAddChildList (n, copy);
2934 if (!n)
2935 rc = GPG_ERR_ENOMEM;
2938 strv_free (path);
2940 else
2942 char **path = NULL;
2944 /* Check if the content root element can create a DTD root element. */
2945 if (!xmlStrEqual ((xmlChar *) "element", root->name))
2947 rc = GPG_ERR_SYNTAX;
2948 goto fail;
2951 xmlChar *a;
2953 if ((a = xmlGetProp (root, (xmlChar *) "_name")) == NULL)
2955 rc = GPG_ERR_SYNTAX;
2956 goto fail;
2959 char *tmp = str_dup ((char *) a);
2960 xmlFree (a);
2961 int literal = is_literal_element (&tmp);
2963 if (!valid_xml_element ((xmlChar *) tmp) || literal)
2965 xfree (tmp);
2966 rc = GPG_ERR_INV_VALUE;
2967 goto fail;
2970 if (strv_printf (&path, "%s", tmp) == 0)
2972 xfree (tmp);
2973 rc = GPG_ERR_ENOMEM;
2974 goto fail;
2977 xfree (tmp);
2978 n = find_root_element (client->doc, &path, &rc, NULL, 0, 1);
2979 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2981 rc = GPG_ERR_BAD_DATA;
2982 goto fail;
2985 /* Overwriting the existing tree. */
2986 if (!rc)
2988 xmlUnlinkNode (n);
2989 xmlFreeNodeList (n);
2992 rc = 0;
2993 xmlSetProp (root, (xmlChar *) "_name", (xmlChar *) path[0]);
2994 n = xmlCopyNode (root, 1);
2995 n = xmlAddChildList (xmlDocGetRootElement (client->doc), n);
2996 strv_free (path);
2999 if (n && !rc)
3000 rc = update_element_mtime (n->parent);
3002 for (root = root_orig->next; root; root = root->next)
3004 if (root->type == XML_ELEMENT_NODE)
3005 break;
3008 root_orig = root;
3010 while (root);
3012 fail:
3013 if (doc)
3014 xmlFreeDoc (doc);
3016 if (dst_path)
3017 strv_free (dst_path);
3019 return rc;
3022 static gpg_error_t
3023 parse_import_opt_root (void *data, void *value)
3025 struct client_s *client = data;
3027 client->import_root = str_dup (value);
3028 return client->import_root ? 0 : GPG_ERR_ENOMEM;
3031 static gpg_error_t
3032 import_command (assuan_context_t ctx, char *line)
3034 gpg_error_t rc;
3035 struct client_s *client = assuan_get_pointer (ctx);
3036 unsigned char *result;
3037 size_t len;
3038 struct argv_s *args[] = {
3039 &(struct argv_s) {"root", OPTION_TYPE_ARG, parse_import_opt_root},
3040 NULL
3043 xfree (client->import_root);
3044 client->import_root = NULL;
3045 rc = parse_options (&line, args, client);
3046 if (rc)
3047 return send_error (ctx, rc);
3049 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3050 if (rc)
3051 return send_error (ctx, rc);
3053 rc = do_import (client, client->import_root, result);
3054 xfree (client->import_root);
3055 client->import_root = NULL;
3056 return send_error (ctx, rc);
3059 static gpg_error_t
3060 do_lock (struct client_s *client, int add)
3062 gpg_error_t rc = lock_file_mutex (client, add);
3064 if (!rc)
3065 client->flags |= FLAG_LOCK_CMD;
3067 return rc;
3070 static gpg_error_t
3071 lock_command (assuan_context_t ctx, char *line)
3073 struct client_s *client = assuan_get_pointer (ctx);
3074 gpg_error_t rc = do_lock (client, 0);
3076 return send_error (ctx, rc);
3079 static gpg_error_t
3080 unlock_command (assuan_context_t ctx, char *line)
3082 struct client_s *client = assuan_get_pointer (ctx);
3083 gpg_error_t rc;
3085 rc = unlock_file_mutex (client, 0);
3086 return send_error (ctx, rc);
3089 static gpg_error_t
3090 option_command (assuan_context_t ctx, char *line)
3092 struct client_s *client = assuan_get_pointer (ctx);
3093 gpg_error_t rc = 0;
3094 struct pinentry_option_s *pin_opts = &client->pinentry_opts;
3095 #ifdef WITH_AGENT
3096 struct agent_s *agent = client->crypto->agent;
3097 #endif
3098 char namebuf[255] = { 0 };
3099 char *name = namebuf;
3100 char *value = NULL, *p;
3102 p = strchr (line, '=');
3103 if (!p)
3104 strncpy (namebuf, line, sizeof(namebuf));
3105 else
3107 strncpy (namebuf, line, strlen (line)-strlen (p));
3108 value = p+1;
3111 log_write1 ("OPTION name='%s' value='%s'", name, value);
3113 if (strcasecmp (name, (char *) "log_level") == 0)
3115 long l = 0;
3117 if (value)
3119 l = strtol (value, NULL, 10);
3121 if (l < 0 || l > 2)
3122 return send_error (ctx, GPG_ERR_INV_VALUE);
3125 MUTEX_LOCK (&rcfile_mutex);
3126 config_set_int_param (&global_config, "global", "log_level", value);
3127 MUTEX_UNLOCK (&rcfile_mutex);
3128 goto done;
3130 else if (strcasecmp (name, (char *) "lock-timeout") == 0)
3132 long n = 0;
3133 char *p = NULL;
3135 if (value)
3137 n = strtol (value, &p, 10);
3138 if (p && *p)
3139 return send_error (ctx, GPG_ERR_INV_VALUE);
3142 client->lock_timeout = n;
3143 goto done;
3145 else if (strcasecmp (name, (char *) "NAME") == 0)
3147 char *tmp = pthread_getspecific (thread_name_key);
3149 if (tmp)
3150 xfree (tmp);
3152 if (!value || !*value)
3154 pthread_setspecific (thread_name_key, str_dup (""));
3155 goto done;
3158 pthread_setspecific (thread_name_key, str_dup (value));
3159 goto done;
3161 else if (strcasecmp (name, (char *) "lc-messages") == 0)
3163 xfree (pin_opts->lc_messages);
3164 pin_opts->lc_messages = NULL;
3165 if (value && *value)
3166 pin_opts->lc_messages = str_dup (value);
3167 #ifdef WITH_AGENT
3168 if (use_agent)
3169 rc = set_agent_option (client->crypto->agent, "lc-messages", value);
3170 #endif
3172 else if (strcasecmp (name, (char *) "lc-ctype") == 0)
3174 xfree (pin_opts->lc_ctype);
3175 pin_opts->lc_ctype = NULL;
3176 if (value && *value)
3177 pin_opts->lc_ctype = str_dup (value);
3178 #ifdef WITH_AGENT
3179 if (use_agent)
3180 rc = set_agent_option (client->crypto->agent, "lc-ctype", value);
3181 #endif
3183 else if (strcasecmp (name, (char *) "ttyname") == 0)
3185 xfree (pin_opts->ttyname);
3186 pin_opts->ttyname = NULL;
3187 if (value && *value)
3188 pin_opts->ttyname = str_dup (value);
3189 #ifdef WITH_AGENT
3190 if (use_agent)
3191 rc = set_agent_option (client->crypto->agent, "ttyname", value);
3192 #endif
3194 else if (strcasecmp (name, (char *) "ttytype") == 0)
3196 xfree (pin_opts->ttytype);
3197 pin_opts->ttytype = NULL;
3198 if (value && *value)
3199 pin_opts->ttytype = str_dup (value);
3200 #ifdef WITH_AGENT
3201 if (use_agent)
3202 rc = set_agent_option (client->crypto->agent, "ttytype", value);
3203 #endif
3205 else if (strcasecmp (name, (char *) "display") == 0)
3207 xfree (pin_opts->display);
3208 pin_opts->display = NULL;
3209 if (value && *value)
3210 pin_opts->display = str_dup (value);
3211 #ifdef WITH_AGENT
3212 if (use_agent)
3213 rc = set_agent_option (client->crypto->agent, "display", value);
3214 #endif
3216 else if (strcasecmp (name, (char *) "pinentry-desc") == 0)
3218 xfree (pin_opts->desc);
3219 pin_opts->desc = NULL;
3220 if (value && *value)
3221 pin_opts->desc = str_dup (value);
3223 else if (strcasecmp (name, (char *) "pinentry-title") == 0)
3225 xfree (pin_opts->title);
3226 pin_opts->title = NULL;
3227 if (value && *value)
3228 pin_opts->title = str_dup (value);
3230 else if (strcasecmp (name, (char *) "pinentry-prompt") == 0)
3232 xfree (pin_opts->prompt);
3233 pin_opts->prompt = NULL;
3234 if (value && *value)
3235 pin_opts->prompt = str_dup (value);
3238 else if (strcasecmp (name, "pinentry-timeout") == 0)
3240 char *p = NULL;
3241 int n;
3243 if (!value)
3244 goto done;
3246 n = (int) strtol (value, &p, 10);
3248 if (*p || n < 0)
3249 return send_error (ctx, GPG_ERR_INV_VALUE);
3251 pin_opts->timeout = n;
3252 MUTEX_LOCK (&rcfile_mutex);
3253 config_set_int_param (&global_config,
3254 client->filename ? client->filename : "global",
3255 "pinentry_timeout", value);
3256 MUTEX_UNLOCK (&rcfile_mutex);
3257 goto done;
3259 else if (strcasecmp (name, "disable-pinentry") == 0)
3261 char *p = NULL;
3262 int n = 1;
3264 if (value && *value)
3266 n = (int) strtol (value, &p, 10);
3267 if (*p || n < 0 || n > 1)
3268 return send_error (ctx, GPG_ERR_INV_VALUE);
3271 if (n)
3272 client->flags |= FLAG_NO_PINENTRY;
3273 else
3274 client->flags &= ~FLAG_NO_PINENTRY;
3276 else
3277 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
3279 done:
3280 #ifdef WITH_AGENT
3281 if (!rc && use_agent && agent)
3283 rc = pinentry_merge_options (&client->crypto->agent->pinentry_opts,
3284 pin_opts);
3286 #endif
3288 return send_error (ctx, rc);
3291 static gpg_error_t
3292 do_rename (assuan_context_t ctx, char *line)
3294 struct client_s *client = assuan_get_pointer (ctx);
3295 gpg_error_t rc;
3296 char **req, **src, *dst;
3297 xmlNodePtr n, ndst;
3299 req = str_split (line, " ", 0);
3301 if (!req || !req[0] || !req[1])
3303 strv_free (req);
3304 return GPG_ERR_SYNTAX;
3307 dst = req[1];
3308 is_literal_element (&dst);
3310 if (!valid_xml_element ((xmlChar *) dst))
3312 strv_free (req);
3313 return GPG_ERR_INV_VALUE;
3316 if (strchr (req[0], '\t'))
3317 src = str_split (req[0], "\t", 0);
3318 else
3319 src = str_split (req[0], " ", 0);
3321 if (!src || !*src)
3323 rc = GPG_ERR_SYNTAX;
3324 goto fail;
3327 n = find_root_element (client->doc, &src, &rc, NULL, 0, 0);
3328 if (src[1] && n)
3329 n = find_elements (client->doc, n->children, src + 1, &rc, NULL, NULL,
3330 NULL, 0, 0, NULL, 0);
3332 if (!n)
3333 goto fail;
3335 xmlChar *a = xmlGetProp (n, (xmlChar *) "_name");
3336 if (!a)
3338 rc = GPG_ERR_ENOMEM;
3339 goto fail;
3342 /* To prevent unwanted effects:
3344 * <root name="a"><b/></root>
3346 * RENAME a<TAB>b b
3348 if (xmlStrEqual (a, (xmlChar *) dst))
3350 xmlFree (a);
3351 rc = GPG_ERR_AMBIGUOUS_NAME;
3352 goto fail;
3355 xmlFree (a);
3356 char **tmp = NULL;
3357 if (src[1])
3359 char **p;
3361 for (p = src; *p; p++)
3363 if (!*(p + 1))
3364 break;
3365 strv_printf (&tmp, "%s", *p);
3369 strv_printf (&tmp, "!%s", dst);
3370 ndst = find_root_element (client->doc, &tmp, &rc, NULL, 0, 0);
3371 if (!ndst && rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3373 strv_free (tmp);
3374 goto fail;
3377 if (tmp[1] && ndst)
3378 ndst = find_elements (client->doc, ndst->children, tmp + 1, &rc, NULL,
3379 NULL, NULL, 0, 0, NULL, 0);
3381 strv_free (tmp);
3382 if (!ndst && rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3383 goto fail;
3385 rc = 0;
3387 /* Target may exist:
3389 * <root name="a"/>
3390 * <root name="b" target="a"/>
3392 * RENAME b a
3394 * Would need to do:
3395 * RENAME !b a
3397 if (ndst == n)
3399 rc = GPG_ERR_AMBIGUOUS_NAME;
3400 goto fail;
3403 if (ndst)
3405 unlink_node (ndst);
3406 xmlFreeNodeList (ndst);
3409 rc = add_attribute (n, "_name", dst);
3411 fail:
3412 strv_free (req);
3413 strv_free (src);
3414 return rc;
3417 static gpg_error_t
3418 rename_command (assuan_context_t ctx, char *line)
3420 struct client_s *client = assuan_get_pointer (ctx);
3421 gpg_error_t rc;
3422 struct argv_s *args[] = {
3423 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3424 NULL
3427 rc = parse_options (&line, args, client);
3428 if (rc)
3429 return send_error (ctx, rc);
3431 if (client->opts & OPT_INQUIRE)
3433 unsigned char *result;
3434 size_t len;
3436 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3437 if (rc)
3438 return send_error (ctx, rc);
3440 line = (char *) result;
3443 rc = do_rename (ctx, line);
3445 if (client->opts & OPT_INQUIRE)
3446 xfree (line);
3448 return send_error (ctx, rc);
3451 static gpg_error_t
3452 do_copy (assuan_context_t ctx, char *line)
3454 struct client_s *client = assuan_get_pointer (ctx);
3455 gpg_error_t rc;
3456 char **req, **src = NULL, **dst = NULL;
3457 xmlNodePtr nsrc, ndst, new = NULL;
3459 req = str_split (line, " ", 0);
3460 if (!req || !req[0] || !req[1])
3462 strv_free (req);
3463 return GPG_ERR_SYNTAX;
3466 if (strchr (req[0], '\t'))
3467 src = str_split (req[0], "\t", 0);
3468 else
3469 src = str_split (req[0], " ", 0);
3471 if (!src || !*src)
3473 rc = GPG_ERR_SYNTAX;
3474 goto fail;
3477 if (strchr (req[1], '\t'))
3478 dst = str_split (req[1], "\t", 0);
3479 else
3480 dst = str_split (req[1], " ", 0);
3482 if (!dst || !*dst)
3484 rc = GPG_ERR_SYNTAX;
3485 goto fail;
3488 if (!valid_element_path (dst, 0))
3490 rc = GPG_ERR_INV_VALUE;
3491 goto fail;
3494 nsrc = find_root_element (client->doc, &src, &rc, NULL, 0, 0);
3495 if (nsrc && src[1])
3496 nsrc = find_elements (client->doc, nsrc->children, src + 1, &rc, NULL,
3497 NULL, NULL, 0, 0, NULL, 0);
3499 if (!nsrc)
3500 goto fail;
3502 new = xmlCopyNodeList (nsrc);
3503 if (!new)
3505 rc = GPG_ERR_ENOMEM;
3506 goto fail;
3509 int create = 0;
3510 ndst = find_root_element (client->doc, &dst, &rc, NULL, 0, 0);
3511 if (ndst && dst[1])
3513 if (ndst->children)
3514 ndst = find_elements (client->doc, ndst->children, dst + 1, &rc, NULL,
3515 NULL, create_target_elements_cb, 0, 0, NULL, 0);
3516 else
3517 create = 1;
3519 else
3520 create = 1;
3522 if (!ndst && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3523 goto fail;
3524 else if (!ndst || create)
3526 ndst = create_element_path (client, &dst, &rc, NULL);
3527 if (!ndst)
3528 goto fail;
3531 /* Merge any attributes from the src node to the initial dst node. */
3532 for (xmlAttrPtr attr = new->properties; attr; attr = attr->next)
3534 if (xmlStrEqual (attr->name, (xmlChar *) "_name"))
3535 continue;
3537 xmlAttrPtr a = xmlHasProp (ndst, attr->name);
3538 if (a)
3539 xmlRemoveProp (a);
3541 xmlChar *tmp = xmlNodeGetContent (attr->children);
3542 xmlNewProp (ndst, attr->name, tmp);
3543 xmlFree (tmp);
3544 rc = add_attribute (ndst, NULL, NULL);
3547 xmlNodePtr n = ndst->children;
3548 xmlUnlinkNode (n);
3549 xmlFreeNodeList (n);
3550 ndst->children = NULL;
3552 if (new->children)
3554 n = xmlCopyNodeList (new->children);
3555 if (!n)
3557 rc = GPG_ERR_ENOMEM;
3558 goto fail;
3561 n = xmlAddChildList (ndst, n);
3562 if (!n)
3564 rc = GPG_ERR_ENOMEM;
3565 goto fail;
3568 rc = update_element_mtime (xmlDocGetRootElement (client->doc) ==
3569 ndst->parent ? ndst : ndst->parent);
3572 fail:
3573 if (new)
3575 xmlUnlinkNode (new);
3576 xmlFreeNodeList (new);
3579 if (req)
3580 strv_free (req);
3582 if (src)
3583 strv_free (src);
3585 if (dst)
3586 strv_free (dst);
3588 return rc;
3591 static gpg_error_t
3592 copy_command (assuan_context_t ctx, char *line)
3594 struct client_s *client = assuan_get_pointer (ctx);
3595 gpg_error_t rc;
3596 struct argv_s *args[] = {
3597 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3598 NULL
3601 rc = parse_options (&line, args, client);
3602 if (rc)
3603 return send_error (ctx, rc);
3605 if (client->opts & OPT_INQUIRE)
3607 unsigned char *result;
3608 size_t len;
3610 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3611 if (rc)
3612 return send_error (ctx, rc);
3614 line = (char *) result;
3617 rc = do_copy (ctx, line);
3619 if (client->opts & OPT_INQUIRE)
3620 xfree (line);
3622 return send_error (ctx, rc);
3625 static gpg_error_t
3626 do_move (assuan_context_t ctx, char *line)
3628 struct client_s *client = assuan_get_pointer (ctx);
3629 gpg_error_t rc;
3630 char **req, **src = NULL, **dst = NULL;
3631 xmlNodePtr nsrc, ndst = NULL;
3633 req = str_split (line, " ", 0);
3635 if (!req || !req[0] || !req[1])
3637 strv_free (req);
3638 return GPG_ERR_SYNTAX;
3641 if (strchr (req[0], '\t'))
3642 src = str_split (req[0], "\t", 0);
3643 else
3644 src = str_split (req[0], " ", 0);
3646 if (!src || !*src)
3648 rc = GPG_ERR_SYNTAX;
3649 goto fail;
3652 if (strchr (req[1], '\t'))
3653 dst = str_split (req[1], "\t", 0);
3654 else
3655 dst = str_split (req[1], " ", 0);
3657 nsrc = find_root_element (client->doc, &src, &rc, NULL, 0, 0);
3658 if (nsrc && src[1])
3659 nsrc = find_elements (client->doc, nsrc->children, src + 1, &rc, NULL,
3660 NULL, NULL, 0, 0, NULL, 0);
3662 if (!nsrc)
3663 goto fail;
3665 if (dst)
3667 if (!valid_element_path (dst, 0))
3669 rc = GPG_ERR_INV_VALUE;
3670 goto fail;
3673 ndst = find_root_element (client->doc, &dst, &rc, NULL, 0, 0);
3674 if (ndst && dst[1])
3675 ndst = find_elements (client->doc, ndst->children, dst + 1, &rc, NULL,
3676 NULL, NULL, 0, 0, NULL, 0);
3678 else
3679 ndst = xmlDocGetRootElement (client->doc);
3681 for (xmlNodePtr n = ndst; n; n = n->parent)
3683 if (n == nsrc)
3685 rc = GPG_ERR_CONFLICT;
3686 goto fail;
3690 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3691 goto fail;
3693 rc = 0;
3695 if (ndst)
3697 xmlChar *a = node_has_attribute (nsrc, (xmlChar *) "_name");
3698 xmlNodePtr dup = find_element (ndst->children, (char *) a, NULL);
3700 xmlFree (a);
3701 if (dup)
3703 if (dup == nsrc)
3704 goto fail;
3706 if (ndst == xmlDocGetRootElement (client->doc))
3708 xmlNodePtr n = nsrc;
3709 int match = 0;
3711 while (n->parent && n->parent != ndst)
3712 n = n->parent;
3714 xmlChar *a = node_has_attribute (n, (xmlChar *) "_name");
3715 xmlChar *b = node_has_attribute (nsrc, (xmlChar *) "_name");
3717 if (xmlStrEqual (a, b))
3719 match = 1;
3720 xmlUnlinkNode (nsrc);
3721 xmlUnlinkNode (n);
3722 xmlFreeNodeList (n);
3725 xmlFree (a);
3726 xmlFree (b);
3728 if (!match)
3730 xmlUnlinkNode (dup);
3731 xmlFreeNodeList (dup);
3734 else
3735 xmlUnlinkNode (dup);
3739 if (!ndst && dst)
3741 xmlChar *name = node_has_attribute (nsrc, (xmlChar *) "_name");
3743 if (nsrc->parent == xmlDocGetRootElement (client->doc)
3744 && !strcmp ((char *) name, *dst))
3746 xmlFree (name);
3747 rc = GPG_ERR_CONFLICT;
3748 goto fail;
3751 xmlFree (name);
3752 ndst = create_element_path (client, &dst, &rc, nsrc);
3755 if (!ndst)
3756 goto fail;
3758 update_element_mtime (nsrc->parent);
3759 xmlUnlinkNode (nsrc);
3760 ndst = xmlAddChildList (ndst, nsrc);
3762 if (!ndst)
3763 rc = GPG_ERR_ENOMEM;
3764 else
3765 update_element_mtime (ndst->parent);
3767 fail:
3768 if (req)
3769 strv_free (req);
3771 if (src)
3772 strv_free (src);
3774 if (dst)
3775 strv_free (dst);
3777 return rc;
3780 static gpg_error_t
3781 move_command (assuan_context_t ctx, char *line)
3783 struct client_s *client = assuan_get_pointer (ctx);
3784 gpg_error_t rc;
3785 struct argv_s *args[] = {
3786 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3787 NULL
3790 rc = parse_options (&line, args, client);
3791 if (rc)
3792 return send_error (ctx, rc);
3794 if (client->opts & OPT_INQUIRE)
3796 unsigned char *result;
3797 size_t len;
3799 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3800 if (rc)
3801 return send_error (ctx, rc);
3803 line = (char *) result;
3806 rc = do_move (ctx, line);
3808 if (client->opts & OPT_INQUIRE)
3809 xfree (line);
3811 return send_error (ctx, rc);
3814 static gpg_error_t
3815 ls_command (assuan_context_t ctx, char *line)
3817 gpg_error_t rc;
3818 char *tmp = str_asprintf ("%s/data", homedir);
3819 char *dir = expand_homedir (tmp);
3820 DIR *d = opendir (dir);
3822 rc = gpg_error_from_errno (errno);
3823 xfree (tmp);
3825 if (!d)
3827 xfree (dir);
3828 return send_error (ctx, rc);
3831 size_t len =
3832 offsetof (struct dirent, d_name) +pathconf (dir, _PC_NAME_MAX) + 1;
3833 struct dirent *p = xmalloc (len), *cur = NULL;
3834 char *list = NULL;
3836 xfree (dir);
3837 rc = 0;
3839 while (!readdir_r (d, p, &cur) && cur)
3841 if (cur->d_name[0] == '.' && cur->d_name[1] == '\0')
3842 continue;
3843 else if (cur->d_name[0] == '.' && cur->d_name[1] == '.'
3844 && cur->d_name[2] == '\0')
3845 continue;
3847 tmp = str_asprintf ("%s%s\n", list ? list : "", cur->d_name);
3849 if (!tmp)
3851 if (list)
3852 xfree (list);
3854 rc = GPG_ERR_ENOMEM;
3855 break;
3858 xfree (list);
3859 list = tmp;
3862 closedir (d);
3863 xfree (p);
3865 if (rc)
3866 return send_error (ctx, rc);
3868 if (!list)
3869 return send_error (ctx, GPG_ERR_NO_DATA);
3871 list[strlen (list) - 1] = 0;
3872 rc = xfer_data (ctx, list, strlen (list));
3873 xfree (list);
3874 return send_error (ctx, rc);
3877 static gpg_error_t
3878 bye_notify (assuan_context_t ctx, char *line)
3880 struct client_s *cl = assuan_get_pointer (ctx);
3882 #ifdef WITH_GNUTLS
3883 if (cl->thd->remote)
3885 int rc;
3889 struct timeval tv = { 0, 50000 };
3891 rc = gnutls_bye (cl->thd->tls->ses, GNUTLS_SHUT_RDWR);
3892 if (rc == GNUTLS_E_AGAIN)
3893 select (0, NULL, NULL, NULL, &tv);
3895 while (rc == GNUTLS_E_AGAIN);
3897 #endif
3899 /* This will let assuan_process_next() return. */
3900 fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK);
3901 cl->last_rc = 0; // BYE command result
3902 return 0;
3905 static gpg_error_t
3906 reset_notify (assuan_context_t ctx, char *line)
3908 struct client_s *client = assuan_get_pointer (ctx);
3910 if (client)
3911 cleanup_client (client);
3913 return 0;
3917 * This is called before every Assuan command.
3919 static gpg_error_t
3920 command_startup (assuan_context_t ctx, const char *name)
3922 struct client_s *client = assuan_get_pointer (ctx);
3923 gpg_error_t rc;
3924 struct command_table_s *cmd = NULL;
3926 log_write1 ("command='%s'", name);
3927 client->last_rc = client->opts = 0;
3929 for (int i = 0; command_table[i]; i++)
3931 if (!strcasecmp (name, command_table[i]->name))
3933 if (command_table[i]->ignore_startup)
3934 return 0;
3935 cmd = command_table[i];
3936 break;
3940 client->last_rc = rc = gpg_error (file_modified (client, cmd));
3941 return rc;
3945 * This is called after every Assuan command.
3947 static void
3948 command_finalize (assuan_context_t ctx, gpg_error_t rc)
3950 struct client_s *client = assuan_get_pointer (ctx);
3952 if (!(client->flags & FLAG_LOCK_CMD))
3953 unlock_file_mutex (client, 0);
3955 log_write1 (_("command completed: rc=%u"), client->last_rc);
3956 client->last_rc = gpg_error (GPG_ERR_UNKNOWN_COMMAND);
3957 #ifdef WITH_GNUTLS
3958 client->thd->buffer_timeout = client->thd->last_buffer_size = 0;
3959 #endif
3962 static gpg_error_t
3963 help_command (assuan_context_t ctx, char *line)
3965 gpg_error_t rc;
3966 int i;
3968 if (!line || !*line)
3970 char *tmp;
3971 char *help = str_dup (_("Usage: HELP [<COMMAND>]\n"
3972 "For commands that take an element path as an argument, each element is "
3973 "separated with an ASCII @key{TAB} character (ASCII 0x09)."
3974 "\n" "COMMANDS:"));
3976 for (i = 0; command_table[i]; i++)
3978 if (!command_table[i]->help)
3979 continue;
3981 tmp = str_asprintf ("%s %s", help, command_table[i]->name);
3982 xfree (help);
3983 help = tmp;
3986 tmp = strip_texi_and_wrap (help);
3987 xfree (help);
3988 rc = xfer_data (ctx, tmp, strlen (tmp));
3989 xfree (tmp);
3990 return send_error (ctx, rc);
3993 for (i = 0; command_table[i]; i++)
3995 if (!strcasecmp (line, command_table[i]->name))
3997 char *help, *tmp;
3999 if (!command_table[i]->help)
4000 break;
4002 help = strip_texi_and_wrap (command_table[i]->help);
4003 tmp = str_asprintf (_("Usage: %s"), help);
4004 xfree (help);
4005 rc = xfer_data (ctx, tmp, strlen (tmp));
4006 xfree (tmp);
4007 return send_error (ctx, rc);
4011 return send_error (ctx, GPG_ERR_INV_NAME);
4014 static void
4015 new_command (const char *name, int ignore, int unlock,
4016 gpg_error_t (*handler) (assuan_context_t, char *),
4017 const char *help)
4019 int i = 0;
4021 if (command_table)
4022 for (i = 0; command_table[i]; i++);
4024 command_table =
4025 xrealloc (command_table, (i + 2) * sizeof (struct command_table_s *));
4026 command_table[i] = xcalloc (1, sizeof (struct command_table_s));
4027 command_table[i]->name = name;
4028 command_table[i]->handler = handler;
4029 command_table[i]->ignore_startup = ignore;
4030 command_table[i]->unlock = unlock;
4031 command_table[i++]->help = help;
4032 command_table[i] = NULL;
4035 void
4036 deinit_commands ()
4038 int i;
4040 for (i = 0; command_table[i]; i++)
4041 xfree (command_table[i]);
4043 xfree (command_table);
4046 static int
4047 sort_commands (const void *arg1, const void *arg2)
4049 struct command_table_s *const *a = arg1;
4050 struct command_table_s *const *b = arg2;
4052 if (!*a || !*b)
4053 return 0;
4054 else if (*a && !*b)
4055 return 1;
4056 else if (!*a && *b)
4057 return -1;
4059 return strcmp ((*a)->name, (*b)->name);
4062 static gpg_error_t
4063 passwd_command (assuan_context_t ctx, char *line)
4065 struct client_s *client = assuan_get_pointer (ctx);
4066 gpg_error_t rc;
4067 struct argv_s *args[] = {
4068 &(struct argv_s) {"reset", OPTION_TYPE_NOARG, parse_opt_reset},
4069 &(struct argv_s) {"s2k-count", OPTION_TYPE_ARG, parse_opt_s2k_count},
4070 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG, parse_opt_no_passphrase},
4071 NULL
4074 if (client->flags & FLAG_NEW)
4075 return send_error (ctx, GPG_ERR_INV_STATE);
4077 client->crypto->save.s2k_count =
4078 config_get_ulong (client->filename, "s2k_count");
4079 rc = parse_options (&line, args, client);
4080 if (rc)
4081 return send_error (ctx, rc);
4083 if (!rc && client->opts & OPT_RESET)
4085 rc = cache_clear (client->md5file);
4086 if (!rc)
4087 send_status_all (STATUS_CACHE, NULL);
4090 if (!rc)
4092 if (!IS_PKI (client->crypto))
4094 struct crypto_s *crypto;
4096 xfree (client->crypto->filename);
4097 client->crypto->filename = str_dup (client->filename);
4098 rc = change_passwd (ctx, client->filename,
4099 client->flags & FLAG_NO_PINENTRY, &crypto,
4100 (client->opts & OPT_NO_PASSPHRASE));
4101 if (!rc)
4103 cleanup_crypto (&client->crypto);
4104 client->crypto = crypto;
4105 update_checksum (client);
4106 cleanup_crypto_stage1 (client->crypto);
4109 #ifdef WITH_AGENT
4110 else
4112 if (client->crypto->save.s2k_count)
4113 rc = send_to_agent (client->crypto->agent, NULL, NULL,
4114 "OPTION s2k-count=%lu",
4115 client->crypto->save.s2k_count);
4117 if (!rc)
4118 rc = agent_passwd (client->crypto);
4120 #endif
4123 return send_error (ctx, rc);
4126 static gpg_error_t
4127 parse_keygrip_opt_sign (void *data, void *value)
4129 struct client_s *client = data;
4131 (void) value;
4132 client->opts |= OPT_SIGN;
4133 return 0;
4136 static gpg_error_t
4137 keygrip_command (assuan_context_t ctx, char *line)
4139 struct client_s *client = assuan_get_pointer (ctx);
4140 gpg_error_t rc;
4141 struct crypto_s *crypto = NULL;
4142 struct argv_s *args[] = {
4143 &(struct argv_s) {"sign", OPTION_TYPE_NOARG, parse_keygrip_opt_sign},
4144 NULL
4147 if (!line || !*line)
4148 return send_error (ctx, GPG_ERR_SYNTAX);
4150 rc = parse_options (&line, args, client);
4151 if (rc)
4152 return send_error (ctx, rc);
4154 if (!valid_filename (line))
4155 return send_error (ctx, GPG_ERR_INV_VALUE);
4157 rc = init_client_crypto (&crypto);
4158 if (rc)
4159 return send_error (ctx, rc);
4161 rc = read_data_file (line, crypto);
4162 if (!rc)
4164 char *hexgrip = NULL;
4166 if (!IS_PKI (crypto))
4168 cleanup_crypto (&crypto);
4169 return send_error (ctx, GPG_ERR_NOT_SUPPORTED);
4172 if (client->opts & OPT_SIGN)
4174 if (valid_keygrip (crypto->sign_grip, sizeof (crypto->sign_grip)))
4175 hexgrip = bin2hex (crypto->sign_grip, sizeof (crypto->sign_grip));
4178 if (!hexgrip)
4179 hexgrip = bin2hex (crypto->grip, sizeof (crypto->grip));
4181 if (!hexgrip)
4182 rc = GPG_ERR_ENOMEM;
4183 else
4184 rc = xfer_data (ctx, hexgrip, strlen (hexgrip));
4186 xfree (hexgrip);
4189 UPDATE_AGENT_CTX (client, crypto);
4190 cleanup_crypto (&crypto);
4191 return send_error (ctx, rc);
4194 static gpg_error_t
4195 parse_opt_data (void *data, void *value)
4197 struct client_s *client = data;
4199 (void) value;
4200 client->opts |= OPT_DATA;
4201 return 0;
4204 static gpg_error_t
4205 getinfo_command (assuan_context_t ctx, char *line)
4207 struct client_s *client = assuan_get_pointer (ctx);
4208 gpg_error_t rc;
4209 char buf[ASSUAN_LINELENGTH];
4210 struct argv_s *args[] = {
4211 &(struct argv_s) {"data", OPTION_TYPE_NOARG, parse_opt_data},
4212 NULL
4215 rc = parse_options (&line, args, client);
4216 if (rc)
4217 return send_error (ctx, rc);
4219 if (!strcasecmp (line, "clients"))
4221 if (client->opts & OPT_DATA)
4223 MUTEX_LOCK (&cn_mutex);
4224 snprintf (buf, sizeof (buf), "%i", slist_length (cn_thread_list));
4225 MUTEX_UNLOCK (&cn_mutex);
4226 rc = xfer_data (ctx, buf, strlen (buf));
4228 else
4229 rc = send_status (ctx, STATUS_CLIENTS, NULL);
4231 else if (!strcasecmp (line, "cache"))
4233 if (client->opts & OPT_DATA)
4235 snprintf (buf, sizeof (buf), "%u", cache_file_count ());
4236 rc = xfer_data (ctx, buf, strlen (buf));
4238 else
4239 rc = send_status (ctx, STATUS_CACHE, NULL);
4241 else if (!strcasecmp (line, "pid"))
4243 char buf[32];
4244 pid_t pid = getpid ();
4246 snprintf (buf, sizeof (buf), "%i", pid);
4247 rc = xfer_data (ctx, buf, strlen (buf));
4249 else if (!strcasecmp (line, "version"))
4251 char *buf = str_asprintf ("0x%06x %s%s", VERSION_HEX,
4252 #ifdef WITH_LIBACL
4253 "ACL "
4254 #endif
4255 #ifdef WITH_GNUTLS
4256 "GNUTLS "
4257 #endif
4258 #ifdef WITH_QUALITY
4259 "QUALITY "
4260 #endif
4261 "", use_agent ? "AGENT" : "");
4262 rc = xfer_data (ctx, buf, strlen (buf));
4263 xfree (buf);
4265 else if (!strcasecmp (line, "last_error"))
4267 if (client->last_error)
4268 rc = xfer_data (ctx, client->last_error, strlen (client->last_error));
4269 else
4270 rc = GPG_ERR_NO_DATA;
4272 else
4273 rc = gpg_error (GPG_ERR_SYNTAX);
4275 return send_error (ctx, rc);
4278 #ifdef WITH_AGENT
4279 static gpg_error_t
4280 send_data_cb (void *user, const void *buf, size_t len)
4282 assuan_context_t ctx = user;
4284 return assuan_send_data (ctx, buf, len);
4287 static gpg_error_t
4288 send_status_cb (void *user, const char *line)
4290 assuan_context_t ctx = user;
4291 char keyword[200], *k;
4292 const char *p;
4294 for (p = line, k = keyword; *p; p++)
4296 if (isspace (*p))
4297 break;
4299 *k++ = *p;
4302 *k = 0;
4303 if (*p == '#')
4304 p++;
4306 while (isspace (*p))
4307 p++;
4309 return assuan_write_status (ctx, keyword, *p ? p : NULL);
4311 #endif
4313 static gpg_error_t
4314 agent_command (assuan_context_t ctx, char *line)
4316 gpg_error_t rc = 0;
4318 if (!use_agent)
4319 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
4321 #ifdef WITH_AGENT
4322 struct client_s *client = assuan_get_pointer (ctx);
4324 if (!line || !*line)
4325 return send_error (ctx, GPG_ERR_SYNTAX);
4327 assuan_set_flag (client->crypto->agent->ctx, ASSUAN_CONVEY_COMMENTS, 1);
4328 rc = assuan_transact (client->crypto->agent->ctx, line, send_data_cb,
4329 client->ctx, agent_loopback_cb, client->crypto,
4330 send_status_cb, client->ctx);
4331 if (gpg_err_code (rc) == GPG_ERR_ASS_CANCELED)
4333 char *line;
4334 size_t len;
4336 rc = assuan_write_line (client->crypto->agent->ctx, "CAN");
4337 if (!rc)
4339 rc = assuan_read_line (client->crypto->agent->ctx, &line, &len);
4340 if (!rc)
4341 rc = gpg_error (GPG_ERR_ASS_CANCELED);
4345 assuan_set_flag (client->crypto->agent->ctx, ASSUAN_CONVEY_COMMENTS, 0);
4346 #endif
4347 return send_error (ctx, rc);
4350 void
4351 init_commands ()
4353 /* !BEGIN-HELP-TEXT!
4355 * This comment is used as a marker to generate the offline documentation
4356 * found in doc/pwmd.info. The indentation needs to be kept for the awk
4357 * script to determine where commands begin and end.
4359 new_command("HELP", 1, 1, help_command, _(
4360 "HELP [<COMMAND>]\n"
4361 "Show available commands or command specific help text."
4364 new_command("AGENT", 1, 1, agent_command, _(
4365 "AGENT <command>\n"
4366 "Send a @command{gpg-agent} protocol @var{command} directly to the "
4367 "@command{gpg-agent}."
4370 new_command("GETINFO", 1, 1, getinfo_command, _(
4371 "GETINFO [--data] CACHE | CLIENTS | PID | LAST_ERROR | VERSION\n"
4372 "Get server and other information: @var{cache} returns the number of cached "
4373 "documents via a status message. @var{clients} returns the number of "
4374 "connected clients via a status message. @var{pid} returns the process ID "
4375 "number of the server via a data response. @var{VERSION} returns the server "
4376 "version number and compile-time features with a data response with each "
4377 "being space delimited. @var{LAST_ERROR} returns a detailed description of "
4378 "the last failed command when available. @xref{Status Messages}. "
4379 "\n"
4380 "When the @option{--data} option is specified then the result will be sent "
4381 "via a data response rather than a status message."
4384 new_command("PASSWD", 0, 0, passwd_command, _(
4385 "PASSWD [--reset] [--s2k-count=N] [--no-passphrase]\n"
4386 "Changes the passphrase of the secret key required to open the current "
4387 "file or the passphrase of a symmetrically encrypted data file. When the "
4388 "@option{--reset} option is passed then the cache entry for the current "
4389 "file will be reset and the passphrase, if any, will be required during the "
4390 "next @code{OPEN}. @xref{OPEN}."
4391 "\n"
4392 "The @option{--s2k-count} option sets number of hash iterations for a "
4393 "passphrase and must be either @code{0} to use the calibrated count of the "
4394 "machine (the default), or a value greater than or equal to @code{65536}. "
4395 "@xref{SAVE}. This option has no effect for symmetrically encrypted data "
4396 "files."
4397 "\n"
4398 "The @option{--no-passphrase} option will prevent requiring a passphrase for "
4399 "the data file, although a passphrase may be required when changing it."
4402 new_command("KEYGRIP", 1, 1, keygrip_command, _(
4403 "KEYGRIP [--sign] <filename>\n"
4404 "Returns the hex encoded keygrip of the specified @var{filename} with a "
4405 "data response."
4406 "\n"
4407 "When the @option{--sign} option is specified then the key used for signing "
4408 "of the specified @var{filename} will be returned."
4409 "\n"
4410 "For symmetrically encrypted data files this command returns the error "
4411 "GPG_ERR_NOT_SUPPORTED."
4414 new_command("OPEN", 1, 1, open_command, _(
4415 "OPEN [--lock] <filename> [<passphrase>]\n"
4416 "Opens @var{filename} using @var{passphrase}. When the filename is not "
4417 "found on the file-system then a new document will be created. If the file "
4418 "is found, it is looked for in the file cache. If cached and no "
4419 "@var{passphrase} was specified then the cached document is opened. When not "
4420 "cached, @cite{pinentry(1)} will be used to retrieve the passphrase to use "
4421 "for decryption unless @option{disable-pinentry} (@pxref{OPTION}) was "
4422 "specified."
4423 "\n"
4424 "When the @option{--lock} option is passed then the file mutex will be "
4425 "locked as if the @code{LOCK} command (@pxref{LOCK}) had been sent after the "
4426 "file has been opened."
4429 new_command("SAVE", 0, 0, save_command, _(
4430 "SAVE [--no-passphrase] [--reset] [--no-agent] [--s2k-count=N] [--cipher=<algo>] [--cipher-iterations=N] [--inquire-keyparam] [--keygrip=hexstring] [--sign-keygrip=hexstring]\n"
4431 "Writes the @abbr{XML} document to disk. The file written to is the file that "
4432 "was opened using the @code{OPEN} command (@pxref{OPEN}). If the file is a "
4433 "new one or the option @option{--inquire-keyparam} was passed, then a new "
4434 "keypair will be generated and a pinentry will be used to prompt for the "
4435 "passphrase to encrypt with unless the @option{--no-passphrase} option was "
4436 "passed in which case the data file will not be passphrase protected. "
4437 "\n"
4438 "The @option{--no-agent} option disables use of @command{gpg-agent} for "
4439 "passphrase retrieval and caching of new files when @command{gpg-agent} "
4440 "use is enabled. The datafile will be symmetrically encrypted and will not "
4441 "use or generate any keypair."
4442 "\n"
4443 "The @option{--reset} option will clear the cache entry for the current file "
4444 "and require a passphrase, if needed, before saving."
4445 "\n"
4446 "The @option{--cipher} option can be used to encrypt the @abbr{XML} data to "
4447 "an alternate cipher. The default is @code{aes256}. See the Configuration "
4448 "(@pxref{Configuration}) for available ciphers."
4449 "\n"
4450 "The @option{--cipher-iterations} option specifies the number of times to "
4451 "encrypt the XML data. The default is 0 although 1 iteration is still done."
4452 "\n"
4453 "The @option{--inquire-keyparam} option will send a server @emph{INQUIRE} to "
4454 "the client to obtain the key paramaters to use when generating a new "
4455 "keypair. The inquired data is expected to be an S-expression. If not "
4456 "specified then an @samp{RSA} key of @samp{2048} bits will be generated "
4457 "unless otherwise set in the configuration file (@pxref{Configuration}). Note "
4458 "that when this option is specified a new keypair will be generated "
4459 "reguardless if the file is a new one and that if the data file is protected "
4460 "the passphrase to open it will be required before generating the new keypair."
4461 "\n"
4462 "You can encrypt the data file to a public key other than the one that it "
4463 "was originally encrypted with by passing the @option{--keygrip} option with "
4464 "the hex encoded keygrip of the public key as its argument. The keygrip may "
4465 "be of any key that @command{gpg-agent} knows about. The "
4466 "@option{--sign-keygrip} option may also be used to sign with an alternate "
4467 "secret key. This option may be needed when using a smartcard. This option "
4468 "has no effect with symmetrically encrypted data files."
4469 "\n"
4470 "The @option{--s2k-count} option sets number of hash iterations for a "
4471 "passphrase. A value less-than @code{65536} will use the machine calibrated "
4472 "value and is the default. This setting only affects new files. To change "
4473 "the setting use the @code{PASSWD} command (@pxref{PASSWD}). This option "
4474 "has no effect with symmetrically encrypted data files."
4477 new_command("ISCACHED", 1, 0, iscached_command, _(
4478 "ISCACHED [--lock] <filename>\n"
4479 "An @emph{OK} response is returned if the specified @var{filename} is found "
4480 "in the file cache. If not found in the cache but exists on the filesystem "
4481 "then @var{GPG_ERR_NO_DATA} is returned. Otherwise a filesystem error is "
4482 "returned."
4483 "\n"
4484 "The @option{lock} option will lock the file mutex of @var{filename} when the "
4485 "file exists; it does not need to be opened nor cached."
4488 new_command("CLEARCACHE", 1, 1, clearcache_command, _(
4489 "CLEARCACHE [<filename>]\n"
4490 "Clears a file cache entry for all or the specified @var{filename}."
4493 new_command("CACHETIMEOUT", 1, 1, cachetimeout_command, _(
4494 "CACHETIMEOUT <filename> <seconds>\n"
4495 "The time in @var{seconds} until @var{filename} will be removed from the "
4496 "cache. @code{-1} will keep the cache entry forever, @code{0} will require "
4497 "the passphrase for each @code{OPEN} or @code{SAVE} command (@pxref{OPEN}, "
4498 "@pxref{SAVE}). @xref{Configuration}, and the @code{cache_timeout} "
4499 "parameter."
4502 new_command("LIST", 0, 1, list_command, _(
4503 "LIST [--inquire] [--no-recurse] [--verbose] [--with-target] [--all] [[!]element[<TAB>[!]child[..]]]\n"
4504 "If no element path is given then a newline separated list of root elements "
4505 "is returned with a data response. If given, then all reachable elements "
4506 "of the specified element path are returned unless the @option{--no-recurse} "
4507 "option is specified. If specified, only the child elements of the element "
4508 "path are returned without recursing into grandchildren. Each resulting "
4509 "element is prefixed with the literal @code{!} character when the element "
4510 "contains no @code{target} attribute. @xref{Target Attribute}, for details."
4511 "\n"
4512 "When the @option{--verbose} option is passed then each element path "
4513 "returned will have zero or more flags appened to it. These flags are "
4514 "delimited from the element path by a single space character. A flag itself "
4515 "is a single character. Flag @code{+} indicates that there are child nodes of "
4516 "the current element path. Flag @code{E} indicates that an element of an "
4517 "element path contained in a @var{target} attribute could not be found. Flag "
4518 "@code{O} indicates that a @var{target} attribute recursion limit was reached "
4519 "(@pxref{Configuration}). Flag @code{T} will append the resolved element path "
4520 "of the @var{target} attribute contained in the current element (see below)."
4521 "\n"
4522 "The @option{--with-target} option implies @option{--verbose} and will append "
4523 "an additional flag @code{T} followed by a single space then an element path. "
4524 "The appended element path is the resolved path (@pxref{REALPATH}) of the "
4525 "current element when it contains a @var{target} attribute. When no "
4526 "@var{target} attribute is found then no flag will be appended."
4527 "\n"
4528 "The @option{--no-recurse} option limits the amount of data returned to only "
4529 "the listing of children of the specified element path and not any "
4530 "grandchildren."
4531 "\n"
4532 "The @option{--all} option lists the entire element tree for each root "
4533 "element. This option also implies option @option{--verbose}."
4534 "\n"
4535 "When the @option{--inquire} option is passed then all remaining non-option "
4536 "arguments are retrieved via a server @emph{INQUIRE}."
4539 new_command("REALPATH", 0, 1, realpath_command, _(
4540 "REALPATH [--inquire] [!]element[<TAB>[!]child[..]]\n"
4541 "Resolves all @code{target} attributes of the specified element path and "
4542 "returns the result with a data response. @xref{Target Attribute}, for details."
4543 "\n"
4544 "When the @option{--inquire} option is passed then all remaining non-option "
4545 "arguments are retrieved via a server @emph{INQUIRE}."
4548 new_command("STORE", 0, 1, store_command, _(
4549 "STORE [!]element[<TAB>[!]child[..]]<TAB>[content]\n"
4550 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
4551 "\n"
4552 "Creates a new element path or modifies the @var{content} of an existing "
4553 "element. If only a single element is specified then a new root element is "
4554 "created. Otherwise, elements are @key{TAB} delimited and the content will be "
4555 "set to the final @key{TAB} delimited element. If no @var{content} is "
4556 "specified after the final @key{TAB}, then the content of the element will "
4557 "be removed, or empty when creating a new element."
4558 "\n"
4559 "The only restriction of an element name is that it not contain whitespace "
4560 "or begin with the literal element character @code{!} unless specifying a "
4561 "literal element (@pxref{Target Attribute}). There is no whitespace between "
4562 "the @key{TAB} delimited elements. It is recommended that the content of an "
4563 "element be base64 encoded when it contains control or @key{TAB} characters "
4564 "to prevent @abbr{XML} parsing and @command{pwmd} syntax errors."
4567 new_command("RENAME", 0, 1, rename_command, _(
4568 "RENAME [--inquire] [!]element[<TAB>[!]child[..]] <value>\n"
4569 "Renames the specified @var{element} to the new @var{value}. If an element of "
4570 "the same name as the @var{value} already exists it will be overwritten."
4571 "\n"
4572 "When the @option{--inquire} option is passed then all remaining non-option "
4573 "arguments are retrieved via a server @emph{INQUIRE}."
4576 new_command("COPY", 0, 1, copy_command, _(
4577 "COPY [--inquire] [!]source[<TAB>[!]child[..]] [!]dest[<TAB>[!]child[..]]\n"
4578 "Copies the entire element tree starting from the child node of the source "
4579 "element, to the destination element path. If the destination element path "
4580 "does not exist then it will be created; otherwise it is overwritten."
4581 "\n"
4582 "Note that attributes from the source element are merged into the "
4583 "destination element when the destination element path exists. When an "
4584 "attribute of the same name exists in both the source and destination "
4585 "elements then the destination attribute will be updated to the source "
4586 "attribute value."
4587 "\n"
4588 "When the @option{--inquire} option is passed then all remaining non-option "
4589 "arguments are retrieved via a server @emph{INQUIRE}."
4592 new_command("MOVE", 0, 1, move_command, _(
4593 "MOVE [--inquire] [!]source[<TAB>[!]child[..]] [[!]dest[<TAB>[!]child[..]]]\n"
4594 "Moves the source element path to the destination element path. If the "
4595 "destination is not specified then it will be moved to the root node of the "
4596 "document. If the destination is specified and exists then it will be "
4597 "overwritten; otherwise non-existing elements of the destination element "
4598 "path will be created."
4599 "\n"
4600 "When the @option{--inquire} option is passed then all remaining non-option "
4601 "arguments are retrieved via a server @emph{INQUIRE}."
4604 new_command("DELETE", 0, 1, delete_command, _(
4605 "DELETE [--inquire] [!]element[<TAB>[!]child[..]]\n"
4606 "Removes the specified element path and all of its children. This may break "
4607 "an element with a @code{target} attribute (@pxref{Target Attribute}) that "
4608 "refers to this element or any of its children."
4609 "\n"
4610 "When the @option{--inquire} option is passed then all remaining non-option "
4611 "arguments are retrieved via a server @emph{INQUIRE}."
4614 new_command("GET", 0, 1, get_command, _(
4615 "GET [--inquire] [!]element[<TAB>[!]child[..]]\n"
4616 "Retrieves the content of the specified element. The content is returned "
4617 "with a data response."
4618 "\n"
4619 "When the @option{--inquire} option is passed then all remaining non-option "
4620 "arguments are retrieved via a server @emph{INQUIRE}."
4623 new_command("ATTR", 0, 1, attr_command, _(
4624 "ATTR [--inquire] SET|GET|DELETE|LIST [<attribute>] [!]element[<TAB>[!]child[..]] ..\n"
4625 "@table @asis\n"
4626 "@item ATTR SET attribute [!]element[<TAB>[!]child[..]] [value]\n"
4627 "\n"
4628 " Stores or updates an @var{attribute} name and optional @var{value} of an "
4629 "element. When no @var{value} is specified any existing value will be removed."
4630 "\n"
4631 "@item ATTR DELETE attribute [!]element[<TAB>[!]child[..]]\n"
4632 "\n"
4633 " Removes an @var{attribute} from an element."
4634 "\n"
4635 "@item ATTR LIST [!]element[<TAB>[!]child[..]]\n"
4636 "\n"
4637 " Retrieves a newline separated list of attributes names and values "
4638 "from the specified element. Each attribute name and value is space delimited."
4639 "\n"
4640 "@item ATTR GET attribute [!]element[<TAB>[!]child[..]]\n"
4641 "\n"
4642 " Retrieves the value of an @var{attribute} from an element."
4643 "@end table\n"
4644 "\n"
4645 "The @code{_name} attribute (case sensitive) cannot be removed nor modified. "
4646 "Use the @code{DELETE} (@pxref{DELETE}) or @code{RENAME} (@pxref{RENAME}) "
4647 "commands instead."
4648 "\n"
4649 "The @code{_mtime} attribute is updated each time an element is modified by "
4650 "either storing content, editing attributes or by deleting a child element. "
4651 "The @code{_ctime} attribute is created for each new element in an element "
4652 "path."
4653 "\n"
4654 "When the @option{--inquire} option is passed then all remaining non-option "
4655 "arguments are retrieved via a server @emph{INQUIRE}."
4656 "\n"
4657 "@xref{Target Attribute}, for details about this special attribute."
4660 new_command("XPATH", 0, 1, xpath_command, _(
4661 "XPATH [--inquire] <expression>[<TAB>[value]]\n"
4662 "Evaluates an XPath @var{expression}. If no @var{value} argument is "
4663 "specified it is assumed the expression is a request to return a result. "
4664 "Otherwise, the result is set to the @var{value} argument and the document is "
4665 "updated. If there is no @var{value} after the @key{TAB} character, the value "
4666 "is assumed to be empty and the document is updated. For example:"
4667 "@sp 1\n"
4668 "@example\n"
4669 "XPATH //element[@@_name='password']@key{TAB}\n"
4670 "@end example\n"
4671 "@sp 1"
4672 "would clear the content of all @code{password} elements in the data file "
4673 "while leaving off the trailing @key{TAB} would return all @code{password} "
4674 "elements in @abbr{XML} format."
4675 "\n"
4676 "When the @option{--inquire} option is passed then all remaining non-option "
4677 "arguments are retrieved via a server @emph{INQUIRE}."
4678 "\n"
4679 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
4680 "expression syntax."
4683 new_command("XPATHATTR", 0, 1, xpathattr_command, _(
4684 "XPATHATTR [--inquire] SET|DELETE <name> <expression>[<TAB>[<value>]]\n"
4685 "Like the @code{XPATH} command (@pxref{XPATH}) but operates on element "
4686 "attributes and does not return a result. For the @var{SET} operation the "
4687 "@var{value} is optional but the field is required. If not specified then "
4688 "the attribute value will be empty. For example:"
4689 "@sp 1"
4690 "@example\n"
4691 "XPATHATTR SET password //element[@@_name='password']@key{TAB}\n"
4692 "@end example\n"
4693 "@sp 1"
4694 "would create an @code{password} attribute for each @code{password} element "
4695 "found in the document. The attribute value will be empty but still exist."
4696 "\n"
4697 "When the @option{--inquire} option is passed then all remaining non-option "
4698 "arguments are retrieved via a server @emph{INQUIRE}."
4699 "\n"
4700 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
4701 "expression syntax."
4704 new_command("IMPORT", 0, 1, import_command, _(
4705 "IMPORT [--root [!]element[<TAB>[!]child[..]]] <content>\n"
4706 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
4707 "\n"
4708 "Like the @code{STORE} command (@pxref{STORE}), but the @var{content} "
4709 "argument is raw @abbr{XML} data. The content is created as a child of "
4710 "the element path specified with the @option{--root} option or at the "
4711 "document root when not specified. Existing elements of the same name will "
4712 "be overwritten."
4713 "\n"
4714 "The content must begin with an @abbr{XML} element node. @xref{Introduction}, "
4715 "for details."
4718 new_command("DUMP", 0, 1, dump_command, _(
4719 "DUMP\n"
4720 "Shows the in memory @abbr{XML} document with indenting. @xref{XPATH}, for "
4721 "dumping a specific node."
4724 new_command("LOCK", 0, 0, lock_command, _(
4725 "LOCK\n"
4726 "Locks the mutex associated with the opened file. This prevents other clients "
4727 "from sending commands to the same opened file until the client "
4728 "that sent this command either disconnects or sends the @code{UNLOCK} "
4729 "command. @xref{UNLOCK}."
4732 new_command("UNLOCK", 1, 0, unlock_command, _(
4733 "UNLOCK\n"
4734 "Unlocks the file mutex which was locked with the @code{LOCK} command or "
4735 "a commands' @option{--lock} option (@pxref{LOCK}, @pxref{OPEN}, "
4736 "@pxref{ISCACHED})."
4739 new_command("GETCONFIG", 1, 1, getconfig_command, _(
4740 "GETCONFIG [filename] <parameter>\n"
4741 "Returns the value of a @command{pwmd} configuration @var{parameter} with a "
4742 "data response. If no file has been opened then the value for @var{filename} "
4743 "or the default from the @samp{global} section will be returned. If a file "
4744 "has been opened and no @var{filename} is specified, a value previously "
4745 "set with the @code{OPTION} command (@pxref{OPTION}) will be returned."
4748 new_command("OPTION", 1, 1, option_command, _(
4749 "OPTION <NAME>=<VALUE>\n"
4750 "Sets a client option @var{name} to @var{value}. The value for an option is "
4751 "kept for the duration of the connection."
4752 "\n"
4753 "@table @asis\n"
4754 "@item DISABLE-PINENTRY\n"
4755 "Disable use of @command{pinentry} for passphrase retrieval. When set, a "
4756 "server inquire is sent to the client to obtain the passphrase. This option "
4757 "may be set as needed before the @pxref{OPEN}, @pxref{PASSWD}, and "
4758 "@pxref{SAVE} commands."
4759 "\n"
4760 "@item PINENTRY-TIMEOUT\n"
4761 "Sets the number of seconds before a pinentry prompt will return an error "
4762 "while waiting for user input."
4763 "\n"
4764 "@item TTYNAME\n"
4765 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4766 "\n"
4767 "@item TTYTYPE\n"
4768 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4769 "\n"
4770 "@item DISPLAY\n"
4771 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4772 "\n"
4773 "@item PINENTRY-DESC\n"
4774 "Sets the description string of the @command{gpg-agent} and @command{pinentry} dialog."
4775 "\n"
4776 "@item PINENTRY-TITLE\n"
4777 "Sets the title string of the @command{gpg-agent} and @command{pinentry} dialog."
4778 "\n"
4779 "@item PINENTRY-PROMPT\n"
4780 "Sets the prompt string of the @command{gpg-agent} and @command{pinentry} dialog."
4781 "\n"
4782 "@item LC-CTYPE\n"
4783 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4784 "\n"
4785 "@item LC-MESSAGES\n"
4786 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4787 "\n"
4788 "@item NAME\n"
4789 "Associates the thread ID of the connection with the specified textual "
4790 "representation. Useful for debugging log messages."
4791 "\n"
4792 "@item LOCK-TIMEOUT\n"
4793 "When not @code{0}, the duration in tenths of a second to wait for the file "
4794 "mutex which has been locked by another thread to be released before returning "
4795 "an error. When @code{-1}, then an error will be returned immediately."
4796 "\n"
4797 "@item LOG-LEVEL\n"
4798 "An integer specifiying the logging level."
4799 "@end table\n"
4802 new_command("LS", 1, 1, ls_command, _(
4803 "LS\n"
4804 "Lists the available data files stored in the data directory "
4805 "(@file{~/.pwmd/data}). The result is a newline separated list of filenames."
4808 new_command("RESET", 1, 1, NULL, _(
4809 "RESET\n"
4810 "Closes the currently opened file but keeps any previously set client options."
4813 new_command("NOP", 1, 1, NULL, _(
4814 "NOP\n"
4815 "Does nothing. Always returns successfully."
4818 /* !END-HELP-TEXT! */
4819 new_command ("CANCEL", 1, 1, NULL, NULL);
4820 new_command ("END", 1, 1, NULL, NULL);
4821 new_command ("BYE", 1, 1, NULL, NULL);
4823 int i;
4824 for (i = 0; command_table[i]; i++);
4825 qsort (command_table, i - 1, sizeof (struct command_table_s *),
4826 sort_commands);
4829 gpg_error_t
4830 register_commands (assuan_context_t ctx)
4832 int i = 0, rc;
4834 for (; command_table[i]; i++)
4836 if (!command_table[i]->handler)
4837 continue;
4839 rc = assuan_register_command (ctx, command_table[i]->name,
4840 command_table[i]->handler,
4841 command_table[i]->help);
4842 if (rc)
4843 return rc;
4846 rc = assuan_register_bye_notify (ctx, bye_notify);
4847 if (rc)
4848 return rc;
4850 rc = assuan_register_reset_notify (ctx, reset_notify);
4851 if (rc)
4852 return rc;
4854 rc = assuan_register_pre_cmd_notify (ctx, command_startup);
4855 if (rc)
4856 return rc;
4858 return assuan_register_post_cmd_notify (ctx, command_finalize);