Comment crypto.c and agent.c.
[pwmd.git] / src / commands.c
blobb483f8817bb581b07f40e176820257dc8950000f
1 /*
2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013
3 Ben Kibbey <bjk@luxsci.net>
5 This file is part of pwmd.
7 Pwmd is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 2 of the License, or
10 (at your option) any later version.
12 Pwmd is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
20 #ifdef HAVE_CONFIG_H
21 #include <config.h>
22 #endif
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <unistd.h>
27 #include <err.h>
28 #include <errno.h>
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <fcntl.h>
32 #include <ctype.h>
33 #include <dirent.h>
34 #include <pthread.h>
35 #include <stdint.h>
37 #ifdef WITH_LIBACL
38 #include <sys/acl.h>
39 #endif
41 #include "pwmd-error.h"
42 #include <gcrypt.h>
44 #include "mem.h"
45 #include "xml.h"
46 #include "util-misc.h"
47 #include "common.h"
48 #include "rcfile.h"
49 #include "cache.h"
50 #include "commands.h"
51 #include "mutex.h"
52 #include "crypto.h"
53 #include "pinentry.h"
55 /* Flags needed to be retained for a client across commands. */
56 #define FLAG_NEW 0x0001
57 #define FLAG_HAS_LOCK 0x0002
58 #define FLAG_LOCK_CMD 0x0004
59 #define FLAG_NO_PINENTRY 0x0008
60 #define FLAG_OPEN 0x0010
61 #define FLAG_KEEP_LOCK 0x0020
63 /* These are command option flags. */
64 #define OPT_INQUIRE 0x0001
65 #define OPT_NO_PASSPHRASE 0x0002
66 #define OPT_RESET 0x0004
67 #define OPT_LIST_RECURSE 0x0008
68 #define OPT_LIST_VERBOSE 0x0010
69 #define OPT_LOCK 0x0020
70 #define OPT_LOCK_ON_OPEN 0x0040
71 #define OPT_SIGN 0x0080
72 #define OPT_LIST_ALL 0x0100
73 #define OPT_LIST_WITH_TARGET 0x0200
74 #define OPT_DATA 0x0400
75 #define OPT_NO_AGENT 0x0800
77 #ifdef WITH_AGENT
78 /* The GETCONFIG command, for example, may fail because pwmd lost the
79 * gpg-agent connection. Update the recovered agent ctx. */
80 #define UPDATE_AGENT_CTX(client, crypto) do { \
81 if (crypto && crypto->agent && crypto->agent->did_restart \
82 && client->crypto && client->crypto->agent \
83 && client->crypto->agent->ctx && \
84 crypto->agent->ctx != client->crypto->agent->ctx) \
85 { \
86 client->crypto->agent->ctx = crypto->agent->ctx; \
87 crypto->agent->ctx = NULL; \
88 } \
89 } while (0)
90 #else
91 #define UPDATE_AGENT_CTX(client, crypto)
92 #endif
94 struct command_table_s
96 const char *name;
97 gpg_error_t (*handler) (assuan_context_t, char *line);
98 const char *help;
99 int ignore_startup;
100 int unlock; // unlock the file mutex after validating the checksum
103 static struct command_table_s **command_table;
105 static gpg_error_t do_lock (struct client_s *client, int add);
106 static gpg_error_t validate_checksum (struct client_s *,
107 struct cache_data_s *);
108 static gpg_error_t update_checksum (struct client_s *client);
110 static gpg_error_t
111 unlock_file_mutex (struct client_s *client, int remove)
113 gpg_error_t rc = 0;
115 // OPEN: keep the lock for the same file being reopened.
116 if (client->flags & FLAG_KEEP_LOCK && client->flags & FLAG_HAS_LOCK)
117 return 0;
119 if (!(client->flags & FLAG_HAS_LOCK))
120 return GPG_ERR_NOT_LOCKED;
122 rc = cache_unlock_mutex (client->md5file, remove);
123 if (rc)
124 rc = GPG_ERR_INV_STATE;
125 else
126 client->flags &= ~(FLAG_HAS_LOCK | FLAG_LOCK_CMD);
128 return rc;
131 static gpg_error_t
132 lock_file_mutex (struct client_s *client, int add)
134 gpg_error_t rc = 0;
135 int timeout = config_get_integer (client->filename, "cache_timeout");
137 if (client->flags & FLAG_HAS_LOCK)
138 return 0;
140 rc = cache_lock_mutex (client->ctx, client->md5file,
141 client->lock_timeout, add, timeout);
142 if (!rc)
143 client->flags |= FLAG_HAS_LOCK;
145 return rc;
148 static gpg_error_t
149 file_modified (struct client_s *client, struct command_table_s *cmd)
151 gpg_error_t rc = 0;
153 if (!(client->flags & FLAG_OPEN))
154 return GPG_ERR_INV_STATE;
156 rc = lock_file_mutex (client, 0);
157 if (!rc || rc == GPG_ERR_NO_DATA)
159 rc = validate_checksum (client, NULL);
160 if (gpg_err_code (rc) == GPG_ERR_ENOENT)
161 rc = 0;
164 if ((cmd->unlock && !(client->flags & FLAG_HAS_LOCK)) || rc)
165 unlock_file_mutex (client, 0);
167 return rc;
170 static gpg_error_t
171 parse_xml (assuan_context_t ctx, int new)
173 struct client_s *client = assuan_get_pointer (ctx);
174 int cached = client->doc != NULL;
176 if (new)
178 client->doc = new_document ();
179 if (client->doc)
181 xmlChar *result;
182 int len;
184 xmlDocDumpFormatMemory (client->doc, &result, &len, 0);
185 client->crypto->plaintext = result;
186 client->crypto->plaintext_len = len;
187 if (!client->crypto->plaintext)
189 xmlFreeDoc (client->doc);
190 client->doc = NULL;
194 else if (!cached)
195 client->doc = parse_doc ((char *) client->crypto->plaintext,
196 client->crypto->plaintext_len);
198 return !client->doc ? GPG_ERR_ENOMEM : 0;
201 static void
202 free_client (struct client_s *client)
204 if (client->doc)
205 xmlFreeDoc (client->doc);
207 xfree (client->crc);
208 xfree (client->filename);
209 xfree (client->last_error);
211 if (client->crypto)
213 cleanup_crypto_stage2 (client->crypto);
214 if (client->crypto->pkey_sexp)
215 gcry_sexp_release (client->crypto->pkey_sexp);
217 client->crypto->pkey_sexp = NULL;
218 memset (client->crypto->sign_grip, 0,
219 sizeof (client->crypto->sign_grip));
220 memset (client->crypto->grip, 0, sizeof(client->crypto->grip));
223 if (client->xml_error)
224 xmlResetError (client->xml_error);
227 void
228 cleanup_client (struct client_s *client)
230 assuan_context_t ctx = client->ctx;
231 struct client_thread_s *thd = client->thd;
232 struct crypto_s *crypto = client->crypto;
233 long lock_timeout = client->lock_timeout;
234 int no_pinentry = (client->flags & FLAG_NO_PINENTRY);
235 struct pinentry_option_s pin_opts;
236 #ifdef WITH_AGENT
237 struct pinentry_option_s agent_pin_opts;
239 if (crypto && crypto->agent)
240 memcpy (&agent_pin_opts, &crypto->agent->pinentry_opts,
241 sizeof(struct pinentry_option_s));
242 #endif
244 memcpy (&pin_opts, &client->pinentry_opts, sizeof(struct pinentry_option_s));
245 unlock_file_mutex (client, client->flags & FLAG_NEW);
246 free_client (client);
247 memset (client, 0, sizeof (struct client_s));
248 client->crypto = crypto;
249 client->ctx = ctx;
250 client->thd = thd;
251 client->lock_timeout = lock_timeout;
252 memcpy (&client->pinentry_opts, &pin_opts, sizeof(struct pinentry_option_s));
253 client->flags |= no_pinentry ? FLAG_NO_PINENTRY : 0;
254 #ifdef WITH_AGENT
255 if (crypto && crypto->agent)
256 memcpy (&crypto->agent->pinentry_opts, &agent_pin_opts,
257 sizeof(struct pinentry_option_s));
258 #endif
261 static gpg_error_t
262 open_finalize (assuan_context_t ctx, char *key, size_t keylen)
264 struct client_s *client = assuan_get_pointer (ctx);
265 gpg_error_t rc = 0;
266 struct cache_data_s *cdata = cache_get_data (client->md5file);
267 int cached = 0, keyarg = key ? 1 : 0;
268 size_t keysize;
269 unsigned char *salted_key = NULL;
270 int algo;
271 int pin_try = 1;
272 int pin_tries = 3;
273 char *pin_title = client->pinentry_opts.title;
275 client->crypto->filename = str_dup (client->filename);
276 if (cdata || client->flags & FLAG_NEW)
278 if (cdata && !(client->flags & FLAG_NEW))
280 rc = decrypt_cache (client->crypto, cdata->doc, cdata->doclen);
281 if (rc)
282 return rc;
285 cached = cdata != NULL;
286 goto done;
289 if (!key && !IS_PKI (client->crypto))
291 if (client->flags & FLAG_NO_PINENTRY)
293 rc = inquire_passphrase (ctx, "PASSPHRASE", (unsigned char **)&key,
294 &keylen);
295 if (rc)
296 return rc;
298 else
300 client->pinentry_opts.timeout = config_get_integer (client->filename,
301 "pinentry_timeout");
302 pin_again:
303 rc = getpin_common (client->ctx, client->filename, PINENTRY_OPEN,
304 &key, &keylen);
305 if (rc)
306 return rc;
310 if (!IS_PKI (client->crypto))
312 algo = cipher_to_gcrypt (client->crypto->hdr.flags);
313 rc = hash_key (algo, client->crypto->hdr.salt,
314 sizeof(client->crypto->hdr.salt), key, keylen,
315 (void **)&salted_key, &keysize);
316 if (!keyarg)
317 gcry_free (key);
319 if (!rc)
321 rc = decrypt_data (client->ctx, client->crypto, salted_key, keysize);
322 if (gpg_err_code (rc) == GPG_ERR_BAD_PASSPHRASE
323 && ++pin_try <= pin_tries && !(client->flags & FLAG_NO_PINENTRY))
325 gcry_free (salted_key);
326 salted_key = NULL;
327 key = NULL;
328 keylen = 0;
329 client->pinentry_opts.title = str_asprintf (_ ("Bad passphrase (try %i of %i)"), pin_try, pin_tries);
330 goto pin_again;
334 if (client->pinentry_opts.title != pin_title)
335 xfree (client->pinentry_opts.title);
337 client->pinentry_opts.title = pin_title;
338 if (rc)
339 return rc;
341 cdata = xcalloc (1, sizeof (struct cache_data_s));
342 if (!cdata)
343 return GPG_ERR_ENOMEM;
345 cdata->key = salted_key;
346 cdata->keylen = keysize;
348 else
349 rc = decrypt_data (client->ctx, client->crypto, NULL, 0);
351 done:
352 if (!rc)
354 rc = parse_xml (ctx, client->flags & FLAG_NEW);
355 if (!rc)
357 int timeout = config_get_integer (client->filename,
358 "cache_timeout");
360 if (!cached)
362 if (!cdata)
363 cdata = xcalloc (1, sizeof (struct cache_data_s));
365 rc = encrypt_xml (NULL, cache_key, cache_keysize,
366 GCRY_CIPHER_AES, client->crypto->plaintext,
367 client->crypto->plaintext_len, &cdata->doc,
368 &cdata->doclen, &cache_iv, &cache_blocksize,
370 if (!rc && !(client->flags & FLAG_NEW) && IS_PKI (client->crypto))
372 rc = gcry_sexp_build ((gcry_sexp_t *) & cdata->pubkey, NULL,
373 "%S", client->crypto->pkey_sexp);
377 if (cdata->sigkey)
378 gcry_sexp_release (cdata->sigkey);
380 cdata->sigkey = NULL;
381 if (!rc && IS_PKI (client->crypto))
382 rc = gcry_sexp_build ((gcry_sexp_t *) &cdata->sigkey, NULL,
383 "%S", client->crypto->sigpkey_sexp);
385 if (!rc && !cache_add_file (client->md5file,
386 (client->flags & FLAG_NEW)
387 ? NULL
388 : client->crypto->grip, cdata, timeout))
390 if (!cached)
392 free_cache_data_once (cdata);
393 xmlFreeDoc (client->doc);
394 client->doc = NULL;
396 rc = GPG_ERR_ENOMEM;
399 if (!rc)
400 client->flags |= FLAG_OPEN;
404 if (!rc)
405 update_checksum (client);
407 if (!rc && (client->opts & OPT_LOCK_ON_OPEN))
408 rc = do_lock (client, 0);
410 return rc;
413 static void
414 req_cleanup (void *arg)
416 if (!arg)
417 return;
419 strv_free ((char **) arg);
422 static gpg_error_t
423 parse_open_opt_lock (void *data, void *value)
425 struct client_s *client = data;
427 client->opts |= OPT_LOCK_ON_OPEN;
428 return 0;
431 static gpg_error_t
432 parse_opt_inquire (void *data, void *value)
434 struct client_s *client = data;
436 (void) value;
437 client->opts |= OPT_INQUIRE;
438 return 0;
441 static gpg_error_t
442 update_checksum (struct client_s *client)
444 unsigned char *crc;
445 size_t len;
446 struct cache_data_s *cdata;
447 gpg_error_t rc = get_checksum (client->filename, &crc, &len);
449 if (rc)
450 return rc;
452 xfree (client->crc);
453 client->crc = crc;
454 cdata = cache_get_data (client->md5file);
455 if (cdata)
457 xfree (cdata->crc);
458 cdata->crc = xmalloc (len);
459 memcpy (cdata->crc, crc, len);
462 return 0;
465 static gpg_error_t
466 validate_checksum (struct client_s *client, struct cache_data_s *cdata)
468 unsigned char *crc;
469 size_t len;
470 gpg_error_t rc;
471 int n = 0;
473 if (cdata && !cdata->crc)
474 return GPG_ERR_CHECKSUM;
476 rc = get_checksum (client->filename, &crc, &len);
477 if (rc)
478 return rc;
480 if (cdata)
481 n = memcmp (cdata->crc, crc, len);
482 else if (client->crc)
483 n = memcmp (client->crc, crc, len);
485 xfree (crc);
486 return n ? GPG_ERR_CHECKSUM : 0;
489 static gpg_error_t
490 do_open (assuan_context_t ctx, const char *filename, const char *password)
492 struct client_s *client = assuan_get_pointer (ctx);
493 struct cache_data_s *cdata;
494 gpg_error_t rc = 0;
495 int done = 0;
497 if (!valid_filename (filename))
498 return GPG_ERR_INV_VALUE;
500 gcry_md_hash_buffer (GCRY_MD_MD5, client->md5file, filename,
501 strlen (filename));
502 client->filename = str_dup (filename);
503 if (!client->filename)
504 return GPG_ERR_ENOMEM;
506 // Cached document?
507 cdata = cache_get_data (client->md5file);
508 if (cdata && cdata->doc)
510 int defer;
512 rc = validate_checksum (client, cdata);
513 /* This will check that the key is cached in the agent which needs to
514 * be determined for files that share a keygrip. */
515 if (!rc)
517 rc = cache_iscached (client->filename, &defer);
518 if (!rc && defer)
519 rc = GPG_ERR_KEY_EXPIRED;
522 #ifdef WITH_GNUTLS
523 if (!rc && client->thd->remote
524 && config_get_boolean (client->filename, "tcp_require_key"))
525 rc = GPG_ERR_KEY_EXPIRED;
526 #endif
528 if (!rc && !password)
530 rc = read_data_header (client->filename, &client->crypto->hdr,
531 NULL, NULL);
532 if (!rc)
534 if (IS_PKI (client->crypto))
536 gcry_sexp_build (&client->crypto->pkey_sexp, NULL, "%S",
537 cdata->pubkey);
538 gcry_pk_get_keygrip (client->crypto->pkey_sexp,
539 client->crypto->grip);
540 gcry_sexp_build (&client->crypto->sigpkey_sexp, NULL, "%S",
541 cdata->sigkey);
542 gcry_pk_get_keygrip (client->crypto->sigpkey_sexp,
543 client->crypto->sign_grip);
546 if (!rc)
548 rc = open_finalize (ctx, NULL, 0);
549 done = 1;
554 /* There was an error accessing the file so clear the cache entry. The
555 * real error will be returned from read_data_file() since the file
556 * may have only disappeared. */
557 if (!done)
559 log_write ("%s: %s", filename, pwmd_strerror (rc));
560 rc = cache_clear (client->md5file);
561 send_status_all (STATUS_CACHE, NULL);
565 if (done || rc)
566 return rc;
568 rc = read_data_file (client->filename, client->crypto);
569 if (rc)
571 if (gpg_err_source (rc) != GPG_ERR_SOURCE_DEFAULT ||
572 gpg_err_code (rc) != GPG_ERR_ENOENT)
574 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
575 return rc;
578 client->flags |= FLAG_NEW;
579 memset (client->crypto->grip, 0, sizeof (client->crypto->grip));
580 memset (client->crypto->sign_grip, 0,
581 sizeof (client->crypto->sign_grip));
582 rc = open_finalize (ctx, NULL, 0);
583 return rc;
586 if (password && IS_PKI (client->crypto))
588 #ifdef WITH_AGENT
589 rc = set_agent_passphrase (client->crypto, password, strlen (password));
590 if (rc)
591 return rc;
592 #endif
595 rc = open_finalize (ctx, (char *)password, password ? strlen (password) : 0);
596 return rc;
599 static gpg_error_t
600 open_command (assuan_context_t ctx, char *line)
602 gpg_error_t rc;
603 struct client_s *client = assuan_get_pointer (ctx);
604 char **req, *password = NULL, *filename;
605 unsigned char md5file[16];
606 int same_file = 0;
607 struct argv_s *args[] = {
608 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_open_opt_lock},
609 NULL
612 rc = parse_options (&line, args, client);
613 if (rc)
614 return send_error (ctx, rc);
616 req = str_split (line, " ", 2);
617 if (!req)
618 return send_error (ctx, GPG_ERR_SYNTAX);
620 #ifdef WITH_GNUTLS
621 if (client->thd->remote)
623 rc = tls_validate_access (client, req[0]);
624 if (rc)
626 if (rc == GPG_ERR_INV_USER_ID)
627 log_write (_("client validation failed for file '%s'"), req[0]);
628 strv_free (req);
629 return send_error (ctx, rc);
632 /* Remote pinentries are not supported. */
633 client->flags |= FLAG_NO_PINENTRY;
635 #endif
637 pthread_cleanup_push (req_cleanup, req);
638 filename = req[0];
639 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
640 /* This client may have locked a different file with ISCACHED --lock than
641 * the current filename. This will remove that lock. */
642 same_file = !memcmp (md5file, client->md5file, 16) ? 1 : 0;
643 if (client->flags & FLAG_OPEN ||
644 (client->flags & FLAG_HAS_LOCK && !same_file))
646 typeof (client->opts) opts = client->opts;
647 typeof (client->flags) flags = client->flags;
649 if (same_file)
650 client->flags |= FLAG_KEEP_LOCK;
652 cleanup_client (client);
653 client->opts = opts;
654 client->flags |= flags;
655 client->flags &= ~(FLAG_LOCK_CMD | FLAG_NEW);
656 if (!same_file)
657 client->flags &= ~(FLAG_HAS_LOCK);
660 /* Need to lock the mutex here because file_modified() cannot without
661 * knowing the filename. */
662 memcpy (client->md5file, md5file, 16);
663 rc = lock_file_mutex (client, 1);
664 if (!rc)
666 password = req[1] && *req[1] ? req[1] : NULL;
667 #ifdef WITH_AGENT
668 if (IS_PKI (client->crypto))
669 rc = set_pinentry_mode (client->crypto->agent,
670 (client->flags & FLAG_NO_PINENTRY) ? "loopback"
671 : "ask");
672 #endif
673 if (!rc)
675 rc = do_open (ctx, filename, password);
676 if (rc)
677 cleanup_client (client);
679 cleanup_crypto_stage1 (client->crypto);
683 pthread_cleanup_pop (1);
685 if (!rc && client->flags & FLAG_NEW)
686 rc = send_status (ctx, STATUS_NEWFILE, NULL);
688 #ifdef WITH_AGENT
689 (void) kill_scd (client->crypto->agent);
690 #endif
691 return send_error (ctx, rc);
694 static gpg_error_t
695 parse_save_opt_no_passphrase (void *data, void *value)
697 struct client_s *client = data;
699 (void) value;
700 client->opts |= OPT_NO_PASSPHRASE;
701 return 0;
704 static gpg_error_t
705 parse_save_opt_no_agent (void *data, void *value)
707 struct client_s *client = data;
709 client->opts |= OPT_NO_AGENT;
710 return 0;
713 static gpg_error_t
714 parse_save_opt_cipher (void *data, void *value)
716 struct client_s *client = data;
717 int algo = cipher_string_to_gcrypt ((char *) value);
718 file_header_t *hdr = &client->crypto->save.hdr;
720 if (algo == -1)
721 return GPG_ERR_INV_VALUE;
723 hdr->flags = set_cipher_flag (hdr->flags, algo);
724 return 0;
727 static gpg_error_t
728 parse_save_opt_keygrip (void *data, void *value)
730 struct client_s *client = data;
732 if (!IS_PKI (client->crypto))
733 return GPG_ERR_INV_ARG;
735 #ifdef WITH_AGENT
736 if (client->crypto->save.pkey)
737 gcry_sexp_release (client->crypto->save.pkey);
739 client->crypto->save.pkey = NULL;
740 return get_pubkey (client->crypto, value, &client->crypto->save.pkey);
741 #else
742 return GPG_ERR_INV_ARG;
743 #endif
746 static gpg_error_t
747 parse_save_opt_sign_keygrip (void *data, void *value)
749 struct client_s *client = data;
751 if (!IS_PKI (client->crypto))
752 return GPG_ERR_INV_ARG;
754 #ifdef WITH_AGENT
755 if (client->crypto->save.sigpkey)
756 gcry_sexp_release (client->crypto->save.sigpkey);
758 client->crypto->save.sigpkey = NULL;
759 return get_pubkey (client->crypto, value, &client->crypto->save.sigpkey);
760 #else
761 return GPG_ERR_INV_ARG;
762 #endif
765 static gpg_error_t
766 parse_opt_s2k_count (void *data, void *value)
768 struct client_s *client = data;
769 char *v = value;
771 if (!v || !*v)
772 return GPG_ERR_INV_VALUE;
774 client->crypto->save.s2k_count = strtoul (v, NULL, 10);
775 return 0;
778 static gpg_error_t
779 parse_save_opt_iterations (void *data, void *value)
781 struct client_s *client = data;
782 char *v = value, *p;
783 uint64_t n;
785 if (!v || !*v)
786 return GPG_ERR_INV_VALUE;
788 errno = 0;
789 n = strtoull (v, &p, 10);
790 if (n == UINT64_MAX && errno)
791 return gpg_error_from_syserror ();
792 else if (p && *p)
793 return GPG_ERR_INV_VALUE;
795 client->crypto->save.hdr.iterations = n;
796 return 0;
799 static gpg_error_t
800 save_finalize (assuan_context_t ctx)
802 struct client_s *client = assuan_get_pointer (ctx);
803 gpg_error_t rc = 0;
804 xmlChar *xmlbuf = NULL;
805 int xmlbuflen;
806 void *key = NULL;
807 size_t keylen = 0;
809 xmlDocDumpFormatMemory (client->doc, &xmlbuf, &xmlbuflen, 0);
810 if (!xmlbuf)
811 return GPG_ERR_ENOMEM;
813 pthread_cleanup_push (xmlFree, xmlbuf);
815 if (!use_agent || ((client->flags & FLAG_NEW)
816 && (client->opts & OPT_NO_AGENT))
817 || !(client->crypto->hdr.flags & PWMD_FLAG_PKI))
819 rc = export_common (ctx, client->flags & FLAG_NO_PINENTRY,
820 client->crypto, xmlbuf, xmlbuflen, client->filename,
821 NULL, &key, &keylen, 1, 1);
823 #ifdef WITH_AGENT
824 else
826 gcry_sexp_t pubkey = client->crypto->save.pkey;
827 gcry_sexp_t sigkey = client->crypto->save.sigpkey;
829 if (!pubkey)
830 pubkey = client->crypto->pkey_sexp;
832 if (!sigkey)
834 sigkey = client->crypto->sigpkey_sexp;
835 if (!sigkey)
837 gcry_sexp_build (&client->crypto->save.sigpkey, 0, "%S", pubkey);
838 sigkey = client->crypto->save.sigpkey;
842 rc = encrypt_data_file (client->ctx, client->crypto, pubkey, sigkey,
843 client->filename, xmlbuf, xmlbuflen);
844 if (pubkey == client->crypto->save.pkey)
846 if (!rc)
848 gcry_sexp_release (client->crypto->pkey_sexp);
849 client->crypto->pkey_sexp = client->crypto->save.pkey;
850 gcry_pk_get_keygrip (client->crypto->pkey_sexp,
851 client->crypto->grip);
853 else
854 gcry_sexp_release (pubkey);
856 client->crypto->save.pkey = NULL;
859 if (!rc)
860 gcry_pk_get_keygrip (sigkey, client->crypto->sign_grip);
862 if (sigkey == client->crypto->save.sigpkey)
864 if (!rc)
866 if (client->crypto->sigpkey_sexp)
867 gcry_sexp_release (client->crypto->sigpkey_sexp);
869 client->crypto->sigpkey_sexp = client->crypto->save.sigpkey;
870 gcry_pk_get_keygrip (client->crypto->sigpkey_sexp,
871 client->crypto->sign_grip);
873 else
874 gcry_sexp_release (sigkey);
876 client->crypto->save.sigpkey = NULL;
879 #endif
881 if (!rc)
883 int cached;
885 rc = save_common (client->filename, client->crypto, xmlbuf, xmlbuflen,
886 key, keylen, &cached, client->opts & OPT_NO_AGENT);
887 if (rc)
888 gcry_free (key);
890 if (!rc && (!cached || (client->flags & FLAG_NEW)))
891 send_status_all (STATUS_CACHE, NULL);
893 if (!rc)
895 update_checksum (client);
896 client->flags &= ~(FLAG_NEW);
898 else
899 rc = GPG_ERR_ENOMEM;
902 pthread_cleanup_pop (1); // xmlFree
903 return rc;
906 static gpg_error_t
907 parse_opt_reset (void *data, void *value)
909 struct client_s *client = data;
911 (void) value;
912 client->opts |= OPT_RESET;
913 return 0;
916 static gpg_error_t
917 save_command (assuan_context_t ctx, char *line)
919 struct client_s *client = assuan_get_pointer (ctx);
920 gpg_error_t rc;
921 struct stat st;
922 struct argv_s *args[] = {
923 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG,
924 parse_save_opt_no_passphrase},
925 &(struct argv_s) {"cipher", OPTION_TYPE_ARG, parse_save_opt_cipher},
926 &(struct argv_s) {"inquire-keyparam", OPTION_TYPE_NOARG,
927 parse_opt_inquire},
928 &(struct argv_s) {"keygrip", OPTION_TYPE_ARG, parse_save_opt_keygrip},
929 &(struct argv_s) {"sign-keygrip", OPTION_TYPE_ARG,
930 parse_save_opt_sign_keygrip},
931 &(struct argv_s) {"s2k-count", OPTION_TYPE_ARG, parse_opt_s2k_count},
932 &(struct argv_s) {"reset", OPTION_TYPE_NOARG, parse_opt_reset},
933 &(struct argv_s) {"cipher-iterations", OPTION_TYPE_ARG,
934 parse_save_opt_iterations},
935 &(struct argv_s) {"no-agent", OPTION_TYPE_NOARG,
936 parse_save_opt_no_agent},
937 NULL
940 cleanup_save (&client->crypto->save);
941 memcpy (&client->crypto->save.hdr, &client->crypto->hdr,
942 sizeof (file_header_t));
943 client->crypto->save.s2k_count =
944 config_get_ulong (client->filename, "s2k_count");
946 if (client->flags & FLAG_NEW)
947 client->crypto->save.hdr.iterations =
948 config_get_ulonglong (client->filename, "cipher_iterations");
950 rc = parse_options (&line, args, client);
951 if (rc)
952 return send_error (ctx, rc);
954 if (!(client->flags & FLAG_NEW))
955 client->opts &= ~OPT_NO_AGENT;
956 else if (client->opts & OPT_NO_AGENT)
958 client->crypto->save.hdr.flags &= ~PWMD_FLAG_PKI;
959 client->crypto->hdr.flags &= ~PWMD_FLAG_PKI;
962 if ((client->opts & OPT_NO_PASSPHRASE) && !(client->flags & FLAG_NEW)
963 && !(client->opts & OPT_INQUIRE))
964 return send_error (ctx, GPG_ERR_WRONG_KEY_USAGE);
966 if (lstat (client->filename, &st) == -1 && errno != ENOENT)
967 return send_error (ctx, gpg_error_from_syserror ());
969 if (errno != ENOENT && !S_ISREG (st.st_mode))
971 log_write ("%s: %s", client->filename, pwmd_strerror (GPG_ERR_ENOANO));
972 return send_error (ctx, GPG_ERR_ENOANO);
975 int defer;
976 rc = cache_iscached (client->filename, &defer);
977 if ((!rc && defer) || config_get_boolean ("global", "require_save_key"))
978 client->opts |= OPT_RESET;
980 if (client->opts & OPT_RESET)
982 rc = cache_clear (client->md5file);
983 if (rc)
984 return send_error (ctx, rc);
986 log_write ("%s: %s", client->filename,
987 pwmd_strerror (GPG_ERR_KEY_EXPIRED));
988 send_status_all (STATUS_CACHE, NULL);
991 rc = update_element_mtime (xmlDocGetRootElement (client->doc));
992 if (rc)
993 return send_error (ctx, rc);
995 #ifdef WITH_AGENT
996 if (!rc && use_agent && !client->crypto->save.pkey &&
997 (client->flags & FLAG_NEW || client->opts & OPT_INQUIRE)
998 && !(client->opts & OPT_NO_AGENT))
1000 rc = set_pinentry_mode (client->crypto->agent,
1001 (client->flags & FLAG_NO_PINENTRY) ? "loopback"
1002 : "ask");
1004 if (!(client->flags & FLAG_NEW))
1006 struct crypto_s *crypto;
1007 char *key = NULL;
1008 size_t keylen = 0;
1010 /* Wanting to generate a new key. Require the key to open the
1011 current file before proceeding reguardless of the
1012 require_save_key configuration parameter. */
1013 rc = cache_clear (client->md5file);
1014 if (!rc)
1016 rc = init_client_crypto (&crypto);
1017 if (!rc)
1018 crypto->client_ctx = client->ctx;
1021 if (!rc)
1022 rc = decrypt_common (client->ctx, client->opts&OPT_INQUIRE, crypto,
1023 client->filename, &key, &keylen);
1025 xfree (key);
1026 cleanup_crypto (&crypto);
1029 if (!rc)
1030 rc = send_status (client->ctx, STATUS_GENKEY, NULL);
1032 if (!rc)
1034 struct inquire_data_s idata = { 0 };
1035 char *params = client->opts & OPT_INQUIRE
1036 ? NULL : default_key_params (client->crypto);
1038 pthread_cleanup_push (xfree, params);
1039 idata.crypto = client->crypto;
1041 if (params)
1043 idata.line = params;
1044 idata.len = strlen (params);
1046 else
1047 idata.preset = 1;
1049 client->crypto->agent->inquire_data = &idata;
1050 client->crypto->agent->inquire_cb = NULL;
1051 rc = generate_key (client->crypto, params,
1052 (client->opts & OPT_NO_PASSPHRASE), 1);
1053 pthread_cleanup_pop (1);
1056 #endif
1058 if (!rc)
1059 rc = save_finalize (ctx);
1061 cleanup_crypto_stage1 (client->crypto);
1062 #ifdef WITH_AGENT
1063 (void) kill_scd (client->crypto->agent);
1064 #endif
1065 return send_error (ctx, rc);
1068 static gpg_error_t
1069 do_delete (assuan_context_t ctx, char *line)
1071 struct client_s *client = assuan_get_pointer (ctx);
1072 gpg_error_t rc;
1073 char **req;
1074 xmlNodePtr n;
1076 if (strchr (line, '\t'))
1077 req = str_split (line, "\t", 0);
1078 else
1079 req = str_split (line, " ", 0);
1081 if (!req || !*req)
1082 return GPG_ERR_SYNTAX;
1084 n = find_root_element (client->doc, &req, &rc, NULL, 0, 0);
1085 if (!n)
1087 strv_free (req);
1088 return rc;
1092 * No sub-node defined. Remove the entire node (root element).
1094 if (!req[1])
1096 if (n)
1098 rc = unlink_node (n);
1099 xmlFreeNode (n);
1102 strv_free (req);
1103 return rc;
1107 find_elements (client->doc, n->children, req + 1, &rc, NULL, NULL, NULL,
1108 0, 0, NULL, 0);
1109 strv_free (req);
1110 if (!n)
1111 return rc;
1113 if (n)
1115 rc = unlink_node (n);
1116 xmlFreeNode (n);
1119 return rc;
1122 static gpg_error_t
1123 delete_command (assuan_context_t ctx, char *line)
1125 struct client_s *client = assuan_get_pointer (ctx);
1126 gpg_error_t rc;
1127 struct argv_s *args[] = {
1128 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1129 NULL
1132 rc = parse_options (&line, args, client);
1133 if (rc)
1134 return send_error (ctx, rc);
1136 if (client->opts & OPT_INQUIRE)
1138 unsigned char *result;
1139 size_t len;
1141 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1142 if (rc)
1143 return send_error (ctx, rc);
1145 line = (char *) result;
1148 rc = do_delete (ctx, line);
1150 if (client->opts & OPT_INQUIRE)
1151 xfree (line);
1153 return send_error (ctx, rc);
1156 static gpg_error_t
1157 store_command (assuan_context_t ctx, char *line)
1159 struct client_s *client = assuan_get_pointer (ctx);
1160 gpg_error_t rc;
1161 size_t len;
1162 unsigned char *result;
1163 char **req;
1164 xmlNodePtr n, parent;
1165 int has_content;
1166 char *content = NULL;
1168 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1169 if (rc)
1170 return send_error (ctx, rc);
1172 req = str_split ((char *) result, "\t", 0);
1173 xfree (result);
1175 if (!req || !*req)
1176 return send_error (ctx, GPG_ERR_SYNTAX);
1178 len = strv_length (req);
1179 has_content = line[strlen (line) - 1] != '\t' && len > 1;
1180 if (*(req + 1) && !valid_element_path (req, has_content))
1182 strv_free (req);
1183 return send_error (ctx, GPG_ERR_INV_VALUE);
1186 if (has_content || !*req[len - 1])
1188 has_content = 1;
1189 content = req[len - 1];
1190 req[len - 1] = NULL;
1193 again:
1194 n = find_root_element (client->doc, &req, &rc, NULL, 0, 0);
1195 if (rc && rc == GPG_ERR_ELEMENT_NOT_FOUND)
1197 rc = new_root_element (client->doc, *req);
1198 if (rc)
1200 strv_free (req);
1201 return send_error (ctx, GPG_ERR_SYNTAX);
1204 goto again;
1207 if (!n)
1209 strv_free (req);
1210 return send_error (ctx, rc);
1213 parent = n;
1215 if (req[1] && *req[1])
1217 if (!n->children)
1218 parent = create_elements_cb (n, req + 1, &rc, NULL);
1219 else
1220 parent = find_elements (client->doc, n->children, req + 1, &rc,
1221 NULL, NULL, create_elements_cb, 0, 0, NULL,
1225 if (!rc && len > 1)
1227 n = find_text_node (parent->children);
1228 if (n)
1229 xmlNodeSetContent (n, (xmlChar *) content);
1230 else
1231 xmlNodeAddContent (parent, (xmlChar *) content);
1233 update_element_mtime (parent);
1236 xfree (content);
1237 strv_free (req);
1238 return send_error (ctx, rc);
1241 static gpg_error_t
1242 xfer_data (assuan_context_t ctx, const char *line, int total)
1244 int to_send;
1245 int sent = 0;
1246 gpg_error_t rc;
1247 int progress = config_get_integer ("global", "xfer_progress");
1248 int flush = 0;
1250 progress =
1251 progress > 0 ? (progress / ASSUAN_LINELENGTH) * ASSUAN_LINELENGTH : 0;
1252 to_send = total < ASSUAN_LINELENGTH ? total : ASSUAN_LINELENGTH;
1253 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1255 if (rc)
1256 return rc;
1258 again:
1261 if (sent + to_send > total)
1262 to_send = total - sent;
1264 rc = assuan_send_data (ctx, flush ? NULL : (char *) line + sent,
1265 flush ? 0 : to_send);
1266 if (!rc)
1268 sent += flush ? 0 : to_send;
1270 if ((progress && !(sent % progress) && sent != total) ||
1271 (sent == total && flush))
1272 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1274 if (!flush && !rc && sent == total)
1276 flush = 1;
1277 goto again;
1281 while (!rc && sent < total);
1283 return rc;
1286 static gpg_error_t
1287 do_get (assuan_context_t ctx, char *line)
1289 struct client_s *client = assuan_get_pointer (ctx);
1290 gpg_error_t rc;
1291 char **req;
1292 xmlNodePtr n;
1294 req = str_split (line, "\t", 0);
1296 if (!req || !*req)
1298 strv_free (req);
1299 return GPG_ERR_SYNTAX;
1302 n = find_root_element (client->doc, &req, &rc, NULL, 0, 0);
1303 if (!n)
1305 strv_free (req);
1306 return rc;
1309 if (req[1])
1311 find_elements (client->doc, n->children, req + 1, &rc, NULL, NULL, NULL,
1312 0, 0, NULL, 0);
1314 strv_free (req);
1315 if (rc)
1316 return rc;
1318 if (!n || !n->children)
1319 return GPG_ERR_NO_DATA;
1321 n = find_text_node (n->children);
1322 if (!n || !n->content || !*n->content)
1323 return GPG_ERR_NO_DATA;
1325 rc = xfer_data (ctx, (char *) n->content, xmlStrlen (n->content));
1326 return rc;
1329 static gpg_error_t
1330 get_command (assuan_context_t ctx, char *line)
1332 struct client_s *client = assuan_get_pointer (ctx);
1333 gpg_error_t rc;
1334 struct argv_s *args[] = {
1335 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1336 NULL
1339 rc = parse_options (&line, args, client);
1340 if (rc)
1341 return send_error (ctx, rc);
1343 if (client->opts & OPT_INQUIRE)
1345 unsigned char *result;
1346 size_t len;
1348 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1349 if (rc)
1350 return send_error (ctx, rc);
1352 line = (char *) result;
1355 rc = do_get (ctx, line);
1357 if (client->opts & OPT_INQUIRE)
1358 xfree (line);
1360 return send_error (ctx, rc);
1363 static void list_command_cleanup1 (void *arg);
1364 static gpg_error_t
1365 realpath_command (assuan_context_t ctx, char *line)
1367 struct string_s *string = NULL;
1368 gpg_error_t rc;
1369 struct client_s *client = assuan_get_pointer (ctx);
1370 struct argv_s *args[] = {
1371 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1372 NULL
1375 rc = parse_options (&line, args, client);
1376 if (rc)
1377 return send_error (ctx, rc);
1379 if (client->opts & OPT_INQUIRE)
1381 unsigned char *result;
1382 size_t len;
1384 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1385 if (rc)
1386 return send_error (ctx, rc);
1388 line = (char *) result;
1391 rc = build_realpath (client->doc, line, &string);
1392 if (!rc)
1394 pthread_cleanup_push (list_command_cleanup1, string);
1395 rc = xfer_data (ctx, string->str, string->len);
1396 pthread_cleanup_pop (1);
1399 if (client->opts & OPT_INQUIRE)
1400 xfree (line);
1402 return send_error (ctx, rc);
1405 static void
1406 list_command_cleanup1 (void *arg)
1408 if (arg)
1409 string_free ((struct string_s *) arg, 1);
1412 static void
1413 list_command_cleanup2 (void *arg)
1415 struct element_list_s *elements = arg;
1417 if (elements)
1419 if (elements->list)
1421 int total = slist_length (elements->list);
1422 int i;
1424 for (i = 0; i < total; i++)
1426 char *tmp = slist_nth_data (elements->list, i);
1427 xfree (tmp);
1430 slist_free (elements->list);
1433 if (elements->prefix)
1434 xfree (elements->prefix);
1436 if (elements->req)
1437 strv_free (elements->req);
1439 xfree (elements);
1443 static gpg_error_t
1444 parse_list_opt_norecurse (void *data, void *value)
1446 struct client_s *client = data;
1448 client->opts &= ~(OPT_LIST_RECURSE);
1449 return 0;
1452 static gpg_error_t
1453 parse_list_opt_verbose (void *data, void *value)
1455 struct client_s *client = data;
1457 client->opts |= OPT_LIST_VERBOSE;
1458 return 0;
1461 static gpg_error_t
1462 parse_list_opt_target (void *data, void *value)
1464 struct client_s *client = data;
1466 client->opts |= OPT_LIST_WITH_TARGET;
1467 return 0;
1470 static gpg_error_t
1471 parse_list_opt_all (void *data, void *value)
1473 struct client_s *client = data;
1475 client->opts |= OPT_LIST_ALL;
1476 return 0;
1479 static gpg_error_t
1480 list_path_once (struct client_s *client, char *line,
1481 struct element_list_s *elements, struct string_s *result)
1483 gpg_error_t rc;
1485 elements->req = str_split (line, " ", 0);
1486 if (!elements->req)
1487 strv_printf (&elements->req, "%s", line);
1489 rc = create_path_list (client->doc, elements, *elements->req);
1490 if (rc == GPG_ERR_ELOOP && elements->verbose)
1491 rc = 0;
1493 if (!rc)
1495 int total = slist_length (elements->list);
1496 int i;
1498 if (!total)
1499 rc = GPG_ERR_NO_DATA;
1501 if (!rc)
1503 if (!rc)
1505 for (i = 0; i < total; i++)
1507 char *tmp = slist_nth_data (elements->list, i);
1509 string_append_printf (result, "%s%s", tmp,
1510 i + 1 == total ? "" : "\n");
1514 else
1515 rc = GPG_ERR_NO_DATA;
1518 return rc;
1521 static int
1522 has_list_flag (char *path, char *flags)
1524 char *p = path;
1526 while (*p && *++p != ' ');
1528 if (!*p)
1529 return 0;
1531 for (; *p; p++)
1533 char *f;
1535 for (f = flags; *f && *f != ' '; f++)
1537 if (*p == *f)
1538 return 1;
1542 return 0;
1545 static gpg_error_t
1546 do_list (assuan_context_t ctx, char *line)
1548 struct client_s *client = assuan_get_pointer (ctx);
1549 gpg_error_t rc;
1550 struct element_list_s *elements = NULL;
1552 elements = xcalloc (1, sizeof (struct element_list_s));
1553 if (!elements)
1554 return GPG_ERR_ENOMEM;
1556 elements->recurse = client->opts & OPT_LIST_RECURSE;
1557 elements->verbose =
1558 (client->opts & OPT_LIST_VERBOSE) | (client->opts & OPT_LIST_WITH_TARGET);
1559 elements->with_target = client->opts & OPT_LIST_WITH_TARGET;
1561 if (!line || !*line)
1563 struct string_s *str = NULL;
1565 pthread_cleanup_push (list_command_cleanup2, elements);
1566 rc = list_root_elements (client->doc, &str, elements->verbose,
1567 elements->with_target);
1568 pthread_cleanup_pop (1);
1569 pthread_cleanup_push (list_command_cleanup1, str);
1571 if (!rc)
1573 if (client->opts & OPT_LIST_ALL)
1575 char **roots = str_split (str->str, "\n", 0);
1576 char **p;
1578 pthread_cleanup_push (req_cleanup, roots);
1579 string_truncate (str, 0);
1581 for (p = roots; *p; p++)
1583 if (strchr (*p, ' '))
1585 if (has_list_flag (*p, "EO"))
1587 string_append_printf (str, "%s%s", *p,
1588 *(p + 1) ? "\n" : "");
1589 continue;
1593 elements = xcalloc (1, sizeof (struct element_list_s));
1594 if (!elements)
1596 rc = GPG_ERR_ENOMEM;
1597 break;
1600 elements->recurse = client->opts & OPT_LIST_RECURSE;
1601 elements->verbose =
1602 (client->opts & OPT_LIST_VERBOSE) | (client->opts &
1603 OPT_LIST_WITH_TARGET);
1604 elements->with_target = client->opts & OPT_LIST_WITH_TARGET;
1605 pthread_cleanup_push (list_command_cleanup2, elements);
1606 rc = list_path_once (client, *p, elements, str);
1607 pthread_cleanup_pop (1);
1608 if (rc)
1609 break;
1611 if (*(p + 1))
1612 string_append (str, "\n");
1615 pthread_cleanup_pop (1);
1618 if (!rc)
1619 rc = xfer_data (ctx, str->str, str->len);
1622 pthread_cleanup_pop (1);
1623 return rc;
1626 pthread_cleanup_push (list_command_cleanup2, elements);
1627 struct string_s *str = string_new (NULL);
1628 pthread_cleanup_push (list_command_cleanup1, str);
1629 rc = list_path_once (client, line, elements, str);
1630 if (!rc)
1631 rc = xfer_data (ctx, str->str, str->len);
1633 pthread_cleanup_pop (1);
1634 pthread_cleanup_pop (1);
1635 return rc;
1638 static gpg_error_t
1639 list_command (assuan_context_t ctx, char *line)
1641 struct client_s *client = assuan_get_pointer (ctx);
1642 gpg_error_t rc;
1643 struct argv_s *args[] = {
1644 &(struct argv_s) {"no-recurse", OPTION_TYPE_NOARG,
1645 parse_list_opt_norecurse},
1646 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_list_opt_verbose},
1647 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1648 &(struct argv_s) {"with-target", OPTION_TYPE_NOARG,
1649 parse_list_opt_target},
1650 &(struct argv_s) {"all", OPTION_TYPE_NOARG, parse_list_opt_all},
1651 NULL
1654 if (disable_list_and_dump == 1)
1655 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
1657 client->opts |= OPT_LIST_RECURSE;
1658 rc = parse_options (&line, args, client);
1659 if (rc)
1660 return send_error (ctx, rc);
1662 if (client->opts & OPT_LIST_ALL)
1663 client->opts |= OPT_LIST_RECURSE | OPT_LIST_VERBOSE;
1665 if (client->opts & OPT_INQUIRE)
1667 unsigned char *result;
1668 size_t len;
1670 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1671 if (rc)
1672 return send_error (ctx, rc);
1674 line = (char *) result;
1677 rc = do_list (ctx, line);
1679 if (client->opts & OPT_INQUIRE)
1680 xfree (line);
1682 return send_error (ctx, rc);
1686 * req[0] - element path
1688 static gpg_error_t
1689 attribute_list (assuan_context_t ctx, char **req)
1691 struct client_s *client = assuan_get_pointer (ctx);
1692 char **attrlist = NULL;
1693 int i = 0;
1694 char **path = NULL;
1695 xmlAttrPtr a;
1696 xmlNodePtr n, an;
1697 char *line;
1698 gpg_error_t rc;
1700 if (!req || !req[0])
1701 return GPG_ERR_SYNTAX;
1703 if ((path = str_split (req[0], "\t", 0)) == NULL)
1706 * The first argument may be only a root element.
1708 if ((path = str_split (req[0], " ", 0)) == NULL)
1709 return GPG_ERR_SYNTAX;
1712 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
1714 if (!n)
1716 strv_free (path);
1717 return rc;
1720 if (path[1])
1722 n = find_elements (client->doc, n->children, path + 1, &rc,
1723 NULL, NULL, NULL, 0, 0, NULL, 0);
1725 if (!n)
1727 strv_free (path);
1728 return rc;
1732 strv_free (path);
1734 for (a = n->properties; a; a = a->next)
1736 char **pa;
1738 if ((pa = xrealloc (attrlist, (i + 2) * sizeof (char *))) == NULL)
1740 if (attrlist)
1741 strv_free (attrlist);
1743 log_write ("%s(%i): %s", __FILE__, __LINE__,
1744 pwmd_strerror (GPG_ERR_ENOMEM));
1745 return GPG_ERR_ENOMEM;
1748 attrlist = pa;
1749 an = a->children;
1750 attrlist[i] = str_asprintf ("%s %s", (char *) a->name,
1752 && an->content ? (char *) an->content : "");
1754 if (!attrlist[i])
1756 strv_free (attrlist);
1757 log_write ("%s(%i): %s", __FILE__, __LINE__,
1758 pwmd_strerror (GPG_ERR_ENOMEM));
1759 return GPG_ERR_ENOMEM;
1762 attrlist[++i] = NULL;
1765 if (!attrlist)
1766 return GPG_ERR_NO_DATA;
1768 line = strv_join ("\n", attrlist);
1770 if (!line)
1772 log_write ("%s(%i): %s", __FILE__, __LINE__,
1773 pwmd_strerror (GPG_ERR_ENOMEM));
1774 strv_free (attrlist);
1775 return GPG_ERR_ENOMEM;
1778 pthread_cleanup_push (xfree, line);
1779 pthread_cleanup_push (req_cleanup, attrlist);
1780 rc = xfer_data (ctx, line, strlen (line));
1781 pthread_cleanup_pop (1);
1782 pthread_cleanup_pop (1);
1783 return rc;
1787 * req[0] - attribute
1788 * req[1] - element path
1790 static gpg_error_t
1791 attribute_delete (struct client_s *client, char **req)
1793 xmlNodePtr n;
1794 char **path = NULL;
1795 gpg_error_t rc;
1797 if (!req || !req[0] || !req[1])
1798 return GPG_ERR_SYNTAX;
1800 if (!strcmp (req[0], "_name"))
1801 return GPG_ERR_INV_ATTR;
1803 if ((path = str_split (req[1], "\t", 0)) == NULL)
1806 * The first argument may be only a root element.
1808 if ((path = str_split (req[1], " ", 0)) == NULL)
1809 return GPG_ERR_SYNTAX;
1812 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
1813 if (!n)
1814 goto fail;
1816 if (path[1])
1818 n = find_elements (client->doc, n->children, path + 1, &rc,
1819 NULL, NULL, NULL, 0, 0, NULL, 0);
1820 if (!n)
1821 goto fail;
1824 rc = delete_attribute (n, (xmlChar *) req[0]);
1826 fail:
1827 strv_free (path);
1828 return rc;
1831 static xmlNodePtr
1832 create_element_path (struct client_s *client,
1833 char ***elements, gpg_error_t * rc, xmlNodePtr parent)
1835 char **req = *elements;
1836 char **req_orig = strv_dup (req);
1837 xmlNodePtr n = NULL;
1839 *rc = 0;
1841 if (!req_orig)
1843 *rc = GPG_ERR_ENOMEM;
1844 log_write ("%s(%i): %s", __FILE__, __LINE__,
1845 pwmd_strerror (GPG_ERR_ENOMEM));
1846 goto fail;
1849 again:
1850 n = find_root_element (client->doc, &req, rc, NULL, 0, 0);
1851 if (!n)
1853 if (*rc != GPG_ERR_ELEMENT_NOT_FOUND)
1854 goto fail;
1856 *rc = new_root_element (client->doc, req[0]);
1857 if (*rc)
1858 goto fail;
1860 goto again;
1862 else if (n == parent)
1864 *rc = GPG_ERR_CONFLICT;
1865 goto fail;
1868 if (req[1])
1870 if (!n->children)
1871 n = create_target_elements_cb (n, req + 1, rc, NULL);
1872 else
1873 n = find_elements (client->doc, n->children, req + 1, rc, NULL, NULL,
1874 create_target_elements_cb, 0, 0, parent, 0);
1876 if (!n)
1877 goto fail;
1880 * Reset the position of the element tree now that the elements
1881 * have been created.
1883 strv_free (req);
1884 req = req_orig;
1885 req_orig = NULL;
1886 n = find_root_element (client->doc, &req, rc, NULL, 0, 0);
1887 if (!n)
1888 goto fail;
1890 n = find_elements (client->doc, n->children, req + 1, rc,
1891 NULL, NULL, NULL, 0, 0, NULL, 0);
1892 if (!n)
1893 goto fail;
1896 fail:
1897 if (req_orig)
1898 strv_free (req_orig);
1900 *elements = req;
1901 return n;
1905 * Creates a "target" attribute. When other commands encounter an element with
1906 * this attribute, the element path is modified to the target value. If the
1907 * source element path doesn't exist when using 'ATTR SET target', it is
1908 * created, but the destination element path must exist.
1910 * req[0] - source element path
1911 * req[1] - destination element path
1913 static gpg_error_t
1914 target_attribute (struct client_s *client, char **req)
1916 char **src, **dst, *line = NULL, **odst = NULL;
1917 gpg_error_t rc;
1918 xmlNodePtr n;
1920 if (!req || !req[0] || !req[1])
1921 return GPG_ERR_SYNTAX;
1923 if ((src = str_split (req[0], "\t", 0)) == NULL)
1926 * The first argument may be only a root element.
1928 if ((src = str_split (req[0], " ", 0)) == NULL)
1929 return GPG_ERR_SYNTAX;
1932 if (!valid_element_path (src, 0))
1933 return GPG_ERR_INV_VALUE;
1935 if ((dst = str_split (req[1], "\t", 0)) == NULL)
1938 * The first argument may be only a root element.
1940 if ((dst = str_split (req[1], " ", 0)) == NULL)
1942 rc = GPG_ERR_SYNTAX;
1943 goto fail;
1947 odst = strv_dup (dst);
1948 if (!odst)
1950 rc = GPG_ERR_ENOMEM;
1951 goto fail;
1954 n = find_root_element (client->doc, &dst, &rc, NULL, 0, 0);
1956 * Make sure the destination element path exists.
1958 if (!n)
1959 goto fail;
1961 if (dst[1])
1963 n = find_elements (client->doc, n->children, dst + 1, &rc,
1964 NULL, NULL, NULL, 0, 0, NULL, 0);
1965 if (!n)
1966 goto fail;
1969 rc = validate_target_attribute (client->doc, req[0], n);
1970 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
1971 goto fail;
1973 n = create_element_path (client, &src, &rc, NULL);
1974 if (rc)
1975 goto fail;
1977 line = strv_join ("\t", odst);
1978 if (!line)
1980 rc = GPG_ERR_ENOMEM;
1981 goto fail;
1984 rc = add_attribute (n, "target", line);
1986 fail:
1987 xfree (line);
1988 strv_free (src);
1989 strv_free (dst);
1990 strv_free (odst);
1991 return rc;
1995 * req[0] - attribute
1996 * req[1] - element path
1998 static gpg_error_t
1999 attribute_get (assuan_context_t ctx, char **req)
2001 struct client_s *client = assuan_get_pointer (ctx);
2002 xmlNodePtr n;
2003 xmlChar *a;
2004 char **path = NULL;
2005 gpg_error_t rc;
2007 if (!req || !req[0] || !req[1])
2008 return GPG_ERR_SYNTAX;
2010 if (strchr (req[1], '\t'))
2012 if ((path = str_split (req[1], "\t", 0)) == NULL)
2013 return GPG_ERR_SYNTAX;
2015 else
2017 if ((path = str_split (req[1], " ", 0)) == NULL)
2018 return GPG_ERR_SYNTAX;
2021 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
2023 if (!n)
2024 goto fail;
2026 if (path[1])
2028 n = find_elements (client->doc, n->children, path + 1, &rc,
2029 NULL, NULL, NULL, 0, 0, NULL, 0);
2031 if (!n)
2032 goto fail;
2035 strv_free (path);
2037 if ((a = xmlGetProp (n, (xmlChar *) req[0])) == NULL)
2038 return GPG_ERR_NOT_FOUND;
2040 pthread_cleanup_push (xmlFree, a);
2042 if (*a)
2043 rc = xfer_data (ctx, (char *) a, xmlStrlen (a));
2044 else
2045 rc = GPG_ERR_NO_DATA;
2047 pthread_cleanup_pop (1);
2048 return rc;
2050 fail:
2051 strv_free (path);
2052 return rc;
2056 * req[0] - attribute
2057 * req[1] - element path
2058 * req[2] - value
2060 static gpg_error_t
2061 attribute_set (struct client_s *client, char **req)
2063 char **path = NULL;
2064 gpg_error_t rc;
2065 xmlNodePtr n;
2067 if (!req || !req[0] || !req[1])
2068 return GPG_ERR_SYNTAX;
2071 * Reserved attribute names.
2073 if (!strcmp (req[0], "_name"))
2074 return GPG_ERR_INV_ATTR;
2075 else if (!strcmp (req[0], "target"))
2076 return target_attribute (client, req + 1);
2078 if ((path = str_split (req[1], "\t", 0)) == NULL)
2081 * The first argument may be only a root element.
2083 if ((path = str_split (req[1], " ", 0)) == NULL)
2084 return GPG_ERR_SYNTAX;
2087 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
2089 if (!n)
2090 goto fail;
2092 if (path[1])
2094 n = find_elements (client->doc, n->children, path + 1, &rc,
2095 NULL, NULL, NULL, 0, 0, NULL, 0);
2097 if (!n)
2098 goto fail;
2101 rc = add_attribute (n, req[0], req[2]);
2103 fail:
2104 strv_free (path);
2105 return rc;
2109 * req[0] - command
2110 * req[1] - attribute name or element path if command is LIST
2111 * req[2] - element path
2112 * req[2] - element path or value
2115 static gpg_error_t
2116 do_attr (assuan_context_t ctx, char *line)
2118 struct client_s *client = assuan_get_pointer (ctx);
2119 gpg_error_t rc = 0;
2120 char **req;
2122 req = str_split (line, " ", 4);
2123 if (!req || !req[0] || !req[1])
2125 strv_free (req);
2126 return GPG_ERR_SYNTAX;
2129 pthread_cleanup_push (req_cleanup, req);
2131 if (strcasecmp (req[0], "SET") == 0)
2132 rc = attribute_set (client, req + 1);
2133 else if (strcasecmp (req[0], "GET") == 0)
2134 rc = attribute_get (ctx, req + 1);
2135 else if (strcasecmp (req[0], "DELETE") == 0)
2136 rc = attribute_delete (client, req + 1);
2137 else if (strcasecmp (req[0], "LIST") == 0)
2138 rc = attribute_list (ctx, req + 1);
2139 else
2140 rc = GPG_ERR_SYNTAX;
2142 pthread_cleanup_pop (1);
2143 return rc;
2146 static gpg_error_t
2147 attr_command (assuan_context_t ctx, char *line)
2149 struct client_s *client = assuan_get_pointer (ctx);
2150 gpg_error_t rc;
2151 struct argv_s *args[] = {
2152 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2153 NULL
2156 rc = parse_options (&line, args, client);
2157 if (rc)
2158 return send_error (ctx, rc);
2160 if (client->opts & OPT_INQUIRE)
2162 unsigned char *result;
2163 size_t len;
2165 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2166 if (rc)
2167 return send_error (ctx, rc);
2169 line = (char *) result;
2172 rc = do_attr (ctx, line);
2174 if (client->opts & OPT_INQUIRE)
2175 xfree (line);
2177 return send_error (ctx, rc);
2180 static gpg_error_t
2181 parse_iscached_opt_lock (void *data, void *value)
2183 struct client_s *client = data;
2185 (void) value;
2186 client->opts |= OPT_LOCK;
2187 return 0;
2190 static gpg_error_t
2191 iscached_command (assuan_context_t ctx, char *line)
2193 struct client_s *client = assuan_get_pointer (ctx);
2194 gpg_error_t rc;
2195 unsigned char md5file[16];
2196 struct argv_s *args[] = {
2197 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_iscached_opt_lock},
2198 NULL
2201 if (!line || !*line)
2202 return send_error (ctx, GPG_ERR_SYNTAX);
2204 rc = parse_options (&line, args, client);
2205 if (rc)
2206 return send_error (ctx, rc);
2207 else if (!valid_filename (line))
2208 return send_error (ctx, GPG_ERR_INV_VALUE);
2210 rc = cache_iscached (line, NULL);
2211 if (client->opts & OPT_LOCK
2212 && (!rc || gpg_err_code (rc) == GPG_ERR_NO_DATA))
2214 gpg_error_t trc = rc;
2215 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2216 if (memcmp (md5file, client->md5file, 16))
2217 cleanup_client (client);
2219 memcpy (client->md5file, md5file, 16);
2220 rc = do_lock (client, 1);
2221 if (!rc)
2222 rc = trc;
2225 return send_error (ctx, rc);
2228 static gpg_error_t
2229 clearcache_command (assuan_context_t ctx, char *line)
2231 gpg_error_t rc = 0, all_rc = 0;
2232 unsigned char md5file[16];
2233 int i;
2234 int t;
2235 int all = 0;
2236 struct client_thread_s *once = NULL;
2238 cache_lock ();
2239 MUTEX_LOCK (&cn_mutex);
2240 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
2242 if (!line || !*line)
2243 all = 1;
2245 t = slist_length (cn_thread_list);
2247 for (i = 0; i < t; i++)
2249 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2251 if (!thd->cl)
2252 continue;
2254 /* Lock each connected clients' file mutex to prevent any other client
2255 * from accessing the cache entry (the file mutex is locked upon
2256 * command startup). The cache for the entry is not cleared if the
2257 * file mutex is locked by another client to prevent this function
2258 * from blocking.
2260 if (all)
2262 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0, -1);
2263 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2265 if (pthread_equal (pthread_self (), thd->tid))
2266 rc = 0;
2267 else
2269 if (!thd->cl->filename ||
2270 cache_iscached (thd->cl->filename,
2271 NULL) == GPG_ERR_NO_DATA)
2273 rc = 0;
2274 continue;
2277 cache_defer_clear (thd->cl->md5file);
2280 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
2282 rc = 0;
2283 continue;
2286 if (!rc)
2288 rc = cache_clear (thd->cl->md5file);
2289 if (rc)
2290 all_rc = rc;
2292 cache_unlock_mutex (thd->cl->md5file, 0);
2294 else
2295 all_rc = rc;
2297 rc = 0;
2299 /* A single data filename was specified. Lock only this data file
2300 * mutex and free the cache entry. */
2301 else
2303 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2305 if (!memcmp (thd->cl->md5file, md5file, sizeof (md5file)))
2307 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0,
2308 -1);
2309 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2311 if (pthread_equal (pthread_self (), thd->tid))
2312 rc = 0;
2315 if (!rc)
2317 once = thd;
2318 rc = cache_clear (thd->cl->md5file);
2319 cache_unlock_mutex (thd->cl->md5file, 0);
2321 else
2323 cache_defer_clear (thd->cl->md5file);
2326 break;
2331 /* Only connected clients' cache entries have been cleared. Now clear any
2332 * remaining cache entries without clients but only if there wasn't an
2333 * error from above since this would defeat the locking check of the
2334 * remaining entries. */
2335 if (!all_rc && all)
2337 cache_clear (NULL);
2340 /* No clients are using the specified file. */
2341 else if (!all_rc && !rc && !once)
2343 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2344 rc = cache_clear (md5file);
2347 /* Release the connection mutex. */
2348 pthread_cleanup_pop (1);
2349 cache_unlock ();
2351 if (!rc)
2352 send_status_all (STATUS_CACHE, NULL);
2354 /* One or more files were locked while clearing all cache entries. */
2355 if (all_rc)
2356 rc = all_rc;
2358 return send_error (ctx, rc);
2361 static gpg_error_t
2362 cachetimeout_command (assuan_context_t ctx, char *line)
2364 unsigned char md5file[16];
2365 int timeout;
2366 char **req = str_split (line, " ", 0);
2367 char *p;
2368 gpg_error_t rc = 0;
2370 if (!req || !*req || !req[1])
2372 strv_free (req);
2373 return send_error (ctx, GPG_ERR_SYNTAX);
2376 errno = 0;
2377 timeout = (int) strtol (req[1], &p, 10);
2378 if (errno != 0 || *p || timeout < -1)
2380 strv_free (req);
2381 return send_error (ctx, GPG_ERR_SYNTAX);
2384 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, req[0], strlen (req[0]));
2385 rc = cache_set_timeout (md5file, timeout);
2386 if (!rc || gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
2388 rc = 0;
2389 MUTEX_LOCK (&rcfile_mutex);
2390 config_set_int_param (&global_config, req[0], "cache_timeout", req[1]);
2391 MUTEX_UNLOCK (&rcfile_mutex);
2394 strv_free (req);
2395 return send_error (ctx, rc);
2398 static gpg_error_t
2399 dump_command (assuan_context_t ctx, char *line)
2401 xmlChar *xml;
2402 int len;
2403 struct client_s *client = assuan_get_pointer (ctx);
2404 gpg_error_t rc;
2406 if (disable_list_and_dump == 1)
2407 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2409 xmlDocDumpFormatMemory (client->doc, &xml, &len, 1);
2411 if (!xml)
2413 log_write ("%s(%i): %s", __FILE__, __LINE__,
2414 pwmd_strerror (GPG_ERR_ENOMEM));
2415 return send_error (ctx, GPG_ERR_ENOMEM);
2418 pthread_cleanup_push (xmlFree, xml);
2419 rc = xfer_data (ctx, (char *) xml, len);
2420 pthread_cleanup_pop (1);
2421 return send_error (ctx, rc);
2424 static gpg_error_t
2425 getconfig_command (assuan_context_t ctx, char *line)
2427 struct client_s *client = assuan_get_pointer (ctx);
2428 gpg_error_t rc = 0;
2429 char filename[255] = { 0 }, param[747] = { 0 };
2430 char *p, *tmp = NULL, *fp = client->filename, *paramp = line;
2432 if (!line || !*line)
2433 return send_error (ctx, GPG_ERR_SYNTAX);
2435 if (strchr (line, ' '))
2437 sscanf (line, " %254[^ ] %746c", filename, param);
2438 paramp = param;
2439 fp = filename;
2442 if (fp && !valid_filename (fp))
2443 return send_error (ctx, GPG_ERR_INV_VALUE);
2445 paramp = str_down (paramp);
2446 if (!strcmp (paramp, "cipher") && fp)
2448 struct crypto_s *crypto = NULL;
2450 rc = init_client_crypto (&crypto);
2451 if (!rc)
2453 rc = read_data_header (fp, &crypto->hdr, NULL, NULL);
2454 if (!rc)
2456 const char *t =
2457 gcry_cipher_algo_name (cipher_to_gcrypt (crypto->hdr.flags));
2458 if (t)
2460 tmp = str_dup (t);
2461 if (tmp)
2462 str_down (tmp);
2467 UPDATE_AGENT_CTX (client, crypto);
2468 cleanup_crypto (&crypto);
2469 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
2470 return send_error (ctx, rc);
2472 if (!rc && tmp)
2473 goto done;
2475 else if (!strcmp (paramp, "cipher_iterations") && fp)
2477 struct crypto_s *crypto = NULL;
2479 rc = init_client_crypto (&crypto);
2480 if (!rc)
2482 rc = read_data_header (fp, &crypto->hdr, NULL, NULL);
2483 if (!rc)
2485 tmp = str_asprintf ("%llu",
2486 (unsigned long long) crypto->hdr.
2487 iterations);
2488 if (!tmp)
2489 rc = GPG_ERR_ENOMEM;
2493 UPDATE_AGENT_CTX (client, crypto);
2494 cleanup_crypto (&crypto);
2495 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
2496 return send_error (ctx, rc);
2498 if (!rc && tmp)
2499 goto done;
2501 else if (!strcmp (paramp, "passphrase"))
2502 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2504 p = config_get_value (fp ? fp : "global", paramp);
2505 if (!p)
2506 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2508 tmp = expand_homedir (p);
2509 xfree (p);
2510 if (!tmp)
2512 log_write ("%s(%i): %s", __FILE__, __LINE__,
2513 pwmd_strerror (GPG_ERR_ENOMEM));
2514 return send_error (ctx, GPG_ERR_ENOMEM);
2517 done:
2518 p = tmp;
2519 pthread_cleanup_push (xfree, p);
2520 rc = xfer_data (ctx, p, strlen (p));
2521 pthread_cleanup_pop (1);
2522 return send_error (ctx, rc);
2525 struct xpath_s
2527 xmlXPathContextPtr xp;
2528 xmlXPathObjectPtr result;
2529 xmlBufferPtr buf;
2530 char **req;
2533 static void
2534 xpath_command_cleanup (void *arg)
2536 struct xpath_s *xpath = arg;
2538 if (!xpath)
2539 return;
2541 req_cleanup (xpath->req);
2543 if (xpath->buf)
2544 xmlBufferFree (xpath->buf);
2546 if (xpath->result)
2547 xmlXPathFreeObject (xpath->result);
2549 if (xpath->xp)
2550 xmlXPathFreeContext (xpath->xp);
2553 static gpg_error_t
2554 do_xpath (assuan_context_t ctx, char *line)
2556 gpg_error_t rc;
2557 struct client_s *client = assuan_get_pointer (ctx);
2558 struct xpath_s _x = { 0 };
2559 struct xpath_s *xpath = &_x;
2561 if ((xpath->req = str_split (line, "\t", 2)) == NULL)
2563 if (strv_printf (&xpath->req, "%s", line) == 0)
2564 return GPG_ERR_ENOMEM;
2567 xpath->xp = xmlXPathNewContext (client->doc);
2568 if (!xpath->xp)
2570 rc = GPG_ERR_BAD_DATA;
2571 goto fail;
2574 xpath->result =
2575 xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2576 if (!xpath->result)
2578 rc = GPG_ERR_BAD_DATA;
2579 goto fail;
2582 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2584 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2585 goto fail;
2588 rc = recurse_xpath_nodeset (client->doc, xpath->result->nodesetval,
2589 (xmlChar *) xpath->req[1], &xpath->buf, 0,
2590 NULL);
2591 if (rc)
2592 goto fail;
2593 else if (!xpath->req[1] && !xmlBufferLength (xpath->buf))
2595 rc = GPG_ERR_NO_DATA;
2596 goto fail;
2598 else if (xpath->req[1])
2600 rc = 0;
2601 goto fail;
2604 pthread_cleanup_push (xpath_command_cleanup, &xpath);
2605 rc = xfer_data (ctx, (char *) xmlBufferContent (xpath->buf),
2606 xmlBufferLength (xpath->buf));
2607 pthread_cleanup_pop (0);
2608 fail:
2609 xpath_command_cleanup (xpath);
2610 return rc;
2613 static gpg_error_t
2614 xpath_command (assuan_context_t ctx, char *line)
2616 struct client_s *client = assuan_get_pointer (ctx);
2617 gpg_error_t rc;
2618 struct argv_s *args[] = {
2619 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2620 NULL
2623 if (disable_list_and_dump == 1)
2624 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2626 rc = parse_options (&line, args, client);
2627 if (rc)
2628 return send_error (ctx, rc);
2630 if (client->opts & OPT_INQUIRE)
2632 unsigned char *result;
2633 size_t len;
2635 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2636 if (rc)
2637 return send_error (ctx, rc);
2639 line = (char *) result;
2642 if (!line || !*line)
2643 rc = GPG_ERR_SYNTAX;
2645 if (!rc)
2646 rc = do_xpath (ctx, line);
2648 if (client->opts & OPT_INQUIRE)
2649 xfree (line);
2651 return send_error (ctx, rc);
2654 static gpg_error_t
2655 do_xpathattr (assuan_context_t ctx, char *line)
2657 struct client_s *client = assuan_get_pointer (ctx);
2658 gpg_error_t rc;
2659 char **req = NULL;
2660 int cmd = 0; //SET
2661 struct xpath_s _x = { 0 };
2662 struct xpath_s *xpath = &_x;
2664 if ((req = str_split (line, " ", 3)) == NULL)
2665 return GPG_ERR_ENOMEM;
2667 if (!req[0])
2669 rc = GPG_ERR_SYNTAX;
2670 goto fail;
2673 if (!strcasecmp (req[0], "SET"))
2674 cmd = 0;
2675 else if (!strcasecmp (req[0], "DELETE"))
2676 cmd = 1;
2677 else
2679 rc = GPG_ERR_SYNTAX;
2680 goto fail;
2683 if (!req[1] || !req[2])
2685 rc = GPG_ERR_SYNTAX;
2686 goto fail;
2689 if ((xpath->req = str_split (req[2], "\t", 3)) == NULL)
2691 rc = GPG_ERR_ENOMEM;
2692 goto fail;
2695 if (!xpath->req[0] || (!xpath->req[1] && !cmd) || (xpath->req[1] && cmd))
2697 rc = GPG_ERR_SYNTAX;
2698 goto fail;
2701 xpath->xp = xmlXPathNewContext (client->doc);
2702 if (!xpath->xp)
2704 rc = GPG_ERR_BAD_DATA;
2705 goto fail;
2708 xpath->result = xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2709 if (!xpath->result)
2711 rc = GPG_ERR_BAD_DATA;
2712 goto fail;
2715 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2717 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2718 goto fail;
2721 rc = recurse_xpath_nodeset (client->doc, xpath->result->nodesetval,
2722 (xmlChar *) xpath->req[1], &xpath->buf, cmd,
2723 (xmlChar *) req[1]);
2725 fail:
2726 xpath_command_cleanup (xpath);
2727 strv_free (req);
2728 return rc;
2731 /* XPATHATTR SET|DELETE <name> <expression>[<TAB>[value]] */
2732 static gpg_error_t
2733 xpathattr_command (assuan_context_t ctx, char *line)
2735 struct client_s *client = assuan_get_pointer (ctx);
2736 gpg_error_t rc;
2737 struct argv_s *args[] = {
2738 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2739 NULL
2742 if (disable_list_and_dump == 1)
2743 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2745 rc = parse_options (&line, args, client);
2746 if (rc)
2747 return send_error (ctx, rc);
2749 if (client->opts & OPT_INQUIRE)
2751 unsigned char *result;
2752 size_t len;
2754 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2755 if (rc)
2756 return send_error (ctx, rc);
2758 line = (char *) result;
2761 if (!line || !*line)
2762 rc = GPG_ERR_SYNTAX;
2764 if (!rc)
2765 rc = do_xpathattr (ctx, line);
2767 if (client->opts & OPT_INQUIRE)
2768 xfree (line);
2770 return send_error (ctx, rc);
2773 static gpg_error_t
2774 do_import (struct client_s *client, const char *root_element,
2775 unsigned char *content)
2777 char **dst_path = NULL;
2778 xmlDocPtr doc = NULL;
2779 xmlNodePtr n, root, copy;
2780 gpg_error_t rc;
2782 if (!content || !*content)
2784 xfree (content);
2785 return GPG_ERR_SYNTAX;
2788 if (root_element)
2789 dst_path = str_split (root_element, "\t", 0);
2791 if (dst_path && !valid_element_path (dst_path, 0))
2793 if (dst_path)
2794 strv_free (dst_path);
2796 return GPG_ERR_INV_VALUE;
2799 struct string_s *str = string_new_content ((char *)content);
2800 str = string_prepend (str, "<pwmd>");
2801 str = string_append (str, "</pwmd>");
2802 doc = xmlReadDoc ((xmlChar *) str->str, NULL, "UTF-8", XML_PARSE_NOBLANKS);
2803 string_free (str, 1);
2804 if (!doc)
2806 rc = GPG_ERR_BAD_DATA;
2807 goto fail;
2810 root = xmlDocGetRootElement (doc);
2811 xmlNodePtr root_orig = root->children;
2812 root = root->children;
2813 rc = validate_import (root);
2814 if (rc)
2815 goto fail;
2819 again:
2820 if (dst_path)
2822 char **path = strv_dup (dst_path);
2823 if (!path)
2825 log_write ("%s(%i): %s", __FILE__, __LINE__,
2826 pwmd_strerror (GPG_ERR_ENOMEM));
2827 rc = GPG_ERR_ENOMEM;
2828 goto fail;
2831 xmlChar *a = xmlGetProp (root, (xmlChar *) "_name");
2832 if (!a)
2834 strv_free (path);
2835 rc = GPG_ERR_ENOMEM;
2836 goto fail;
2839 if (strv_printf (&path, "%s", (char *) a) == 0)
2841 xmlFree (a);
2842 rc = GPG_ERR_ENOMEM;
2843 goto fail;
2846 xmlFree (a);
2847 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
2848 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2850 strv_free (path);
2851 goto fail;
2854 if (!rc)
2856 n = find_elements (client->doc, n->children, path + 1, &rc,
2857 NULL, NULL, NULL, 0, 0, NULL, 1);
2858 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2860 strv_free (path);
2861 goto fail;
2863 else if (!rc)
2865 xmlUnlinkNode (n);
2866 xmlFreeNode (n);
2867 strv_free (path);
2868 path = NULL;
2869 goto again;
2873 if (rc == GPG_ERR_ELEMENT_NOT_FOUND)
2875 n = create_element_path (client, &path, &rc, NULL);
2876 if (rc)
2877 goto fail;
2880 if (root->children)
2882 copy = xmlCopyNodeList (root->children);
2883 n = xmlAddChildList (n, copy);
2884 if (!n)
2885 rc = GPG_ERR_ENOMEM;
2888 strv_free (path);
2890 else
2892 char **path = NULL;
2894 /* Check if the content root element can create a DTD root element. */
2895 if (!xmlStrEqual ((xmlChar *) "element", root->name))
2897 rc = GPG_ERR_SYNTAX;
2898 goto fail;
2901 xmlChar *a;
2903 if ((a = xmlGetProp (root, (xmlChar *) "_name")) == NULL)
2905 rc = GPG_ERR_SYNTAX;
2906 goto fail;
2909 char *tmp = str_dup ((char *) a);
2910 xmlFree (a);
2911 int literal = is_literal_element (&tmp);
2913 if (!valid_xml_element ((xmlChar *) tmp) || literal)
2915 xfree (tmp);
2916 rc = GPG_ERR_INV_VALUE;
2917 goto fail;
2920 if (strv_printf (&path, "%s", tmp) == 0)
2922 xfree (tmp);
2923 rc = GPG_ERR_ENOMEM;
2924 goto fail;
2927 xfree (tmp);
2928 n = find_root_element (client->doc, &path, &rc, NULL, 0, 1);
2929 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2931 rc = GPG_ERR_BAD_DATA;
2932 goto fail;
2935 /* Overwriting the existing tree. */
2936 if (!rc)
2938 xmlUnlinkNode (n);
2939 xmlFreeNodeList (n);
2942 rc = 0;
2943 xmlSetProp (root, (xmlChar *) "_name", (xmlChar *) path[0]);
2944 n = xmlCopyNode (root, 1);
2945 n = xmlAddChildList (xmlDocGetRootElement (client->doc), n);
2946 strv_free (path);
2949 if (n && !rc)
2950 rc = update_element_mtime (n->parent);
2952 for (root = root_orig->next; root; root = root->next)
2954 if (root->type == XML_ELEMENT_NODE)
2955 break;
2958 root_orig = root;
2960 while (root);
2962 fail:
2963 if (doc)
2964 xmlFreeDoc (doc);
2966 if (dst_path)
2967 strv_free (dst_path);
2969 return rc;
2972 static gpg_error_t
2973 parse_import_opt_root (void *data, void *value)
2975 struct client_s *client = data;
2977 client->import_root = str_dup (value);
2978 return client->import_root ? 0 : GPG_ERR_ENOMEM;
2981 static gpg_error_t
2982 import_command (assuan_context_t ctx, char *line)
2984 gpg_error_t rc;
2985 struct client_s *client = assuan_get_pointer (ctx);
2986 unsigned char *result;
2987 size_t len;
2988 struct argv_s *args[] = {
2989 &(struct argv_s) {"root", OPTION_TYPE_ARG, parse_import_opt_root},
2990 NULL
2993 xfree (client->import_root);
2994 client->import_root = NULL;
2995 rc = parse_options (&line, args, client);
2996 if (rc)
2997 return send_error (ctx, rc);
2999 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3000 if (rc)
3001 return send_error (ctx, rc);
3003 rc = do_import (client, client->import_root, result);
3004 xfree (client->import_root);
3005 client->import_root = NULL;
3006 return send_error (ctx, rc);
3009 static gpg_error_t
3010 do_lock (struct client_s *client, int add)
3012 gpg_error_t rc = lock_file_mutex (client, add);
3014 if (!rc)
3015 client->flags |= FLAG_LOCK_CMD;
3017 return rc;
3020 static gpg_error_t
3021 lock_command (assuan_context_t ctx, char *line)
3023 struct client_s *client = assuan_get_pointer (ctx);
3024 gpg_error_t rc = do_lock (client, 0);
3026 return send_error (ctx, rc);
3029 static gpg_error_t
3030 unlock_command (assuan_context_t ctx, char *line)
3032 struct client_s *client = assuan_get_pointer (ctx);
3033 gpg_error_t rc;
3035 rc = unlock_file_mutex (client, 0);
3036 return send_error (ctx, rc);
3039 static gpg_error_t
3040 option_command (assuan_context_t ctx, char *line)
3042 struct client_s *client = assuan_get_pointer (ctx);
3043 gpg_error_t rc = 0;
3044 struct pinentry_option_s *pin_opts = &client->pinentry_opts;
3045 #ifdef WITH_AGENT
3046 struct agent_s *agent = client->crypto->agent;
3047 #endif
3048 char namebuf[255] = { 0 };
3049 char *name = namebuf;
3050 char *value = NULL, *p;
3052 p = strchr (line, '=');
3053 if (!p)
3054 strncpy (namebuf, line, sizeof(namebuf));
3055 else
3057 strncpy (namebuf, line, strlen (line)-strlen (p));
3058 value = p+1;
3061 log_write1 ("OPTION name='%s' value='%s'", name, value);
3063 if (strcasecmp (name, (char *) "log_level") == 0)
3065 long l = 0;
3067 if (value)
3069 l = strtol (value, NULL, 10);
3071 if (l < 0 || l > 2)
3072 return send_error (ctx, GPG_ERR_INV_VALUE);
3075 MUTEX_LOCK (&rcfile_mutex);
3076 config_set_int_param (&global_config, "global", "log_level", value);
3077 MUTEX_UNLOCK (&rcfile_mutex);
3078 goto done;
3080 else if (strcasecmp (name, (char *) "lock-timeout") == 0)
3082 long n = 0;
3083 char *p = NULL;
3085 if (value)
3087 n = strtol (value, &p, 10);
3088 if (p && *p)
3089 return send_error (ctx, GPG_ERR_INV_VALUE);
3092 client->lock_timeout = n;
3093 goto done;
3095 else if (strcasecmp (name, (char *) "NAME") == 0)
3097 char *tmp = pthread_getspecific (thread_name_key);
3099 if (tmp)
3100 xfree (tmp);
3102 if (!value || !*value)
3104 pthread_setspecific (thread_name_key, str_dup (""));
3105 goto done;
3108 pthread_setspecific (thread_name_key, str_dup (value));
3109 goto done;
3111 else if (strcasecmp (name, (char *) "lc-messages") == 0)
3113 xfree (pin_opts->lc_messages);
3114 pin_opts->lc_messages = NULL;
3115 if (value && *value)
3116 pin_opts->lc_messages = str_dup (value);
3117 #ifdef WITH_AGENT
3118 if (use_agent)
3119 rc = set_agent_option (client->crypto->agent, "lc-messages", value);
3120 #endif
3122 else if (strcasecmp (name, (char *) "lc-ctype") == 0)
3124 xfree (pin_opts->lc_ctype);
3125 pin_opts->lc_ctype = NULL;
3126 if (value && *value)
3127 pin_opts->lc_ctype = str_dup (value);
3128 #ifdef WITH_AGENT
3129 if (use_agent)
3130 rc = set_agent_option (client->crypto->agent, "lc-ctype", value);
3131 #endif
3133 else if (strcasecmp (name, (char *) "ttyname") == 0)
3135 xfree (pin_opts->ttyname);
3136 pin_opts->ttyname = NULL;
3137 if (value && *value)
3138 pin_opts->ttyname = str_dup (value);
3139 #ifdef WITH_AGENT
3140 if (use_agent)
3141 rc = set_agent_option (client->crypto->agent, "ttyname", value);
3142 #endif
3144 else if (strcasecmp (name, (char *) "ttytype") == 0)
3146 xfree (pin_opts->ttytype);
3147 pin_opts->ttytype = NULL;
3148 if (value && *value)
3149 pin_opts->ttytype = str_dup (value);
3150 #ifdef WITH_AGENT
3151 if (use_agent)
3152 rc = set_agent_option (client->crypto->agent, "ttytype", value);
3153 #endif
3155 else if (strcasecmp (name, (char *) "display") == 0)
3157 xfree (pin_opts->display);
3158 pin_opts->display = NULL;
3159 if (value && *value)
3160 pin_opts->display = str_dup (value);
3161 #ifdef WITH_AGENT
3162 if (use_agent)
3163 rc = set_agent_option (client->crypto->agent, "display", value);
3164 #endif
3166 else if (strcasecmp (name, (char *) "pinentry-desc") == 0)
3168 xfree (pin_opts->desc);
3169 pin_opts->desc = NULL;
3170 if (value && *value)
3171 pin_opts->desc = str_dup (value);
3173 else if (strcasecmp (name, (char *) "pinentry-title") == 0)
3175 xfree (pin_opts->title);
3176 pin_opts->title = NULL;
3177 if (value && *value)
3178 pin_opts->title = str_dup (value);
3180 else if (strcasecmp (name, (char *) "pinentry-prompt") == 0)
3182 xfree (pin_opts->prompt);
3183 pin_opts->prompt = NULL;
3184 if (value && *value)
3185 pin_opts->prompt = str_dup (value);
3188 else if (strcasecmp (name, "pinentry-timeout") == 0)
3190 char *p = NULL;
3191 int n;
3193 if (!value)
3194 goto done;
3196 n = (int) strtol (value, &p, 10);
3198 if (*p || n < 0)
3199 return send_error (ctx, GPG_ERR_INV_VALUE);
3201 pin_opts->timeout = n;
3202 MUTEX_LOCK (&rcfile_mutex);
3203 config_set_int_param (&global_config,
3204 client->filename ? client->filename : "global",
3205 "pinentry_timeout", value);
3206 MUTEX_UNLOCK (&rcfile_mutex);
3207 goto done;
3209 else if (strcasecmp (name, "disable-pinentry") == 0)
3211 char *p = NULL;
3212 int n = 1;
3214 if (value && *value)
3216 n = (int) strtol (value, &p, 10);
3217 if (*p || n < 0 || n > 1)
3218 return send_error (ctx, GPG_ERR_INV_VALUE);
3221 if (n)
3222 client->flags |= FLAG_NO_PINENTRY;
3223 else
3224 client->flags &= ~FLAG_NO_PINENTRY;
3226 else
3227 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
3229 done:
3230 #ifdef WITH_AGENT
3231 if (!rc && use_agent && agent)
3233 rc = pinentry_merge_options (&client->crypto->agent->pinentry_opts,
3234 pin_opts);
3236 #endif
3238 return send_error (ctx, rc);
3241 static gpg_error_t
3242 do_rename (assuan_context_t ctx, char *line)
3244 struct client_s *client = assuan_get_pointer (ctx);
3245 gpg_error_t rc;
3246 char **req, **src, *dst;
3247 xmlNodePtr n, ndst;
3249 req = str_split (line, " ", 0);
3251 if (!req || !req[0] || !req[1])
3253 strv_free (req);
3254 return GPG_ERR_SYNTAX;
3257 dst = req[1];
3258 is_literal_element (&dst);
3260 if (!valid_xml_element ((xmlChar *) dst))
3262 strv_free (req);
3263 return GPG_ERR_INV_VALUE;
3266 if (strchr (req[0], '\t'))
3267 src = str_split (req[0], "\t", 0);
3268 else
3269 src = str_split (req[0], " ", 0);
3271 if (!src || !*src)
3273 rc = GPG_ERR_SYNTAX;
3274 goto fail;
3277 n = find_root_element (client->doc, &src, &rc, NULL, 0, 0);
3278 if (src[1] && n)
3279 n = find_elements (client->doc, n->children, src + 1, &rc, NULL, NULL,
3280 NULL, 0, 0, NULL, 0);
3282 if (!n)
3283 goto fail;
3285 xmlChar *a = xmlGetProp (n, (xmlChar *) "_name");
3286 if (!a)
3288 rc = GPG_ERR_ENOMEM;
3289 goto fail;
3292 /* To prevent unwanted effects:
3294 * <root name="a"><b/></root>
3296 * RENAME a<TAB>b b
3298 if (xmlStrEqual (a, (xmlChar *) dst))
3300 xmlFree (a);
3301 rc = GPG_ERR_AMBIGUOUS_NAME;
3302 goto fail;
3305 xmlFree (a);
3306 char **tmp = NULL;
3307 if (src[1])
3309 char **p;
3311 for (p = src; *p; p++)
3313 if (!*(p + 1))
3314 break;
3315 strv_printf (&tmp, "%s", *p);
3319 strv_printf (&tmp, "!%s", dst);
3320 ndst = find_root_element (client->doc, &tmp, &rc, NULL, 0, 0);
3321 if (!ndst && rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3323 strv_free (tmp);
3324 goto fail;
3327 if (tmp[1] && ndst)
3328 ndst = find_elements (client->doc, ndst->children, tmp + 1, &rc, NULL,
3329 NULL, NULL, 0, 0, NULL, 0);
3331 strv_free (tmp);
3332 if (!ndst && rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3333 goto fail;
3335 rc = 0;
3337 /* Target may exist:
3339 * <root name="a"/>
3340 * <root name="b" target="a"/>
3342 * RENAME b a
3344 * Would need to do:
3345 * RENAME !b a
3347 if (ndst == n)
3349 rc = GPG_ERR_AMBIGUOUS_NAME;
3350 goto fail;
3353 if (ndst)
3355 unlink_node (ndst);
3356 xmlFreeNodeList (ndst);
3359 rc = add_attribute (n, "_name", dst);
3361 fail:
3362 strv_free (req);
3363 strv_free (src);
3364 return rc;
3367 static gpg_error_t
3368 rename_command (assuan_context_t ctx, char *line)
3370 struct client_s *client = assuan_get_pointer (ctx);
3371 gpg_error_t rc;
3372 struct argv_s *args[] = {
3373 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3374 NULL
3377 rc = parse_options (&line, args, client);
3378 if (rc)
3379 return send_error (ctx, rc);
3381 if (client->opts & OPT_INQUIRE)
3383 unsigned char *result;
3384 size_t len;
3386 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3387 if (rc)
3388 return send_error (ctx, rc);
3390 line = (char *) result;
3393 rc = do_rename (ctx, line);
3395 if (client->opts & OPT_INQUIRE)
3396 xfree (line);
3398 return send_error (ctx, rc);
3401 static gpg_error_t
3402 do_copy (assuan_context_t ctx, char *line)
3404 struct client_s *client = assuan_get_pointer (ctx);
3405 gpg_error_t rc;
3406 char **req, **src = NULL, **dst = NULL;
3407 xmlNodePtr nsrc, ndst, new = NULL;
3409 req = str_split (line, " ", 0);
3410 if (!req || !req[0] || !req[1])
3412 strv_free (req);
3413 return GPG_ERR_SYNTAX;
3416 if (strchr (req[0], '\t'))
3417 src = str_split (req[0], "\t", 0);
3418 else
3419 src = str_split (req[0], " ", 0);
3421 if (!src || !*src)
3423 rc = GPG_ERR_SYNTAX;
3424 goto fail;
3427 if (strchr (req[1], '\t'))
3428 dst = str_split (req[1], "\t", 0);
3429 else
3430 dst = str_split (req[1], " ", 0);
3432 if (!dst || !*dst)
3434 rc = GPG_ERR_SYNTAX;
3435 goto fail;
3438 if (!valid_element_path (dst, 0))
3440 rc = GPG_ERR_INV_VALUE;
3441 goto fail;
3444 nsrc = find_root_element (client->doc, &src, &rc, NULL, 0, 0);
3445 if (nsrc && src[1])
3446 nsrc = find_elements (client->doc, nsrc->children, src + 1, &rc, NULL,
3447 NULL, NULL, 0, 0, NULL, 0);
3449 if (!nsrc)
3450 goto fail;
3452 new = xmlCopyNodeList (nsrc);
3453 if (!new)
3455 rc = GPG_ERR_ENOMEM;
3456 goto fail;
3459 int create = 0;
3460 ndst = find_root_element (client->doc, &dst, &rc, NULL, 0, 0);
3461 if (ndst && dst[1])
3463 if (ndst->children)
3464 ndst = find_elements (client->doc, ndst->children, dst + 1, &rc, NULL,
3465 NULL, create_target_elements_cb, 0, 0, NULL, 0);
3466 else
3467 create = 1;
3469 else
3470 create = 1;
3472 if (!ndst && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3473 goto fail;
3474 else if (!ndst || create)
3476 ndst = create_element_path (client, &dst, &rc, NULL);
3477 if (!ndst)
3478 goto fail;
3481 /* Merge any attributes from the src node to the initial dst node. */
3482 for (xmlAttrPtr attr = new->properties; attr; attr = attr->next)
3484 if (xmlStrEqual (attr->name, (xmlChar *) "_name"))
3485 continue;
3487 xmlAttrPtr a = xmlHasProp (ndst, attr->name);
3488 if (a)
3489 xmlRemoveProp (a);
3491 xmlChar *tmp = xmlNodeGetContent (attr->children);
3492 xmlNewProp (ndst, attr->name, tmp);
3493 xmlFree (tmp);
3494 rc = add_attribute (ndst, NULL, NULL);
3497 xmlNodePtr n = ndst->children;
3498 xmlUnlinkNode (n);
3499 xmlFreeNodeList (n);
3500 ndst->children = NULL;
3502 if (new->children)
3504 n = xmlCopyNodeList (new->children);
3505 if (!n)
3507 rc = GPG_ERR_ENOMEM;
3508 goto fail;
3511 n = xmlAddChildList (ndst, n);
3512 if (!n)
3514 rc = GPG_ERR_ENOMEM;
3515 goto fail;
3518 rc = update_element_mtime (xmlDocGetRootElement (client->doc) ==
3519 ndst->parent ? ndst : ndst->parent);
3522 fail:
3523 if (new)
3525 xmlUnlinkNode (new);
3526 xmlFreeNodeList (new);
3529 if (req)
3530 strv_free (req);
3532 if (src)
3533 strv_free (src);
3535 if (dst)
3536 strv_free (dst);
3538 return rc;
3541 static gpg_error_t
3542 copy_command (assuan_context_t ctx, char *line)
3544 struct client_s *client = assuan_get_pointer (ctx);
3545 gpg_error_t rc;
3546 struct argv_s *args[] = {
3547 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3548 NULL
3551 rc = parse_options (&line, args, client);
3552 if (rc)
3553 return send_error (ctx, rc);
3555 if (client->opts & OPT_INQUIRE)
3557 unsigned char *result;
3558 size_t len;
3560 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3561 if (rc)
3562 return send_error (ctx, rc);
3564 line = (char *) result;
3567 rc = do_copy (ctx, line);
3569 if (client->opts & OPT_INQUIRE)
3570 xfree (line);
3572 return send_error (ctx, rc);
3575 static gpg_error_t
3576 do_move (assuan_context_t ctx, char *line)
3578 struct client_s *client = assuan_get_pointer (ctx);
3579 gpg_error_t rc;
3580 char **req, **src = NULL, **dst = NULL;
3581 xmlNodePtr nsrc, ndst = NULL;
3583 req = str_split (line, " ", 0);
3585 if (!req || !req[0] || !req[1])
3587 strv_free (req);
3588 return GPG_ERR_SYNTAX;
3591 if (strchr (req[0], '\t'))
3592 src = str_split (req[0], "\t", 0);
3593 else
3594 src = str_split (req[0], " ", 0);
3596 if (!src || !*src)
3598 rc = GPG_ERR_SYNTAX;
3599 goto fail;
3602 if (strchr (req[1], '\t'))
3603 dst = str_split (req[1], "\t", 0);
3604 else
3605 dst = str_split (req[1], " ", 0);
3607 nsrc = find_root_element (client->doc, &src, &rc, NULL, 0, 0);
3608 if (nsrc && src[1])
3609 nsrc = find_elements (client->doc, nsrc->children, src + 1, &rc, NULL,
3610 NULL, NULL, 0, 0, NULL, 0);
3612 if (!nsrc)
3613 goto fail;
3615 if (dst)
3617 if (!valid_element_path (dst, 0))
3619 rc = GPG_ERR_INV_VALUE;
3620 goto fail;
3623 ndst = find_root_element (client->doc, &dst, &rc, NULL, 0, 0);
3624 if (ndst && dst[1])
3625 ndst = find_elements (client->doc, ndst->children, dst + 1, &rc, NULL,
3626 NULL, NULL, 0, 0, NULL, 0);
3628 else
3629 ndst = xmlDocGetRootElement (client->doc);
3631 for (xmlNodePtr n = ndst; n; n = n->parent)
3633 if (n == nsrc)
3635 rc = GPG_ERR_CONFLICT;
3636 goto fail;
3640 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3641 goto fail;
3643 rc = 0;
3645 if (ndst)
3647 xmlChar *a = node_has_attribute (nsrc, (xmlChar *) "_name");
3648 xmlNodePtr dup = find_element (ndst->children, (char *) a, NULL);
3650 xmlFree (a);
3651 if (dup)
3653 if (dup == nsrc)
3654 goto fail;
3656 if (ndst == xmlDocGetRootElement (client->doc))
3658 xmlNodePtr n = nsrc;
3659 int match = 0;
3661 while (n->parent && n->parent != ndst)
3662 n = n->parent;
3664 xmlChar *a = node_has_attribute (n, (xmlChar *) "_name");
3665 xmlChar *b = node_has_attribute (nsrc, (xmlChar *) "_name");
3667 if (xmlStrEqual (a, b))
3669 match = 1;
3670 xmlUnlinkNode (nsrc);
3671 xmlUnlinkNode (n);
3672 xmlFreeNodeList (n);
3675 xmlFree (a);
3676 xmlFree (b);
3678 if (!match)
3680 xmlUnlinkNode (dup);
3681 xmlFreeNodeList (dup);
3684 else
3685 xmlUnlinkNode (dup);
3689 if (!ndst && dst)
3691 xmlChar *name = node_has_attribute (nsrc, (xmlChar *) "_name");
3693 if (nsrc->parent == xmlDocGetRootElement (client->doc)
3694 && !strcmp ((char *) name, *dst))
3696 xmlFree (name);
3697 rc = GPG_ERR_CONFLICT;
3698 goto fail;
3701 xmlFree (name);
3702 ndst = create_element_path (client, &dst, &rc, nsrc);
3705 if (!ndst)
3706 goto fail;
3708 update_element_mtime (nsrc->parent);
3709 xmlUnlinkNode (nsrc);
3710 ndst = xmlAddChildList (ndst, nsrc);
3712 if (!ndst)
3713 rc = GPG_ERR_ENOMEM;
3714 else
3715 update_element_mtime (ndst->parent);
3717 fail:
3718 if (req)
3719 strv_free (req);
3721 if (src)
3722 strv_free (src);
3724 if (dst)
3725 strv_free (dst);
3727 return rc;
3730 static gpg_error_t
3731 move_command (assuan_context_t ctx, char *line)
3733 struct client_s *client = assuan_get_pointer (ctx);
3734 gpg_error_t rc;
3735 struct argv_s *args[] = {
3736 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3737 NULL
3740 rc = parse_options (&line, args, client);
3741 if (rc)
3742 return send_error (ctx, rc);
3744 if (client->opts & OPT_INQUIRE)
3746 unsigned char *result;
3747 size_t len;
3749 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3750 if (rc)
3751 return send_error (ctx, rc);
3753 line = (char *) result;
3756 rc = do_move (ctx, line);
3758 if (client->opts & OPT_INQUIRE)
3759 xfree (line);
3761 return send_error (ctx, rc);
3764 static gpg_error_t
3765 ls_command (assuan_context_t ctx, char *line)
3767 gpg_error_t rc;
3768 char *tmp = str_asprintf ("%s/data", homedir);
3769 char *dir = expand_homedir (tmp);
3770 DIR *d = opendir (dir);
3772 rc = gpg_error_from_syserror ();
3773 xfree (tmp);
3775 if (!d)
3777 xfree (dir);
3778 return send_error (ctx, rc);
3781 size_t len =
3782 offsetof (struct dirent, d_name) +pathconf (dir, _PC_NAME_MAX) + 1;
3783 struct dirent *p = xmalloc (len), *cur = NULL;
3784 char *list = NULL;
3786 xfree (dir);
3787 rc = 0;
3789 while (!readdir_r (d, p, &cur) && cur)
3791 if (cur->d_name[0] == '.' && cur->d_name[1] == '\0')
3792 continue;
3793 else if (cur->d_name[0] == '.' && cur->d_name[1] == '.'
3794 && cur->d_name[2] == '\0')
3795 continue;
3797 tmp = str_asprintf ("%s%s\n", list ? list : "", cur->d_name);
3799 if (!tmp)
3801 if (list)
3802 xfree (list);
3804 rc = GPG_ERR_ENOMEM;
3805 break;
3808 xfree (list);
3809 list = tmp;
3812 closedir (d);
3813 xfree (p);
3815 if (rc)
3816 return send_error (ctx, rc);
3818 if (!list)
3819 return send_error (ctx, GPG_ERR_NO_DATA);
3821 list[strlen (list) - 1] = 0;
3822 rc = xfer_data (ctx, list, strlen (list));
3823 xfree (list);
3824 return send_error (ctx, rc);
3827 static gpg_error_t
3828 bye_notify (assuan_context_t ctx, char *line)
3830 struct client_s *cl = assuan_get_pointer (ctx);
3832 #ifdef WITH_GNUTLS
3833 if (cl->thd->remote)
3835 int rc;
3839 struct timeval tv = { 0, 50000 };
3841 rc = gnutls_bye (cl->thd->tls->ses, GNUTLS_SHUT_RDWR);
3842 if (rc == GNUTLS_E_AGAIN)
3843 select (0, NULL, NULL, NULL, &tv);
3845 while (rc == GNUTLS_E_AGAIN);
3847 #endif
3849 /* This will let assuan_process_next() return. */
3850 fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK);
3851 cl->last_rc = 0; // BYE command result
3852 return 0;
3855 static gpg_error_t
3856 reset_notify (assuan_context_t ctx, char *line)
3858 struct client_s *client = assuan_get_pointer (ctx);
3860 if (client)
3861 cleanup_client (client);
3863 return 0;
3867 * This is called before every Assuan command.
3869 static gpg_error_t
3870 command_startup (assuan_context_t ctx, const char *name)
3872 struct client_s *client = assuan_get_pointer (ctx);
3873 gpg_error_t rc;
3874 struct command_table_s *cmd = NULL;
3876 log_write1 ("command='%s'", name);
3877 client->last_rc = client->opts = 0;
3879 for (int i = 0; command_table[i]; i++)
3881 if (!strcasecmp (name, command_table[i]->name))
3883 if (command_table[i]->ignore_startup)
3884 return 0;
3885 cmd = command_table[i];
3886 break;
3890 client->last_rc = rc = gpg_error (file_modified (client, cmd));
3891 return rc;
3895 * This is called after every Assuan command.
3897 static void
3898 command_finalize (assuan_context_t ctx, gpg_error_t rc)
3900 struct client_s *client = assuan_get_pointer (ctx);
3902 if (!(client->flags & FLAG_LOCK_CMD))
3903 unlock_file_mutex (client, 0);
3905 log_write1 (_("command completed: rc=%u"), client->last_rc);
3906 client->last_rc = gpg_error (GPG_ERR_UNKNOWN_COMMAND);
3907 #ifdef WITH_GNUTLS
3908 client->thd->buffer_timeout = client->thd->last_buffer_size = 0;
3909 #endif
3912 static gpg_error_t
3913 help_command (assuan_context_t ctx, char *line)
3915 gpg_error_t rc;
3916 int i;
3918 if (!line || !*line)
3920 char *tmp;
3921 char *help = str_dup (_("Usage: HELP [<COMMAND>]\n"
3922 "For commands that take an element path as an argument, each element is "
3923 "separated with an ASCII @key{TAB} character (ASCII 0x09)."
3924 "\n" "COMMANDS:"));
3926 for (i = 0; command_table[i]; i++)
3928 if (!command_table[i]->help)
3929 continue;
3931 tmp = str_asprintf ("%s %s", help, command_table[i]->name);
3932 xfree (help);
3933 help = tmp;
3936 tmp = strip_texi_and_wrap (help);
3937 xfree (help);
3938 rc = xfer_data (ctx, tmp, strlen (tmp));
3939 xfree (tmp);
3940 return send_error (ctx, rc);
3943 for (i = 0; command_table[i]; i++)
3945 if (!strcasecmp (line, command_table[i]->name))
3947 char *help, *tmp;
3949 if (!command_table[i]->help)
3950 break;
3952 help = strip_texi_and_wrap (command_table[i]->help);
3953 tmp = str_asprintf (_("Usage: %s"), help);
3954 xfree (help);
3955 rc = xfer_data (ctx, tmp, strlen (tmp));
3956 xfree (tmp);
3957 return send_error (ctx, rc);
3961 return send_error (ctx, GPG_ERR_INV_NAME);
3964 static void
3965 new_command (const char *name, int ignore, int unlock,
3966 gpg_error_t (*handler) (assuan_context_t, char *),
3967 const char *help)
3969 int i = 0;
3971 if (command_table)
3972 for (i = 0; command_table[i]; i++);
3974 command_table =
3975 xrealloc (command_table, (i + 2) * sizeof (struct command_table_s *));
3976 command_table[i] = xcalloc (1, sizeof (struct command_table_s));
3977 command_table[i]->name = name;
3978 command_table[i]->handler = handler;
3979 command_table[i]->ignore_startup = ignore;
3980 command_table[i]->unlock = unlock;
3981 command_table[i++]->help = help;
3982 command_table[i] = NULL;
3985 void
3986 deinit_commands ()
3988 int i;
3990 for (i = 0; command_table[i]; i++)
3991 xfree (command_table[i]);
3993 xfree (command_table);
3996 static int
3997 sort_commands (const void *arg1, const void *arg2)
3999 struct command_table_s *const *a = arg1;
4000 struct command_table_s *const *b = arg2;
4002 if (!*a || !*b)
4003 return 0;
4004 else if (*a && !*b)
4005 return 1;
4006 else if (!*a && *b)
4007 return -1;
4009 return strcmp ((*a)->name, (*b)->name);
4012 static gpg_error_t
4013 passwd_command (assuan_context_t ctx, char *line)
4015 struct client_s *client = assuan_get_pointer (ctx);
4016 gpg_error_t rc;
4017 struct argv_s *args[] = {
4018 &(struct argv_s) {"reset", OPTION_TYPE_NOARG, parse_opt_reset},
4019 &(struct argv_s) {"s2k-count", OPTION_TYPE_ARG, parse_opt_s2k_count},
4020 NULL
4023 if (client->flags & FLAG_NEW)
4024 return send_error (ctx, GPG_ERR_INV_STATE);
4026 client->crypto->save.s2k_count =
4027 config_get_ulong (client->filename, "s2k_count");
4028 rc = parse_options (&line, args, client);
4029 if (rc)
4030 return send_error (ctx, rc);
4032 if (!rc && client->opts & OPT_RESET)
4034 rc = cache_clear (client->md5file);
4035 if (!rc)
4036 send_status_all (STATUS_CACHE, NULL);
4039 if (!rc)
4041 if (!IS_PKI (client->crypto))
4043 struct crypto_s *crypto;
4045 xfree (client->crypto->filename);
4046 client->crypto->filename = str_dup (client->filename);
4047 rc = change_passwd (ctx, client->filename,
4048 client->flags & FLAG_NO_PINENTRY, &crypto);
4049 if (!rc)
4051 cleanup_crypto (&client->crypto);
4052 client->crypto = crypto;
4053 update_checksum (client);
4054 cleanup_crypto_stage1 (client->crypto);
4057 #ifdef WITH_AGENT
4058 else
4060 if (client->crypto->save.s2k_count)
4061 rc = send_to_agent (client->crypto->agent, NULL, NULL,
4062 "OPTION s2k-count=%lu",
4063 client->crypto->save.s2k_count);
4065 if (!rc)
4066 rc = agent_passwd (client->crypto);
4068 #endif
4071 return send_error (ctx, rc);
4074 static gpg_error_t
4075 parse_keygrip_opt_sign (void *data, void *value)
4077 struct client_s *client = data;
4079 (void) value;
4080 client->opts |= OPT_SIGN;
4081 return 0;
4084 static gpg_error_t
4085 keygrip_command (assuan_context_t ctx, char *line)
4087 struct client_s *client = assuan_get_pointer (ctx);
4088 gpg_error_t rc;
4089 struct crypto_s *crypto = NULL;
4090 struct argv_s *args[] = {
4091 &(struct argv_s) {"sign", OPTION_TYPE_NOARG, parse_keygrip_opt_sign},
4092 NULL
4095 if (!line || !*line)
4096 return send_error (ctx, GPG_ERR_SYNTAX);
4098 rc = parse_options (&line, args, client);
4099 if (rc)
4100 return send_error (ctx, rc);
4102 if (!valid_filename (line))
4103 return send_error (ctx, GPG_ERR_INV_VALUE);
4105 rc = init_client_crypto (&crypto);
4106 if (rc)
4107 return send_error (ctx, rc);
4109 rc = read_data_file (line, crypto);
4110 if (!rc)
4112 char *hexgrip = NULL;
4114 if (!IS_PKI (crypto))
4116 cleanup_crypto (&crypto);
4117 return send_error (ctx, GPG_ERR_NOT_SUPPORTED);
4120 if (client->opts & OPT_SIGN)
4122 if (valid_keygrip (crypto->sign_grip, sizeof (crypto->sign_grip)))
4123 hexgrip = bin2hex (crypto->sign_grip, sizeof (crypto->sign_grip));
4126 if (!hexgrip)
4127 hexgrip = bin2hex (crypto->grip, sizeof (crypto->grip));
4129 if (!hexgrip)
4130 rc = GPG_ERR_ENOMEM;
4131 else
4132 rc = xfer_data (ctx, hexgrip, strlen (hexgrip));
4134 xfree (hexgrip);
4137 UPDATE_AGENT_CTX (client, crypto);
4138 cleanup_crypto (&crypto);
4139 return send_error (ctx, rc);
4142 static gpg_error_t
4143 parse_opt_data (void *data, void *value)
4145 struct client_s *client = data;
4147 (void) value;
4148 client->opts |= OPT_DATA;
4149 return 0;
4152 static gpg_error_t
4153 getinfo_command (assuan_context_t ctx, char *line)
4155 struct client_s *client = assuan_get_pointer (ctx);
4156 gpg_error_t rc;
4157 char buf[ASSUAN_LINELENGTH];
4158 struct argv_s *args[] = {
4159 &(struct argv_s) {"data", OPTION_TYPE_NOARG, parse_opt_data},
4160 NULL
4163 rc = parse_options (&line, args, client);
4164 if (rc)
4165 return send_error (ctx, rc);
4167 if (!strcasecmp (line, "clients"))
4169 if (client->opts & OPT_DATA)
4171 MUTEX_LOCK (&cn_mutex);
4172 snprintf (buf, sizeof (buf), "%i", slist_length (cn_thread_list));
4173 MUTEX_UNLOCK (&cn_mutex);
4174 rc = xfer_data (ctx, buf, strlen (buf));
4176 else
4177 rc = send_status (ctx, STATUS_CLIENTS, NULL);
4179 else if (!strcasecmp (line, "cache"))
4181 if (client->opts & OPT_DATA)
4183 snprintf (buf, sizeof (buf), "%u", cache_file_count ());
4184 rc = xfer_data (ctx, buf, strlen (buf));
4186 else
4187 rc = send_status (ctx, STATUS_CACHE, NULL);
4189 else if (!strcasecmp (line, "pid"))
4191 char buf[32];
4192 pid_t pid = getpid ();
4194 snprintf (buf, sizeof (buf), "%i", pid);
4195 rc = xfer_data (ctx, buf, strlen (buf));
4197 else if (!strcasecmp (line, "version"))
4199 char *buf = str_asprintf ("0x%06x %s%s", VERSION_HEX,
4200 #ifdef WITH_LIBACL
4201 "ACL "
4202 #endif
4203 #ifdef WITH_GNUTLS
4204 "GNUTLS "
4205 #endif
4206 #ifdef WITH_QUALITY
4207 "QUALITY "
4208 #endif
4209 "", use_agent ? "AGENT" : "");
4210 rc = xfer_data (ctx, buf, strlen (buf));
4211 xfree (buf);
4213 else if (!strcasecmp (line, "last_error"))
4215 if (client->last_error)
4216 rc = xfer_data (ctx, client->last_error, strlen (client->last_error));
4217 else
4218 rc = GPG_ERR_NO_DATA;
4220 else
4221 rc = gpg_error (GPG_ERR_SYNTAX);
4223 return send_error (ctx, rc);
4226 #ifdef WITH_AGENT
4227 static gpg_error_t
4228 send_data_cb (void *user, const void *buf, size_t len)
4230 assuan_context_t ctx = user;
4232 return assuan_send_data (ctx, buf, len);
4235 static gpg_error_t
4236 send_status_cb (void *user, const char *line)
4238 assuan_context_t ctx = user;
4239 char keyword[200], *k;
4240 const char *p;
4242 for (p = line, k = keyword; *p; p++)
4244 if (isspace (*p))
4245 break;
4247 *k++ = *p;
4250 *k = 0;
4251 if (*p == '#')
4252 p++;
4254 while (isspace (*p))
4255 p++;
4257 return assuan_write_status (ctx, keyword, *p ? p : NULL);
4259 #endif
4261 static gpg_error_t
4262 agent_command (assuan_context_t ctx, char *line)
4264 gpg_error_t rc = 0;
4266 if (!use_agent)
4267 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
4269 #ifdef WITH_AGENT
4270 struct client_s *client = assuan_get_pointer (ctx);
4272 if (!line || !*line)
4273 return send_error (ctx, GPG_ERR_SYNTAX);
4275 assuan_set_flag (client->crypto->agent->ctx, ASSUAN_CONVEY_COMMENTS, 1);
4276 rc = assuan_transact (client->crypto->agent->ctx, line, send_data_cb,
4277 client->ctx, agent_loopback_cb, client->crypto,
4278 send_status_cb, client->ctx);
4279 if (gpg_err_code (rc) == GPG_ERR_ASS_CANCELED)
4281 char *line;
4282 size_t len;
4284 rc = assuan_write_line (client->crypto->agent->ctx, "CAN");
4285 if (!rc)
4287 rc = assuan_read_line (client->crypto->agent->ctx, &line, &len);
4288 if (!rc)
4289 rc = gpg_error (GPG_ERR_ASS_CANCELED);
4293 assuan_set_flag (client->crypto->agent->ctx, ASSUAN_CONVEY_COMMENTS, 0);
4294 #endif
4295 return send_error (ctx, rc);
4298 void
4299 init_commands ()
4301 /* !BEGIN-HELP-TEXT!
4303 * This comment is used as a marker to generate the offline documentation
4304 * found in doc/pwmd.info. The indentation needs to be kept for the awk
4305 * script to determine where commands begin and end.
4307 new_command("HELP", 1, 1, help_command, _(
4308 "HELP [<COMMAND>]\n"
4309 "Show available commands or command specific help text."
4312 new_command("AGENT", 1, 1, agent_command, _(
4313 "AGENT <command>\n"
4314 "Send a @command{gpg-agent} protocol @var{command} directly to the "
4315 "@command{gpg-agent}."
4318 new_command("GETINFO", 1, 1, getinfo_command, _(
4319 "GETINFO [--data] CACHE | CLIENTS | PID | LAST_ERROR | VERSION\n"
4320 "Get server and other information: @var{cache} returns the number of cached "
4321 "documents via a status message. @var{clients} returns the number of "
4322 "connected clients via a status message. @var{pid} returns the process ID "
4323 "number of the server via a data response. @var{VERSION} returns the server "
4324 "version number and compile-time features with a data response with each "
4325 "being space delimited. @var{LAST_ERROR} returns a detailed description of "
4326 "the last failed command when available. @xref{Status Messages}. "
4327 "\n"
4328 "When the @option{--data} option is specified then the result will be sent "
4329 "via a data response rather than a status message."
4332 new_command("PASSWD", 0, 0, passwd_command, _(
4333 "PASSWD [--reset] [--s2k-count=N]\n"
4334 "Changes the passphrase of the secret key required to open the current "
4335 "file or the passphrase of a symmetrically encrypted data file. When the "
4336 "@option{--reset} option is passed then the cache entry for the current "
4337 "file will be reset and the passphrase, if any, will be required during the "
4338 "next @code{OPEN}. @xref{OPEN}."
4339 "\n"
4340 "The @option{--s2k-count} option sets number of hash iterations for a "
4341 "passphrase and must be either @code{0} to use the calibrated count of the "
4342 "machine (the default), or a value greater than or equal to @code{65536}. "
4343 "@xref{SAVE}. This option has no effect for symmetrically encrypted data "
4344 "files."
4347 new_command("KEYGRIP", 1, 1, keygrip_command, _(
4348 "KEYGRIP [--sign] <filename>\n"
4349 "Returns the hex encoded keygrip of the specified @var{filename} with a "
4350 "data response."
4351 "\n"
4352 "When the @option{--sign} option is specified then the key used for signing "
4353 "of the specified @var{filename} will be returned."
4354 "\n"
4355 "For symmetrically encrypted data files this command returns the error "
4356 "GPG_ERR_NOT_SUPPORTED."
4359 new_command("OPEN", 1, 1, open_command, _(
4360 "OPEN [--lock] <filename> [<passphrase>]\n"
4361 "Opens @var{filename} using @var{passphrase}. When the filename is not "
4362 "found on the file-system then a new document will be created. If the file "
4363 "is found, it is looked for in the file cache. If cached and no "
4364 "@var{passphrase} was specified then the cached document is opened. When not "
4365 "cached, @cite{pinentry(1)} will be used to retrieve the passphrase to use "
4366 "for decryption unless @option{disable-pinentry} (@pxref{OPTION}) was "
4367 "specified."
4368 "\n"
4369 "When the @option{--lock} option is passed then the file mutex will be "
4370 "locked as if the @code{LOCK} command (@pxref{LOCK}) had been sent after the "
4371 "file has been opened."
4374 new_command("SAVE", 0, 0, save_command, _(
4375 "SAVE [--no-passphrase] [--reset] [--no-agent] [--s2k-count=N] [--cipher=<algo>] [--cipher-iterations=N] [--inquire-keyparam] [--keygrip=hexstring] [--sign-keygrip=hexstring]\n"
4376 "Writes the @abbr{XML} document to disk. The file written to is the file that "
4377 "was opened using the @code{OPEN} command (@pxref{OPEN}). If the file is a "
4378 "new one or the option @option{--inquire-keyparam} was passed, then a new "
4379 "keypair will be generated and a pinentry will be used to prompt for the "
4380 "passphrase to encrypt with unless the @option{--no-passphrase} option was "
4381 "passed in which case the data file will not be passphrase protected. "
4382 "\n"
4383 "The @option{--no-agent} option disables use of @command{gpg-agent} for "
4384 "passphrase retrieval and caching of new files when @command{gpg-agent} "
4385 "use is enabled. The datafile will be symmetrically encrypted and will not "
4386 "use or generate any keypair."
4387 "\n"
4388 "The @option{--reset} option will clear the cache entry for the current file "
4389 "and require a passphrase, if needed, before saving."
4390 "\n"
4391 "The @option{--cipher} option can be used to encrypt the @abbr{XML} data to "
4392 "an alternate cipher. The default is @code{aes256}. See the Configuration "
4393 "(@pxref{Configuration}) for available ciphers."
4394 "\n"
4395 "The @option{--cipher-iterations} option specifies the number of times to "
4396 "encrypt the XML data. The default is 0 although 1 iteration is still done."
4397 "\n"
4398 "The @option{--inquire-keyparam} option will send a server @emph{INQUIRE} to "
4399 "the client to obtain the key paramaters to use when generating a new "
4400 "keypair. The inquired data is expected to be an S-expression. If not "
4401 "specified then an @samp{RSA} key of @samp{2048} bits will be generated "
4402 "unless otherwise set in the configuration file (@pxref{Configuration}). Note "
4403 "that when this option is specified a new keypair will be generated "
4404 "reguardless if the file is a new one and that if the data file is protected "
4405 "the passphrase to open it will be required before generating the new keypair."
4406 "\n"
4407 "You can encrypt the data file to a public key other than the one that it "
4408 "was originally encrypted with by passing the @option{--keygrip} option with "
4409 "the hex encoded keygrip of the public key as its argument. The keygrip may "
4410 "be of any key that @command{gpg-agent} knows about. The "
4411 "@option{--sign-keygrip} option may also be used to sign with an alternate "
4412 "secret key. This option may be needed when using a smartcard. This option "
4413 "has no effect with symmetrically encrypted data files."
4414 "\n"
4415 "The @option{--s2k-count} option sets number of hash iterations for a "
4416 "passphrase. A value less-than @code{65536} will use the machine calibrated "
4417 "value and is the default. This setting only affects new files. To change "
4418 "the setting use the @code{PASSWD} command (@pxref{PASSWD}). This option "
4419 "has no effect with symmetrically encrypted data files."
4422 new_command("ISCACHED", 1, 0, iscached_command, _(
4423 "ISCACHED [--lock] <filename>\n"
4424 "An @emph{OK} response is returned if the specified @var{filename} is found "
4425 "in the file cache. If not found in the cache but exists on the filesystem "
4426 "then @var{GPG_ERR_NO_DATA} is returned. Otherwise a filesystem error is "
4427 "returned."
4428 "\n"
4429 "The @option{lock} option will lock the file mutex of @var{filename} when the "
4430 "file exists; it does not need to be opened nor cached."
4433 new_command("CLEARCACHE", 1, 1, clearcache_command, _(
4434 "CLEARCACHE [<filename>]\n"
4435 "Clears a file cache entry for all or the specified @var{filename}."
4438 new_command("CACHETIMEOUT", 1, 1, cachetimeout_command, _(
4439 "CACHETIMEOUT <filename> <seconds>\n"
4440 "The time in @var{seconds} until @var{filename} will be removed from the "
4441 "cache. @code{-1} will keep the cache entry forever, @code{0} will require "
4442 "the passphrase for each @code{OPEN} or @code{SAVE} command (@pxref{OPEN}, "
4443 "@pxref{SAVE}). @xref{Configuration}, and the @code{cache_timeout} "
4444 "parameter."
4447 new_command("LIST", 0, 1, list_command, _(
4448 "LIST [--inquire] [--no-recurse] [--verbose] [--with-target] [--all] [[!]element[<TAB>[!]child[..]]]\n"
4449 "If no element path is given then a newline separated list of root elements "
4450 "is returned with a data response. If given, then all reachable elements "
4451 "of the specified element path are returned unless the @option{--no-recurse} "
4452 "option is specified. If specified, only the child elements of the element "
4453 "path are returned without recursing into grandchildren. Each resulting "
4454 "element is prefixed with the literal @code{!} character when the element "
4455 "contains no @code{target} attribute. @xref{Target Attribute}, for details."
4456 "\n"
4457 "When the @option{--verbose} option is passed then each element path "
4458 "returned will have zero or more flags appened to it. These flags are "
4459 "delimited from the element path by a single space character. A flag itself "
4460 "is a single character. Flag @code{+} indicates that there are child nodes of "
4461 "the current element path. Flag @code{E} indicates that an element of an "
4462 "element path contained in a @var{target} attribute could not be found. Flag "
4463 "@code{O} indicates that a @var{target} attribute recursion limit was reached "
4464 "(@pxref{Configuration}). Flag @code{T} will append the resolved element path "
4465 "of the @var{target} attribute contained in the current element (see below)."
4466 "\n"
4467 "The @option{--with-target} option implies @option{--verbose} and will append "
4468 "an additional flag @code{T} followed by a single space then an element path. "
4469 "The appended element path is the resolved path (@pxref{REALPATH}) of the "
4470 "current element when it contains a @var{target} attribute. When no "
4471 "@var{target} attribute is found then no flag will be appended."
4472 "\n"
4473 "The @option{--no-recurse} option limits the amount of data returned to only "
4474 "the listing of children of the specified element path and not any "
4475 "grandchildren."
4476 "\n"
4477 "The @option{--all} option lists the entire element tree for each root "
4478 "element. This option also implies option @option{--verbose}."
4479 "\n"
4480 "When the @option{--inquire} option is passed then all remaining non-option "
4481 "arguments are retrieved via a server @emph{INQUIRE}."
4484 new_command("REALPATH", 0, 1, realpath_command, _(
4485 "REALPATH [--inquire] [!]element[<TAB>[!]child[..]]\n"
4486 "Resolves all @code{target} attributes of the specified element path and "
4487 "returns the result with a data response. @xref{Target Attribute}, for details."
4488 "\n"
4489 "When the @option{--inquire} option is passed then all remaining non-option "
4490 "arguments are retrieved via a server @emph{INQUIRE}."
4493 new_command("STORE", 0, 1, store_command, _(
4494 "STORE [!]element[<TAB>[!]child[..]]<TAB>[content]\n"
4495 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
4496 "\n"
4497 "Creates a new element path or modifies the @var{content} of an existing "
4498 "element. If only a single element is specified then a new root element is "
4499 "created. Otherwise, elements are @key{TAB} delimited and the content will be "
4500 "set to the final @key{TAB} delimited element. If no @var{content} is "
4501 "specified after the final @key{TAB}, then the content of the element will "
4502 "be removed, or empty when creating a new element."
4503 "\n"
4504 "The only restriction of an element name is that it not contain whitespace "
4505 "or begin with the literal element character @code{!} unless specifying a "
4506 "literal element (@pxref{Target Attribute}). There is no whitespace between "
4507 "the @key{TAB} delimited elements. It is recommended that the content of an "
4508 "element be base64 encoded when it contains control or @key{TAB} characters "
4509 "to prevent @abbr{XML} parsing and @command{pwmd} syntax errors."
4512 new_command("RENAME", 0, 1, rename_command, _(
4513 "RENAME [--inquire] [!]element[<TAB>[!]child[..]] <value>\n"
4514 "Renames the specified @var{element} to the new @var{value}. If an element of "
4515 "the same name as the @var{value} already exists it will be overwritten."
4516 "\n"
4517 "When the @option{--inquire} option is passed then all remaining non-option "
4518 "arguments are retrieved via a server @emph{INQUIRE}."
4521 new_command("COPY", 0, 1, copy_command, _(
4522 "COPY [--inquire] [!]source[<TAB>[!]child[..]] [!]dest[<TAB>[!]child[..]]\n"
4523 "Copies the entire element tree starting from the child node of the source "
4524 "element, to the destination element path. If the destination element path "
4525 "does not exist then it will be created; otherwise it is overwritten."
4526 "\n"
4527 "Note that attributes from the source element are merged into the "
4528 "destination element when the destination element path exists. When an "
4529 "attribute of the same name exists in both the source and destination "
4530 "elements then the destination attribute will be updated to the source "
4531 "attribute value."
4532 "\n"
4533 "When the @option{--inquire} option is passed then all remaining non-option "
4534 "arguments are retrieved via a server @emph{INQUIRE}."
4537 new_command("MOVE", 0, 1, move_command, _(
4538 "MOVE [--inquire] [!]source[<TAB>[!]child[..]] [[!]dest[<TAB>[!]child[..]]]\n"
4539 "Moves the source element path to the destination element path. If the "
4540 "destination is not specified then it will be moved to the root node of the "
4541 "document. If the destination is specified and exists then it will be "
4542 "overwritten; otherwise non-existing elements of the destination element "
4543 "path will be created."
4544 "\n"
4545 "When the @option{--inquire} option is passed then all remaining non-option "
4546 "arguments are retrieved via a server @emph{INQUIRE}."
4549 new_command("DELETE", 0, 1, delete_command, _(
4550 "DELETE [--inquire] [!]element[<TAB>[!]child[..]]\n"
4551 "Removes the specified element path and all of its children. This may break "
4552 "an element with a @code{target} attribute (@pxref{Target Attribute}) that "
4553 "refers to this element or any of its children."
4554 "\n"
4555 "When the @option{--inquire} option is passed then all remaining non-option "
4556 "arguments are retrieved via a server @emph{INQUIRE}."
4559 new_command("GET", 0, 1, get_command, _(
4560 "GET [--inquire] [!]element[<TAB>[!]child[..]]\n"
4561 "Retrieves the content of the specified element. The content is returned "
4562 "with a data response."
4563 "\n"
4564 "When the @option{--inquire} option is passed then all remaining non-option "
4565 "arguments are retrieved via a server @emph{INQUIRE}."
4568 new_command("ATTR", 0, 1, attr_command, _(
4569 "ATTR [--inquire] SET|GET|DELETE|LIST [<attribute>] [!]element[<TAB>[!]child[..]] ..\n"
4570 "@table @asis\n"
4571 "@item ATTR SET attribute [!]element[<TAB>[!]child[..]] [value]\n"
4572 "\n"
4573 " Stores or updates an @var{attribute} name and optional @var{value} of an "
4574 "element. When no @var{value} is specified any existing value will be removed."
4575 "\n"
4576 "@item ATTR DELETE attribute [!]element[<TAB>[!]child[..]]\n"
4577 "\n"
4578 " Removes an @var{attribute} from an element."
4579 "\n"
4580 "@item ATTR LIST [!]element[<TAB>[!]child[..]]\n"
4581 "\n"
4582 " Retrieves a newline separated list of attributes names and values "
4583 "from the specified element. Each attribute name and value is space delimited."
4584 "\n"
4585 "@item ATTR GET attribute [!]element[<TAB>[!]child[..]]\n"
4586 "\n"
4587 " Retrieves the value of an @var{attribute} from an element."
4588 "@end table\n"
4589 "\n"
4590 "The @code{_name} attribute (case sensitive) cannot be removed nor modified. "
4591 "Use the @code{DELETE} (@pxref{DELETE}) or @code{RENAME} (@pxref{RENAME}) "
4592 "commands instead."
4593 "\n"
4594 "The @code{_mtime} attribute is updated each time an element is modified by "
4595 "either storing content, editing attributes or by deleting a child element. "
4596 "The @code{_ctime} attribute is created for each new element in an element "
4597 "path."
4598 "\n"
4599 "When the @option{--inquire} option is passed then all remaining non-option "
4600 "arguments are retrieved via a server @emph{INQUIRE}."
4601 "\n"
4602 "@xref{Target Attribute}, for details about this special attribute."
4605 new_command("XPATH", 0, 1, xpath_command, _(
4606 "XPATH [--inquire] <expression>[<TAB>[value]]\n"
4607 "Evaluates an XPath @var{expression}. If no @var{value} argument is "
4608 "specified it is assumed the expression is a request to return a result. "
4609 "Otherwise, the result is set to the @var{value} argument and the document is "
4610 "updated. If there is no @var{value} after the @key{TAB} character, the value "
4611 "is assumed to be empty and the document is updated. For example:"
4612 "@sp 1\n"
4613 "@example\n"
4614 "XPATH //element[@@_name='password']@key{TAB}\n"
4615 "@end example\n"
4616 "@sp 1"
4617 "would clear the content of all @code{password} elements in the data file "
4618 "while leaving off the trailing @key{TAB} would return all @code{password} "
4619 "elements in @abbr{XML} format."
4620 "\n"
4621 "When the @option{--inquire} option is passed then all remaining non-option "
4622 "arguments are retrieved via a server @emph{INQUIRE}."
4623 "\n"
4624 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
4625 "expression syntax."
4628 new_command("XPATHATTR", 0, 1, xpathattr_command, _(
4629 "XPATHATTR [--inquire] SET|DELETE <name> <expression>[<TAB>[<value>]]\n"
4630 "Like the @code{XPATH} command (@pxref{XPATH}) but operates on element "
4631 "attributes and does not return a result. For the @var{SET} operation the "
4632 "@var{value} is optional but the field is required. If not specified then "
4633 "the attribute value will be empty. For example:"
4634 "@sp 1"
4635 "@example\n"
4636 "XPATHATTR SET password //element[@@_name='password']@key{TAB}\n"
4637 "@end example\n"
4638 "@sp 1"
4639 "would create an @code{password} attribute for each @code{password} element "
4640 "found in the document. The attribute value will be empty but still exist."
4641 "\n"
4642 "When the @option{--inquire} option is passed then all remaining non-option "
4643 "arguments are retrieved via a server @emph{INQUIRE}."
4644 "\n"
4645 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
4646 "expression syntax."
4649 new_command("IMPORT", 0, 1, import_command, _(
4650 "IMPORT [--root [!]element[<TAB>[!]child[..]]] <content>\n"
4651 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
4652 "\n"
4653 "Like the @code{STORE} command (@pxref{STORE}), but the @var{content} "
4654 "argument is raw @abbr{XML} data. The content is created as a child of "
4655 "the element path specified with the @option{--root} option or at the "
4656 "document root when not specified. Existing elements of the same name will "
4657 "be overwritten."
4658 "\n"
4659 "The content must begin with an @abbr{XML} element node. @xref{Introduction}, "
4660 "for details."
4663 new_command("DUMP", 0, 1, dump_command, _(
4664 "DUMP\n"
4665 "Shows the in memory @abbr{XML} document with indenting. @xref{XPATH}, for "
4666 "dumping a specific node."
4669 new_command("LOCK", 0, 0, lock_command, _(
4670 "LOCK\n"
4671 "Locks the mutex associated with the opened file. This prevents other clients "
4672 "from sending commands to the same opened file until the client "
4673 "that sent this command either disconnects or sends the @code{UNLOCK} "
4674 "command. @xref{UNLOCK}."
4677 new_command("UNLOCK", 1, 0, unlock_command, _(
4678 "UNLOCK\n"
4679 "Unlocks the file mutex which was locked with the @code{LOCK} command or "
4680 "a commands' @option{--lock} option (@pxref{LOCK}, @pxref{OPEN}, "
4681 "@pxref{ISCACHED})."
4684 new_command("GETCONFIG", 1, 1, getconfig_command, _(
4685 "GETCONFIG [filename] <parameter>\n"
4686 "Returns the value of a @command{pwmd} configuration @var{parameter} with a "
4687 "data response. If no file has been opened then the value for @var{filename} "
4688 "or the default from the @samp{global} section will be returned. If a file "
4689 "has been opened and no @var{filename} is specified, a value previously "
4690 "set with the @code{OPTION} command (@pxref{OPTION}) will be returned."
4693 new_command("OPTION", 1, 1, option_command, _(
4694 "OPTION <NAME>=<VALUE>\n"
4695 "Sets a client option @var{name} to @var{value}. The value for an option is "
4696 "kept for the duration of the connection."
4697 "\n"
4698 "@table @asis\n"
4699 "@item DISABLE-PINENTRY\n"
4700 "Disable use of @command{pinentry} for passphrase retrieval. When set, a "
4701 "server inquire is sent to the client to obtain the passphrase. This option "
4702 "may be set as needed before the @pxref{OPEN}, @pxref{PASSWD}, and "
4703 "@pxref{SAVE} commands."
4704 "\n"
4705 "@item PINENTRY-TIMEOUT\n"
4706 "Sets the number of seconds before a pinentry prompt will return an error "
4707 "while waiting for user input."
4708 "\n"
4709 "@item TTYNAME\n"
4710 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4711 "\n"
4712 "@item TTYTYPE\n"
4713 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4714 "\n"
4715 "@item DISPLAY\n"
4716 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4717 "\n"
4718 "@item PINENTRY-DESC\n"
4719 "Sets the description string of the @command{gpg-agent} and @command{pinentry} dialog."
4720 "\n"
4721 "@item PINENTRY-TITLE\n"
4722 "Sets the title string of the @command{gpg-agent} and @command{pinentry} dialog."
4723 "\n"
4724 "@item PINENTRY-PROMPT\n"
4725 "Sets the prompt string of the @command{gpg-agent} and @command{pinentry} dialog."
4726 "\n"
4727 "@item LC-CTYPE\n"
4728 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4729 "\n"
4730 "@item LC-MESSAGES\n"
4731 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4732 "\n"
4733 "@item NAME\n"
4734 "Associates the thread ID of the connection with the specified textual "
4735 "representation. Useful for debugging log messages."
4736 "\n"
4737 "@item LOCK-TIMEOUT\n"
4738 "When not @code{0}, the duration in tenths of a second to wait for the file "
4739 "mutex which has been locked by another thread to be released before returning "
4740 "an error. When @code{-1}, then an error will be returned immediately."
4741 "\n"
4742 "@item LOG-LEVEL\n"
4743 "An integer specifiying the logging level."
4744 "@end table\n"
4747 new_command("LS", 1, 1, ls_command, _(
4748 "LS\n"
4749 "Lists the available data files stored in the data directory "
4750 "(@file{~/.pwmd/data}). The result is a newline separated list of filenames."
4753 new_command("RESET", 1, 1, NULL, _(
4754 "RESET\n"
4755 "Closes the currently opened file but keeps any previously set client options."
4758 new_command("NOP", 1, 1, NULL, _(
4759 "NOP\n"
4760 "Does nothing. Always returns successfully."
4763 /* !END-HELP-TEXT! */
4764 new_command ("CANCEL", 1, 1, NULL, NULL);
4765 new_command ("END", 1, 1, NULL, NULL);
4766 new_command ("BYE", 1, 1, NULL, NULL);
4768 int i;
4769 for (i = 0; command_table[i]; i++);
4770 qsort (command_table, i - 1, sizeof (struct command_table_s *),
4771 sort_commands);
4774 gpg_error_t
4775 register_commands (assuan_context_t ctx)
4777 int i = 0, rc;
4779 for (; command_table[i]; i++)
4781 if (!command_table[i]->handler)
4782 continue;
4784 rc = assuan_register_command (ctx, command_table[i]->name,
4785 command_table[i]->handler,
4786 command_table[i]->help);
4787 if (rc)
4788 return rc;
4791 rc = assuan_register_bye_notify (ctx, bye_notify);
4792 if (rc)
4793 return rc;
4795 rc = assuan_register_reset_notify (ctx, reset_notify);
4796 if (rc)
4797 return rc;
4799 rc = assuan_register_pre_cmd_notify (ctx, command_startup);
4800 if (rc)
4801 return rc;
4803 return assuan_register_post_cmd_notify (ctx, command_finalize);