Reimplement the KEEPALIVE status message.
[pwmd.git] / src / commands.c
blob9a7e428f3572153155a29d391b9287c7d4f3949a
1 /*
2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013
3 Ben Kibbey <bjk@luxsci.net>
5 This file is part of pwmd.
7 Pwmd is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 2 of the License, or
10 (at your option) any later version.
12 Pwmd is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
20 #ifdef HAVE_CONFIG_H
21 #include <config.h>
22 #endif
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <unistd.h>
27 #include <err.h>
28 #include <errno.h>
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <fcntl.h>
32 #include <ctype.h>
33 #include <dirent.h>
34 #include <pthread.h>
35 #include <stdint.h>
37 #ifdef WITH_LIBACL
38 #include <sys/acl.h>
39 #endif
41 #include "pwmd-error.h"
42 #include <gcrypt.h>
44 #include "mem.h"
45 #include "xml.h"
46 #include "util-misc.h"
47 #include "common.h"
48 #include "rcfile.h"
49 #include "cache.h"
50 #include "commands.h"
51 #include "mutex.h"
52 #include "crypto.h"
53 #include "pinentry.h"
55 /* Flags needed to be retained for a client across commands. */
56 #define FLAG_NEW 0x0001
57 #define FLAG_HAS_LOCK 0x0002
58 #define FLAG_LOCK_CMD 0x0004
59 #define FLAG_NO_PINENTRY 0x0008
60 #define FLAG_OPEN 0x0010
61 #define FLAG_KEEP_LOCK 0x0020
63 /* These are command option flags. */
64 #define OPT_INQUIRE 0x0001
65 #define OPT_NO_PASSPHRASE 0x0002
66 #define OPT_RESET 0x0004
67 #define OPT_LIST_RECURSE 0x0008
68 #define OPT_LIST_VERBOSE 0x0010
69 #define OPT_LOCK 0x0020
70 #define OPT_LOCK_ON_OPEN 0x0040
71 #define OPT_SIGN 0x0080
72 #define OPT_LIST_ALL 0x0100
73 #define OPT_LIST_WITH_TARGET 0x0200
74 #define OPT_DATA 0x0400
75 #define OPT_NO_AGENT 0x0800
77 #ifdef WITH_AGENT
78 /* The GETCONFIG command, for example, may fail because pwmd lost the
79 * gpg-agent connection. Update the recovered agent ctx. */
80 #define UPDATE_AGENT_CTX(client, crypto) do { \
81 if (crypto && crypto->agent && crypto->agent->did_restart \
82 && client->crypto && client->crypto->agent \
83 && client->crypto->agent->ctx && \
84 crypto->agent->ctx != client->crypto->agent->ctx) \
85 { \
86 client->crypto->agent->ctx = crypto->agent->ctx; \
87 crypto->agent->ctx = NULL; \
88 } \
89 } while (0)
90 #else
91 #define UPDATE_AGENT_CTX(client, crypto)
92 #endif
94 struct command_table_s
96 const char *name;
97 gpg_error_t (*handler) (assuan_context_t, char *line);
98 const char *help;
99 int ignore_startup;
100 int unlock; // unlock the file mutex after validating the checksum
103 static struct command_table_s **command_table;
105 static gpg_error_t do_lock (struct client_s *client, int add);
106 static gpg_error_t validate_checksum (struct client_s *,
107 struct cache_data_s *);
108 static gpg_error_t update_checksum (struct client_s *client);
110 static gpg_error_t
111 unlock_file_mutex (struct client_s *client, int remove)
113 gpg_error_t rc = 0;
115 // OPEN: keep the lock for the same file being reopened.
116 if (client->flags & FLAG_KEEP_LOCK && client->flags & FLAG_HAS_LOCK)
117 return 0;
119 if (!(client->flags & FLAG_HAS_LOCK))
120 return GPG_ERR_NOT_LOCKED;
122 rc = cache_unlock_mutex (client->md5file, remove);
123 if (rc)
124 rc = GPG_ERR_INV_STATE;
125 else
126 client->flags &= ~(FLAG_HAS_LOCK | FLAG_LOCK_CMD);
128 return rc;
131 static gpg_error_t
132 lock_file_mutex (struct client_s *client, int add)
134 gpg_error_t rc = 0;
135 int timeout = config_get_integer (client->filename, "cache_timeout");
137 if (client->flags & FLAG_HAS_LOCK)
138 return 0;
140 rc = cache_lock_mutex (client->ctx, client->md5file,
141 client->lock_timeout, add, timeout);
142 if (!rc)
143 client->flags |= FLAG_HAS_LOCK;
145 return rc;
148 static gpg_error_t
149 file_modified (struct client_s *client, struct command_table_s *cmd)
151 gpg_error_t rc = 0;
153 if (!(client->flags & FLAG_OPEN))
154 return GPG_ERR_INV_STATE;
156 rc = lock_file_mutex (client, 0);
157 if (!rc || rc == GPG_ERR_NO_DATA)
159 rc = validate_checksum (client, NULL);
160 if (gpg_err_code (rc) == GPG_ERR_ENOENT)
161 rc = 0;
164 if ((cmd->unlock && !(client->flags & FLAG_HAS_LOCK)) || rc)
165 unlock_file_mutex (client, 0);
167 return rc;
170 static gpg_error_t
171 parse_xml (assuan_context_t ctx, int new)
173 struct client_s *client = assuan_get_pointer (ctx);
174 int cached = client->doc != NULL;
176 if (new)
178 client->doc = new_document ();
179 if (client->doc)
181 xmlDocDumpFormatMemory (client->doc,
182 (xmlChar **) & client->crypto->plaintext,
183 (int *) &client->crypto->plaintext_len, 0);
184 if (!client->crypto->plaintext)
186 xmlFreeDoc (client->doc);
187 client->doc = NULL;
191 else if (!cached)
192 client->doc = parse_doc ((char *) client->crypto->plaintext,
193 client->crypto->plaintext_len);
195 return !client->doc ? GPG_ERR_ENOMEM : 0;
198 static void
199 free_client (struct client_s *client)
201 if (client->doc)
202 xmlFreeDoc (client->doc);
204 xfree (client->crc);
205 xfree (client->filename);
206 xfree (client->last_error);
208 if (client->crypto)
210 cleanup_crypto_stage2 (client->crypto);
211 if (client->crypto->pkey_sexp)
212 gcry_sexp_release (client->crypto->pkey_sexp);
214 client->crypto->pkey_sexp = NULL;
215 memset (client->crypto->sign_grip, 0,
216 sizeof (client->crypto->sign_grip));
217 memset (client->crypto->grip, 0, sizeof(client->crypto->grip));
220 if (client->xml_error)
221 xmlResetError (client->xml_error);
224 void
225 cleanup_client (struct client_s *client)
227 assuan_context_t ctx = client->ctx;
228 struct client_thread_s *thd = client->thd;
229 struct crypto_s *crypto = client->crypto;
230 long lock_timeout = client->lock_timeout;
231 int no_pinentry = (client->flags & FLAG_NO_PINENTRY);
232 struct pinentry_option_s pin_opts;
233 #ifdef WITH_AGENT
234 struct pinentry_option_s agent_pin_opts;
236 if (crypto && crypto->agent)
237 memcpy (&agent_pin_opts, &crypto->agent->pinentry_opts,
238 sizeof(struct pinentry_option_s));
239 #endif
241 memcpy (&pin_opts, &client->pinentry_opts, sizeof(struct pinentry_option_s));
242 unlock_file_mutex (client, client->flags & FLAG_NEW);
243 free_client (client);
244 memset (client, 0, sizeof (struct client_s));
245 client->crypto = crypto;
246 client->ctx = ctx;
247 client->thd = thd;
248 client->lock_timeout = lock_timeout;
249 memcpy (&client->pinentry_opts, &pin_opts, sizeof(struct pinentry_option_s));
250 client->flags |= no_pinentry ? FLAG_NO_PINENTRY : 0;
251 #ifdef WITH_AGENT
252 if (crypto && crypto->agent)
253 memcpy (&crypto->agent->pinentry_opts, &agent_pin_opts,
254 sizeof(struct pinentry_option_s));
255 #endif
258 static gpg_error_t
259 open_finalize (assuan_context_t ctx, char *key, size_t keylen)
261 struct client_s *client = assuan_get_pointer (ctx);
262 gpg_error_t rc = 0;
263 struct cache_data_s *cdata = cache_get_data (client->md5file);
264 int cached = 0, keyarg = key ? 1 : 0;
265 size_t keysize;
266 unsigned char *salted_key = NULL;
267 int algo;
268 int pin_try = 1;
269 int pin_tries = 3;
270 char *pin_title = client->pinentry_opts.title;
272 client->crypto->filename = str_dup (client->filename);
273 if (cdata || client->flags & FLAG_NEW)
275 if (cdata && !(client->flags & FLAG_NEW))
277 rc = decrypt_xml (client->crypto, cdata->doc, cdata->doclen);
278 if (rc)
279 return rc;
282 cached = cdata != NULL;
283 goto done;
286 if (!key && !IS_PKCS (client->crypto))
288 if (client->flags & FLAG_NO_PINENTRY)
290 rc = inquire_passphrase (ctx, "PASSPHRASE", (unsigned char **)&key,
291 &keylen);
292 if (rc)
293 return rc;
295 else
297 client->pinentry_opts.timeout = config_get_integer (client->filename,
298 "pinentry_timeout");
299 pin_again:
300 rc = getpin_common (client->ctx, client->filename, PINENTRY_OPEN,
301 &key, &keylen);
302 if (rc)
303 return rc;
307 if (!IS_PKCS (client->crypto))
309 algo = cipher_to_gcrypt (client->crypto->hdr.flags);
310 rc = hash_key (algo, client->crypto->hdr.salt,
311 sizeof(client->crypto->hdr.salt), key, keylen,
312 (void **)&salted_key, &keysize);
313 if (!keyarg)
314 gcry_free (key);
316 if (!rc)
318 rc = decrypt_data (client->ctx, client->crypto, salted_key, keysize);
319 if (gpg_err_code (rc) == GPG_ERR_BAD_PASSPHRASE
320 && ++pin_try <= pin_tries && !(client->flags & FLAG_NO_PINENTRY))
322 gcry_free (salted_key);
323 salted_key = NULL;
324 key = NULL;
325 keylen = 0;
326 client->pinentry_opts.title = str_asprintf (_ ("Bad passphrase (try %i of %i)"), pin_try, pin_tries);
327 goto pin_again;
331 if (client->pinentry_opts.title != pin_title)
332 xfree (client->pinentry_opts.title);
334 client->pinentry_opts.title = pin_title;
335 if (rc)
336 return rc;
338 cdata = xcalloc (1, sizeof (struct cache_data_s));
339 if (!cdata)
340 return GPG_ERR_ENOMEM;
342 cdata->key = salted_key;
343 cdata->keylen = keysize;
345 else
346 rc = decrypt_data (client->ctx, client->crypto, NULL, 0);
348 done:
349 if (!rc)
351 rc = parse_xml (ctx, client->flags & FLAG_NEW);
352 if (!rc)
354 int timeout = config_get_integer (client->filename,
355 "cache_timeout");
357 if (!cached)
359 if (!cdata)
360 cdata = xcalloc (1, sizeof (struct cache_data_s));
362 rc = encrypt_xml (NULL, cache_key, cache_keysize,
363 GCRY_CIPHER_AES, client->crypto->plaintext,
364 client->crypto->plaintext_len, &cdata->doc,
365 &cdata->doclen, &cache_iv, &cache_blocksize,
367 if (!rc && !(client->flags & FLAG_NEW) && IS_PKCS (client->crypto))
369 rc = gcry_sexp_build ((gcry_sexp_t *) & cdata->pubkey, NULL,
370 "%S", client->crypto->pkey_sexp);
374 if (cdata->sigkey)
375 gcry_sexp_release (cdata->sigkey);
377 cdata->sigkey = NULL;
379 if (!rc && IS_PKCS (client->crypto))
380 rc = gcry_sexp_build ((gcry_sexp_t *) &cdata->sigkey, NULL,
381 "%S", client->crypto->sigpkey_sexp);
383 if (!rc
384 && !cache_add_file (client->md5file, (client->flags & FLAG_NEW)
385 ? NULL : client->crypto->grip, cdata, timeout))
387 if (!cached)
389 free_cache_data_once (cdata);
390 xmlFreeDoc (client->doc);
391 client->doc = NULL;
393 rc = GPG_ERR_ENOMEM;
396 if (!rc)
397 client->flags |= FLAG_OPEN;
401 if (!rc)
402 update_checksum (client);
404 if (!rc && (client->opts & OPT_LOCK_ON_OPEN))
405 rc = do_lock (client, 0);
407 return rc;
410 static void
411 req_cleanup (void *arg)
413 if (!arg)
414 return;
416 strv_free ((char **) arg);
419 static gpg_error_t
420 parse_open_opt_lock (void *data, void *value)
422 struct client_s *client = data;
424 client->opts |= OPT_LOCK_ON_OPEN;
425 return 0;
428 static gpg_error_t
429 parse_opt_inquire (void *data, void *value)
431 struct client_s *client = data;
433 (void) value;
434 client->opts |= OPT_INQUIRE;
435 return 0;
438 static gpg_error_t
439 update_checksum (struct client_s *client)
441 unsigned char *crc;
442 size_t len;
443 struct cache_data_s *cdata;
444 gpg_error_t rc = get_checksum (client->filename, &crc, &len);
446 if (rc)
447 return rc;
449 xfree (client->crc);
450 client->crc = crc;
451 cdata = cache_get_data (client->md5file);
452 if (cdata)
454 xfree (cdata->crc);
455 cdata->crc = xmalloc (len);
456 memcpy (cdata->crc, crc, len);
459 return 0;
462 static gpg_error_t
463 validate_checksum (struct client_s *client, struct cache_data_s *cdata)
465 unsigned char *crc;
466 size_t len;
467 gpg_error_t rc;
468 int n = 0;
470 if (cdata && !cdata->crc)
471 return GPG_ERR_CHECKSUM;
473 rc = get_checksum (client->filename, &crc, &len);
474 if (rc)
475 return rc;
477 if (cdata)
478 n = memcmp (cdata->crc, crc, len);
479 else if (client->crc)
480 n = memcmp (client->crc, crc, len);
482 xfree (crc);
483 return n ? GPG_ERR_CHECKSUM : 0;
486 static gpg_error_t
487 do_open (assuan_context_t ctx, const char *filename, const char *password)
489 struct client_s *client = assuan_get_pointer (ctx);
490 struct cache_data_s *cdata;
491 gpg_error_t rc = 0;
492 int done = 0;
494 if (!valid_filename (filename))
495 return GPG_ERR_INV_VALUE;
497 gcry_md_hash_buffer (GCRY_MD_MD5, client->md5file, filename,
498 strlen (filename));
499 client->filename = str_dup (filename);
500 if (!client->filename)
501 return GPG_ERR_ENOMEM;
503 // Cached document?
504 cdata = cache_get_data (client->md5file);
505 if (cdata && cdata->doc)
507 int defer;
509 rc = validate_checksum (client, cdata);
510 /* This will check that the key is cached in the agent which needs to
511 * be determined for files that share a keygrip. */
512 if (!rc)
514 rc = cache_iscached (client->filename, &defer);
515 if (!rc && defer)
516 rc = GPG_ERR_KEY_EXPIRED;
519 #ifdef WITH_GNUTLS
520 if (!rc && client->thd->remote
521 && config_get_boolean (client->filename, "tcp_require_key"))
522 rc = GPG_ERR_KEY_EXPIRED;
523 #endif
525 if (!rc && !password)
527 rc = read_data_header (client->filename, &client->crypto->hdr,
528 NULL, NULL);
529 if (!rc)
531 if (IS_PKCS (client->crypto))
533 gcry_sexp_build (&client->crypto->pkey_sexp, NULL, "%S",
534 cdata->pubkey);
535 gcry_pk_get_keygrip (client->crypto->pkey_sexp,
536 client->crypto->grip);
537 gcry_sexp_build (&client->crypto->sigpkey_sexp, NULL, "%S",
538 cdata->sigkey);
539 gcry_pk_get_keygrip (client->crypto->sigpkey_sexp,
540 client->crypto->sign_grip);
543 if (!rc)
545 rc = open_finalize (ctx, NULL, 0);
546 done = 1;
551 /* There was an error accessing the file so clear the cache entry. The
552 * real error will be returned from read_data_file() since the file
553 * may have only disappeared. */
554 if (!done)
556 log_write ("%s: %s", filename, pwmd_strerror (rc));
557 rc = cache_clear (client->md5file);
558 send_status_all (STATUS_CACHE, NULL);
562 if (done || rc)
563 return rc;
565 rc = read_data_file (client->filename, client->crypto);
566 if (rc)
568 if (gpg_err_source (rc) != GPG_ERR_SOURCE_DEFAULT ||
569 gpg_err_code (rc) != GPG_ERR_ENOENT)
571 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
572 return rc;
575 client->flags |= FLAG_NEW;
576 memset (client->crypto->grip, 0, sizeof (client->crypto->grip));
577 memset (client->crypto->sign_grip, 0,
578 sizeof (client->crypto->sign_grip));
579 rc = open_finalize (ctx, NULL, 0);
580 return rc;
583 if (password && IS_PKCS (client->crypto))
585 #ifdef WITH_AGENT
586 rc = set_agent_passphrase (client->crypto, password, strlen (password));
587 if (rc)
588 return rc;
589 #endif
592 rc = open_finalize (ctx, (char *)password, password ? strlen (password) : 0);
593 return rc;
596 static gpg_error_t
597 open_command (assuan_context_t ctx, char *line)
599 gpg_error_t rc;
600 struct client_s *client = assuan_get_pointer (ctx);
601 char **req, *password = NULL, *filename;
602 unsigned char md5file[16];
603 int same_file = 0;
604 struct argv_s *args[] = {
605 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_open_opt_lock},
606 NULL
609 rc = parse_options (&line, args, client);
610 if (rc)
611 return send_error (ctx, rc);
613 req = str_split (line, " ", 2);
614 if (!req)
615 return send_error (ctx, GPG_ERR_SYNTAX);
617 #ifdef WITH_GNUTLS
618 if (client->thd->remote)
620 rc = tls_validate_access (client, req[0]);
621 if (rc)
623 if (rc == GPG_ERR_INV_USER_ID)
624 log_write (_("client validation failed for file '%s'"), req[0]);
625 strv_free (req);
626 return send_error (ctx, rc);
629 /* Remote pinentries are not supported. */
630 client->flags |= FLAG_NO_PINENTRY;
632 #endif
634 pthread_cleanup_push (req_cleanup, req);
635 filename = req[0];
636 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
637 /* This client may have locked a different file with ISCACHED --lock than
638 * the current filename. This will remove that lock. */
639 same_file = !memcmp (md5file, client->md5file, 16) ? 1 : 0;
640 if (client->flags & FLAG_OPEN ||
641 (client->flags & FLAG_HAS_LOCK && !same_file))
643 typeof (client->opts) opts = client->opts;
644 typeof (client->flags) flags = client->flags;
646 if (same_file)
647 client->flags |= FLAG_KEEP_LOCK;
649 cleanup_client (client);
650 client->opts = opts;
651 client->flags |= flags;
652 client->flags &= ~(FLAG_LOCK_CMD | FLAG_NEW);
653 if (!same_file)
654 client->flags &= ~(FLAG_HAS_LOCK);
657 /* Need to lock the mutex here because file_modified() cannot without
658 * knowing the filename. */
659 memcpy (client->md5file, md5file, 16);
660 rc = lock_file_mutex (client, 1);
661 if (!rc)
663 password = req[1] && *req[1] ? req[1] : NULL;
664 #ifdef WITH_AGENT
665 if (IS_PKCS (client->crypto))
666 rc = set_pinentry_mode (client->crypto->agent,
667 (client->flags & FLAG_NO_PINENTRY) ? "loopback"
668 : "ask");
669 #endif
670 if (!rc)
672 rc = do_open (ctx, filename, password);
673 if (rc)
674 cleanup_client (client);
676 cleanup_crypto_stage1 (client->crypto);
680 pthread_cleanup_pop (1);
682 if (!rc && client->flags & FLAG_NEW)
683 rc = send_status (ctx, STATUS_NEWFILE, NULL);
685 #ifdef WITH_AGENT
686 (void) kill_scd (client->crypto->agent);
687 #endif
688 return send_error (ctx, rc);
691 static gpg_error_t
692 parse_save_opt_no_passphrase (void *data, void *value)
694 struct client_s *client = data;
696 (void) value;
697 client->opts |= OPT_NO_PASSPHRASE;
698 return 0;
701 static gpg_error_t
702 parse_save_opt_no_agent (void *data, void *value)
704 struct client_s *client = data;
706 client->opts |= OPT_NO_AGENT;
707 return 0;
710 static gpg_error_t
711 parse_save_opt_cipher (void *data, void *value)
713 struct client_s *client = data;
714 int algo = cipher_string_to_gcrypt ((char *) value);
715 file_header_t *hdr = &client->crypto->save.hdr;
717 if (algo == -1)
718 return GPG_ERR_INV_VALUE;
720 hdr->flags = set_cipher_flag (hdr->flags, algo);
721 return 0;
724 static gpg_error_t
725 parse_save_opt_keygrip (void *data, void *value)
727 struct client_s *client = data;
729 if (!IS_PKCS (client->crypto))
730 return GPG_ERR_INV_ARG;
732 #ifdef WITH_AGENT
733 if (client->crypto->save.pkey)
734 gcry_sexp_release (client->crypto->save.pkey);
736 client->crypto->save.pkey = NULL;
737 return get_pubkey (client->crypto, value, &client->crypto->save.pkey);
738 #else
739 return GPG_ERR_INV_ARG;
740 #endif
743 static gpg_error_t
744 parse_save_opt_sign_keygrip (void *data, void *value)
746 struct client_s *client = data;
748 if (!IS_PKCS (client->crypto))
749 return GPG_ERR_INV_ARG;
751 #ifdef WITH_AGENT
752 if (client->crypto->save.sigpkey)
753 gcry_sexp_release (client->crypto->save.sigpkey);
755 client->crypto->save.sigpkey = NULL;
756 return get_pubkey (client->crypto, value, &client->crypto->save.sigpkey);
757 #else
758 return GPG_ERR_INV_ARG;
759 #endif
762 static gpg_error_t
763 parse_opt_s2k_count (void *data, void *value)
765 struct client_s *client = data;
766 char *v = value;
768 if (!v || !*v)
769 return GPG_ERR_INV_VALUE;
771 client->crypto->save.s2k_count = strtoul (v, NULL, 10);
772 return 0;
775 static gpg_error_t
776 parse_save_opt_iterations (void *data, void *value)
778 struct client_s *client = data;
779 char *v = value, *p;
780 uint64_t n;
782 if (!v || !*v)
783 return GPG_ERR_INV_VALUE;
785 errno = 0;
786 n = strtoull (v, &p, 10);
787 if (n == UINT64_MAX && errno)
788 return gpg_error_from_syserror ();
789 else if (p && *p)
790 return GPG_ERR_INV_VALUE;
792 client->crypto->save.hdr.iterations = n;
793 return 0;
796 static gpg_error_t
797 save_finalize (assuan_context_t ctx)
799 struct client_s *client = assuan_get_pointer (ctx);
800 gpg_error_t rc = 0;
801 xmlChar *xmlbuf = NULL;
802 int xmlbuflen;
803 void *key = NULL;
804 size_t keylen = 0;
806 xmlDocDumpFormatMemory (client->doc, &xmlbuf, &xmlbuflen, 0);
807 if (!xmlbuf)
808 return GPG_ERR_ENOMEM;
810 pthread_cleanup_push (xmlFree, xmlbuf);
812 if (!use_agent || ((client->flags & FLAG_NEW)
813 && (client->opts & OPT_NO_AGENT))
814 || !(client->crypto->hdr.flags & PWMD_FLAG_PKCS))
816 rc = export_common (ctx, client->flags & FLAG_NO_PINENTRY,
817 client->crypto, xmlbuf, xmlbuflen, client->filename,
818 NULL, &key, &keylen, 1, 1);
820 #ifdef WITH_AGENT
821 else
823 gcry_sexp_t pubkey = client->crypto->save.pkey;
824 gcry_sexp_t sigkey = client->crypto->save.sigpkey;
826 if (!pubkey)
827 pubkey = client->crypto->pkey_sexp;
829 if (!sigkey)
831 sigkey = client->crypto->sigpkey_sexp;
832 if (!sigkey)
834 gcry_sexp_build (&client->crypto->save.sigpkey, 0, "%S", pubkey);
835 sigkey = client->crypto->save.sigpkey;
839 rc = encrypt_data_file (client->ctx, client->crypto, pubkey, sigkey,
840 client->filename, xmlbuf, xmlbuflen);
841 if (pubkey == client->crypto->save.pkey)
843 if (!rc)
845 gcry_sexp_release (client->crypto->pkey_sexp);
846 client->crypto->pkey_sexp = client->crypto->save.pkey;
847 gcry_pk_get_keygrip (client->crypto->pkey_sexp,
848 client->crypto->grip);
850 else
851 gcry_sexp_release (pubkey);
853 client->crypto->save.pkey = NULL;
856 if (!rc)
857 gcry_pk_get_keygrip (sigkey, client->crypto->sign_grip);
859 if (sigkey == client->crypto->save.sigpkey)
861 if (!rc)
863 if (client->crypto->sigpkey_sexp)
864 gcry_sexp_release (client->crypto->sigpkey_sexp);
866 client->crypto->sigpkey_sexp = client->crypto->save.sigpkey;
867 gcry_pk_get_keygrip (client->crypto->sigpkey_sexp,
868 client->crypto->sign_grip);
870 else
871 gcry_sexp_release (sigkey);
873 client->crypto->save.sigpkey = NULL;
876 #endif
878 if (!rc)
880 int cached;
882 rc = save_common (client->filename, client->crypto, xmlbuf, xmlbuflen,
883 key, keylen, &cached, client->opts & OPT_NO_AGENT);
884 if (rc)
885 gcry_free (key);
887 if (!rc && (!cached || (client->flags & FLAG_NEW)))
888 send_status_all (STATUS_CACHE, NULL);
890 if (!rc)
892 update_checksum (client);
893 client->flags &= ~(FLAG_NEW);
895 else
896 rc = GPG_ERR_ENOMEM;
899 pthread_cleanup_pop (1); // xmlFree
900 return rc;
903 static gpg_error_t
904 parse_opt_reset (void *data, void *value)
906 struct client_s *client = data;
908 (void) value;
909 client->opts |= OPT_RESET;
910 return 0;
913 static gpg_error_t
914 save_command (assuan_context_t ctx, char *line)
916 struct client_s *client = assuan_get_pointer (ctx);
917 gpg_error_t rc;
918 struct stat st;
919 struct argv_s *args[] = {
920 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG,
921 parse_save_opt_no_passphrase},
922 &(struct argv_s) {"cipher", OPTION_TYPE_ARG, parse_save_opt_cipher},
923 &(struct argv_s) {"inquire-keyparam", OPTION_TYPE_NOARG,
924 parse_opt_inquire},
925 &(struct argv_s) {"keygrip", OPTION_TYPE_ARG, parse_save_opt_keygrip},
926 &(struct argv_s) {"sign-keygrip", OPTION_TYPE_ARG,
927 parse_save_opt_sign_keygrip},
928 &(struct argv_s) {"s2k-count", OPTION_TYPE_ARG, parse_opt_s2k_count},
929 &(struct argv_s) {"reset", OPTION_TYPE_NOARG, parse_opt_reset},
930 &(struct argv_s) {"cipher-iterations", OPTION_TYPE_ARG,
931 parse_save_opt_iterations},
932 &(struct argv_s) {"no-agent", OPTION_TYPE_NOARG,
933 parse_save_opt_no_agent},
934 NULL
937 cleanup_save (&client->crypto->save);
938 memcpy (&client->crypto->save.hdr, &client->crypto->hdr,
939 sizeof (file_header_t));
940 client->crypto->save.s2k_count =
941 config_get_ulong (client->filename, "s2k_count");
943 if (client->flags & FLAG_NEW)
944 client->crypto->save.hdr.iterations =
945 config_get_ulonglong (client->filename, "cipher_iterations");
947 rc = parse_options (&line, args, client);
948 if (rc)
949 return send_error (ctx, rc);
951 if (!(client->flags & FLAG_NEW))
952 client->opts &= ~OPT_NO_AGENT;
953 else if (client->opts & OPT_NO_AGENT)
955 client->crypto->save.hdr.flags &= ~PWMD_FLAG_PKCS;
956 client->crypto->hdr.flags &= ~PWMD_FLAG_PKCS;
959 if ((client->opts & OPT_NO_PASSPHRASE) && !(client->flags & FLAG_NEW)
960 && !(client->opts & OPT_INQUIRE))
961 return send_error (ctx, GPG_ERR_WRONG_KEY_USAGE);
963 if (lstat (client->filename, &st) == -1 && errno != ENOENT)
964 return send_error (ctx, gpg_error_from_syserror ());
966 if (errno != ENOENT && !S_ISREG (st.st_mode))
968 log_write ("%s: %s", client->filename, pwmd_strerror (GPG_ERR_ENOANO));
969 return send_error (ctx, GPG_ERR_ENOANO);
972 int defer;
973 rc = cache_iscached (client->filename, &defer);
974 if (!rc && defer)
976 log_write ("%s: %s", client->filename,
977 pwmd_strerror (GPG_ERR_KEY_EXPIRED));
978 client->opts |= OPT_RESET;
981 if (client->opts & OPT_RESET)
983 rc = cache_clear (client->md5file);
984 if (rc)
985 return send_error (ctx, rc);
987 send_status_all (STATUS_CACHE, NULL);
990 rc = update_element_mtime (xmlDocGetRootElement (client->doc));
991 if (rc)
992 return send_error (ctx, rc);
994 #ifdef WITH_AGENT
995 if (!rc && use_agent && !client->crypto->save.pkey &&
996 (client->flags & FLAG_NEW || client->opts & OPT_INQUIRE)
997 && !(client->opts & OPT_NO_AGENT))
999 rc = send_status (client->ctx, STATUS_GENKEY, NULL);
1000 if (!rc)
1002 struct inquire_data_s idata = { 0 };
1003 char *params = client->opts & OPT_INQUIRE ? NULL
1004 : default_key_params (client->crypto);
1006 pthread_cleanup_push (xfree, params);
1007 idata.crypto = client->crypto;
1009 if (params)
1011 idata.line = params;
1012 idata.len = strlen (params);
1014 else
1015 idata.preset = 1;
1017 client->crypto->agent->inquire_data = &idata;
1018 client->crypto->agent->inquire_cb = NULL;
1019 rc = generate_key (client->crypto, params,
1020 (client->opts & OPT_NO_PASSPHRASE), 1);
1021 pthread_cleanup_pop (1);
1024 #endif
1026 if (!rc)
1027 rc = save_finalize (ctx);
1029 cleanup_crypto_stage1 (client->crypto);
1030 #ifdef WITH_AGENT
1031 (void) kill_scd (client->crypto->agent);
1032 #endif
1033 return send_error (ctx, rc);
1036 static gpg_error_t
1037 do_delete (assuan_context_t ctx, char *line)
1039 struct client_s *client = assuan_get_pointer (ctx);
1040 gpg_error_t rc;
1041 char **req;
1042 xmlNodePtr n;
1044 if (strchr (line, '\t'))
1045 req = str_split (line, "\t", 0);
1046 else
1047 req = str_split (line, " ", 0);
1049 if (!req || !*req)
1050 return GPG_ERR_SYNTAX;
1052 n = find_root_element (client->doc, &req, &rc, NULL, 0, 0);
1053 if (!n)
1055 strv_free (req);
1056 return rc;
1060 * No sub-node defined. Remove the entire node (root element).
1062 if (!req[1])
1064 if (n)
1066 rc = unlink_node (n);
1067 xmlFreeNode (n);
1070 strv_free (req);
1071 return rc;
1075 find_elements (client->doc, n->children, req + 1, &rc, NULL, NULL, NULL,
1076 0, 0, NULL, 0);
1077 strv_free (req);
1078 if (!n)
1079 return rc;
1081 if (n)
1083 rc = unlink_node (n);
1084 xmlFreeNode (n);
1087 return rc;
1090 static gpg_error_t
1091 delete_command (assuan_context_t ctx, char *line)
1093 struct client_s *client = assuan_get_pointer (ctx);
1094 gpg_error_t rc;
1095 struct argv_s *args[] = {
1096 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1097 NULL
1100 rc = parse_options (&line, args, client);
1101 if (rc)
1102 return send_error (ctx, rc);
1104 if (client->opts & OPT_INQUIRE)
1106 unsigned char *result;
1107 size_t len;
1109 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1110 if (rc)
1111 return send_error (ctx, rc);
1113 line = (char *) result;
1116 rc = do_delete (ctx, line);
1118 if (client->opts & OPT_INQUIRE)
1119 xfree (line);
1121 return send_error (ctx, rc);
1124 static gpg_error_t
1125 store_command (assuan_context_t ctx, char *line)
1127 struct client_s *client = assuan_get_pointer (ctx);
1128 gpg_error_t rc;
1129 size_t len;
1130 unsigned char *result;
1131 char **req;
1132 xmlNodePtr n, parent;
1133 int has_content;
1134 char *content = NULL;
1136 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1137 if (rc)
1138 return send_error (ctx, rc);
1140 req = str_split ((char *) result, "\t", 0);
1141 xfree (result);
1143 if (!req || !*req)
1144 return send_error (ctx, GPG_ERR_SYNTAX);
1146 len = strv_length (req);
1147 has_content = line[strlen (line) - 1] != '\t' && len > 1;
1148 if (*(req + 1) && !valid_element_path (req, has_content))
1150 strv_free (req);
1151 return send_error (ctx, GPG_ERR_INV_VALUE);
1154 if (has_content || !*req[len - 1])
1156 has_content = 1;
1157 content = req[len - 1];
1158 req[len - 1] = NULL;
1161 again:
1162 n = find_root_element (client->doc, &req, &rc, NULL, 0, 0);
1163 if (rc && rc == GPG_ERR_ELEMENT_NOT_FOUND)
1165 rc = new_root_element (client->doc, *req);
1166 if (rc)
1168 strv_free (req);
1169 return send_error (ctx, GPG_ERR_SYNTAX);
1172 goto again;
1175 if (!n)
1177 strv_free (req);
1178 return send_error (ctx, rc);
1181 parent = n;
1183 if (req[1] && *req[1])
1185 if (!n->children)
1186 parent = create_elements_cb (n, req + 1, &rc, NULL);
1187 else
1188 parent = find_elements (client->doc, n->children, req + 1, &rc,
1189 NULL, NULL, create_elements_cb, 0, 0, NULL,
1193 if (!rc && len > 1)
1195 n = find_text_node (parent->children);
1196 if (n)
1197 xmlNodeSetContent (n, (xmlChar *) content);
1198 else
1199 xmlNodeAddContent (parent, (xmlChar *) content);
1201 update_element_mtime (parent);
1204 xfree (content);
1205 strv_free (req);
1206 return send_error (ctx, rc);
1209 static gpg_error_t
1210 xfer_data (assuan_context_t ctx, const char *line, int total)
1212 int to_send;
1213 int sent = 0;
1214 gpg_error_t rc;
1215 int progress = config_get_integer ("global", "xfer_progress");
1216 int flush = 0;
1218 progress =
1219 progress > 0 ? (progress / ASSUAN_LINELENGTH) * ASSUAN_LINELENGTH : 0;
1220 to_send = total < ASSUAN_LINELENGTH ? total : ASSUAN_LINELENGTH;
1221 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1223 if (rc)
1224 return rc;
1226 again:
1229 if (sent + to_send > total)
1230 to_send = total - sent;
1232 rc = assuan_send_data (ctx, flush ? NULL : (char *) line + sent,
1233 flush ? 0 : to_send);
1234 if (!rc)
1236 sent += flush ? 0 : to_send;
1238 if ((progress && !(sent % progress) && sent != total) ||
1239 (sent == total && flush))
1240 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1242 if (!flush && !rc && sent == total)
1244 flush = 1;
1245 goto again;
1249 while (!rc && sent < total);
1251 return rc;
1254 static gpg_error_t
1255 do_get (assuan_context_t ctx, char *line)
1257 struct client_s *client = assuan_get_pointer (ctx);
1258 gpg_error_t rc;
1259 char **req;
1260 xmlNodePtr n;
1262 req = str_split (line, "\t", 0);
1264 if (!req || !*req)
1266 strv_free (req);
1267 return GPG_ERR_SYNTAX;
1270 n = find_root_element (client->doc, &req, &rc, NULL, 0, 0);
1271 if (!n)
1273 strv_free (req);
1274 return rc;
1277 if (req[1])
1279 find_elements (client->doc, n->children, req + 1, &rc, NULL, NULL, NULL,
1280 0, 0, NULL, 0);
1282 strv_free (req);
1283 if (rc)
1284 return rc;
1286 if (!n || !n->children)
1287 return GPG_ERR_NO_DATA;
1289 n = find_text_node (n->children);
1290 if (!n || !n->content || !*n->content)
1291 return GPG_ERR_NO_DATA;
1293 rc = xfer_data (ctx, (char *) n->content, xmlStrlen (n->content));
1294 return rc;
1297 static gpg_error_t
1298 get_command (assuan_context_t ctx, char *line)
1300 struct client_s *client = assuan_get_pointer (ctx);
1301 gpg_error_t rc;
1302 struct argv_s *args[] = {
1303 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1304 NULL
1307 rc = parse_options (&line, args, client);
1308 if (rc)
1309 return send_error (ctx, rc);
1311 if (client->opts & OPT_INQUIRE)
1313 unsigned char *result;
1314 size_t len;
1316 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1317 if (rc)
1318 return send_error (ctx, rc);
1320 line = (char *) result;
1323 rc = do_get (ctx, line);
1325 if (client->opts & OPT_INQUIRE)
1326 xfree (line);
1328 return send_error (ctx, rc);
1331 static void list_command_cleanup1 (void *arg);
1332 static gpg_error_t
1333 realpath_command (assuan_context_t ctx, char *line)
1335 struct string_s *string = NULL;
1336 gpg_error_t rc;
1337 struct client_s *client = assuan_get_pointer (ctx);
1338 struct argv_s *args[] = {
1339 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1340 NULL
1343 rc = parse_options (&line, args, client);
1344 if (rc)
1345 return send_error (ctx, rc);
1347 if (client->opts & OPT_INQUIRE)
1349 unsigned char *result;
1350 size_t len;
1352 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1353 if (rc)
1354 return send_error (ctx, rc);
1356 line = (char *) result;
1359 rc = build_realpath (client->doc, line, &string);
1360 if (!rc)
1362 pthread_cleanup_push (list_command_cleanup1, string);
1363 rc = xfer_data (ctx, string->str, string->len);
1364 pthread_cleanup_pop (1);
1367 if (client->opts & OPT_INQUIRE)
1368 xfree (line);
1370 return send_error (ctx, rc);
1373 static void
1374 list_command_cleanup1 (void *arg)
1376 if (arg)
1377 string_free ((struct string_s *) arg, 1);
1380 static void
1381 list_command_cleanup2 (void *arg)
1383 struct element_list_s *elements = arg;
1385 if (elements)
1387 if (elements->list)
1389 int total = slist_length (elements->list);
1390 int i;
1392 for (i = 0; i < total; i++)
1394 char *tmp = slist_nth_data (elements->list, i);
1395 xfree (tmp);
1398 slist_free (elements->list);
1401 if (elements->prefix)
1402 xfree (elements->prefix);
1404 if (elements->req)
1405 strv_free (elements->req);
1407 xfree (elements);
1411 static gpg_error_t
1412 parse_list_opt_norecurse (void *data, void *value)
1414 struct client_s *client = data;
1416 client->opts &= ~(OPT_LIST_RECURSE);
1417 return 0;
1420 static gpg_error_t
1421 parse_list_opt_verbose (void *data, void *value)
1423 struct client_s *client = data;
1425 client->opts |= OPT_LIST_VERBOSE;
1426 return 0;
1429 static gpg_error_t
1430 parse_list_opt_target (void *data, void *value)
1432 struct client_s *client = data;
1434 client->opts |= OPT_LIST_WITH_TARGET;
1435 return 0;
1438 static gpg_error_t
1439 parse_list_opt_all (void *data, void *value)
1441 struct client_s *client = data;
1443 client->opts |= OPT_LIST_ALL;
1444 return 0;
1447 static gpg_error_t
1448 list_path_once (struct client_s *client, char *line,
1449 struct element_list_s *elements, struct string_s *result)
1451 gpg_error_t rc;
1453 elements->req = str_split (line, " ", 0);
1454 if (!elements->req)
1455 strv_printf (&elements->req, "%s", line);
1457 rc = create_path_list (client->doc, elements, *elements->req);
1458 if (rc == GPG_ERR_ELOOP && elements->verbose)
1459 rc = 0;
1461 if (!rc)
1463 int total = slist_length (elements->list);
1464 int i;
1466 if (!total)
1467 rc = GPG_ERR_NO_DATA;
1469 if (!rc)
1471 if (!rc)
1473 for (i = 0; i < total; i++)
1475 char *tmp = slist_nth_data (elements->list, i);
1477 string_append_printf (result, "%s%s", tmp,
1478 i + 1 == total ? "" : "\n");
1482 else
1483 rc = GPG_ERR_NO_DATA;
1486 return rc;
1489 static int
1490 has_list_flag (char *path, char *flags)
1492 char *p = path;
1494 while (*p && *++p != ' ');
1496 if (!*p)
1497 return 0;
1499 for (; *p; p++)
1501 char *f;
1503 for (f = flags; *f && *f != ' '; f++)
1505 if (*p == *f)
1506 return 1;
1510 return 0;
1513 static gpg_error_t
1514 do_list (assuan_context_t ctx, char *line)
1516 struct client_s *client = assuan_get_pointer (ctx);
1517 gpg_error_t rc;
1518 struct element_list_s *elements = NULL;
1520 elements = xcalloc (1, sizeof (struct element_list_s));
1521 if (!elements)
1522 return GPG_ERR_ENOMEM;
1524 elements->recurse = client->opts & OPT_LIST_RECURSE;
1525 elements->verbose =
1526 (client->opts & OPT_LIST_VERBOSE) | (client->opts & OPT_LIST_WITH_TARGET);
1527 elements->with_target = client->opts & OPT_LIST_WITH_TARGET;
1529 if (!line || !*line)
1531 struct string_s *str = NULL;
1533 pthread_cleanup_push (list_command_cleanup2, elements);
1534 rc = list_root_elements (client->doc, &str, elements->verbose,
1535 elements->with_target);
1536 pthread_cleanup_pop (1);
1537 pthread_cleanup_push (list_command_cleanup1, str);
1539 if (!rc)
1541 if (client->opts & OPT_LIST_ALL)
1543 char **roots = str_split (str->str, "\n", 0);
1544 char **p;
1546 pthread_cleanup_push (req_cleanup, roots);
1547 string_truncate (str, 0);
1549 for (p = roots; *p; p++)
1551 if (strchr (*p, ' '))
1553 if (has_list_flag (*p, "EO"))
1555 string_append_printf (str, "%s%s", *p,
1556 *(p + 1) ? "\n" : "");
1557 continue;
1561 elements = xcalloc (1, sizeof (struct element_list_s));
1562 if (!elements)
1564 rc = GPG_ERR_ENOMEM;
1565 break;
1568 elements->recurse = client->opts & OPT_LIST_RECURSE;
1569 elements->verbose =
1570 (client->opts & OPT_LIST_VERBOSE) | (client->opts &
1571 OPT_LIST_WITH_TARGET);
1572 elements->with_target = client->opts & OPT_LIST_WITH_TARGET;
1573 pthread_cleanup_push (list_command_cleanup2, elements);
1574 rc = list_path_once (client, *p, elements, str);
1575 pthread_cleanup_pop (1);
1576 if (rc)
1577 break;
1579 if (*(p + 1))
1580 string_append (str, "\n");
1583 pthread_cleanup_pop (1);
1586 if (!rc)
1587 rc = xfer_data (ctx, str->str, str->len);
1590 pthread_cleanup_pop (1);
1591 return rc;
1594 pthread_cleanup_push (list_command_cleanup2, elements);
1595 struct string_s *str = string_new (NULL);
1596 pthread_cleanup_push (list_command_cleanup1, str);
1597 rc = list_path_once (client, line, elements, str);
1598 if (!rc)
1599 rc = xfer_data (ctx, str->str, str->len);
1601 pthread_cleanup_pop (1);
1602 pthread_cleanup_pop (1);
1603 return rc;
1606 static gpg_error_t
1607 list_command (assuan_context_t ctx, char *line)
1609 struct client_s *client = assuan_get_pointer (ctx);
1610 gpg_error_t rc;
1611 struct argv_s *args[] = {
1612 &(struct argv_s) {"no-recurse", OPTION_TYPE_NOARG,
1613 parse_list_opt_norecurse},
1614 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_list_opt_verbose},
1615 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1616 &(struct argv_s) {"with-target", OPTION_TYPE_NOARG,
1617 parse_list_opt_target},
1618 &(struct argv_s) {"all", OPTION_TYPE_NOARG, parse_list_opt_all},
1619 NULL
1622 if (disable_list_and_dump == 1)
1623 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
1625 client->opts |= OPT_LIST_RECURSE;
1626 rc = parse_options (&line, args, client);
1627 if (rc)
1628 return send_error (ctx, rc);
1630 if (client->opts & OPT_LIST_ALL)
1631 client->opts |= OPT_LIST_RECURSE | OPT_LIST_VERBOSE;
1633 if (client->opts & OPT_INQUIRE)
1635 unsigned char *result;
1636 size_t len;
1638 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1639 if (rc)
1640 return send_error (ctx, rc);
1642 line = (char *) result;
1645 rc = do_list (ctx, line);
1647 if (client->opts & OPT_INQUIRE)
1648 xfree (line);
1650 return send_error (ctx, rc);
1654 * req[0] - element path
1656 static gpg_error_t
1657 attribute_list (assuan_context_t ctx, char **req)
1659 struct client_s *client = assuan_get_pointer (ctx);
1660 char **attrlist = NULL;
1661 int i = 0;
1662 char **path = NULL;
1663 xmlAttrPtr a;
1664 xmlNodePtr n, an;
1665 char *line;
1666 gpg_error_t rc;
1668 if (!req || !req[0])
1669 return GPG_ERR_SYNTAX;
1671 if ((path = str_split (req[0], "\t", 0)) == NULL)
1674 * The first argument may be only a root element.
1676 if ((path = str_split (req[0], " ", 0)) == NULL)
1677 return GPG_ERR_SYNTAX;
1680 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
1682 if (!n)
1684 strv_free (path);
1685 return rc;
1688 if (path[1])
1690 n = find_elements (client->doc, n->children, path + 1, &rc,
1691 NULL, NULL, NULL, 0, 0, NULL, 0);
1693 if (!n)
1695 strv_free (path);
1696 return rc;
1700 strv_free (path);
1702 for (a = n->properties; a; a = a->next)
1704 char **pa;
1706 if ((pa = xrealloc (attrlist, (i + 2) * sizeof (char *))) == NULL)
1708 if (attrlist)
1709 strv_free (attrlist);
1711 log_write ("%s(%i): %s", __FILE__, __LINE__,
1712 pwmd_strerror (GPG_ERR_ENOMEM));
1713 return GPG_ERR_ENOMEM;
1716 attrlist = pa;
1717 an = a->children;
1718 attrlist[i] = str_asprintf ("%s %s", (char *) a->name,
1720 && an->content ? (char *) an->content : "");
1722 if (!attrlist[i])
1724 strv_free (attrlist);
1725 log_write ("%s(%i): %s", __FILE__, __LINE__,
1726 pwmd_strerror (GPG_ERR_ENOMEM));
1727 return GPG_ERR_ENOMEM;
1730 attrlist[++i] = NULL;
1733 if (!attrlist)
1734 return GPG_ERR_NO_DATA;
1736 line = strv_join ("\n", attrlist);
1738 if (!line)
1740 log_write ("%s(%i): %s", __FILE__, __LINE__,
1741 pwmd_strerror (GPG_ERR_ENOMEM));
1742 strv_free (attrlist);
1743 return GPG_ERR_ENOMEM;
1746 pthread_cleanup_push (xfree, line);
1747 pthread_cleanup_push (req_cleanup, attrlist);
1748 rc = xfer_data (ctx, line, strlen (line));
1749 pthread_cleanup_pop (1);
1750 pthread_cleanup_pop (1);
1751 return rc;
1755 * req[0] - attribute
1756 * req[1] - element path
1758 static gpg_error_t
1759 attribute_delete (struct client_s *client, char **req)
1761 xmlNodePtr n;
1762 char **path = NULL;
1763 gpg_error_t rc;
1765 if (!req || !req[0] || !req[1])
1766 return GPG_ERR_SYNTAX;
1768 if (!strcmp (req[0], "_name"))
1769 return GPG_ERR_INV_ATTR;
1771 if ((path = str_split (req[1], "\t", 0)) == NULL)
1774 * The first argument may be only a root element.
1776 if ((path = str_split (req[1], " ", 0)) == NULL)
1777 return GPG_ERR_SYNTAX;
1780 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
1781 if (!n)
1782 goto fail;
1784 if (path[1])
1786 n = find_elements (client->doc, n->children, path + 1, &rc,
1787 NULL, NULL, NULL, 0, 0, NULL, 0);
1788 if (!n)
1789 goto fail;
1792 rc = delete_attribute (n, (xmlChar *) req[0]);
1794 fail:
1795 strv_free (path);
1796 return rc;
1799 static xmlNodePtr
1800 create_element_path (struct client_s *client,
1801 char ***elements, gpg_error_t * rc, xmlNodePtr parent)
1803 char **req = *elements;
1804 char **req_orig = strv_dup (req);
1805 xmlNodePtr n = NULL;
1807 *rc = 0;
1809 if (!req_orig)
1811 *rc = GPG_ERR_ENOMEM;
1812 log_write ("%s(%i): %s", __FILE__, __LINE__,
1813 pwmd_strerror (GPG_ERR_ENOMEM));
1814 goto fail;
1817 again:
1818 n = find_root_element (client->doc, &req, rc, NULL, 0, 0);
1819 if (!n)
1821 if (*rc != GPG_ERR_ELEMENT_NOT_FOUND)
1822 goto fail;
1824 *rc = new_root_element (client->doc, req[0]);
1825 if (*rc)
1826 goto fail;
1828 goto again;
1830 else if (n == parent)
1832 *rc = GPG_ERR_CONFLICT;
1833 goto fail;
1836 if (req[1])
1838 if (!n->children)
1839 n = create_target_elements_cb (n, req + 1, rc, NULL);
1840 else
1841 n = find_elements (client->doc, n->children, req + 1, rc, NULL, NULL,
1842 create_target_elements_cb, 0, 0, parent, 0);
1844 if (!n)
1845 goto fail;
1848 * Reset the position of the element tree now that the elements
1849 * have been created.
1851 strv_free (req);
1852 req = req_orig;
1853 req_orig = NULL;
1854 n = find_root_element (client->doc, &req, rc, NULL, 0, 0);
1855 if (!n)
1856 goto fail;
1858 n = find_elements (client->doc, n->children, req + 1, rc,
1859 NULL, NULL, NULL, 0, 0, NULL, 0);
1860 if (!n)
1861 goto fail;
1864 fail:
1865 if (req_orig)
1866 strv_free (req_orig);
1868 *elements = req;
1869 return n;
1873 * Creates a "target" attribute. When other commands encounter an element with
1874 * this attribute, the element path is modified to the target value. If the
1875 * source element path doesn't exist when using 'ATTR SET target', it is
1876 * created, but the destination element path must exist.
1878 * req[0] - source element path
1879 * req[1] - destination element path
1881 static gpg_error_t
1882 target_attribute (struct client_s *client, char **req)
1884 char **src, **dst, *line = NULL, **odst = NULL;
1885 gpg_error_t rc;
1886 xmlNodePtr n;
1888 if (!req || !req[0] || !req[1])
1889 return GPG_ERR_SYNTAX;
1891 if ((src = str_split (req[0], "\t", 0)) == NULL)
1894 * The first argument may be only a root element.
1896 if ((src = str_split (req[0], " ", 0)) == NULL)
1897 return GPG_ERR_SYNTAX;
1900 if (!valid_element_path (src, 0))
1901 return GPG_ERR_INV_VALUE;
1903 if ((dst = str_split (req[1], "\t", 0)) == NULL)
1906 * The first argument may be only a root element.
1908 if ((dst = str_split (req[1], " ", 0)) == NULL)
1910 rc = GPG_ERR_SYNTAX;
1911 goto fail;
1915 odst = strv_dup (dst);
1916 if (!odst)
1918 rc = GPG_ERR_ENOMEM;
1919 goto fail;
1922 n = find_root_element (client->doc, &dst, &rc, NULL, 0, 0);
1924 * Make sure the destination element path exists.
1926 if (!n)
1927 goto fail;
1929 if (dst[1])
1931 n = find_elements (client->doc, n->children, dst + 1, &rc,
1932 NULL, NULL, NULL, 0, 0, NULL, 0);
1933 if (!n)
1934 goto fail;
1937 rc = validate_target_attribute (client->doc, req[0], n);
1938 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
1939 goto fail;
1941 n = create_element_path (client, &src, &rc, NULL);
1942 if (rc)
1943 goto fail;
1945 line = strv_join ("\t", odst);
1946 if (!line)
1948 rc = GPG_ERR_ENOMEM;
1949 goto fail;
1952 rc = add_attribute (n, "target", line);
1954 fail:
1955 xfree (line);
1956 strv_free (src);
1957 strv_free (dst);
1958 strv_free (odst);
1959 return rc;
1963 * req[0] - attribute
1964 * req[1] - element path
1966 static gpg_error_t
1967 attribute_get (assuan_context_t ctx, char **req)
1969 struct client_s *client = assuan_get_pointer (ctx);
1970 xmlNodePtr n;
1971 xmlChar *a;
1972 char **path = NULL;
1973 gpg_error_t rc;
1975 if (!req || !req[0] || !req[1])
1976 return GPG_ERR_SYNTAX;
1978 if (strchr (req[1], '\t'))
1980 if ((path = str_split (req[1], "\t", 0)) == NULL)
1981 return GPG_ERR_SYNTAX;
1983 else
1985 if ((path = str_split (req[1], " ", 0)) == NULL)
1986 return GPG_ERR_SYNTAX;
1989 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
1991 if (!n)
1992 goto fail;
1994 if (path[1])
1996 n = find_elements (client->doc, n->children, path + 1, &rc,
1997 NULL, NULL, NULL, 0, 0, NULL, 0);
1999 if (!n)
2000 goto fail;
2003 strv_free (path);
2005 if ((a = xmlGetProp (n, (xmlChar *) req[0])) == NULL)
2006 return GPG_ERR_NOT_FOUND;
2008 pthread_cleanup_push (xmlFree, a);
2010 if (*a)
2011 rc = xfer_data (ctx, (char *) a, xmlStrlen (a));
2012 else
2013 rc = GPG_ERR_NO_DATA;
2015 pthread_cleanup_pop (1);
2016 return rc;
2018 fail:
2019 strv_free (path);
2020 return rc;
2024 * req[0] - attribute
2025 * req[1] - element path
2026 * req[2] - value
2028 static gpg_error_t
2029 attribute_set (struct client_s *client, char **req)
2031 char **path = NULL;
2032 gpg_error_t rc;
2033 xmlNodePtr n;
2035 if (!req || !req[0] || !req[1])
2036 return GPG_ERR_SYNTAX;
2039 * Reserved attribute names.
2041 if (!strcmp (req[0], "_name"))
2042 return GPG_ERR_INV_ATTR;
2043 else if (!strcmp (req[0], "target"))
2044 return target_attribute (client, req + 1);
2046 if ((path = str_split (req[1], "\t", 0)) == NULL)
2049 * The first argument may be only a root element.
2051 if ((path = str_split (req[1], " ", 0)) == NULL)
2052 return GPG_ERR_SYNTAX;
2055 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
2057 if (!n)
2058 goto fail;
2060 if (path[1])
2062 n = find_elements (client->doc, n->children, path + 1, &rc,
2063 NULL, NULL, NULL, 0, 0, NULL, 0);
2065 if (!n)
2066 goto fail;
2069 rc = add_attribute (n, req[0], req[2]);
2071 fail:
2072 strv_free (path);
2073 return rc;
2077 * req[0] - command
2078 * req[1] - attribute name or element path if command is LIST
2079 * req[2] - element path
2080 * req[2] - element path or value
2083 static gpg_error_t
2084 do_attr (assuan_context_t ctx, char *line)
2086 struct client_s *client = assuan_get_pointer (ctx);
2087 gpg_error_t rc = 0;
2088 char **req;
2090 req = str_split (line, " ", 4);
2091 if (!req || !req[0] || !req[1])
2093 strv_free (req);
2094 return GPG_ERR_SYNTAX;
2097 pthread_cleanup_push (req_cleanup, req);
2099 if (strcasecmp (req[0], "SET") == 0)
2100 rc = attribute_set (client, req + 1);
2101 else if (strcasecmp (req[0], "GET") == 0)
2102 rc = attribute_get (ctx, req + 1);
2103 else if (strcasecmp (req[0], "DELETE") == 0)
2104 rc = attribute_delete (client, req + 1);
2105 else if (strcasecmp (req[0], "LIST") == 0)
2106 rc = attribute_list (ctx, req + 1);
2107 else
2108 rc = GPG_ERR_SYNTAX;
2110 pthread_cleanup_pop (1);
2111 return rc;
2114 static gpg_error_t
2115 attr_command (assuan_context_t ctx, char *line)
2117 struct client_s *client = assuan_get_pointer (ctx);
2118 gpg_error_t rc;
2119 struct argv_s *args[] = {
2120 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2121 NULL
2124 rc = parse_options (&line, args, client);
2125 if (rc)
2126 return send_error (ctx, rc);
2128 if (client->opts & OPT_INQUIRE)
2130 unsigned char *result;
2131 size_t len;
2133 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2134 if (rc)
2135 return send_error (ctx, rc);
2137 line = (char *) result;
2140 rc = do_attr (ctx, line);
2142 if (client->opts & OPT_INQUIRE)
2143 xfree (line);
2145 return send_error (ctx, rc);
2148 static gpg_error_t
2149 parse_iscached_opt_lock (void *data, void *value)
2151 struct client_s *client = data;
2153 (void) value;
2154 client->opts |= OPT_LOCK;
2155 return 0;
2158 static gpg_error_t
2159 iscached_command (assuan_context_t ctx, char *line)
2161 struct client_s *client = assuan_get_pointer (ctx);
2162 gpg_error_t rc;
2163 unsigned char md5file[16];
2164 struct argv_s *args[] = {
2165 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_iscached_opt_lock},
2166 NULL
2169 if (!line || !*line)
2170 return send_error (ctx, GPG_ERR_SYNTAX);
2172 rc = parse_options (&line, args, client);
2173 if (rc)
2174 return send_error (ctx, rc);
2175 else if (!valid_filename (line))
2176 return send_error (ctx, GPG_ERR_INV_VALUE);
2178 rc = cache_iscached (line, NULL);
2179 if (client->opts & OPT_LOCK
2180 && (!rc || gpg_err_code (rc) == GPG_ERR_NO_DATA))
2182 gpg_error_t trc = rc;
2183 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2184 if (memcmp (md5file, client->md5file, 16))
2185 cleanup_client (client);
2187 memcpy (client->md5file, md5file, 16);
2188 rc = do_lock (client, 1);
2189 if (!rc)
2190 rc = trc;
2193 return send_error (ctx, rc);
2196 static gpg_error_t
2197 clearcache_command (assuan_context_t ctx, char *line)
2199 gpg_error_t rc = 0, all_rc = 0;
2200 unsigned char md5file[16];
2201 int i;
2202 int t;
2203 int all = 0;
2204 struct client_thread_s *once = NULL;
2206 cache_lock ();
2207 MUTEX_LOCK (&cn_mutex);
2208 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
2210 if (!line || !*line)
2211 all = 1;
2213 t = slist_length (cn_thread_list);
2215 for (i = 0; i < t; i++)
2217 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2219 if (!thd->cl)
2220 continue;
2222 /* Lock each connected clients' file mutex to prevent any other client
2223 * from accessing the cache entry (the file mutex is locked upon
2224 * command startup). The cache for the entry is not cleared if the
2225 * file mutex is locked by another client to prevent this function
2226 * from blocking.
2228 if (all)
2230 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0, -1);
2231 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2233 if (pthread_equal (pthread_self (), thd->tid))
2234 rc = 0;
2235 else
2237 if (!thd->cl->filename ||
2238 cache_iscached (thd->cl->filename,
2239 NULL) == GPG_ERR_NO_DATA)
2241 rc = 0;
2242 continue;
2245 cache_defer_clear (thd->cl->md5file);
2248 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
2250 rc = 0;
2251 continue;
2254 if (!rc)
2256 rc = cache_clear (thd->cl->md5file);
2257 if (rc)
2258 all_rc = rc;
2260 cache_unlock_mutex (thd->cl->md5file, 0);
2262 else
2263 all_rc = rc;
2265 rc = 0;
2267 /* A single data filename was specified. Lock only this data file
2268 * mutex and free the cache entry. */
2269 else
2271 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2273 if (!memcmp (thd->cl->md5file, md5file, sizeof (md5file)))
2275 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0,
2276 -1);
2277 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2279 if (pthread_equal (pthread_self (), thd->tid))
2280 rc = 0;
2283 if (!rc)
2285 once = thd;
2286 rc = cache_clear (thd->cl->md5file);
2287 cache_unlock_mutex (thd->cl->md5file, 0);
2289 else
2291 cache_defer_clear (thd->cl->md5file);
2294 break;
2299 /* Only connected clients' cache entries have been cleared. Now clear any
2300 * remaining cache entries without clients but only if there wasn't an
2301 * error from above since this would defeat the locking check of the
2302 * remaining entries. */
2303 if (!all_rc && all)
2305 cache_clear (NULL);
2308 /* No clients are using the specified file. */
2309 else if (!all_rc && !rc && !once)
2311 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2312 rc = cache_clear (md5file);
2315 /* Release the connection mutex. */
2316 pthread_cleanup_pop (1);
2317 cache_unlock ();
2319 if (!rc)
2320 send_status_all (STATUS_CACHE, NULL);
2322 /* One or more files were locked while clearing all cache entries. */
2323 if (all_rc)
2324 rc = all_rc;
2326 return send_error (ctx, rc);
2329 static gpg_error_t
2330 cachetimeout_command (assuan_context_t ctx, char *line)
2332 unsigned char md5file[16];
2333 int timeout;
2334 char **req = str_split (line, " ", 0);
2335 char *p;
2336 gpg_error_t rc = 0;
2338 if (!req || !*req || !req[1])
2340 strv_free (req);
2341 return send_error (ctx, GPG_ERR_SYNTAX);
2344 errno = 0;
2345 timeout = (int) strtol (req[1], &p, 10);
2346 if (errno != 0 || *p || timeout < -1)
2348 strv_free (req);
2349 return send_error (ctx, GPG_ERR_SYNTAX);
2352 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, req[0], strlen (req[0]));
2353 rc = cache_set_timeout (md5file, timeout);
2354 if (!rc || gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
2356 rc = 0;
2357 MUTEX_LOCK (&rcfile_mutex);
2358 config_set_int_param (&global_config, req[0], "cache_timeout", req[1]);
2359 MUTEX_UNLOCK (&rcfile_mutex);
2362 strv_free (req);
2363 return send_error (ctx, rc);
2366 static gpg_error_t
2367 dump_command (assuan_context_t ctx, char *line)
2369 xmlChar *xml;
2370 int len;
2371 struct client_s *client = assuan_get_pointer (ctx);
2372 gpg_error_t rc;
2374 if (disable_list_and_dump == 1)
2375 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2377 xmlDocDumpFormatMemory (client->doc, &xml, &len, 1);
2379 if (!xml)
2381 log_write ("%s(%i): %s", __FILE__, __LINE__,
2382 pwmd_strerror (GPG_ERR_ENOMEM));
2383 return send_error (ctx, GPG_ERR_ENOMEM);
2386 pthread_cleanup_push (xmlFree, xml);
2387 rc = xfer_data (ctx, (char *) xml, len);
2388 pthread_cleanup_pop (1);
2389 return send_error (ctx, rc);
2392 static gpg_error_t
2393 getconfig_command (assuan_context_t ctx, char *line)
2395 struct client_s *client = assuan_get_pointer (ctx);
2396 gpg_error_t rc = 0;
2397 char filename[255] = { 0 }, param[747] =
2400 char *p, *tmp = NULL, *fp = client->filename, *paramp = line;
2402 if (!line || !*line)
2403 return send_error (ctx, GPG_ERR_SYNTAX);
2405 if (strchr (line, ' '))
2407 sscanf (line, " %254[^ ] %746c", filename, param);
2408 paramp = param;
2409 fp = filename;
2412 if (fp && !valid_filename (fp))
2413 return send_error (ctx, GPG_ERR_INV_VALUE);
2415 paramp = str_down (paramp);
2416 if (!strcmp (paramp, "cipher") && fp)
2418 struct crypto_s *crypto = NULL;
2420 rc = init_client_crypto (&crypto);
2421 if (!rc)
2423 rc = read_data_header (fp, &crypto->hdr, NULL, NULL);
2424 if (!rc)
2426 const char *t =
2427 gcry_cipher_algo_name (cipher_to_gcrypt (crypto->hdr.flags));
2428 if (t)
2430 tmp = str_dup (t);
2431 if (tmp)
2432 str_down (tmp);
2437 UPDATE_AGENT_CTX (client, crypto);
2438 cleanup_crypto (&crypto);
2439 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
2440 return send_error (ctx, rc);
2442 if (!rc && tmp)
2443 goto done;
2445 else if (!strcmp (paramp, "cipher_iterations") && fp)
2447 struct crypto_s *crypto = NULL;
2449 rc = init_client_crypto (&crypto);
2450 if (!rc)
2452 rc = read_data_header (fp, &crypto->hdr, NULL, NULL);
2453 if (!rc)
2455 tmp = str_asprintf ("%llu",
2456 (unsigned long long) crypto->hdr.
2457 iterations);
2458 if (!tmp)
2459 rc = GPG_ERR_ENOMEM;
2463 UPDATE_AGENT_CTX (client, crypto);
2464 cleanup_crypto (&crypto);
2465 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
2466 return send_error (ctx, rc);
2468 if (!rc && tmp)
2469 goto done;
2471 else if (!strcmp (paramp, "passphrase"))
2472 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2474 p = config_get_value (fp ? fp : "global", paramp);
2475 if (!p)
2476 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2478 tmp = expand_homedir (p);
2479 xfree (p);
2480 if (!tmp)
2482 log_write ("%s(%i): %s", __FILE__, __LINE__,
2483 pwmd_strerror (GPG_ERR_ENOMEM));
2484 return send_error (ctx, GPG_ERR_ENOMEM);
2487 done:
2488 p = tmp;
2489 pthread_cleanup_push (xfree, p);
2490 rc = xfer_data (ctx, p, strlen (p));
2491 pthread_cleanup_pop (1);
2492 return send_error (ctx, rc);
2495 struct xpath_s
2497 xmlXPathContextPtr xp;
2498 xmlXPathObjectPtr result;
2499 xmlBufferPtr buf;
2500 char **req;
2503 static void
2504 xpath_command_cleanup (void *arg)
2506 struct xpath_s *xpath = arg;
2508 if (!xpath)
2509 return;
2511 req_cleanup (xpath->req);
2513 if (xpath->buf)
2514 xmlBufferFree (xpath->buf);
2516 if (xpath->result)
2517 xmlXPathFreeObject (xpath->result);
2519 if (xpath->xp)
2520 xmlXPathFreeContext (xpath->xp);
2523 static gpg_error_t
2524 do_xpath (assuan_context_t ctx, char *line)
2526 gpg_error_t rc;
2527 struct client_s *client = assuan_get_pointer (ctx);
2528 struct xpath_s _x = { 0 };
2529 struct xpath_s *xpath = &_x;
2531 if ((xpath->req = str_split (line, "\t", 2)) == NULL)
2533 if (strv_printf (&xpath->req, "%s", line) == 0)
2534 return GPG_ERR_ENOMEM;
2537 xpath->xp = xmlXPathNewContext (client->doc);
2538 if (!xpath->xp)
2540 rc = GPG_ERR_BAD_DATA;
2541 goto fail;
2544 xpath->result =
2545 xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2546 if (!xpath->result)
2548 rc = GPG_ERR_BAD_DATA;
2549 goto fail;
2552 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2554 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2555 goto fail;
2558 rc = recurse_xpath_nodeset (client->doc, xpath->result->nodesetval,
2559 (xmlChar *) xpath->req[1], &xpath->buf, 0,
2560 NULL);
2561 if (rc)
2562 goto fail;
2563 else if (!xpath->req[1] && !xmlBufferLength (xpath->buf))
2565 rc = GPG_ERR_NO_DATA;
2566 goto fail;
2568 else if (xpath->req[1])
2570 rc = 0;
2571 goto fail;
2574 pthread_cleanup_push (xpath_command_cleanup, &xpath);
2575 rc = xfer_data (ctx, (char *) xmlBufferContent (xpath->buf),
2576 xmlBufferLength (xpath->buf));
2577 pthread_cleanup_pop (0);
2578 fail:
2579 xpath_command_cleanup (xpath);
2580 return rc;
2583 static gpg_error_t
2584 xpath_command (assuan_context_t ctx, char *line)
2586 struct client_s *client = assuan_get_pointer (ctx);
2587 gpg_error_t rc;
2588 struct argv_s *args[] = {
2589 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2590 NULL
2593 if (disable_list_and_dump == 1)
2594 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2596 rc = parse_options (&line, args, client);
2597 if (rc)
2598 return send_error (ctx, rc);
2600 if (client->opts & OPT_INQUIRE)
2602 unsigned char *result;
2603 size_t len;
2605 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2606 if (rc)
2607 return send_error (ctx, rc);
2609 line = (char *) result;
2612 if (!line || !*line)
2613 rc = GPG_ERR_SYNTAX;
2615 if (!rc)
2616 rc = do_xpath (ctx, line);
2618 if (client->opts & OPT_INQUIRE)
2619 xfree (line);
2621 return send_error (ctx, rc);
2624 static gpg_error_t
2625 do_xpathattr (assuan_context_t ctx, char *line)
2627 struct client_s *client = assuan_get_pointer (ctx);
2628 gpg_error_t rc;
2629 char **req = NULL;
2630 int cmd = 0; //SET
2631 struct xpath_s _x = { 0 };
2632 struct xpath_s *xpath = &_x;
2634 if ((req = str_split (line, " ", 3)) == NULL)
2635 return GPG_ERR_ENOMEM;
2637 if (!req[0])
2639 rc = GPG_ERR_SYNTAX;
2640 goto fail;
2643 if (!strcasecmp (req[0], "SET"))
2644 cmd = 0;
2645 else if (!strcasecmp (req[0], "DELETE"))
2646 cmd = 1;
2647 else
2649 rc = GPG_ERR_SYNTAX;
2650 goto fail;
2653 if (!req[1] || !req[2])
2655 rc = GPG_ERR_SYNTAX;
2656 goto fail;
2659 if ((xpath->req = str_split (req[2], "\t", 3)) == NULL)
2661 rc = GPG_ERR_ENOMEM;
2662 goto fail;
2665 if (!xpath->req[0] || (!xpath->req[1] && !cmd) || (xpath->req[1] && cmd))
2667 rc = GPG_ERR_SYNTAX;
2668 goto fail;
2671 xpath->xp = xmlXPathNewContext (client->doc);
2672 if (!xpath->xp)
2674 rc = GPG_ERR_BAD_DATA;
2675 goto fail;
2678 xpath->result =
2679 xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2680 if (!xpath->result)
2682 rc = GPG_ERR_BAD_DATA;
2683 goto fail;
2686 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2688 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2689 goto fail;
2692 rc = recurse_xpath_nodeset (client->doc, xpath->result->nodesetval,
2693 (xmlChar *) xpath->req[1], &xpath->buf, cmd,
2694 (xmlChar *) req[1]);
2696 fail:
2697 xpath_command_cleanup (xpath);
2698 strv_free (req);
2699 return rc;
2702 /* XPATHATTR SET|DELETE <name> <expression>[<TAB>[value]] */
2703 static gpg_error_t
2704 xpathattr_command (assuan_context_t ctx, char *line)
2706 struct client_s *client = assuan_get_pointer (ctx);
2707 gpg_error_t rc;
2708 struct argv_s *args[] = {
2709 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2710 NULL
2713 if (disable_list_and_dump == 1)
2714 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2716 rc = parse_options (&line, args, client);
2717 if (rc)
2718 return send_error (ctx, rc);
2720 if (client->opts & OPT_INQUIRE)
2722 unsigned char *result;
2723 size_t len;
2725 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2726 if (rc)
2727 return send_error (ctx, rc);
2729 line = (char *) result;
2732 if (!line || !*line)
2733 rc = GPG_ERR_SYNTAX;
2735 if (!rc)
2736 rc = do_xpathattr (ctx, line);
2738 if (client->opts & OPT_INQUIRE)
2739 xfree (line);
2741 return send_error (ctx, rc);
2744 static gpg_error_t
2745 do_import (struct client_s *client, unsigned char *line)
2747 char **req, **path = NULL, **path_orig = NULL, *content;
2748 xmlDocPtr doc = NULL;
2749 xmlNodePtr n, root, copy;
2750 gpg_error_t rc;
2752 req = str_split ((char *) line, "\t", 2);
2753 xfree (line);
2754 if (!req || !*req)
2755 return GPG_ERR_SYNTAX;
2757 content = req[0];
2758 path = str_split (req[1], "\t", 0);
2759 if (!content || !*content)
2761 rc = GPG_ERR_SYNTAX;
2762 goto fail;
2765 if (path && !valid_element_path (path, 0))
2767 rc = GPG_ERR_INV_VALUE;
2768 goto fail;
2771 doc = xmlReadDoc ((xmlChar *) content, NULL, "UTF-8", XML_PARSE_NOBLANKS);
2772 if (!doc)
2774 rc = GPG_ERR_BAD_DATA;
2775 goto fail;
2778 root = xmlDocGetRootElement (doc);
2779 rc = validate_import (root);
2780 if (rc)
2781 goto fail;
2783 if (path)
2785 path_orig = strv_dup (path);
2786 if (!path_orig)
2788 log_write ("%s(%i): %s", __FILE__, __LINE__,
2789 pwmd_strerror (GPG_ERR_ENOMEM));
2790 rc = GPG_ERR_ENOMEM;
2791 goto fail;
2794 xmlChar *a = xmlGetProp (root, (xmlChar *) "_name");
2795 if (!a)
2797 strv_free (path_orig);
2798 rc = GPG_ERR_ENOMEM;
2799 goto fail;
2802 if (strv_printf (&path, "%s", (char *) a) == 0)
2804 xmlFree (a);
2805 strv_free (path_orig);
2806 rc = GPG_ERR_ENOMEM;
2807 goto fail;
2810 xmlFree (a);
2811 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
2813 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2815 strv_free (path_orig);
2816 goto fail;
2819 if (!rc)
2822 find_elements (client->doc, n->children, path + 1, &rc, NULL,
2823 NULL, NULL, 0, 0, NULL, 1);
2825 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2827 strv_free (path_orig);
2828 goto fail;
2830 else if (!rc)
2832 xmlNodePtr parent = n->parent;
2834 xmlUnlinkNode (n);
2835 xmlFreeNode (n);
2836 n = parent;
2840 strv_free (path);
2841 path = path_orig;
2843 if (rc == GPG_ERR_ELEMENT_NOT_FOUND)
2845 n = create_element_path (client, &path, &rc, NULL);
2847 if (rc)
2848 goto fail;
2851 copy = xmlCopyNodeList (root);
2852 n = xmlAddChildList (n, copy);
2853 if (!n)
2854 rc = GPG_ERR_BAD_DATA;
2856 else
2858 /* Check if the content root element can create a DTD root element. */
2859 if (!xmlStrEqual ((xmlChar *) "element", root->name))
2861 rc = GPG_ERR_SYNTAX;
2862 goto fail;
2865 xmlChar *a;
2867 if ((a = xmlGetProp (root, (xmlChar *) "_name")) == NULL)
2869 rc = GPG_ERR_SYNTAX;
2870 goto fail;
2873 char *tmp = str_dup ((char *) a);
2874 xmlFree (a);
2875 int literal = is_literal_element (&tmp);
2877 if (!valid_xml_element ((xmlChar *) tmp) || literal)
2879 xfree (tmp);
2880 rc = GPG_ERR_INV_VALUE;
2881 goto fail;
2884 if (strv_printf (&path, "%s", tmp) == 0)
2886 xfree (tmp);
2887 rc = GPG_ERR_ENOMEM;
2888 goto fail;
2891 xfree (tmp);
2892 n = find_root_element (client->doc, &path, &rc, NULL, 0, 1);
2894 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2896 rc = GPG_ERR_BAD_DATA;
2897 goto fail;
2900 /* Overwriting the existing tree. */
2901 if (!rc)
2903 xmlUnlinkNode (n);
2904 xmlFreeNodeList (n);
2907 rc = 0;
2908 xmlSetProp (root, (xmlChar *) "_name", (xmlChar *) path[0]);
2909 n = xmlCopyNode (root, 1);
2910 n = xmlAddChildList (xmlDocGetRootElement (client->doc), n);
2913 if (n && !rc)
2914 rc = update_element_mtime (n->parent);
2916 fail:
2917 if (doc)
2918 xmlFreeDoc (doc);
2920 if (path)
2921 strv_free (path);
2923 strv_free (req);
2924 return rc;
2927 static gpg_error_t
2928 import_command (assuan_context_t ctx, char *line)
2930 gpg_error_t rc;
2931 struct client_s *client = assuan_get_pointer (ctx);
2932 unsigned char *result;
2933 size_t len;
2935 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2936 if (rc)
2937 return send_error (ctx, rc);
2939 rc = do_import (client, result);
2940 return send_error (ctx, rc);
2943 static gpg_error_t
2944 do_lock (struct client_s *client, int add)
2946 gpg_error_t rc = lock_file_mutex (client, add);
2948 if (!rc)
2949 client->flags |= FLAG_LOCK_CMD;
2951 return rc;
2954 static gpg_error_t
2955 lock_command (assuan_context_t ctx, char *line)
2957 struct client_s *client = assuan_get_pointer (ctx);
2958 gpg_error_t rc = do_lock (client, 0);
2960 return send_error (ctx, rc);
2963 static gpg_error_t
2964 unlock_command (assuan_context_t ctx, char *line)
2966 struct client_s *client = assuan_get_pointer (ctx);
2967 gpg_error_t rc;
2969 rc = unlock_file_mutex (client, 0);
2970 return send_error (ctx, rc);
2973 static gpg_error_t
2974 option_command (assuan_context_t ctx, char *line)
2976 struct client_s *client = assuan_get_pointer (ctx);
2977 gpg_error_t rc = 0;
2978 struct pinentry_option_s *pin_opts = &client->pinentry_opts;
2979 #ifdef WITH_AGENT
2980 struct agent_s *agent = client->crypto->agent;
2981 #endif
2982 char namebuf[255] = { 0 };
2983 char *name = namebuf;
2984 char *value = NULL, *p;
2986 p = strchr (line, '=');
2987 if (!p)
2988 strncpy (namebuf, line, sizeof(namebuf));
2989 else
2991 strncpy (namebuf, line, strlen (line)-strlen (p));
2992 value = p+1;
2995 log_write1 ("OPTION name='%s' value='%s'", name, value);
2997 if (strcasecmp (name, (char *) "log_level") == 0)
2999 long l = 0;
3001 if (value)
3003 l = strtol (value, NULL, 10);
3005 if (l < 0 || l > 2)
3006 return send_error (ctx, GPG_ERR_INV_VALUE);
3009 MUTEX_LOCK (&rcfile_mutex);
3010 config_set_int_param (&global_config, "global", "log_level", value);
3011 MUTEX_UNLOCK (&rcfile_mutex);
3012 goto done;
3014 else if (strcasecmp (name, (char *) "lock-timeout") == 0)
3016 long n = 0;
3017 char *p = NULL;
3019 if (value)
3021 n = strtol (value, &p, 10);
3022 if (p && *p)
3023 return send_error (ctx, GPG_ERR_INV_VALUE);
3026 client->lock_timeout = n;
3027 goto done;
3029 else if (strcasecmp (name, (char *) "NAME") == 0)
3031 char *tmp = pthread_getspecific (thread_name_key);
3033 if (tmp)
3034 xfree (tmp);
3036 if (!value || !*value)
3038 pthread_setspecific (thread_name_key, str_dup (""));
3039 goto done;
3042 pthread_setspecific (thread_name_key, str_dup (value));
3043 goto done;
3045 else if (strcasecmp (name, (char *) "lc-messages") == 0)
3047 xfree (pin_opts->lc_messages);
3048 pin_opts->lc_messages = NULL;
3049 if (value && *value)
3050 pin_opts->lc_messages = str_dup (value);
3051 #ifdef WITH_AGENT
3052 if (use_agent)
3053 rc = set_agent_option (client->crypto->agent, "lc-messages", value);
3054 #endif
3056 else if (strcasecmp (name, (char *) "lc-ctype") == 0)
3058 xfree (pin_opts->lc_ctype);
3059 pin_opts->lc_ctype = NULL;
3060 if (value && *value)
3061 pin_opts->lc_ctype = str_dup (value);
3062 #ifdef WITH_AGENT
3063 if (use_agent)
3064 rc = set_agent_option (client->crypto->agent, "lc-ctype", value);
3065 #endif
3067 else if (strcasecmp (name, (char *) "ttyname") == 0)
3069 xfree (pin_opts->ttyname);
3070 pin_opts->ttyname = NULL;
3071 if (value && *value)
3072 pin_opts->ttyname = str_dup (value);
3073 #ifdef WITH_AGENT
3074 if (use_agent)
3075 rc = set_agent_option (client->crypto->agent, "ttyname", value);
3076 #endif
3078 else if (strcasecmp (name, (char *) "ttytype") == 0)
3080 xfree (pin_opts->ttytype);
3081 pin_opts->ttytype = NULL;
3082 if (value && *value)
3083 pin_opts->ttytype = str_dup (value);
3084 #ifdef WITH_AGENT
3085 if (use_agent)
3086 rc = set_agent_option (client->crypto->agent, "ttytype", value);
3087 #endif
3089 else if (strcasecmp (name, (char *) "display") == 0)
3091 xfree (pin_opts->display);
3092 pin_opts->display = NULL;
3093 if (value && *value)
3094 pin_opts->display = str_dup (value);
3095 #ifdef WITH_AGENT
3096 if (use_agent)
3097 rc = set_agent_option (client->crypto->agent, "display", value);
3098 #endif
3100 else if (strcasecmp (name, (char *) "pinentry-desc") == 0)
3102 xfree (pin_opts->desc);
3103 pin_opts->desc = NULL;
3104 if (value && *value)
3105 pin_opts->desc = str_dup (value);
3107 else if (strcasecmp (name, (char *) "pinentry-title") == 0)
3109 xfree (pin_opts->title);
3110 pin_opts->title = NULL;
3111 if (value && *value)
3112 pin_opts->title = str_dup (value);
3114 else if (strcasecmp (name, (char *) "pinentry-prompt") == 0)
3116 xfree (pin_opts->prompt);
3117 pin_opts->prompt = NULL;
3118 if (value && *value)
3119 pin_opts->prompt = str_dup (value);
3122 else if (strcasecmp (name, "pinentry-timeout") == 0)
3124 char *p = NULL;
3125 int n;
3127 if (!value)
3128 goto done;
3130 n = (int) strtol (value, &p, 10);
3132 if (*p || n < 0)
3133 return send_error (ctx, GPG_ERR_INV_VALUE);
3135 pin_opts->timeout = n;
3136 MUTEX_LOCK (&rcfile_mutex);
3137 config_set_int_param (&global_config,
3138 client->filename ? client->filename : "global",
3139 "pinentry_timeout", value);
3140 MUTEX_UNLOCK (&rcfile_mutex);
3141 goto done;
3143 else if (strcasecmp (name, "disable-pinentry") == 0)
3145 char *p = NULL;
3146 int n = 1;
3148 if (value && *value)
3150 n = (int) strtol (value, &p, 10);
3151 if (*p || n < 0 || n > 1)
3152 return send_error (ctx, GPG_ERR_INV_VALUE);
3155 if (n)
3156 client->flags |= FLAG_NO_PINENTRY;
3157 else
3158 client->flags &= ~FLAG_NO_PINENTRY;
3160 else
3161 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
3163 done:
3164 #ifdef WITH_AGENT
3165 if (!rc && use_agent && agent)
3167 rc = pinentry_merge_options (&client->crypto->agent->pinentry_opts,
3168 pin_opts);
3170 #endif
3172 return send_error (ctx, rc);
3175 static gpg_error_t
3176 do_rename (assuan_context_t ctx, char *line)
3178 struct client_s *client = assuan_get_pointer (ctx);
3179 gpg_error_t rc;
3180 char **req, **src, *dst;
3181 xmlNodePtr n, ndst;
3183 req = str_split (line, " ", 0);
3185 if (!req || !req[0] || !req[1])
3187 strv_free (req);
3188 return GPG_ERR_SYNTAX;
3191 dst = req[1];
3192 is_literal_element (&dst);
3194 if (!valid_xml_element ((xmlChar *) dst))
3196 strv_free (req);
3197 return GPG_ERR_INV_VALUE;
3200 if (strchr (req[0], '\t'))
3201 src = str_split (req[0], "\t", 0);
3202 else
3203 src = str_split (req[0], " ", 0);
3205 if (!src || !*src)
3207 rc = GPG_ERR_SYNTAX;
3208 goto fail;
3211 n = find_root_element (client->doc, &src, &rc, NULL, 0, 0);
3212 if (src[1] && n)
3213 n = find_elements (client->doc, n->children, src + 1, &rc, NULL, NULL,
3214 NULL, 0, 0, NULL, 0);
3216 if (!n)
3217 goto fail;
3219 xmlChar *a = xmlGetProp (n, (xmlChar *) "_name");
3220 if (!a)
3222 rc = GPG_ERR_ENOMEM;
3223 goto fail;
3226 /* To prevent unwanted effects:
3228 * <root name="a"><b/></root>
3230 * RENAME a<TAB>b b
3232 if (xmlStrEqual (a, (xmlChar *) dst))
3234 xmlFree (a);
3235 rc = GPG_ERR_AMBIGUOUS_NAME;
3236 goto fail;
3239 xmlFree (a);
3240 char **tmp = NULL;
3241 if (src[1])
3243 char **p;
3245 for (p = src; *p; p++)
3247 if (!*(p + 1))
3248 break;
3249 strv_printf (&tmp, "%s", *p);
3253 strv_printf (&tmp, "!%s", dst);
3254 ndst = find_root_element (client->doc, &tmp, &rc, NULL, 0, 0);
3255 if (!ndst && rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3257 strv_free (tmp);
3258 goto fail;
3261 if (tmp[1] && ndst)
3262 ndst = find_elements (client->doc, ndst->children, tmp + 1, &rc, NULL,
3263 NULL, NULL, 0, 0, NULL, 0);
3265 strv_free (tmp);
3266 if (!ndst && rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3267 goto fail;
3269 rc = 0;
3271 /* Target may exist:
3273 * <root name="a"/>
3274 * <root name="b" target="a"/>
3276 * RENAME b a
3278 * Would need to do:
3279 * RENAME !b a
3281 if (ndst == n)
3283 rc = GPG_ERR_AMBIGUOUS_NAME;
3284 goto fail;
3287 if (ndst)
3289 unlink_node (ndst);
3290 xmlFreeNodeList (ndst);
3293 rc = add_attribute (n, "_name", dst);
3295 fail:
3296 strv_free (req);
3297 strv_free (src);
3298 return rc;
3301 static gpg_error_t
3302 rename_command (assuan_context_t ctx, char *line)
3304 struct client_s *client = assuan_get_pointer (ctx);
3305 gpg_error_t rc;
3306 struct argv_s *args[] = {
3307 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3308 NULL
3311 rc = parse_options (&line, args, client);
3312 if (rc)
3313 return send_error (ctx, rc);
3315 if (client->opts & OPT_INQUIRE)
3317 unsigned char *result;
3318 size_t len;
3320 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3321 if (rc)
3322 return send_error (ctx, rc);
3324 line = (char *) result;
3327 rc = do_rename (ctx, line);
3329 if (client->opts & OPT_INQUIRE)
3330 xfree (line);
3332 return send_error (ctx, rc);
3335 static gpg_error_t
3336 do_copy (assuan_context_t ctx, char *line)
3338 struct client_s *client = assuan_get_pointer (ctx);
3339 gpg_error_t rc;
3340 char **req, **src = NULL, **dst = NULL;
3341 xmlNodePtr nsrc, ndst, new = NULL;
3343 req = str_split (line, " ", 0);
3344 if (!req || !req[0] || !req[1])
3346 strv_free (req);
3347 return GPG_ERR_SYNTAX;
3350 if (strchr (req[0], '\t'))
3351 src = str_split (req[0], "\t", 0);
3352 else
3353 src = str_split (req[0], " ", 0);
3355 if (!src || !*src)
3357 rc = GPG_ERR_SYNTAX;
3358 goto fail;
3361 if (strchr (req[1], '\t'))
3362 dst = str_split (req[1], "\t", 0);
3363 else
3364 dst = str_split (req[1], " ", 0);
3366 if (!dst || !*dst)
3368 rc = GPG_ERR_SYNTAX;
3369 goto fail;
3372 if (!valid_element_path (dst, 0))
3374 rc = GPG_ERR_INV_VALUE;
3375 goto fail;
3378 nsrc = find_root_element (client->doc, &src, &rc, NULL, 0, 0);
3379 if (nsrc && src[1])
3380 nsrc = find_elements (client->doc, nsrc->children, src + 1, &rc, NULL,
3381 NULL, NULL, 0, 0, NULL, 0);
3383 if (!nsrc)
3384 goto fail;
3386 new = xmlCopyNodeList (nsrc);
3387 if (!new)
3389 rc = GPG_ERR_ENOMEM;
3390 goto fail;
3393 int create = 0;
3394 ndst = find_root_element (client->doc, &dst, &rc, NULL, 0, 0);
3395 if (ndst && dst[1])
3397 if (ndst->children)
3398 ndst = find_elements (client->doc, ndst->children, dst + 1, &rc, NULL,
3399 NULL, create_target_elements_cb, 0, 0, NULL, 0);
3400 else
3401 create = 1;
3403 else
3404 create = 1;
3406 if (!ndst && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3407 goto fail;
3408 else if (!ndst || create)
3410 ndst = create_element_path (client, &dst, &rc, NULL);
3411 if (!ndst)
3412 goto fail;
3415 /* Merge any attributes from the src node to the initial dst node. */
3416 for (xmlAttrPtr attr = new->properties; attr; attr = attr->next)
3418 if (xmlStrEqual (attr->name, (xmlChar *) "_name"))
3419 continue;
3421 xmlAttrPtr a = xmlHasProp (ndst, attr->name);
3422 if (a)
3423 xmlRemoveProp (a);
3425 xmlChar *tmp = xmlNodeGetContent (attr->children);
3426 xmlNewProp (ndst, attr->name, tmp);
3427 xmlFree (tmp);
3428 rc = add_attribute (ndst, NULL, NULL);
3431 xmlNodePtr n = ndst->children;
3432 xmlUnlinkNode (n);
3433 xmlFreeNodeList (n);
3434 ndst->children = NULL;
3436 if (new->children)
3438 n = xmlCopyNodeList (new->children);
3439 if (!n)
3441 rc = GPG_ERR_ENOMEM;
3442 goto fail;
3445 n = xmlAddChildList (ndst, n);
3446 if (!n)
3448 rc = GPG_ERR_ENOMEM;
3449 goto fail;
3452 rc = update_element_mtime (xmlDocGetRootElement (client->doc) ==
3453 ndst->parent ? ndst : ndst->parent);
3456 fail:
3457 if (new)
3459 xmlUnlinkNode (new);
3460 xmlFreeNodeList (new);
3463 if (req)
3464 strv_free (req);
3466 if (src)
3467 strv_free (src);
3469 if (dst)
3470 strv_free (dst);
3472 return rc;
3475 static gpg_error_t
3476 copy_command (assuan_context_t ctx, char *line)
3478 struct client_s *client = assuan_get_pointer (ctx);
3479 gpg_error_t rc;
3480 struct argv_s *args[] = {
3481 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3482 NULL
3485 rc = parse_options (&line, args, client);
3486 if (rc)
3487 return send_error (ctx, rc);
3489 if (client->opts & OPT_INQUIRE)
3491 unsigned char *result;
3492 size_t len;
3494 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3495 if (rc)
3496 return send_error (ctx, rc);
3498 line = (char *) result;
3501 rc = do_copy (ctx, line);
3503 if (client->opts & OPT_INQUIRE)
3504 xfree (line);
3506 return send_error (ctx, rc);
3509 static gpg_error_t
3510 do_move (assuan_context_t ctx, char *line)
3512 struct client_s *client = assuan_get_pointer (ctx);
3513 gpg_error_t rc;
3514 char **req, **src = NULL, **dst = NULL;
3515 xmlNodePtr nsrc, ndst = NULL;
3517 req = str_split (line, " ", 0);
3519 if (!req || !req[0] || !req[1])
3521 strv_free (req);
3522 return GPG_ERR_SYNTAX;
3525 if (strchr (req[0], '\t'))
3526 src = str_split (req[0], "\t", 0);
3527 else
3528 src = str_split (req[0], " ", 0);
3530 if (!src || !*src)
3532 rc = GPG_ERR_SYNTAX;
3533 goto fail;
3536 if (strchr (req[1], '\t'))
3537 dst = str_split (req[1], "\t", 0);
3538 else
3539 dst = str_split (req[1], " ", 0);
3541 nsrc = find_root_element (client->doc, &src, &rc, NULL, 0, 0);
3542 if (nsrc && src[1])
3543 nsrc = find_elements (client->doc, nsrc->children, src + 1, &rc, NULL,
3544 NULL, NULL, 0, 0, NULL, 0);
3546 if (!nsrc)
3547 goto fail;
3549 if (dst)
3551 if (!valid_element_path (dst, 0))
3553 rc = GPG_ERR_INV_VALUE;
3554 goto fail;
3557 ndst = find_root_element (client->doc, &dst, &rc, NULL, 0, 0);
3558 if (ndst && dst[1])
3559 ndst = find_elements (client->doc, ndst->children, dst + 1, &rc, NULL,
3560 NULL, NULL, 0, 0, NULL, 0);
3562 else
3563 ndst = xmlDocGetRootElement (client->doc);
3565 for (xmlNodePtr n = ndst; n; n = n->parent)
3567 if (n == nsrc)
3569 rc = GPG_ERR_CONFLICT;
3570 goto fail;
3574 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3575 goto fail;
3577 rc = 0;
3579 if (ndst)
3581 xmlChar *a = node_has_attribute (nsrc, (xmlChar *) "_name");
3582 xmlNodePtr dup = find_element (ndst->children, (char *) a, NULL);
3584 xmlFree (a);
3585 if (dup)
3587 if (dup == nsrc)
3588 goto fail;
3590 if (ndst == xmlDocGetRootElement (client->doc))
3592 xmlNodePtr n = nsrc;
3593 int match = 0;
3595 while (n->parent && n->parent != ndst)
3596 n = n->parent;
3598 xmlChar *a = node_has_attribute (n, (xmlChar *) "_name");
3599 xmlChar *b = node_has_attribute (nsrc, (xmlChar *) "_name");
3601 if (xmlStrEqual (a, b))
3603 match = 1;
3604 xmlUnlinkNode (nsrc);
3605 xmlUnlinkNode (n);
3606 xmlFreeNodeList (n);
3609 xmlFree (a);
3610 xmlFree (b);
3612 if (!match)
3614 xmlUnlinkNode (dup);
3615 xmlFreeNodeList (dup);
3618 else
3619 xmlUnlinkNode (dup);
3623 if (!ndst && dst)
3625 xmlChar *name = node_has_attribute (nsrc, (xmlChar *) "_name");
3627 if (nsrc->parent == xmlDocGetRootElement (client->doc)
3628 && !strcmp ((char *) name, *dst))
3630 xmlFree (name);
3631 rc = GPG_ERR_CONFLICT;
3632 goto fail;
3635 xmlFree (name);
3636 ndst = create_element_path (client, &dst, &rc, nsrc);
3639 if (!ndst)
3640 goto fail;
3642 update_element_mtime (nsrc->parent);
3643 xmlUnlinkNode (nsrc);
3644 ndst = xmlAddChildList (ndst, nsrc);
3646 if (!ndst)
3647 rc = GPG_ERR_ENOMEM;
3648 else
3649 update_element_mtime (ndst->parent);
3651 fail:
3652 if (req)
3653 strv_free (req);
3655 if (src)
3656 strv_free (src);
3658 if (dst)
3659 strv_free (dst);
3661 return rc;
3664 static gpg_error_t
3665 move_command (assuan_context_t ctx, char *line)
3667 struct client_s *client = assuan_get_pointer (ctx);
3668 gpg_error_t rc;
3669 struct argv_s *args[] = {
3670 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3671 NULL
3674 rc = parse_options (&line, args, client);
3675 if (rc)
3676 return send_error (ctx, rc);
3678 if (client->opts & OPT_INQUIRE)
3680 unsigned char *result;
3681 size_t len;
3683 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3684 if (rc)
3685 return send_error (ctx, rc);
3687 line = (char *) result;
3690 rc = do_move (ctx, line);
3692 if (client->opts & OPT_INQUIRE)
3693 xfree (line);
3695 return send_error (ctx, rc);
3698 static gpg_error_t
3699 ls_command (assuan_context_t ctx, char *line)
3701 gpg_error_t rc;
3702 char *tmp = str_asprintf ("%s/data", homedir);
3703 char *dir = expand_homedir (tmp);
3704 DIR *d = opendir (dir);
3706 rc = gpg_error_from_syserror ();
3707 xfree (tmp);
3709 if (!d)
3711 xfree (dir);
3712 return send_error (ctx, rc);
3715 size_t len =
3716 offsetof (struct dirent, d_name) +pathconf (dir, _PC_NAME_MAX) + 1;
3717 struct dirent *p = xmalloc (len), *cur = NULL;
3718 char *list = NULL;
3720 xfree (dir);
3721 rc = 0;
3723 while (!readdir_r (d, p, &cur) && cur)
3725 if (cur->d_name[0] == '.' && cur->d_name[1] == '\0')
3726 continue;
3727 else if (cur->d_name[0] == '.' && cur->d_name[1] == '.'
3728 && cur->d_name[2] == '\0')
3729 continue;
3731 tmp = str_asprintf ("%s%s\n", list ? list : "", cur->d_name);
3733 if (!tmp)
3735 if (list)
3736 xfree (list);
3738 rc = GPG_ERR_ENOMEM;
3739 break;
3742 xfree (list);
3743 list = tmp;
3746 closedir (d);
3747 xfree (p);
3749 if (rc)
3750 return send_error (ctx, rc);
3752 if (!list)
3753 return send_error (ctx, GPG_ERR_NO_DATA);
3755 list[strlen (list) - 1] = 0;
3756 rc = xfer_data (ctx, list, strlen (list));
3757 xfree (list);
3758 return send_error (ctx, rc);
3761 static gpg_error_t
3762 bye_notify (assuan_context_t ctx, char *line)
3764 struct client_s *cl = assuan_get_pointer (ctx);
3766 #ifdef WITH_GNUTLS
3767 if (cl->thd->remote)
3769 int rc;
3773 struct timeval tv = { 0, 50000 };
3775 rc = gnutls_bye (cl->thd->tls->ses, GNUTLS_SHUT_RDWR);
3776 if (rc == GNUTLS_E_AGAIN)
3777 select (0, NULL, NULL, NULL, &tv);
3779 while (rc == GNUTLS_E_AGAIN);
3781 #endif
3783 /* This will let assuan_process_next() return. */
3784 fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK);
3785 cl->last_rc = 0; // BYE command result
3786 return 0;
3789 static gpg_error_t
3790 reset_notify (assuan_context_t ctx, char *line)
3792 struct client_s *client = assuan_get_pointer (ctx);
3794 if (client)
3795 cleanup_client (client);
3797 return 0;
3801 * This is called before every Assuan command.
3803 static gpg_error_t
3804 command_startup (assuan_context_t ctx, const char *name)
3806 struct client_s *client = assuan_get_pointer (ctx);
3807 gpg_error_t rc;
3808 struct command_table_s *cmd = NULL;
3810 log_write1 ("command='%s'", name);
3811 client->last_rc = client->opts = 0;
3813 for (int i = 0; command_table[i]; i++)
3815 if (!strcasecmp (name, command_table[i]->name))
3817 if (command_table[i]->ignore_startup)
3818 return 0;
3819 cmd = command_table[i];
3820 break;
3824 client->last_rc = rc = gpg_error (file_modified (client, cmd));
3825 return rc;
3829 * This is called after every Assuan command.
3831 static void
3832 command_finalize (assuan_context_t ctx, gpg_error_t rc)
3834 struct client_s *client = assuan_get_pointer (ctx);
3836 if (!(client->flags & FLAG_LOCK_CMD))
3837 unlock_file_mutex (client, 0);
3839 log_write1 (_("command completed: rc=%u"), client->last_rc);
3840 client->last_rc = gpg_error (GPG_ERR_UNKNOWN_COMMAND);
3843 static gpg_error_t
3844 help_command (assuan_context_t ctx, char *line)
3846 gpg_error_t rc;
3847 int i;
3849 if (!line || !*line)
3851 char *tmp;
3852 char *help = str_dup (_("Usage: HELP [<COMMAND>]\n"
3853 "For commands that take an element path as an argument, each element is "
3854 "separated with an ASCII @key{TAB} character (ASCII 0x09)."
3855 "\n" "COMMANDS:"));
3857 for (i = 0; command_table[i]; i++)
3859 if (!command_table[i]->help)
3860 continue;
3862 tmp = str_asprintf ("%s %s", help, command_table[i]->name);
3863 xfree (help);
3864 help = tmp;
3867 tmp = strip_texi_and_wrap (help);
3868 xfree (help);
3869 rc = xfer_data (ctx, tmp, strlen (tmp));
3870 xfree (tmp);
3871 return send_error (ctx, rc);
3874 for (i = 0; command_table[i]; i++)
3876 if (!strcasecmp (line, command_table[i]->name))
3878 char *help, *tmp;
3880 if (!command_table[i]->help)
3881 break;
3883 help = strip_texi_and_wrap (command_table[i]->help);
3884 tmp = str_asprintf (_("Usage: %s"), help);
3885 xfree (help);
3886 rc = xfer_data (ctx, tmp, strlen (tmp));
3887 xfree (tmp);
3888 return send_error (ctx, rc);
3892 return send_error (ctx, GPG_ERR_INV_NAME);
3895 static void
3896 new_command (const char *name, int ignore, int unlock,
3897 gpg_error_t (*handler) (assuan_context_t, char *),
3898 const char *help)
3900 int i = 0;
3902 if (command_table)
3903 for (i = 0; command_table[i]; i++);
3905 command_table =
3906 xrealloc (command_table, (i + 2) * sizeof (struct command_table_s *));
3907 command_table[i] = xcalloc (1, sizeof (struct command_table_s));
3908 command_table[i]->name = name;
3909 command_table[i]->handler = handler;
3910 command_table[i]->ignore_startup = ignore;
3911 command_table[i]->unlock = unlock;
3912 command_table[i++]->help = help;
3913 command_table[i] = NULL;
3916 void
3917 deinit_commands ()
3919 int i;
3921 for (i = 0; command_table[i]; i++)
3922 xfree (command_table[i]);
3924 xfree (command_table);
3927 static int
3928 sort_commands (const void *arg1, const void *arg2)
3930 struct command_table_s *const *a = arg1;
3931 struct command_table_s *const *b = arg2;
3933 if (!*a || !*b)
3934 return 0;
3935 else if (*a && !*b)
3936 return 1;
3937 else if (!*a && *b)
3938 return -1;
3940 return strcmp ((*a)->name, (*b)->name);
3943 static gpg_error_t
3944 passwd_command (assuan_context_t ctx, char *line)
3946 struct client_s *client = assuan_get_pointer (ctx);
3947 gpg_error_t rc;
3948 struct argv_s *args[] = {
3949 &(struct argv_s) {"reset", OPTION_TYPE_NOARG, parse_opt_reset},
3950 &(struct argv_s) {"s2k-count", OPTION_TYPE_ARG, parse_opt_s2k_count},
3951 NULL
3954 if (client->flags & FLAG_NEW)
3955 return send_error (ctx, GPG_ERR_INV_STATE);
3957 client->crypto->save.s2k_count =
3958 config_get_ulong (client->filename, "s2k_count");
3959 rc = parse_options (&line, args, client);
3960 if (rc)
3961 return send_error (ctx, rc);
3963 if (!rc && client->opts & OPT_RESET)
3965 rc = cache_clear (client->md5file);
3966 if (!rc)
3967 send_status_all (STATUS_CACHE, NULL);
3970 if (!rc)
3972 if (!IS_PKCS (client->crypto))
3974 struct crypto_s *crypto;
3976 xfree (client->crypto->filename);
3977 client->crypto->filename = str_dup (client->filename);
3978 rc = change_passwd (ctx, client->filename,
3979 client->flags & FLAG_NO_PINENTRY, &crypto);
3980 if (!rc)
3982 cleanup_crypto (&client->crypto);
3983 client->crypto = crypto;
3984 update_checksum (client);
3985 cleanup_crypto_stage1 (client->crypto);
3988 #ifdef WITH_AGENT
3989 else
3991 if (client->crypto->save.s2k_count)
3992 rc = send_to_agent (client->crypto->agent, NULL, NULL,
3993 "OPTION s2k-count=%lu",
3994 client->crypto->save.s2k_count);
3996 if (!rc)
3997 rc = agent_passwd (client->crypto);
3999 #endif
4002 return send_error (ctx, rc);
4005 static gpg_error_t
4006 parse_keygrip_opt_sign (void *data, void *value)
4008 struct client_s *client = data;
4010 (void) value;
4011 client->opts |= OPT_SIGN;
4012 return 0;
4015 static gpg_error_t
4016 keygrip_command (assuan_context_t ctx, char *line)
4018 struct client_s *client = assuan_get_pointer (ctx);
4019 gpg_error_t rc;
4020 struct crypto_s *crypto = NULL;
4021 struct argv_s *args[] = {
4022 &(struct argv_s) {"sign", OPTION_TYPE_NOARG, parse_keygrip_opt_sign},
4023 NULL
4026 if (!line || !*line)
4027 return send_error (ctx, GPG_ERR_SYNTAX);
4029 rc = parse_options (&line, args, client);
4030 if (rc)
4031 return send_error (ctx, rc);
4033 if (!valid_filename (line))
4034 return send_error (ctx, GPG_ERR_INV_VALUE);
4036 rc = init_client_crypto (&crypto);
4037 if (rc)
4038 return send_error (ctx, rc);
4040 rc = read_data_file (line, crypto);
4041 if (!rc)
4043 char *hexgrip = NULL;
4045 if (!IS_PKCS (crypto))
4047 cleanup_crypto (&crypto);
4048 return send_error (ctx, GPG_ERR_NOT_SUPPORTED);
4051 if (client->opts & OPT_SIGN)
4053 if (valid_keygrip (crypto->sign_grip, sizeof (crypto->sign_grip)))
4054 hexgrip = bin2hex (crypto->sign_grip, sizeof (crypto->sign_grip));
4057 if (!hexgrip)
4058 hexgrip = bin2hex (crypto->grip, sizeof (crypto->grip));
4060 if (!hexgrip)
4061 rc = GPG_ERR_ENOMEM;
4062 else
4063 rc = xfer_data (ctx, hexgrip, strlen (hexgrip));
4065 xfree (hexgrip);
4068 UPDATE_AGENT_CTX (client, crypto);
4069 cleanup_crypto (&crypto);
4070 return send_error (ctx, rc);
4073 static gpg_error_t
4074 parse_opt_data (void *data, void *value)
4076 struct client_s *client = data;
4078 (void) value;
4079 client->opts |= OPT_DATA;
4080 return 0;
4083 static gpg_error_t
4084 getinfo_command (assuan_context_t ctx, char *line)
4086 struct client_s *client = assuan_get_pointer (ctx);
4087 gpg_error_t rc;
4088 char buf[ASSUAN_LINELENGTH];
4089 struct argv_s *args[] = {
4090 &(struct argv_s) {"data", OPTION_TYPE_NOARG, parse_opt_data},
4091 NULL
4094 rc = parse_options (&line, args, client);
4095 if (rc)
4096 return send_error (ctx, rc);
4098 if (!strcasecmp (line, "clients"))
4100 if (client->opts & OPT_DATA)
4102 MUTEX_LOCK (&cn_mutex);
4103 snprintf (buf, sizeof (buf), "%i", slist_length (cn_thread_list));
4104 MUTEX_UNLOCK (&cn_mutex);
4105 rc = xfer_data (ctx, buf, strlen (buf));
4107 else
4108 rc = send_status (ctx, STATUS_CLIENTS, NULL);
4110 else if (!strcasecmp (line, "cache"))
4112 if (client->opts & OPT_DATA)
4114 snprintf (buf, sizeof (buf), "%u", cache_file_count ());
4115 rc = xfer_data (ctx, buf, strlen (buf));
4117 else
4118 rc = send_status (ctx, STATUS_CACHE, NULL);
4120 else if (!strcasecmp (line, "pid"))
4122 char buf[32];
4123 pid_t pid = getpid ();
4125 snprintf (buf, sizeof (buf), "%i", pid);
4126 rc = xfer_data (ctx, buf, strlen (buf));
4128 else if (!strcasecmp (line, "version"))
4130 char *buf = str_asprintf ("0x%06x %s%s", VERSION_HEX,
4131 #ifdef WITH_LIBACL
4132 "ACL "
4133 #endif
4134 #ifdef WITH_GNUTLS
4135 "GNUTLS "
4136 #endif
4137 #ifdef WITH_QUALITY
4138 "QUALITY "
4139 #endif
4140 "", use_agent ? "AGENT" : "");
4141 rc = xfer_data (ctx, buf, strlen (buf));
4142 xfree (buf);
4144 else if (!strcasecmp (line, "last_error"))
4146 if (client->last_error)
4147 rc = xfer_data (ctx, client->last_error, strlen (client->last_error));
4148 else
4149 rc = GPG_ERR_NO_DATA;
4151 else
4152 rc = gpg_error (GPG_ERR_SYNTAX);
4154 return send_error (ctx, rc);
4157 #ifdef WITH_AGENT
4158 static gpg_error_t
4159 send_data_cb (void *user, const void *buf, size_t len)
4161 assuan_context_t ctx = user;
4163 return assuan_send_data (ctx, buf, len);
4166 static gpg_error_t
4167 send_status_cb (void *user, const char *line)
4169 assuan_context_t ctx = user;
4170 char keyword[200], *k;
4171 const char *p;
4173 for (p = line, k = keyword; *p; p++)
4175 if (isspace (*p))
4176 break;
4178 *k++ = *p;
4181 *k = 0;
4182 if (*p == '#')
4183 p++;
4185 while (isspace (*p))
4186 p++;
4188 return assuan_write_status (ctx, keyword, *p ? p : NULL);
4190 #endif
4192 static gpg_error_t
4193 agent_command (assuan_context_t ctx, char *line)
4195 gpg_error_t rc = 0;
4197 if (!use_agent)
4198 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
4200 #ifdef WITH_AGENT
4201 struct client_s *client = assuan_get_pointer (ctx);
4203 if (!line || !*line)
4204 return send_error (ctx, GPG_ERR_SYNTAX);
4206 assuan_set_flag (client->crypto->agent->ctx, ASSUAN_CONVEY_COMMENTS, 1);
4207 rc = assuan_transact (client->crypto->agent->ctx, line, send_data_cb,
4208 client->ctx, agent_loopback_cb, client->crypto,
4209 send_status_cb, client->ctx);
4210 if (gpg_err_code (rc) == GPG_ERR_ASS_CANCELED)
4212 char *line;
4213 size_t len;
4215 rc = assuan_write_line (client->crypto->agent->ctx, "CAN");
4216 if (!rc)
4218 rc = assuan_read_line (client->crypto->agent->ctx, &line, &len);
4219 if (!rc)
4220 rc = gpg_error (GPG_ERR_ASS_CANCELED);
4224 assuan_set_flag (client->crypto->agent->ctx, ASSUAN_CONVEY_COMMENTS, 0);
4225 #endif
4226 return send_error (ctx, rc);
4229 void
4230 init_commands ()
4232 /* !BEGIN-HELP-TEXT!
4234 * This comment is used as a marker to generate the offline documentation
4235 * found in doc/pwmd.info. The indentation needs to be kept for the awk
4236 * script to determine where commands begin and end.
4238 new_command("HELP", 1, 1, help_command, _(
4239 "HELP [<COMMAND>]\n"
4240 "Show available commands or command specific help text."
4243 new_command("AGENT", 1, 1, agent_command, _(
4244 "AGENT <command>\n"
4245 "Send a @command{gpg-agent} protocol @var{command} directly to the "
4246 "@command{gpg-agent}."
4249 new_command("GETINFO", 1, 1, getinfo_command, _(
4250 "GETINFO [--data] CACHE | CLIENTS | PID | LAST_ERROR | VERSION\n"
4251 "Get server and other information: @var{cache} returns the number of cached "
4252 "documents via a status message. @var{clients} returns the number of "
4253 "connected clients via a status message. @var{pid} returns the process ID "
4254 "number of the server via a data response. @var{VERSION} returns the server "
4255 "version number and compile-time features with a data response with each "
4256 "being space delimited. @var{LAST_ERROR} returns a detailed description of "
4257 "the last failed command when available. @xref{Status Messages}. "
4258 "\n"
4259 "When the @option{--data} option is specified then the result will be sent "
4260 "via a data response rather than a status message."
4263 new_command("PASSWD", 0, 0, passwd_command, _(
4264 "PASSWD [--reset] [--s2k-count=N]\n"
4265 "Changes the passphrase of the secret key required to open the current "
4266 "file or the passphrase of a symmetrically encrypted data file. When the "
4267 "@option{--reset} option is passed then the cache entry for the current "
4268 "file will be reset and the passphrase, if any, will be required during the "
4269 "next @code{OPEN}. @xref{OPEN}."
4270 "\n"
4271 "The @option{--s2k-count} option sets number of hash iterations for a "
4272 "passphrase and must be either @code{0} to use the calibrated count of the "
4273 "machine (the default), or a value greater than or equal to @code{65536}. "
4274 "@xref{SAVE}. This option has no effect for symmetrically encrypted data "
4275 "files."
4278 new_command("KEYGRIP", 1, 1, keygrip_command, _(
4279 "KEYGRIP [--sign] <filename>\n"
4280 "Returns the hex encoded keygrip of the specified @var{filename} with a "
4281 "data response."
4282 "\n"
4283 "When the @option{--sign} option is specified then the key used for signing "
4284 "of the specified @var{filename} will be returned."
4285 "\n"
4286 "For symmetrically encrypted data files this command returns the error "
4287 "GPG_ERR_NOT_SUPPORTED."
4290 new_command("OPEN", 1, 1, open_command, _(
4291 "OPEN [--lock] <filename> [<passphrase>]\n"
4292 "Opens @var{filename} using @var{passphrase}. When the filename is not "
4293 "found on the file-system then a new document will be created. If the file "
4294 "is found, it is looked for in the file cache. If cached and no "
4295 "@var{passphrase} was specified then the cached document is opened. When not "
4296 "cached, @cite{pinentry(1)} will be used to retrieve the passphrase to use "
4297 "for decryption unless @option{disable-pinentry} (@pxref{OPTION}) was "
4298 "specified."
4299 "\n"
4300 "When the @option{--lock} option is passed then the file mutex will be "
4301 "locked as if the @code{LOCK} command (@pxref{LOCK}) had been sent after the "
4302 "file has been opened."
4305 new_command("SAVE", 0, 0, save_command, _(
4306 "SAVE [--no-passphrase] [--reset] [--no-agent] [--s2k-count=N] [--cipher=<algo>] [--cipher-iterations=N] [--inquire-keyparam] [--keygrip=hexstring [--sign-keygrip=hexstring]]\n"
4307 "Writes the @abbr{XML} document to disk. The file written to is the file that "
4308 "was opened using the @code{OPEN} command (@pxref{OPEN}). If the file is a "
4309 "new one or the option @option{--inquire-keyparam} was passed, then a new "
4310 "keypair will be generated and a pinentry will be used to prompt for the "
4311 "passphrase to encrypt with unless the @option{--no-passphrase} option was "
4312 "passed, in which case the data file will not be passphrase protected."
4313 "\n"
4314 "The @option{--no-agent} option disables use of @command{gpg-agent} for "
4315 "passphrase retrieval and caching of new files and behaves as if the "
4316 "@option{--no-agent} commmand line option to @command{pwmd} was specified."
4317 "The datafile will be symmetrically encrypted and will not use or generate "
4318 "any keypair."
4319 "\n"
4320 "The @option{--reset} option will clear the cache entry for the current file "
4321 "and require a passphrase, if needed, before saving."
4322 "\n"
4323 "The @option{--cipher} option can be used to encrypt the @abbr{XML} data to "
4324 "an alternate cipher. The default is @code{aes256}. See the Configuration "
4325 "(@pxref{Configuration}) for available ciphers."
4326 "\n"
4327 "The @option{--cipher-iterations} option specifies the number of times to "
4328 "encrypt the XML data. The default is 0 although 1 iteration is still done."
4329 "\n"
4330 "The @option{--inquire-keyparam} option will send a server @emph{INQUIRE} to "
4331 "the client to obtain the key paramaters to use when generating a new "
4332 "keypair. The inquired data is expected to be an S-expression. If not "
4333 "specified then an @samp{RSA} key of @samp{2048} bits will be generated "
4334 "unless otherwise set in the configuration file (@pxref{Configuration}). Note "
4335 "that when this option is specified a new keypair will be generated "
4336 "reguardless if the file is a new one or not."
4337 "\n"
4338 "You can encrypt the data file to a public key other than the one that it "
4339 "was originally encrypted with by passing the @option{--keygrip} option with "
4340 "the hex encoded keygrip of the public key as its argument. The keygrip may "
4341 "be of any key that @command{gpg-agent} knows about. The "
4342 "@option{--sign-keygrip} option may also be used to sign with an alternate "
4343 "secret key. This option may be needed when using a smartcard. This option "
4344 "has no effect with symmetrically encrypted data files."
4345 "\n"
4346 "The @option{--s2k-count} option sets number of hash iterations for a "
4347 "passphrase. A value less-than @code{65536} will use the machine calibrated "
4348 "value which is the default. This setting only affects new files. To change "
4349 "the setting, use the @code{PASSWD} command (@pxref{PASSWD}). This option "
4350 "has no effect with symmetrically encrypted data files."
4353 new_command("ISCACHED", 1, 0, iscached_command, _(
4354 "ISCACHED [--lock] <filename>\n"
4355 "An @emph{OK} response is returned if the specified @var{filename} is found "
4356 "in the file cache. If not found in the cache but exists on the filesystem "
4357 "then @var{GPG_ERR_NO_DATA} is returned. Otherwise a filesystem error is "
4358 "returned."
4359 "\n"
4360 "The @option{lock} option will lock the file mutex of @var{filename} when the "
4361 "file exists; it does not need to be opened nor cached."
4364 new_command("CLEARCACHE", 1, 1, clearcache_command, _(
4365 "CLEARCACHE [<filename>]\n"
4366 "Clears a file cache entry for all or the specified @var{filename}."
4369 new_command("CACHETIMEOUT", 1, 1, cachetimeout_command, _(
4370 "CACHETIMEOUT <filename> <seconds>\n"
4371 "The time in @var{seconds} until @var{filename} will be removed from the "
4372 "cache. @code{-1} will keep the cache entry forever, @code{0} will require "
4373 "the passphrase for each @code{OPEN} or @code{SAVE} command (@pxref{OPEN}, "
4374 "@pxref{SAVE}). @xref{Configuration}, and the @code{cache_timeout} "
4375 "parameter."
4378 new_command("LIST", 0, 1, list_command, _(
4379 "LIST [--inquire] [--no-recurse] [--verbose] [--with-target] [--all] [[!]element[<TAB>[!]child[..]]]\n"
4380 "If no element path is given then a newline separated list of root elements "
4381 "is returned with a data response. If given, then all reachable elements "
4382 "of the specified element path are returned unless the @option{--no-recurse} "
4383 "option is specified. If specified, only the child elements of the element "
4384 "path are returned without recursing into grandchildren. Each resulting "
4385 "element is prefixed with the literal @code{!} character when the element "
4386 "contains no @code{target} attribute. @xref{Target Attribute}, for details."
4387 "\n"
4388 "When the @option{--verbose} option is passed then each element path "
4389 "returned will have zero or more flags appened to it. These flags are "
4390 "delimited from the element path by a single space character. A flag itself "
4391 "is a single character. Flag @code{+} indicates that there are child nodes of "
4392 "the current element path. Flag @code{E} indicates that an element of an "
4393 "element path contained in a @var{target} attribute could not be found. Flag "
4394 "@code{O} indicates that a @var{target} attribute recursion limit was reached "
4395 "(@pxref{Configuration}). Flag @code{T} will append the resolved element path "
4396 "of the @var{target} attribute contained in the current element (see below)."
4397 "\n"
4398 "The @option{--with-target} option implies @option{--verbose} and will append "
4399 "an additional flag @code{T} followed by a single space then an element path. "
4400 "The appended element path is the resolved path (@pxref{REALPATH}) of the "
4401 "current element when it contains a @var{target} attribute. When no "
4402 "@var{target} attribute is found then no flag will be appended."
4403 "\n"
4404 "The @option{--no-recurse} option limits the amount of data returned to only "
4405 "the listing of children of the specified element path and not any "
4406 "grandchildren."
4407 "\n"
4408 "The @option{--all} option lists the entire element tree for each root "
4409 "element. This option also implies option @option{--verbose}."
4410 "\n"
4411 "When the @option{--inquire} option is passed then all remaining non-option "
4412 "arguments are retrieved via a server @emph{INQUIRE}."
4415 new_command("REALPATH", 0, 1, realpath_command, _(
4416 "REALPATH [--inquire] [!]element[<TAB>[!]child[..]]\n"
4417 "Resolves all @code{target} attributes of the specified element path and "
4418 "returns the result with a data response. @xref{Target Attribute}, for details."
4419 "\n"
4420 "When the @option{--inquire} option is passed then all remaining non-option "
4421 "arguments are retrieved via a server @emph{INQUIRE}."
4424 new_command("STORE", 0, 1, store_command, _(
4425 "STORE [!]element[<TAB>[!]child[..]]<TAB>[content]\n"
4426 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
4427 "\n"
4428 "Creates a new element path or modifies the @var{content} of an existing "
4429 "element. If only a single element is specified then a new root element is "
4430 "created. Otherwise, elements are @key{TAB} delimited and the content will be "
4431 "set to the final @key{TAB} delimited element. If no @var{content} is "
4432 "specified after the final @key{TAB}, then the content of the element will "
4433 "be removed, or empty when creating a new element."
4434 "\n"
4435 "The only restriction of an element name is that it not contain whitespace "
4436 "or begin with the literal element character @code{!} unless specifying a "
4437 "literal element (@pxref{Target Attribute}). There is no whitespace between "
4438 "the @key{TAB} delimited elements. It is recommended that the content of an "
4439 "element be base64 encoded when it contains control or @key{TAB} characters "
4440 "to prevent @abbr{XML} parsing and @command{pwmd} syntax errors."
4443 new_command("RENAME", 0, 1, rename_command, _(
4444 "RENAME [--inquire] [!]element[<TAB>[!]child[..]] <value>\n"
4445 "Renames the specified @var{element} to the new @var{value}. If an element of "
4446 "the same name as the @var{value} already exists it will be overwritten."
4447 "\n"
4448 "When the @option{--inquire} option is passed then all remaining non-option "
4449 "arguments are retrieved via a server @emph{INQUIRE}."
4452 new_command("COPY", 0, 1, copy_command, _(
4453 "COPY [--inquire] [!]source[<TAB>[!]child[..]] [!]dest[<TAB>[!]child[..]]\n"
4454 "Copies the entire element tree starting from the child node of the source "
4455 "element, to the destination element path. If the destination element path "
4456 "does not exist then it will be created; otherwise it is overwritten."
4457 "\n"
4458 "Note that attributes from the source element are merged into the "
4459 "destination element when the destination element path exists. When an "
4460 "attribute of the same name exists in both the source and destination "
4461 "elements then the destination attribute will be updated to the source "
4462 "attribute value."
4463 "\n"
4464 "When the @option{--inquire} option is passed then all remaining non-option "
4465 "arguments are retrieved via a server @emph{INQUIRE}."
4468 new_command("MOVE", 0, 1, move_command, _(
4469 "MOVE [--inquire] [!]source[<TAB>[!]child[..]] [[!]dest[<TAB>[!]child[..]]]\n"
4470 "Moves the source element path to the destination element path. If the "
4471 "destination is not specified then it will be moved to the root node of the "
4472 "document. If the destination is specified and exists then it will be "
4473 "overwritten; otherwise non-existing elements of the destination element "
4474 "path will be created."
4475 "\n"
4476 "When the @option{--inquire} option is passed then all remaining non-option "
4477 "arguments are retrieved via a server @emph{INQUIRE}."
4480 new_command("DELETE", 0, 1, delete_command, _(
4481 "DELETE [--inquire] [!]element[<TAB>[!]child[..]]\n"
4482 "Removes the specified element path and all of its children. This may break "
4483 "an element with a @code{target} attribute (@pxref{Target Attribute}) that "
4484 "refers to this element or any of its children."
4485 "\n"
4486 "When the @option{--inquire} option is passed then all remaining non-option "
4487 "arguments are retrieved via a server @emph{INQUIRE}."
4490 new_command("GET", 0, 1, get_command, _(
4491 "GET [--inquire] [!]element[<TAB>[!]child[..]]\n"
4492 "Retrieves the content of the specified element. The content is returned "
4493 "with a data response."
4494 "\n"
4495 "When the @option{--inquire} option is passed then all remaining non-option "
4496 "arguments are retrieved via a server @emph{INQUIRE}."
4499 new_command("ATTR", 0, 1, attr_command, _(
4500 "ATTR [--inquire] SET|GET|DELETE|LIST [<attribute>] [!]element[<TAB>[!]child[..]] ..\n"
4501 "@table @asis\n"
4502 "@item ATTR SET attribute [!]element[<TAB>[!]child[..]] [value]\n"
4503 "\n"
4504 " Stores or updates an @var{attribute} name and optional @var{value} of an "
4505 "element. When no @var{value} is specified any existing value will be removed."
4506 "\n"
4507 "@item ATTR DELETE attribute [!]element[<TAB>[!]child[..]]\n"
4508 "\n"
4509 " Removes an @var{attribute} from an element."
4510 "\n"
4511 "@item ATTR LIST [!]element[<TAB>[!]child[..]]\n"
4512 "\n"
4513 " Retrieves a newline separated list of attributes names and values "
4514 "from the specified element. Each attribute name and value is space delimited."
4515 "\n"
4516 "@item ATTR GET attribute [!]element[<TAB>[!]child[..]]\n"
4517 "\n"
4518 " Retrieves the value of an @var{attribute} from an element."
4519 "@end table\n"
4520 "\n"
4521 "The @code{_name} attribute (case sensitive) cannot be removed nor modified. "
4522 "Use the @code{DELETE} (@pxref{DELETE}) or @code{RENAME} (@pxref{RENAME}) "
4523 "commands instead."
4524 "\n"
4525 "The @code{_mtime} attribute is updated each time an element is modified by "
4526 "either storing content, editing attributes or by deleting a child element. "
4527 "The @code{_ctime} attribute is created for each new element in an element "
4528 "path."
4529 "\n"
4530 "When the @option{--inquire} option is passed then all remaining non-option "
4531 "arguments are retrieved via a server @emph{INQUIRE}."
4532 "\n"
4533 "@xref{Target Attribute}, for details about this special attribute."
4536 new_command("XPATH", 0, 1, xpath_command, _(
4537 "XPATH [--inquire] <expression>[<TAB>[value]]\n"
4538 "Evaluates an XPath @var{expression}. If no @var{value} argument is "
4539 "specified, it is assumed the expression is a request to return a result. "
4540 "Otherwise, the result is set to the @var{value} argument and the document is "
4541 "updated. If there is no @var{value} after the @key{TAB} character, the value "
4542 "is assumed to be empty and the document is updated. For example:"
4543 "@sp 1\n"
4544 "@example\n"
4545 "XPATH //element[@@_name='password']@key{TAB}\n"
4546 "@end example\n"
4547 "@sp 1"
4548 "would clear the content of all @code{password} elements in the data file "
4549 "while leaving off the trailing @key{TAB} would return all @code{password} "
4550 "elements in @abbr{XML} format."
4551 "\n"
4552 "When the @option{--inquire} option is passed then all remaining non-option "
4553 "arguments are retrieved via a server @emph{INQUIRE}."
4554 "\n"
4555 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
4556 "expression syntax."
4559 new_command("XPATHATTR", 0, 1, xpathattr_command, _(
4560 "XPATHATTR [--inquire] SET|DELETE <name> <expression>[<TAB>[<value>]]\n"
4561 "Like the @code{XPATH} command (@pxref{XPATH}) but operates on element "
4562 "attributes and does not return a result. For the @var{SET} operation the "
4563 "@var{value} is optional but the field is required. If not specified then "
4564 "the attribute value will be empty. For example:"
4565 "@sp 1"
4566 "@example\n"
4567 "XPATHATTR SET password //element[@@_name='password']@key{TAB}\n"
4568 "@end example\n"
4569 "@sp 1"
4570 "would create an @code{password} attribute for each @code{password} element "
4571 "found in the document. The attribute value will be empty but still exist."
4572 "\n"
4573 "When the @option{--inquire} option is passed then all remaining non-option "
4574 "arguments are retrieved via a server @emph{INQUIRE}."
4575 "\n"
4576 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
4577 "expression syntax."
4580 new_command("IMPORT", 0, 1, import_command, _(
4581 "IMPORT <content>[<TAB>[!]element[<TAB>[!]child[..]]]\n"
4582 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
4583 "\n"
4584 "Like the @code{STORE} command (@pxref{STORE}), but the @var{content} "
4585 "argument is raw @abbr{XML} data. The content is created as a child of the "
4586 "specified element path and will overwrite an existing element of the same "
4587 "name. If an element of the element path does not exist then it will be "
4588 "created."
4589 "\n"
4590 "The content must begin with an @abbr{XML} element node. @xref{Introduction}, "
4591 "for details."
4594 new_command("DUMP", 0, 1, dump_command, _(
4595 "DUMP\n"
4596 "Shows the in memory @abbr{XML} document with indenting. @xref{XPATH}, for "
4597 "dumping a specific node."
4600 new_command("LOCK", 0, 0, lock_command, _(
4601 "LOCK\n"
4602 "Locks the mutex associated with the opened file. This prevents other clients "
4603 "from sending commands to the same opened file until the client "
4604 "that sent this command either disconnects or sends the @code{UNLOCK} "
4605 "command. @xref{UNLOCK}."
4608 new_command("UNLOCK", 1, 0, unlock_command, _(
4609 "UNLOCK\n"
4610 "Unlocks the file mutex which was locked with the @code{LOCK} command or "
4611 "a commands' @option{--lock} option (@pxref{LOCK}, @pxref{OPEN}, "
4612 "@pxref{ISCACHED})."
4615 new_command("GETCONFIG", 1, 1, getconfig_command, _(
4616 "GETCONFIG [filename] <parameter>\n"
4617 "Returns the value of a @command{pwmd} configuration @var{parameter} with a "
4618 "data response. If no file has been opened then the value for @var{filename} "
4619 "or the default from the @samp{global} section will be returned. If a file "
4620 "has been opened and no @var{filename} is specified, a value previously "
4621 "set with the @code{OPTION} command (@pxref{OPTION}) will be returned."
4624 new_command("OPTION", 1, 1, option_command, _(
4625 "OPTION <NAME>=<VALUE>\n"
4626 "Sets a client option @var{name} to @var{value}. The value for an option is "
4627 "kept for the duration of the connection."
4628 "\n"
4629 "@table @asis\n"
4630 "@item DISABLE-PINENTRY\n"
4631 " Disable use of @command{pinentry} for passphrase retrieval. When set, a "
4632 " server inquire is sent to the client to obtain the passphrase. This option "
4633 " may be set as needed before the @pxref{OPEN}, @pxref{PASSWD}, and "
4634 " @pxref{SAVE} commands."
4635 "\n"
4636 "@item TTYNAME\n"
4637 " Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4638 "\n"
4639 "@item TTYTYPE\n"
4640 " Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4641 "\n"
4642 "@item DISPLAY\n"
4643 " Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4644 "\n"
4645 "@item PINENTRY-DESC\n"
4646 " Sets the description string of the @command{gpg-agent} and @command{pinentry} dialog."
4647 "\n"
4648 "@item PINENTRY-TITLE\n"
4649 " Sets the title string of the @command{gpg-agent} and @command{pinentry} dialog."
4650 "\n"
4651 "@item PINENTRY-PROMPT\n"
4652 " Sets the prompt string of the @command{gpg-agent} and @command{pinentry} dialog."
4653 "\n"
4654 "@item LC-CTYPE\n"
4655 " Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4656 "\n"
4657 "@item LC-MESSAGES\n"
4658 " Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4659 "\n"
4660 "@item NAME\n"
4661 " Associates the thread ID of the connection with the specified textual "
4662 "representation. Useful for debugging log messages."
4663 "\n"
4664 "@item LOCK-TIMEOUT\n"
4665 " When not @code{0}, the duration in tenths of a second to wait for the file "
4666 "mutex which has been locked by another thread to be released before returning "
4667 "an error. When @code{-1}, then an error will be returned immediately."
4668 "@end table\n"
4671 new_command("LS", 1, 1, ls_command, _(
4672 "LS\n"
4673 "Lists the available data files stored in the data directory "
4674 "(@file{~/.pwmd/data}). The result is a newline separated list of filenames."
4677 new_command("RESET", 1, 1, NULL, _(
4678 "RESET\n"
4679 "Closes the currently opened file but keeps any previously set client options."
4682 new_command("NOP", 1, 1, NULL, _(
4683 "NOP\n"
4684 "Does nothing. Always returns successfully."
4687 /* !END-HELP-TEXT! */
4688 new_command ("CANCEL", 1, 1, NULL, NULL);
4689 new_command ("END", 1, 1, NULL, NULL);
4690 new_command ("BYE", 1, 1, NULL, NULL);
4692 int i;
4693 for (i = 0; command_table[i]; i++);
4694 qsort (command_table, i - 1, sizeof (struct command_table_s *),
4695 sort_commands);
4698 gpg_error_t
4699 register_commands (assuan_context_t ctx)
4701 int i = 0, rc;
4703 for (; command_table[i]; i++)
4705 if (!command_table[i]->handler)
4706 continue;
4708 rc = assuan_register_command (ctx, command_table[i]->name,
4709 command_table[i]->handler,
4710 command_table[i]->help);
4711 if (rc)
4712 return rc;
4715 rc = assuan_register_bye_notify (ctx, bye_notify);
4716 if (rc)
4717 return rc;
4719 rc = assuan_register_reset_notify (ctx, reset_notify);
4720 if (rc)
4721 return rc;
4723 rc = assuan_register_pre_cmd_notify (ctx, command_startup);
4724 if (rc)
4725 return rc;
4727 return assuan_register_post_cmd_notify (ctx, command_finalize);