Let the CLEARCACHE and CACHETIMEOUT commands make use of 'allowed'.
[pwmd.git] / src / commands.c
bloba5027da718a358e28571d6d04c2e0170ffd7aef8
1 /*
2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013
3 Ben Kibbey <bjk@luxsci.net>
5 This file is part of pwmd.
7 Pwmd is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 2 of the License, or
10 (at your option) any later version.
12 Pwmd is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
20 #ifdef HAVE_CONFIG_H
21 #include <config.h>
22 #endif
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <unistd.h>
27 #include <err.h>
28 #include <errno.h>
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <fcntl.h>
32 #include <ctype.h>
33 #include <dirent.h>
34 #include <pthread.h>
35 #include <stdint.h>
37 #ifdef WITH_LIBACL
38 #include <sys/acl.h>
39 #endif
41 #include "pwmd-error.h"
42 #include <gcrypt.h>
44 #include "mem.h"
45 #include "xml.h"
46 #include "util-misc.h"
47 #include "common.h"
48 #include "rcfile.h"
49 #include "cache.h"
50 #include "commands.h"
51 #include "mutex.h"
52 #include "crypto.h"
53 #include "pinentry.h"
55 /* Flags needed to be retained for a client across commands. */
56 #define FLAG_NEW 0x0001
57 #define FLAG_HAS_LOCK 0x0002
58 #define FLAG_LOCK_CMD 0x0004
59 #define FLAG_NO_PINENTRY 0x0008
60 #define FLAG_OPEN 0x0010
61 #define FLAG_KEEP_LOCK 0x0020
63 /* These are command option flags. */
64 #define OPT_INQUIRE 0x0001
65 #define OPT_NO_PASSPHRASE 0x0002
66 #define OPT_RESET 0x0004
67 #define OPT_LIST_RECURSE 0x0008
68 #define OPT_LIST_VERBOSE 0x0010
69 #define OPT_LOCK 0x0020
70 #define OPT_LOCK_ON_OPEN 0x0040
71 #define OPT_SIGN 0x0080
72 #define OPT_LIST_ALL 0x0100
73 #define OPT_LIST_WITH_TARGET 0x0200
74 #define OPT_DATA 0x0400
75 #define OPT_NO_AGENT 0x0800
77 #ifdef WITH_AGENT
78 /* The GETCONFIG command, for example, may fail because pwmd lost the
79 * gpg-agent connection. Update the recovered agent ctx. */
80 #define UPDATE_AGENT_CTX(client, crypto) do { \
81 if (crypto && crypto->agent && crypto->agent->did_restart \
82 && client->crypto && client->crypto->agent \
83 && client->crypto->agent->ctx && \
84 crypto->agent->ctx != client->crypto->agent->ctx) \
85 { \
86 client->crypto->agent->ctx = crypto->agent->ctx; \
87 crypto->agent->ctx = NULL; \
88 } \
89 } while (0)
90 #else
91 #define UPDATE_AGENT_CTX(client, crypto)
92 #endif
94 struct command_table_s
96 const char *name;
97 gpg_error_t (*handler) (assuan_context_t, char *line);
98 const char *help;
99 int ignore_startup;
100 int unlock; // unlock the file mutex after validating the checksum
103 static struct command_table_s **command_table;
105 static gpg_error_t do_lock (struct client_s *client, int add);
106 static gpg_error_t validate_checksum (struct client_s *,
107 struct cache_data_s *);
108 static gpg_error_t update_checksum (struct client_s *client);
110 static gpg_error_t
111 unlock_file_mutex (struct client_s *client, int remove)
113 gpg_error_t rc = 0;
115 // OPEN: keep the lock for the same file being reopened.
116 if (client->flags & FLAG_KEEP_LOCK && client->flags & FLAG_HAS_LOCK)
117 return 0;
119 if (!(client->flags & FLAG_HAS_LOCK))
120 return GPG_ERR_NOT_LOCKED;
122 rc = cache_unlock_mutex (client->md5file, remove);
123 if (rc)
124 rc = GPG_ERR_INV_STATE;
125 else
126 client->flags &= ~(FLAG_HAS_LOCK | FLAG_LOCK_CMD);
128 return rc;
131 static gpg_error_t
132 lock_file_mutex (struct client_s *client, int add)
134 gpg_error_t rc = 0;
135 int timeout = config_get_integer (client->filename, "cache_timeout");
137 if (client->flags & FLAG_HAS_LOCK)
138 return 0;
140 rc = cache_lock_mutex (client->ctx, client->md5file,
141 client->lock_timeout, add, timeout);
142 if (!rc)
143 client->flags |= FLAG_HAS_LOCK;
145 return rc;
148 static gpg_error_t
149 file_modified (struct client_s *client, struct command_table_s *cmd)
151 gpg_error_t rc = 0;
153 if (!(client->flags & FLAG_OPEN))
154 return GPG_ERR_INV_STATE;
156 rc = lock_file_mutex (client, 0);
157 if (!rc || rc == GPG_ERR_NO_DATA)
159 rc = validate_checksum (client, NULL);
160 if (gpg_err_code (rc) == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
161 rc = 0;
162 else if (rc)
163 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
166 if ((cmd->unlock && !(client->flags & FLAG_HAS_LOCK)) || rc)
167 unlock_file_mutex (client, 0);
169 return rc;
172 static gpg_error_t
173 parse_xml (assuan_context_t ctx, int new)
175 struct client_s *client = assuan_get_pointer (ctx);
176 int cached = client->doc != NULL;
178 if (new)
180 client->doc = new_document ();
181 if (client->doc)
183 xmlChar *result;
184 int len;
186 xmlDocDumpFormatMemory (client->doc, &result, &len, 0);
187 client->crypto->plaintext = result;
188 client->crypto->plaintext_len = len;
189 if (!client->crypto->plaintext)
191 xmlFreeDoc (client->doc);
192 client->doc = NULL;
196 else if (!cached)
197 client->doc = parse_doc ((char *) client->crypto->plaintext,
198 client->crypto->plaintext_len);
200 return !client->doc ? GPG_ERR_ENOMEM : 0;
203 static void
204 free_client (struct client_s *client)
206 if (client->doc)
207 xmlFreeDoc (client->doc);
209 xfree (client->crc);
210 xfree (client->filename);
211 xfree (client->last_error);
213 if (client->crypto)
215 cleanup_crypto_stage2 (client->crypto);
216 if (client->crypto->pkey_sexp)
217 gcry_sexp_release (client->crypto->pkey_sexp);
219 client->crypto->pkey_sexp = NULL;
220 memset (client->crypto->sign_grip, 0,
221 sizeof (client->crypto->sign_grip));
222 memset (client->crypto->grip, 0, sizeof(client->crypto->grip));
225 if (client->xml_error)
226 xmlResetError (client->xml_error);
229 void
230 cleanup_client (struct client_s *client)
232 assuan_context_t ctx = client->ctx;
233 struct client_thread_s *thd = client->thd;
234 struct crypto_s *crypto = client->crypto;
235 long lock_timeout = client->lock_timeout;
236 int no_pinentry = (client->flags & FLAG_NO_PINENTRY);
237 struct pinentry_option_s pin_opts;
238 #ifdef WITH_AGENT
239 struct pinentry_option_s agent_pin_opts;
241 if (crypto && crypto->agent)
242 memcpy (&agent_pin_opts, &crypto->agent->pinentry_opts,
243 sizeof(struct pinentry_option_s));
244 #endif
246 memcpy (&pin_opts, &client->pinentry_opts, sizeof(struct pinentry_option_s));
247 unlock_file_mutex (client, client->flags & FLAG_NEW);
248 free_client (client);
249 memset (client, 0, sizeof (struct client_s));
250 client->crypto = crypto;
251 client->ctx = ctx;
252 client->thd = thd;
253 client->lock_timeout = lock_timeout;
254 memcpy (&client->pinentry_opts, &pin_opts, sizeof(struct pinentry_option_s));
255 client->flags |= no_pinentry ? FLAG_NO_PINENTRY : 0;
256 #ifdef WITH_AGENT
257 if (crypto && crypto->agent)
258 memcpy (&crypto->agent->pinentry_opts, &agent_pin_opts,
259 sizeof(struct pinentry_option_s));
260 #endif
263 static gpg_error_t
264 open_finalize (assuan_context_t ctx, char *key, size_t keylen)
266 struct client_s *client = assuan_get_pointer (ctx);
267 gpg_error_t rc = 0;
268 struct cache_data_s *cdata = cache_get_data (client->md5file);
269 int cached = 0, keyarg = key ? 1 : 0;
270 size_t keysize;
271 unsigned char *salted_key = NULL;
272 int algo;
273 int pin_try = 1;
274 int pin_tries = 3;
275 char *pin_title = client->pinentry_opts.title;
277 client->crypto->filename = str_dup (client->filename);
278 if (cdata || client->flags & FLAG_NEW)
280 if (cdata && !(client->flags & FLAG_NEW))
282 rc = decrypt_cache (client->crypto, cdata->doc, cdata->doclen);
283 if (rc)
284 return rc;
287 cached = cdata != NULL;
288 goto done;
291 if (!key && !IS_PKI (client->crypto))
293 if (client->flags & FLAG_NO_PINENTRY)
295 rc = inquire_passphrase (ctx, "PASSPHRASE", (unsigned char **)&key,
296 &keylen);
297 if (rc)
298 return rc;
300 else
302 client->pinentry_opts.timeout = config_get_integer (client->filename,
303 "pinentry_timeout");
304 pin_again:
305 rc = getpin_common (client->ctx, client->filename, PINENTRY_OPEN,
306 &key, &keylen);
307 if (rc)
308 return rc;
312 if (!IS_PKI (client->crypto))
314 algo = cipher_to_gcrypt (client->crypto->hdr.flags);
315 rc = hash_key (algo, client->crypto->hdr.salt,
316 sizeof(client->crypto->hdr.salt), key, keylen,
317 (void **)&salted_key, &keysize);
318 if (!keyarg)
319 gcry_free (key);
321 if (!rc)
323 rc = decrypt_data (client->ctx, client->crypto, salted_key, keysize);
324 if (gpg_err_code (rc) == GPG_ERR_BAD_PASSPHRASE
325 && ++pin_try <= pin_tries && !(client->flags & FLAG_NO_PINENTRY))
327 gcry_free (salted_key);
328 salted_key = NULL;
329 key = NULL;
330 keylen = 0;
331 client->pinentry_opts.title = str_asprintf (_ ("Bad passphrase (try %i of %i)"), pin_try, pin_tries);
332 goto pin_again;
336 if (client->pinentry_opts.title != pin_title)
337 xfree (client->pinentry_opts.title);
339 client->pinentry_opts.title = pin_title;
340 if (rc)
341 return rc;
343 cdata = xcalloc (1, sizeof (struct cache_data_s));
344 if (!cdata)
345 return GPG_ERR_ENOMEM;
347 cdata->key = salted_key;
348 cdata->keylen = keysize;
350 else
351 rc = decrypt_data (client->ctx, client->crypto, NULL, 0);
353 done:
354 if (!rc)
356 rc = parse_xml (ctx, client->flags & FLAG_NEW);
357 if (!rc)
359 int timeout = config_get_integer (client->filename,
360 "cache_timeout");
362 if (!cached)
364 if (!cdata)
365 cdata = xcalloc (1, sizeof (struct cache_data_s));
367 rc = encrypt_xml (NULL, cache_key, cache_keysize,
368 GCRY_CIPHER_AES, client->crypto->plaintext,
369 client->crypto->plaintext_len, &cdata->doc,
370 &cdata->doclen, &cache_iv, &cache_blocksize,
372 if (!rc && !(client->flags & FLAG_NEW) && IS_PKI (client->crypto))
374 rc = gcry_sexp_build ((gcry_sexp_t *) & cdata->pubkey, NULL,
375 "%S", client->crypto->pkey_sexp);
379 if (cdata->sigkey)
380 gcry_sexp_release (cdata->sigkey);
382 cdata->sigkey = NULL;
383 if (!rc && IS_PKI (client->crypto))
384 rc = gcry_sexp_build ((gcry_sexp_t *) &cdata->sigkey, NULL,
385 "%S", client->crypto->sigpkey_sexp);
387 if (!rc && !cache_add_file (client->md5file,
388 (client->flags & FLAG_NEW)
389 ? NULL
390 : client->crypto->grip, cdata, timeout))
392 if (!cached)
394 free_cache_data_once (cdata);
395 xmlFreeDoc (client->doc);
396 client->doc = NULL;
398 rc = GPG_ERR_ENOMEM;
401 if (!rc)
402 client->flags |= FLAG_OPEN;
406 if (!rc)
407 update_checksum (client);
409 if (!rc && (client->opts & OPT_LOCK_ON_OPEN))
410 rc = do_lock (client, 0);
412 return rc;
415 static void
416 req_cleanup (void *arg)
418 if (!arg)
419 return;
421 strv_free ((char **) arg);
424 static gpg_error_t
425 parse_open_opt_lock (void *data, void *value)
427 struct client_s *client = data;
429 client->opts |= OPT_LOCK_ON_OPEN;
430 return 0;
433 static gpg_error_t
434 parse_opt_inquire (void *data, void *value)
436 struct client_s *client = data;
438 (void) value;
439 client->opts |= OPT_INQUIRE;
440 return 0;
443 static gpg_error_t
444 update_checksum (struct client_s *client)
446 unsigned char *crc;
447 size_t len;
448 struct cache_data_s *cdata;
449 gpg_error_t rc = get_checksum (client->filename, &crc, &len);
451 if (rc)
452 return rc;
454 xfree (client->crc);
455 client->crc = crc;
456 cdata = cache_get_data (client->md5file);
457 if (cdata)
459 xfree (cdata->crc);
460 cdata->crc = xmalloc (len);
461 memcpy (cdata->crc, crc, len);
464 return 0;
467 static gpg_error_t
468 validate_checksum (struct client_s *client, struct cache_data_s *cdata)
470 unsigned char *crc;
471 size_t len;
472 gpg_error_t rc;
473 int n = 0;
475 if (cdata && !cdata->crc)
476 return GPG_ERR_CHECKSUM;
478 rc = get_checksum (client->filename, &crc, &len);
479 if (rc)
480 return rc;
482 if (cdata)
483 n = memcmp (cdata->crc, crc, len);
484 else if (client->crc)
485 n = memcmp (client->crc, crc, len);
487 xfree (crc);
488 return n ? GPG_ERR_CHECKSUM : 0;
491 static gpg_error_t
492 do_open (assuan_context_t ctx, const char *filename, const char *password)
494 struct client_s *client = assuan_get_pointer (ctx);
495 struct cache_data_s *cdata;
496 gpg_error_t rc = 0;
497 int done = 0;
499 if (!valid_filename (filename))
500 return GPG_ERR_INV_VALUE;
502 gcry_md_hash_buffer (GCRY_MD_MD5, client->md5file, filename,
503 strlen (filename));
504 client->filename = str_dup (filename);
505 if (!client->filename)
506 return GPG_ERR_ENOMEM;
508 // Cached document?
509 cdata = cache_get_data (client->md5file);
510 if (cdata && cdata->doc)
512 int defer;
514 /* This will check that the key is cached in the agent which needs to
515 * be determined for files that share a keygrip. */
516 if (!rc)
518 rc = cache_iscached (client->filename, &defer);
519 if ((!rc || rc == GPG_ERR_ENOENT) && defer)
520 rc = GPG_ERR_KEY_EXPIRED;
523 if (!rc && !(client->flags & FLAG_NEW))
524 rc = validate_checksum (client, cdata);
526 #ifdef WITH_GNUTLS
527 if (!rc && client->thd->remote
528 && config_get_boolean (client->filename, "tcp_require_key"))
529 rc = GPG_ERR_KEY_EXPIRED;
530 #endif
532 if (!rc && !password)
534 rc = read_data_header (client->filename, &client->crypto->hdr,
535 NULL, NULL);
536 if (!rc)
538 if (IS_PKI (client->crypto))
540 gcry_sexp_build (&client->crypto->pkey_sexp, NULL, "%S",
541 cdata->pubkey);
542 gcry_pk_get_keygrip (client->crypto->pkey_sexp,
543 client->crypto->grip);
544 gcry_sexp_build (&client->crypto->sigpkey_sexp, NULL, "%S",
545 cdata->sigkey);
546 gcry_pk_get_keygrip (client->crypto->sigpkey_sexp,
547 client->crypto->sign_grip);
550 if (!rc)
552 rc = open_finalize (ctx, NULL, 0);
553 done = 1;
558 /* There was an error accessing the file so clear the cache entry. The
559 * real error will be returned from read_data_file() since the file
560 * may have only disappeared. */
561 if (!done)
563 log_write ("%s: %s", filename, pwmd_strerror (rc));
564 rc = cache_clear (client->md5file);
565 send_status_all (STATUS_CACHE, NULL);
569 if (done || rc)
570 return rc;
572 rc = read_data_file (client->filename, client->crypto);
573 if (rc)
575 if (gpg_err_source (rc) != GPG_ERR_SOURCE_DEFAULT ||
576 gpg_err_code (rc) != GPG_ERR_ENOENT)
578 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
579 return rc;
582 client->flags |= FLAG_NEW;
583 memset (client->crypto->grip, 0, sizeof (client->crypto->grip));
584 memset (client->crypto->sign_grip, 0,
585 sizeof (client->crypto->sign_grip));
586 rc = open_finalize (ctx, NULL, 0);
587 return rc;
590 if (password && IS_PKI (client->crypto))
592 #ifdef WITH_AGENT
593 rc = set_agent_passphrase (client->crypto, password, strlen (password));
594 if (rc)
595 return rc;
596 #endif
599 rc = open_finalize (ctx, (char *)password, password ? strlen (password) : 0);
600 return rc;
603 static gpg_error_t
604 open_command (assuan_context_t ctx, char *line)
606 gpg_error_t rc;
607 struct client_s *client = assuan_get_pointer (ctx);
608 char **req, *password = NULL, *filename;
609 unsigned char md5file[16];
610 int same_file = 0;
611 struct argv_s *args[] = {
612 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_open_opt_lock},
613 NULL
616 rc = parse_options (&line, args, client);
617 if (rc)
618 return send_error (ctx, rc);
620 req = str_split (line, " ", 2);
621 if (!req)
622 return send_error (ctx, GPG_ERR_SYNTAX);
624 #ifdef WITH_GNUTLS
625 if (client->thd->remote)
627 rc = tls_validate_access (client, req[0]);
628 if (rc)
630 if (rc == GPG_ERR_INV_USER_ID)
631 log_write (_("client validation failed for file '%s'"), req[0]);
632 strv_free (req);
633 return send_error (ctx, rc);
636 /* Remote pinentries are not supported. */
637 client->flags |= FLAG_NO_PINENTRY;
639 else
641 #endif
642 assuan_peercred_t peer;
643 rc = do_validate_peer (ctx, req[0], &peer);
644 if (rc)
646 strv_free (req);
647 return send_error (ctx, rc);
649 #ifdef WITH_GNUTLS
651 #endif
653 pthread_cleanup_push (req_cleanup, req);
654 filename = req[0];
655 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
656 /* This client may have locked a different file with ISCACHED --lock than
657 * the current filename. This will remove that lock. */
658 same_file = !memcmp (md5file, client->md5file, 16) ? 1 : 0;
659 if (client->flags & FLAG_OPEN ||
660 (client->flags & FLAG_HAS_LOCK && !same_file))
662 typeof (client->opts) opts = client->opts;
663 typeof (client->flags) flags = client->flags;
665 if (same_file)
666 client->flags |= FLAG_KEEP_LOCK;
668 cleanup_client (client);
669 client->opts = opts;
670 client->flags |= flags;
671 client->flags &= ~(FLAG_LOCK_CMD);
672 if (!same_file)
673 client->flags &= ~(FLAG_HAS_LOCK | FLAG_NEW);
676 /* Need to lock the mutex here because file_modified() cannot without
677 * knowing the filename. */
678 memcpy (client->md5file, md5file, 16);
679 rc = lock_file_mutex (client, 1);
680 if (!rc)
682 password = req[1] && *req[1] ? req[1] : NULL;
683 #ifdef WITH_AGENT
684 if (IS_PKI (client->crypto))
685 rc = set_pinentry_mode (client->crypto->agent,
686 (client->flags & FLAG_NO_PINENTRY) ? "loopback"
687 : "ask");
688 #endif
689 if (!rc)
691 rc = do_open (ctx, filename, password);
692 if (rc)
693 cleanup_client (client);
695 cleanup_crypto_stage1 (client->crypto);
699 pthread_cleanup_pop (1);
701 if (!rc && client->flags & FLAG_NEW)
702 rc = send_status (ctx, STATUS_NEWFILE, NULL);
704 #ifdef WITH_AGENT
705 (void) kill_scd (client->crypto->agent);
706 #endif
707 return send_error (ctx, rc);
710 static gpg_error_t
711 parse_save_opt_no_passphrase (void *data, void *value)
713 struct client_s *client = data;
715 (void) value;
716 client->opts |= OPT_NO_PASSPHRASE;
717 return 0;
720 static gpg_error_t
721 parse_save_opt_no_agent (void *data, void *value)
723 struct client_s *client = data;
725 client->opts |= OPT_NO_AGENT;
726 return 0;
729 static gpg_error_t
730 parse_save_opt_cipher (void *data, void *value)
732 struct client_s *client = data;
733 int algo = cipher_string_to_gcrypt ((char *) value);
734 file_header_t *hdr = &client->crypto->save.hdr;
736 if (algo == -1)
737 return GPG_ERR_INV_VALUE;
739 hdr->flags = set_cipher_flag (hdr->flags, algo);
740 return 0;
743 static gpg_error_t
744 parse_save_opt_keygrip (void *data, void *value)
746 struct client_s *client = data;
748 if (!IS_PKI (client->crypto))
749 return GPG_ERR_INV_ARG;
751 #ifdef WITH_AGENT
752 if (client->crypto->save.pkey)
753 gcry_sexp_release (client->crypto->save.pkey);
755 client->crypto->save.pkey = NULL;
756 return get_pubkey (client->crypto, value, &client->crypto->save.pkey);
757 #else
758 return GPG_ERR_INV_ARG;
759 #endif
762 static gpg_error_t
763 parse_save_opt_sign_keygrip (void *data, void *value)
765 struct client_s *client = data;
767 if (!IS_PKI (client->crypto))
768 return GPG_ERR_INV_ARG;
770 #ifdef WITH_AGENT
771 if (client->crypto->save.sigpkey)
772 gcry_sexp_release (client->crypto->save.sigpkey);
774 client->crypto->save.sigpkey = NULL;
775 return get_pubkey (client->crypto, value, &client->crypto->save.sigpkey);
776 #else
777 return GPG_ERR_INV_ARG;
778 #endif
781 static gpg_error_t
782 parse_opt_s2k_count (void *data, void *value)
784 struct client_s *client = data;
785 char *v = value;
787 if (!v || !*v)
788 return GPG_ERR_INV_VALUE;
790 client->crypto->save.s2k_count = strtoul (v, NULL, 10);
791 return 0;
794 static gpg_error_t
795 parse_save_opt_iterations (void *data, void *value)
797 struct client_s *client = data;
798 char *v = value, *p;
799 uint64_t n;
801 if (!v || !*v)
802 return GPG_ERR_INV_VALUE;
804 errno = 0;
805 n = strtoull (v, &p, 10);
806 if (n == UINT64_MAX && errno)
807 return gpg_error_from_errno (errno);
808 else if (p && *p)
809 return GPG_ERR_INV_VALUE;
811 client->crypto->save.hdr.iterations = n;
812 return 0;
815 static gpg_error_t
816 save_finalize (assuan_context_t ctx)
818 struct client_s *client = assuan_get_pointer (ctx);
819 gpg_error_t rc = 0;
820 xmlChar *xmlbuf = NULL;
821 int xmlbuflen;
822 void *key = NULL;
823 size_t keylen = 0;
825 xmlDocDumpFormatMemory (client->doc, &xmlbuf, &xmlbuflen, 0);
826 if (!xmlbuf)
827 return GPG_ERR_ENOMEM;
829 pthread_cleanup_push (xmlFree, xmlbuf);
831 if (!use_agent || ((client->flags & FLAG_NEW)
832 && (client->opts & OPT_NO_AGENT))
833 || !(client->crypto->hdr.flags & PWMD_FLAG_PKI))
835 rc = export_common (ctx, client->flags & FLAG_NO_PINENTRY,
836 client->crypto, xmlbuf, xmlbuflen, client->filename,
837 NULL, &key, &keylen, 1, 1);
839 #ifdef WITH_AGENT
840 else
842 gcry_sexp_t pubkey = client->crypto->save.pkey;
843 gcry_sexp_t sigkey = client->crypto->save.sigpkey;
845 if (!pubkey)
846 pubkey = client->crypto->pkey_sexp;
848 if (!sigkey)
850 sigkey = client->crypto->sigpkey_sexp;
851 if (!sigkey)
853 gcry_sexp_build (&client->crypto->save.sigpkey, 0, "%S", pubkey);
854 sigkey = client->crypto->save.sigpkey;
858 rc = encrypt_data_file (client->ctx, client->crypto, pubkey, sigkey,
859 client->filename, xmlbuf, xmlbuflen);
860 if (pubkey == client->crypto->save.pkey)
862 if (!rc)
864 gcry_sexp_release (client->crypto->pkey_sexp);
865 client->crypto->pkey_sexp = client->crypto->save.pkey;
866 gcry_pk_get_keygrip (client->crypto->pkey_sexp,
867 client->crypto->grip);
869 else
870 gcry_sexp_release (pubkey);
872 client->crypto->save.pkey = NULL;
875 if (!rc)
876 gcry_pk_get_keygrip (sigkey, client->crypto->sign_grip);
878 if (sigkey == client->crypto->save.sigpkey)
880 if (!rc)
882 if (client->crypto->sigpkey_sexp)
883 gcry_sexp_release (client->crypto->sigpkey_sexp);
885 client->crypto->sigpkey_sexp = client->crypto->save.sigpkey;
886 gcry_pk_get_keygrip (client->crypto->sigpkey_sexp,
887 client->crypto->sign_grip);
889 else
890 gcry_sexp_release (sigkey);
892 client->crypto->save.sigpkey = NULL;
895 #endif
897 if (!rc)
899 int cached;
901 rc = save_common (client->filename, client->crypto, xmlbuf, xmlbuflen,
902 key, keylen, &cached, client->opts & OPT_NO_AGENT);
903 if (rc)
904 gcry_free (key);
906 if (!rc && (!cached || (client->flags & FLAG_NEW)))
907 send_status_all (STATUS_CACHE, NULL);
909 if (!rc)
911 rc = update_checksum (client);
912 client->flags &= ~(FLAG_NEW);
916 pthread_cleanup_pop (1); // xmlFree
917 return rc;
920 static gpg_error_t
921 parse_opt_reset (void *data, void *value)
923 struct client_s *client = data;
925 (void) value;
926 client->opts |= OPT_RESET;
927 return 0;
930 static gpg_error_t
931 save_command (assuan_context_t ctx, char *line)
933 struct client_s *client = assuan_get_pointer (ctx);
934 gpg_error_t rc;
935 struct stat st;
936 struct argv_s *args[] = {
937 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG,
938 parse_save_opt_no_passphrase},
939 &(struct argv_s) {"cipher", OPTION_TYPE_ARG, parse_save_opt_cipher},
940 &(struct argv_s) {"inquire-keyparam", OPTION_TYPE_NOARG,
941 parse_opt_inquire},
942 &(struct argv_s) {"keygrip", OPTION_TYPE_ARG, parse_save_opt_keygrip},
943 &(struct argv_s) {"sign-keygrip", OPTION_TYPE_ARG,
944 parse_save_opt_sign_keygrip},
945 &(struct argv_s) {"s2k-count", OPTION_TYPE_ARG, parse_opt_s2k_count},
946 &(struct argv_s) {"reset", OPTION_TYPE_NOARG, parse_opt_reset},
947 &(struct argv_s) {"cipher-iterations", OPTION_TYPE_ARG,
948 parse_save_opt_iterations},
949 &(struct argv_s) {"no-agent", OPTION_TYPE_NOARG,
950 parse_save_opt_no_agent},
951 NULL
954 cleanup_save (&client->crypto->save);
955 memcpy (&client->crypto->save.hdr, &client->crypto->hdr,
956 sizeof (file_header_t));
957 client->crypto->save.s2k_count =
958 config_get_ulong (client->filename, "s2k_count");
960 if (client->flags & FLAG_NEW)
961 client->crypto->save.hdr.iterations =
962 config_get_ulonglong (client->filename, "cipher_iterations");
964 rc = parse_options (&line, args, client);
965 if (rc)
966 return send_error (ctx, rc);
968 if (!(client->flags & FLAG_NEW))
969 client->opts &= ~OPT_NO_AGENT;
970 else if (client->opts & OPT_NO_AGENT)
972 client->crypto->save.hdr.flags &= ~PWMD_FLAG_PKI;
973 client->crypto->hdr.flags &= ~PWMD_FLAG_PKI;
976 if ((client->opts & OPT_NO_PASSPHRASE) && !(client->flags & FLAG_NEW)
977 && !(client->opts & OPT_INQUIRE))
978 return send_error (ctx, GPG_ERR_WRONG_KEY_USAGE);
980 if (lstat (client->filename, &st) == -1 && errno != ENOENT)
981 return send_error (ctx, gpg_error_from_errno (errno));
983 if (errno != ENOENT && !S_ISREG (st.st_mode))
985 log_write ("%s: %s", client->filename, pwmd_strerror (GPG_ERR_ENOANO));
986 return send_error (ctx, GPG_ERR_ENOANO);
989 int defer;
990 rc = cache_iscached (client->filename, &defer);
991 if (gpg_err_code (rc) == GPG_ERR_ENOENT && client->flags & FLAG_NEW)
992 rc = 0;
993 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
994 rc = 0;
996 if ((!rc && defer) || config_get_boolean ("global", "require_save_key"))
997 client->opts |= OPT_RESET;
999 if (!rc && (client->opts & OPT_RESET))
1001 rc = cache_clear (client->md5file);
1002 if (rc)
1003 return send_error (ctx, rc);
1005 log_write ("%s: %s", client->filename,
1006 pwmd_strerror (GPG_ERR_KEY_EXPIRED));
1007 send_status_all (STATUS_CACHE, NULL);
1010 if (!rc)
1011 rc = update_element_mtime (xmlDocGetRootElement (client->doc));
1013 if (rc)
1014 return send_error (ctx, rc);
1016 #ifdef WITH_AGENT
1017 if (!rc && use_agent && !client->crypto->save.pkey &&
1018 (client->flags & FLAG_NEW || client->opts & OPT_INQUIRE)
1019 && !(client->opts & OPT_NO_AGENT))
1021 rc = set_pinentry_mode (client->crypto->agent,
1022 (client->flags & FLAG_NO_PINENTRY) ? "loopback"
1023 : "ask");
1025 if (!(client->flags & FLAG_NEW))
1027 struct crypto_s *crypto;
1028 char *key = NULL;
1029 size_t keylen = 0;
1031 /* Wanting to generate a new key. Require the key to open the
1032 current file before proceeding reguardless of the
1033 require_save_key configuration parameter. */
1034 rc = cache_clear (client->md5file);
1035 if (!rc)
1037 rc = init_client_crypto (&crypto);
1038 if (!rc)
1039 crypto->client_ctx = client->ctx;
1042 if (!rc)
1043 rc = decrypt_common (client->ctx, client->opts&OPT_INQUIRE, crypto,
1044 client->filename, &key, &keylen);
1046 xfree (key);
1047 cleanup_crypto (&crypto);
1050 if (!rc)
1051 rc = send_status (client->ctx, STATUS_GENKEY, NULL);
1053 if (!rc)
1055 struct inquire_data_s idata = { 0 };
1056 char *params = client->opts & OPT_INQUIRE
1057 ? NULL : default_key_params (client->crypto);
1059 pthread_cleanup_push (xfree, params);
1060 idata.crypto = client->crypto;
1062 if (params)
1064 idata.line = params;
1065 idata.len = strlen (params);
1067 else
1068 idata.preset = 1;
1070 client->crypto->agent->inquire_data = &idata;
1071 client->crypto->agent->inquire_cb = NULL;
1072 rc = generate_key (client->crypto, params,
1073 (client->opts & OPT_NO_PASSPHRASE), 1);
1074 pthread_cleanup_pop (1);
1077 #endif
1079 if (!rc)
1080 rc = save_finalize (ctx);
1082 cleanup_crypto_stage1 (client->crypto);
1083 #ifdef WITH_AGENT
1084 (void) kill_scd (client->crypto->agent);
1085 #endif
1086 return send_error (ctx, rc);
1089 static gpg_error_t
1090 do_delete (assuan_context_t ctx, char *line)
1092 struct client_s *client = assuan_get_pointer (ctx);
1093 gpg_error_t rc;
1094 char **req;
1095 xmlNodePtr n;
1097 if (strchr (line, '\t'))
1098 req = str_split (line, "\t", 0);
1099 else
1100 req = str_split (line, " ", 0);
1102 if (!req || !*req)
1103 return GPG_ERR_SYNTAX;
1105 n = find_root_element (client->doc, &req, &rc, NULL, 0, 0);
1106 if (!n)
1108 strv_free (req);
1109 return rc;
1113 * No sub-node defined. Remove the entire node (root element).
1115 if (!req[1])
1117 if (n)
1119 rc = unlink_node (n);
1120 xmlFreeNode (n);
1123 strv_free (req);
1124 return rc;
1128 find_elements (client->doc, n->children, req + 1, &rc, NULL, NULL, NULL,
1129 0, 0, NULL, 0);
1130 strv_free (req);
1131 if (!n)
1132 return rc;
1134 if (n)
1136 rc = unlink_node (n);
1137 xmlFreeNode (n);
1140 return rc;
1143 static gpg_error_t
1144 delete_command (assuan_context_t ctx, char *line)
1146 struct client_s *client = assuan_get_pointer (ctx);
1147 gpg_error_t rc;
1148 struct argv_s *args[] = {
1149 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1150 NULL
1153 rc = parse_options (&line, args, client);
1154 if (rc)
1155 return send_error (ctx, rc);
1157 if (client->opts & OPT_INQUIRE)
1159 unsigned char *result;
1160 size_t len;
1162 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1163 if (rc)
1164 return send_error (ctx, rc);
1166 line = (char *) result;
1169 rc = do_delete (ctx, line);
1171 if (client->opts & OPT_INQUIRE)
1172 xfree (line);
1174 return send_error (ctx, rc);
1177 static gpg_error_t
1178 store_command (assuan_context_t ctx, char *line)
1180 struct client_s *client = assuan_get_pointer (ctx);
1181 gpg_error_t rc;
1182 size_t len;
1183 unsigned char *result;
1184 char **req;
1185 xmlNodePtr n, parent;
1186 int has_content;
1187 char *content = NULL;
1189 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1190 if (rc)
1191 return send_error (ctx, rc);
1193 req = str_split ((char *) result, "\t", 0);
1194 xfree (result);
1196 if (!req || !*req)
1197 return send_error (ctx, GPG_ERR_SYNTAX);
1199 len = strv_length (req);
1200 has_content = line[strlen (line) - 1] != '\t' && len > 1;
1201 if (*(req + 1) && !valid_element_path (req, has_content))
1203 strv_free (req);
1204 return send_error (ctx, GPG_ERR_INV_VALUE);
1207 if (has_content || !*req[len - 1])
1209 has_content = 1;
1210 content = req[len - 1];
1211 req[len - 1] = NULL;
1214 again:
1215 n = find_root_element (client->doc, &req, &rc, NULL, 0, 0);
1216 if (rc && rc == GPG_ERR_ELEMENT_NOT_FOUND)
1218 rc = new_root_element (client->doc, *req);
1219 if (rc)
1221 strv_free (req);
1222 return send_error (ctx, GPG_ERR_SYNTAX);
1225 goto again;
1228 if (!n)
1230 strv_free (req);
1231 return send_error (ctx, rc);
1234 parent = n;
1236 if (req[1] && *req[1])
1238 if (!n->children)
1239 parent = create_elements_cb (n, req + 1, &rc, NULL);
1240 else
1241 parent = find_elements (client->doc, n->children, req + 1, &rc,
1242 NULL, NULL, create_elements_cb, 0, 0, NULL,
1246 if (!rc && len > 1)
1248 n = find_text_node (parent->children);
1249 if (n)
1250 xmlNodeSetContent (n, (xmlChar *) content);
1251 else
1252 xmlNodeAddContent (parent, (xmlChar *) content);
1254 update_element_mtime (parent);
1257 xfree (content);
1258 strv_free (req);
1259 return send_error (ctx, rc);
1262 static gpg_error_t
1263 xfer_data (assuan_context_t ctx, const char *line, int total)
1265 int to_send;
1266 int sent = 0;
1267 gpg_error_t rc;
1268 int progress = config_get_integer ("global", "xfer_progress");
1269 int flush = 0;
1271 progress =
1272 progress > 0 ? (progress / ASSUAN_LINELENGTH) * ASSUAN_LINELENGTH : 0;
1273 to_send = total < ASSUAN_LINELENGTH ? total : ASSUAN_LINELENGTH;
1274 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1276 if (rc)
1277 return rc;
1279 again:
1282 if (sent + to_send > total)
1283 to_send = total - sent;
1285 rc = assuan_send_data (ctx, flush ? NULL : (char *) line + sent,
1286 flush ? 0 : to_send);
1287 if (!rc)
1289 sent += flush ? 0 : to_send;
1291 if ((progress && !(sent % progress) && sent != total) ||
1292 (sent == total && flush))
1293 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1295 if (!flush && !rc && sent == total)
1297 flush = 1;
1298 goto again;
1302 while (!rc && sent < total);
1304 return rc;
1307 static gpg_error_t
1308 do_get (assuan_context_t ctx, char *line)
1310 struct client_s *client = assuan_get_pointer (ctx);
1311 gpg_error_t rc;
1312 char **req;
1313 xmlNodePtr n;
1315 req = str_split (line, "\t", 0);
1317 if (!req || !*req)
1319 strv_free (req);
1320 return GPG_ERR_SYNTAX;
1323 n = find_root_element (client->doc, &req, &rc, NULL, 0, 0);
1324 if (!n)
1326 strv_free (req);
1327 return rc;
1330 if (req[1])
1332 find_elements (client->doc, n->children, req + 1, &rc, NULL, NULL, NULL,
1333 0, 0, NULL, 0);
1335 strv_free (req);
1336 if (rc)
1337 return rc;
1339 if (!n || !n->children)
1340 return GPG_ERR_NO_DATA;
1342 n = find_text_node (n->children);
1343 if (!n || !n->content || !*n->content)
1344 return GPG_ERR_NO_DATA;
1346 rc = xfer_data (ctx, (char *) n->content, xmlStrlen (n->content));
1347 return rc;
1350 static gpg_error_t
1351 get_command (assuan_context_t ctx, char *line)
1353 struct client_s *client = assuan_get_pointer (ctx);
1354 gpg_error_t rc;
1355 struct argv_s *args[] = {
1356 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1357 NULL
1360 rc = parse_options (&line, args, client);
1361 if (rc)
1362 return send_error (ctx, rc);
1364 if (client->opts & OPT_INQUIRE)
1366 unsigned char *result;
1367 size_t len;
1369 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1370 if (rc)
1371 return send_error (ctx, rc);
1373 line = (char *) result;
1376 rc = do_get (ctx, line);
1378 if (client->opts & OPT_INQUIRE)
1379 xfree (line);
1381 return send_error (ctx, rc);
1384 static void list_command_cleanup1 (void *arg);
1385 static gpg_error_t
1386 realpath_command (assuan_context_t ctx, char *line)
1388 struct string_s *string = NULL;
1389 gpg_error_t rc;
1390 struct client_s *client = assuan_get_pointer (ctx);
1391 struct argv_s *args[] = {
1392 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1393 NULL
1396 rc = parse_options (&line, args, client);
1397 if (rc)
1398 return send_error (ctx, rc);
1400 if (client->opts & OPT_INQUIRE)
1402 unsigned char *result;
1403 size_t len;
1405 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1406 if (rc)
1407 return send_error (ctx, rc);
1409 line = (char *) result;
1412 rc = build_realpath (client->doc, line, &string);
1413 if (!rc)
1415 pthread_cleanup_push (list_command_cleanup1, string);
1416 rc = xfer_data (ctx, string->str, string->len);
1417 pthread_cleanup_pop (1);
1420 if (client->opts & OPT_INQUIRE)
1421 xfree (line);
1423 return send_error (ctx, rc);
1426 static void
1427 list_command_cleanup1 (void *arg)
1429 if (arg)
1430 string_free ((struct string_s *) arg, 1);
1433 static void
1434 list_command_cleanup2 (void *arg)
1436 struct element_list_s *elements = arg;
1438 if (elements)
1440 if (elements->list)
1442 int total = slist_length (elements->list);
1443 int i;
1445 for (i = 0; i < total; i++)
1447 char *tmp = slist_nth_data (elements->list, i);
1448 xfree (tmp);
1451 slist_free (elements->list);
1454 if (elements->prefix)
1455 xfree (elements->prefix);
1457 if (elements->req)
1458 strv_free (elements->req);
1460 xfree (elements);
1464 static gpg_error_t
1465 parse_list_opt_norecurse (void *data, void *value)
1467 struct client_s *client = data;
1469 client->opts &= ~(OPT_LIST_RECURSE);
1470 return 0;
1473 static gpg_error_t
1474 parse_list_opt_verbose (void *data, void *value)
1476 struct client_s *client = data;
1478 client->opts |= OPT_LIST_VERBOSE;
1479 return 0;
1482 static gpg_error_t
1483 parse_list_opt_target (void *data, void *value)
1485 struct client_s *client = data;
1487 client->opts |= OPT_LIST_WITH_TARGET;
1488 return 0;
1491 static gpg_error_t
1492 parse_list_opt_all (void *data, void *value)
1494 struct client_s *client = data;
1496 client->opts |= OPT_LIST_ALL;
1497 return 0;
1500 static gpg_error_t
1501 list_path_once (struct client_s *client, char *line,
1502 struct element_list_s *elements, struct string_s *result)
1504 gpg_error_t rc;
1506 elements->req = str_split (line, " ", 0);
1507 if (!elements->req)
1508 strv_printf (&elements->req, "%s", line);
1510 rc = create_path_list (client->doc, elements, *elements->req);
1511 if (rc == GPG_ERR_ELOOP && elements->verbose)
1512 rc = 0;
1514 if (!rc)
1516 int total = slist_length (elements->list);
1517 int i;
1519 if (!total)
1520 rc = GPG_ERR_NO_DATA;
1522 if (!rc)
1524 if (!rc)
1526 for (i = 0; i < total; i++)
1528 char *tmp = slist_nth_data (elements->list, i);
1530 string_append_printf (result, "%s%s", tmp,
1531 i + 1 == total ? "" : "\n");
1535 else
1536 rc = GPG_ERR_NO_DATA;
1539 return rc;
1542 static int
1543 has_list_flag (char *path, char *flags)
1545 char *p = path;
1547 while (*p && *++p != ' ');
1549 if (!*p)
1550 return 0;
1552 for (; *p; p++)
1554 char *f;
1556 for (f = flags; *f && *f != ' '; f++)
1558 if (*p == *f)
1559 return 1;
1563 return 0;
1566 static gpg_error_t
1567 do_list (assuan_context_t ctx, char *line)
1569 struct client_s *client = assuan_get_pointer (ctx);
1570 gpg_error_t rc;
1571 struct element_list_s *elements = NULL;
1573 elements = xcalloc (1, sizeof (struct element_list_s));
1574 if (!elements)
1575 return GPG_ERR_ENOMEM;
1577 elements->recurse = client->opts & OPT_LIST_RECURSE;
1578 elements->verbose =
1579 (client->opts & OPT_LIST_VERBOSE) | (client->opts & OPT_LIST_WITH_TARGET);
1580 elements->with_target = client->opts & OPT_LIST_WITH_TARGET;
1582 if (!line || !*line)
1584 struct string_s *str = NULL;
1586 pthread_cleanup_push (list_command_cleanup2, elements);
1587 rc = list_root_elements (client->doc, &str, elements->verbose,
1588 elements->with_target);
1589 pthread_cleanup_pop (1);
1590 pthread_cleanup_push (list_command_cleanup1, str);
1592 if (!rc)
1594 if (client->opts & OPT_LIST_ALL)
1596 char **roots = str_split (str->str, "\n", 0);
1597 char **p;
1599 pthread_cleanup_push (req_cleanup, roots);
1600 string_truncate (str, 0);
1602 for (p = roots; *p; p++)
1604 if (strchr (*p, ' '))
1606 if (has_list_flag (*p, "EO"))
1608 string_append_printf (str, "%s%s", *p,
1609 *(p + 1) ? "\n" : "");
1610 continue;
1614 elements = xcalloc (1, sizeof (struct element_list_s));
1615 if (!elements)
1617 rc = GPG_ERR_ENOMEM;
1618 break;
1621 elements->recurse = client->opts & OPT_LIST_RECURSE;
1622 elements->verbose =
1623 (client->opts & OPT_LIST_VERBOSE) | (client->opts &
1624 OPT_LIST_WITH_TARGET);
1625 elements->with_target = client->opts & OPT_LIST_WITH_TARGET;
1626 pthread_cleanup_push (list_command_cleanup2, elements);
1627 rc = list_path_once (client, *p, elements, str);
1628 pthread_cleanup_pop (1);
1629 if (rc)
1630 break;
1632 if (*(p + 1))
1633 string_append (str, "\n");
1636 pthread_cleanup_pop (1);
1639 if (!rc)
1640 rc = xfer_data (ctx, str->str, str->len);
1643 pthread_cleanup_pop (1);
1644 return rc;
1647 pthread_cleanup_push (list_command_cleanup2, elements);
1648 struct string_s *str = string_new (NULL);
1649 pthread_cleanup_push (list_command_cleanup1, str);
1650 rc = list_path_once (client, line, elements, str);
1651 if (!rc)
1652 rc = xfer_data (ctx, str->str, str->len);
1654 pthread_cleanup_pop (1);
1655 pthread_cleanup_pop (1);
1656 return rc;
1659 static gpg_error_t
1660 list_command (assuan_context_t ctx, char *line)
1662 struct client_s *client = assuan_get_pointer (ctx);
1663 gpg_error_t rc;
1664 struct argv_s *args[] = {
1665 &(struct argv_s) {"no-recurse", OPTION_TYPE_NOARG,
1666 parse_list_opt_norecurse},
1667 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_list_opt_verbose},
1668 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1669 &(struct argv_s) {"with-target", OPTION_TYPE_NOARG,
1670 parse_list_opt_target},
1671 &(struct argv_s) {"all", OPTION_TYPE_NOARG, parse_list_opt_all},
1672 NULL
1675 if (disable_list_and_dump == 1)
1676 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
1678 client->opts |= OPT_LIST_RECURSE;
1679 rc = parse_options (&line, args, client);
1680 if (rc)
1681 return send_error (ctx, rc);
1683 if (client->opts & OPT_LIST_ALL)
1684 client->opts |= OPT_LIST_RECURSE | OPT_LIST_VERBOSE;
1686 if (client->opts & OPT_INQUIRE)
1688 unsigned char *result;
1689 size_t len;
1691 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1692 if (rc)
1693 return send_error (ctx, rc);
1695 line = (char *) result;
1698 rc = do_list (ctx, line);
1700 if (client->opts & OPT_INQUIRE)
1701 xfree (line);
1703 return send_error (ctx, rc);
1707 * req[0] - element path
1709 static gpg_error_t
1710 attribute_list (assuan_context_t ctx, char **req)
1712 struct client_s *client = assuan_get_pointer (ctx);
1713 char **attrlist = NULL;
1714 int i = 0;
1715 char **path = NULL;
1716 xmlAttrPtr a;
1717 xmlNodePtr n, an;
1718 char *line;
1719 gpg_error_t rc;
1721 if (!req || !req[0])
1722 return GPG_ERR_SYNTAX;
1724 if ((path = str_split (req[0], "\t", 0)) == NULL)
1727 * The first argument may be only a root element.
1729 if ((path = str_split (req[0], " ", 0)) == NULL)
1730 return GPG_ERR_SYNTAX;
1733 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
1735 if (!n)
1737 strv_free (path);
1738 return rc;
1741 if (path[1])
1743 n = find_elements (client->doc, n->children, path + 1, &rc,
1744 NULL, NULL, NULL, 0, 0, NULL, 0);
1746 if (!n)
1748 strv_free (path);
1749 return rc;
1753 strv_free (path);
1755 for (a = n->properties; a; a = a->next)
1757 char **pa;
1759 if ((pa = xrealloc (attrlist, (i + 2) * sizeof (char *))) == NULL)
1761 if (attrlist)
1762 strv_free (attrlist);
1764 log_write ("%s(%i): %s", __FILE__, __LINE__,
1765 pwmd_strerror (GPG_ERR_ENOMEM));
1766 return GPG_ERR_ENOMEM;
1769 attrlist = pa;
1770 an = a->children;
1771 attrlist[i] = str_asprintf ("%s %s", (char *) a->name,
1773 && an->content ? (char *) an->content : "");
1775 if (!attrlist[i])
1777 strv_free (attrlist);
1778 log_write ("%s(%i): %s", __FILE__, __LINE__,
1779 pwmd_strerror (GPG_ERR_ENOMEM));
1780 return GPG_ERR_ENOMEM;
1783 attrlist[++i] = NULL;
1786 if (!attrlist)
1787 return GPG_ERR_NO_DATA;
1789 line = strv_join ("\n", attrlist);
1791 if (!line)
1793 log_write ("%s(%i): %s", __FILE__, __LINE__,
1794 pwmd_strerror (GPG_ERR_ENOMEM));
1795 strv_free (attrlist);
1796 return GPG_ERR_ENOMEM;
1799 pthread_cleanup_push (xfree, line);
1800 pthread_cleanup_push (req_cleanup, attrlist);
1801 rc = xfer_data (ctx, line, strlen (line));
1802 pthread_cleanup_pop (1);
1803 pthread_cleanup_pop (1);
1804 return rc;
1808 * req[0] - attribute
1809 * req[1] - element path
1811 static gpg_error_t
1812 attribute_delete (struct client_s *client, char **req)
1814 xmlNodePtr n;
1815 char **path = NULL;
1816 gpg_error_t rc;
1818 if (!req || !req[0] || !req[1])
1819 return GPG_ERR_SYNTAX;
1821 if (!strcmp (req[0], "_name"))
1822 return GPG_ERR_INV_ATTR;
1824 if ((path = str_split (req[1], "\t", 0)) == NULL)
1827 * The first argument may be only a root element.
1829 if ((path = str_split (req[1], " ", 0)) == NULL)
1830 return GPG_ERR_SYNTAX;
1833 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
1834 if (!n)
1835 goto fail;
1837 if (path[1])
1839 n = find_elements (client->doc, n->children, path + 1, &rc,
1840 NULL, NULL, NULL, 0, 0, NULL, 0);
1841 if (!n)
1842 goto fail;
1845 rc = delete_attribute (n, (xmlChar *) req[0]);
1847 fail:
1848 strv_free (path);
1849 return rc;
1852 static xmlNodePtr
1853 create_element_path (struct client_s *client,
1854 char ***elements, gpg_error_t * rc, xmlNodePtr parent)
1856 char **req = *elements;
1857 char **req_orig = strv_dup (req);
1858 xmlNodePtr n = NULL;
1860 *rc = 0;
1862 if (!req_orig)
1864 *rc = GPG_ERR_ENOMEM;
1865 log_write ("%s(%i): %s", __FILE__, __LINE__,
1866 pwmd_strerror (GPG_ERR_ENOMEM));
1867 goto fail;
1870 again:
1871 n = find_root_element (client->doc, &req, rc, NULL, 0, 0);
1872 if (!n)
1874 if (*rc != GPG_ERR_ELEMENT_NOT_FOUND)
1875 goto fail;
1877 *rc = new_root_element (client->doc, req[0]);
1878 if (*rc)
1879 goto fail;
1881 goto again;
1883 else if (n == parent)
1885 *rc = GPG_ERR_CONFLICT;
1886 goto fail;
1889 if (req[1])
1891 if (!n->children)
1892 n = create_target_elements_cb (n, req + 1, rc, NULL);
1893 else
1894 n = find_elements (client->doc, n->children, req + 1, rc, NULL, NULL,
1895 create_target_elements_cb, 0, 0, parent, 0);
1897 if (!n)
1898 goto fail;
1901 * Reset the position of the element tree now that the elements
1902 * have been created.
1904 strv_free (req);
1905 req = req_orig;
1906 req_orig = NULL;
1907 n = find_root_element (client->doc, &req, rc, NULL, 0, 0);
1908 if (!n)
1909 goto fail;
1911 n = find_elements (client->doc, n->children, req + 1, rc,
1912 NULL, NULL, NULL, 0, 0, NULL, 0);
1913 if (!n)
1914 goto fail;
1917 fail:
1918 if (req_orig)
1919 strv_free (req_orig);
1921 *elements = req;
1922 return n;
1926 * Creates a "target" attribute. When other commands encounter an element with
1927 * this attribute, the element path is modified to the target value. If the
1928 * source element path doesn't exist when using 'ATTR SET target', it is
1929 * created, but the destination element path must exist.
1931 * req[0] - source element path
1932 * req[1] - destination element path
1934 static gpg_error_t
1935 target_attribute (struct client_s *client, char **req)
1937 char **src, **dst, *line = NULL, **odst = NULL;
1938 gpg_error_t rc;
1939 xmlNodePtr n;
1941 if (!req || !req[0] || !req[1])
1942 return GPG_ERR_SYNTAX;
1944 if ((src = str_split (req[0], "\t", 0)) == NULL)
1947 * The first argument may be only a root element.
1949 if ((src = str_split (req[0], " ", 0)) == NULL)
1950 return GPG_ERR_SYNTAX;
1953 if (!valid_element_path (src, 0))
1954 return GPG_ERR_INV_VALUE;
1956 if ((dst = str_split (req[1], "\t", 0)) == NULL)
1959 * The first argument may be only a root element.
1961 if ((dst = str_split (req[1], " ", 0)) == NULL)
1963 rc = GPG_ERR_SYNTAX;
1964 goto fail;
1968 odst = strv_dup (dst);
1969 if (!odst)
1971 rc = GPG_ERR_ENOMEM;
1972 goto fail;
1975 n = find_root_element (client->doc, &dst, &rc, NULL, 0, 0);
1977 * Make sure the destination element path exists.
1979 if (!n)
1980 goto fail;
1982 if (dst[1])
1984 n = find_elements (client->doc, n->children, dst + 1, &rc,
1985 NULL, NULL, NULL, 0, 0, NULL, 0);
1986 if (!n)
1987 goto fail;
1990 rc = validate_target_attribute (client->doc, req[0], n);
1991 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
1992 goto fail;
1994 n = create_element_path (client, &src, &rc, NULL);
1995 if (rc)
1996 goto fail;
1998 line = strv_join ("\t", odst);
1999 if (!line)
2001 rc = GPG_ERR_ENOMEM;
2002 goto fail;
2005 rc = add_attribute (n, "target", line);
2007 fail:
2008 xfree (line);
2009 strv_free (src);
2010 strv_free (dst);
2011 strv_free (odst);
2012 return rc;
2016 * req[0] - attribute
2017 * req[1] - element path
2019 static gpg_error_t
2020 attribute_get (assuan_context_t ctx, char **req)
2022 struct client_s *client = assuan_get_pointer (ctx);
2023 xmlNodePtr n;
2024 xmlChar *a;
2025 char **path = NULL;
2026 gpg_error_t rc;
2028 if (!req || !req[0] || !req[1])
2029 return GPG_ERR_SYNTAX;
2031 if (strchr (req[1], '\t'))
2033 if ((path = str_split (req[1], "\t", 0)) == NULL)
2034 return GPG_ERR_SYNTAX;
2036 else
2038 if ((path = str_split (req[1], " ", 0)) == NULL)
2039 return GPG_ERR_SYNTAX;
2042 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
2044 if (!n)
2045 goto fail;
2047 if (path[1])
2049 n = find_elements (client->doc, n->children, path + 1, &rc,
2050 NULL, NULL, NULL, 0, 0, NULL, 0);
2052 if (!n)
2053 goto fail;
2056 strv_free (path);
2058 if ((a = xmlGetProp (n, (xmlChar *) req[0])) == NULL)
2059 return GPG_ERR_NOT_FOUND;
2061 pthread_cleanup_push (xmlFree, a);
2063 if (*a)
2064 rc = xfer_data (ctx, (char *) a, xmlStrlen (a));
2065 else
2066 rc = GPG_ERR_NO_DATA;
2068 pthread_cleanup_pop (1);
2069 return rc;
2071 fail:
2072 strv_free (path);
2073 return rc;
2077 * req[0] - attribute
2078 * req[1] - element path
2079 * req[2] - value
2081 static gpg_error_t
2082 attribute_set (struct client_s *client, char **req)
2084 char **path = NULL;
2085 gpg_error_t rc;
2086 xmlNodePtr n;
2088 if (!req || !req[0] || !req[1])
2089 return GPG_ERR_SYNTAX;
2092 * Reserved attribute names.
2094 if (!strcmp (req[0], "_name"))
2095 return GPG_ERR_INV_ATTR;
2096 else if (!strcmp (req[0], "target"))
2097 return target_attribute (client, req + 1);
2099 if ((path = str_split (req[1], "\t", 0)) == NULL)
2102 * The first argument may be only a root element.
2104 if ((path = str_split (req[1], " ", 0)) == NULL)
2105 return GPG_ERR_SYNTAX;
2108 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
2110 if (!n)
2111 goto fail;
2113 if (path[1])
2115 n = find_elements (client->doc, n->children, path + 1, &rc,
2116 NULL, NULL, NULL, 0, 0, NULL, 0);
2118 if (!n)
2119 goto fail;
2122 rc = add_attribute (n, req[0], req[2]);
2124 fail:
2125 strv_free (path);
2126 return rc;
2130 * req[0] - command
2131 * req[1] - attribute name or element path if command is LIST
2132 * req[2] - element path
2133 * req[2] - element path or value
2136 static gpg_error_t
2137 do_attr (assuan_context_t ctx, char *line)
2139 struct client_s *client = assuan_get_pointer (ctx);
2140 gpg_error_t rc = 0;
2141 char **req;
2143 req = str_split (line, " ", 4);
2144 if (!req || !req[0] || !req[1])
2146 strv_free (req);
2147 return GPG_ERR_SYNTAX;
2150 pthread_cleanup_push (req_cleanup, req);
2152 if (strcasecmp (req[0], "SET") == 0)
2153 rc = attribute_set (client, req + 1);
2154 else if (strcasecmp (req[0], "GET") == 0)
2155 rc = attribute_get (ctx, req + 1);
2156 else if (strcasecmp (req[0], "DELETE") == 0)
2157 rc = attribute_delete (client, req + 1);
2158 else if (strcasecmp (req[0], "LIST") == 0)
2159 rc = attribute_list (ctx, req + 1);
2160 else
2161 rc = GPG_ERR_SYNTAX;
2163 pthread_cleanup_pop (1);
2164 return rc;
2167 static gpg_error_t
2168 attr_command (assuan_context_t ctx, char *line)
2170 struct client_s *client = assuan_get_pointer (ctx);
2171 gpg_error_t rc;
2172 struct argv_s *args[] = {
2173 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2174 NULL
2177 rc = parse_options (&line, args, client);
2178 if (rc)
2179 return send_error (ctx, rc);
2181 if (client->opts & OPT_INQUIRE)
2183 unsigned char *result;
2184 size_t len;
2186 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2187 if (rc)
2188 return send_error (ctx, rc);
2190 line = (char *) result;
2193 rc = do_attr (ctx, line);
2195 if (client->opts & OPT_INQUIRE)
2196 xfree (line);
2198 return send_error (ctx, rc);
2201 static gpg_error_t
2202 parse_iscached_opt_lock (void *data, void *value)
2204 struct client_s *client = data;
2206 (void) value;
2207 client->opts |= OPT_LOCK;
2208 return 0;
2211 static gpg_error_t
2212 iscached_command (assuan_context_t ctx, char *line)
2214 struct client_s *client = assuan_get_pointer (ctx);
2215 gpg_error_t rc;
2216 unsigned char md5file[16];
2217 struct argv_s *args[] = {
2218 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_iscached_opt_lock},
2219 NULL
2222 if (!line || !*line)
2223 return send_error (ctx, GPG_ERR_SYNTAX);
2225 rc = parse_options (&line, args, client);
2226 if (rc)
2227 return send_error (ctx, rc);
2228 else if (!valid_filename (line))
2229 return send_error (ctx, GPG_ERR_INV_VALUE);
2231 rc = cache_iscached (line, NULL);
2232 if (client->opts & OPT_LOCK
2233 && (!rc || gpg_err_code (rc) == GPG_ERR_NO_DATA))
2235 gpg_error_t trc = rc;
2236 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2237 if (memcmp (md5file, client->md5file, 16))
2238 cleanup_client (client);
2240 memcpy (client->md5file, md5file, 16);
2241 rc = do_lock (client, 1);
2242 if (!rc)
2243 rc = trc;
2246 return send_error (ctx, rc);
2249 static gpg_error_t
2250 clearcache_command (assuan_context_t ctx, char *line)
2252 gpg_error_t rc = 0, all_rc = 0;
2253 unsigned char md5file[16];
2254 int i;
2255 int t;
2256 int all = 0;
2257 struct client_thread_s *once = NULL;
2259 cache_lock ();
2260 MUTEX_LOCK (&cn_mutex);
2261 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
2263 if (!line || !*line)
2264 all = 1;
2266 t = slist_length (cn_thread_list);
2268 for (i = 0; i < t; i++)
2270 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2271 assuan_peercred_t peer;
2273 if (!thd->cl)
2274 continue;
2276 /* Lock each connected clients' file mutex to prevent any other client
2277 * from accessing the cache entry (the file mutex is locked upon
2278 * command startup). The cache for the entry is not cleared if the
2279 * file mutex is locked by another client to prevent this function
2280 * from blocking.
2282 if (all)
2284 if (thd->cl->filename)
2286 rc = do_validate_peer (ctx, thd->cl->filename, &peer);
2287 all_rc = !all_rc ? rc : all_rc;
2288 if (rc)
2290 rc = 0;
2291 continue;
2295 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0, -1);
2296 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2298 if (pthread_equal (pthread_self (), thd->tid))
2299 rc = 0;
2300 else
2302 if (!thd->cl->filename ||
2303 cache_iscached (thd->cl->filename,
2304 NULL) == GPG_ERR_NO_DATA)
2306 rc = 0;
2307 continue;
2310 cache_defer_clear (thd->cl->md5file);
2313 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
2315 rc = 0;
2316 continue;
2319 if (!rc)
2321 rc = cache_clear (thd->cl->md5file);
2322 cache_unlock_mutex (thd->cl->md5file, 0);
2325 if (rc)
2326 all_rc = rc;
2328 rc = 0;
2330 /* A single data filename was specified. Lock only this data file
2331 * mutex and free the cache entry. */
2332 else
2334 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2335 rc = do_validate_peer (ctx, line, &peer);
2337 if (!rc && !memcmp (thd->cl->md5file, md5file, sizeof (md5file)))
2339 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0,
2340 -1);
2341 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2343 if (pthread_equal (pthread_self (), thd->tid))
2344 rc = 0;
2347 if (!rc)
2349 once = thd;
2350 rc = cache_clear (thd->cl->md5file);
2351 cache_unlock_mutex (thd->cl->md5file, 0);
2353 else
2355 cache_defer_clear (thd->cl->md5file);
2358 break;
2363 /* Only connected clients' cache entries have been cleared. Now clear any
2364 * remaining cache entries without clients but only if there wasn't an
2365 * error from above since this would defeat the locking check of the
2366 * remaining entries. */
2367 if (!all_rc && all)
2369 cache_clear (NULL);
2372 /* No clients are using the specified file. */
2373 else if (!all_rc && !rc && !once)
2375 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2376 rc = cache_clear (md5file);
2379 /* Release the connection mutex. */
2380 pthread_cleanup_pop (1);
2381 cache_unlock ();
2383 if (!rc)
2384 send_status_all (STATUS_CACHE, NULL);
2386 /* One or more files were locked while clearing all cache entries. */
2387 if (all_rc)
2388 rc = all_rc;
2390 return send_error (ctx, rc);
2393 static gpg_error_t
2394 cachetimeout_command (assuan_context_t ctx, char *line)
2396 unsigned char md5file[16];
2397 int timeout;
2398 char **req = str_split (line, " ", 0);
2399 char *p;
2400 gpg_error_t rc = 0;
2401 assuan_peercred_t peer;
2403 if (!req || !*req || !req[1])
2405 strv_free (req);
2406 return send_error (ctx, GPG_ERR_SYNTAX);
2409 errno = 0;
2410 timeout = (int) strtol (req[1], &p, 10);
2411 if (errno != 0 || *p || timeout < -1)
2413 strv_free (req);
2414 return send_error (ctx, GPG_ERR_SYNTAX);
2417 rc = do_validate_peer (ctx, req[0], &peer);
2418 if (!rc)
2420 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, req[0], strlen (req[0]));
2421 rc = cache_set_timeout (md5file, timeout);
2422 if (!rc || gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
2424 rc = 0;
2425 MUTEX_LOCK (&rcfile_mutex);
2426 config_set_int_param (&global_config, req[0], "cache_timeout",
2427 req[1]);
2428 MUTEX_UNLOCK (&rcfile_mutex);
2432 strv_free (req);
2433 return send_error (ctx, rc);
2436 static gpg_error_t
2437 dump_command (assuan_context_t ctx, char *line)
2439 xmlChar *xml;
2440 int len;
2441 struct client_s *client = assuan_get_pointer (ctx);
2442 gpg_error_t rc;
2444 if (disable_list_and_dump == 1)
2445 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2447 xmlDocDumpFormatMemory (client->doc, &xml, &len, 1);
2449 if (!xml)
2451 log_write ("%s(%i): %s", __FILE__, __LINE__,
2452 pwmd_strerror (GPG_ERR_ENOMEM));
2453 return send_error (ctx, GPG_ERR_ENOMEM);
2456 pthread_cleanup_push (xmlFree, xml);
2457 rc = xfer_data (ctx, (char *) xml, len);
2458 pthread_cleanup_pop (1);
2459 return send_error (ctx, rc);
2462 static gpg_error_t
2463 getconfig_command (assuan_context_t ctx, char *line)
2465 struct client_s *client = assuan_get_pointer (ctx);
2466 gpg_error_t rc = 0;
2467 char filename[255] = { 0 }, param[747] = { 0 };
2468 char *p, *tmp = NULL, *fp = client->filename, *paramp = line;
2470 if (!line || !*line)
2471 return send_error (ctx, GPG_ERR_SYNTAX);
2473 if (strchr (line, ' '))
2475 sscanf (line, " %254[^ ] %746c", filename, param);
2476 paramp = param;
2477 fp = filename;
2480 if (fp && !valid_filename (fp))
2481 return send_error (ctx, GPG_ERR_INV_VALUE);
2483 paramp = str_down (paramp);
2484 if (!strcmp (paramp, "cipher") && fp)
2486 struct crypto_s *crypto = NULL;
2488 rc = init_client_crypto (&crypto);
2489 if (!rc)
2491 rc = read_data_header (fp, &crypto->hdr, NULL, NULL);
2492 if (!rc)
2494 const char *t =
2495 gcry_cipher_algo_name (cipher_to_gcrypt (crypto->hdr.flags));
2496 if (t)
2498 tmp = str_dup (t);
2499 if (tmp)
2500 str_down (tmp);
2505 UPDATE_AGENT_CTX (client, crypto);
2506 cleanup_crypto (&crypto);
2507 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
2508 return send_error (ctx, rc);
2510 if (!rc && tmp)
2511 goto done;
2513 else if (!strcmp (paramp, "cipher_iterations") && fp)
2515 struct crypto_s *crypto = NULL;
2517 rc = init_client_crypto (&crypto);
2518 if (!rc)
2520 rc = read_data_header (fp, &crypto->hdr, NULL, NULL);
2521 if (!rc)
2523 tmp = str_asprintf ("%llu",
2524 (unsigned long long) crypto->hdr.
2525 iterations);
2526 if (!tmp)
2527 rc = GPG_ERR_ENOMEM;
2531 UPDATE_AGENT_CTX (client, crypto);
2532 cleanup_crypto (&crypto);
2533 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
2534 return send_error (ctx, rc);
2536 if (!rc && tmp)
2537 goto done;
2539 else if (!strcmp (paramp, "passphrase"))
2540 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2542 p = config_get_value (fp ? fp : "global", paramp);
2543 if (!p)
2544 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2546 tmp = expand_homedir (p);
2547 xfree (p);
2548 if (!tmp)
2550 log_write ("%s(%i): %s", __FILE__, __LINE__,
2551 pwmd_strerror (GPG_ERR_ENOMEM));
2552 return send_error (ctx, GPG_ERR_ENOMEM);
2555 done:
2556 p = tmp;
2557 pthread_cleanup_push (xfree, p);
2558 rc = xfer_data (ctx, p, strlen (p));
2559 pthread_cleanup_pop (1);
2560 return send_error (ctx, rc);
2563 struct xpath_s
2565 xmlXPathContextPtr xp;
2566 xmlXPathObjectPtr result;
2567 xmlBufferPtr buf;
2568 char **req;
2571 static void
2572 xpath_command_cleanup (void *arg)
2574 struct xpath_s *xpath = arg;
2576 if (!xpath)
2577 return;
2579 req_cleanup (xpath->req);
2581 if (xpath->buf)
2582 xmlBufferFree (xpath->buf);
2584 if (xpath->result)
2585 xmlXPathFreeObject (xpath->result);
2587 if (xpath->xp)
2588 xmlXPathFreeContext (xpath->xp);
2591 static gpg_error_t
2592 do_xpath (assuan_context_t ctx, char *line)
2594 gpg_error_t rc;
2595 struct client_s *client = assuan_get_pointer (ctx);
2596 struct xpath_s _x = { 0 };
2597 struct xpath_s *xpath = &_x;
2599 if ((xpath->req = str_split (line, "\t", 2)) == NULL)
2601 if (strv_printf (&xpath->req, "%s", line) == 0)
2602 return GPG_ERR_ENOMEM;
2605 xpath->xp = xmlXPathNewContext (client->doc);
2606 if (!xpath->xp)
2608 rc = GPG_ERR_BAD_DATA;
2609 goto fail;
2612 xpath->result =
2613 xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2614 if (!xpath->result)
2616 rc = GPG_ERR_BAD_DATA;
2617 goto fail;
2620 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2622 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2623 goto fail;
2626 rc = recurse_xpath_nodeset (client->doc, xpath->result->nodesetval,
2627 (xmlChar *) xpath->req[1], &xpath->buf, 0,
2628 NULL);
2629 if (rc)
2630 goto fail;
2631 else if (!xpath->req[1] && !xmlBufferLength (xpath->buf))
2633 rc = GPG_ERR_NO_DATA;
2634 goto fail;
2636 else if (xpath->req[1])
2638 rc = 0;
2639 goto fail;
2642 pthread_cleanup_push (xpath_command_cleanup, &xpath);
2643 rc = xfer_data (ctx, (char *) xmlBufferContent (xpath->buf),
2644 xmlBufferLength (xpath->buf));
2645 pthread_cleanup_pop (0);
2646 fail:
2647 xpath_command_cleanup (xpath);
2648 return rc;
2651 static gpg_error_t
2652 xpath_command (assuan_context_t ctx, char *line)
2654 struct client_s *client = assuan_get_pointer (ctx);
2655 gpg_error_t rc;
2656 struct argv_s *args[] = {
2657 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2658 NULL
2661 if (disable_list_and_dump == 1)
2662 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2664 rc = parse_options (&line, args, client);
2665 if (rc)
2666 return send_error (ctx, rc);
2668 if (client->opts & OPT_INQUIRE)
2670 unsigned char *result;
2671 size_t len;
2673 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2674 if (rc)
2675 return send_error (ctx, rc);
2677 line = (char *) result;
2680 if (!line || !*line)
2681 rc = GPG_ERR_SYNTAX;
2683 if (!rc)
2684 rc = do_xpath (ctx, line);
2686 if (client->opts & OPT_INQUIRE)
2687 xfree (line);
2689 return send_error (ctx, rc);
2692 static gpg_error_t
2693 do_xpathattr (assuan_context_t ctx, char *line)
2695 struct client_s *client = assuan_get_pointer (ctx);
2696 gpg_error_t rc;
2697 char **req = NULL;
2698 int cmd = 0; //SET
2699 struct xpath_s _x = { 0 };
2700 struct xpath_s *xpath = &_x;
2702 if ((req = str_split (line, " ", 3)) == NULL)
2703 return GPG_ERR_ENOMEM;
2705 if (!req[0])
2707 rc = GPG_ERR_SYNTAX;
2708 goto fail;
2711 if (!strcasecmp (req[0], "SET"))
2712 cmd = 0;
2713 else if (!strcasecmp (req[0], "DELETE"))
2714 cmd = 1;
2715 else
2717 rc = GPG_ERR_SYNTAX;
2718 goto fail;
2721 if (!req[1] || !req[2])
2723 rc = GPG_ERR_SYNTAX;
2724 goto fail;
2727 if ((xpath->req = str_split (req[2], "\t", 3)) == NULL)
2729 rc = GPG_ERR_ENOMEM;
2730 goto fail;
2733 if (!xpath->req[0] || (!xpath->req[1] && !cmd) || (xpath->req[1] && cmd))
2735 rc = GPG_ERR_SYNTAX;
2736 goto fail;
2739 xpath->xp = xmlXPathNewContext (client->doc);
2740 if (!xpath->xp)
2742 rc = GPG_ERR_BAD_DATA;
2743 goto fail;
2746 xpath->result = xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2747 if (!xpath->result)
2749 rc = GPG_ERR_BAD_DATA;
2750 goto fail;
2753 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2755 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2756 goto fail;
2759 rc = recurse_xpath_nodeset (client->doc, xpath->result->nodesetval,
2760 (xmlChar *) xpath->req[1], &xpath->buf, cmd,
2761 (xmlChar *) req[1]);
2763 fail:
2764 xpath_command_cleanup (xpath);
2765 strv_free (req);
2766 return rc;
2769 /* XPATHATTR SET|DELETE <name> <expression>[<TAB>[value]] */
2770 static gpg_error_t
2771 xpathattr_command (assuan_context_t ctx, char *line)
2773 struct client_s *client = assuan_get_pointer (ctx);
2774 gpg_error_t rc;
2775 struct argv_s *args[] = {
2776 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2777 NULL
2780 if (disable_list_and_dump == 1)
2781 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2783 rc = parse_options (&line, args, client);
2784 if (rc)
2785 return send_error (ctx, rc);
2787 if (client->opts & OPT_INQUIRE)
2789 unsigned char *result;
2790 size_t len;
2792 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2793 if (rc)
2794 return send_error (ctx, rc);
2796 line = (char *) result;
2799 if (!line || !*line)
2800 rc = GPG_ERR_SYNTAX;
2802 if (!rc)
2803 rc = do_xpathattr (ctx, line);
2805 if (client->opts & OPT_INQUIRE)
2806 xfree (line);
2808 return send_error (ctx, rc);
2811 static gpg_error_t
2812 do_import (struct client_s *client, const char *root_element,
2813 unsigned char *content)
2815 char **dst_path = NULL;
2816 xmlDocPtr doc = NULL;
2817 xmlNodePtr n, root, copy;
2818 gpg_error_t rc;
2820 if (!content || !*content)
2822 xfree (content);
2823 return GPG_ERR_SYNTAX;
2826 if (root_element)
2827 dst_path = str_split (root_element, "\t", 0);
2829 if (dst_path && !valid_element_path (dst_path, 0))
2831 if (dst_path)
2832 strv_free (dst_path);
2834 return GPG_ERR_INV_VALUE;
2837 struct string_s *str = string_new_content ((char *)content);
2838 str = string_prepend (str, "<pwmd>");
2839 str = string_append (str, "</pwmd>");
2840 doc = xmlReadDoc ((xmlChar *) str->str, NULL, "UTF-8", XML_PARSE_NOBLANKS);
2841 string_free (str, 1);
2842 if (!doc)
2844 rc = GPG_ERR_BAD_DATA;
2845 goto fail;
2848 root = xmlDocGetRootElement (doc);
2849 xmlNodePtr root_orig = root->children;
2850 root = root->children;
2851 rc = validate_import (root);
2852 if (rc)
2853 goto fail;
2857 again:
2858 if (dst_path)
2860 char **path = strv_dup (dst_path);
2861 if (!path)
2863 log_write ("%s(%i): %s", __FILE__, __LINE__,
2864 pwmd_strerror (GPG_ERR_ENOMEM));
2865 rc = GPG_ERR_ENOMEM;
2866 goto fail;
2869 xmlChar *a = xmlGetProp (root, (xmlChar *) "_name");
2870 if (!a)
2872 strv_free (path);
2873 rc = GPG_ERR_ENOMEM;
2874 goto fail;
2877 if (strv_printf (&path, "%s", (char *) a) == 0)
2879 xmlFree (a);
2880 rc = GPG_ERR_ENOMEM;
2881 goto fail;
2884 xmlFree (a);
2885 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
2886 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2888 strv_free (path);
2889 goto fail;
2892 if (!rc)
2894 n = find_elements (client->doc, n->children, path + 1, &rc,
2895 NULL, NULL, NULL, 0, 0, NULL, 1);
2896 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2898 strv_free (path);
2899 goto fail;
2901 else if (!rc)
2903 xmlUnlinkNode (n);
2904 xmlFreeNode (n);
2905 strv_free (path);
2906 path = NULL;
2907 goto again;
2911 if (rc == GPG_ERR_ELEMENT_NOT_FOUND)
2913 n = create_element_path (client, &path, &rc, NULL);
2914 if (rc)
2915 goto fail;
2918 if (root->children)
2920 copy = xmlCopyNodeList (root->children);
2921 n = xmlAddChildList (n, copy);
2922 if (!n)
2923 rc = GPG_ERR_ENOMEM;
2926 strv_free (path);
2928 else
2930 char **path = NULL;
2932 /* Check if the content root element can create a DTD root element. */
2933 if (!xmlStrEqual ((xmlChar *) "element", root->name))
2935 rc = GPG_ERR_SYNTAX;
2936 goto fail;
2939 xmlChar *a;
2941 if ((a = xmlGetProp (root, (xmlChar *) "_name")) == NULL)
2943 rc = GPG_ERR_SYNTAX;
2944 goto fail;
2947 char *tmp = str_dup ((char *) a);
2948 xmlFree (a);
2949 int literal = is_literal_element (&tmp);
2951 if (!valid_xml_element ((xmlChar *) tmp) || literal)
2953 xfree (tmp);
2954 rc = GPG_ERR_INV_VALUE;
2955 goto fail;
2958 if (strv_printf (&path, "%s", tmp) == 0)
2960 xfree (tmp);
2961 rc = GPG_ERR_ENOMEM;
2962 goto fail;
2965 xfree (tmp);
2966 n = find_root_element (client->doc, &path, &rc, NULL, 0, 1);
2967 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2969 rc = GPG_ERR_BAD_DATA;
2970 goto fail;
2973 /* Overwriting the existing tree. */
2974 if (!rc)
2976 xmlUnlinkNode (n);
2977 xmlFreeNodeList (n);
2980 rc = 0;
2981 xmlSetProp (root, (xmlChar *) "_name", (xmlChar *) path[0]);
2982 n = xmlCopyNode (root, 1);
2983 n = xmlAddChildList (xmlDocGetRootElement (client->doc), n);
2984 strv_free (path);
2987 if (n && !rc)
2988 rc = update_element_mtime (n->parent);
2990 for (root = root_orig->next; root; root = root->next)
2992 if (root->type == XML_ELEMENT_NODE)
2993 break;
2996 root_orig = root;
2998 while (root);
3000 fail:
3001 if (doc)
3002 xmlFreeDoc (doc);
3004 if (dst_path)
3005 strv_free (dst_path);
3007 return rc;
3010 static gpg_error_t
3011 parse_import_opt_root (void *data, void *value)
3013 struct client_s *client = data;
3015 client->import_root = str_dup (value);
3016 return client->import_root ? 0 : GPG_ERR_ENOMEM;
3019 static gpg_error_t
3020 import_command (assuan_context_t ctx, char *line)
3022 gpg_error_t rc;
3023 struct client_s *client = assuan_get_pointer (ctx);
3024 unsigned char *result;
3025 size_t len;
3026 struct argv_s *args[] = {
3027 &(struct argv_s) {"root", OPTION_TYPE_ARG, parse_import_opt_root},
3028 NULL
3031 xfree (client->import_root);
3032 client->import_root = NULL;
3033 rc = parse_options (&line, args, client);
3034 if (rc)
3035 return send_error (ctx, rc);
3037 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3038 if (rc)
3039 return send_error (ctx, rc);
3041 rc = do_import (client, client->import_root, result);
3042 xfree (client->import_root);
3043 client->import_root = NULL;
3044 return send_error (ctx, rc);
3047 static gpg_error_t
3048 do_lock (struct client_s *client, int add)
3050 gpg_error_t rc = lock_file_mutex (client, add);
3052 if (!rc)
3053 client->flags |= FLAG_LOCK_CMD;
3055 return rc;
3058 static gpg_error_t
3059 lock_command (assuan_context_t ctx, char *line)
3061 struct client_s *client = assuan_get_pointer (ctx);
3062 gpg_error_t rc = do_lock (client, 0);
3064 return send_error (ctx, rc);
3067 static gpg_error_t
3068 unlock_command (assuan_context_t ctx, char *line)
3070 struct client_s *client = assuan_get_pointer (ctx);
3071 gpg_error_t rc;
3073 rc = unlock_file_mutex (client, 0);
3074 return send_error (ctx, rc);
3077 static gpg_error_t
3078 option_command (assuan_context_t ctx, char *line)
3080 struct client_s *client = assuan_get_pointer (ctx);
3081 gpg_error_t rc = 0;
3082 struct pinentry_option_s *pin_opts = &client->pinentry_opts;
3083 #ifdef WITH_AGENT
3084 struct agent_s *agent = client->crypto->agent;
3085 #endif
3086 char namebuf[255] = { 0 };
3087 char *name = namebuf;
3088 char *value = NULL, *p;
3090 p = strchr (line, '=');
3091 if (!p)
3092 strncpy (namebuf, line, sizeof(namebuf));
3093 else
3095 strncpy (namebuf, line, strlen (line)-strlen (p));
3096 value = p+1;
3099 log_write1 ("OPTION name='%s' value='%s'", name, value);
3101 if (strcasecmp (name, (char *) "log_level") == 0)
3103 long l = 0;
3105 if (value)
3107 l = strtol (value, NULL, 10);
3109 if (l < 0 || l > 2)
3110 return send_error (ctx, GPG_ERR_INV_VALUE);
3113 MUTEX_LOCK (&rcfile_mutex);
3114 config_set_int_param (&global_config, "global", "log_level", value);
3115 MUTEX_UNLOCK (&rcfile_mutex);
3116 goto done;
3118 else if (strcasecmp (name, (char *) "lock-timeout") == 0)
3120 long n = 0;
3121 char *p = NULL;
3123 if (value)
3125 n = strtol (value, &p, 10);
3126 if (p && *p)
3127 return send_error (ctx, GPG_ERR_INV_VALUE);
3130 client->lock_timeout = n;
3131 goto done;
3133 else if (strcasecmp (name, (char *) "NAME") == 0)
3135 char *tmp = pthread_getspecific (thread_name_key);
3137 if (tmp)
3138 xfree (tmp);
3140 if (!value || !*value)
3142 pthread_setspecific (thread_name_key, str_dup (""));
3143 goto done;
3146 pthread_setspecific (thread_name_key, str_dup (value));
3147 goto done;
3149 else if (strcasecmp (name, (char *) "lc-messages") == 0)
3151 xfree (pin_opts->lc_messages);
3152 pin_opts->lc_messages = NULL;
3153 if (value && *value)
3154 pin_opts->lc_messages = str_dup (value);
3155 #ifdef WITH_AGENT
3156 if (use_agent)
3157 rc = set_agent_option (client->crypto->agent, "lc-messages", value);
3158 #endif
3160 else if (strcasecmp (name, (char *) "lc-ctype") == 0)
3162 xfree (pin_opts->lc_ctype);
3163 pin_opts->lc_ctype = NULL;
3164 if (value && *value)
3165 pin_opts->lc_ctype = str_dup (value);
3166 #ifdef WITH_AGENT
3167 if (use_agent)
3168 rc = set_agent_option (client->crypto->agent, "lc-ctype", value);
3169 #endif
3171 else if (strcasecmp (name, (char *) "ttyname") == 0)
3173 xfree (pin_opts->ttyname);
3174 pin_opts->ttyname = NULL;
3175 if (value && *value)
3176 pin_opts->ttyname = str_dup (value);
3177 #ifdef WITH_AGENT
3178 if (use_agent)
3179 rc = set_agent_option (client->crypto->agent, "ttyname", value);
3180 #endif
3182 else if (strcasecmp (name, (char *) "ttytype") == 0)
3184 xfree (pin_opts->ttytype);
3185 pin_opts->ttytype = NULL;
3186 if (value && *value)
3187 pin_opts->ttytype = str_dup (value);
3188 #ifdef WITH_AGENT
3189 if (use_agent)
3190 rc = set_agent_option (client->crypto->agent, "ttytype", value);
3191 #endif
3193 else if (strcasecmp (name, (char *) "display") == 0)
3195 xfree (pin_opts->display);
3196 pin_opts->display = NULL;
3197 if (value && *value)
3198 pin_opts->display = str_dup (value);
3199 #ifdef WITH_AGENT
3200 if (use_agent)
3201 rc = set_agent_option (client->crypto->agent, "display", value);
3202 #endif
3204 else if (strcasecmp (name, (char *) "pinentry-desc") == 0)
3206 xfree (pin_opts->desc);
3207 pin_opts->desc = NULL;
3208 if (value && *value)
3209 pin_opts->desc = str_dup (value);
3211 else if (strcasecmp (name, (char *) "pinentry-title") == 0)
3213 xfree (pin_opts->title);
3214 pin_opts->title = NULL;
3215 if (value && *value)
3216 pin_opts->title = str_dup (value);
3218 else if (strcasecmp (name, (char *) "pinentry-prompt") == 0)
3220 xfree (pin_opts->prompt);
3221 pin_opts->prompt = NULL;
3222 if (value && *value)
3223 pin_opts->prompt = str_dup (value);
3226 else if (strcasecmp (name, "pinentry-timeout") == 0)
3228 char *p = NULL;
3229 int n;
3231 if (!value)
3232 goto done;
3234 n = (int) strtol (value, &p, 10);
3236 if (*p || n < 0)
3237 return send_error (ctx, GPG_ERR_INV_VALUE);
3239 pin_opts->timeout = n;
3240 MUTEX_LOCK (&rcfile_mutex);
3241 config_set_int_param (&global_config,
3242 client->filename ? client->filename : "global",
3243 "pinentry_timeout", value);
3244 MUTEX_UNLOCK (&rcfile_mutex);
3245 goto done;
3247 else if (strcasecmp (name, "disable-pinentry") == 0)
3249 char *p = NULL;
3250 int n = 1;
3252 if (value && *value)
3254 n = (int) strtol (value, &p, 10);
3255 if (*p || n < 0 || n > 1)
3256 return send_error (ctx, GPG_ERR_INV_VALUE);
3259 if (n)
3260 client->flags |= FLAG_NO_PINENTRY;
3261 else
3262 client->flags &= ~FLAG_NO_PINENTRY;
3264 else
3265 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
3267 done:
3268 #ifdef WITH_AGENT
3269 if (!rc && use_agent && agent)
3271 rc = pinentry_merge_options (&client->crypto->agent->pinentry_opts,
3272 pin_opts);
3274 #endif
3276 return send_error (ctx, rc);
3279 static gpg_error_t
3280 do_rename (assuan_context_t ctx, char *line)
3282 struct client_s *client = assuan_get_pointer (ctx);
3283 gpg_error_t rc;
3284 char **req, **src, *dst;
3285 xmlNodePtr n, ndst;
3287 req = str_split (line, " ", 0);
3289 if (!req || !req[0] || !req[1])
3291 strv_free (req);
3292 return GPG_ERR_SYNTAX;
3295 dst = req[1];
3296 is_literal_element (&dst);
3298 if (!valid_xml_element ((xmlChar *) dst))
3300 strv_free (req);
3301 return GPG_ERR_INV_VALUE;
3304 if (strchr (req[0], '\t'))
3305 src = str_split (req[0], "\t", 0);
3306 else
3307 src = str_split (req[0], " ", 0);
3309 if (!src || !*src)
3311 rc = GPG_ERR_SYNTAX;
3312 goto fail;
3315 n = find_root_element (client->doc, &src, &rc, NULL, 0, 0);
3316 if (src[1] && n)
3317 n = find_elements (client->doc, n->children, src + 1, &rc, NULL, NULL,
3318 NULL, 0, 0, NULL, 0);
3320 if (!n)
3321 goto fail;
3323 xmlChar *a = xmlGetProp (n, (xmlChar *) "_name");
3324 if (!a)
3326 rc = GPG_ERR_ENOMEM;
3327 goto fail;
3330 /* To prevent unwanted effects:
3332 * <root name="a"><b/></root>
3334 * RENAME a<TAB>b b
3336 if (xmlStrEqual (a, (xmlChar *) dst))
3338 xmlFree (a);
3339 rc = GPG_ERR_AMBIGUOUS_NAME;
3340 goto fail;
3343 xmlFree (a);
3344 char **tmp = NULL;
3345 if (src[1])
3347 char **p;
3349 for (p = src; *p; p++)
3351 if (!*(p + 1))
3352 break;
3353 strv_printf (&tmp, "%s", *p);
3357 strv_printf (&tmp, "!%s", dst);
3358 ndst = find_root_element (client->doc, &tmp, &rc, NULL, 0, 0);
3359 if (!ndst && rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3361 strv_free (tmp);
3362 goto fail;
3365 if (tmp[1] && ndst)
3366 ndst = find_elements (client->doc, ndst->children, tmp + 1, &rc, NULL,
3367 NULL, NULL, 0, 0, NULL, 0);
3369 strv_free (tmp);
3370 if (!ndst && rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3371 goto fail;
3373 rc = 0;
3375 /* Target may exist:
3377 * <root name="a"/>
3378 * <root name="b" target="a"/>
3380 * RENAME b a
3382 * Would need to do:
3383 * RENAME !b a
3385 if (ndst == n)
3387 rc = GPG_ERR_AMBIGUOUS_NAME;
3388 goto fail;
3391 if (ndst)
3393 unlink_node (ndst);
3394 xmlFreeNodeList (ndst);
3397 rc = add_attribute (n, "_name", dst);
3399 fail:
3400 strv_free (req);
3401 strv_free (src);
3402 return rc;
3405 static gpg_error_t
3406 rename_command (assuan_context_t ctx, char *line)
3408 struct client_s *client = assuan_get_pointer (ctx);
3409 gpg_error_t rc;
3410 struct argv_s *args[] = {
3411 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3412 NULL
3415 rc = parse_options (&line, args, client);
3416 if (rc)
3417 return send_error (ctx, rc);
3419 if (client->opts & OPT_INQUIRE)
3421 unsigned char *result;
3422 size_t len;
3424 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3425 if (rc)
3426 return send_error (ctx, rc);
3428 line = (char *) result;
3431 rc = do_rename (ctx, line);
3433 if (client->opts & OPT_INQUIRE)
3434 xfree (line);
3436 return send_error (ctx, rc);
3439 static gpg_error_t
3440 do_copy (assuan_context_t ctx, char *line)
3442 struct client_s *client = assuan_get_pointer (ctx);
3443 gpg_error_t rc;
3444 char **req, **src = NULL, **dst = NULL;
3445 xmlNodePtr nsrc, ndst, new = NULL;
3447 req = str_split (line, " ", 0);
3448 if (!req || !req[0] || !req[1])
3450 strv_free (req);
3451 return GPG_ERR_SYNTAX;
3454 if (strchr (req[0], '\t'))
3455 src = str_split (req[0], "\t", 0);
3456 else
3457 src = str_split (req[0], " ", 0);
3459 if (!src || !*src)
3461 rc = GPG_ERR_SYNTAX;
3462 goto fail;
3465 if (strchr (req[1], '\t'))
3466 dst = str_split (req[1], "\t", 0);
3467 else
3468 dst = str_split (req[1], " ", 0);
3470 if (!dst || !*dst)
3472 rc = GPG_ERR_SYNTAX;
3473 goto fail;
3476 if (!valid_element_path (dst, 0))
3478 rc = GPG_ERR_INV_VALUE;
3479 goto fail;
3482 nsrc = find_root_element (client->doc, &src, &rc, NULL, 0, 0);
3483 if (nsrc && src[1])
3484 nsrc = find_elements (client->doc, nsrc->children, src + 1, &rc, NULL,
3485 NULL, NULL, 0, 0, NULL, 0);
3487 if (!nsrc)
3488 goto fail;
3490 new = xmlCopyNodeList (nsrc);
3491 if (!new)
3493 rc = GPG_ERR_ENOMEM;
3494 goto fail;
3497 int create = 0;
3498 ndst = find_root_element (client->doc, &dst, &rc, NULL, 0, 0);
3499 if (ndst && dst[1])
3501 if (ndst->children)
3502 ndst = find_elements (client->doc, ndst->children, dst + 1, &rc, NULL,
3503 NULL, create_target_elements_cb, 0, 0, NULL, 0);
3504 else
3505 create = 1;
3507 else
3508 create = 1;
3510 if (!ndst && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3511 goto fail;
3512 else if (!ndst || create)
3514 ndst = create_element_path (client, &dst, &rc, NULL);
3515 if (!ndst)
3516 goto fail;
3519 /* Merge any attributes from the src node to the initial dst node. */
3520 for (xmlAttrPtr attr = new->properties; attr; attr = attr->next)
3522 if (xmlStrEqual (attr->name, (xmlChar *) "_name"))
3523 continue;
3525 xmlAttrPtr a = xmlHasProp (ndst, attr->name);
3526 if (a)
3527 xmlRemoveProp (a);
3529 xmlChar *tmp = xmlNodeGetContent (attr->children);
3530 xmlNewProp (ndst, attr->name, tmp);
3531 xmlFree (tmp);
3532 rc = add_attribute (ndst, NULL, NULL);
3535 xmlNodePtr n = ndst->children;
3536 xmlUnlinkNode (n);
3537 xmlFreeNodeList (n);
3538 ndst->children = NULL;
3540 if (new->children)
3542 n = xmlCopyNodeList (new->children);
3543 if (!n)
3545 rc = GPG_ERR_ENOMEM;
3546 goto fail;
3549 n = xmlAddChildList (ndst, n);
3550 if (!n)
3552 rc = GPG_ERR_ENOMEM;
3553 goto fail;
3556 rc = update_element_mtime (xmlDocGetRootElement (client->doc) ==
3557 ndst->parent ? ndst : ndst->parent);
3560 fail:
3561 if (new)
3563 xmlUnlinkNode (new);
3564 xmlFreeNodeList (new);
3567 if (req)
3568 strv_free (req);
3570 if (src)
3571 strv_free (src);
3573 if (dst)
3574 strv_free (dst);
3576 return rc;
3579 static gpg_error_t
3580 copy_command (assuan_context_t ctx, char *line)
3582 struct client_s *client = assuan_get_pointer (ctx);
3583 gpg_error_t rc;
3584 struct argv_s *args[] = {
3585 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3586 NULL
3589 rc = parse_options (&line, args, client);
3590 if (rc)
3591 return send_error (ctx, rc);
3593 if (client->opts & OPT_INQUIRE)
3595 unsigned char *result;
3596 size_t len;
3598 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3599 if (rc)
3600 return send_error (ctx, rc);
3602 line = (char *) result;
3605 rc = do_copy (ctx, line);
3607 if (client->opts & OPT_INQUIRE)
3608 xfree (line);
3610 return send_error (ctx, rc);
3613 static gpg_error_t
3614 do_move (assuan_context_t ctx, char *line)
3616 struct client_s *client = assuan_get_pointer (ctx);
3617 gpg_error_t rc;
3618 char **req, **src = NULL, **dst = NULL;
3619 xmlNodePtr nsrc, ndst = NULL;
3621 req = str_split (line, " ", 0);
3623 if (!req || !req[0] || !req[1])
3625 strv_free (req);
3626 return GPG_ERR_SYNTAX;
3629 if (strchr (req[0], '\t'))
3630 src = str_split (req[0], "\t", 0);
3631 else
3632 src = str_split (req[0], " ", 0);
3634 if (!src || !*src)
3636 rc = GPG_ERR_SYNTAX;
3637 goto fail;
3640 if (strchr (req[1], '\t'))
3641 dst = str_split (req[1], "\t", 0);
3642 else
3643 dst = str_split (req[1], " ", 0);
3645 nsrc = find_root_element (client->doc, &src, &rc, NULL, 0, 0);
3646 if (nsrc && src[1])
3647 nsrc = find_elements (client->doc, nsrc->children, src + 1, &rc, NULL,
3648 NULL, NULL, 0, 0, NULL, 0);
3650 if (!nsrc)
3651 goto fail;
3653 if (dst)
3655 if (!valid_element_path (dst, 0))
3657 rc = GPG_ERR_INV_VALUE;
3658 goto fail;
3661 ndst = find_root_element (client->doc, &dst, &rc, NULL, 0, 0);
3662 if (ndst && dst[1])
3663 ndst = find_elements (client->doc, ndst->children, dst + 1, &rc, NULL,
3664 NULL, NULL, 0, 0, NULL, 0);
3666 else
3667 ndst = xmlDocGetRootElement (client->doc);
3669 for (xmlNodePtr n = ndst; n; n = n->parent)
3671 if (n == nsrc)
3673 rc = GPG_ERR_CONFLICT;
3674 goto fail;
3678 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3679 goto fail;
3681 rc = 0;
3683 if (ndst)
3685 xmlChar *a = node_has_attribute (nsrc, (xmlChar *) "_name");
3686 xmlNodePtr dup = find_element (ndst->children, (char *) a, NULL);
3688 xmlFree (a);
3689 if (dup)
3691 if (dup == nsrc)
3692 goto fail;
3694 if (ndst == xmlDocGetRootElement (client->doc))
3696 xmlNodePtr n = nsrc;
3697 int match = 0;
3699 while (n->parent && n->parent != ndst)
3700 n = n->parent;
3702 xmlChar *a = node_has_attribute (n, (xmlChar *) "_name");
3703 xmlChar *b = node_has_attribute (nsrc, (xmlChar *) "_name");
3705 if (xmlStrEqual (a, b))
3707 match = 1;
3708 xmlUnlinkNode (nsrc);
3709 xmlUnlinkNode (n);
3710 xmlFreeNodeList (n);
3713 xmlFree (a);
3714 xmlFree (b);
3716 if (!match)
3718 xmlUnlinkNode (dup);
3719 xmlFreeNodeList (dup);
3722 else
3723 xmlUnlinkNode (dup);
3727 if (!ndst && dst)
3729 xmlChar *name = node_has_attribute (nsrc, (xmlChar *) "_name");
3731 if (nsrc->parent == xmlDocGetRootElement (client->doc)
3732 && !strcmp ((char *) name, *dst))
3734 xmlFree (name);
3735 rc = GPG_ERR_CONFLICT;
3736 goto fail;
3739 xmlFree (name);
3740 ndst = create_element_path (client, &dst, &rc, nsrc);
3743 if (!ndst)
3744 goto fail;
3746 update_element_mtime (nsrc->parent);
3747 xmlUnlinkNode (nsrc);
3748 ndst = xmlAddChildList (ndst, nsrc);
3750 if (!ndst)
3751 rc = GPG_ERR_ENOMEM;
3752 else
3753 update_element_mtime (ndst->parent);
3755 fail:
3756 if (req)
3757 strv_free (req);
3759 if (src)
3760 strv_free (src);
3762 if (dst)
3763 strv_free (dst);
3765 return rc;
3768 static gpg_error_t
3769 move_command (assuan_context_t ctx, char *line)
3771 struct client_s *client = assuan_get_pointer (ctx);
3772 gpg_error_t rc;
3773 struct argv_s *args[] = {
3774 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3775 NULL
3778 rc = parse_options (&line, args, client);
3779 if (rc)
3780 return send_error (ctx, rc);
3782 if (client->opts & OPT_INQUIRE)
3784 unsigned char *result;
3785 size_t len;
3787 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3788 if (rc)
3789 return send_error (ctx, rc);
3791 line = (char *) result;
3794 rc = do_move (ctx, line);
3796 if (client->opts & OPT_INQUIRE)
3797 xfree (line);
3799 return send_error (ctx, rc);
3802 static gpg_error_t
3803 ls_command (assuan_context_t ctx, char *line)
3805 gpg_error_t rc;
3806 char *tmp = str_asprintf ("%s/data", homedir);
3807 char *dir = expand_homedir (tmp);
3808 DIR *d = opendir (dir);
3810 rc = gpg_error_from_errno (errno);
3811 xfree (tmp);
3813 if (!d)
3815 xfree (dir);
3816 return send_error (ctx, rc);
3819 size_t len =
3820 offsetof (struct dirent, d_name) +pathconf (dir, _PC_NAME_MAX) + 1;
3821 struct dirent *p = xmalloc (len), *cur = NULL;
3822 char *list = NULL;
3824 xfree (dir);
3825 rc = 0;
3827 while (!readdir_r (d, p, &cur) && cur)
3829 if (cur->d_name[0] == '.' && cur->d_name[1] == '\0')
3830 continue;
3831 else if (cur->d_name[0] == '.' && cur->d_name[1] == '.'
3832 && cur->d_name[2] == '\0')
3833 continue;
3835 tmp = str_asprintf ("%s%s\n", list ? list : "", cur->d_name);
3837 if (!tmp)
3839 if (list)
3840 xfree (list);
3842 rc = GPG_ERR_ENOMEM;
3843 break;
3846 xfree (list);
3847 list = tmp;
3850 closedir (d);
3851 xfree (p);
3853 if (rc)
3854 return send_error (ctx, rc);
3856 if (!list)
3857 return send_error (ctx, GPG_ERR_NO_DATA);
3859 list[strlen (list) - 1] = 0;
3860 rc = xfer_data (ctx, list, strlen (list));
3861 xfree (list);
3862 return send_error (ctx, rc);
3865 static gpg_error_t
3866 bye_notify (assuan_context_t ctx, char *line)
3868 struct client_s *cl = assuan_get_pointer (ctx);
3870 #ifdef WITH_GNUTLS
3871 if (cl->thd->remote)
3873 int rc;
3877 struct timeval tv = { 0, 50000 };
3879 rc = gnutls_bye (cl->thd->tls->ses, GNUTLS_SHUT_RDWR);
3880 if (rc == GNUTLS_E_AGAIN)
3881 select (0, NULL, NULL, NULL, &tv);
3883 while (rc == GNUTLS_E_AGAIN);
3885 #endif
3887 /* This will let assuan_process_next() return. */
3888 fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK);
3889 cl->last_rc = 0; // BYE command result
3890 return 0;
3893 static gpg_error_t
3894 reset_notify (assuan_context_t ctx, char *line)
3896 struct client_s *client = assuan_get_pointer (ctx);
3898 if (client)
3899 cleanup_client (client);
3901 return 0;
3905 * This is called before every Assuan command.
3907 static gpg_error_t
3908 command_startup (assuan_context_t ctx, const char *name)
3910 struct client_s *client = assuan_get_pointer (ctx);
3911 gpg_error_t rc;
3912 struct command_table_s *cmd = NULL;
3914 log_write1 ("command='%s'", name);
3915 client->last_rc = client->opts = 0;
3917 for (int i = 0; command_table[i]; i++)
3919 if (!strcasecmp (name, command_table[i]->name))
3921 if (command_table[i]->ignore_startup)
3922 return 0;
3923 cmd = command_table[i];
3924 break;
3928 client->last_rc = rc = gpg_error (file_modified (client, cmd));
3929 return rc;
3933 * This is called after every Assuan command.
3935 static void
3936 command_finalize (assuan_context_t ctx, gpg_error_t rc)
3938 struct client_s *client = assuan_get_pointer (ctx);
3940 if (!(client->flags & FLAG_LOCK_CMD))
3941 unlock_file_mutex (client, 0);
3943 log_write1 (_("command completed: rc=%u"), client->last_rc);
3944 client->last_rc = gpg_error (GPG_ERR_UNKNOWN_COMMAND);
3945 #ifdef WITH_GNUTLS
3946 client->thd->buffer_timeout = client->thd->last_buffer_size = 0;
3947 #endif
3950 static gpg_error_t
3951 help_command (assuan_context_t ctx, char *line)
3953 gpg_error_t rc;
3954 int i;
3956 if (!line || !*line)
3958 char *tmp;
3959 char *help = str_dup (_("Usage: HELP [<COMMAND>]\n"
3960 "For commands that take an element path as an argument, each element is "
3961 "separated with an ASCII @key{TAB} character (ASCII 0x09)."
3962 "\n" "COMMANDS:"));
3964 for (i = 0; command_table[i]; i++)
3966 if (!command_table[i]->help)
3967 continue;
3969 tmp = str_asprintf ("%s %s", help, command_table[i]->name);
3970 xfree (help);
3971 help = tmp;
3974 tmp = strip_texi_and_wrap (help);
3975 xfree (help);
3976 rc = xfer_data (ctx, tmp, strlen (tmp));
3977 xfree (tmp);
3978 return send_error (ctx, rc);
3981 for (i = 0; command_table[i]; i++)
3983 if (!strcasecmp (line, command_table[i]->name))
3985 char *help, *tmp;
3987 if (!command_table[i]->help)
3988 break;
3990 help = strip_texi_and_wrap (command_table[i]->help);
3991 tmp = str_asprintf (_("Usage: %s"), help);
3992 xfree (help);
3993 rc = xfer_data (ctx, tmp, strlen (tmp));
3994 xfree (tmp);
3995 return send_error (ctx, rc);
3999 return send_error (ctx, GPG_ERR_INV_NAME);
4002 static void
4003 new_command (const char *name, int ignore, int unlock,
4004 gpg_error_t (*handler) (assuan_context_t, char *),
4005 const char *help)
4007 int i = 0;
4009 if (command_table)
4010 for (i = 0; command_table[i]; i++);
4012 command_table =
4013 xrealloc (command_table, (i + 2) * sizeof (struct command_table_s *));
4014 command_table[i] = xcalloc (1, sizeof (struct command_table_s));
4015 command_table[i]->name = name;
4016 command_table[i]->handler = handler;
4017 command_table[i]->ignore_startup = ignore;
4018 command_table[i]->unlock = unlock;
4019 command_table[i++]->help = help;
4020 command_table[i] = NULL;
4023 void
4024 deinit_commands ()
4026 int i;
4028 for (i = 0; command_table[i]; i++)
4029 xfree (command_table[i]);
4031 xfree (command_table);
4034 static int
4035 sort_commands (const void *arg1, const void *arg2)
4037 struct command_table_s *const *a = arg1;
4038 struct command_table_s *const *b = arg2;
4040 if (!*a || !*b)
4041 return 0;
4042 else if (*a && !*b)
4043 return 1;
4044 else if (!*a && *b)
4045 return -1;
4047 return strcmp ((*a)->name, (*b)->name);
4050 static gpg_error_t
4051 passwd_command (assuan_context_t ctx, char *line)
4053 struct client_s *client = assuan_get_pointer (ctx);
4054 gpg_error_t rc;
4055 struct argv_s *args[] = {
4056 &(struct argv_s) {"reset", OPTION_TYPE_NOARG, parse_opt_reset},
4057 &(struct argv_s) {"s2k-count", OPTION_TYPE_ARG, parse_opt_s2k_count},
4058 NULL
4061 if (client->flags & FLAG_NEW)
4062 return send_error (ctx, GPG_ERR_INV_STATE);
4064 client->crypto->save.s2k_count =
4065 config_get_ulong (client->filename, "s2k_count");
4066 rc = parse_options (&line, args, client);
4067 if (rc)
4068 return send_error (ctx, rc);
4070 if (!rc && client->opts & OPT_RESET)
4072 rc = cache_clear (client->md5file);
4073 if (!rc)
4074 send_status_all (STATUS_CACHE, NULL);
4077 if (!rc)
4079 if (!IS_PKI (client->crypto))
4081 struct crypto_s *crypto;
4083 xfree (client->crypto->filename);
4084 client->crypto->filename = str_dup (client->filename);
4085 rc = change_passwd (ctx, client->filename,
4086 client->flags & FLAG_NO_PINENTRY, &crypto);
4087 if (!rc)
4089 cleanup_crypto (&client->crypto);
4090 client->crypto = crypto;
4091 update_checksum (client);
4092 cleanup_crypto_stage1 (client->crypto);
4095 #ifdef WITH_AGENT
4096 else
4098 if (client->crypto->save.s2k_count)
4099 rc = send_to_agent (client->crypto->agent, NULL, NULL,
4100 "OPTION s2k-count=%lu",
4101 client->crypto->save.s2k_count);
4103 if (!rc)
4104 rc = agent_passwd (client->crypto);
4106 #endif
4109 return send_error (ctx, rc);
4112 static gpg_error_t
4113 parse_keygrip_opt_sign (void *data, void *value)
4115 struct client_s *client = data;
4117 (void) value;
4118 client->opts |= OPT_SIGN;
4119 return 0;
4122 static gpg_error_t
4123 keygrip_command (assuan_context_t ctx, char *line)
4125 struct client_s *client = assuan_get_pointer (ctx);
4126 gpg_error_t rc;
4127 struct crypto_s *crypto = NULL;
4128 struct argv_s *args[] = {
4129 &(struct argv_s) {"sign", OPTION_TYPE_NOARG, parse_keygrip_opt_sign},
4130 NULL
4133 if (!line || !*line)
4134 return send_error (ctx, GPG_ERR_SYNTAX);
4136 rc = parse_options (&line, args, client);
4137 if (rc)
4138 return send_error (ctx, rc);
4140 if (!valid_filename (line))
4141 return send_error (ctx, GPG_ERR_INV_VALUE);
4143 rc = init_client_crypto (&crypto);
4144 if (rc)
4145 return send_error (ctx, rc);
4147 rc = read_data_file (line, crypto);
4148 if (!rc)
4150 char *hexgrip = NULL;
4152 if (!IS_PKI (crypto))
4154 cleanup_crypto (&crypto);
4155 return send_error (ctx, GPG_ERR_NOT_SUPPORTED);
4158 if (client->opts & OPT_SIGN)
4160 if (valid_keygrip (crypto->sign_grip, sizeof (crypto->sign_grip)))
4161 hexgrip = bin2hex (crypto->sign_grip, sizeof (crypto->sign_grip));
4164 if (!hexgrip)
4165 hexgrip = bin2hex (crypto->grip, sizeof (crypto->grip));
4167 if (!hexgrip)
4168 rc = GPG_ERR_ENOMEM;
4169 else
4170 rc = xfer_data (ctx, hexgrip, strlen (hexgrip));
4172 xfree (hexgrip);
4175 UPDATE_AGENT_CTX (client, crypto);
4176 cleanup_crypto (&crypto);
4177 return send_error (ctx, rc);
4180 static gpg_error_t
4181 parse_opt_data (void *data, void *value)
4183 struct client_s *client = data;
4185 (void) value;
4186 client->opts |= OPT_DATA;
4187 return 0;
4190 static gpg_error_t
4191 getinfo_command (assuan_context_t ctx, char *line)
4193 struct client_s *client = assuan_get_pointer (ctx);
4194 gpg_error_t rc;
4195 char buf[ASSUAN_LINELENGTH];
4196 struct argv_s *args[] = {
4197 &(struct argv_s) {"data", OPTION_TYPE_NOARG, parse_opt_data},
4198 NULL
4201 rc = parse_options (&line, args, client);
4202 if (rc)
4203 return send_error (ctx, rc);
4205 if (!strcasecmp (line, "clients"))
4207 if (client->opts & OPT_DATA)
4209 MUTEX_LOCK (&cn_mutex);
4210 snprintf (buf, sizeof (buf), "%i", slist_length (cn_thread_list));
4211 MUTEX_UNLOCK (&cn_mutex);
4212 rc = xfer_data (ctx, buf, strlen (buf));
4214 else
4215 rc = send_status (ctx, STATUS_CLIENTS, NULL);
4217 else if (!strcasecmp (line, "cache"))
4219 if (client->opts & OPT_DATA)
4221 snprintf (buf, sizeof (buf), "%u", cache_file_count ());
4222 rc = xfer_data (ctx, buf, strlen (buf));
4224 else
4225 rc = send_status (ctx, STATUS_CACHE, NULL);
4227 else if (!strcasecmp (line, "pid"))
4229 char buf[32];
4230 pid_t pid = getpid ();
4232 snprintf (buf, sizeof (buf), "%i", pid);
4233 rc = xfer_data (ctx, buf, strlen (buf));
4235 else if (!strcasecmp (line, "version"))
4237 char *buf = str_asprintf ("0x%06x %s%s", VERSION_HEX,
4238 #ifdef WITH_LIBACL
4239 "ACL "
4240 #endif
4241 #ifdef WITH_GNUTLS
4242 "GNUTLS "
4243 #endif
4244 #ifdef WITH_QUALITY
4245 "QUALITY "
4246 #endif
4247 "", use_agent ? "AGENT" : "");
4248 rc = xfer_data (ctx, buf, strlen (buf));
4249 xfree (buf);
4251 else if (!strcasecmp (line, "last_error"))
4253 if (client->last_error)
4254 rc = xfer_data (ctx, client->last_error, strlen (client->last_error));
4255 else
4256 rc = GPG_ERR_NO_DATA;
4258 else
4259 rc = gpg_error (GPG_ERR_SYNTAX);
4261 return send_error (ctx, rc);
4264 #ifdef WITH_AGENT
4265 static gpg_error_t
4266 send_data_cb (void *user, const void *buf, size_t len)
4268 assuan_context_t ctx = user;
4270 return assuan_send_data (ctx, buf, len);
4273 static gpg_error_t
4274 send_status_cb (void *user, const char *line)
4276 assuan_context_t ctx = user;
4277 char keyword[200], *k;
4278 const char *p;
4280 for (p = line, k = keyword; *p; p++)
4282 if (isspace (*p))
4283 break;
4285 *k++ = *p;
4288 *k = 0;
4289 if (*p == '#')
4290 p++;
4292 while (isspace (*p))
4293 p++;
4295 return assuan_write_status (ctx, keyword, *p ? p : NULL);
4297 #endif
4299 static gpg_error_t
4300 agent_command (assuan_context_t ctx, char *line)
4302 gpg_error_t rc = 0;
4304 if (!use_agent)
4305 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
4307 #ifdef WITH_AGENT
4308 struct client_s *client = assuan_get_pointer (ctx);
4310 if (!line || !*line)
4311 return send_error (ctx, GPG_ERR_SYNTAX);
4313 assuan_set_flag (client->crypto->agent->ctx, ASSUAN_CONVEY_COMMENTS, 1);
4314 rc = assuan_transact (client->crypto->agent->ctx, line, send_data_cb,
4315 client->ctx, agent_loopback_cb, client->crypto,
4316 send_status_cb, client->ctx);
4317 if (gpg_err_code (rc) == GPG_ERR_ASS_CANCELED)
4319 char *line;
4320 size_t len;
4322 rc = assuan_write_line (client->crypto->agent->ctx, "CAN");
4323 if (!rc)
4325 rc = assuan_read_line (client->crypto->agent->ctx, &line, &len);
4326 if (!rc)
4327 rc = gpg_error (GPG_ERR_ASS_CANCELED);
4331 assuan_set_flag (client->crypto->agent->ctx, ASSUAN_CONVEY_COMMENTS, 0);
4332 #endif
4333 return send_error (ctx, rc);
4336 void
4337 init_commands ()
4339 /* !BEGIN-HELP-TEXT!
4341 * This comment is used as a marker to generate the offline documentation
4342 * found in doc/pwmd.info. The indentation needs to be kept for the awk
4343 * script to determine where commands begin and end.
4345 new_command("HELP", 1, 1, help_command, _(
4346 "HELP [<COMMAND>]\n"
4347 "Show available commands or command specific help text."
4350 new_command("AGENT", 1, 1, agent_command, _(
4351 "AGENT <command>\n"
4352 "Send a @command{gpg-agent} protocol @var{command} directly to the "
4353 "@command{gpg-agent}."
4356 new_command("GETINFO", 1, 1, getinfo_command, _(
4357 "GETINFO [--data] CACHE | CLIENTS | PID | LAST_ERROR | VERSION\n"
4358 "Get server and other information: @var{cache} returns the number of cached "
4359 "documents via a status message. @var{clients} returns the number of "
4360 "connected clients via a status message. @var{pid} returns the process ID "
4361 "number of the server via a data response. @var{VERSION} returns the server "
4362 "version number and compile-time features with a data response with each "
4363 "being space delimited. @var{LAST_ERROR} returns a detailed description of "
4364 "the last failed command when available. @xref{Status Messages}. "
4365 "\n"
4366 "When the @option{--data} option is specified then the result will be sent "
4367 "via a data response rather than a status message."
4370 new_command("PASSWD", 0, 0, passwd_command, _(
4371 "PASSWD [--reset] [--s2k-count=N]\n"
4372 "Changes the passphrase of the secret key required to open the current "
4373 "file or the passphrase of a symmetrically encrypted data file. When the "
4374 "@option{--reset} option is passed then the cache entry for the current "
4375 "file will be reset and the passphrase, if any, will be required during the "
4376 "next @code{OPEN}. @xref{OPEN}."
4377 "\n"
4378 "The @option{--s2k-count} option sets number of hash iterations for a "
4379 "passphrase and must be either @code{0} to use the calibrated count of the "
4380 "machine (the default), or a value greater than or equal to @code{65536}. "
4381 "@xref{SAVE}. This option has no effect for symmetrically encrypted data "
4382 "files."
4385 new_command("KEYGRIP", 1, 1, keygrip_command, _(
4386 "KEYGRIP [--sign] <filename>\n"
4387 "Returns the hex encoded keygrip of the specified @var{filename} with a "
4388 "data response."
4389 "\n"
4390 "When the @option{--sign} option is specified then the key used for signing "
4391 "of the specified @var{filename} will be returned."
4392 "\n"
4393 "For symmetrically encrypted data files this command returns the error "
4394 "GPG_ERR_NOT_SUPPORTED."
4397 new_command("OPEN", 1, 1, open_command, _(
4398 "OPEN [--lock] <filename> [<passphrase>]\n"
4399 "Opens @var{filename} using @var{passphrase}. When the filename is not "
4400 "found on the file-system then a new document will be created. If the file "
4401 "is found, it is looked for in the file cache. If cached and no "
4402 "@var{passphrase} was specified then the cached document is opened. When not "
4403 "cached, @cite{pinentry(1)} will be used to retrieve the passphrase to use "
4404 "for decryption unless @option{disable-pinentry} (@pxref{OPTION}) was "
4405 "specified."
4406 "\n"
4407 "When the @option{--lock} option is passed then the file mutex will be "
4408 "locked as if the @code{LOCK} command (@pxref{LOCK}) had been sent after the "
4409 "file has been opened."
4412 new_command("SAVE", 0, 0, save_command, _(
4413 "SAVE [--no-passphrase] [--reset] [--no-agent] [--s2k-count=N] [--cipher=<algo>] [--cipher-iterations=N] [--inquire-keyparam] [--keygrip=hexstring] [--sign-keygrip=hexstring]\n"
4414 "Writes the @abbr{XML} document to disk. The file written to is the file that "
4415 "was opened using the @code{OPEN} command (@pxref{OPEN}). If the file is a "
4416 "new one or the option @option{--inquire-keyparam} was passed, then a new "
4417 "keypair will be generated and a pinentry will be used to prompt for the "
4418 "passphrase to encrypt with unless the @option{--no-passphrase} option was "
4419 "passed in which case the data file will not be passphrase protected. "
4420 "\n"
4421 "The @option{--no-agent} option disables use of @command{gpg-agent} for "
4422 "passphrase retrieval and caching of new files when @command{gpg-agent} "
4423 "use is enabled. The datafile will be symmetrically encrypted and will not "
4424 "use or generate any keypair."
4425 "\n"
4426 "The @option{--reset} option will clear the cache entry for the current file "
4427 "and require a passphrase, if needed, before saving."
4428 "\n"
4429 "The @option{--cipher} option can be used to encrypt the @abbr{XML} data to "
4430 "an alternate cipher. The default is @code{aes256}. See the Configuration "
4431 "(@pxref{Configuration}) for available ciphers."
4432 "\n"
4433 "The @option{--cipher-iterations} option specifies the number of times to "
4434 "encrypt the XML data. The default is 0 although 1 iteration is still done."
4435 "\n"
4436 "The @option{--inquire-keyparam} option will send a server @emph{INQUIRE} to "
4437 "the client to obtain the key paramaters to use when generating a new "
4438 "keypair. The inquired data is expected to be an S-expression. If not "
4439 "specified then an @samp{RSA} key of @samp{2048} bits will be generated "
4440 "unless otherwise set in the configuration file (@pxref{Configuration}). Note "
4441 "that when this option is specified a new keypair will be generated "
4442 "reguardless if the file is a new one and that if the data file is protected "
4443 "the passphrase to open it will be required before generating the new keypair."
4444 "\n"
4445 "You can encrypt the data file to a public key other than the one that it "
4446 "was originally encrypted with by passing the @option{--keygrip} option with "
4447 "the hex encoded keygrip of the public key as its argument. The keygrip may "
4448 "be of any key that @command{gpg-agent} knows about. The "
4449 "@option{--sign-keygrip} option may also be used to sign with an alternate "
4450 "secret key. This option may be needed when using a smartcard. This option "
4451 "has no effect with symmetrically encrypted data files."
4452 "\n"
4453 "The @option{--s2k-count} option sets number of hash iterations for a "
4454 "passphrase. A value less-than @code{65536} will use the machine calibrated "
4455 "value and is the default. This setting only affects new files. To change "
4456 "the setting use the @code{PASSWD} command (@pxref{PASSWD}). This option "
4457 "has no effect with symmetrically encrypted data files."
4460 new_command("ISCACHED", 1, 0, iscached_command, _(
4461 "ISCACHED [--lock] <filename>\n"
4462 "An @emph{OK} response is returned if the specified @var{filename} is found "
4463 "in the file cache. If not found in the cache but exists on the filesystem "
4464 "then @var{GPG_ERR_NO_DATA} is returned. Otherwise a filesystem error is "
4465 "returned."
4466 "\n"
4467 "The @option{lock} option will lock the file mutex of @var{filename} when the "
4468 "file exists; it does not need to be opened nor cached."
4471 new_command("CLEARCACHE", 1, 1, clearcache_command, _(
4472 "CLEARCACHE [<filename>]\n"
4473 "Clears a file cache entry for all or the specified @var{filename}."
4476 new_command("CACHETIMEOUT", 1, 1, cachetimeout_command, _(
4477 "CACHETIMEOUT <filename> <seconds>\n"
4478 "The time in @var{seconds} until @var{filename} will be removed from the "
4479 "cache. @code{-1} will keep the cache entry forever, @code{0} will require "
4480 "the passphrase for each @code{OPEN} or @code{SAVE} command (@pxref{OPEN}, "
4481 "@pxref{SAVE}). @xref{Configuration}, and the @code{cache_timeout} "
4482 "parameter."
4485 new_command("LIST", 0, 1, list_command, _(
4486 "LIST [--inquire] [--no-recurse] [--verbose] [--with-target] [--all] [[!]element[<TAB>[!]child[..]]]\n"
4487 "If no element path is given then a newline separated list of root elements "
4488 "is returned with a data response. If given, then all reachable elements "
4489 "of the specified element path are returned unless the @option{--no-recurse} "
4490 "option is specified. If specified, only the child elements of the element "
4491 "path are returned without recursing into grandchildren. Each resulting "
4492 "element is prefixed with the literal @code{!} character when the element "
4493 "contains no @code{target} attribute. @xref{Target Attribute}, for details."
4494 "\n"
4495 "When the @option{--verbose} option is passed then each element path "
4496 "returned will have zero or more flags appened to it. These flags are "
4497 "delimited from the element path by a single space character. A flag itself "
4498 "is a single character. Flag @code{+} indicates that there are child nodes of "
4499 "the current element path. Flag @code{E} indicates that an element of an "
4500 "element path contained in a @var{target} attribute could not be found. Flag "
4501 "@code{O} indicates that a @var{target} attribute recursion limit was reached "
4502 "(@pxref{Configuration}). Flag @code{T} will append the resolved element path "
4503 "of the @var{target} attribute contained in the current element (see below)."
4504 "\n"
4505 "The @option{--with-target} option implies @option{--verbose} and will append "
4506 "an additional flag @code{T} followed by a single space then an element path. "
4507 "The appended element path is the resolved path (@pxref{REALPATH}) of the "
4508 "current element when it contains a @var{target} attribute. When no "
4509 "@var{target} attribute is found then no flag will be appended."
4510 "\n"
4511 "The @option{--no-recurse} option limits the amount of data returned to only "
4512 "the listing of children of the specified element path and not any "
4513 "grandchildren."
4514 "\n"
4515 "The @option{--all} option lists the entire element tree for each root "
4516 "element. This option also implies option @option{--verbose}."
4517 "\n"
4518 "When the @option{--inquire} option is passed then all remaining non-option "
4519 "arguments are retrieved via a server @emph{INQUIRE}."
4522 new_command("REALPATH", 0, 1, realpath_command, _(
4523 "REALPATH [--inquire] [!]element[<TAB>[!]child[..]]\n"
4524 "Resolves all @code{target} attributes of the specified element path and "
4525 "returns the result with a data response. @xref{Target Attribute}, for details."
4526 "\n"
4527 "When the @option{--inquire} option is passed then all remaining non-option "
4528 "arguments are retrieved via a server @emph{INQUIRE}."
4531 new_command("STORE", 0, 1, store_command, _(
4532 "STORE [!]element[<TAB>[!]child[..]]<TAB>[content]\n"
4533 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
4534 "\n"
4535 "Creates a new element path or modifies the @var{content} of an existing "
4536 "element. If only a single element is specified then a new root element is "
4537 "created. Otherwise, elements are @key{TAB} delimited and the content will be "
4538 "set to the final @key{TAB} delimited element. If no @var{content} is "
4539 "specified after the final @key{TAB}, then the content of the element will "
4540 "be removed, or empty when creating a new element."
4541 "\n"
4542 "The only restriction of an element name is that it not contain whitespace "
4543 "or begin with the literal element character @code{!} unless specifying a "
4544 "literal element (@pxref{Target Attribute}). There is no whitespace between "
4545 "the @key{TAB} delimited elements. It is recommended that the content of an "
4546 "element be base64 encoded when it contains control or @key{TAB} characters "
4547 "to prevent @abbr{XML} parsing and @command{pwmd} syntax errors."
4550 new_command("RENAME", 0, 1, rename_command, _(
4551 "RENAME [--inquire] [!]element[<TAB>[!]child[..]] <value>\n"
4552 "Renames the specified @var{element} to the new @var{value}. If an element of "
4553 "the same name as the @var{value} already exists it will be overwritten."
4554 "\n"
4555 "When the @option{--inquire} option is passed then all remaining non-option "
4556 "arguments are retrieved via a server @emph{INQUIRE}."
4559 new_command("COPY", 0, 1, copy_command, _(
4560 "COPY [--inquire] [!]source[<TAB>[!]child[..]] [!]dest[<TAB>[!]child[..]]\n"
4561 "Copies the entire element tree starting from the child node of the source "
4562 "element, to the destination element path. If the destination element path "
4563 "does not exist then it will be created; otherwise it is overwritten."
4564 "\n"
4565 "Note that attributes from the source element are merged into the "
4566 "destination element when the destination element path exists. When an "
4567 "attribute of the same name exists in both the source and destination "
4568 "elements then the destination attribute will be updated to the source "
4569 "attribute value."
4570 "\n"
4571 "When the @option{--inquire} option is passed then all remaining non-option "
4572 "arguments are retrieved via a server @emph{INQUIRE}."
4575 new_command("MOVE", 0, 1, move_command, _(
4576 "MOVE [--inquire] [!]source[<TAB>[!]child[..]] [[!]dest[<TAB>[!]child[..]]]\n"
4577 "Moves the source element path to the destination element path. If the "
4578 "destination is not specified then it will be moved to the root node of the "
4579 "document. If the destination is specified and exists then it will be "
4580 "overwritten; otherwise non-existing elements of the destination element "
4581 "path will be created."
4582 "\n"
4583 "When the @option{--inquire} option is passed then all remaining non-option "
4584 "arguments are retrieved via a server @emph{INQUIRE}."
4587 new_command("DELETE", 0, 1, delete_command, _(
4588 "DELETE [--inquire] [!]element[<TAB>[!]child[..]]\n"
4589 "Removes the specified element path and all of its children. This may break "
4590 "an element with a @code{target} attribute (@pxref{Target Attribute}) that "
4591 "refers to this element or any of its children."
4592 "\n"
4593 "When the @option{--inquire} option is passed then all remaining non-option "
4594 "arguments are retrieved via a server @emph{INQUIRE}."
4597 new_command("GET", 0, 1, get_command, _(
4598 "GET [--inquire] [!]element[<TAB>[!]child[..]]\n"
4599 "Retrieves the content of the specified element. The content is returned "
4600 "with a data response."
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("ATTR", 0, 1, attr_command, _(
4607 "ATTR [--inquire] SET|GET|DELETE|LIST [<attribute>] [!]element[<TAB>[!]child[..]] ..\n"
4608 "@table @asis\n"
4609 "@item ATTR SET attribute [!]element[<TAB>[!]child[..]] [value]\n"
4610 "\n"
4611 " Stores or updates an @var{attribute} name and optional @var{value} of an "
4612 "element. When no @var{value} is specified any existing value will be removed."
4613 "\n"
4614 "@item ATTR DELETE attribute [!]element[<TAB>[!]child[..]]\n"
4615 "\n"
4616 " Removes an @var{attribute} from an element."
4617 "\n"
4618 "@item ATTR LIST [!]element[<TAB>[!]child[..]]\n"
4619 "\n"
4620 " Retrieves a newline separated list of attributes names and values "
4621 "from the specified element. Each attribute name and value is space delimited."
4622 "\n"
4623 "@item ATTR GET attribute [!]element[<TAB>[!]child[..]]\n"
4624 "\n"
4625 " Retrieves the value of an @var{attribute} from an element."
4626 "@end table\n"
4627 "\n"
4628 "The @code{_name} attribute (case sensitive) cannot be removed nor modified. "
4629 "Use the @code{DELETE} (@pxref{DELETE}) or @code{RENAME} (@pxref{RENAME}) "
4630 "commands instead."
4631 "\n"
4632 "The @code{_mtime} attribute is updated each time an element is modified by "
4633 "either storing content, editing attributes or by deleting a child element. "
4634 "The @code{_ctime} attribute is created for each new element in an element "
4635 "path."
4636 "\n"
4637 "When the @option{--inquire} option is passed then all remaining non-option "
4638 "arguments are retrieved via a server @emph{INQUIRE}."
4639 "\n"
4640 "@xref{Target Attribute}, for details about this special attribute."
4643 new_command("XPATH", 0, 1, xpath_command, _(
4644 "XPATH [--inquire] <expression>[<TAB>[value]]\n"
4645 "Evaluates an XPath @var{expression}. If no @var{value} argument is "
4646 "specified it is assumed the expression is a request to return a result. "
4647 "Otherwise, the result is set to the @var{value} argument and the document is "
4648 "updated. If there is no @var{value} after the @key{TAB} character, the value "
4649 "is assumed to be empty and the document is updated. For example:"
4650 "@sp 1\n"
4651 "@example\n"
4652 "XPATH //element[@@_name='password']@key{TAB}\n"
4653 "@end example\n"
4654 "@sp 1"
4655 "would clear the content of all @code{password} elements in the data file "
4656 "while leaving off the trailing @key{TAB} would return all @code{password} "
4657 "elements in @abbr{XML} format."
4658 "\n"
4659 "When the @option{--inquire} option is passed then all remaining non-option "
4660 "arguments are retrieved via a server @emph{INQUIRE}."
4661 "\n"
4662 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
4663 "expression syntax."
4666 new_command("XPATHATTR", 0, 1, xpathattr_command, _(
4667 "XPATHATTR [--inquire] SET|DELETE <name> <expression>[<TAB>[<value>]]\n"
4668 "Like the @code{XPATH} command (@pxref{XPATH}) but operates on element "
4669 "attributes and does not return a result. For the @var{SET} operation the "
4670 "@var{value} is optional but the field is required. If not specified then "
4671 "the attribute value will be empty. For example:"
4672 "@sp 1"
4673 "@example\n"
4674 "XPATHATTR SET password //element[@@_name='password']@key{TAB}\n"
4675 "@end example\n"
4676 "@sp 1"
4677 "would create an @code{password} attribute for each @code{password} element "
4678 "found in the document. The attribute value will be empty but still exist."
4679 "\n"
4680 "When the @option{--inquire} option is passed then all remaining non-option "
4681 "arguments are retrieved via a server @emph{INQUIRE}."
4682 "\n"
4683 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
4684 "expression syntax."
4687 new_command("IMPORT", 0, 1, import_command, _(
4688 "IMPORT [--root [!]element[<TAB>[!]child[..]]] <content>\n"
4689 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
4690 "\n"
4691 "Like the @code{STORE} command (@pxref{STORE}), but the @var{content} "
4692 "argument is raw @abbr{XML} data. The content is created as a child of "
4693 "the element path specified with the @option{--root} option or at the "
4694 "document root when not specified. Existing elements of the same name will "
4695 "be overwritten."
4696 "\n"
4697 "The content must begin with an @abbr{XML} element node. @xref{Introduction}, "
4698 "for details."
4701 new_command("DUMP", 0, 1, dump_command, _(
4702 "DUMP\n"
4703 "Shows the in memory @abbr{XML} document with indenting. @xref{XPATH}, for "
4704 "dumping a specific node."
4707 new_command("LOCK", 0, 0, lock_command, _(
4708 "LOCK\n"
4709 "Locks the mutex associated with the opened file. This prevents other clients "
4710 "from sending commands to the same opened file until the client "
4711 "that sent this command either disconnects or sends the @code{UNLOCK} "
4712 "command. @xref{UNLOCK}."
4715 new_command("UNLOCK", 1, 0, unlock_command, _(
4716 "UNLOCK\n"
4717 "Unlocks the file mutex which was locked with the @code{LOCK} command or "
4718 "a commands' @option{--lock} option (@pxref{LOCK}, @pxref{OPEN}, "
4719 "@pxref{ISCACHED})."
4722 new_command("GETCONFIG", 1, 1, getconfig_command, _(
4723 "GETCONFIG [filename] <parameter>\n"
4724 "Returns the value of a @command{pwmd} configuration @var{parameter} with a "
4725 "data response. If no file has been opened then the value for @var{filename} "
4726 "or the default from the @samp{global} section will be returned. If a file "
4727 "has been opened and no @var{filename} is specified, a value previously "
4728 "set with the @code{OPTION} command (@pxref{OPTION}) will be returned."
4731 new_command("OPTION", 1, 1, option_command, _(
4732 "OPTION <NAME>=<VALUE>\n"
4733 "Sets a client option @var{name} to @var{value}. The value for an option is "
4734 "kept for the duration of the connection."
4735 "\n"
4736 "@table @asis\n"
4737 "@item DISABLE-PINENTRY\n"
4738 "Disable use of @command{pinentry} for passphrase retrieval. When set, a "
4739 "server inquire is sent to the client to obtain the passphrase. This option "
4740 "may be set as needed before the @pxref{OPEN}, @pxref{PASSWD}, and "
4741 "@pxref{SAVE} commands."
4742 "\n"
4743 "@item PINENTRY-TIMEOUT\n"
4744 "Sets the number of seconds before a pinentry prompt will return an error "
4745 "while waiting for user input."
4746 "\n"
4747 "@item TTYNAME\n"
4748 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4749 "\n"
4750 "@item TTYTYPE\n"
4751 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4752 "\n"
4753 "@item DISPLAY\n"
4754 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4755 "\n"
4756 "@item PINENTRY-DESC\n"
4757 "Sets the description string of the @command{gpg-agent} and @command{pinentry} dialog."
4758 "\n"
4759 "@item PINENTRY-TITLE\n"
4760 "Sets the title string of the @command{gpg-agent} and @command{pinentry} dialog."
4761 "\n"
4762 "@item PINENTRY-PROMPT\n"
4763 "Sets the prompt string of the @command{gpg-agent} and @command{pinentry} dialog."
4764 "\n"
4765 "@item LC-CTYPE\n"
4766 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4767 "\n"
4768 "@item LC-MESSAGES\n"
4769 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4770 "\n"
4771 "@item NAME\n"
4772 "Associates the thread ID of the connection with the specified textual "
4773 "representation. Useful for debugging log messages."
4774 "\n"
4775 "@item LOCK-TIMEOUT\n"
4776 "When not @code{0}, the duration in tenths of a second to wait for the file "
4777 "mutex which has been locked by another thread to be released before returning "
4778 "an error. When @code{-1}, then an error will be returned immediately."
4779 "\n"
4780 "@item LOG-LEVEL\n"
4781 "An integer specifiying the logging level."
4782 "@end table\n"
4785 new_command("LS", 1, 1, ls_command, _(
4786 "LS\n"
4787 "Lists the available data files stored in the data directory "
4788 "(@file{~/.pwmd/data}). The result is a newline separated list of filenames."
4791 new_command("RESET", 1, 1, NULL, _(
4792 "RESET\n"
4793 "Closes the currently opened file but keeps any previously set client options."
4796 new_command("NOP", 1, 1, NULL, _(
4797 "NOP\n"
4798 "Does nothing. Always returns successfully."
4801 /* !END-HELP-TEXT! */
4802 new_command ("CANCEL", 1, 1, NULL, NULL);
4803 new_command ("END", 1, 1, NULL, NULL);
4804 new_command ("BYE", 1, 1, NULL, NULL);
4806 int i;
4807 for (i = 0; command_table[i]; i++);
4808 qsort (command_table, i - 1, sizeof (struct command_table_s *),
4809 sort_commands);
4812 gpg_error_t
4813 register_commands (assuan_context_t ctx)
4815 int i = 0, rc;
4817 for (; command_table[i]; i++)
4819 if (!command_table[i]->handler)
4820 continue;
4822 rc = assuan_register_command (ctx, command_table[i]->name,
4823 command_table[i]->handler,
4824 command_table[i]->help);
4825 if (rc)
4826 return rc;
4829 rc = assuan_register_bye_notify (ctx, bye_notify);
4830 if (rc)
4831 return rc;
4833 rc = assuan_register_reset_notify (ctx, reset_notify);
4834 if (rc)
4835 return rc;
4837 rc = assuan_register_pre_cmd_notify (ctx, command_startup);
4838 if (rc)
4839 return rc;
4841 return assuan_register_post_cmd_notify (ctx, command_finalize);