Fix potential memory leak.
[pwmd.git] / src / commands.c
blob89f4cb24ba74f379f1519bbea630f6ac34c2d5c1
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;
177 gpg_error_t rc = 0;
179 if (new)
181 client->doc = new_document ();
182 if (client->doc)
184 xmlChar *result;
185 int len;
187 xmlDocDumpFormatMemory (client->doc, &result, &len, 0);
188 client->crypto->plaintext = result;
189 client->crypto->plaintext_len = len;
190 if (!client->crypto->plaintext)
192 xmlFreeDoc (client->doc);
193 client->doc = NULL;
197 else if (!cached)
198 rc = parse_doc ((char *) client->crypto->plaintext,
199 client->crypto->plaintext_len, (xmlDocPtr *)&client->doc);
201 return rc;
204 static void
205 free_client (struct client_s *client)
207 if (client->doc)
208 xmlFreeDoc (client->doc);
210 xfree (client->crc);
211 xfree (client->filename);
212 xfree (client->last_error);
214 if (client->crypto)
216 cleanup_crypto_stage2 (client->crypto);
217 if (client->crypto->pkey_sexp)
218 gcry_sexp_release (client->crypto->pkey_sexp);
220 client->crypto->pkey_sexp = NULL;
221 memset (client->crypto->sign_grip, 0,
222 sizeof (client->crypto->sign_grip));
223 memset (client->crypto->grip, 0, sizeof(client->crypto->grip));
227 void
228 cleanup_client (struct client_s *client)
230 assuan_context_t ctx = client->ctx;
231 struct client_thread_s *thd = client->thd;
232 struct crypto_s *crypto = client->crypto;
233 long lock_timeout = client->lock_timeout;
234 int no_pinentry = (client->flags & FLAG_NO_PINENTRY);
235 struct pinentry_option_s pin_opts;
236 xmlErrorPtr xml_error = client->xml_error;
237 #ifdef WITH_AGENT
238 struct pinentry_option_s agent_pin_opts;
240 if (crypto && crypto->agent)
241 memcpy (&agent_pin_opts, &crypto->agent->pinentry_opts,
242 sizeof(struct pinentry_option_s));
243 #endif
245 memcpy (&pin_opts, &client->pinentry_opts, sizeof(struct pinentry_option_s));
246 unlock_file_mutex (client, client->flags & FLAG_NEW);
247 free_client (client);
248 memset (client, 0, sizeof (struct client_s));
249 client->xml_error = xml_error;
250 client->crypto = crypto;
251 client->ctx = ctx;
252 client->thd = thd;
253 client->lock_timeout = lock_timeout;
254 memcpy (&client->pinentry_opts, &pin_opts, sizeof(struct pinentry_option_s));
255 client->flags |= no_pinentry ? FLAG_NO_PINENTRY : 0;
256 #ifdef WITH_AGENT
257 if (crypto && crypto->agent)
258 memcpy (&crypto->agent->pinentry_opts, &agent_pin_opts,
259 sizeof(struct pinentry_option_s));
260 #endif
263 static gpg_error_t
264 open_finalize (assuan_context_t ctx, char *key, size_t keylen)
266 struct client_s *client = assuan_get_pointer (ctx);
267 gpg_error_t rc = 0;
268 struct cache_data_s *cdata = cache_get_data (client->md5file);
269 int cached = 0, keyarg = key ? 1 : 0;
270 size_t keysize;
271 unsigned char *salted_key = NULL;
272 int algo;
273 int pin_try = 1;
274 int pin_tries = 3;
275 char *pin_title = client->pinentry_opts.title;
277 client->crypto->filename = str_dup (client->filename);
278 if (cdata || client->flags & FLAG_NEW)
280 if (cdata && !(client->flags & FLAG_NEW))
282 rc = decrypt_cache (client->crypto, cdata->doc, cdata->doclen);
283 if (rc)
284 return rc;
287 cached = cdata != NULL;
288 goto done;
291 if (!key && !IS_PKI (client->crypto)
292 && !(client->crypto->hdr.flags & PWMD_FLAG_NO_PASSPHRASE))
294 if (client->flags & FLAG_NO_PINENTRY)
296 rc = inquire_passphrase (ctx, "PASSPHRASE", (unsigned char **)&key,
297 &keylen);
298 if (rc)
299 return rc;
301 else
303 client->pinentry_opts.timeout = config_get_integer (client->filename,
304 "pinentry_timeout");
305 pin_again:
306 rc = getpin_common (client->ctx, client->filename, PINENTRY_OPEN,
307 &key, &keylen);
308 if (rc)
309 return rc;
313 if (!IS_PKI (client->crypto))
315 if (client->crypto->hdr.flags & PWMD_FLAG_NO_PASSPHRASE)
317 keylen = 1;
318 key = gcry_malloc (keylen);
319 memset (key, 0, keylen);
322 algo = cipher_to_gcrypt (client->crypto->hdr.flags);
323 rc = hash_key (algo, client->crypto->hdr.salt,
324 sizeof(client->crypto->hdr.salt), key, keylen,
325 (void **)&salted_key, &keysize);
326 if (!keyarg)
327 gcry_free (key);
329 if (!rc)
331 rc = decrypt_data (client->ctx, client->crypto, salted_key, keysize);
332 if (gpg_err_code (rc) == GPG_ERR_BAD_PASSPHRASE
333 && ++pin_try <= pin_tries && !(client->flags & FLAG_NO_PINENTRY))
335 gcry_free (salted_key);
336 salted_key = NULL;
337 key = NULL;
338 keylen = 0;
339 client->pinentry_opts.title = str_asprintf (_ ("Bad passphrase (try %i of %i)"), pin_try, pin_tries);
340 goto pin_again;
344 if (client->pinentry_opts.title != pin_title)
345 xfree (client->pinentry_opts.title);
347 client->pinentry_opts.title = pin_title;
348 if (rc)
350 gcry_free (salted_key);
351 return rc;
354 cdata = xcalloc (1, sizeof (struct cache_data_s));
355 if (!cdata)
357 gcry_free (salted_key);
358 return GPG_ERR_ENOMEM;
361 cdata->key = salted_key;
362 cdata->keylen = keysize;
364 else
365 rc = decrypt_data (client->ctx, client->crypto, NULL, 0);
367 done:
368 if (!rc)
370 rc = parse_xml (ctx, client->flags & FLAG_NEW);
371 if (rc && !cached)
372 free_cache_data_once (cdata);
374 if (!rc)
376 int timeout = config_get_integer (client->filename,
377 "cache_timeout");
379 if (!cached)
381 if (!cdata)
382 cdata = xcalloc (1, sizeof (struct cache_data_s));
384 rc = encrypt_xml (NULL, cache_key, cache_keysize,
385 GCRY_CIPHER_AES, client->crypto->plaintext,
386 client->crypto->plaintext_len, &cdata->doc,
387 &cdata->doclen, &cache_iv, &cache_blocksize,
389 if (!rc && !(client->flags & FLAG_NEW) && IS_PKI (client->crypto))
391 rc = gcry_sexp_build ((gcry_sexp_t *) & cdata->pubkey, NULL,
392 "%S", client->crypto->pkey_sexp);
396 if (cdata->sigkey)
397 gcry_sexp_release (cdata->sigkey);
399 cdata->sigkey = NULL;
400 if (!rc && IS_PKI (client->crypto))
401 rc = gcry_sexp_build ((gcry_sexp_t *) &cdata->sigkey, NULL,
402 "%S", client->crypto->sigpkey_sexp);
404 if (!rc && !cache_add_file (client->md5file,
405 (client->flags & FLAG_NEW)
406 ? NULL
407 : client->crypto->grip, cdata, timeout))
409 if (!cached)
411 free_cache_data_once (cdata);
412 xmlFreeDoc (client->doc);
413 client->doc = NULL;
415 rc = GPG_ERR_ENOMEM;
418 if (!rc)
419 client->flags |= FLAG_OPEN;
423 if (!rc)
424 update_checksum (client);
426 if (!rc && (client->opts & OPT_LOCK_ON_OPEN))
427 rc = do_lock (client, 0);
429 return rc;
432 static void
433 req_cleanup (void *arg)
435 if (!arg)
436 return;
438 strv_free ((char **) arg);
441 static gpg_error_t
442 parse_open_opt_lock (void *data, void *value)
444 struct client_s *client = data;
446 client->opts |= OPT_LOCK_ON_OPEN;
447 return 0;
450 static gpg_error_t
451 parse_opt_inquire (void *data, void *value)
453 struct client_s *client = data;
455 (void) value;
456 client->opts |= OPT_INQUIRE;
457 return 0;
460 static gpg_error_t
461 update_checksum (struct client_s *client)
463 unsigned char *crc;
464 size_t len;
465 struct cache_data_s *cdata;
466 gpg_error_t rc = get_checksum (client->filename, &crc, &len);
468 if (rc)
469 return rc;
471 xfree (client->crc);
472 client->crc = crc;
473 cdata = cache_get_data (client->md5file);
474 if (cdata)
476 xfree (cdata->crc);
477 cdata->crc = xmalloc (len);
478 memcpy (cdata->crc, crc, len);
481 return 0;
484 static gpg_error_t
485 validate_checksum (struct client_s *client, struct cache_data_s *cdata)
487 unsigned char *crc;
488 size_t len;
489 gpg_error_t rc;
490 int n = 0;
492 if (cdata && !cdata->crc)
493 return GPG_ERR_CHECKSUM;
495 rc = get_checksum (client->filename, &crc, &len);
496 if (rc)
497 return rc;
499 if (cdata)
500 n = memcmp (cdata->crc, crc, len);
501 else if (client->crc)
502 n = memcmp (client->crc, crc, len);
504 xfree (crc);
505 return n ? GPG_ERR_CHECKSUM : 0;
508 static gpg_error_t
509 do_open (assuan_context_t ctx, const char *filename, const char *password)
511 struct client_s *client = assuan_get_pointer (ctx);
512 struct cache_data_s *cdata;
513 gpg_error_t rc = 0;
514 int done = 0;
516 if (!valid_filename (filename))
517 return GPG_ERR_INV_VALUE;
519 gcry_md_hash_buffer (GCRY_MD_MD5, client->md5file, filename,
520 strlen (filename));
521 client->filename = str_dup (filename);
522 if (!client->filename)
523 return GPG_ERR_ENOMEM;
525 // Cached document?
526 cdata = cache_get_data (client->md5file);
527 if (cdata && cdata->doc)
529 int defer = 0;
531 /* This will check that the key is cached in the agent which needs to
532 * be determined for files that share a keygrip. */
533 if (!rc)
535 rc = cache_iscached (client->filename, &defer);
536 if ((!rc || rc == GPG_ERR_ENOENT) && defer)
537 rc = GPG_ERR_KEY_EXPIRED;
540 if (!rc && !(client->flags & FLAG_NEW))
541 rc = validate_checksum (client, cdata);
543 #ifdef WITH_GNUTLS
544 if (!rc && client->thd->remote
545 && config_get_boolean (client->filename, "tcp_require_key"))
546 rc = GPG_ERR_KEY_EXPIRED;
547 #endif
549 if (!rc && !password)
551 rc = read_data_header (client->filename, &client->crypto->hdr,
552 NULL, NULL);
553 if (!rc)
555 if (IS_PKI (client->crypto))
557 gcry_sexp_build (&client->crypto->pkey_sexp, NULL, "%S",
558 cdata->pubkey);
559 gcry_pk_get_keygrip (client->crypto->pkey_sexp,
560 client->crypto->grip);
561 gcry_sexp_build (&client->crypto->sigpkey_sexp, NULL, "%S",
562 cdata->sigkey);
563 gcry_pk_get_keygrip (client->crypto->sigpkey_sexp,
564 client->crypto->sign_grip);
567 if (!rc)
569 rc = open_finalize (ctx, NULL, 0);
570 done = 1;
575 /* There was an error accessing the file so clear the cache entry. The
576 * real error will be returned from read_data_file() since the file
577 * may have only disappeared. */
578 if (!done)
580 log_write ("%s: %s", filename, pwmd_strerror (rc));
581 rc = cache_clear (client->md5file);
582 send_status_all (STATUS_CACHE, NULL);
586 if (done || rc)
587 return rc;
589 rc = read_data_file (client->filename, client->crypto);
590 if (rc)
592 if (gpg_err_source (rc) != GPG_ERR_SOURCE_DEFAULT ||
593 gpg_err_code (rc) != GPG_ERR_ENOENT)
595 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
596 return rc;
599 client->flags |= FLAG_NEW;
600 memset (client->crypto->grip, 0, sizeof (client->crypto->grip));
601 memset (client->crypto->sign_grip, 0,
602 sizeof (client->crypto->sign_grip));
603 rc = open_finalize (ctx, NULL, 0);
604 return rc;
607 if (password && IS_PKI (client->crypto))
609 #ifdef WITH_AGENT
610 rc = set_agent_passphrase (client->crypto, password, strlen (password));
611 if (rc)
612 return rc;
613 #endif
616 rc = open_finalize (ctx, (char *)password, password ? strlen (password) : 0);
617 return rc;
620 static gpg_error_t
621 open_command (assuan_context_t ctx, char *line)
623 gpg_error_t rc;
624 struct client_s *client = assuan_get_pointer (ctx);
625 char **req, *password = NULL, *filename;
626 unsigned char md5file[16];
627 int same_file = 0;
628 assuan_peercred_t peer;
629 struct argv_s *args[] = {
630 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_open_opt_lock},
631 NULL
634 rc = parse_options (&line, args, client);
635 if (rc)
636 return send_error (ctx, rc);
638 req = str_split (line, " ", 2);
639 if (!req)
640 return send_error (ctx, GPG_ERR_SYNTAX);
642 rc = do_validate_peer (ctx, req[0], &peer);
643 if (rc)
645 strv_free (req);
646 return send_error (ctx, rc);
649 pthread_cleanup_push (req_cleanup, req);
650 filename = req[0];
651 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
652 /* This client may have locked a different file with ISCACHED --lock than
653 * the current filename. This will remove that lock. */
654 same_file = !memcmp (md5file, client->md5file, 16) ? 1 : 0;
655 if (client->flags & FLAG_OPEN ||
656 (client->flags & FLAG_HAS_LOCK && !same_file))
658 typeof (client->opts) opts = client->opts;
659 typeof (client->flags) flags = client->flags;
661 if (same_file)
662 client->flags |= FLAG_KEEP_LOCK;
664 cleanup_client (client);
665 client->opts = opts;
666 client->flags |= flags;
667 client->flags &= ~(FLAG_LOCK_CMD);
668 if (!same_file)
669 client->flags &= ~(FLAG_HAS_LOCK | FLAG_NEW);
672 /* Need to lock the mutex here because file_modified() cannot without
673 * knowing the filename. */
674 memcpy (client->md5file, md5file, 16);
675 rc = lock_file_mutex (client, 1);
676 if (!rc)
678 password = req[1] && *req[1] ? req[1] : NULL;
679 #ifdef WITH_AGENT
680 if (IS_PKI (client->crypto))
681 rc = set_pinentry_mode (client->crypto->agent,
682 (client->flags & FLAG_NO_PINENTRY) ? "loopback"
683 : "ask");
684 #endif
685 if (!rc)
687 rc = do_open (ctx, filename, password);
688 if (rc)
689 cleanup_client (client);
691 cleanup_crypto_stage1 (client->crypto);
695 pthread_cleanup_pop (1);
697 if (!rc && client->flags & FLAG_NEW)
698 rc = send_status (ctx, STATUS_NEWFILE, NULL);
700 #ifdef WITH_AGENT
701 (void) kill_scd (client->crypto->agent);
702 #endif
703 return send_error (ctx, rc);
706 static gpg_error_t
707 parse_opt_no_passphrase (void *data, void *value)
709 struct client_s *client = data;
711 (void) value;
712 client->opts |= OPT_NO_PASSPHRASE;
713 return 0;
716 static gpg_error_t
717 parse_save_opt_no_agent (void *data, void *value)
719 struct client_s *client = data;
721 client->opts |= OPT_NO_AGENT;
722 return 0;
725 static gpg_error_t
726 parse_save_opt_cipher (void *data, void *value)
728 struct client_s *client = data;
729 int algo = cipher_string_to_gcrypt ((char *) value);
730 file_header_t *hdr = &client->crypto->save.hdr;
732 if (algo == -1)
733 return GPG_ERR_INV_VALUE;
735 hdr->flags = set_cipher_flag (hdr->flags, algo);
736 return 0;
739 static gpg_error_t
740 parse_save_opt_keygrip (void *data, void *value)
742 struct client_s *client = data;
744 if (!IS_PKI (client->crypto))
745 return GPG_ERR_INV_ARG;
747 #ifdef WITH_AGENT
748 if (client->crypto->save.pkey)
749 gcry_sexp_release (client->crypto->save.pkey);
751 client->crypto->save.pkey = NULL;
752 return get_pubkey (client->crypto, value, &client->crypto->save.pkey);
753 #else
754 return GPG_ERR_INV_ARG;
755 #endif
758 static gpg_error_t
759 parse_save_opt_sign_keygrip (void *data, void *value)
761 struct client_s *client = data;
763 if (!IS_PKI (client->crypto))
764 return GPG_ERR_INV_ARG;
766 #ifdef WITH_AGENT
767 if (client->crypto->save.sigpkey)
768 gcry_sexp_release (client->crypto->save.sigpkey);
770 client->crypto->save.sigpkey = NULL;
771 return get_pubkey (client->crypto, value, &client->crypto->save.sigpkey);
772 #else
773 return GPG_ERR_INV_ARG;
774 #endif
777 static gpg_error_t
778 parse_opt_s2k_count (void *data, void *value)
780 struct client_s *client = data;
781 char *v = value;
783 if (!v || !*v)
784 return GPG_ERR_INV_VALUE;
786 client->crypto->save.s2k_count = strtoul (v, NULL, 10);
787 return 0;
790 static gpg_error_t
791 parse_save_opt_iterations (void *data, void *value)
793 struct client_s *client = data;
794 char *v = value, *p;
795 uint64_t n;
797 if (!v || !*v)
798 return GPG_ERR_INV_VALUE;
800 errno = 0;
801 n = strtoull (v, &p, 10);
802 if (n == UINT64_MAX && errno)
803 return gpg_error_from_errno (errno);
804 else if (p && *p)
805 return GPG_ERR_INV_VALUE;
807 client->crypto->save.hdr.iterations = n;
808 return 0;
811 static gpg_error_t
812 save_finalize (assuan_context_t ctx)
814 struct client_s *client = assuan_get_pointer (ctx);
815 gpg_error_t rc = 0;
816 xmlChar *xmlbuf = NULL;
817 int xmlbuflen;
818 void *key = NULL;
819 size_t keylen = 0;
821 xmlDocDumpFormatMemory (client->doc, &xmlbuf, &xmlbuflen, 0);
822 if (!xmlbuf)
823 return GPG_ERR_ENOMEM;
825 pthread_cleanup_push (xmlFree, xmlbuf);
827 if (!use_agent || ((client->flags & FLAG_NEW)
828 && (client->opts & OPT_NO_AGENT))
829 || !(client->crypto->hdr.flags & PWMD_FLAG_PKI))
831 rc = export_common (ctx, client->flags & FLAG_NO_PINENTRY,
832 client->crypto, xmlbuf, xmlbuflen, client->filename,
833 NULL, &key, &keylen, 1, 1,
834 (client->opts & OPT_NO_PASSPHRASE));
836 #ifdef WITH_AGENT
837 else
839 gcry_sexp_t pubkey = client->crypto->save.pkey;
840 gcry_sexp_t sigkey = client->crypto->save.sigpkey;
842 if (!pubkey)
843 pubkey = client->crypto->pkey_sexp;
845 if (!sigkey)
847 sigkey = client->crypto->sigpkey_sexp;
848 if (!sigkey)
850 gcry_sexp_build (&client->crypto->save.sigpkey, 0, "%S", pubkey);
851 sigkey = client->crypto->save.sigpkey;
855 rc = encrypt_data_file (client->ctx, client->crypto, pubkey, sigkey,
856 client->filename, xmlbuf, xmlbuflen);
857 if (pubkey == client->crypto->save.pkey)
859 if (!rc)
861 gcry_sexp_release (client->crypto->pkey_sexp);
862 client->crypto->pkey_sexp = client->crypto->save.pkey;
863 gcry_pk_get_keygrip (client->crypto->pkey_sexp,
864 client->crypto->grip);
866 else
867 gcry_sexp_release (pubkey);
869 client->crypto->save.pkey = NULL;
872 if (!rc)
873 gcry_pk_get_keygrip (sigkey, client->crypto->sign_grip);
875 if (sigkey == client->crypto->save.sigpkey)
877 if (!rc)
879 if (client->crypto->sigpkey_sexp)
880 gcry_sexp_release (client->crypto->sigpkey_sexp);
882 client->crypto->sigpkey_sexp = client->crypto->save.sigpkey;
883 gcry_pk_get_keygrip (client->crypto->sigpkey_sexp,
884 client->crypto->sign_grip);
886 else
887 gcry_sexp_release (sigkey);
889 client->crypto->save.sigpkey = NULL;
892 #endif
894 if (!rc)
896 int cached;
898 rc = save_common (client->filename, client->crypto, xmlbuf, xmlbuflen,
899 key, keylen, &cached, client->opts & OPT_NO_AGENT);
900 if (rc)
901 gcry_free (key);
903 if (!rc && (!cached || (client->flags & FLAG_NEW)))
904 send_status_all (STATUS_CACHE, NULL);
906 if (!rc)
908 rc = update_checksum (client);
909 client->flags &= ~(FLAG_NEW);
913 pthread_cleanup_pop (1); // xmlFree
914 return rc;
917 static gpg_error_t
918 parse_opt_reset (void *data, void *value)
920 struct client_s *client = data;
922 (void) value;
923 client->opts |= OPT_RESET;
924 return 0;
927 static gpg_error_t
928 save_command (assuan_context_t ctx, char *line)
930 struct client_s *client = assuan_get_pointer (ctx);
931 gpg_error_t rc;
932 struct stat st;
933 struct argv_s *args[] = {
934 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG,
935 parse_opt_no_passphrase},
936 &(struct argv_s) {"cipher", OPTION_TYPE_ARG, parse_save_opt_cipher},
937 &(struct argv_s) {"inquire-keyparam", OPTION_TYPE_NOARG,
938 parse_opt_inquire},
939 &(struct argv_s) {"keygrip", OPTION_TYPE_ARG, parse_save_opt_keygrip},
940 &(struct argv_s) {"sign-keygrip", OPTION_TYPE_ARG,
941 parse_save_opt_sign_keygrip},
942 &(struct argv_s) {"s2k-count", OPTION_TYPE_ARG, parse_opt_s2k_count},
943 &(struct argv_s) {"reset", OPTION_TYPE_NOARG, parse_opt_reset},
944 &(struct argv_s) {"cipher-iterations", OPTION_TYPE_ARG,
945 parse_save_opt_iterations},
946 &(struct argv_s) {"no-agent", OPTION_TYPE_NOARG,
947 parse_save_opt_no_agent},
948 NULL
951 cleanup_save (&client->crypto->save);
952 memcpy (&client->crypto->save.hdr, &client->crypto->hdr,
953 sizeof (file_header_t));
954 client->crypto->save.s2k_count =
955 config_get_ulong (client->filename, "s2k_count");
957 if (client->flags & FLAG_NEW)
958 client->crypto->save.hdr.iterations =
959 config_get_ulonglong (client->filename, "cipher_iterations");
961 rc = parse_options (&line, args, client);
962 if (rc)
963 return send_error (ctx, rc);
965 if (!(client->flags & FLAG_NEW))
966 client->opts &= ~OPT_NO_AGENT;
967 else if (client->opts & OPT_NO_AGENT)
969 client->crypto->save.hdr.flags &= ~PWMD_FLAG_PKI;
970 client->crypto->hdr.flags &= ~PWMD_FLAG_PKI;
973 if ((client->opts & OPT_NO_PASSPHRASE) && !(client->flags & FLAG_NEW)
974 && !(client->opts & OPT_INQUIRE))
975 return send_error (ctx, GPG_ERR_WRONG_KEY_USAGE);
977 if (lstat (client->filename, &st) == -1 && errno != ENOENT)
978 return send_error (ctx, gpg_error_from_errno (errno));
980 if (errno != ENOENT && !S_ISREG (st.st_mode))
982 log_write ("%s: %s", client->filename, pwmd_strerror (GPG_ERR_ENOANO));
983 return send_error (ctx, GPG_ERR_ENOANO);
986 int defer = 0;
987 rc = cache_iscached (client->filename, &defer);
988 if (gpg_err_code (rc) == GPG_ERR_ENOENT && client->flags & FLAG_NEW)
989 rc = 0;
990 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
991 rc = 0;
993 if ((!rc && defer) || config_get_boolean ("global", "require_save_key"))
994 client->opts |= OPT_RESET;
996 if (!rc && (client->opts & OPT_RESET))
998 rc = cache_clear (client->md5file);
999 if (rc)
1000 return send_error (ctx, rc);
1002 log_write ("%s: %s", client->filename,
1003 pwmd_strerror (GPG_ERR_KEY_EXPIRED));
1004 send_status_all (STATUS_CACHE, NULL);
1007 if (!rc)
1008 rc = update_element_mtime (xmlDocGetRootElement (client->doc));
1010 if (rc)
1011 return send_error (ctx, rc);
1013 #ifdef WITH_AGENT
1014 if (!rc && use_agent && !client->crypto->save.pkey &&
1015 (client->flags & FLAG_NEW || client->opts & OPT_INQUIRE)
1016 && !(client->opts & OPT_NO_AGENT))
1018 rc = set_pinentry_mode (client->crypto->agent,
1019 (client->flags & FLAG_NO_PINENTRY) ? "loopback"
1020 : "ask");
1022 if (!(client->flags & FLAG_NEW))
1024 struct crypto_s *crypto;
1025 char *key = NULL;
1026 size_t keylen = 0;
1028 /* Wanting to generate a new key. Require the key to open the
1029 current file before proceeding reguardless of the
1030 require_save_key configuration parameter. */
1031 rc = cache_clear (client->md5file);
1032 if (!rc)
1034 rc = init_client_crypto (&crypto);
1035 if (!rc)
1036 crypto->client_ctx = client->ctx;
1039 if (!rc)
1040 rc = decrypt_common (client->ctx, client->opts&OPT_INQUIRE, crypto,
1041 client->filename, &key, &keylen);
1043 xfree (key);
1044 cleanup_crypto (&crypto);
1047 if (!rc)
1048 rc = send_status (client->ctx, STATUS_GENKEY, NULL);
1050 if (!rc)
1052 struct inquire_data_s idata = { 0 };
1053 char *params = client->opts & OPT_INQUIRE
1054 ? NULL : default_key_params (client->crypto);
1056 pthread_cleanup_push (xfree, params);
1057 idata.crypto = client->crypto;
1059 if (params)
1061 idata.line = params;
1062 idata.len = strlen (params);
1064 else
1065 idata.preset = 1;
1067 client->crypto->agent->inquire_data = &idata;
1068 client->crypto->agent->inquire_cb = NULL;
1069 rc = generate_key (client->crypto, params,
1070 (client->opts & OPT_NO_PASSPHRASE), 1);
1071 pthread_cleanup_pop (1);
1074 #endif
1076 if (!rc)
1077 rc = save_finalize (ctx);
1079 cleanup_crypto_stage1 (client->crypto);
1080 #ifdef WITH_AGENT
1081 (void) kill_scd (client->crypto->agent);
1082 #endif
1083 return send_error (ctx, rc);
1086 static gpg_error_t
1087 do_delete (assuan_context_t ctx, char *line)
1089 struct client_s *client = assuan_get_pointer (ctx);
1090 gpg_error_t rc;
1091 char **req;
1092 xmlNodePtr n;
1094 if (strchr (line, '\t'))
1095 req = str_split (line, "\t", 0);
1096 else
1097 req = str_split (line, " ", 0);
1099 if (!req || !*req)
1100 return GPG_ERR_SYNTAX;
1102 n = find_root_element (client->doc, &req, &rc, NULL, 0, 0);
1103 if (!n)
1105 strv_free (req);
1106 return rc;
1110 * No sub-node defined. Remove the entire node (root element).
1112 if (!req[1])
1114 if (n)
1116 rc = unlink_node (n);
1117 xmlFreeNode (n);
1120 strv_free (req);
1121 return rc;
1125 find_elements (client->doc, n->children, req + 1, &rc, NULL, NULL, NULL,
1126 0, 0, NULL, 0);
1127 strv_free (req);
1128 if (!n)
1129 return rc;
1131 if (n)
1133 rc = unlink_node (n);
1134 xmlFreeNode (n);
1137 return rc;
1140 static gpg_error_t
1141 delete_command (assuan_context_t ctx, char *line)
1143 struct client_s *client = assuan_get_pointer (ctx);
1144 gpg_error_t rc;
1145 struct argv_s *args[] = {
1146 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1147 NULL
1150 rc = parse_options (&line, args, client);
1151 if (rc)
1152 return send_error (ctx, rc);
1154 if (client->opts & OPT_INQUIRE)
1156 unsigned char *result;
1157 size_t len;
1159 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1160 if (rc)
1161 return send_error (ctx, rc);
1163 line = (char *) result;
1166 rc = do_delete (ctx, line);
1168 if (client->opts & OPT_INQUIRE)
1169 xfree (line);
1171 return send_error (ctx, rc);
1174 static gpg_error_t
1175 store_command (assuan_context_t ctx, char *line)
1177 struct client_s *client = assuan_get_pointer (ctx);
1178 gpg_error_t rc;
1179 size_t len;
1180 unsigned char *result;
1181 char **req;
1182 xmlNodePtr n, parent;
1183 int has_content;
1184 char *content = NULL;
1186 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1187 if (rc)
1188 return send_error (ctx, rc);
1190 req = str_split ((char *) result, "\t", 0);
1191 xfree (result);
1193 if (!req || !*req)
1194 return send_error (ctx, GPG_ERR_SYNTAX);
1196 len = strv_length (req);
1197 has_content = line[strlen (line) - 1] != '\t' && len > 1;
1198 if (*(req + 1) && !valid_element_path (req, has_content))
1200 strv_free (req);
1201 return send_error (ctx, GPG_ERR_INV_VALUE);
1204 if (has_content || !*req[len - 1])
1206 has_content = 1;
1207 content = req[len - 1];
1208 req[len - 1] = NULL;
1211 again:
1212 n = find_root_element (client->doc, &req, &rc, NULL, 0, 0);
1213 if (rc && rc == GPG_ERR_ELEMENT_NOT_FOUND)
1215 rc = new_root_element (client->doc, *req);
1216 if (rc)
1218 strv_free (req);
1219 return send_error (ctx, GPG_ERR_SYNTAX);
1222 goto again;
1225 if (!n)
1227 strv_free (req);
1228 return send_error (ctx, rc);
1231 parent = n;
1233 if (req[1] && *req[1])
1235 if (!n->children)
1236 parent = create_elements_cb (n, req + 1, &rc, NULL);
1237 else
1238 parent = find_elements (client->doc, n->children, req + 1, &rc,
1239 NULL, NULL, create_elements_cb, 0, 0, NULL,
1243 if (!rc && len > 1)
1245 n = find_text_node (parent->children);
1246 if (n)
1247 xmlNodeSetContent (n, (xmlChar *) content);
1248 else
1249 xmlNodeAddContent (parent, (xmlChar *) content);
1251 update_element_mtime (parent);
1254 xfree (content);
1255 strv_free (req);
1256 return send_error (ctx, rc);
1259 static gpg_error_t
1260 xfer_data (assuan_context_t ctx, const char *line, int total)
1262 int to_send;
1263 int sent = 0;
1264 gpg_error_t rc;
1265 int progress = config_get_integer ("global", "xfer_progress");
1266 int flush = 0;
1268 progress =
1269 progress > 0 ? (progress / ASSUAN_LINELENGTH) * ASSUAN_LINELENGTH : 0;
1270 to_send = total < ASSUAN_LINELENGTH ? total : ASSUAN_LINELENGTH;
1271 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1273 if (rc)
1274 return rc;
1276 again:
1279 if (sent + to_send > total)
1280 to_send = total - sent;
1282 rc = assuan_send_data (ctx, flush ? NULL : (char *) line + sent,
1283 flush ? 0 : to_send);
1284 if (!rc)
1286 sent += flush ? 0 : to_send;
1288 if ((progress && !(sent % progress) && sent != total) ||
1289 (sent == total && flush))
1290 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1292 if (!flush && !rc && sent == total)
1294 flush = 1;
1295 goto again;
1299 while (!rc && sent < total);
1301 return rc;
1304 static gpg_error_t
1305 do_get (assuan_context_t ctx, char *line)
1307 struct client_s *client = assuan_get_pointer (ctx);
1308 gpg_error_t rc;
1309 char **req;
1310 xmlNodePtr n;
1312 req = str_split (line, "\t", 0);
1314 if (!req || !*req)
1316 strv_free (req);
1317 return GPG_ERR_SYNTAX;
1320 n = find_root_element (client->doc, &req, &rc, NULL, 0, 0);
1321 if (!n)
1323 strv_free (req);
1324 return rc;
1327 if (req[1])
1329 find_elements (client->doc, n->children, req + 1, &rc, NULL, NULL, NULL,
1330 0, 0, NULL, 0);
1332 strv_free (req);
1333 if (rc)
1334 return rc;
1336 if (!n || !n->children)
1337 return GPG_ERR_NO_DATA;
1339 n = find_text_node (n->children);
1340 if (!n || !n->content || !*n->content)
1341 return GPG_ERR_NO_DATA;
1343 rc = xfer_data (ctx, (char *) n->content, xmlStrlen (n->content));
1344 return rc;
1347 static gpg_error_t
1348 get_command (assuan_context_t ctx, char *line)
1350 struct client_s *client = assuan_get_pointer (ctx);
1351 gpg_error_t rc;
1352 struct argv_s *args[] = {
1353 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1354 NULL
1357 rc = parse_options (&line, args, client);
1358 if (rc)
1359 return send_error (ctx, rc);
1361 if (client->opts & OPT_INQUIRE)
1363 unsigned char *result;
1364 size_t len;
1366 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1367 if (rc)
1368 return send_error (ctx, rc);
1370 line = (char *) result;
1373 rc = do_get (ctx, line);
1375 if (client->opts & OPT_INQUIRE)
1376 xfree (line);
1378 return send_error (ctx, rc);
1381 static void list_command_cleanup1 (void *arg);
1382 static gpg_error_t
1383 realpath_command (assuan_context_t ctx, char *line)
1385 struct string_s *string = NULL;
1386 gpg_error_t rc;
1387 struct client_s *client = assuan_get_pointer (ctx);
1388 struct argv_s *args[] = {
1389 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1390 NULL
1393 rc = parse_options (&line, args, client);
1394 if (rc)
1395 return send_error (ctx, rc);
1397 if (client->opts & OPT_INQUIRE)
1399 unsigned char *result;
1400 size_t len;
1402 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1403 if (rc)
1404 return send_error (ctx, rc);
1406 line = (char *) result;
1409 rc = build_realpath (client->doc, line, &string);
1410 if (!rc)
1412 pthread_cleanup_push (list_command_cleanup1, string);
1413 rc = xfer_data (ctx, string->str, string->len);
1414 pthread_cleanup_pop (1);
1417 if (client->opts & OPT_INQUIRE)
1418 xfree (line);
1420 return send_error (ctx, rc);
1423 static void
1424 list_command_cleanup1 (void *arg)
1426 if (arg)
1427 string_free ((struct string_s *) arg, 1);
1430 static void
1431 list_command_cleanup2 (void *arg)
1433 struct element_list_s *elements = arg;
1435 if (elements)
1437 if (elements->list)
1439 int total = slist_length (elements->list);
1440 int i;
1442 for (i = 0; i < total; i++)
1444 char *tmp = slist_nth_data (elements->list, i);
1445 xfree (tmp);
1448 slist_free (elements->list);
1451 if (elements->prefix)
1452 xfree (elements->prefix);
1454 if (elements->req)
1455 strv_free (elements->req);
1457 xfree (elements);
1461 static gpg_error_t
1462 parse_list_opt_norecurse (void *data, void *value)
1464 struct client_s *client = data;
1466 client->opts &= ~(OPT_LIST_RECURSE);
1467 return 0;
1470 static gpg_error_t
1471 parse_list_opt_verbose (void *data, void *value)
1473 struct client_s *client = data;
1475 client->opts |= OPT_LIST_VERBOSE;
1476 return 0;
1479 static gpg_error_t
1480 parse_list_opt_target (void *data, void *value)
1482 struct client_s *client = data;
1484 client->opts |= OPT_LIST_WITH_TARGET;
1485 return 0;
1488 static gpg_error_t
1489 parse_list_opt_all (void *data, void *value)
1491 struct client_s *client = data;
1493 client->opts |= OPT_LIST_ALL;
1494 return 0;
1497 static gpg_error_t
1498 list_path_once (struct client_s *client, char *line,
1499 struct element_list_s *elements, struct string_s *result)
1501 gpg_error_t rc;
1503 elements->req = str_split (line, " ", 0);
1504 if (!elements->req)
1505 strv_printf (&elements->req, "%s", line);
1507 rc = create_path_list (client->doc, elements, *elements->req);
1508 if (rc == GPG_ERR_ELOOP && elements->verbose)
1509 rc = 0;
1511 if (!rc)
1513 int total = slist_length (elements->list);
1514 int i;
1516 if (!total)
1517 rc = GPG_ERR_NO_DATA;
1519 if (!rc)
1521 if (!rc)
1523 for (i = 0; i < total; i++)
1525 char *tmp = slist_nth_data (elements->list, i);
1527 string_append_printf (result, "%s%s", tmp,
1528 i + 1 == total ? "" : "\n");
1532 else
1533 rc = GPG_ERR_NO_DATA;
1536 return rc;
1539 static int
1540 has_list_flag (char *path, char *flags)
1542 char *p = path;
1544 while (*p && *++p != ' ');
1546 if (!*p)
1547 return 0;
1549 for (; *p; p++)
1551 char *f;
1553 for (f = flags; *f && *f != ' '; f++)
1555 if (*p == *f)
1556 return 1;
1560 return 0;
1563 static gpg_error_t
1564 do_list (assuan_context_t ctx, char *line)
1566 struct client_s *client = assuan_get_pointer (ctx);
1567 gpg_error_t rc;
1568 struct element_list_s *elements = NULL;
1570 elements = xcalloc (1, sizeof (struct element_list_s));
1571 if (!elements)
1572 return GPG_ERR_ENOMEM;
1574 elements->recurse = client->opts & OPT_LIST_RECURSE;
1575 elements->verbose =
1576 (client->opts & OPT_LIST_VERBOSE) | (client->opts & OPT_LIST_WITH_TARGET);
1577 elements->with_target = client->opts & OPT_LIST_WITH_TARGET;
1579 if (!line || !*line)
1581 struct string_s *str = NULL;
1583 pthread_cleanup_push (list_command_cleanup2, elements);
1584 rc = list_root_elements (client->doc, &str, elements->verbose,
1585 elements->with_target);
1586 pthread_cleanup_pop (1);
1587 pthread_cleanup_push (list_command_cleanup1, str);
1589 if (!rc)
1591 if (client->opts & OPT_LIST_ALL)
1593 char **roots = str_split (str->str, "\n", 0);
1594 char **p;
1596 pthread_cleanup_push (req_cleanup, roots);
1597 string_truncate (str, 0);
1599 for (p = roots; *p; p++)
1601 if (strchr (*p, ' '))
1603 if (has_list_flag (*p, "EO"))
1605 string_append_printf (str, "%s%s", *p,
1606 *(p + 1) ? "\n" : "");
1607 continue;
1611 elements = xcalloc (1, sizeof (struct element_list_s));
1612 if (!elements)
1614 rc = GPG_ERR_ENOMEM;
1615 break;
1618 elements->recurse = client->opts & OPT_LIST_RECURSE;
1619 elements->verbose =
1620 (client->opts & OPT_LIST_VERBOSE) | (client->opts &
1621 OPT_LIST_WITH_TARGET);
1622 elements->with_target = client->opts & OPT_LIST_WITH_TARGET;
1623 pthread_cleanup_push (list_command_cleanup2, elements);
1624 rc = list_path_once (client, *p, elements, str);
1625 pthread_cleanup_pop (1);
1626 if (rc)
1627 break;
1629 if (*(p + 1))
1630 string_append (str, "\n");
1633 pthread_cleanup_pop (1);
1636 if (!rc)
1637 rc = xfer_data (ctx, str->str, str->len);
1640 pthread_cleanup_pop (1);
1641 return rc;
1644 pthread_cleanup_push (list_command_cleanup2, elements);
1645 struct string_s *str = string_new (NULL);
1646 pthread_cleanup_push (list_command_cleanup1, str);
1647 rc = list_path_once (client, line, elements, str);
1648 if (!rc)
1649 rc = xfer_data (ctx, str->str, str->len);
1651 pthread_cleanup_pop (1);
1652 pthread_cleanup_pop (1);
1653 return rc;
1656 static gpg_error_t
1657 list_command (assuan_context_t ctx, char *line)
1659 struct client_s *client = assuan_get_pointer (ctx);
1660 gpg_error_t rc;
1661 struct argv_s *args[] = {
1662 &(struct argv_s) {"no-recurse", OPTION_TYPE_NOARG,
1663 parse_list_opt_norecurse},
1664 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_list_opt_verbose},
1665 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1666 &(struct argv_s) {"with-target", OPTION_TYPE_NOARG,
1667 parse_list_opt_target},
1668 &(struct argv_s) {"all", OPTION_TYPE_NOARG, parse_list_opt_all},
1669 NULL
1672 if (disable_list_and_dump == 1)
1673 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
1675 client->opts |= OPT_LIST_RECURSE;
1676 rc = parse_options (&line, args, client);
1677 if (rc)
1678 return send_error (ctx, rc);
1680 if (client->opts & OPT_LIST_ALL)
1681 client->opts |= OPT_LIST_RECURSE | OPT_LIST_VERBOSE;
1683 if (client->opts & OPT_INQUIRE)
1685 unsigned char *result;
1686 size_t len;
1688 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1689 if (rc)
1690 return send_error (ctx, rc);
1692 line = (char *) result;
1695 rc = do_list (ctx, line);
1697 if (client->opts & OPT_INQUIRE)
1698 xfree (line);
1700 return send_error (ctx, rc);
1704 * req[0] - element path
1706 static gpg_error_t
1707 attribute_list (assuan_context_t ctx, char **req)
1709 struct client_s *client = assuan_get_pointer (ctx);
1710 char **attrlist = NULL;
1711 int i = 0;
1712 char **path = NULL;
1713 xmlAttrPtr a;
1714 xmlNodePtr n, an;
1715 char *line;
1716 gpg_error_t rc;
1718 if (!req || !req[0])
1719 return GPG_ERR_SYNTAX;
1721 if ((path = str_split (req[0], "\t", 0)) == NULL)
1724 * The first argument may be only a root element.
1726 if ((path = str_split (req[0], " ", 0)) == NULL)
1727 return GPG_ERR_SYNTAX;
1730 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
1732 if (!n)
1734 strv_free (path);
1735 return rc;
1738 if (path[1])
1740 n = find_elements (client->doc, n->children, path + 1, &rc,
1741 NULL, NULL, NULL, 0, 0, NULL, 0);
1743 if (!n)
1745 strv_free (path);
1746 return rc;
1750 strv_free (path);
1752 for (a = n->properties; a; a = a->next)
1754 char **pa;
1756 if ((pa = xrealloc (attrlist, (i + 2) * sizeof (char *))) == NULL)
1758 if (attrlist)
1759 strv_free (attrlist);
1761 log_write ("%s(%i): %s", __FILE__, __LINE__,
1762 pwmd_strerror (GPG_ERR_ENOMEM));
1763 return GPG_ERR_ENOMEM;
1766 attrlist = pa;
1767 an = a->children;
1768 attrlist[i] = str_asprintf ("%s %s", (char *) a->name,
1770 && an->content ? (char *) an->content : "");
1772 if (!attrlist[i])
1774 strv_free (attrlist);
1775 log_write ("%s(%i): %s", __FILE__, __LINE__,
1776 pwmd_strerror (GPG_ERR_ENOMEM));
1777 return GPG_ERR_ENOMEM;
1780 attrlist[++i] = NULL;
1783 if (!attrlist)
1784 return GPG_ERR_NO_DATA;
1786 line = strv_join ("\n", attrlist);
1788 if (!line)
1790 log_write ("%s(%i): %s", __FILE__, __LINE__,
1791 pwmd_strerror (GPG_ERR_ENOMEM));
1792 strv_free (attrlist);
1793 return GPG_ERR_ENOMEM;
1796 pthread_cleanup_push (xfree, line);
1797 pthread_cleanup_push (req_cleanup, attrlist);
1798 rc = xfer_data (ctx, line, strlen (line));
1799 pthread_cleanup_pop (1);
1800 pthread_cleanup_pop (1);
1801 return rc;
1805 * req[0] - attribute
1806 * req[1] - element path
1808 static gpg_error_t
1809 attribute_delete (struct client_s *client, char **req)
1811 xmlNodePtr n;
1812 char **path = NULL;
1813 gpg_error_t rc;
1815 if (!req || !req[0] || !req[1])
1816 return GPG_ERR_SYNTAX;
1818 if (!strcmp (req[0], "_name"))
1819 return GPG_ERR_INV_ATTR;
1821 if ((path = str_split (req[1], "\t", 0)) == NULL)
1824 * The first argument may be only a root element.
1826 if ((path = str_split (req[1], " ", 0)) == NULL)
1827 return GPG_ERR_SYNTAX;
1830 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
1831 if (!n)
1832 goto fail;
1834 if (path[1])
1836 n = find_elements (client->doc, n->children, path + 1, &rc,
1837 NULL, NULL, NULL, 0, 0, NULL, 0);
1838 if (!n)
1839 goto fail;
1842 rc = delete_attribute (n, (xmlChar *) req[0]);
1844 fail:
1845 strv_free (path);
1846 return rc;
1849 static xmlNodePtr
1850 create_element_path (struct client_s *client,
1851 char ***elements, gpg_error_t * rc, xmlNodePtr parent)
1853 char **req = *elements;
1854 char **req_orig = strv_dup (req);
1855 xmlNodePtr n = NULL;
1857 *rc = 0;
1859 if (!req_orig)
1861 *rc = GPG_ERR_ENOMEM;
1862 log_write ("%s(%i): %s", __FILE__, __LINE__,
1863 pwmd_strerror (GPG_ERR_ENOMEM));
1864 goto fail;
1867 again:
1868 n = find_root_element (client->doc, &req, rc, NULL, 0, 0);
1869 if (!n)
1871 if (*rc != GPG_ERR_ELEMENT_NOT_FOUND)
1872 goto fail;
1874 *rc = new_root_element (client->doc, req[0]);
1875 if (*rc)
1876 goto fail;
1878 goto again;
1880 else if (n == parent)
1882 *rc = GPG_ERR_CONFLICT;
1883 goto fail;
1886 if (req[1])
1888 if (!n->children)
1889 n = create_target_elements_cb (n, req + 1, rc, NULL);
1890 else
1891 n = find_elements (client->doc, n->children, req + 1, rc, NULL, NULL,
1892 create_target_elements_cb, 0, 0, parent, 0);
1894 if (!n)
1895 goto fail;
1898 * Reset the position of the element tree now that the elements
1899 * have been created.
1901 strv_free (req);
1902 req = req_orig;
1903 req_orig = NULL;
1904 n = find_root_element (client->doc, &req, rc, NULL, 0, 0);
1905 if (!n)
1906 goto fail;
1908 n = find_elements (client->doc, n->children, req + 1, rc,
1909 NULL, NULL, NULL, 0, 0, NULL, 0);
1910 if (!n)
1911 goto fail;
1914 fail:
1915 if (req_orig)
1916 strv_free (req_orig);
1918 *elements = req;
1919 return n;
1923 * Creates a "target" attribute. When other commands encounter an element with
1924 * this attribute, the element path is modified to the target value. If the
1925 * source element path doesn't exist when using 'ATTR SET target', it is
1926 * created, but the destination element path must exist.
1928 * req[0] - source element path
1929 * req[1] - destination element path
1931 static gpg_error_t
1932 target_attribute (struct client_s *client, char **req)
1934 char **src, **dst, *line = NULL, **odst = NULL;
1935 gpg_error_t rc;
1936 xmlNodePtr n;
1938 if (!req || !req[0] || !req[1])
1939 return GPG_ERR_SYNTAX;
1941 if ((src = str_split (req[0], "\t", 0)) == NULL)
1944 * The first argument may be only a root element.
1946 if ((src = str_split (req[0], " ", 0)) == NULL)
1947 return GPG_ERR_SYNTAX;
1950 if (!valid_element_path (src, 0))
1951 return GPG_ERR_INV_VALUE;
1953 if ((dst = str_split (req[1], "\t", 0)) == NULL)
1956 * The first argument may be only a root element.
1958 if ((dst = str_split (req[1], " ", 0)) == NULL)
1960 rc = GPG_ERR_SYNTAX;
1961 goto fail;
1965 odst = strv_dup (dst);
1966 if (!odst)
1968 rc = GPG_ERR_ENOMEM;
1969 goto fail;
1972 n = find_root_element (client->doc, &dst, &rc, NULL, 0, 0);
1974 * Make sure the destination element path exists.
1976 if (!n)
1977 goto fail;
1979 if (dst[1])
1981 n = find_elements (client->doc, n->children, dst + 1, &rc,
1982 NULL, NULL, NULL, 0, 0, NULL, 0);
1983 if (!n)
1984 goto fail;
1987 rc = validate_target_attribute (client->doc, req[0], n);
1988 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
1989 goto fail;
1991 n = create_element_path (client, &src, &rc, NULL);
1992 if (rc)
1993 goto fail;
1995 line = strv_join ("\t", odst);
1996 if (!line)
1998 rc = GPG_ERR_ENOMEM;
1999 goto fail;
2002 rc = add_attribute (n, "target", line);
2004 fail:
2005 xfree (line);
2006 strv_free (src);
2007 strv_free (dst);
2008 strv_free (odst);
2009 return rc;
2013 * req[0] - attribute
2014 * req[1] - element path
2016 static gpg_error_t
2017 attribute_get (assuan_context_t ctx, char **req)
2019 struct client_s *client = assuan_get_pointer (ctx);
2020 xmlNodePtr n;
2021 xmlChar *a;
2022 char **path = NULL;
2023 gpg_error_t rc;
2025 if (!req || !req[0] || !req[1])
2026 return GPG_ERR_SYNTAX;
2028 if (strchr (req[1], '\t'))
2030 if ((path = str_split (req[1], "\t", 0)) == NULL)
2031 return GPG_ERR_SYNTAX;
2033 else
2035 if ((path = str_split (req[1], " ", 0)) == NULL)
2036 return GPG_ERR_SYNTAX;
2039 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
2041 if (!n)
2042 goto fail;
2044 if (path[1])
2046 n = find_elements (client->doc, n->children, path + 1, &rc,
2047 NULL, NULL, NULL, 0, 0, NULL, 0);
2049 if (!n)
2050 goto fail;
2053 strv_free (path);
2055 if ((a = xmlGetProp (n, (xmlChar *) req[0])) == NULL)
2056 return GPG_ERR_NOT_FOUND;
2058 pthread_cleanup_push (xmlFree, a);
2060 if (*a)
2061 rc = xfer_data (ctx, (char *) a, xmlStrlen (a));
2062 else
2063 rc = GPG_ERR_NO_DATA;
2065 pthread_cleanup_pop (1);
2066 return rc;
2068 fail:
2069 strv_free (path);
2070 return rc;
2074 * req[0] - attribute
2075 * req[1] - element path
2076 * req[2] - value
2078 static gpg_error_t
2079 attribute_set (struct client_s *client, char **req)
2081 char **path = NULL;
2082 gpg_error_t rc;
2083 xmlNodePtr n;
2085 if (!req || !req[0] || !req[1])
2086 return GPG_ERR_SYNTAX;
2089 * Reserved attribute names.
2091 if (!strcmp (req[0], "_name"))
2092 return GPG_ERR_INV_ATTR;
2093 else if (!strcmp (req[0], "target"))
2094 return target_attribute (client, req + 1);
2095 else if (!valid_xml_attribute (req[0]))
2096 return GPG_ERR_INV_VALUE;
2098 if ((path = str_split (req[1], "\t", 0)) == NULL)
2101 * The first argument may be only a root element.
2103 if ((path = str_split (req[1], " ", 0)) == NULL)
2104 return GPG_ERR_SYNTAX;
2107 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
2109 if (!n)
2110 goto fail;
2112 if (path[1])
2114 n = find_elements (client->doc, n->children, path + 1, &rc,
2115 NULL, NULL, NULL, 0, 0, NULL, 0);
2117 if (!n)
2118 goto fail;
2121 rc = add_attribute (n, req[0], req[2]);
2123 fail:
2124 strv_free (path);
2125 return rc;
2129 * req[0] - command
2130 * req[1] - attribute name or element path if command is LIST
2131 * req[2] - element path
2132 * req[2] - element path or value
2135 static gpg_error_t
2136 do_attr (assuan_context_t ctx, char *line)
2138 struct client_s *client = assuan_get_pointer (ctx);
2139 gpg_error_t rc = 0;
2140 char **req;
2142 req = str_split (line, " ", 4);
2143 if (!req || !req[0] || !req[1])
2145 strv_free (req);
2146 return GPG_ERR_SYNTAX;
2149 pthread_cleanup_push (req_cleanup, req);
2151 if (strcasecmp (req[0], "SET") == 0)
2152 rc = attribute_set (client, req + 1);
2153 else if (strcasecmp (req[0], "GET") == 0)
2154 rc = attribute_get (ctx, req + 1);
2155 else if (strcasecmp (req[0], "DELETE") == 0)
2156 rc = attribute_delete (client, req + 1);
2157 else if (strcasecmp (req[0], "LIST") == 0)
2158 rc = attribute_list (ctx, req + 1);
2159 else
2160 rc = GPG_ERR_SYNTAX;
2162 pthread_cleanup_pop (1);
2163 return rc;
2166 static gpg_error_t
2167 attr_command (assuan_context_t ctx, char *line)
2169 struct client_s *client = assuan_get_pointer (ctx);
2170 gpg_error_t rc;
2171 struct argv_s *args[] = {
2172 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2173 NULL
2176 rc = parse_options (&line, args, client);
2177 if (rc)
2178 return send_error (ctx, rc);
2180 if (client->opts & OPT_INQUIRE)
2182 unsigned char *result;
2183 size_t len;
2185 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2186 if (rc)
2187 return send_error (ctx, rc);
2189 line = (char *) result;
2192 rc = do_attr (ctx, line);
2194 if (client->opts & OPT_INQUIRE)
2195 xfree (line);
2197 return send_error (ctx, rc);
2200 static gpg_error_t
2201 parse_iscached_opt_lock (void *data, void *value)
2203 struct client_s *client = data;
2205 (void) value;
2206 client->opts |= OPT_LOCK;
2207 return 0;
2210 static gpg_error_t
2211 iscached_command (assuan_context_t ctx, char *line)
2213 struct client_s *client = assuan_get_pointer (ctx);
2214 gpg_error_t rc;
2215 unsigned char md5file[16];
2216 struct argv_s *args[] = {
2217 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_iscached_opt_lock},
2218 NULL
2221 if (!line || !*line)
2222 return send_error (ctx, GPG_ERR_SYNTAX);
2224 rc = parse_options (&line, args, client);
2225 if (rc)
2226 return send_error (ctx, rc);
2227 else if (!valid_filename (line))
2228 return send_error (ctx, GPG_ERR_INV_VALUE);
2230 rc = cache_iscached (line, NULL);
2231 if (client->opts & OPT_LOCK
2232 && (!rc || gpg_err_code (rc) == GPG_ERR_NO_DATA))
2234 gpg_error_t trc = rc;
2235 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2236 if (memcmp (md5file, client->md5file, 16))
2237 cleanup_client (client);
2239 memcpy (client->md5file, md5file, 16);
2240 rc = do_lock (client, 1);
2241 if (!rc)
2242 rc = trc;
2245 return send_error (ctx, rc);
2248 static gpg_error_t
2249 clearcache_command (assuan_context_t ctx, char *line)
2251 gpg_error_t rc = 0, all_rc = 0;
2252 unsigned char md5file[16];
2253 int i;
2254 int t;
2255 int all = 0;
2256 struct client_thread_s *once = NULL;
2258 cache_lock ();
2259 MUTEX_LOCK (&cn_mutex);
2260 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
2262 if (!line || !*line)
2263 all = 1;
2265 t = slist_length (cn_thread_list);
2267 for (i = 0; i < t; i++)
2269 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2270 assuan_peercred_t peer;
2272 if (!thd->cl)
2273 continue;
2275 /* Lock each connected clients' file mutex to prevent any other client
2276 * from accessing the cache entry (the file mutex is locked upon
2277 * command startup). The cache for the entry is not cleared if the
2278 * file mutex is locked by another client to prevent this function
2279 * from blocking.
2281 if (all)
2283 if (thd->cl->filename)
2285 rc = do_validate_peer (ctx, thd->cl->filename, &peer);
2286 all_rc = !all_rc ? rc : all_rc;
2287 if (rc)
2289 rc = 0;
2290 continue;
2294 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0, -1);
2295 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2297 if (pthread_equal (pthread_self (), thd->tid))
2298 rc = 0;
2299 else
2301 if (!thd->cl->filename ||
2302 cache_iscached (thd->cl->filename,
2303 NULL) == GPG_ERR_NO_DATA)
2305 rc = 0;
2306 continue;
2309 cache_defer_clear (thd->cl->md5file);
2312 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
2314 rc = 0;
2315 continue;
2318 if (!rc)
2320 rc = cache_clear (thd->cl->md5file);
2321 cache_unlock_mutex (thd->cl->md5file, 0);
2324 if (rc)
2325 all_rc = rc;
2327 rc = 0;
2329 /* A single data filename was specified. Lock only this data file
2330 * mutex and free the cache entry. */
2331 else
2333 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2334 rc = do_validate_peer (ctx, line, &peer);
2336 if (!rc && !memcmp (thd->cl->md5file, md5file, sizeof (md5file)))
2338 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0,
2339 -1);
2340 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2342 if (pthread_equal (pthread_self (), thd->tid))
2343 rc = 0;
2346 if (!rc)
2348 once = thd;
2349 rc = cache_clear (thd->cl->md5file);
2350 cache_unlock_mutex (thd->cl->md5file, 0);
2352 else
2354 cache_defer_clear (thd->cl->md5file);
2357 break;
2362 /* Only connected clients' cache entries have been cleared. Now clear any
2363 * remaining cache entries without clients but only if there wasn't an
2364 * error from above since this would defeat the locking check of the
2365 * remaining entries. */
2366 if (!all_rc && all)
2368 cache_clear (NULL);
2371 /* No clients are using the specified file. */
2372 else if (!all_rc && !rc && !once)
2374 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2375 rc = cache_clear (md5file);
2378 /* Release the connection mutex. */
2379 pthread_cleanup_pop (1);
2380 cache_unlock ();
2382 if (!rc)
2383 send_status_all (STATUS_CACHE, NULL);
2385 /* One or more files were locked while clearing all cache entries. */
2386 if (all_rc)
2387 rc = all_rc;
2389 return send_error (ctx, rc);
2392 static gpg_error_t
2393 cachetimeout_command (assuan_context_t ctx, char *line)
2395 unsigned char md5file[16];
2396 int timeout;
2397 char **req = str_split (line, " ", 0);
2398 char *p;
2399 gpg_error_t rc = 0;
2400 assuan_peercred_t peer;
2402 if (!req || !*req || !req[1])
2404 strv_free (req);
2405 return send_error (ctx, GPG_ERR_SYNTAX);
2408 errno = 0;
2409 timeout = (int) strtol (req[1], &p, 10);
2410 if (errno != 0 || *p || timeout < -1)
2412 strv_free (req);
2413 return send_error (ctx, GPG_ERR_SYNTAX);
2416 rc = do_validate_peer (ctx, req[0], &peer);
2417 if (!rc)
2419 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, req[0], strlen (req[0]));
2420 rc = cache_set_timeout (md5file, timeout);
2421 if (!rc || gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
2423 rc = 0;
2424 MUTEX_LOCK (&rcfile_mutex);
2425 config_set_int_param (&global_config, req[0], "cache_timeout",
2426 req[1]);
2427 MUTEX_UNLOCK (&rcfile_mutex);
2431 strv_free (req);
2432 return send_error (ctx, rc);
2435 static gpg_error_t
2436 dump_command (assuan_context_t ctx, char *line)
2438 xmlChar *xml;
2439 int len;
2440 struct client_s *client = assuan_get_pointer (ctx);
2441 gpg_error_t rc;
2443 if (disable_list_and_dump == 1)
2444 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2446 xmlDocDumpFormatMemory (client->doc, &xml, &len, 1);
2448 if (!xml)
2450 log_write ("%s(%i): %s", __FILE__, __LINE__,
2451 pwmd_strerror (GPG_ERR_ENOMEM));
2452 return send_error (ctx, GPG_ERR_ENOMEM);
2455 pthread_cleanup_push (xmlFree, xml);
2456 rc = xfer_data (ctx, (char *) xml, len);
2457 pthread_cleanup_pop (1);
2458 return send_error (ctx, rc);
2461 static gpg_error_t
2462 getconfig_command (assuan_context_t ctx, char *line)
2464 struct client_s *client = assuan_get_pointer (ctx);
2465 gpg_error_t rc = 0;
2466 char filename[255] = { 0 }, param[747] = { 0 };
2467 char *p, *tmp = NULL, *fp = client->filename, *paramp = line;
2469 if (!line || !*line)
2470 return send_error (ctx, GPG_ERR_SYNTAX);
2472 if (strchr (line, ' '))
2474 sscanf (line, " %254[^ ] %746c", filename, param);
2475 paramp = param;
2476 fp = filename;
2479 if (fp && !valid_filename (fp))
2480 return send_error (ctx, GPG_ERR_INV_VALUE);
2482 paramp = str_down (paramp);
2483 if (!strcmp (paramp, "cipher") && fp)
2485 struct crypto_s *crypto = NULL;
2487 rc = init_client_crypto (&crypto);
2488 if (!rc)
2490 rc = read_data_header (fp, &crypto->hdr, NULL, NULL);
2491 if (!rc)
2493 const char *t =
2494 gcry_cipher_algo_name (cipher_to_gcrypt (crypto->hdr.flags));
2495 if (t)
2497 tmp = str_dup (t);
2498 if (tmp)
2499 str_down (tmp);
2504 UPDATE_AGENT_CTX (client, crypto);
2505 cleanup_crypto (&crypto);
2506 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
2507 return send_error (ctx, rc);
2509 if (!rc && tmp)
2510 goto done;
2512 else if (!strcmp (paramp, "cipher_iterations") && fp)
2514 struct crypto_s *crypto = NULL;
2516 rc = init_client_crypto (&crypto);
2517 if (!rc)
2519 rc = read_data_header (fp, &crypto->hdr, NULL, NULL);
2520 if (!rc)
2522 tmp = str_asprintf ("%llu",
2523 (unsigned long long) crypto->hdr.
2524 iterations);
2525 if (!tmp)
2526 rc = GPG_ERR_ENOMEM;
2530 UPDATE_AGENT_CTX (client, crypto);
2531 cleanup_crypto (&crypto);
2532 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
2533 return send_error (ctx, rc);
2535 if (!rc && tmp)
2536 goto done;
2538 else if (!strcmp (paramp, "passphrase"))
2539 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2541 p = config_get_value (fp ? fp : "global", paramp);
2542 if (!p)
2543 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2545 tmp = expand_homedir (p);
2546 xfree (p);
2547 if (!tmp)
2549 log_write ("%s(%i): %s", __FILE__, __LINE__,
2550 pwmd_strerror (GPG_ERR_ENOMEM));
2551 return send_error (ctx, GPG_ERR_ENOMEM);
2554 done:
2555 p = tmp;
2556 pthread_cleanup_push (xfree, p);
2557 rc = xfer_data (ctx, p, strlen (p));
2558 pthread_cleanup_pop (1);
2559 return send_error (ctx, rc);
2562 struct xpath_s
2564 xmlXPathContextPtr xp;
2565 xmlXPathObjectPtr result;
2566 xmlBufferPtr buf;
2567 char **req;
2570 static void
2571 xpath_command_cleanup (void *arg)
2573 struct xpath_s *xpath = arg;
2575 if (!xpath)
2576 return;
2578 req_cleanup (xpath->req);
2580 if (xpath->buf)
2581 xmlBufferFree (xpath->buf);
2583 if (xpath->result)
2584 xmlXPathFreeObject (xpath->result);
2586 if (xpath->xp)
2587 xmlXPathFreeContext (xpath->xp);
2590 static gpg_error_t
2591 do_xpath (assuan_context_t ctx, char *line)
2593 gpg_error_t rc;
2594 struct client_s *client = assuan_get_pointer (ctx);
2595 struct xpath_s _x = { 0 };
2596 struct xpath_s *xpath = &_x;
2598 if ((xpath->req = str_split (line, "\t", 2)) == NULL)
2600 if (strv_printf (&xpath->req, "%s", line) == 0)
2601 return GPG_ERR_ENOMEM;
2604 xpath->xp = xmlXPathNewContext (client->doc);
2605 if (!xpath->xp)
2607 rc = GPG_ERR_BAD_DATA;
2608 goto fail;
2611 xpath->result =
2612 xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2613 if (!xpath->result)
2615 rc = GPG_ERR_BAD_DATA;
2616 goto fail;
2619 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2621 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2622 goto fail;
2625 rc = recurse_xpath_nodeset (client->doc, xpath->result->nodesetval,
2626 (xmlChar *) xpath->req[1], &xpath->buf, 0,
2627 NULL);
2628 if (rc)
2629 goto fail;
2630 else if (!xpath->req[1] && !xmlBufferLength (xpath->buf))
2632 rc = GPG_ERR_NO_DATA;
2633 goto fail;
2635 else if (xpath->req[1])
2637 rc = 0;
2638 goto fail;
2641 pthread_cleanup_push (xpath_command_cleanup, &xpath);
2642 rc = xfer_data (ctx, (char *) xmlBufferContent (xpath->buf),
2643 xmlBufferLength (xpath->buf));
2644 pthread_cleanup_pop (0);
2645 fail:
2646 xpath_command_cleanup (xpath);
2647 return rc;
2650 static gpg_error_t
2651 xpath_command (assuan_context_t ctx, char *line)
2653 struct client_s *client = assuan_get_pointer (ctx);
2654 gpg_error_t rc;
2655 struct argv_s *args[] = {
2656 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2657 NULL
2660 if (disable_list_and_dump == 1)
2661 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2663 rc = parse_options (&line, args, client);
2664 if (rc)
2665 return send_error (ctx, rc);
2667 if (client->opts & OPT_INQUIRE)
2669 unsigned char *result;
2670 size_t len;
2672 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2673 if (rc)
2674 return send_error (ctx, rc);
2676 line = (char *) result;
2679 if (!line || !*line)
2680 rc = GPG_ERR_SYNTAX;
2682 if (!rc)
2683 rc = do_xpath (ctx, line);
2685 if (client->opts & OPT_INQUIRE)
2686 xfree (line);
2688 return send_error (ctx, rc);
2691 static gpg_error_t
2692 do_xpathattr (assuan_context_t ctx, char *line)
2694 struct client_s *client = assuan_get_pointer (ctx);
2695 gpg_error_t rc;
2696 char **req = NULL;
2697 int cmd = 0; //SET
2698 struct xpath_s _x = { 0 };
2699 struct xpath_s *xpath = &_x;
2701 if ((req = str_split (line, " ", 3)) == NULL)
2702 return GPG_ERR_ENOMEM;
2704 if (!req[0])
2706 rc = GPG_ERR_SYNTAX;
2707 goto fail;
2710 if (!strcasecmp (req[0], "SET"))
2711 cmd = 0;
2712 else if (!strcasecmp (req[0], "DELETE"))
2713 cmd = 1;
2714 else
2716 rc = GPG_ERR_SYNTAX;
2717 goto fail;
2720 if (!req[1] || !req[2])
2722 rc = GPG_ERR_SYNTAX;
2723 goto fail;
2726 if ((xpath->req = str_split (req[2], "\t", 3)) == NULL)
2728 rc = GPG_ERR_ENOMEM;
2729 goto fail;
2732 if (!xpath->req[0] || (!xpath->req[1] && !cmd) || (xpath->req[1] && cmd))
2734 rc = GPG_ERR_SYNTAX;
2735 goto fail;
2738 xpath->xp = xmlXPathNewContext (client->doc);
2739 if (!xpath->xp)
2741 rc = GPG_ERR_BAD_DATA;
2742 goto fail;
2745 xpath->result = xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2746 if (!xpath->result)
2748 rc = GPG_ERR_BAD_DATA;
2749 goto fail;
2752 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2754 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2755 goto fail;
2758 rc = recurse_xpath_nodeset (client->doc, xpath->result->nodesetval,
2759 (xmlChar *) xpath->req[1], &xpath->buf, cmd,
2760 (xmlChar *) req[1]);
2762 fail:
2763 xpath_command_cleanup (xpath);
2764 strv_free (req);
2765 return rc;
2768 /* XPATHATTR SET|DELETE <name> <expression>[<TAB>[value]] */
2769 static gpg_error_t
2770 xpathattr_command (assuan_context_t ctx, char *line)
2772 struct client_s *client = assuan_get_pointer (ctx);
2773 gpg_error_t rc;
2774 struct argv_s *args[] = {
2775 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2776 NULL
2779 if (disable_list_and_dump == 1)
2780 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2782 rc = parse_options (&line, args, client);
2783 if (rc)
2784 return send_error (ctx, rc);
2786 if (client->opts & OPT_INQUIRE)
2788 unsigned char *result;
2789 size_t len;
2791 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2792 if (rc)
2793 return send_error (ctx, rc);
2795 line = (char *) result;
2798 if (!line || !*line)
2799 rc = GPG_ERR_SYNTAX;
2801 if (!rc)
2802 rc = do_xpathattr (ctx, line);
2804 if (client->opts & OPT_INQUIRE)
2805 xfree (line);
2807 return send_error (ctx, rc);
2810 static gpg_error_t
2811 do_import (struct client_s *client, const char *root_element,
2812 unsigned char *content)
2814 char **dst_path = NULL;
2815 xmlDocPtr doc = NULL;
2816 xmlNodePtr n, root, copy;
2817 gpg_error_t rc;
2819 if (!content || !*content)
2821 xfree (content);
2822 return GPG_ERR_SYNTAX;
2825 if (root_element)
2826 dst_path = str_split (root_element, "\t", 0);
2828 if (dst_path && !valid_element_path (dst_path, 0))
2830 if (dst_path)
2831 strv_free (dst_path);
2833 return GPG_ERR_INV_VALUE;
2836 struct string_s *str = string_new_content ((char *)content);
2837 str = string_prepend (str, "<pwmd>");
2838 str = string_append (str, "</pwmd>");
2839 doc = xmlReadDoc ((xmlChar *) str->str, NULL, "UTF-8", XML_PARSE_NOBLANKS);
2840 string_free (str, 1);
2841 if (!doc)
2843 rc = GPG_ERR_BAD_DATA;
2844 goto fail;
2847 root = xmlDocGetRootElement (doc);
2848 xmlNodePtr root_orig = root->children;
2849 root = root->children;
2850 rc = validate_import (root);
2851 if (rc)
2852 goto fail;
2856 again:
2857 if (dst_path)
2859 char **path = strv_dup (dst_path);
2860 if (!path)
2862 log_write ("%s(%i): %s", __FILE__, __LINE__,
2863 pwmd_strerror (GPG_ERR_ENOMEM));
2864 rc = GPG_ERR_ENOMEM;
2865 goto fail;
2868 xmlChar *a = xmlGetProp (root, (xmlChar *) "_name");
2869 if (!a)
2871 strv_free (path);
2872 rc = GPG_ERR_ENOMEM;
2873 goto fail;
2876 if (strv_printf (&path, "%s", (char *) a) == 0)
2878 xmlFree (a);
2879 rc = GPG_ERR_ENOMEM;
2880 goto fail;
2883 xmlFree (a);
2884 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
2885 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2887 strv_free (path);
2888 goto fail;
2891 if (!rc)
2893 n = find_elements (client->doc, n->children, path + 1, &rc,
2894 NULL, NULL, NULL, 0, 0, NULL, 1);
2895 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2897 strv_free (path);
2898 goto fail;
2900 else if (!rc)
2902 xmlUnlinkNode (n);
2903 xmlFreeNode (n);
2904 strv_free (path);
2905 path = NULL;
2906 goto again;
2910 if (rc == GPG_ERR_ELEMENT_NOT_FOUND)
2912 n = create_element_path (client, &path, &rc, NULL);
2913 if (rc)
2914 goto fail;
2917 if (root->children)
2919 copy = xmlCopyNodeList (root->children);
2920 n = xmlAddChildList (n, copy);
2921 if (!n)
2922 rc = GPG_ERR_ENOMEM;
2925 strv_free (path);
2927 else
2929 char **path = NULL;
2931 /* Check if the content root element can create a DTD root element. */
2932 if (!xmlStrEqual ((xmlChar *) "element", root->name))
2934 rc = GPG_ERR_SYNTAX;
2935 goto fail;
2938 xmlChar *a;
2940 if ((a = xmlGetProp (root, (xmlChar *) "_name")) == NULL)
2942 rc = GPG_ERR_SYNTAX;
2943 goto fail;
2946 char *tmp = str_dup ((char *) a);
2947 xmlFree (a);
2948 int literal = is_literal_element (&tmp);
2950 if (!valid_xml_element ((xmlChar *) tmp) || literal)
2952 xfree (tmp);
2953 rc = GPG_ERR_INV_VALUE;
2954 goto fail;
2957 if (strv_printf (&path, "%s", tmp) == 0)
2959 xfree (tmp);
2960 rc = GPG_ERR_ENOMEM;
2961 goto fail;
2964 xfree (tmp);
2965 n = find_root_element (client->doc, &path, &rc, NULL, 0, 1);
2966 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2968 rc = GPG_ERR_BAD_DATA;
2969 goto fail;
2972 /* Overwriting the existing tree. */
2973 if (!rc)
2975 xmlUnlinkNode (n);
2976 xmlFreeNodeList (n);
2979 rc = 0;
2980 xmlSetProp (root, (xmlChar *) "_name", (xmlChar *) path[0]);
2981 n = xmlCopyNode (root, 1);
2982 n = xmlAddChildList (xmlDocGetRootElement (client->doc), n);
2983 strv_free (path);
2986 if (n && !rc)
2987 rc = update_element_mtime (n->parent);
2989 for (root = root_orig->next; root; root = root->next)
2991 if (root->type == XML_ELEMENT_NODE)
2992 break;
2995 root_orig = root;
2997 while (root);
2999 fail:
3000 if (doc)
3001 xmlFreeDoc (doc);
3003 if (dst_path)
3004 strv_free (dst_path);
3006 return rc;
3009 static gpg_error_t
3010 parse_import_opt_root (void *data, void *value)
3012 struct client_s *client = data;
3014 client->import_root = str_dup (value);
3015 return client->import_root ? 0 : GPG_ERR_ENOMEM;
3018 static gpg_error_t
3019 import_command (assuan_context_t ctx, char *line)
3021 gpg_error_t rc;
3022 struct client_s *client = assuan_get_pointer (ctx);
3023 unsigned char *result;
3024 size_t len;
3025 struct argv_s *args[] = {
3026 &(struct argv_s) {"root", OPTION_TYPE_ARG, parse_import_opt_root},
3027 NULL
3030 xfree (client->import_root);
3031 client->import_root = NULL;
3032 rc = parse_options (&line, args, client);
3033 if (rc)
3034 return send_error (ctx, rc);
3036 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3037 if (rc)
3038 return send_error (ctx, rc);
3040 rc = do_import (client, client->import_root, result);
3041 xfree (client->import_root);
3042 client->import_root = NULL;
3043 return send_error (ctx, rc);
3046 static gpg_error_t
3047 do_lock (struct client_s *client, int add)
3049 gpg_error_t rc = lock_file_mutex (client, add);
3051 if (!rc)
3052 client->flags |= FLAG_LOCK_CMD;
3054 return rc;
3057 static gpg_error_t
3058 lock_command (assuan_context_t ctx, char *line)
3060 struct client_s *client = assuan_get_pointer (ctx);
3061 gpg_error_t rc = do_lock (client, 0);
3063 return send_error (ctx, rc);
3066 static gpg_error_t
3067 unlock_command (assuan_context_t ctx, char *line)
3069 struct client_s *client = assuan_get_pointer (ctx);
3070 gpg_error_t rc;
3072 rc = unlock_file_mutex (client, 0);
3073 return send_error (ctx, rc);
3076 static gpg_error_t
3077 option_command (assuan_context_t ctx, char *line)
3079 struct client_s *client = assuan_get_pointer (ctx);
3080 gpg_error_t rc = 0;
3081 struct pinentry_option_s *pin_opts = &client->pinentry_opts;
3082 #ifdef WITH_AGENT
3083 struct agent_s *agent = client->crypto->agent;
3084 #endif
3085 char namebuf[255] = { 0 };
3086 char *name = namebuf;
3087 char *value = NULL, *p;
3089 p = strchr (line, '=');
3090 if (!p)
3091 strncpy (namebuf, line, sizeof(namebuf));
3092 else
3094 strncpy (namebuf, line, strlen (line)-strlen (p));
3095 value = p+1;
3098 log_write1 ("OPTION name='%s' value='%s'", name, value);
3100 if (strcasecmp (name, (char *) "log_level") == 0)
3102 long l = 0;
3104 if (value)
3106 l = strtol (value, NULL, 10);
3108 if (l < 0 || l > 2)
3109 return send_error (ctx, GPG_ERR_INV_VALUE);
3112 MUTEX_LOCK (&rcfile_mutex);
3113 config_set_int_param (&global_config, "global", "log_level", value);
3114 MUTEX_UNLOCK (&rcfile_mutex);
3115 goto done;
3117 else if (strcasecmp (name, (char *) "lock-timeout") == 0)
3119 long n = 0;
3120 char *p = NULL;
3122 if (value)
3124 n = strtol (value, &p, 10);
3125 if (p && *p)
3126 return send_error (ctx, GPG_ERR_INV_VALUE);
3129 client->lock_timeout = n;
3130 goto done;
3132 else if (strcasecmp (name, (char *) "NAME") == 0)
3134 char *tmp = pthread_getspecific (thread_name_key);
3136 if (tmp)
3137 xfree (tmp);
3139 if (!value || !*value)
3141 pthread_setspecific (thread_name_key, str_dup (""));
3142 goto done;
3145 pthread_setspecific (thread_name_key, str_dup (value));
3146 goto done;
3148 else if (strcasecmp (name, (char *) "lc-messages") == 0)
3150 xfree (pin_opts->lc_messages);
3151 pin_opts->lc_messages = NULL;
3152 if (value && *value)
3153 pin_opts->lc_messages = str_dup (value);
3154 #ifdef WITH_AGENT
3155 if (use_agent)
3156 rc = set_agent_option (client->crypto->agent, "lc-messages", value);
3157 #endif
3159 else if (strcasecmp (name, (char *) "lc-ctype") == 0)
3161 xfree (pin_opts->lc_ctype);
3162 pin_opts->lc_ctype = NULL;
3163 if (value && *value)
3164 pin_opts->lc_ctype = str_dup (value);
3165 #ifdef WITH_AGENT
3166 if (use_agent)
3167 rc = set_agent_option (client->crypto->agent, "lc-ctype", value);
3168 #endif
3170 else if (strcasecmp (name, (char *) "ttyname") == 0)
3172 xfree (pin_opts->ttyname);
3173 pin_opts->ttyname = NULL;
3174 if (value && *value)
3175 pin_opts->ttyname = str_dup (value);
3176 #ifdef WITH_AGENT
3177 if (use_agent)
3178 rc = set_agent_option (client->crypto->agent, "ttyname", value);
3179 #endif
3181 else if (strcasecmp (name, (char *) "ttytype") == 0)
3183 xfree (pin_opts->ttytype);
3184 pin_opts->ttytype = NULL;
3185 if (value && *value)
3186 pin_opts->ttytype = str_dup (value);
3187 #ifdef WITH_AGENT
3188 if (use_agent)
3189 rc = set_agent_option (client->crypto->agent, "ttytype", value);
3190 #endif
3192 else if (strcasecmp (name, (char *) "display") == 0)
3194 xfree (pin_opts->display);
3195 pin_opts->display = NULL;
3196 if (value && *value)
3197 pin_opts->display = str_dup (value);
3198 #ifdef WITH_AGENT
3199 if (use_agent)
3200 rc = set_agent_option (client->crypto->agent, "display", value);
3201 #endif
3203 else if (strcasecmp (name, (char *) "pinentry-desc") == 0)
3205 xfree (pin_opts->desc);
3206 pin_opts->desc = NULL;
3207 if (value && *value)
3208 pin_opts->desc = str_dup (value);
3210 else if (strcasecmp (name, (char *) "pinentry-title") == 0)
3212 xfree (pin_opts->title);
3213 pin_opts->title = NULL;
3214 if (value && *value)
3215 pin_opts->title = str_dup (value);
3217 else if (strcasecmp (name, (char *) "pinentry-prompt") == 0)
3219 xfree (pin_opts->prompt);
3220 pin_opts->prompt = NULL;
3221 if (value && *value)
3222 pin_opts->prompt = str_dup (value);
3225 else if (strcasecmp (name, "pinentry-timeout") == 0)
3227 char *p = NULL;
3228 int n;
3230 if (!value)
3231 goto done;
3233 n = (int) strtol (value, &p, 10);
3235 if (*p || n < 0)
3236 return send_error (ctx, GPG_ERR_INV_VALUE);
3238 pin_opts->timeout = n;
3239 MUTEX_LOCK (&rcfile_mutex);
3240 config_set_int_param (&global_config,
3241 client->filename ? client->filename : "global",
3242 "pinentry_timeout", value);
3243 MUTEX_UNLOCK (&rcfile_mutex);
3244 goto done;
3246 else if (strcasecmp (name, "disable-pinentry") == 0)
3248 char *p = NULL;
3249 int n = 1;
3251 if (value && *value)
3253 n = (int) strtol (value, &p, 10);
3254 if (*p || n < 0 || n > 1)
3255 return send_error (ctx, GPG_ERR_INV_VALUE);
3258 if (n)
3259 client->flags |= FLAG_NO_PINENTRY;
3260 else
3261 client->flags &= ~FLAG_NO_PINENTRY;
3263 #ifdef WITH_AGENT
3264 if (use_agent)
3266 if (client->flags & FLAG_NO_PINENTRY)
3267 rc = set_agent_option (client->crypto->agent, "pinentry-mode",
3268 "loopback");
3269 else
3270 rc = set_agent_option (client->crypto->agent, "pinentry-mode",
3271 "ask");
3273 if (rc)
3274 return send_error (ctx, rc);
3276 #endif
3278 else
3279 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
3281 done:
3282 #ifdef WITH_AGENT
3283 if (!rc && use_agent && agent)
3285 rc = pinentry_merge_options (&client->crypto->agent->pinentry_opts,
3286 pin_opts);
3288 #endif
3290 return send_error (ctx, rc);
3293 static gpg_error_t
3294 do_rename (assuan_context_t ctx, char *line)
3296 struct client_s *client = assuan_get_pointer (ctx);
3297 gpg_error_t rc;
3298 char **req, **src, *dst;
3299 xmlNodePtr n, ndst;
3301 req = str_split (line, " ", 0);
3303 if (!req || !req[0] || !req[1])
3305 strv_free (req);
3306 return GPG_ERR_SYNTAX;
3309 dst = req[1];
3310 is_literal_element (&dst);
3312 if (!valid_xml_element ((xmlChar *) dst))
3314 strv_free (req);
3315 return GPG_ERR_INV_VALUE;
3318 if (strchr (req[0], '\t'))
3319 src = str_split (req[0], "\t", 0);
3320 else
3321 src = str_split (req[0], " ", 0);
3323 if (!src || !*src)
3325 rc = GPG_ERR_SYNTAX;
3326 goto fail;
3329 n = find_root_element (client->doc, &src, &rc, NULL, 0, 0);
3330 if (src[1] && n)
3331 n = find_elements (client->doc, n->children, src + 1, &rc, NULL, NULL,
3332 NULL, 0, 0, NULL, 0);
3334 if (!n)
3335 goto fail;
3337 xmlChar *a = xmlGetProp (n, (xmlChar *) "_name");
3338 if (!a)
3340 rc = GPG_ERR_ENOMEM;
3341 goto fail;
3344 /* To prevent unwanted effects:
3346 * <root name="a"><b/></root>
3348 * RENAME a<TAB>b b
3350 if (xmlStrEqual (a, (xmlChar *) dst))
3352 xmlFree (a);
3353 rc = GPG_ERR_AMBIGUOUS_NAME;
3354 goto fail;
3357 xmlFree (a);
3358 char **tmp = NULL;
3359 if (src[1])
3361 char **p;
3363 for (p = src; *p; p++)
3365 if (!*(p + 1))
3366 break;
3367 strv_printf (&tmp, "%s", *p);
3371 strv_printf (&tmp, "!%s", dst);
3372 ndst = find_root_element (client->doc, &tmp, &rc, NULL, 0, 0);
3373 if (!ndst && rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3375 strv_free (tmp);
3376 goto fail;
3379 if (tmp[1] && ndst)
3380 ndst = find_elements (client->doc, ndst->children, tmp + 1, &rc, NULL,
3381 NULL, NULL, 0, 0, NULL, 0);
3383 strv_free (tmp);
3384 if (!ndst && rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3385 goto fail;
3387 rc = 0;
3389 /* Target may exist:
3391 * <root name="a"/>
3392 * <root name="b" target="a"/>
3394 * RENAME b a
3396 * Would need to do:
3397 * RENAME !b a
3399 if (ndst == n)
3401 rc = GPG_ERR_AMBIGUOUS_NAME;
3402 goto fail;
3405 if (ndst)
3407 unlink_node (ndst);
3408 xmlFreeNodeList (ndst);
3411 rc = add_attribute (n, "_name", dst);
3413 fail:
3414 strv_free (req);
3415 strv_free (src);
3416 return rc;
3419 static gpg_error_t
3420 rename_command (assuan_context_t ctx, char *line)
3422 struct client_s *client = assuan_get_pointer (ctx);
3423 gpg_error_t rc;
3424 struct argv_s *args[] = {
3425 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3426 NULL
3429 rc = parse_options (&line, args, client);
3430 if (rc)
3431 return send_error (ctx, rc);
3433 if (client->opts & OPT_INQUIRE)
3435 unsigned char *result;
3436 size_t len;
3438 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3439 if (rc)
3440 return send_error (ctx, rc);
3442 line = (char *) result;
3445 rc = do_rename (ctx, line);
3447 if (client->opts & OPT_INQUIRE)
3448 xfree (line);
3450 return send_error (ctx, rc);
3453 static gpg_error_t
3454 do_copy (assuan_context_t ctx, char *line)
3456 struct client_s *client = assuan_get_pointer (ctx);
3457 gpg_error_t rc;
3458 char **req, **src = NULL, **dst = NULL;
3459 xmlNodePtr nsrc, ndst, new = NULL;
3461 req = str_split (line, " ", 0);
3462 if (!req || !req[0] || !req[1])
3464 strv_free (req);
3465 return GPG_ERR_SYNTAX;
3468 if (strchr (req[0], '\t'))
3469 src = str_split (req[0], "\t", 0);
3470 else
3471 src = str_split (req[0], " ", 0);
3473 if (!src || !*src)
3475 rc = GPG_ERR_SYNTAX;
3476 goto fail;
3479 if (strchr (req[1], '\t'))
3480 dst = str_split (req[1], "\t", 0);
3481 else
3482 dst = str_split (req[1], " ", 0);
3484 if (!dst || !*dst)
3486 rc = GPG_ERR_SYNTAX;
3487 goto fail;
3490 if (!valid_element_path (dst, 0))
3492 rc = GPG_ERR_INV_VALUE;
3493 goto fail;
3496 nsrc = find_root_element (client->doc, &src, &rc, NULL, 0, 0);
3497 if (nsrc && src[1])
3498 nsrc = find_elements (client->doc, nsrc->children, src + 1, &rc, NULL,
3499 NULL, NULL, 0, 0, NULL, 0);
3501 if (!nsrc)
3502 goto fail;
3504 new = xmlCopyNodeList (nsrc);
3505 if (!new)
3507 rc = GPG_ERR_ENOMEM;
3508 goto fail;
3511 int create = 0;
3512 ndst = find_root_element (client->doc, &dst, &rc, NULL, 0, 0);
3513 if (ndst && dst[1])
3515 if (ndst->children)
3516 ndst = find_elements (client->doc, ndst->children, dst + 1, &rc, NULL,
3517 NULL, create_target_elements_cb, 0, 0, NULL, 0);
3518 else
3519 create = 1;
3521 else
3522 create = 1;
3524 if (!ndst && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3525 goto fail;
3526 else if (!ndst || create)
3528 ndst = create_element_path (client, &dst, &rc, NULL);
3529 if (!ndst)
3530 goto fail;
3533 /* Merge any attributes from the src node to the initial dst node. */
3534 for (xmlAttrPtr attr = new->properties; attr; attr = attr->next)
3536 if (xmlStrEqual (attr->name, (xmlChar *) "_name"))
3537 continue;
3539 xmlAttrPtr a = xmlHasProp (ndst, attr->name);
3540 if (a)
3541 xmlRemoveProp (a);
3543 xmlChar *tmp = xmlNodeGetContent (attr->children);
3544 xmlNewProp (ndst, attr->name, tmp);
3545 xmlFree (tmp);
3546 rc = add_attribute (ndst, NULL, NULL);
3549 xmlNodePtr n = ndst->children;
3550 xmlUnlinkNode (n);
3551 xmlFreeNodeList (n);
3552 ndst->children = NULL;
3554 if (new->children)
3556 n = xmlCopyNodeList (new->children);
3557 if (!n)
3559 rc = GPG_ERR_ENOMEM;
3560 goto fail;
3563 n = xmlAddChildList (ndst, n);
3564 if (!n)
3566 rc = GPG_ERR_ENOMEM;
3567 goto fail;
3570 rc = update_element_mtime (xmlDocGetRootElement (client->doc) ==
3571 ndst->parent ? ndst : ndst->parent);
3574 fail:
3575 if (new)
3577 xmlUnlinkNode (new);
3578 xmlFreeNodeList (new);
3581 if (req)
3582 strv_free (req);
3584 if (src)
3585 strv_free (src);
3587 if (dst)
3588 strv_free (dst);
3590 return rc;
3593 static gpg_error_t
3594 copy_command (assuan_context_t ctx, char *line)
3596 struct client_s *client = assuan_get_pointer (ctx);
3597 gpg_error_t rc;
3598 struct argv_s *args[] = {
3599 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3600 NULL
3603 rc = parse_options (&line, args, client);
3604 if (rc)
3605 return send_error (ctx, rc);
3607 if (client->opts & OPT_INQUIRE)
3609 unsigned char *result;
3610 size_t len;
3612 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3613 if (rc)
3614 return send_error (ctx, rc);
3616 line = (char *) result;
3619 rc = do_copy (ctx, line);
3621 if (client->opts & OPT_INQUIRE)
3622 xfree (line);
3624 return send_error (ctx, rc);
3627 static gpg_error_t
3628 do_move (assuan_context_t ctx, char *line)
3630 struct client_s *client = assuan_get_pointer (ctx);
3631 gpg_error_t rc;
3632 char **req, **src = NULL, **dst = NULL;
3633 xmlNodePtr nsrc, ndst = NULL;
3635 req = str_split (line, " ", 0);
3637 if (!req || !req[0] || !req[1])
3639 strv_free (req);
3640 return GPG_ERR_SYNTAX;
3643 if (strchr (req[0], '\t'))
3644 src = str_split (req[0], "\t", 0);
3645 else
3646 src = str_split (req[0], " ", 0);
3648 if (!src || !*src)
3650 rc = GPG_ERR_SYNTAX;
3651 goto fail;
3654 if (strchr (req[1], '\t'))
3655 dst = str_split (req[1], "\t", 0);
3656 else
3657 dst = str_split (req[1], " ", 0);
3659 nsrc = find_root_element (client->doc, &src, &rc, NULL, 0, 0);
3660 if (nsrc && src[1])
3661 nsrc = find_elements (client->doc, nsrc->children, src + 1, &rc, NULL,
3662 NULL, NULL, 0, 0, NULL, 0);
3664 if (!nsrc)
3665 goto fail;
3667 if (dst)
3669 if (!valid_element_path (dst, 0))
3671 rc = GPG_ERR_INV_VALUE;
3672 goto fail;
3675 ndst = find_root_element (client->doc, &dst, &rc, NULL, 0, 0);
3676 if (ndst && dst[1])
3677 ndst = find_elements (client->doc, ndst->children, dst + 1, &rc, NULL,
3678 NULL, NULL, 0, 0, NULL, 0);
3680 else
3681 ndst = xmlDocGetRootElement (client->doc);
3683 for (xmlNodePtr n = ndst; n; n = n->parent)
3685 if (n == nsrc)
3687 rc = GPG_ERR_CONFLICT;
3688 goto fail;
3692 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3693 goto fail;
3695 rc = 0;
3697 if (ndst)
3699 xmlChar *a = node_has_attribute (nsrc, (xmlChar *) "_name");
3700 xmlNodePtr dup = find_element (ndst->children, (char *) a, NULL);
3702 xmlFree (a);
3703 if (dup)
3705 if (dup == nsrc)
3706 goto fail;
3708 if (ndst == xmlDocGetRootElement (client->doc))
3710 xmlNodePtr n = nsrc;
3711 int match = 0;
3713 while (n->parent && n->parent != ndst)
3714 n = n->parent;
3716 xmlChar *a = node_has_attribute (n, (xmlChar *) "_name");
3717 xmlChar *b = node_has_attribute (nsrc, (xmlChar *) "_name");
3719 if (xmlStrEqual (a, b))
3721 match = 1;
3722 xmlUnlinkNode (nsrc);
3723 xmlUnlinkNode (n);
3724 xmlFreeNodeList (n);
3727 xmlFree (a);
3728 xmlFree (b);
3730 if (!match)
3732 xmlUnlinkNode (dup);
3733 xmlFreeNodeList (dup);
3736 else
3737 xmlUnlinkNode (dup);
3741 if (!ndst && dst)
3743 xmlChar *name = node_has_attribute (nsrc, (xmlChar *) "_name");
3745 if (nsrc->parent == xmlDocGetRootElement (client->doc)
3746 && !strcmp ((char *) name, *dst))
3748 xmlFree (name);
3749 rc = GPG_ERR_CONFLICT;
3750 goto fail;
3753 xmlFree (name);
3754 ndst = create_element_path (client, &dst, &rc, nsrc);
3757 if (!ndst)
3758 goto fail;
3760 update_element_mtime (nsrc->parent);
3761 xmlUnlinkNode (nsrc);
3762 ndst = xmlAddChildList (ndst, nsrc);
3764 if (!ndst)
3765 rc = GPG_ERR_ENOMEM;
3766 else
3767 update_element_mtime (ndst->parent);
3769 fail:
3770 if (req)
3771 strv_free (req);
3773 if (src)
3774 strv_free (src);
3776 if (dst)
3777 strv_free (dst);
3779 return rc;
3782 static gpg_error_t
3783 move_command (assuan_context_t ctx, char *line)
3785 struct client_s *client = assuan_get_pointer (ctx);
3786 gpg_error_t rc;
3787 struct argv_s *args[] = {
3788 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3789 NULL
3792 rc = parse_options (&line, args, client);
3793 if (rc)
3794 return send_error (ctx, rc);
3796 if (client->opts & OPT_INQUIRE)
3798 unsigned char *result;
3799 size_t len;
3801 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3802 if (rc)
3803 return send_error (ctx, rc);
3805 line = (char *) result;
3808 rc = do_move (ctx, line);
3810 if (client->opts & OPT_INQUIRE)
3811 xfree (line);
3813 return send_error (ctx, rc);
3816 static gpg_error_t
3817 ls_command (assuan_context_t ctx, char *line)
3819 gpg_error_t rc;
3820 char *tmp = str_asprintf ("%s/data", homedir);
3821 char *dir = expand_homedir (tmp);
3822 DIR *d = opendir (dir);
3824 rc = gpg_error_from_errno (errno);
3825 xfree (tmp);
3827 if (!d)
3829 xfree (dir);
3830 return send_error (ctx, rc);
3833 size_t len =
3834 offsetof (struct dirent, d_name) +pathconf (dir, _PC_NAME_MAX) + 1;
3835 struct dirent *p = xmalloc (len), *cur = NULL;
3836 char *list = NULL;
3838 xfree (dir);
3839 rc = 0;
3841 while (!readdir_r (d, p, &cur) && cur)
3843 if (cur->d_name[0] == '.' && cur->d_name[1] == '\0')
3844 continue;
3845 else if (cur->d_name[0] == '.' && cur->d_name[1] == '.'
3846 && cur->d_name[2] == '\0')
3847 continue;
3849 tmp = str_asprintf ("%s%s\n", list ? list : "", cur->d_name);
3851 if (!tmp)
3853 if (list)
3854 xfree (list);
3856 rc = GPG_ERR_ENOMEM;
3857 break;
3860 xfree (list);
3861 list = tmp;
3864 closedir (d);
3865 xfree (p);
3867 if (rc)
3868 return send_error (ctx, rc);
3870 if (!list)
3871 return send_error (ctx, GPG_ERR_NO_DATA);
3873 list[strlen (list) - 1] = 0;
3874 rc = xfer_data (ctx, list, strlen (list));
3875 xfree (list);
3876 return send_error (ctx, rc);
3879 static gpg_error_t
3880 bye_notify (assuan_context_t ctx, char *line)
3882 struct client_s *cl = assuan_get_pointer (ctx);
3884 #ifdef WITH_GNUTLS
3885 if (cl->thd->remote)
3887 int rc;
3891 struct timeval tv = { 0, 50000 };
3893 rc = gnutls_bye (cl->thd->tls->ses, GNUTLS_SHUT_RDWR);
3894 if (rc == GNUTLS_E_AGAIN)
3895 select (0, NULL, NULL, NULL, &tv);
3897 while (rc == GNUTLS_E_AGAIN);
3899 #endif
3901 /* This will let assuan_process_next() return. */
3902 fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK);
3903 cl->last_rc = 0; // BYE command result
3904 return 0;
3907 static gpg_error_t
3908 reset_notify (assuan_context_t ctx, char *line)
3910 struct client_s *client = assuan_get_pointer (ctx);
3912 if (client)
3913 cleanup_client (client);
3915 return 0;
3919 * This is called before every Assuan command.
3921 static gpg_error_t
3922 command_startup (assuan_context_t ctx, const char *name)
3924 struct client_s *client = assuan_get_pointer (ctx);
3925 gpg_error_t rc;
3926 struct command_table_s *cmd = NULL;
3928 log_write1 ("command='%s'", name);
3929 client->last_rc = client->opts = 0;
3931 for (int i = 0; command_table[i]; i++)
3933 if (!strcasecmp (name, command_table[i]->name))
3935 if (command_table[i]->ignore_startup)
3936 return 0;
3937 cmd = command_table[i];
3938 break;
3942 client->last_rc = rc = gpg_error (file_modified (client, cmd));
3943 return rc;
3947 * This is called after every Assuan command.
3949 static void
3950 command_finalize (assuan_context_t ctx, gpg_error_t rc)
3952 struct client_s *client = assuan_get_pointer (ctx);
3954 if (!(client->flags & FLAG_LOCK_CMD))
3955 unlock_file_mutex (client, 0);
3957 log_write1 (_("command completed: rc=%u"), client->last_rc);
3958 client->last_rc = gpg_error (GPG_ERR_UNKNOWN_COMMAND);
3959 #ifdef WITH_GNUTLS
3960 client->thd->buffer_timeout = client->thd->last_buffer_size = 0;
3961 #endif
3964 static gpg_error_t
3965 help_command (assuan_context_t ctx, char *line)
3967 gpg_error_t rc;
3968 int i;
3970 if (!line || !*line)
3972 char *tmp;
3973 char *help = str_dup (_("Usage: HELP [<COMMAND>]\n"
3974 "For commands that take an element path as an argument, each element is "
3975 "separated with an ASCII @key{TAB} character (ASCII 0x09)."
3976 "\n" "COMMANDS:"));
3978 for (i = 0; command_table[i]; i++)
3980 if (!command_table[i]->help)
3981 continue;
3983 tmp = str_asprintf ("%s %s", help, command_table[i]->name);
3984 xfree (help);
3985 help = tmp;
3988 tmp = strip_texi_and_wrap (help);
3989 xfree (help);
3990 rc = xfer_data (ctx, tmp, strlen (tmp));
3991 xfree (tmp);
3992 return send_error (ctx, rc);
3995 for (i = 0; command_table[i]; i++)
3997 if (!strcasecmp (line, command_table[i]->name))
3999 char *help, *tmp;
4001 if (!command_table[i]->help)
4002 break;
4004 help = strip_texi_and_wrap (command_table[i]->help);
4005 tmp = str_asprintf (_("Usage: %s"), help);
4006 xfree (help);
4007 rc = xfer_data (ctx, tmp, strlen (tmp));
4008 xfree (tmp);
4009 return send_error (ctx, rc);
4013 return send_error (ctx, GPG_ERR_INV_NAME);
4016 static void
4017 new_command (const char *name, int ignore, int unlock,
4018 gpg_error_t (*handler) (assuan_context_t, char *),
4019 const char *help)
4021 int i = 0;
4023 if (command_table)
4024 for (i = 0; command_table[i]; i++);
4026 command_table =
4027 xrealloc (command_table, (i + 2) * sizeof (struct command_table_s *));
4028 command_table[i] = xcalloc (1, sizeof (struct command_table_s));
4029 command_table[i]->name = name;
4030 command_table[i]->handler = handler;
4031 command_table[i]->ignore_startup = ignore;
4032 command_table[i]->unlock = unlock;
4033 command_table[i++]->help = help;
4034 command_table[i] = NULL;
4037 void
4038 deinit_commands ()
4040 int i;
4042 for (i = 0; command_table[i]; i++)
4043 xfree (command_table[i]);
4045 xfree (command_table);
4048 static int
4049 sort_commands (const void *arg1, const void *arg2)
4051 struct command_table_s *const *a = arg1;
4052 struct command_table_s *const *b = arg2;
4054 if (!*a || !*b)
4055 return 0;
4056 else if (*a && !*b)
4057 return 1;
4058 else if (!*a && *b)
4059 return -1;
4061 return strcmp ((*a)->name, (*b)->name);
4064 static gpg_error_t
4065 passwd_command (assuan_context_t ctx, char *line)
4067 struct client_s *client = assuan_get_pointer (ctx);
4068 gpg_error_t rc;
4069 struct argv_s *args[] = {
4070 &(struct argv_s) {"reset", OPTION_TYPE_NOARG, parse_opt_reset},
4071 &(struct argv_s) {"s2k-count", OPTION_TYPE_ARG, parse_opt_s2k_count},
4072 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG, parse_opt_no_passphrase},
4073 NULL
4076 if (client->flags & FLAG_NEW)
4077 return send_error (ctx, GPG_ERR_INV_STATE);
4079 client->crypto->save.s2k_count =
4080 config_get_ulong (client->filename, "s2k_count");
4081 rc = parse_options (&line, args, client);
4082 if (rc)
4083 return send_error (ctx, rc);
4085 if (!rc && client->opts & OPT_RESET)
4087 rc = cache_clear (client->md5file);
4088 if (!rc)
4089 send_status_all (STATUS_CACHE, NULL);
4092 if (!rc)
4094 if (!IS_PKI (client->crypto))
4096 struct crypto_s *crypto;
4098 xfree (client->crypto->filename);
4099 client->crypto->filename = str_dup (client->filename);
4100 rc = change_passwd (ctx, client->filename,
4101 client->flags & FLAG_NO_PINENTRY, &crypto,
4102 (client->opts & OPT_NO_PASSPHRASE));
4103 if (!rc)
4105 cleanup_crypto (&client->crypto);
4106 client->crypto = crypto;
4107 update_checksum (client);
4108 cleanup_crypto_stage1 (client->crypto);
4111 #ifdef WITH_AGENT
4112 else
4114 if (client->crypto->save.s2k_count)
4115 rc = send_to_agent (client->crypto->agent, NULL, NULL,
4116 "OPTION s2k-count=%lu",
4117 client->crypto->save.s2k_count);
4119 if (!rc)
4120 rc = agent_passwd (client->crypto);
4122 #endif
4125 return send_error (ctx, rc);
4128 static gpg_error_t
4129 parse_keygrip_opt_sign (void *data, void *value)
4131 struct client_s *client = data;
4133 (void) value;
4134 client->opts |= OPT_SIGN;
4135 return 0;
4138 static gpg_error_t
4139 keygrip_command (assuan_context_t ctx, char *line)
4141 struct client_s *client = assuan_get_pointer (ctx);
4142 gpg_error_t rc;
4143 struct crypto_s *crypto = NULL;
4144 struct argv_s *args[] = {
4145 &(struct argv_s) {"sign", OPTION_TYPE_NOARG, parse_keygrip_opt_sign},
4146 NULL
4149 if (!line || !*line)
4150 return send_error (ctx, GPG_ERR_SYNTAX);
4152 rc = parse_options (&line, args, client);
4153 if (rc)
4154 return send_error (ctx, rc);
4156 if (!valid_filename (line))
4157 return send_error (ctx, GPG_ERR_INV_VALUE);
4159 rc = init_client_crypto (&crypto);
4160 if (rc)
4161 return send_error (ctx, rc);
4163 rc = read_data_file (line, crypto);
4164 if (!rc)
4166 char *hexgrip = NULL;
4168 if (!IS_PKI (crypto))
4170 cleanup_crypto (&crypto);
4171 return send_error (ctx, GPG_ERR_NOT_SUPPORTED);
4174 if (client->opts & OPT_SIGN)
4176 if (valid_keygrip (crypto->sign_grip, sizeof (crypto->sign_grip)))
4177 hexgrip = bin2hex (crypto->sign_grip, sizeof (crypto->sign_grip));
4180 if (!hexgrip)
4181 hexgrip = bin2hex (crypto->grip, sizeof (crypto->grip));
4183 if (!hexgrip)
4184 rc = GPG_ERR_ENOMEM;
4185 else
4186 rc = xfer_data (ctx, hexgrip, strlen (hexgrip));
4188 xfree (hexgrip);
4191 UPDATE_AGENT_CTX (client, crypto);
4192 cleanup_crypto (&crypto);
4193 return send_error (ctx, rc);
4196 static gpg_error_t
4197 parse_opt_data (void *data, void *value)
4199 struct client_s *client = data;
4201 (void) value;
4202 client->opts |= OPT_DATA;
4203 return 0;
4206 static gpg_error_t
4207 getinfo_command (assuan_context_t ctx, char *line)
4209 struct client_s *client = assuan_get_pointer (ctx);
4210 gpg_error_t rc;
4211 char buf[ASSUAN_LINELENGTH];
4212 struct argv_s *args[] = {
4213 &(struct argv_s) {"data", OPTION_TYPE_NOARG, parse_opt_data},
4214 NULL
4217 rc = parse_options (&line, args, client);
4218 if (rc)
4219 return send_error (ctx, rc);
4221 if (!strcasecmp (line, "clients"))
4223 if (client->opts & OPT_DATA)
4225 MUTEX_LOCK (&cn_mutex);
4226 snprintf (buf, sizeof (buf), "%i", slist_length (cn_thread_list));
4227 MUTEX_UNLOCK (&cn_mutex);
4228 rc = xfer_data (ctx, buf, strlen (buf));
4230 else
4231 rc = send_status (ctx, STATUS_CLIENTS, NULL);
4233 else if (!strcasecmp (line, "cache"))
4235 if (client->opts & OPT_DATA)
4237 snprintf (buf, sizeof (buf), "%u", cache_file_count ());
4238 rc = xfer_data (ctx, buf, strlen (buf));
4240 else
4241 rc = send_status (ctx, STATUS_CACHE, NULL);
4243 else if (!strcasecmp (line, "pid"))
4245 char buf[32];
4246 pid_t pid = getpid ();
4248 snprintf (buf, sizeof (buf), "%i", pid);
4249 rc = xfer_data (ctx, buf, strlen (buf));
4251 else if (!strcasecmp (line, "version"))
4253 char *buf = str_asprintf ("0x%06x %s%s", VERSION_HEX,
4254 #ifdef WITH_LIBACL
4255 "ACL "
4256 #endif
4257 #ifdef WITH_GNUTLS
4258 "GNUTLS "
4259 #endif
4260 #ifdef WITH_QUALITY
4261 "QUALITY "
4262 #endif
4263 "", use_agent ? "AGENT" : "");
4264 rc = xfer_data (ctx, buf, strlen (buf));
4265 xfree (buf);
4267 else if (!strcasecmp (line, "last_error"))
4269 if (client->last_error)
4270 rc = xfer_data (ctx, client->last_error, strlen (client->last_error));
4271 else
4272 rc = GPG_ERR_NO_DATA;
4274 else
4275 rc = gpg_error (GPG_ERR_SYNTAX);
4277 return send_error (ctx, rc);
4280 #ifdef WITH_AGENT
4281 static gpg_error_t
4282 send_data_cb (void *user, const void *buf, size_t len)
4284 assuan_context_t ctx = user;
4286 return assuan_send_data (ctx, buf, len);
4289 static gpg_error_t
4290 send_status_cb (void *user, const char *line)
4292 assuan_context_t ctx = user;
4293 char keyword[200], *k;
4294 const char *p;
4296 for (p = line, k = keyword; *p; p++)
4298 if (isspace (*p))
4299 break;
4301 *k++ = *p;
4304 *k = 0;
4305 if (*p == '#')
4306 p++;
4308 while (isspace (*p))
4309 p++;
4311 return assuan_write_status (ctx, keyword, *p ? p : NULL);
4313 #endif
4315 static gpg_error_t
4316 agent_command (assuan_context_t ctx, char *line)
4318 gpg_error_t rc = 0;
4320 if (!use_agent)
4321 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
4323 #ifdef WITH_AGENT
4324 struct client_s *client = assuan_get_pointer (ctx);
4326 if (!line || !*line)
4327 return send_error (ctx, GPG_ERR_SYNTAX);
4329 assuan_set_flag (client->crypto->agent->ctx, ASSUAN_CONVEY_COMMENTS, 1);
4330 rc = assuan_transact (client->crypto->agent->ctx, line, send_data_cb,
4331 client->ctx, agent_loopback_cb, client->crypto,
4332 send_status_cb, client->ctx);
4333 if (gpg_err_code (rc) == GPG_ERR_ASS_CANCELED)
4335 char *line;
4336 size_t len;
4338 rc = assuan_write_line (client->crypto->agent->ctx, "CAN");
4339 if (!rc)
4341 rc = assuan_read_line (client->crypto->agent->ctx, &line, &len);
4342 if (!rc)
4343 rc = gpg_error (GPG_ERR_ASS_CANCELED);
4347 assuan_set_flag (client->crypto->agent->ctx, ASSUAN_CONVEY_COMMENTS, 0);
4348 #endif
4349 return send_error (ctx, rc);
4352 void
4353 init_commands ()
4355 /* !BEGIN-HELP-TEXT!
4357 * This comment is used as a marker to generate the offline documentation
4358 * found in doc/pwmd.info. The indentation needs to be kept for the awk
4359 * script to determine where commands begin and end.
4361 new_command("HELP", 1, 1, help_command, _(
4362 "HELP [<COMMAND>]\n"
4363 "Show available commands or command specific help text."
4366 new_command("AGENT", 1, 1, agent_command, _(
4367 "AGENT <command>\n"
4368 "Send a @command{gpg-agent} protocol @var{command} directly to the "
4369 "@command{gpg-agent}."
4372 new_command("GETINFO", 1, 1, getinfo_command, _(
4373 "GETINFO [--data] CACHE | CLIENTS | PID | LAST_ERROR | VERSION\n"
4374 "Get server and other information: @var{cache} returns the number of cached "
4375 "documents via a status message. @var{clients} returns the number of "
4376 "connected clients via a status message. @var{pid} returns the process ID "
4377 "number of the server via a data response. @var{VERSION} returns the server "
4378 "version number and compile-time features with a data response with each "
4379 "being space delimited. @var{LAST_ERROR} returns a detailed description of "
4380 "the last failed command when available. @xref{Status Messages}. "
4381 "\n"
4382 "When the @option{--data} option is specified then the result will be sent "
4383 "via a data response rather than a status message."
4386 new_command("PASSWD", 0, 0, passwd_command, _(
4387 "PASSWD [--reset] [--s2k-count=N] [--no-passphrase]\n"
4388 "Changes the passphrase of the secret key required to open the current "
4389 "file or the passphrase of a symmetrically encrypted data file. When the "
4390 "@option{--reset} option is passed then the cache entry for the current "
4391 "file will be reset and the passphrase, if any, will be required during the "
4392 "next @code{OPEN}. @xref{OPEN}."
4393 "\n"
4394 "The @option{--s2k-count} option sets number of hash iterations for a "
4395 "passphrase and must be either @code{0} to use the calibrated count of the "
4396 "machine (the default), or a value greater than or equal to @code{65536}. "
4397 "@xref{SAVE}. This option has no effect for symmetrically encrypted data "
4398 "files."
4399 "\n"
4400 "The @option{--no-passphrase} option will prevent requiring a passphrase for "
4401 "the data file, although a passphrase may be required when changing it."
4404 new_command("KEYGRIP", 1, 1, keygrip_command, _(
4405 "KEYGRIP [--sign] <filename>\n"
4406 "Returns the hex encoded keygrip of the specified @var{filename} with a "
4407 "data response."
4408 "\n"
4409 "When the @option{--sign} option is specified then the key used for signing "
4410 "of the specified @var{filename} will be returned."
4411 "\n"
4412 "For symmetrically encrypted data files this command returns the error "
4413 "GPG_ERR_NOT_SUPPORTED."
4416 new_command("OPEN", 1, 1, open_command, _(
4417 "OPEN [--lock] <filename> [<passphrase>]\n"
4418 "Opens @var{filename} using @var{passphrase}. When the filename is not "
4419 "found on the file-system then a new document will be created. If the file "
4420 "is found, it is looked for in the file cache. If cached and no "
4421 "@var{passphrase} was specified then the cached document is opened. When not "
4422 "cached, @cite{pinentry(1)} will be used to retrieve the passphrase to use "
4423 "for decryption unless @option{disable-pinentry} (@pxref{OPTION}) was "
4424 "specified."
4425 "\n"
4426 "When the @option{--lock} option is passed then the file mutex will be "
4427 "locked as if the @code{LOCK} command (@pxref{LOCK}) had been sent after the "
4428 "file has been opened."
4431 new_command("SAVE", 0, 0, save_command, _(
4432 "SAVE [--no-passphrase] [--reset] [--no-agent] [--s2k-count=N] [--cipher=<algo>] [--cipher-iterations=N] [--inquire-keyparam] [--keygrip=hexstring] [--sign-keygrip=hexstring]\n"
4433 "Writes the @abbr{XML} document to disk. The file written to is the file that "
4434 "was opened using the @code{OPEN} command (@pxref{OPEN}). If the file is a "
4435 "new one or the option @option{--inquire-keyparam} was passed, then a new "
4436 "keypair will be generated and a pinentry will be used to prompt for the "
4437 "passphrase to encrypt with unless the @option{--no-passphrase} option was "
4438 "passed in which case the data file will not be passphrase protected. "
4439 "\n"
4440 "The @option{--no-agent} option disables use of @command{gpg-agent} for "
4441 "passphrase retrieval and caching of new files when @command{gpg-agent} "
4442 "use is enabled. The datafile will be symmetrically encrypted and will not "
4443 "use or generate any keypair."
4444 "\n"
4445 "The @option{--reset} option will clear the cache entry for the current file "
4446 "and require a passphrase, if needed, before saving."
4447 "\n"
4448 "The @option{--cipher} option can be used to encrypt the @abbr{XML} data to "
4449 "an alternate cipher. The default is @code{aes256}. See the Configuration "
4450 "(@pxref{Configuration}) for available ciphers."
4451 "\n"
4452 "The @option{--cipher-iterations} option specifies the number of times to "
4453 "encrypt the XML data. The default is 0 although 1 iteration is still done."
4454 "\n"
4455 "The @option{--inquire-keyparam} option will send a server @emph{INQUIRE} to "
4456 "the client to obtain the key paramaters to use when generating a new "
4457 "keypair. The inquired data is expected to be an S-expression. If not "
4458 "specified then an @samp{RSA} key of @samp{2048} bits will be generated "
4459 "unless otherwise set in the configuration file (@pxref{Configuration}). Note "
4460 "that when this option is specified a new keypair will be generated "
4461 "reguardless if the file is a new one and that if the data file is protected "
4462 "the passphrase to open it will be required before generating the new keypair."
4463 "\n"
4464 "You can encrypt the data file to a public key other than the one that it "
4465 "was originally encrypted with by passing the @option{--keygrip} option with "
4466 "the hex encoded keygrip of the public key as its argument. The keygrip may "
4467 "be of any key that @command{gpg-agent} knows about. The "
4468 "@option{--sign-keygrip} option may also be used to sign with an alternate "
4469 "secret key. This option may be needed when using a smartcard. This option "
4470 "has no effect with symmetrically encrypted data files."
4471 "\n"
4472 "The @option{--s2k-count} option sets number of hash iterations for a "
4473 "passphrase. A value less-than @code{65536} will use the machine calibrated "
4474 "value and is the default. This setting only affects new files. To change "
4475 "the setting use the @code{PASSWD} command (@pxref{PASSWD}). This option "
4476 "has no effect with symmetrically encrypted data files."
4479 new_command("ISCACHED", 1, 0, iscached_command, _(
4480 "ISCACHED [--lock] <filename>\n"
4481 "An @emph{OK} response is returned if the specified @var{filename} is found "
4482 "in the file cache. If not found in the cache but exists on the filesystem "
4483 "then @var{GPG_ERR_NO_DATA} is returned. Otherwise a filesystem error is "
4484 "returned."
4485 "\n"
4486 "The @option{lock} option will lock the file mutex of @var{filename} when the "
4487 "file exists; it does not need to be opened nor cached."
4490 new_command("CLEARCACHE", 1, 1, clearcache_command, _(
4491 "CLEARCACHE [<filename>]\n"
4492 "Clears a file cache entry for all or the specified @var{filename}."
4495 new_command("CACHETIMEOUT", 1, 1, cachetimeout_command, _(
4496 "CACHETIMEOUT <filename> <seconds>\n"
4497 "The time in @var{seconds} until @var{filename} will be removed from the "
4498 "cache. @code{-1} will keep the cache entry forever, @code{0} will require "
4499 "the passphrase for each @code{OPEN} or @code{SAVE} command (@pxref{OPEN}, "
4500 "@pxref{SAVE}). @xref{Configuration}, and the @code{cache_timeout} "
4501 "parameter."
4504 new_command("LIST", 0, 1, list_command, _(
4505 "LIST [--inquire] [--no-recurse] [--verbose] [--with-target] [--all] [[!]element[<TAB>[!]child[..]]]\n"
4506 "If no element path is given then a newline separated list of root elements "
4507 "is returned with a data response. If given, then all reachable elements "
4508 "of the specified element path are returned unless the @option{--no-recurse} "
4509 "option is specified. If specified, only the child elements of the element "
4510 "path are returned without recursing into grandchildren. Each resulting "
4511 "element is prefixed with the literal @code{!} character when the element "
4512 "contains no @code{target} attribute. @xref{Target Attribute}, for details."
4513 "\n"
4514 "When the @option{--verbose} option is passed then each element path "
4515 "returned will have zero or more flags appened to it. These flags are "
4516 "delimited from the element path by a single space character. A flag itself "
4517 "is a single character. Flag @code{+} indicates that there are child nodes of "
4518 "the current element path. Flag @code{E} indicates that an element of an "
4519 "element path contained in a @var{target} attribute could not be found. Flag "
4520 "@code{O} indicates that a @var{target} attribute recursion limit was reached "
4521 "(@pxref{Configuration}). Flag @code{T} will append the resolved element path "
4522 "of the @var{target} attribute contained in the current element (see below)."
4523 "\n"
4524 "The @option{--with-target} option implies @option{--verbose} and will append "
4525 "an additional flag @code{T} followed by a single space then an element path. "
4526 "The appended element path is the resolved path (@pxref{REALPATH}) of the "
4527 "current element when it contains a @var{target} attribute. When no "
4528 "@var{target} attribute is found then no flag will be appended."
4529 "\n"
4530 "The @option{--no-recurse} option limits the amount of data returned to only "
4531 "the listing of children of the specified element path and not any "
4532 "grandchildren."
4533 "\n"
4534 "The @option{--all} option lists the entire element tree for each root "
4535 "element. This option also implies option @option{--verbose}."
4536 "\n"
4537 "When the @option{--inquire} option is passed then all remaining non-option "
4538 "arguments are retrieved via a server @emph{INQUIRE}."
4541 new_command("REALPATH", 0, 1, realpath_command, _(
4542 "REALPATH [--inquire] [!]element[<TAB>[!]child[..]]\n"
4543 "Resolves all @code{target} attributes of the specified element path and "
4544 "returns the result with a data response. @xref{Target Attribute}, for details."
4545 "\n"
4546 "When the @option{--inquire} option is passed then all remaining non-option "
4547 "arguments are retrieved via a server @emph{INQUIRE}."
4550 new_command("STORE", 0, 1, store_command, _(
4551 "STORE [!]element[<TAB>[!]child[..]]<TAB>[content]\n"
4552 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
4553 "\n"
4554 "Creates a new element path or modifies the @var{content} of an existing "
4555 "element. If only a single element is specified then a new root element is "
4556 "created. Otherwise, elements are @key{TAB} delimited and the content will be "
4557 "set to the final @key{TAB} delimited element. If no @var{content} is "
4558 "specified after the final @key{TAB}, then the content of the element will "
4559 "be removed, or empty when creating a new element."
4560 "\n"
4561 "The only restriction of an element name is that it not contain whitespace "
4562 "or begin with the literal element character @code{!} unless specifying a "
4563 "literal element (@pxref{Target Attribute}). There is no whitespace between "
4564 "the @key{TAB} delimited elements. It is recommended that the content of an "
4565 "element be base64 encoded when it contains control or @key{TAB} characters "
4566 "to prevent @abbr{XML} parsing and @command{pwmd} syntax errors."
4569 new_command("RENAME", 0, 1, rename_command, _(
4570 "RENAME [--inquire] [!]element[<TAB>[!]child[..]] <value>\n"
4571 "Renames the specified @var{element} to the new @var{value}. If an element of "
4572 "the same name as the @var{value} already exists it will be overwritten."
4573 "\n"
4574 "When the @option{--inquire} option is passed then all remaining non-option "
4575 "arguments are retrieved via a server @emph{INQUIRE}."
4578 new_command("COPY", 0, 1, copy_command, _(
4579 "COPY [--inquire] [!]source[<TAB>[!]child[..]] [!]dest[<TAB>[!]child[..]]\n"
4580 "Copies the entire element tree starting from the child node of the source "
4581 "element, to the destination element path. If the destination element path "
4582 "does not exist then it will be created; otherwise it is overwritten."
4583 "\n"
4584 "Note that attributes from the source element are merged into the "
4585 "destination element when the destination element path exists. When an "
4586 "attribute of the same name exists in both the source and destination "
4587 "elements then the destination attribute will be updated to the source "
4588 "attribute value."
4589 "\n"
4590 "When the @option{--inquire} option is passed then all remaining non-option "
4591 "arguments are retrieved via a server @emph{INQUIRE}."
4594 new_command("MOVE", 0, 1, move_command, _(
4595 "MOVE [--inquire] [!]source[<TAB>[!]child[..]] [[!]dest[<TAB>[!]child[..]]]\n"
4596 "Moves the source element path to the destination element path. If the "
4597 "destination is not specified then it will be moved to the root node of the "
4598 "document. If the destination is specified and exists then it will be "
4599 "overwritten; otherwise non-existing elements of the destination element "
4600 "path will be created."
4601 "\n"
4602 "When the @option{--inquire} option is passed then all remaining non-option "
4603 "arguments are retrieved via a server @emph{INQUIRE}."
4606 new_command("DELETE", 0, 1, delete_command, _(
4607 "DELETE [--inquire] [!]element[<TAB>[!]child[..]]\n"
4608 "Removes the specified element path and all of its children. This may break "
4609 "an element with a @code{target} attribute (@pxref{Target Attribute}) that "
4610 "refers to this element or any of its children."
4611 "\n"
4612 "When the @option{--inquire} option is passed then all remaining non-option "
4613 "arguments are retrieved via a server @emph{INQUIRE}."
4616 new_command("GET", 0, 1, get_command, _(
4617 "GET [--inquire] [!]element[<TAB>[!]child[..]]\n"
4618 "Retrieves the content of the specified element. The content is returned "
4619 "with a data response."
4620 "\n"
4621 "When the @option{--inquire} option is passed then all remaining non-option "
4622 "arguments are retrieved via a server @emph{INQUIRE}."
4625 new_command("ATTR", 0, 1, attr_command, _(
4626 "ATTR [--inquire] SET|GET|DELETE|LIST [<attribute>] [!]element[<TAB>[!]child[..]] ..\n"
4627 "@table @asis\n"
4628 "@item ATTR SET attribute [!]element[<TAB>[!]child[..]] [value]\n"
4629 "\n"
4630 " Stores or updates an @var{attribute} name and optional @var{value} of an "
4631 "element. When no @var{value} is specified any existing value will be removed."
4632 "\n"
4633 "@item ATTR DELETE attribute [!]element[<TAB>[!]child[..]]\n"
4634 "\n"
4635 " Removes an @var{attribute} from an element."
4636 "\n"
4637 "@item ATTR LIST [!]element[<TAB>[!]child[..]]\n"
4638 "\n"
4639 " Retrieves a newline separated list of attributes names and values "
4640 "from the specified element. Each attribute name and value is space delimited."
4641 "\n"
4642 "@item ATTR GET attribute [!]element[<TAB>[!]child[..]]\n"
4643 "\n"
4644 " Retrieves the value of an @var{attribute} from an element."
4645 "@end table\n"
4646 "\n"
4647 "The @code{_name} attribute (case sensitive) cannot be removed nor modified. "
4648 "Use the @code{DELETE} (@pxref{DELETE}) or @code{RENAME} (@pxref{RENAME}) "
4649 "commands instead."
4650 "\n"
4651 "The @code{_mtime} attribute is updated each time an element is modified by "
4652 "either storing content, editing attributes or by deleting a child element. "
4653 "The @code{_ctime} attribute is created for each new element in an element "
4654 "path."
4655 "\n"
4656 "When the @option{--inquire} option is passed then all remaining non-option "
4657 "arguments are retrieved via a server @emph{INQUIRE}."
4658 "\n"
4659 "@xref{Target Attribute}, for details about this special attribute."
4662 new_command("XPATH", 0, 1, xpath_command, _(
4663 "XPATH [--inquire] <expression>[<TAB>[value]]\n"
4664 "Evaluates an XPath @var{expression}. If no @var{value} argument is "
4665 "specified it is assumed the expression is a request to return a result. "
4666 "Otherwise, the result is set to the @var{value} argument and the document is "
4667 "updated. If there is no @var{value} after the @key{TAB} character, the value "
4668 "is assumed to be empty and the document is updated. For example:"
4669 "@sp 1\n"
4670 "@example\n"
4671 "XPATH //element[@@_name='password']@key{TAB}\n"
4672 "@end example\n"
4673 "@sp 1"
4674 "would clear the content of all @code{password} elements in the data file "
4675 "while leaving off the trailing @key{TAB} would return all @code{password} "
4676 "elements in @abbr{XML} format."
4677 "\n"
4678 "When the @option{--inquire} option is passed then all remaining non-option "
4679 "arguments are retrieved via a server @emph{INQUIRE}."
4680 "\n"
4681 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
4682 "expression syntax."
4685 new_command("XPATHATTR", 0, 1, xpathattr_command, _(
4686 "XPATHATTR [--inquire] SET|DELETE <name> <expression>[<TAB>[<value>]]\n"
4687 "Like the @code{XPATH} command (@pxref{XPATH}) but operates on element "
4688 "attributes and does not return a result. For the @var{SET} operation the "
4689 "@var{value} is optional but the field is required. If not specified then "
4690 "the attribute value will be empty. For example:"
4691 "@sp 1"
4692 "@example\n"
4693 "XPATHATTR SET password //element[@@_name='password']@key{TAB}\n"
4694 "@end example\n"
4695 "@sp 1"
4696 "would create an @code{password} attribute for each @code{password} element "
4697 "found in the document. The attribute value will be empty but still exist."
4698 "\n"
4699 "When the @option{--inquire} option is passed then all remaining non-option "
4700 "arguments are retrieved via a server @emph{INQUIRE}."
4701 "\n"
4702 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
4703 "expression syntax."
4706 new_command("IMPORT", 0, 1, import_command, _(
4707 "IMPORT [--root [!]element[<TAB>[!]child[..]]] <content>\n"
4708 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
4709 "\n"
4710 "Like the @code{STORE} command (@pxref{STORE}), but the @var{content} "
4711 "argument is raw @abbr{XML} data. The content is created as a child of "
4712 "the element path specified with the @option{--root} option or at the "
4713 "document root when not specified. Existing elements of the same name will "
4714 "be overwritten."
4715 "\n"
4716 "The content must begin with an @abbr{XML} element node. @xref{Introduction}, "
4717 "for details."
4720 new_command("DUMP", 0, 1, dump_command, _(
4721 "DUMP\n"
4722 "Shows the in memory @abbr{XML} document with indenting. @xref{XPATH}, for "
4723 "dumping a specific node."
4726 new_command("LOCK", 0, 0, lock_command, _(
4727 "LOCK\n"
4728 "Locks the mutex associated with the opened file. This prevents other clients "
4729 "from sending commands to the same opened file until the client "
4730 "that sent this command either disconnects or sends the @code{UNLOCK} "
4731 "command. @xref{UNLOCK}."
4734 new_command("UNLOCK", 1, 0, unlock_command, _(
4735 "UNLOCK\n"
4736 "Unlocks the file mutex which was locked with the @code{LOCK} command or "
4737 "a commands' @option{--lock} option (@pxref{LOCK}, @pxref{OPEN}, "
4738 "@pxref{ISCACHED})."
4741 new_command("GETCONFIG", 1, 1, getconfig_command, _(
4742 "GETCONFIG [filename] <parameter>\n"
4743 "Returns the value of a @command{pwmd} configuration @var{parameter} with a "
4744 "data response. If no file has been opened then the value for @var{filename} "
4745 "or the default from the @samp{global} section will be returned. If a file "
4746 "has been opened and no @var{filename} is specified, a value previously "
4747 "set with the @code{OPTION} command (@pxref{OPTION}) will be returned."
4750 new_command("OPTION", 1, 1, option_command, _(
4751 "OPTION <NAME>=<VALUE>\n"
4752 "Sets a client option @var{name} to @var{value}. The value for an option is "
4753 "kept for the duration of the connection."
4754 "\n"
4755 "@table @asis\n"
4756 "@item DISABLE-PINENTRY\n"
4757 "Disable use of @command{pinentry} for passphrase retrieval. When set, a "
4758 "server inquire is sent to the client to obtain the passphrase. This option "
4759 "may be set as needed before the @pxref{OPEN}, @pxref{PASSWD}, and "
4760 "@pxref{SAVE} commands."
4761 "\n"
4762 "@item PINENTRY-TIMEOUT\n"
4763 "Sets the number of seconds before a pinentry prompt will return an error "
4764 "while waiting for user input."
4765 "\n"
4766 "@item TTYNAME\n"
4767 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4768 "\n"
4769 "@item TTYTYPE\n"
4770 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4771 "\n"
4772 "@item DISPLAY\n"
4773 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4774 "\n"
4775 "@item PINENTRY-DESC\n"
4776 "Sets the description string of the @command{gpg-agent} and @command{pinentry} dialog."
4777 "\n"
4778 "@item PINENTRY-TITLE\n"
4779 "Sets the title string of the @command{gpg-agent} and @command{pinentry} dialog."
4780 "\n"
4781 "@item PINENTRY-PROMPT\n"
4782 "Sets the prompt string of the @command{gpg-agent} and @command{pinentry} dialog."
4783 "\n"
4784 "@item LC-CTYPE\n"
4785 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4786 "\n"
4787 "@item LC-MESSAGES\n"
4788 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4789 "\n"
4790 "@item NAME\n"
4791 "Associates the thread ID of the connection with the specified textual "
4792 "representation. Useful for debugging log messages."
4793 "\n"
4794 "@item LOCK-TIMEOUT\n"
4795 "When not @code{0}, the duration in tenths of a second to wait for the file "
4796 "mutex which has been locked by another thread to be released before returning "
4797 "an error. When @code{-1}, then an error will be returned immediately."
4798 "\n"
4799 "@item LOG-LEVEL\n"
4800 "An integer specifiying the logging level."
4801 "@end table\n"
4804 new_command("LS", 1, 1, ls_command, _(
4805 "LS\n"
4806 "Lists the available data files stored in the data directory "
4807 "(@file{~/.pwmd/data}). The result is a newline separated list of filenames."
4810 new_command("RESET", 1, 1, NULL, _(
4811 "RESET\n"
4812 "Closes the currently opened file but keeps any previously set client options."
4815 new_command("NOP", 1, 1, NULL, _(
4816 "NOP\n"
4817 "Does nothing. Always returns successfully."
4820 /* !END-HELP-TEXT! */
4821 new_command ("CANCEL", 1, 1, NULL, NULL);
4822 new_command ("END", 1, 1, NULL, NULL);
4823 new_command ("BYE", 1, 1, NULL, NULL);
4825 int i;
4826 for (i = 0; command_table[i]; i++);
4827 qsort (command_table, i - 1, sizeof (struct command_table_s *),
4828 sort_commands);
4831 gpg_error_t
4832 register_commands (assuan_context_t ctx)
4834 int i = 0, rc;
4836 for (; command_table[i]; i++)
4838 if (!command_table[i]->handler)
4839 continue;
4841 rc = assuan_register_command (ctx, command_table[i]->name,
4842 command_table[i]->handler,
4843 command_table[i]->help);
4844 if (rc)
4845 return rc;
4848 rc = assuan_register_bye_notify (ctx, bye_notify);
4849 if (rc)
4850 return rc;
4852 rc = assuan_register_reset_notify (ctx, reset_notify);
4853 if (rc)
4854 return rc;
4856 rc = assuan_register_pre_cmd_notify (ctx, command_startup);
4857 if (rc)
4858 return rc;
4860 return assuan_register_post_cmd_notify (ctx, command_finalize);