Fix Smatch warnings.
[pwmd.git] / src / commands.c
blob69784f5a32e3112b0adcdf90627768490e125907
1 /*
2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012
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 && client->crypto && client->crypto->agent \
82 && client->crypto->agent->ctx && \
83 crypto->agent->ctx != client->crypto->agent->ctx) \
84 { \
85 client->crypto->agent->ctx = crypto->agent->ctx; \
86 crypto->agent->ctx = NULL; \
87 } \
88 } while (0)
89 #else
90 #define UPDATE_AGENT_CTX(client, crypto)
91 #endif
93 struct command_table_s
95 const char *name;
96 gpg_error_t (*handler) (assuan_context_t, char *line);
97 const char *help;
98 int ignore_startup;
99 int unlock; // unlock the file mutex after validating the checksum
102 static struct command_table_s **command_table;
104 static gpg_error_t do_lock (struct client_s *client, int add);
105 static gpg_error_t validate_checksum (struct client_s *,
106 struct cache_data_s *);
107 static gpg_error_t update_checksum (struct client_s *client);
109 static gpg_error_t
110 unlock_file_mutex (struct client_s *client, int remove)
112 gpg_error_t rc = 0;
114 // OPEN: keep the lock for the same file being reopened.
115 if (client->flags & FLAG_KEEP_LOCK && client->flags & FLAG_HAS_LOCK)
116 return 0;
118 if (!(client->flags & FLAG_HAS_LOCK))
119 return GPG_ERR_NOT_LOCKED;
121 rc = cache_unlock_mutex (client->md5file, remove);
122 if (rc)
123 rc = GPG_ERR_INV_STATE;
124 else
125 client->flags &= ~(FLAG_HAS_LOCK | FLAG_LOCK_CMD);
127 return rc;
130 static gpg_error_t
131 lock_file_mutex (struct client_s *client, int add)
133 gpg_error_t rc = 0;
134 int timeout = config_get_integer (client->filename, "cache_timeout");
136 if (client->flags & FLAG_HAS_LOCK)
137 return 0;
139 rc = cache_lock_mutex (client->ctx, client->md5file,
140 client->lock_timeout, add, timeout);
141 if (!rc)
142 client->flags |= FLAG_HAS_LOCK;
144 return rc;
147 static gpg_error_t
148 file_modified (struct client_s *client, struct command_table_s *cmd)
150 gpg_error_t rc = 0;
152 if (!(client->flags & FLAG_OPEN))
153 return GPG_ERR_INV_STATE;
155 rc = lock_file_mutex (client, 0);
156 if (!rc || rc == GPG_ERR_NO_DATA)
158 rc = validate_checksum (client, NULL);
159 if (gpg_err_code (rc) == GPG_ERR_ENOENT)
160 rc = 0;
163 if ((cmd->unlock && !(client->flags & FLAG_HAS_LOCK)) || rc)
164 unlock_file_mutex (client, 0);
166 return rc;
169 static gpg_error_t
170 parse_xml (assuan_context_t ctx, int new)
172 struct client_s *client = assuan_get_pointer (ctx);
173 int cached = client->doc != NULL;
175 if (new)
177 client->doc = new_document ();
178 if (client->doc)
180 xmlDocDumpFormatMemory (client->doc,
181 (xmlChar **) & client->crypto->plaintext,
182 (int *) &client->crypto->plaintext_len, 0);
183 if (!client->crypto->plaintext)
185 xmlFreeDoc (client->doc);
186 client->doc = NULL;
190 else if (!cached)
191 client->doc = parse_doc ((char *) client->crypto->plaintext,
192 client->crypto->plaintext_len);
194 return !client->doc ? GPG_ERR_ENOMEM : 0;
197 static void
198 free_client (struct client_s *client)
200 if (client->doc)
201 xmlFreeDoc (client->doc);
203 xfree (client->crc);
204 xfree (client->filename);
205 xfree (client->last_error);
207 if (client->crypto)
209 cleanup_crypto_stage2 (client->crypto);
210 if (client->crypto->pkey_sexp)
211 gcry_sexp_release (client->crypto->pkey_sexp);
213 client->crypto->pkey_sexp = NULL;
214 memset (client->crypto->sign_grip, 0,
215 sizeof (client->crypto->sign_grip));
216 memset (client->crypto->grip, 0, sizeof(client->crypto->grip));
219 if (client->xml_error)
220 xmlResetError (client->xml_error);
223 void
224 cleanup_client (struct client_s *client)
226 assuan_context_t ctx = client->ctx;
227 struct client_thread_s *thd = client->thd;
228 struct crypto_s *crypto = client->crypto;
229 long lock_timeout = client->lock_timeout;
230 int no_pinentry = (client->flags & FLAG_NO_PINENTRY);
231 struct pinentry_option_s pin_opts;
232 #ifdef WITH_AGENT
233 struct pinentry_option_s agent_pin_opts;
235 if (crypto && crypto->agent)
236 memcpy (&agent_pin_opts, &crypto->agent->pinentry_opts,
237 sizeof(struct pinentry_option_s));
238 #endif
240 memcpy (&pin_opts, &client->pinentry_opts, sizeof(struct pinentry_option_s));
241 unlock_file_mutex (client, client->flags & FLAG_NEW);
242 free_client (client);
243 memset (client, 0, sizeof (struct client_s));
244 client->crypto = crypto;
245 client->ctx = ctx;
246 client->thd = thd;
247 client->lock_timeout = lock_timeout;
248 memcpy (&client->pinentry_opts, &pin_opts, sizeof(struct pinentry_option_s));
249 client->flags |= no_pinentry ? FLAG_NO_PINENTRY : 0;
250 #ifdef WITH_AGENT
251 if (crypto && crypto->agent)
252 memcpy (&crypto->agent->pinentry_opts, &agent_pin_opts,
253 sizeof(struct pinentry_option_s));
254 #endif
257 static gpg_error_t
258 open_finalize (assuan_context_t ctx, char *key, size_t keylen)
260 struct client_s *client = assuan_get_pointer (ctx);
261 gpg_error_t rc = 0;
262 struct cache_data_s *cdata = cache_get_data (client->md5file);
263 int cached = 0, keyarg = key ? 1 : 0;
264 size_t keysize;
265 unsigned char *salted_key = NULL;
266 int algo;
268 client->crypto->filename = str_dup (client->filename);
269 if (cdata || client->flags & FLAG_NEW)
271 if (cdata && !(client->flags & FLAG_NEW))
273 rc = decrypt_xml (client->crypto, cdata->doc, cdata->doclen);
274 if (rc)
275 return rc;
278 cached = cdata != NULL;
279 goto done;
282 if (!key && !IS_PKCS (client->crypto))
284 if (client->flags & FLAG_NO_PINENTRY)
286 rc = inquire_passphrase (ctx, "PASSPHRASE", (unsigned char **)&key,
287 &keylen);
288 if (rc)
289 return rc;
291 else
293 client->pinentry_opts.timeout = config_get_integer (client->filename,
294 "pinentry_timeout");
295 rc = getpin_common (client->ctx, client->filename, PINENTRY_OPEN,
296 &key, &keylen);
297 if (rc)
298 return rc;
302 if (!IS_PKCS (client->crypto))
304 algo = cipher_to_gcrypt (client->crypto->hdr.flags);
305 rc = hash_key (algo, client->crypto->hdr.salt,
306 sizeof(client->crypto->hdr.salt), key, keylen,
307 (void **)&salted_key, &keysize);
308 if (!keyarg)
309 gcry_free (key);
311 if (!rc)
312 rc = decrypt_data (client->ctx, client->crypto, salted_key, keysize);
314 if (rc)
315 return rc;
317 cdata = xcalloc (1, sizeof (struct cache_data_s));
318 if (!cdata)
319 return GPG_ERR_ENOMEM;
321 cdata->key = salted_key;
322 cdata->keylen = keysize;
324 else
325 rc = decrypt_data (client->ctx, client->crypto, NULL, 0);
327 done:
328 if (!rc)
330 rc = parse_xml (ctx, client->flags & FLAG_NEW);
331 if (!rc)
333 int timeout = config_get_integer (client->filename,
334 "cache_timeout");
336 if (!cached)
338 if (!cdata)
339 cdata = xcalloc (1, sizeof (struct cache_data_s));
341 rc = encrypt_xml (NULL, cache_key, cache_keysize,
342 GCRY_CIPHER_AES, client->crypto->plaintext,
343 client->crypto->plaintext_len, &cdata->doc,
344 &cdata->doclen, &cache_iv, &cache_blocksize,
346 if (!rc && !(client->flags & FLAG_NEW) && IS_PKCS (client->crypto))
348 rc = gcry_sexp_build ((gcry_sexp_t *) & cdata->pubkey, NULL,
349 "%S", client->crypto->pkey_sexp);
353 if (cdata->sigkey)
354 gcry_sexp_release (cdata->sigkey);
356 cdata->sigkey = NULL;
358 if (!rc && IS_PKCS (client->crypto))
359 rc = gcry_sexp_build ((gcry_sexp_t *) &cdata->sigkey, NULL,
360 "%S", client->crypto->sigpkey_sexp);
362 if (!rc
363 && !cache_add_file (client->md5file, (client->flags & FLAG_NEW)
364 ? NULL : client->crypto->grip, cdata, timeout))
366 if (!cached)
368 free_cache_data_once (cdata);
369 xmlFreeDoc (client->doc);
370 client->doc = NULL;
372 rc = GPG_ERR_ENOMEM;
375 if (!rc)
376 client->flags |= FLAG_OPEN;
380 if (!rc)
381 update_checksum (client);
383 if (!rc && (client->opts & OPT_LOCK_ON_OPEN))
384 rc = do_lock (client, 0);
386 return rc;
389 static void
390 req_cleanup (void *arg)
392 if (!arg)
393 return;
395 strv_free ((char **) arg);
398 static gpg_error_t
399 parse_open_opt_lock (void *data, void *value)
401 struct client_s *client = data;
403 client->opts |= OPT_LOCK_ON_OPEN;
404 return 0;
407 static gpg_error_t
408 parse_opt_inquire (void *data, void *value)
410 struct client_s *client = data;
412 (void) value;
413 client->opts |= OPT_INQUIRE;
414 return 0;
417 static gpg_error_t
418 update_checksum (struct client_s *client)
420 unsigned char *crc;
421 size_t len;
422 struct cache_data_s *cdata;
423 gpg_error_t rc = get_checksum (client->filename, &crc, &len);
425 if (rc)
426 return rc;
428 xfree (client->crc);
429 client->crc = crc;
430 cdata = cache_get_data (client->md5file);
431 if (cdata)
433 xfree (cdata->crc);
434 cdata->crc = xmalloc (len);
435 memcpy (cdata->crc, crc, len);
438 return 0;
441 static gpg_error_t
442 validate_checksum (struct client_s *client, struct cache_data_s *cdata)
444 unsigned char *crc;
445 size_t len;
446 gpg_error_t rc;
447 int n = 0;
449 if (cdata && !cdata->crc)
450 return GPG_ERR_CHECKSUM;
452 rc = get_checksum (client->filename, &crc, &len);
453 if (rc)
454 return rc;
456 if (cdata)
457 n = memcmp (cdata->crc, crc, len);
458 else if (client->crc)
459 n = memcmp (client->crc, crc, len);
461 xfree (crc);
462 return n ? GPG_ERR_CHECKSUM : 0;
465 static gpg_error_t
466 do_open (assuan_context_t ctx, const char *filename, const char *password)
468 struct client_s *client = assuan_get_pointer (ctx);
469 struct cache_data_s *cdata;
470 gpg_error_t rc = 0;
471 int done = 0;
473 if (!valid_filename (filename))
474 return GPG_ERR_INV_VALUE;
476 gcry_md_hash_buffer (GCRY_MD_MD5, client->md5file, filename,
477 strlen (filename));
478 client->filename = str_dup (filename);
479 if (!client->filename)
480 return GPG_ERR_ENOMEM;
482 // Cached document?
483 cdata = cache_get_data (client->md5file);
484 if (cdata && cdata->doc)
486 int defer;
488 rc = validate_checksum (client, cdata);
489 /* This will check that the key is cached in the agent which needs to
490 * be determined for files that share a keygrip. */
491 if (!rc)
493 rc = cache_iscached (client->filename, &defer);
494 if (!rc && defer)
495 rc = GPG_ERR_KEY_EXPIRED;
498 #ifdef WITH_GNUTLS
499 if (!rc && client->thd->remote
500 && config_get_boolean (NULL, "tcp_require_key"))
501 rc = GPG_ERR_KEY_EXPIRED;
502 #endif
504 if (!rc && !password)
506 rc = read_data_header (client->filename, &client->crypto->hdr,
507 NULL, NULL);
508 if (!rc)
510 if (IS_PKCS (client->crypto))
512 gcry_sexp_build (&client->crypto->pkey_sexp, NULL, "%S",
513 cdata->pubkey);
514 gcry_pk_get_keygrip (client->crypto->pkey_sexp,
515 client->crypto->grip);
516 gcry_sexp_build (&client->crypto->sigpkey_sexp, NULL, "%S",
517 cdata->sigkey);
518 gcry_pk_get_keygrip (client->crypto->sigpkey_sexp,
519 client->crypto->sign_grip);
522 if (!rc)
524 rc = open_finalize (ctx, NULL, 0);
525 done = 1;
530 /* There was an error accessing the file so clear the cache entry. The
531 * real error will be returned from read_data_file() since the file
532 * may have only disappeared. */
533 if (!done)
535 log_write ("%s: %s", filename, pwmd_strerror (rc));
536 rc = cache_clear (client->md5file);
537 send_status_all (STATUS_CACHE, NULL);
541 if (done || rc)
542 return rc;
544 rc = read_data_file (client->filename, client->crypto);
545 if (rc)
547 if (gpg_err_source (rc) != GPG_ERR_SOURCE_DEFAULT ||
548 gpg_err_code (rc) != GPG_ERR_ENOENT)
550 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
551 return rc;
554 client->flags |= FLAG_NEW;
555 memset (client->crypto->grip, 0, sizeof (client->crypto->grip));
556 memset (client->crypto->sign_grip, 0,
557 sizeof (client->crypto->sign_grip));
558 rc = open_finalize (ctx, NULL, 0);
559 return rc;
562 if (password && IS_PKCS (client->crypto))
564 #ifdef WITH_AGENT
565 rc = set_agent_passphrase (client->crypto, password, strlen (password));
566 if (rc)
567 return rc;
568 #endif
571 rc = open_finalize (ctx, (char *)password, password ? strlen (password) : 0);
572 return rc;
575 static gpg_error_t
576 open_command (assuan_context_t ctx, char *line)
578 gpg_error_t rc;
579 struct client_s *client = assuan_get_pointer (ctx);
580 char **req, *password = NULL, *filename;
581 unsigned char md5file[16];
582 int same_file = 0;
583 struct argv_s *args[] = {
584 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_open_opt_lock},
585 NULL
588 rc = parse_options (&line, args, client);
589 if (rc)
590 return send_error (ctx, rc);
592 req = str_split (line, " ", 2);
593 if (!req)
594 return send_error (ctx, GPG_ERR_SYNTAX);
596 #ifdef WITH_GNUTLS
597 if (client->thd->remote)
599 rc = tls_validate_access (client, req[0]);
600 if (rc)
602 if (rc == GPG_ERR_INV_USER_ID)
603 log_write (_("client validation failed for file '%s'"), req[0]);
604 strv_free (req);
605 return send_error (ctx, rc);
608 /* Remote pinentries are not supported. */
609 client->flags |= FLAG_NO_PINENTRY;
611 #endif
613 pthread_cleanup_push (req_cleanup, req);
614 filename = req[0];
615 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
616 /* This client may have locked a different file with ISCACHED --lock than
617 * the current filename. This will remove that lock. */
618 same_file = !memcmp (md5file, client->md5file, 16) ? 1 : 0;
619 if (client->flags & FLAG_OPEN ||
620 (client->flags & FLAG_HAS_LOCK && !same_file))
622 typeof (client->opts) opts = client->opts;
623 typeof (client->flags) flags = client->flags;
625 if (same_file)
626 client->flags |= FLAG_KEEP_LOCK;
628 cleanup_client (client);
629 client->opts = opts;
630 client->flags |= flags;
631 client->flags &= ~(FLAG_LOCK_CMD | FLAG_NEW);
632 if (!same_file)
633 client->flags &= ~(FLAG_HAS_LOCK);
636 /* Need to lock the mutex here because file_modified() cannot without
637 * knowing the filename. */
638 memcpy (client->md5file, md5file, 16);
639 rc = lock_file_mutex (client, 1);
640 if (!rc)
642 password = req[1] && *req[1] ? req[1] : NULL;
643 #ifdef WITH_AGENT
644 if (IS_PKCS (client->crypto))
645 rc = set_pinentry_mode (client->crypto->agent,
646 (client->flags & FLAG_NO_PINENTRY) ? "loopback"
647 : "ask");
648 #endif
649 if (!rc)
651 rc = do_open (ctx, filename, password);
652 if (rc)
653 cleanup_client (client);
655 cleanup_crypto_stage1 (client->crypto);
659 pthread_cleanup_pop (1);
661 if (!rc && client->flags & FLAG_NEW)
662 rc = send_status (ctx, STATUS_NEWFILE, NULL);
664 #ifdef WITH_AGENT
665 (void) kill_scd (client->crypto->agent);
666 #endif
667 return send_error (ctx, rc);
670 static gpg_error_t
671 parse_save_opt_no_passphrase (void *data, void *value)
673 struct client_s *client = data;
675 (void) value;
676 client->opts |= OPT_NO_PASSPHRASE;
677 return 0;
680 static gpg_error_t
681 parse_save_opt_no_agent (void *data, void *value)
683 struct client_s *client = data;
685 client->opts |= OPT_NO_AGENT;
686 return 0;
689 static gpg_error_t
690 parse_save_opt_cipher (void *data, void *value)
692 struct client_s *client = data;
693 int algo = cipher_string_to_gcrypt ((char *) value);
694 file_header_t *hdr = &client->crypto->save.hdr;
696 if (algo == -1)
697 return GPG_ERR_INV_VALUE;
699 hdr->flags = set_cipher_flag (hdr->flags, algo);
700 return 0;
703 static gpg_error_t
704 parse_save_opt_keygrip (void *data, void *value)
706 struct client_s *client = data;
708 if (!IS_PKCS (client->crypto))
709 return GPG_ERR_INV_ARG;
711 #ifdef WITH_AGENT
712 if (client->crypto->save.pkey)
713 gcry_sexp_release (client->crypto->save.pkey);
715 client->crypto->save.pkey = NULL;
716 return get_pubkey (client->crypto, value, &client->crypto->save.pkey);
717 #else
718 return GPG_ERR_INV_ARG;
719 #endif
722 static gpg_error_t
723 parse_save_opt_sign_keygrip (void *data, void *value)
725 struct client_s *client = data;
727 if (!IS_PKCS (client->crypto))
728 return GPG_ERR_INV_ARG;
730 #ifdef WITH_AGENT
731 if (client->crypto->save.sigpkey)
732 gcry_sexp_release (client->crypto->save.sigpkey);
734 client->crypto->save.sigpkey = NULL;
735 return get_pubkey (client->crypto, value, &client->crypto->save.sigpkey);
736 #else
737 return GPG_ERR_INV_ARG;
738 #endif
741 static gpg_error_t
742 parse_opt_s2k_count (void *data, void *value)
744 struct client_s *client = data;
745 char *v = value;
747 if (!v || !*v)
748 return GPG_ERR_INV_VALUE;
750 client->crypto->save.s2k_count = strtoul (v, NULL, 10);
751 return 0;
754 static gpg_error_t
755 parse_save_opt_iterations (void *data, void *value)
757 struct client_s *client = data;
758 char *v = value, *p;
759 uint64_t n;
761 if (!v || !*v)
762 return GPG_ERR_INV_VALUE;
764 errno = 0;
765 n = strtoull (v, &p, 10);
766 if (n == UINT64_MAX && errno)
767 return gpg_error_from_syserror ();
768 else if (p && *p)
769 return GPG_ERR_INV_VALUE;
771 client->crypto->save.hdr.iterations = n;
772 return 0;
775 static gpg_error_t
776 save_finalize (assuan_context_t ctx)
778 struct client_s *client = assuan_get_pointer (ctx);
779 gpg_error_t rc = 0;
780 xmlChar *xmlbuf = NULL;
781 int xmlbuflen;
782 void *key = NULL;
783 size_t keylen = 0;
785 xmlDocDumpFormatMemory (client->doc, &xmlbuf, &xmlbuflen, 0);
786 if (!xmlbuf)
787 return GPG_ERR_ENOMEM;
789 pthread_cleanup_push (xmlFree, xmlbuf);
791 if (!use_agent || ((client->flags & FLAG_NEW)
792 && (client->opts & OPT_NO_AGENT))
793 || !(client->crypto->hdr.flags & PWMD_FLAG_PKCS))
795 rc = export_common (ctx, client->flags & FLAG_NO_PINENTRY,
796 client->crypto, xmlbuf, xmlbuflen, client->filename,
797 NULL, &key, &keylen, 1, 1);
799 #ifdef WITH_AGENT
800 else
802 gcry_sexp_t pubkey = client->crypto->save.pkey;
803 gcry_sexp_t sigkey = client->crypto->save.sigpkey;
805 if (!pubkey)
806 pubkey = client->crypto->pkey_sexp;
808 if (!sigkey)
810 sigkey = client->crypto->sigpkey_sexp;
811 if (!sigkey)
813 gcry_sexp_build (&client->crypto->save.sigpkey, 0, "%S", pubkey);
814 sigkey = client->crypto->save.sigpkey;
818 rc = encrypt_data_file (client->ctx, client->crypto, pubkey, sigkey,
819 client->filename, xmlbuf, xmlbuflen);
820 if (pubkey == client->crypto->save.pkey)
822 if (!rc)
824 gcry_sexp_release (client->crypto->pkey_sexp);
825 client->crypto->pkey_sexp = client->crypto->save.pkey;
826 gcry_pk_get_keygrip (client->crypto->pkey_sexp,
827 client->crypto->grip);
829 else
830 gcry_sexp_release (pubkey);
832 client->crypto->save.pkey = NULL;
835 if (!rc)
836 gcry_pk_get_keygrip (sigkey, client->crypto->sign_grip);
838 if (sigkey == client->crypto->save.sigpkey)
840 if (!rc)
842 if (client->crypto->sigpkey_sexp)
843 gcry_sexp_release (client->crypto->sigpkey_sexp);
845 client->crypto->sigpkey_sexp = client->crypto->save.sigpkey;
846 gcry_pk_get_keygrip (client->crypto->sigpkey_sexp,
847 client->crypto->sign_grip);
849 else
850 gcry_sexp_release (sigkey);
852 client->crypto->save.sigpkey = NULL;
855 #endif
857 if (!rc)
859 int cached;
861 rc = save_common (client->filename, client->crypto, xmlbuf, xmlbuflen,
862 key, keylen, &cached, client->opts & OPT_NO_AGENT);
863 if (rc)
864 gcry_free (key);
866 if (!rc && (!cached || (client->flags & FLAG_NEW)))
867 send_status_all (STATUS_CACHE, NULL);
869 if (!rc)
871 update_checksum (client);
872 client->flags &= ~(FLAG_NEW);
874 else
875 rc = GPG_ERR_ENOMEM;
878 pthread_cleanup_pop (1); // xmlFree
879 return rc;
882 static gpg_error_t
883 parse_opt_reset (void *data, void *value)
885 struct client_s *client = data;
887 (void) value;
888 client->opts |= OPT_RESET;
889 return 0;
892 static gpg_error_t
893 save_command (assuan_context_t ctx, char *line)
895 struct client_s *client = assuan_get_pointer (ctx);
896 gpg_error_t rc;
897 struct stat st;
898 struct argv_s *args[] = {
899 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG,
900 parse_save_opt_no_passphrase},
901 &(struct argv_s) {"cipher", OPTION_TYPE_ARG, parse_save_opt_cipher},
902 &(struct argv_s) {"inquire-keyparam", OPTION_TYPE_NOARG,
903 parse_opt_inquire},
904 &(struct argv_s) {"keygrip", OPTION_TYPE_ARG, parse_save_opt_keygrip},
905 &(struct argv_s) {"sign-keygrip", OPTION_TYPE_ARG,
906 parse_save_opt_sign_keygrip},
907 &(struct argv_s) {"s2k-count", OPTION_TYPE_ARG, parse_opt_s2k_count},
908 &(struct argv_s) {"reset", OPTION_TYPE_NOARG, parse_opt_reset},
909 &(struct argv_s) {"cipher-iterations", OPTION_TYPE_ARG,
910 parse_save_opt_iterations},
911 &(struct argv_s) {"no-agent", OPTION_TYPE_NOARG,
912 parse_save_opt_no_agent},
913 NULL
916 cleanup_save (&client->crypto->save);
917 memcpy (&client->crypto->save.hdr, &client->crypto->hdr,
918 sizeof (file_header_t));
919 client->crypto->save.s2k_count =
920 config_get_ulong (client->filename, "s2k_count");
922 if (client->flags & FLAG_NEW)
923 client->crypto->save.hdr.iterations =
924 config_get_ulonglong (client->filename, "cipher_iterations");
926 rc = parse_options (&line, args, client);
927 if (rc)
928 return send_error (ctx, rc);
930 if (!(client->flags & FLAG_NEW))
931 client->opts &= ~OPT_NO_AGENT;
932 else if (client->opts & OPT_NO_AGENT)
934 client->crypto->save.hdr.flags &= ~PWMD_FLAG_PKCS;
935 client->crypto->hdr.flags &= ~PWMD_FLAG_PKCS;
938 if ((client->opts & OPT_NO_PASSPHRASE) && !(client->flags & FLAG_NEW)
939 && !(client->opts & OPT_INQUIRE))
940 return send_error (ctx, GPG_ERR_WRONG_KEY_USAGE);
942 if (lstat (client->filename, &st) == -1 && errno != ENOENT)
943 return send_error (ctx, gpg_error_from_syserror ());
945 if (errno != ENOENT && !S_ISREG (st.st_mode))
947 log_write ("%s: %s", client->filename, pwmd_strerror (GPG_ERR_ENOANO));
948 return send_error (ctx, GPG_ERR_ENOANO);
951 int defer;
952 rc = cache_iscached (client->filename, &defer);
953 if (!rc && defer)
955 log_write ("%s: %s", client->filename,
956 pwmd_strerror (GPG_ERR_KEY_EXPIRED));
957 client->opts |= OPT_RESET;
960 if (client->opts & OPT_RESET)
962 rc = cache_clear (client->md5file);
963 if (rc)
964 return send_error (ctx, rc);
966 send_status_all (STATUS_CACHE, NULL);
969 rc = update_element_mtime (xmlDocGetRootElement (client->doc));
970 if (rc)
971 return send_error (ctx, rc);
973 #ifdef WITH_AGENT
974 if (!rc && use_agent && !client->crypto->save.pkey &&
975 (client->flags & FLAG_NEW || client->opts & OPT_INQUIRE)
976 && !(client->opts & OPT_NO_AGENT))
978 rc = send_status (client->ctx, STATUS_GENKEY, NULL);
979 if (!rc)
981 struct inquire_data_s idata = { 0 };
982 char *params = client->opts & OPT_INQUIRE ? NULL
983 : default_key_params (client->crypto);
985 pthread_cleanup_push (xfree, params);
986 idata.crypto = client->crypto;
988 if (params)
990 idata.line = params;
991 idata.len = strlen (params);
993 else
994 idata.preset = 1;
996 client->crypto->agent->inquire_data = &idata;
997 client->crypto->agent->inquire_cb = NULL;
998 rc = generate_key (client->crypto, params,
999 (client->opts & OPT_NO_PASSPHRASE), 1);
1000 pthread_cleanup_pop (1);
1003 #endif
1005 if (!rc)
1006 rc = save_finalize (ctx);
1008 cleanup_crypto_stage1 (client->crypto);
1009 #ifdef WITH_AGENT
1010 (void) kill_scd (client->crypto->agent);
1011 #endif
1012 return send_error (ctx, rc);
1015 static gpg_error_t
1016 do_delete (assuan_context_t ctx, char *line)
1018 struct client_s *client = assuan_get_pointer (ctx);
1019 gpg_error_t rc;
1020 char **req;
1021 xmlNodePtr n;
1023 if (strchr (line, '\t'))
1024 req = str_split (line, "\t", 0);
1025 else
1026 req = str_split (line, " ", 0);
1028 if (!req || !*req)
1029 return GPG_ERR_SYNTAX;
1031 n = find_root_element (client->doc, &req, &rc, NULL, 0, 0);
1032 if (!n)
1034 strv_free (req);
1035 return rc;
1039 * No sub-node defined. Remove the entire node (root element).
1041 if (!req[1])
1043 if (n)
1045 rc = unlink_node (n);
1046 xmlFreeNode (n);
1049 strv_free (req);
1050 return rc;
1054 find_elements (client->doc, n->children, req + 1, &rc, NULL, NULL, NULL,
1055 0, 0, NULL, 0);
1056 strv_free (req);
1057 if (!n)
1058 return rc;
1060 if (n)
1062 rc = unlink_node (n);
1063 xmlFreeNode (n);
1066 return rc;
1069 static gpg_error_t
1070 delete_command (assuan_context_t ctx, char *line)
1072 struct client_s *client = assuan_get_pointer (ctx);
1073 gpg_error_t rc;
1074 struct argv_s *args[] = {
1075 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1076 NULL
1079 rc = parse_options (&line, args, client);
1080 if (rc)
1081 return send_error (ctx, rc);
1083 if (client->opts & OPT_INQUIRE)
1085 unsigned char *result;
1086 size_t len;
1088 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1089 if (rc)
1090 return send_error (ctx, rc);
1092 line = (char *) result;
1095 rc = do_delete (ctx, line);
1097 if (client->opts & OPT_INQUIRE)
1098 xfree (line);
1100 return send_error (ctx, rc);
1103 static gpg_error_t
1104 store_command (assuan_context_t ctx, char *line)
1106 struct client_s *client = assuan_get_pointer (ctx);
1107 gpg_error_t rc;
1108 size_t len;
1109 unsigned char *result;
1110 char **req;
1111 xmlNodePtr n, parent;
1112 int has_content;
1113 char *content = NULL;
1115 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1116 if (rc)
1117 return send_error (ctx, rc);
1119 req = str_split ((char *) result, "\t", 0);
1120 xfree (result);
1122 if (!req || !*req)
1123 return send_error (ctx, GPG_ERR_SYNTAX);
1125 len = strv_length (req);
1126 has_content = line[strlen (line) - 1] != '\t' && len > 1;
1127 if (*(req + 1) && !valid_element_path (req, has_content))
1129 strv_free (req);
1130 return send_error (ctx, GPG_ERR_INV_VALUE);
1133 if (has_content || !*req[len - 1])
1135 has_content = 1;
1136 content = req[len - 1];
1137 req[len - 1] = NULL;
1140 again:
1141 n = find_root_element (client->doc, &req, &rc, NULL, 0, 0);
1142 if (rc && rc == GPG_ERR_ELEMENT_NOT_FOUND)
1144 rc = new_root_element (client->doc, *req);
1145 if (rc)
1147 strv_free (req);
1148 return send_error (ctx, GPG_ERR_SYNTAX);
1151 goto again;
1154 if (!n)
1156 strv_free (req);
1157 return send_error (ctx, rc);
1160 parent = n;
1162 if (req[1] && *req[1])
1164 if (!n->children)
1165 parent = create_elements_cb (n, req + 1, &rc, NULL);
1166 else
1167 parent = find_elements (client->doc, n->children, req + 1, &rc,
1168 NULL, NULL, create_elements_cb, 0, 0, NULL,
1172 if (!rc && len > 1)
1174 n = find_text_node (parent->children);
1175 if (n)
1176 xmlNodeSetContent (n, (xmlChar *) content);
1177 else
1178 xmlNodeAddContent (parent, (xmlChar *) content);
1180 update_element_mtime (parent);
1183 xfree (content);
1184 strv_free (req);
1185 return send_error (ctx, rc);
1188 static gpg_error_t
1189 xfer_data (assuan_context_t ctx, const char *line, int total)
1191 int to_send;
1192 int sent = 0;
1193 gpg_error_t rc;
1194 int progress = config_get_integer ("global", "xfer_progress");
1195 int flush = 0;
1197 progress =
1198 progress > 0 ? (progress / ASSUAN_LINELENGTH) * ASSUAN_LINELENGTH : 0;
1199 to_send = total < ASSUAN_LINELENGTH ? total : ASSUAN_LINELENGTH;
1200 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1202 if (rc)
1203 return rc;
1205 again:
1208 if (sent + to_send > total)
1209 to_send = total - sent;
1211 rc = assuan_send_data (ctx, flush ? NULL : (char *) line + sent,
1212 flush ? 0 : to_send);
1213 if (!rc)
1215 sent += flush ? 0 : to_send;
1217 if ((progress && !(sent % progress) && sent != total) ||
1218 (sent == total && flush))
1219 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1221 if (!flush && !rc && sent == total)
1223 flush = 1;
1224 goto again;
1228 while (!rc && sent < total);
1230 return rc;
1233 static gpg_error_t
1234 do_get (assuan_context_t ctx, char *line)
1236 struct client_s *client = assuan_get_pointer (ctx);
1237 gpg_error_t rc;
1238 char **req;
1239 xmlNodePtr n;
1241 req = str_split (line, "\t", 0);
1243 if (!req || !*req)
1245 strv_free (req);
1246 return GPG_ERR_SYNTAX;
1249 n = find_root_element (client->doc, &req, &rc, NULL, 0, 0);
1250 if (!n)
1252 strv_free (req);
1253 return rc;
1256 if (req[1])
1258 find_elements (client->doc, n->children, req + 1, &rc, NULL, NULL, NULL,
1259 0, 0, NULL, 0);
1261 strv_free (req);
1262 if (rc)
1263 return rc;
1265 if (!n || !n->children)
1266 return GPG_ERR_NO_DATA;
1268 n = find_text_node (n->children);
1269 if (!n || !n->content || !*n->content)
1270 return GPG_ERR_NO_DATA;
1272 rc = xfer_data (ctx, (char *) n->content, xmlStrlen (n->content));
1273 return rc;
1276 static gpg_error_t
1277 get_command (assuan_context_t ctx, char *line)
1279 struct client_s *client = assuan_get_pointer (ctx);
1280 gpg_error_t rc;
1281 struct argv_s *args[] = {
1282 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1283 NULL
1286 rc = parse_options (&line, args, client);
1287 if (rc)
1288 return send_error (ctx, rc);
1290 if (client->opts & OPT_INQUIRE)
1292 unsigned char *result;
1293 size_t len;
1295 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1296 if (rc)
1297 return send_error (ctx, rc);
1299 line = (char *) result;
1302 rc = do_get (ctx, line);
1304 if (client->opts & OPT_INQUIRE)
1305 xfree (line);
1307 return send_error (ctx, rc);
1310 static void list_command_cleanup1 (void *arg);
1311 static gpg_error_t
1312 realpath_command (assuan_context_t ctx, char *line)
1314 struct string_s *string = NULL;
1315 gpg_error_t rc;
1316 struct client_s *client = assuan_get_pointer (ctx);
1317 struct argv_s *args[] = {
1318 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1319 NULL
1322 rc = parse_options (&line, args, client);
1323 if (rc)
1324 return send_error (ctx, rc);
1326 if (client->opts & OPT_INQUIRE)
1328 unsigned char *result;
1329 size_t len;
1331 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1332 if (rc)
1333 return send_error (ctx, rc);
1335 line = (char *) result;
1338 rc = build_realpath (client->doc, line, &string);
1339 if (!rc)
1341 pthread_cleanup_push (list_command_cleanup1, string);
1342 rc = xfer_data (ctx, string->str, string->len);
1343 pthread_cleanup_pop (1);
1346 if (client->opts & OPT_INQUIRE)
1347 xfree (line);
1349 return send_error (ctx, rc);
1352 static void
1353 list_command_cleanup1 (void *arg)
1355 if (arg)
1356 string_free ((struct string_s *) arg, 1);
1359 static void
1360 list_command_cleanup2 (void *arg)
1362 struct element_list_s *elements = arg;
1364 if (elements)
1366 if (elements->list)
1368 int total = slist_length (elements->list);
1369 int i;
1371 for (i = 0; i < total; i++)
1373 char *tmp = slist_nth_data (elements->list, i);
1374 xfree (tmp);
1377 slist_free (elements->list);
1380 if (elements->prefix)
1381 xfree (elements->prefix);
1383 if (elements->req)
1384 strv_free (elements->req);
1386 xfree (elements);
1390 static gpg_error_t
1391 parse_list_opt_norecurse (void *data, void *value)
1393 struct client_s *client = data;
1395 client->opts &= ~(OPT_LIST_RECURSE);
1396 return 0;
1399 static gpg_error_t
1400 parse_list_opt_verbose (void *data, void *value)
1402 struct client_s *client = data;
1404 client->opts |= OPT_LIST_VERBOSE;
1405 return 0;
1408 static gpg_error_t
1409 parse_list_opt_target (void *data, void *value)
1411 struct client_s *client = data;
1413 client->opts |= OPT_LIST_WITH_TARGET;
1414 return 0;
1417 static gpg_error_t
1418 parse_list_opt_all (void *data, void *value)
1420 struct client_s *client = data;
1422 client->opts |= OPT_LIST_ALL;
1423 return 0;
1426 static gpg_error_t
1427 list_path_once (struct client_s *client, char *line,
1428 struct element_list_s *elements, struct string_s *result)
1430 gpg_error_t rc;
1432 elements->req = str_split (line, " ", 0);
1433 if (!elements->req)
1434 strv_printf (&elements->req, "%s", line);
1436 rc = create_path_list (client->doc, elements, *elements->req);
1437 if (rc == GPG_ERR_ELOOP && elements->verbose)
1438 rc = 0;
1440 if (!rc)
1442 int total = slist_length (elements->list);
1443 int i;
1445 if (!total)
1446 rc = GPG_ERR_NO_DATA;
1448 if (!rc)
1450 if (!rc)
1452 for (i = 0; i < total; i++)
1454 char *tmp = slist_nth_data (elements->list, i);
1456 string_append_printf (result, "%s%s", tmp,
1457 i + 1 == total ? "" : "\n");
1461 else
1462 rc = GPG_ERR_NO_DATA;
1465 return rc;
1468 static int
1469 has_list_flag (char *path, char *flags)
1471 char *p = path;
1473 while (*p && *++p != ' ');
1475 if (!*p)
1476 return 0;
1478 for (; *p; p++)
1480 char *f;
1482 for (f = flags; *f && *f != ' '; f++)
1484 if (*p == *f)
1485 return 1;
1489 return 0;
1492 static gpg_error_t
1493 do_list (assuan_context_t ctx, char *line)
1495 struct client_s *client = assuan_get_pointer (ctx);
1496 gpg_error_t rc;
1497 struct element_list_s *elements = NULL;
1499 elements = xcalloc (1, sizeof (struct element_list_s));
1500 if (!elements)
1501 return GPG_ERR_ENOMEM;
1503 elements->recurse = client->opts & OPT_LIST_RECURSE;
1504 elements->verbose =
1505 (client->opts & OPT_LIST_VERBOSE) | (client->opts & OPT_LIST_WITH_TARGET);
1506 elements->with_target = client->opts & OPT_LIST_WITH_TARGET;
1508 if (!line || !*line)
1510 struct string_s *str = NULL;
1512 pthread_cleanup_push (list_command_cleanup2, elements);
1513 rc = list_root_elements (client->doc, &str, elements->verbose,
1514 elements->with_target);
1515 pthread_cleanup_pop (1);
1516 pthread_cleanup_push (list_command_cleanup1, str);
1518 if (!rc)
1520 if (client->opts & OPT_LIST_ALL)
1522 char **roots = str_split (str->str, "\n", 0);
1523 char **p;
1525 pthread_cleanup_push (req_cleanup, roots);
1526 string_truncate (str, 0);
1528 for (p = roots; *p; p++)
1530 if (strchr (*p, ' '))
1532 if (has_list_flag (*p, "EO"))
1534 string_append_printf (str, "%s%s", *p,
1535 *(p + 1) ? "\n" : "");
1536 continue;
1540 elements = xcalloc (1, sizeof (struct element_list_s));
1541 if (!elements)
1543 rc = GPG_ERR_ENOMEM;
1544 break;
1547 elements->recurse = client->opts & OPT_LIST_RECURSE;
1548 elements->verbose =
1549 (client->opts & OPT_LIST_VERBOSE) | (client->opts &
1550 OPT_LIST_WITH_TARGET);
1551 elements->with_target = client->opts & OPT_LIST_WITH_TARGET;
1552 pthread_cleanup_push (list_command_cleanup2, elements);
1553 rc = list_path_once (client, *p, elements, str);
1554 pthread_cleanup_pop (1);
1555 if (rc)
1556 break;
1558 if (*(p + 1))
1559 string_append (str, "\n");
1562 pthread_cleanup_pop (1);
1565 if (!rc)
1566 rc = xfer_data (ctx, str->str, str->len);
1569 pthread_cleanup_pop (1);
1570 return rc;
1573 pthread_cleanup_push (list_command_cleanup2, elements);
1574 struct string_s *str = string_new (NULL);
1575 pthread_cleanup_push (list_command_cleanup1, str);
1576 rc = list_path_once (client, line, elements, str);
1577 if (!rc)
1578 rc = xfer_data (ctx, str->str, str->len);
1580 pthread_cleanup_pop (1);
1581 pthread_cleanup_pop (1);
1582 return rc;
1585 static gpg_error_t
1586 list_command (assuan_context_t ctx, char *line)
1588 struct client_s *client = assuan_get_pointer (ctx);
1589 gpg_error_t rc;
1590 struct argv_s *args[] = {
1591 &(struct argv_s) {"no-recurse", OPTION_TYPE_NOARG,
1592 parse_list_opt_norecurse},
1593 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_list_opt_verbose},
1594 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1595 &(struct argv_s) {"with-target", OPTION_TYPE_NOARG,
1596 parse_list_opt_target},
1597 &(struct argv_s) {"all", OPTION_TYPE_NOARG, parse_list_opt_all},
1598 NULL
1601 if (disable_list_and_dump == 1)
1602 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
1604 client->opts |= OPT_LIST_RECURSE;
1605 rc = parse_options (&line, args, client);
1606 if (rc)
1607 return send_error (ctx, rc);
1609 if (client->opts & OPT_LIST_ALL)
1610 client->opts |= OPT_LIST_RECURSE | OPT_LIST_VERBOSE;
1612 if (client->opts & OPT_INQUIRE)
1614 unsigned char *result;
1615 size_t len;
1617 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1618 if (rc)
1619 return send_error (ctx, rc);
1621 line = (char *) result;
1624 rc = do_list (ctx, line);
1626 if (client->opts & OPT_INQUIRE)
1627 xfree (line);
1629 return send_error (ctx, rc);
1633 * req[0] - element path
1635 static gpg_error_t
1636 attribute_list (assuan_context_t ctx, char **req)
1638 struct client_s *client = assuan_get_pointer (ctx);
1639 char **attrlist = NULL;
1640 int i = 0;
1641 char **path = NULL;
1642 xmlAttrPtr a;
1643 xmlNodePtr n, an;
1644 char *line;
1645 gpg_error_t rc;
1647 if (!req || !req[0])
1648 return GPG_ERR_SYNTAX;
1650 if ((path = str_split (req[0], "\t", 0)) == NULL)
1653 * The first argument may be only a root element.
1655 if ((path = str_split (req[0], " ", 0)) == NULL)
1656 return GPG_ERR_SYNTAX;
1659 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
1661 if (!n)
1663 strv_free (path);
1664 return rc;
1667 if (path[1])
1669 n = find_elements (client->doc, n->children, path + 1, &rc,
1670 NULL, NULL, NULL, 0, 0, NULL, 0);
1672 if (!n)
1674 strv_free (path);
1675 return rc;
1679 strv_free (path);
1681 for (a = n->properties; a; a = a->next)
1683 char **pa;
1685 if ((pa = xrealloc (attrlist, (i + 2) * sizeof (char *))) == NULL)
1687 if (attrlist)
1688 strv_free (attrlist);
1690 log_write ("%s(%i): %s", __FILE__, __LINE__,
1691 pwmd_strerror (GPG_ERR_ENOMEM));
1692 return GPG_ERR_ENOMEM;
1695 attrlist = pa;
1696 an = a->children;
1697 attrlist[i] = str_asprintf ("%s %s", (char *) a->name,
1699 && an->content ? (char *) an->content : "");
1701 if (!attrlist[i])
1703 strv_free (attrlist);
1704 log_write ("%s(%i): %s", __FILE__, __LINE__,
1705 pwmd_strerror (GPG_ERR_ENOMEM));
1706 return GPG_ERR_ENOMEM;
1709 attrlist[++i] = NULL;
1712 if (!attrlist)
1713 return GPG_ERR_NO_DATA;
1715 line = strv_join ("\n", attrlist);
1717 if (!line)
1719 log_write ("%s(%i): %s", __FILE__, __LINE__,
1720 pwmd_strerror (GPG_ERR_ENOMEM));
1721 strv_free (attrlist);
1722 return GPG_ERR_ENOMEM;
1725 pthread_cleanup_push (xfree, line);
1726 pthread_cleanup_push (req_cleanup, attrlist);
1727 rc = xfer_data (ctx, line, strlen (line));
1728 pthread_cleanup_pop (1);
1729 pthread_cleanup_pop (1);
1730 return rc;
1734 * req[0] - attribute
1735 * req[1] - element path
1737 static gpg_error_t
1738 attribute_delete (struct client_s *client, char **req)
1740 xmlNodePtr n;
1741 char **path = NULL;
1742 gpg_error_t rc;
1744 if (!req || !req[0] || !req[1])
1745 return GPG_ERR_SYNTAX;
1747 if (!strcmp (req[0], "_name"))
1748 return GPG_ERR_INV_ATTR;
1750 if ((path = str_split (req[1], "\t", 0)) == NULL)
1753 * The first argument may be only a root element.
1755 if ((path = str_split (req[1], " ", 0)) == NULL)
1756 return GPG_ERR_SYNTAX;
1759 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
1760 if (!n)
1761 goto fail;
1763 if (path[1])
1765 n = find_elements (client->doc, n->children, path + 1, &rc,
1766 NULL, NULL, NULL, 0, 0, NULL, 0);
1767 if (!n)
1768 goto fail;
1771 rc = delete_attribute (n, (xmlChar *) req[0]);
1773 fail:
1774 strv_free (path);
1775 return rc;
1778 static xmlNodePtr
1779 create_element_path (struct client_s *client,
1780 char ***elements, gpg_error_t * rc, xmlNodePtr parent)
1782 char **req = *elements;
1783 char **req_orig = strv_dup (req);
1784 xmlNodePtr n = NULL;
1786 *rc = 0;
1788 if (!req_orig)
1790 *rc = GPG_ERR_ENOMEM;
1791 log_write ("%s(%i): %s", __FILE__, __LINE__,
1792 pwmd_strerror (GPG_ERR_ENOMEM));
1793 goto fail;
1796 again:
1797 n = find_root_element (client->doc, &req, rc, NULL, 0, 0);
1798 if (!n)
1800 if (*rc != GPG_ERR_ELEMENT_NOT_FOUND)
1801 goto fail;
1803 *rc = new_root_element (client->doc, req[0]);
1804 if (*rc)
1805 goto fail;
1807 goto again;
1809 else if (n == parent)
1811 *rc = GPG_ERR_CONFLICT;
1812 goto fail;
1815 if (req[1])
1817 if (!n->children)
1818 n = create_target_elements_cb (n, req + 1, rc, NULL);
1819 else
1820 n = find_elements (client->doc, n->children, req + 1, rc, NULL, NULL,
1821 create_target_elements_cb, 0, 0, parent, 0);
1823 if (!n)
1824 goto fail;
1827 * Reset the position of the element tree now that the elements
1828 * have been created.
1830 strv_free (req);
1831 req = req_orig;
1832 req_orig = NULL;
1833 n = find_root_element (client->doc, &req, rc, NULL, 0, 0);
1834 if (!n)
1835 goto fail;
1837 n = find_elements (client->doc, n->children, req + 1, rc,
1838 NULL, NULL, NULL, 0, 0, NULL, 0);
1839 if (!n)
1840 goto fail;
1843 fail:
1844 if (req_orig)
1845 strv_free (req_orig);
1847 *elements = req;
1848 return n;
1852 * Creates a "target" attribute. When other commands encounter an element with
1853 * this attribute, the element path is modified to the target value. If the
1854 * source element path doesn't exist when using 'ATTR SET target', it is
1855 * created, but the destination element path must exist.
1857 * req[0] - source element path
1858 * req[1] - destination element path
1860 static gpg_error_t
1861 target_attribute (struct client_s *client, char **req)
1863 char **src, **dst, *line = NULL, **odst = NULL;
1864 gpg_error_t rc;
1865 xmlNodePtr n;
1867 if (!req || !req[0] || !req[1])
1868 return GPG_ERR_SYNTAX;
1870 if ((src = str_split (req[0], "\t", 0)) == NULL)
1873 * The first argument may be only a root element.
1875 if ((src = str_split (req[0], " ", 0)) == NULL)
1876 return GPG_ERR_SYNTAX;
1879 if (!valid_element_path (src, 0))
1880 return GPG_ERR_INV_VALUE;
1882 if ((dst = str_split (req[1], "\t", 0)) == NULL)
1885 * The first argument may be only a root element.
1887 if ((dst = str_split (req[1], " ", 0)) == NULL)
1889 rc = GPG_ERR_SYNTAX;
1890 goto fail;
1894 odst = strv_dup (dst);
1895 if (!odst)
1897 rc = GPG_ERR_ENOMEM;
1898 goto fail;
1901 n = find_root_element (client->doc, &dst, &rc, NULL, 0, 0);
1903 * Make sure the destination element path exists.
1905 if (!n)
1906 goto fail;
1908 if (dst[1])
1910 n = find_elements (client->doc, n->children, dst + 1, &rc,
1911 NULL, NULL, NULL, 0, 0, NULL, 0);
1912 if (!n)
1913 goto fail;
1916 rc = validate_target_attribute (client->doc, req[0], n);
1917 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
1918 goto fail;
1920 n = create_element_path (client, &src, &rc, NULL);
1921 if (rc)
1922 goto fail;
1924 line = strv_join ("\t", odst);
1925 if (!line)
1927 rc = GPG_ERR_ENOMEM;
1928 goto fail;
1931 rc = add_attribute (n, "target", line);
1933 fail:
1934 xfree (line);
1935 strv_free (src);
1936 strv_free (dst);
1937 strv_free (odst);
1938 return rc;
1942 * req[0] - attribute
1943 * req[1] - element path
1945 static gpg_error_t
1946 attribute_get (assuan_context_t ctx, char **req)
1948 struct client_s *client = assuan_get_pointer (ctx);
1949 xmlNodePtr n;
1950 xmlChar *a;
1951 char **path = NULL;
1952 gpg_error_t rc;
1954 if (!req || !req[0] || !req[1])
1955 return GPG_ERR_SYNTAX;
1957 if (strchr (req[1], '\t'))
1959 if ((path = str_split (req[1], "\t", 0)) == NULL)
1960 return GPG_ERR_SYNTAX;
1962 else
1964 if ((path = str_split (req[1], " ", 0)) == NULL)
1965 return GPG_ERR_SYNTAX;
1968 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
1970 if (!n)
1971 goto fail;
1973 if (path[1])
1975 n = find_elements (client->doc, n->children, path + 1, &rc,
1976 NULL, NULL, NULL, 0, 0, NULL, 0);
1978 if (!n)
1979 goto fail;
1982 strv_free (path);
1984 if ((a = xmlGetProp (n, (xmlChar *) req[0])) == NULL)
1985 return GPG_ERR_NOT_FOUND;
1987 pthread_cleanup_push (xmlFree, a);
1989 if (*a)
1990 rc = xfer_data (ctx, (char *) a, xmlStrlen (a));
1991 else
1992 rc = GPG_ERR_NO_DATA;
1994 pthread_cleanup_pop (1);
1995 return rc;
1997 fail:
1998 strv_free (path);
1999 return rc;
2003 * req[0] - attribute
2004 * req[1] - element path
2005 * req[2] - value
2007 static gpg_error_t
2008 attribute_set (struct client_s *client, char **req)
2010 char **path = NULL;
2011 gpg_error_t rc;
2012 xmlNodePtr n;
2014 if (!req || !req[0] || !req[1])
2015 return GPG_ERR_SYNTAX;
2018 * Reserved attribute names.
2020 if (!strcmp (req[0], "_name"))
2021 return GPG_ERR_INV_ATTR;
2022 else if (!strcmp (req[0], "target"))
2023 return target_attribute (client, req + 1);
2025 if ((path = str_split (req[1], "\t", 0)) == NULL)
2028 * The first argument may be only a root element.
2030 if ((path = str_split (req[1], " ", 0)) == NULL)
2031 return GPG_ERR_SYNTAX;
2034 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
2036 if (!n)
2037 goto fail;
2039 if (path[1])
2041 n = find_elements (client->doc, n->children, path + 1, &rc,
2042 NULL, NULL, NULL, 0, 0, NULL, 0);
2044 if (!n)
2045 goto fail;
2048 rc = add_attribute (n, req[0], req[2]);
2050 fail:
2051 strv_free (path);
2052 return rc;
2056 * req[0] - command
2057 * req[1] - attribute name or element path if command is LIST
2058 * req[2] - element path
2059 * req[2] - element path or value
2062 static gpg_error_t
2063 do_attr (assuan_context_t ctx, char *line)
2065 struct client_s *client = assuan_get_pointer (ctx);
2066 gpg_error_t rc = 0;
2067 char **req;
2069 req = str_split (line, " ", 4);
2070 if (!req || !req[0] || !req[1])
2072 strv_free (req);
2073 return GPG_ERR_SYNTAX;
2076 pthread_cleanup_push (req_cleanup, req);
2078 if (strcasecmp (req[0], "SET") == 0)
2079 rc = attribute_set (client, req + 1);
2080 else if (strcasecmp (req[0], "GET") == 0)
2081 rc = attribute_get (ctx, req + 1);
2082 else if (strcasecmp (req[0], "DELETE") == 0)
2083 rc = attribute_delete (client, req + 1);
2084 else if (strcasecmp (req[0], "LIST") == 0)
2085 rc = attribute_list (ctx, req + 1);
2086 else
2087 rc = GPG_ERR_SYNTAX;
2089 pthread_cleanup_pop (1);
2090 return rc;
2093 static gpg_error_t
2094 attr_command (assuan_context_t ctx, char *line)
2096 struct client_s *client = assuan_get_pointer (ctx);
2097 gpg_error_t rc;
2098 struct argv_s *args[] = {
2099 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2100 NULL
2103 rc = parse_options (&line, args, client);
2104 if (rc)
2105 return send_error (ctx, rc);
2107 if (client->opts & OPT_INQUIRE)
2109 unsigned char *result;
2110 size_t len;
2112 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2113 if (rc)
2114 return send_error (ctx, rc);
2116 line = (char *) result;
2119 rc = do_attr (ctx, line);
2121 if (client->opts & OPT_INQUIRE)
2122 xfree (line);
2124 return send_error (ctx, rc);
2127 static gpg_error_t
2128 parse_iscached_opt_lock (void *data, void *value)
2130 struct client_s *client = data;
2132 (void) value;
2133 client->opts |= OPT_LOCK;
2134 return 0;
2137 static gpg_error_t
2138 iscached_command (assuan_context_t ctx, char *line)
2140 struct client_s *client = assuan_get_pointer (ctx);
2141 gpg_error_t rc;
2142 unsigned char md5file[16];
2143 struct argv_s *args[] = {
2144 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_iscached_opt_lock},
2145 NULL
2148 if (!line || !*line)
2149 return send_error (ctx, GPG_ERR_SYNTAX);
2151 rc = parse_options (&line, args, client);
2152 if (rc)
2153 return send_error (ctx, rc);
2154 else if (!valid_filename (line))
2155 return send_error (ctx, GPG_ERR_INV_VALUE);
2157 rc = cache_iscached (line, NULL);
2158 if (client->opts & OPT_LOCK
2159 && (!rc || gpg_err_code (rc) == GPG_ERR_NO_DATA))
2161 gpg_error_t trc = rc;
2162 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2163 if (memcmp (md5file, client->md5file, 16))
2164 cleanup_client (client);
2166 memcpy (client->md5file, md5file, 16);
2167 rc = do_lock (client, 1);
2168 if (!rc)
2169 rc = trc;
2172 return send_error (ctx, rc);
2175 static gpg_error_t
2176 clearcache_command (assuan_context_t ctx, char *line)
2178 gpg_error_t rc = 0, all_rc = 0;
2179 unsigned char md5file[16];
2180 int i;
2181 int t;
2182 int all = 0;
2183 struct client_thread_s *once = NULL;
2185 cache_lock ();
2186 MUTEX_LOCK (&cn_mutex);
2187 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
2189 if (!line || !*line)
2190 all = 1;
2192 t = slist_length (cn_thread_list);
2194 for (i = 0; i < t; i++)
2196 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2198 if (!thd->cl)
2199 continue;
2201 /* Lock each connected clients' file mutex to prevent any other client
2202 * from accessing the cache entry (the file mutex is locked upon
2203 * command startup). The cache for the entry is not cleared if the
2204 * file mutex is locked by another client to prevent this function
2205 * from blocking.
2207 if (all)
2209 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0, -1);
2210 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2212 if (pthread_equal (pthread_self (), thd->tid))
2213 rc = 0;
2214 else
2216 if (!thd->cl->filename ||
2217 cache_iscached (thd->cl->filename,
2218 NULL) == GPG_ERR_NO_DATA)
2220 rc = 0;
2221 continue;
2224 cache_defer_clear (thd->cl->md5file);
2227 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
2229 rc = 0;
2230 continue;
2233 if (!rc)
2235 rc = cache_clear (thd->cl->md5file);
2236 if (rc)
2237 all_rc = rc;
2239 cache_unlock_mutex (thd->cl->md5file, 0);
2241 else
2242 all_rc = rc;
2244 rc = 0;
2246 /* A single data filename was specified. Lock only this data file
2247 * mutex and free the cache entry. */
2248 else
2250 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2252 if (!memcmp (thd->cl->md5file, md5file, sizeof (md5file)))
2254 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0,
2255 -1);
2256 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2258 if (pthread_equal (pthread_self (), thd->tid))
2259 rc = 0;
2262 if (!rc)
2264 once = thd;
2265 rc = cache_clear (thd->cl->md5file);
2266 cache_unlock_mutex (thd->cl->md5file, 0);
2268 else
2270 cache_defer_clear (thd->cl->md5file);
2273 break;
2278 /* Only connected clients' cache entries have been cleared. Now clear any
2279 * remaining cache entries without clients but only if there wasn't an
2280 * error from above since this would defeat the locking check of the
2281 * remaining entries. */
2282 if (!all_rc && all)
2284 cache_clear (NULL);
2287 /* No clients are using the specified file. */
2288 else if (!all_rc && !rc && !once)
2290 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2291 rc = cache_clear (md5file);
2294 /* Release the connection mutex. */
2295 pthread_cleanup_pop (1);
2296 cache_unlock ();
2298 if (!rc)
2299 send_status_all (STATUS_CACHE, NULL);
2301 /* One or more files were locked while clearing all cache entries. */
2302 if (all_rc)
2303 rc = all_rc;
2305 return send_error (ctx, rc);
2308 static gpg_error_t
2309 cachetimeout_command (assuan_context_t ctx, char *line)
2311 unsigned char md5file[16];
2312 int timeout;
2313 char **req = str_split (line, " ", 0);
2314 char *p;
2315 gpg_error_t rc = 0;
2317 if (!req || !*req || !req[1])
2319 strv_free (req);
2320 return send_error (ctx, GPG_ERR_SYNTAX);
2323 errno = 0;
2324 timeout = (int) strtol (req[1], &p, 10);
2325 if (errno != 0 || *p || timeout < -1)
2327 strv_free (req);
2328 return send_error (ctx, GPG_ERR_SYNTAX);
2331 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, req[0], strlen (req[0]));
2332 rc = cache_set_timeout (md5file, timeout);
2333 if (!rc || gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
2335 rc = 0;
2336 MUTEX_LOCK (&rcfile_mutex);
2337 config_set_int_param (&global_config, req[0], "cache_timeout", req[1]);
2338 MUTEX_UNLOCK (&rcfile_mutex);
2341 strv_free (req);
2342 return send_error (ctx, rc);
2345 static gpg_error_t
2346 dump_command (assuan_context_t ctx, char *line)
2348 xmlChar *xml;
2349 int len;
2350 struct client_s *client = assuan_get_pointer (ctx);
2351 gpg_error_t rc;
2353 if (disable_list_and_dump == 1)
2354 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2356 xmlDocDumpFormatMemory (client->doc, &xml, &len, 1);
2358 if (!xml)
2360 log_write ("%s(%i): %s", __FILE__, __LINE__,
2361 pwmd_strerror (GPG_ERR_ENOMEM));
2362 return send_error (ctx, GPG_ERR_ENOMEM);
2365 pthread_cleanup_push (xmlFree, xml);
2366 rc = xfer_data (ctx, (char *) xml, len);
2367 pthread_cleanup_pop (1);
2368 return send_error (ctx, rc);
2371 static gpg_error_t
2372 getconfig_command (assuan_context_t ctx, char *line)
2374 struct client_s *client = assuan_get_pointer (ctx);
2375 gpg_error_t rc = 0;
2376 char filename[255] = { 0 }, param[747] =
2379 char *p, *tmp = NULL, *fp = client->filename, *paramp = line;
2381 if (!line || !*line)
2382 return send_error (ctx, GPG_ERR_SYNTAX);
2384 if (strchr (line, ' '))
2386 sscanf (line, " %254[^ ] %746c", filename, param);
2387 paramp = param;
2388 fp = filename;
2391 if (fp && !valid_filename (fp))
2392 return send_error (ctx, GPG_ERR_INV_VALUE);
2394 paramp = str_down (paramp);
2395 if (!strcmp (paramp, "cipher") && fp)
2397 struct crypto_s *crypto = NULL;
2399 rc = init_client_crypto (&crypto);
2400 if (!rc)
2402 rc = read_data_header (fp, &crypto->hdr, NULL, NULL);
2403 if (!rc)
2405 const char *t =
2406 gcry_cipher_algo_name (cipher_to_gcrypt (crypto->hdr.flags));
2407 if (t)
2409 tmp = str_dup (t);
2410 if (tmp)
2411 str_down (tmp);
2416 UPDATE_AGENT_CTX (client, crypto);
2417 cleanup_crypto (&crypto);
2418 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
2419 return send_error (ctx, rc);
2421 if (!rc && tmp)
2422 goto done;
2424 else if (!strcmp (paramp, "cipher_iterations") && fp)
2426 struct crypto_s *crypto = NULL;
2428 rc = init_client_crypto (&crypto);
2429 if (!rc)
2431 rc = read_data_header (fp, &crypto->hdr, NULL, NULL);
2432 if (!rc)
2434 tmp = str_asprintf ("%llu",
2435 (unsigned long long) crypto->hdr.
2436 iterations);
2437 if (!tmp)
2438 rc = GPG_ERR_ENOMEM;
2442 UPDATE_AGENT_CTX (client, crypto);
2443 cleanup_crypto (&crypto);
2444 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
2445 return send_error (ctx, rc);
2447 if (!rc && tmp)
2448 goto done;
2450 else if (!strcmp (paramp, "passphrase"))
2451 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2453 p = config_get_value (fp ? fp : "global", paramp);
2454 if (!p)
2455 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2457 tmp = expand_homedir (p);
2458 xfree (p);
2459 if (!tmp)
2461 log_write ("%s(%i): %s", __FILE__, __LINE__,
2462 pwmd_strerror (GPG_ERR_ENOMEM));
2463 return send_error (ctx, GPG_ERR_ENOMEM);
2466 done:
2467 p = tmp;
2468 pthread_cleanup_push (xfree, p);
2469 rc = xfer_data (ctx, p, strlen (p));
2470 pthread_cleanup_pop (1);
2471 return send_error (ctx, rc);
2474 struct xpath_s
2476 xmlXPathContextPtr xp;
2477 xmlXPathObjectPtr result;
2478 xmlBufferPtr buf;
2479 char **req;
2482 static void
2483 xpath_command_cleanup (void *arg)
2485 struct xpath_s *xpath = arg;
2487 if (!xpath)
2488 return;
2490 req_cleanup (xpath->req);
2492 if (xpath->buf)
2493 xmlBufferFree (xpath->buf);
2495 if (xpath->result)
2496 xmlXPathFreeObject (xpath->result);
2498 if (xpath->xp)
2499 xmlXPathFreeContext (xpath->xp);
2502 static gpg_error_t
2503 do_xpath (assuan_context_t ctx, char *line)
2505 gpg_error_t rc;
2506 struct client_s *client = assuan_get_pointer (ctx);
2507 struct xpath_s _x = { 0 };
2508 struct xpath_s *xpath = &_x;
2510 if ((xpath->req = str_split (line, "\t", 2)) == NULL)
2512 if (strv_printf (&xpath->req, "%s", line) == 0)
2513 return GPG_ERR_ENOMEM;
2516 xpath->xp = xmlXPathNewContext (client->doc);
2517 if (!xpath->xp)
2519 rc = GPG_ERR_BAD_DATA;
2520 goto fail;
2523 xpath->result =
2524 xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2525 if (!xpath->result)
2527 rc = GPG_ERR_BAD_DATA;
2528 goto fail;
2531 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2533 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2534 goto fail;
2537 rc = recurse_xpath_nodeset (client->doc, xpath->result->nodesetval,
2538 (xmlChar *) xpath->req[1], &xpath->buf, 0,
2539 NULL);
2540 if (rc)
2541 goto fail;
2542 else if (!xpath->req[1] && !xmlBufferLength (xpath->buf))
2544 rc = GPG_ERR_NO_DATA;
2545 goto fail;
2547 else if (xpath->req[1])
2549 rc = 0;
2550 goto fail;
2553 pthread_cleanup_push (xpath_command_cleanup, &xpath);
2554 rc = xfer_data (ctx, (char *) xmlBufferContent (xpath->buf),
2555 xmlBufferLength (xpath->buf));
2556 pthread_cleanup_pop (0);
2557 fail:
2558 xpath_command_cleanup (xpath);
2559 return rc;
2562 static gpg_error_t
2563 xpath_command (assuan_context_t ctx, char *line)
2565 struct client_s *client = assuan_get_pointer (ctx);
2566 gpg_error_t rc;
2567 struct argv_s *args[] = {
2568 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2569 NULL
2572 if (disable_list_and_dump == 1)
2573 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2575 rc = parse_options (&line, args, client);
2576 if (rc)
2577 return send_error (ctx, rc);
2579 if (client->opts & OPT_INQUIRE)
2581 unsigned char *result;
2582 size_t len;
2584 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2585 if (rc)
2586 return send_error (ctx, rc);
2588 line = (char *) result;
2591 if (!line || !*line)
2592 rc = GPG_ERR_SYNTAX;
2594 if (!rc)
2595 rc = do_xpath (ctx, line);
2597 if (client->opts & OPT_INQUIRE)
2598 xfree (line);
2600 return send_error (ctx, rc);
2603 static gpg_error_t
2604 do_xpathattr (assuan_context_t ctx, char *line)
2606 struct client_s *client = assuan_get_pointer (ctx);
2607 gpg_error_t rc;
2608 char **req = NULL;
2609 int cmd = 0; //SET
2610 struct xpath_s _x = { 0 };
2611 struct xpath_s *xpath = &_x;
2613 if ((req = str_split (line, " ", 3)) == NULL)
2614 return GPG_ERR_ENOMEM;
2616 if (!req[0])
2618 rc = GPG_ERR_SYNTAX;
2619 goto fail;
2622 if (!strcasecmp (req[0], "SET"))
2623 cmd = 0;
2624 else if (!strcasecmp (req[0], "DELETE"))
2625 cmd = 1;
2626 else
2628 rc = GPG_ERR_SYNTAX;
2629 goto fail;
2632 if (!req[1] || !req[2])
2634 rc = GPG_ERR_SYNTAX;
2635 goto fail;
2638 if ((xpath->req = str_split (req[2], "\t", 3)) == NULL)
2640 rc = GPG_ERR_ENOMEM;
2641 goto fail;
2644 if (!xpath->req[0] || (!xpath->req[1] && !cmd) || (xpath->req[1] && cmd))
2646 rc = GPG_ERR_SYNTAX;
2647 goto fail;
2650 xpath->xp = xmlXPathNewContext (client->doc);
2651 if (!xpath->xp)
2653 rc = GPG_ERR_BAD_DATA;
2654 goto fail;
2657 xpath->result =
2658 xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2659 if (!xpath->result)
2661 rc = GPG_ERR_BAD_DATA;
2662 goto fail;
2665 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2667 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2668 goto fail;
2671 rc = recurse_xpath_nodeset (client->doc, xpath->result->nodesetval,
2672 (xmlChar *) xpath->req[1], &xpath->buf, cmd,
2673 (xmlChar *) req[1]);
2675 fail:
2676 xpath_command_cleanup (xpath);
2677 strv_free (req);
2678 return rc;
2681 /* XPATHATTR SET|DELETE <name> <expression>[<TAB>[value]] */
2682 static gpg_error_t
2683 xpathattr_command (assuan_context_t ctx, char *line)
2685 struct client_s *client = assuan_get_pointer (ctx);
2686 gpg_error_t rc;
2687 struct argv_s *args[] = {
2688 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2689 NULL
2692 if (disable_list_and_dump == 1)
2693 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2695 rc = parse_options (&line, args, client);
2696 if (rc)
2697 return send_error (ctx, rc);
2699 if (client->opts & OPT_INQUIRE)
2701 unsigned char *result;
2702 size_t len;
2704 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2705 if (rc)
2706 return send_error (ctx, rc);
2708 line = (char *) result;
2711 if (!line || !*line)
2712 rc = GPG_ERR_SYNTAX;
2714 if (!rc)
2715 rc = do_xpathattr (ctx, line);
2717 if (client->opts & OPT_INQUIRE)
2718 xfree (line);
2720 return send_error (ctx, rc);
2723 static gpg_error_t
2724 do_import (struct client_s *client, unsigned char *line)
2726 char **req, **path = NULL, **path_orig = NULL, *content;
2727 xmlDocPtr doc = NULL;
2728 xmlNodePtr n, root, copy;
2729 gpg_error_t rc;
2731 req = str_split ((char *) line, "\t", 2);
2732 xfree (line);
2733 if (!req || !*req)
2734 return GPG_ERR_SYNTAX;
2736 content = req[0];
2737 path = str_split (req[1], "\t", 0);
2738 if (!content || !*content)
2740 rc = GPG_ERR_SYNTAX;
2741 goto fail;
2744 if (path && !valid_element_path (path, 0))
2746 rc = GPG_ERR_INV_VALUE;
2747 goto fail;
2750 doc = xmlReadDoc ((xmlChar *) content, NULL, "UTF-8", XML_PARSE_NOBLANKS);
2751 if (!doc)
2753 rc = GPG_ERR_BAD_DATA;
2754 goto fail;
2757 root = xmlDocGetRootElement (doc);
2758 rc = validate_import (root);
2759 if (rc)
2760 goto fail;
2762 if (path)
2764 path_orig = strv_dup (path);
2765 if (!path_orig)
2767 log_write ("%s(%i): %s", __FILE__, __LINE__,
2768 pwmd_strerror (GPG_ERR_ENOMEM));
2769 rc = GPG_ERR_ENOMEM;
2770 goto fail;
2773 xmlChar *a = xmlGetProp (root, (xmlChar *) "_name");
2774 if (!a)
2776 strv_free (path_orig);
2777 rc = GPG_ERR_ENOMEM;
2778 goto fail;
2781 if (strv_printf (&path, "%s", (char *) a) == 0)
2783 xmlFree (a);
2784 strv_free (path_orig);
2785 rc = GPG_ERR_ENOMEM;
2786 goto fail;
2789 xmlFree (a);
2790 n = find_root_element (client->doc, &path, &rc, NULL, 0, 0);
2792 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2794 strv_free (path_orig);
2795 goto fail;
2798 if (!rc)
2801 find_elements (client->doc, n->children, path + 1, &rc, NULL,
2802 NULL, NULL, 0, 0, NULL, 1);
2804 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2806 strv_free (path_orig);
2807 goto fail;
2809 else if (!rc)
2811 xmlNodePtr parent = n->parent;
2813 xmlUnlinkNode (n);
2814 xmlFreeNode (n);
2815 n = parent;
2819 strv_free (path);
2820 path = path_orig;
2822 if (rc == GPG_ERR_ELEMENT_NOT_FOUND)
2824 n = create_element_path (client, &path, &rc, NULL);
2826 if (rc)
2827 goto fail;
2830 copy = xmlCopyNodeList (root);
2831 n = xmlAddChildList (n, copy);
2832 if (!n)
2833 rc = GPG_ERR_BAD_DATA;
2835 else
2837 /* Check if the content root element can create a DTD root element. */
2838 if (!xmlStrEqual ((xmlChar *) "element", root->name))
2840 rc = GPG_ERR_SYNTAX;
2841 goto fail;
2844 xmlChar *a;
2846 if ((a = xmlGetProp (root, (xmlChar *) "_name")) == NULL)
2848 rc = GPG_ERR_SYNTAX;
2849 goto fail;
2852 char *tmp = str_dup ((char *) a);
2853 xmlFree (a);
2854 int literal = is_literal_element (&tmp);
2856 if (!valid_xml_element ((xmlChar *) tmp) || literal)
2858 xfree (tmp);
2859 rc = GPG_ERR_INV_VALUE;
2860 goto fail;
2863 if (strv_printf (&path, "%s", tmp) == 0)
2865 xfree (tmp);
2866 rc = GPG_ERR_ENOMEM;
2867 goto fail;
2870 xfree (tmp);
2871 n = find_root_element (client->doc, &path, &rc, NULL, 0, 1);
2873 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2875 rc = GPG_ERR_BAD_DATA;
2876 goto fail;
2879 /* Overwriting the existing tree. */
2880 if (!rc)
2882 xmlUnlinkNode (n);
2883 xmlFreeNodeList (n);
2886 rc = 0;
2887 xmlSetProp (root, (xmlChar *) "_name", (xmlChar *) path[0]);
2888 n = xmlCopyNode (root, 1);
2889 n = xmlAddChildList (xmlDocGetRootElement (client->doc), n);
2892 if (n && !rc)
2893 rc = update_element_mtime (n->parent);
2895 fail:
2896 if (doc)
2897 xmlFreeDoc (doc);
2899 if (path)
2900 strv_free (path);
2902 strv_free (req);
2903 return rc;
2906 static gpg_error_t
2907 import_command (assuan_context_t ctx, char *line)
2909 gpg_error_t rc;
2910 struct client_s *client = assuan_get_pointer (ctx);
2911 unsigned char *result;
2912 size_t len;
2914 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2915 if (rc)
2916 return send_error (ctx, rc);
2918 rc = do_import (client, result);
2919 return send_error (ctx, rc);
2922 static gpg_error_t
2923 do_lock (struct client_s *client, int add)
2925 gpg_error_t rc = lock_file_mutex (client, add);
2927 if (!rc)
2928 client->flags |= FLAG_LOCK_CMD;
2930 return rc;
2933 static gpg_error_t
2934 lock_command (assuan_context_t ctx, char *line)
2936 struct client_s *client = assuan_get_pointer (ctx);
2937 gpg_error_t rc = do_lock (client, 0);
2939 return send_error (ctx, rc);
2942 static gpg_error_t
2943 unlock_command (assuan_context_t ctx, char *line)
2945 struct client_s *client = assuan_get_pointer (ctx);
2946 gpg_error_t rc;
2948 rc = unlock_file_mutex (client, 0);
2949 return send_error (ctx, rc);
2952 static gpg_error_t
2953 option_command (assuan_context_t ctx, char *line)
2955 struct client_s *client = assuan_get_pointer (ctx);
2956 gpg_error_t rc = 0;
2957 struct pinentry_option_s *pin_opts = &client->pinentry_opts;
2958 #ifdef WITH_AGENT
2959 struct agent_s *agent = client->crypto->agent;
2960 #endif
2961 char namebuf[255] = { 0 };
2962 char *name = namebuf;
2963 char *value = NULL, *p;
2965 p = strchr (line, '=');
2966 if (!p)
2967 strncpy (namebuf, line, sizeof(namebuf));
2968 else
2970 strncpy (namebuf, line, strlen (line)-strlen (p));
2971 value = p+1;
2974 log_write1 ("OPTION name='%s' value='%s'", name, value);
2976 if (strcasecmp (name, (char *) "log_level") == 0)
2978 long l = 0;
2980 if (value)
2982 l = strtol (value, NULL, 10);
2984 if (l < 0 || l > 2)
2985 return send_error (ctx, GPG_ERR_INV_VALUE);
2988 MUTEX_LOCK (&rcfile_mutex);
2989 config_set_int_param (&global_config, "global", "log_level", value);
2990 MUTEX_UNLOCK (&rcfile_mutex);
2991 goto done;
2993 else if (strcasecmp (name, (char *) "lock-timeout") == 0)
2995 long n = 0;
2996 char *p = NULL;
2998 if (value)
3000 n = strtol (value, &p, 10);
3001 if (p && *p)
3002 return send_error (ctx, GPG_ERR_INV_VALUE);
3005 client->lock_timeout = n;
3006 goto done;
3008 else if (strcasecmp (name, (char *) "NAME") == 0)
3010 char *tmp = pthread_getspecific (thread_name_key);
3012 if (tmp)
3013 xfree (tmp);
3015 if (!value || !*value)
3017 pthread_setspecific (thread_name_key, str_dup (""));
3018 goto done;
3021 pthread_setspecific (thread_name_key, str_dup (value));
3022 goto done;
3024 else if (strcasecmp (name, (char *) "lc-messages") == 0)
3026 xfree (pin_opts->lc_messages);
3027 pin_opts->lc_messages = NULL;
3028 if (value && *value)
3029 pin_opts->lc_messages = str_dup (value);
3030 #ifdef WITH_AGENT
3031 if (use_agent)
3032 rc = set_agent_option (client->crypto->agent, "lc-messages", value);
3033 #endif
3035 else if (strcasecmp (name, (char *) "lc-ctype") == 0)
3037 xfree (pin_opts->lc_ctype);
3038 pin_opts->lc_ctype = NULL;
3039 if (value && *value)
3040 pin_opts->lc_ctype = str_dup (value);
3041 #ifdef WITH_AGENT
3042 if (use_agent)
3043 rc = set_agent_option (client->crypto->agent, "lc-ctype", value);
3044 #endif
3046 else if (strcasecmp (name, (char *) "ttyname") == 0)
3048 xfree (pin_opts->ttyname);
3049 pin_opts->ttyname = NULL;
3050 if (value && *value)
3051 pin_opts->ttyname = str_dup (value);
3052 #ifdef WITH_AGENT
3053 if (use_agent)
3054 rc = set_agent_option (client->crypto->agent, "ttyname", value);
3055 #endif
3057 else if (strcasecmp (name, (char *) "ttytype") == 0)
3059 xfree (pin_opts->ttytype);
3060 pin_opts->ttytype = NULL;
3061 if (value && *value)
3062 pin_opts->ttytype = str_dup (value);
3063 #ifdef WITH_AGENT
3064 if (use_agent)
3065 rc = set_agent_option (client->crypto->agent, "ttytype", value);
3066 #endif
3068 else if (strcasecmp (name, (char *) "display") == 0)
3070 xfree (pin_opts->display);
3071 pin_opts->display = NULL;
3072 if (value && *value)
3073 pin_opts->display = str_dup (value);
3074 #ifdef WITH_AGENT
3075 if (use_agent)
3076 rc = set_agent_option (client->crypto->agent, "display", value);
3077 #endif
3079 else if (strcasecmp (name, (char *) "pinentry-desc") == 0)
3081 xfree (pin_opts->desc);
3082 pin_opts->desc = NULL;
3083 if (value && *value)
3084 pin_opts->desc = str_dup (value);
3086 else if (strcasecmp (name, (char *) "pinentry-title") == 0)
3088 xfree (pin_opts->title);
3089 pin_opts->title = NULL;
3090 if (value && *value)
3091 pin_opts->title = str_dup (value);
3093 else if (strcasecmp (name, (char *) "pinentry-prompt") == 0)
3095 xfree (pin_opts->prompt);
3096 pin_opts->prompt = NULL;
3097 if (value && *value)
3098 pin_opts->prompt = str_dup (value);
3101 else if (strcasecmp (name, "pinentry-timeout") == 0)
3103 char *p = NULL;
3104 int n;
3106 if (!value)
3107 goto done;
3109 n = (int) strtol (value, &p, 10);
3111 if (*p || n < 0)
3112 return send_error (ctx, GPG_ERR_INV_VALUE);
3114 pin_opts->timeout = n;
3115 MUTEX_LOCK (&rcfile_mutex);
3116 config_set_int_param (&global_config,
3117 client->filename ? client->filename : "global",
3118 "pinentry_timeout", value);
3119 MUTEX_UNLOCK (&rcfile_mutex);
3120 goto done;
3122 else if (strcasecmp (name, "disable-pinentry") == 0)
3124 char *p = NULL;
3125 int n = 1;
3127 if (value && *value)
3129 n = (int) strtol (value, &p, 10);
3130 if (*p || n < 0 || n > 1)
3131 return send_error (ctx, GPG_ERR_INV_VALUE);
3134 if (n)
3135 client->flags |= FLAG_NO_PINENTRY;
3136 else
3137 client->flags &= ~FLAG_NO_PINENTRY;
3139 else
3140 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
3142 done:
3143 #ifdef WITH_AGENT
3144 if (!rc && use_agent && agent)
3146 rc = pinentry_merge_options (&client->crypto->agent->pinentry_opts,
3147 pin_opts);
3149 #endif
3151 return send_error (ctx, rc);
3154 static gpg_error_t
3155 do_rename (assuan_context_t ctx, char *line)
3157 struct client_s *client = assuan_get_pointer (ctx);
3158 gpg_error_t rc;
3159 char **req, **src, *dst;
3160 xmlNodePtr n, ndst;
3162 req = str_split (line, " ", 0);
3164 if (!req || !req[0] || !req[1])
3166 strv_free (req);
3167 return GPG_ERR_SYNTAX;
3170 dst = req[1];
3171 is_literal_element (&dst);
3173 if (!valid_xml_element ((xmlChar *) dst))
3175 strv_free (req);
3176 return GPG_ERR_INV_VALUE;
3179 if (strchr (req[0], '\t'))
3180 src = str_split (req[0], "\t", 0);
3181 else
3182 src = str_split (req[0], " ", 0);
3184 if (!src || !*src)
3186 rc = GPG_ERR_SYNTAX;
3187 goto fail;
3190 n = find_root_element (client->doc, &src, &rc, NULL, 0, 0);
3191 if (src[1] && n)
3192 n = find_elements (client->doc, n->children, src + 1, &rc, NULL, NULL,
3193 NULL, 0, 0, NULL, 0);
3195 if (!n)
3196 goto fail;
3198 xmlChar *a = xmlGetProp (n, (xmlChar *) "_name");
3199 if (!a)
3201 rc = GPG_ERR_ENOMEM;
3202 goto fail;
3205 /* To prevent unwanted effects:
3207 * <root name="a"><b/></root>
3209 * RENAME a<TAB>b b
3211 if (xmlStrEqual (a, (xmlChar *) dst))
3213 xmlFree (a);
3214 rc = GPG_ERR_AMBIGUOUS_NAME;
3215 goto fail;
3218 xmlFree (a);
3219 char **tmp = NULL;
3220 if (src[1])
3222 char **p;
3224 for (p = src; *p; p++)
3226 if (!*(p + 1))
3227 break;
3228 strv_printf (&tmp, "%s", *p);
3232 strv_printf (&tmp, "!%s", dst);
3233 ndst = find_root_element (client->doc, &tmp, &rc, NULL, 0, 0);
3234 if (!ndst && rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3236 strv_free (tmp);
3237 goto fail;
3240 if (tmp[1] && ndst)
3241 ndst = find_elements (client->doc, ndst->children, tmp + 1, &rc, NULL,
3242 NULL, NULL, 0, 0, NULL, 0);
3244 strv_free (tmp);
3245 if (!ndst && rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3246 goto fail;
3248 rc = 0;
3250 /* Target may exist:
3252 * <root name="a"/>
3253 * <root name="b" target="a"/>
3255 * RENAME b a
3257 * Would need to do:
3258 * RENAME !b a
3260 if (ndst == n)
3262 rc = GPG_ERR_AMBIGUOUS_NAME;
3263 goto fail;
3266 if (ndst)
3268 unlink_node (ndst);
3269 xmlFreeNodeList (ndst);
3272 rc = add_attribute (n, "_name", dst);
3274 fail:
3275 strv_free (req);
3276 strv_free (src);
3277 return rc;
3280 static gpg_error_t
3281 rename_command (assuan_context_t ctx, char *line)
3283 struct client_s *client = assuan_get_pointer (ctx);
3284 gpg_error_t rc;
3285 struct argv_s *args[] = {
3286 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3287 NULL
3290 rc = parse_options (&line, args, client);
3291 if (rc)
3292 return send_error (ctx, rc);
3294 if (client->opts & OPT_INQUIRE)
3296 unsigned char *result;
3297 size_t len;
3299 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3300 if (rc)
3301 return send_error (ctx, rc);
3303 line = (char *) result;
3306 rc = do_rename (ctx, line);
3308 if (client->opts & OPT_INQUIRE)
3309 xfree (line);
3311 return send_error (ctx, rc);
3314 static gpg_error_t
3315 do_copy (assuan_context_t ctx, char *line)
3317 struct client_s *client = assuan_get_pointer (ctx);
3318 gpg_error_t rc;
3319 char **req, **src = NULL, **dst = NULL;
3320 xmlNodePtr nsrc, ndst, new = NULL;
3322 req = str_split (line, " ", 0);
3323 if (!req || !req[0] || !req[1])
3325 strv_free (req);
3326 return GPG_ERR_SYNTAX;
3329 if (strchr (req[0], '\t'))
3330 src = str_split (req[0], "\t", 0);
3331 else
3332 src = str_split (req[0], " ", 0);
3334 if (!src || !*src)
3336 rc = GPG_ERR_SYNTAX;
3337 goto fail;
3340 if (strchr (req[1], '\t'))
3341 dst = str_split (req[1], "\t", 0);
3342 else
3343 dst = str_split (req[1], " ", 0);
3345 if (!dst || !*dst)
3347 rc = GPG_ERR_SYNTAX;
3348 goto fail;
3351 if (!valid_element_path (dst, 0))
3353 rc = GPG_ERR_INV_VALUE;
3354 goto fail;
3357 nsrc = find_root_element (client->doc, &src, &rc, NULL, 0, 0);
3358 if (nsrc && src[1])
3359 nsrc = find_elements (client->doc, nsrc->children, src + 1, &rc, NULL,
3360 NULL, NULL, 0, 0, NULL, 0);
3362 if (!nsrc)
3363 goto fail;
3365 new = xmlCopyNodeList (nsrc);
3366 if (!new)
3368 rc = GPG_ERR_ENOMEM;
3369 goto fail;
3372 int create = 0;
3373 ndst = find_root_element (client->doc, &dst, &rc, NULL, 0, 0);
3374 if (ndst && dst[1])
3376 if (ndst->children)
3377 ndst = find_elements (client->doc, ndst->children, dst + 1, &rc, NULL,
3378 NULL, create_target_elements_cb, 0, 0, NULL, 0);
3379 else
3380 create = 1;
3382 else
3383 create = 1;
3385 if (!ndst && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3386 goto fail;
3387 else if (!ndst || create)
3389 ndst = create_element_path (client, &dst, &rc, NULL);
3390 if (!ndst)
3391 goto fail;
3394 /* Merge any attributes from the src node to the initial dst node. */
3395 for (xmlAttrPtr attr = new->properties; attr; attr = attr->next)
3397 if (xmlStrEqual (attr->name, (xmlChar *) "_name"))
3398 continue;
3400 xmlAttrPtr a = xmlHasProp (ndst, attr->name);
3401 if (a)
3402 xmlRemoveProp (a);
3404 xmlChar *tmp = xmlNodeGetContent (attr->children);
3405 xmlNewProp (ndst, attr->name, tmp);
3406 xmlFree (tmp);
3407 rc = add_attribute (ndst, NULL, NULL);
3410 xmlNodePtr n = ndst->children;
3411 xmlUnlinkNode (n);
3412 xmlFreeNodeList (n);
3413 ndst->children = NULL;
3415 if (new->children)
3417 n = xmlCopyNodeList (new->children);
3418 if (!n)
3420 rc = GPG_ERR_ENOMEM;
3421 goto fail;
3424 n = xmlAddChildList (ndst, n);
3425 if (!n)
3427 rc = GPG_ERR_ENOMEM;
3428 goto fail;
3431 rc = update_element_mtime (xmlDocGetRootElement (client->doc) ==
3432 ndst->parent ? ndst : ndst->parent);
3435 fail:
3436 if (new)
3438 xmlUnlinkNode (new);
3439 xmlFreeNodeList (new);
3442 if (req)
3443 strv_free (req);
3445 if (src)
3446 strv_free (src);
3448 if (dst)
3449 strv_free (dst);
3451 return rc;
3454 static gpg_error_t
3455 copy_command (assuan_context_t ctx, char *line)
3457 struct client_s *client = assuan_get_pointer (ctx);
3458 gpg_error_t rc;
3459 struct argv_s *args[] = {
3460 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3461 NULL
3464 rc = parse_options (&line, args, client);
3465 if (rc)
3466 return send_error (ctx, rc);
3468 if (client->opts & OPT_INQUIRE)
3470 unsigned char *result;
3471 size_t len;
3473 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3474 if (rc)
3475 return send_error (ctx, rc);
3477 line = (char *) result;
3480 rc = do_copy (ctx, line);
3482 if (client->opts & OPT_INQUIRE)
3483 xfree (line);
3485 return send_error (ctx, rc);
3488 static gpg_error_t
3489 do_move (assuan_context_t ctx, char *line)
3491 struct client_s *client = assuan_get_pointer (ctx);
3492 gpg_error_t rc;
3493 char **req, **src = NULL, **dst = NULL;
3494 xmlNodePtr nsrc, ndst = NULL;
3496 req = str_split (line, " ", 0);
3498 if (!req || !req[0] || !req[1])
3500 strv_free (req);
3501 return GPG_ERR_SYNTAX;
3504 if (strchr (req[0], '\t'))
3505 src = str_split (req[0], "\t", 0);
3506 else
3507 src = str_split (req[0], " ", 0);
3509 if (!src || !*src)
3511 rc = GPG_ERR_SYNTAX;
3512 goto fail;
3515 if (strchr (req[1], '\t'))
3516 dst = str_split (req[1], "\t", 0);
3517 else
3518 dst = str_split (req[1], " ", 0);
3520 nsrc = find_root_element (client->doc, &src, &rc, NULL, 0, 0);
3521 if (nsrc && src[1])
3522 nsrc = find_elements (client->doc, nsrc->children, src + 1, &rc, NULL,
3523 NULL, NULL, 0, 0, NULL, 0);
3525 if (!nsrc)
3526 goto fail;
3528 if (dst)
3530 if (!valid_element_path (dst, 0))
3532 rc = GPG_ERR_INV_VALUE;
3533 goto fail;
3536 ndst = find_root_element (client->doc, &dst, &rc, NULL, 0, 0);
3537 if (ndst && dst[1])
3538 ndst = find_elements (client->doc, ndst->children, dst + 1, &rc, NULL,
3539 NULL, NULL, 0, 0, NULL, 0);
3541 else
3542 ndst = xmlDocGetRootElement (client->doc);
3544 for (xmlNodePtr n = ndst; n; n = n->parent)
3546 if (n == nsrc)
3548 rc = GPG_ERR_CONFLICT;
3549 goto fail;
3553 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3554 goto fail;
3556 rc = 0;
3558 if (ndst)
3560 xmlChar *a = node_has_attribute (nsrc, (xmlChar *) "_name");
3561 xmlNodePtr dup = find_element (ndst->children, (char *) a, NULL);
3563 xmlFree (a);
3564 if (dup)
3566 if (dup == nsrc)
3567 goto fail;
3569 if (ndst == xmlDocGetRootElement (client->doc))
3571 xmlNodePtr n = nsrc;
3572 int match = 0;
3574 while (n->parent && n->parent != ndst)
3575 n = n->parent;
3577 xmlChar *a = node_has_attribute (n, (xmlChar *) "_name");
3578 xmlChar *b = node_has_attribute (nsrc, (xmlChar *) "_name");
3580 if (xmlStrEqual (a, b))
3582 match = 1;
3583 xmlUnlinkNode (nsrc);
3584 xmlUnlinkNode (n);
3585 xmlFreeNodeList (n);
3588 xmlFree (a);
3589 xmlFree (b);
3591 if (!match)
3593 xmlUnlinkNode (dup);
3594 xmlFreeNodeList (dup);
3597 else
3598 xmlUnlinkNode (dup);
3602 if (!ndst && dst)
3604 xmlChar *name = node_has_attribute (nsrc, (xmlChar *) "_name");
3606 if (nsrc->parent == xmlDocGetRootElement (client->doc)
3607 && !strcmp ((char *) name, *dst))
3609 xmlFree (name);
3610 rc = GPG_ERR_CONFLICT;
3611 goto fail;
3614 xmlFree (name);
3615 ndst = create_element_path (client, &dst, &rc, nsrc);
3618 if (!ndst)
3619 goto fail;
3621 update_element_mtime (nsrc->parent);
3622 xmlUnlinkNode (nsrc);
3623 ndst = xmlAddChildList (ndst, nsrc);
3625 if (!ndst)
3626 rc = GPG_ERR_ENOMEM;
3627 else
3628 update_element_mtime (ndst->parent);
3630 fail:
3631 if (req)
3632 strv_free (req);
3634 if (src)
3635 strv_free (src);
3637 if (dst)
3638 strv_free (dst);
3640 return rc;
3643 static gpg_error_t
3644 move_command (assuan_context_t ctx, char *line)
3646 struct client_s *client = assuan_get_pointer (ctx);
3647 gpg_error_t rc;
3648 struct argv_s *args[] = {
3649 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3650 NULL
3653 rc = parse_options (&line, args, client);
3654 if (rc)
3655 return send_error (ctx, rc);
3657 if (client->opts & OPT_INQUIRE)
3659 unsigned char *result;
3660 size_t len;
3662 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3663 if (rc)
3664 return send_error (ctx, rc);
3666 line = (char *) result;
3669 rc = do_move (ctx, line);
3671 if (client->opts & OPT_INQUIRE)
3672 xfree (line);
3674 return send_error (ctx, rc);
3677 static gpg_error_t
3678 ls_command (assuan_context_t ctx, char *line)
3680 gpg_error_t rc;
3681 char *tmp = str_asprintf ("%s/data", homedir);
3682 char *dir = expand_homedir (tmp);
3683 DIR *d = opendir (dir);
3685 rc = gpg_error_from_syserror ();
3686 xfree (tmp);
3688 if (!d)
3690 xfree (dir);
3691 return send_error (ctx, rc);
3694 size_t len =
3695 offsetof (struct dirent, d_name) +pathconf (dir, _PC_NAME_MAX) + 1;
3696 struct dirent *p = xmalloc (len), *cur = NULL;
3697 char *list = NULL;
3699 xfree (dir);
3700 rc = 0;
3702 while (!readdir_r (d, p, &cur) && cur)
3704 if (cur->d_name[0] == '.' && cur->d_name[1] == '\0')
3705 continue;
3706 else if (cur->d_name[0] == '.' && cur->d_name[1] == '.'
3707 && cur->d_name[2] == '\0')
3708 continue;
3710 tmp = str_asprintf ("%s%s\n", list ? list : "", cur->d_name);
3712 if (!tmp)
3714 if (list)
3715 xfree (list);
3717 rc = GPG_ERR_ENOMEM;
3718 break;
3721 xfree (list);
3722 list = tmp;
3725 closedir (d);
3726 xfree (p);
3728 if (rc)
3729 return send_error (ctx, rc);
3731 if (!list)
3732 return send_error (ctx, GPG_ERR_NO_DATA);
3734 list[strlen (list) - 1] = 0;
3735 rc = xfer_data (ctx, list, strlen (list));
3736 xfree (list);
3737 return send_error (ctx, rc);
3740 static gpg_error_t
3741 bye_notify (assuan_context_t ctx, char *line)
3743 struct client_s *cl = assuan_get_pointer (ctx);
3745 #ifdef WITH_GNUTLS
3746 if (cl->thd->remote)
3748 int rc;
3752 struct timeval tv = { 0, 50000 };
3754 rc = gnutls_bye (cl->thd->tls->ses, GNUTLS_SHUT_RDWR);
3755 if (rc == GNUTLS_E_AGAIN)
3756 select (0, NULL, NULL, NULL, &tv);
3758 while (rc == GNUTLS_E_AGAIN);
3760 #endif
3762 /* This will let assuan_process_next() return. */
3763 fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK);
3764 cl->last_rc = 0; // BYE command result
3765 return 0;
3768 static gpg_error_t
3769 reset_notify (assuan_context_t ctx, char *line)
3771 struct client_s *client = assuan_get_pointer (ctx);
3773 if (client)
3774 cleanup_client (client);
3776 return 0;
3780 * This is called before every Assuan command.
3782 static gpg_error_t
3783 command_startup (assuan_context_t ctx, const char *name)
3785 struct client_s *client = assuan_get_pointer (ctx);
3786 gpg_error_t rc;
3787 struct command_table_s *cmd = NULL;
3789 log_write1 ("command='%s'", name);
3790 client->last_rc = client->opts = 0;
3792 for (int i = 0; command_table[i]; i++)
3794 if (!strcasecmp (name, command_table[i]->name))
3796 if (command_table[i]->ignore_startup)
3797 return 0;
3798 cmd = command_table[i];
3799 break;
3803 client->last_rc = rc = gpg_error (file_modified (client, cmd));
3804 return rc;
3808 * This is called after every Assuan command.
3810 static void
3811 command_finalize (assuan_context_t ctx, gpg_error_t rc)
3813 struct client_s *client = assuan_get_pointer (ctx);
3815 if (!(client->flags & FLAG_LOCK_CMD))
3816 unlock_file_mutex (client, 0);
3818 log_write1 (_("command completed: rc=%u"), client->last_rc);
3819 client->last_rc = gpg_error (GPG_ERR_UNKNOWN_COMMAND);
3822 static gpg_error_t
3823 help_command (assuan_context_t ctx, char *line)
3825 gpg_error_t rc;
3826 int i;
3828 if (!line || !*line)
3830 char *tmp;
3831 char *help = str_dup (_("Usage: HELP [<COMMAND>]\n"
3832 "For commands that take an element path as an argument, each element is "
3833 "separated with an ASCII @key{TAB} character (ASCII 0x09)."
3834 "\n" "COMMANDS:"));
3836 for (i = 0; command_table[i]; i++)
3838 if (!command_table[i]->help)
3839 continue;
3841 tmp = str_asprintf ("%s %s", help, command_table[i]->name);
3842 xfree (help);
3843 help = tmp;
3846 tmp = strip_texi_and_wrap (help);
3847 xfree (help);
3848 rc = xfer_data (ctx, tmp, strlen (tmp));
3849 xfree (tmp);
3850 return send_error (ctx, rc);
3853 for (i = 0; command_table[i]; i++)
3855 if (!strcasecmp (line, command_table[i]->name))
3857 char *help, *tmp;
3859 if (!command_table[i]->help)
3860 break;
3862 help = strip_texi_and_wrap (command_table[i]->help);
3863 tmp = str_asprintf (_("Usage: %s"), help);
3864 xfree (help);
3865 rc = xfer_data (ctx, tmp, strlen (tmp));
3866 xfree (tmp);
3867 return send_error (ctx, rc);
3871 return send_error (ctx, GPG_ERR_INV_NAME);
3874 static void
3875 new_command (const char *name, int ignore, int unlock,
3876 gpg_error_t (*handler) (assuan_context_t, char *),
3877 const char *help)
3879 int i = 0;
3881 if (command_table)
3882 for (i = 0; command_table[i]; i++);
3884 command_table =
3885 xrealloc (command_table, (i + 2) * sizeof (struct command_table_s *));
3886 command_table[i] = xcalloc (1, sizeof (struct command_table_s));
3887 command_table[i]->name = name;
3888 command_table[i]->handler = handler;
3889 command_table[i]->ignore_startup = ignore;
3890 command_table[i]->unlock = unlock;
3891 command_table[i++]->help = help;
3892 command_table[i] = NULL;
3895 void
3896 deinit_commands ()
3898 int i;
3900 for (i = 0; command_table[i]; i++)
3901 xfree (command_table[i]);
3903 xfree (command_table);
3906 static int
3907 sort_commands (const void *arg1, const void *arg2)
3909 struct command_table_s *const *a = arg1;
3910 struct command_table_s *const *b = arg2;
3912 if (!*a || !*b)
3913 return 0;
3914 else if (*a && !*b)
3915 return 1;
3916 else if (!*a && *b)
3917 return -1;
3919 return strcmp ((*a)->name, (*b)->name);
3922 static gpg_error_t
3923 passwd_command (assuan_context_t ctx, char *line)
3925 struct client_s *client = assuan_get_pointer (ctx);
3926 gpg_error_t rc;
3927 struct argv_s *args[] = {
3928 &(struct argv_s) {"reset", OPTION_TYPE_NOARG, parse_opt_reset},
3929 &(struct argv_s) {"s2k-count", OPTION_TYPE_ARG, parse_opt_s2k_count},
3930 NULL
3933 if (client->flags & FLAG_NEW)
3934 return send_error (ctx, GPG_ERR_INV_STATE);
3936 client->crypto->save.s2k_count =
3937 config_get_ulong (client->filename, "s2k_count");
3938 rc = parse_options (&line, args, client);
3939 if (rc)
3940 return send_error (ctx, rc);
3942 if (!rc && client->opts & OPT_RESET)
3944 rc = cache_clear (client->md5file);
3945 if (!rc)
3946 send_status_all (STATUS_CACHE, NULL);
3949 if (!rc)
3951 if (!IS_PKCS (client->crypto))
3953 struct crypto_s *crypto;
3955 xfree (client->crypto->filename);
3956 client->crypto->filename = str_dup (client->filename);
3957 rc = change_passwd (ctx, client->filename,
3958 client->flags & FLAG_NO_PINENTRY, &crypto);
3959 if (!rc)
3961 cleanup_crypto (&client->crypto);
3962 client->crypto = crypto;
3963 update_checksum (client);
3964 cleanup_crypto_stage1 (client->crypto);
3967 #ifdef WITH_AGENT
3968 else
3970 if (client->crypto->save.s2k_count)
3971 rc = send_to_agent (client->crypto->agent, NULL, NULL,
3972 "OPTION s2k-count=%lu",
3973 client->crypto->save.s2k_count);
3975 if (!rc)
3976 rc = agent_passwd (client->crypto);
3978 #endif
3981 return send_error (ctx, rc);
3984 static gpg_error_t
3985 parse_keygrip_opt_sign (void *data, void *value)
3987 struct client_s *client = data;
3989 (void) value;
3990 client->opts |= OPT_SIGN;
3991 return 0;
3994 static gpg_error_t
3995 keygrip_command (assuan_context_t ctx, char *line)
3997 struct client_s *client = assuan_get_pointer (ctx);
3998 gpg_error_t rc;
3999 struct crypto_s *crypto = NULL;
4000 struct argv_s *args[] = {
4001 &(struct argv_s) {"sign", OPTION_TYPE_NOARG, parse_keygrip_opt_sign},
4002 NULL
4005 if (!line || !*line)
4006 return send_error (ctx, GPG_ERR_SYNTAX);
4008 rc = parse_options (&line, args, client);
4009 if (rc)
4010 return send_error (ctx, rc);
4012 if (!valid_filename (line))
4013 return send_error (ctx, GPG_ERR_INV_VALUE);
4015 rc = init_client_crypto (&crypto);
4016 if (rc)
4017 return send_error (ctx, rc);
4019 rc = read_data_file (line, crypto);
4020 if (!rc)
4022 char *hexgrip = NULL;
4024 if (!IS_PKCS (crypto))
4026 cleanup_crypto (&crypto);
4027 return send_error (ctx, GPG_ERR_NOT_SUPPORTED);
4030 if (client->opts & OPT_SIGN)
4032 if (valid_keygrip (crypto->sign_grip, sizeof (crypto->sign_grip)))
4033 hexgrip = bin2hex (crypto->sign_grip, sizeof (crypto->sign_grip));
4036 if (!hexgrip)
4037 hexgrip = bin2hex (crypto->grip, sizeof (crypto->grip));
4039 if (!hexgrip)
4040 rc = GPG_ERR_ENOMEM;
4041 else
4042 rc = xfer_data (ctx, hexgrip, strlen (hexgrip));
4044 xfree (hexgrip);
4047 UPDATE_AGENT_CTX (client, crypto);
4048 cleanup_crypto (&crypto);
4049 return send_error (ctx, rc);
4052 static gpg_error_t
4053 parse_opt_data (void *data, void *value)
4055 struct client_s *client = data;
4057 (void) value;
4058 client->opts |= OPT_DATA;
4059 return 0;
4062 static gpg_error_t
4063 getinfo_command (assuan_context_t ctx, char *line)
4065 struct client_s *client = assuan_get_pointer (ctx);
4066 gpg_error_t rc;
4067 char buf[ASSUAN_LINELENGTH];
4068 struct argv_s *args[] = {
4069 &(struct argv_s) {"data", OPTION_TYPE_NOARG, parse_opt_data},
4070 NULL
4073 rc = parse_options (&line, args, client);
4074 if (rc)
4075 return send_error (ctx, rc);
4077 if (!strcasecmp (line, "clients"))
4079 if (client->opts & OPT_DATA)
4081 MUTEX_LOCK (&cn_mutex);
4082 snprintf (buf, sizeof (buf), "%i", slist_length (cn_thread_list));
4083 MUTEX_UNLOCK (&cn_mutex);
4084 rc = xfer_data (ctx, buf, strlen (buf));
4086 else
4087 rc = send_status (ctx, STATUS_CLIENTS, NULL);
4089 else if (!strcasecmp (line, "cache"))
4091 if (client->opts & OPT_DATA)
4093 snprintf (buf, sizeof (buf), "%u", cache_file_count ());
4094 rc = xfer_data (ctx, buf, strlen (buf));
4096 else
4097 rc = send_status (ctx, STATUS_CACHE, NULL);
4099 else if (!strcasecmp (line, "pid"))
4101 char buf[32];
4102 pid_t pid = getpid ();
4104 snprintf (buf, sizeof (buf), "%i", pid);
4105 rc = xfer_data (ctx, buf, strlen (buf));
4107 else if (!strcasecmp (line, "version"))
4109 char *buf = str_asprintf ("0x%06x %s%s", VERSION_HEX,
4110 #ifdef WITH_LIBACL
4111 "ACL "
4112 #endif
4113 #ifdef WITH_GNUTLS
4114 "GNUTLS "
4115 #endif
4116 #ifdef WITH_QUALITY
4117 "QUALITY "
4118 #endif
4119 "", use_agent ? "AGENT" : "");
4120 rc = xfer_data (ctx, buf, strlen (buf));
4121 xfree (buf);
4123 else if (!strcasecmp (line, "last_error"))
4125 if (client->last_error)
4126 rc = xfer_data (ctx, client->last_error, strlen (client->last_error));
4127 else
4128 rc = GPG_ERR_NO_DATA;
4130 else
4131 rc = gpg_error (GPG_ERR_SYNTAX);
4133 return send_error (ctx, rc);
4136 #ifdef WITH_AGENT
4137 static gpg_error_t
4138 send_data_cb (void *user, const void *buf, size_t len)
4140 assuan_context_t ctx = user;
4142 return assuan_send_data (ctx, buf, len);
4145 static gpg_error_t
4146 send_status_cb (void *user, const char *line)
4148 assuan_context_t ctx = user;
4149 char keyword[200], *k;
4150 const char *p;
4152 for (p = line, k = keyword; *p; p++)
4154 if (isspace (*p))
4155 break;
4157 *k++ = *p;
4160 *k = 0;
4161 if (*p == '#')
4162 p++;
4164 while (isspace (*p))
4165 p++;
4167 return assuan_write_status (ctx, keyword, *p ? p : NULL);
4169 #endif
4171 static gpg_error_t
4172 agent_command (assuan_context_t ctx, char *line)
4174 gpg_error_t rc = 0;
4176 if (!use_agent)
4177 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
4179 #ifdef WITH_AGENT
4180 struct client_s *client = assuan_get_pointer (ctx);
4182 if (!line || !*line)
4183 return send_error (ctx, GPG_ERR_SYNTAX);
4185 assuan_set_flag (client->crypto->agent->ctx, ASSUAN_CONVEY_COMMENTS, 1);
4186 rc = assuan_transact (client->crypto->agent->ctx, line, send_data_cb,
4187 client->ctx, agent_loopback_cb, client->crypto,
4188 send_status_cb, client->ctx);
4189 if (gpg_err_code (rc) == GPG_ERR_ASS_CANCELED)
4191 char *line;
4192 size_t len;
4194 rc = assuan_write_line (client->crypto->agent->ctx, "CAN");
4195 if (!rc)
4197 rc = assuan_read_line (client->crypto->agent->ctx, &line, &len);
4198 if (!rc)
4199 rc = gpg_error (GPG_ERR_ASS_CANCELED);
4203 assuan_set_flag (client->crypto->agent->ctx, ASSUAN_CONVEY_COMMENTS, 0);
4204 #endif
4205 return send_error (ctx, rc);
4208 void
4209 init_commands ()
4211 /* !BEGIN-HELP-TEXT!
4213 * This comment is used as a marker to generate the offline documentation
4214 * found in doc/pwmd.info. The indentation needs to be kept for the awk
4215 * script to determine where commands begin and end.
4217 new_command("HELP", 1, 1, help_command, _(
4218 "HELP [<COMMAND>]\n"
4219 "Show available commands or command specific help text."
4222 new_command("AGENT", 1, 1, agent_command, _(
4223 "AGENT <command>\n"
4224 "Send a @command{gpg-agent} protocol @var{command} directly to the "
4225 "@command{gpg-agent}."
4228 new_command("GETINFO", 1, 1, getinfo_command, _(
4229 "GETINFO [--data] CACHE | CLIENTS | PID | LAST_ERROR | VERSION\n"
4230 "Get server and other information: @var{cache} returns the number of cached "
4231 "documents via a status message. @var{clients} returns the number of "
4232 "connected clients via a status message. @var{pid} returns the process ID "
4233 "number of the server via a data response. @var{VERSION} returns the server "
4234 "version number and compile-time features with a data response with each "
4235 "being space delimited. @var{LAST_ERROR} returns a detailed description of "
4236 "the last failed command when available. @xref{Status Messages}. "
4237 "\n"
4238 "When the @option{--data} option is specified then the result will be sent "
4239 "via a data response rather than a status message."
4242 new_command("PASSWD", 0, 0, passwd_command, _(
4243 "PASSWD [--reset] [--s2k-count=N]\n"
4244 "Changes the passphrase of the secret key required to open the current "
4245 "file or the passphrase of a symmetrically encrypted data file. When the "
4246 "@option{--reset} option is passed then the cache entry for the current "
4247 "file will be reset and the passphrase, if any, will be required during the "
4248 "next @code{OPEN}. @xref{OPEN}."
4249 "\n"
4250 "The @option{--s2k-count} option sets number of hash iterations for a "
4251 "passphrase and must be either @code{0} to use the calibrated count of the "
4252 "machine (the default), or a value greater than or equal to @code{65536}. "
4253 "@xref{SAVE}. This option has no effect for symmetrically encrypted data "
4254 "files."
4257 new_command("KEYGRIP", 1, 1, keygrip_command, _(
4258 "KEYGRIP [--sign] <filename>\n"
4259 "Returns the hex encoded keygrip of the specified @var{filename} with a "
4260 "data response."
4261 "\n"
4262 "When the @option{--sign} option is specified then the key used for signing "
4263 "of the specified @var{filename} will be returned."
4264 "\n"
4265 "For symmetrically encrypted data files this command returns the error "
4266 "GPG_ERR_NOT_SUPPORTED."
4269 new_command("OPEN", 1, 1, open_command, _(
4270 "OPEN [--lock] <filename> [<passphrase>]\n"
4271 "Opens @var{filename} using @var{passphrase}. When the filename is not "
4272 "found on the file-system then a new document will be created. If the file "
4273 "is found, it is looked for in the file cache. If cached and no "
4274 "@var{passphrase} was specified then the cached document is opened. When not "
4275 "cached, @cite{pinentry(1)} will be used to retrieve the passphrase to use "
4276 "for decryption unless @option{disable-pinentry} (@pxref{OPTION}) was "
4277 "specified."
4278 "\n"
4279 "When the @option{--lock} option is passed then the file mutex will be "
4280 "locked as if the @code{LOCK} command (@pxref{LOCK}) had been sent after the "
4281 "file has been opened."
4284 new_command("SAVE", 0, 0, save_command, _(
4285 "SAVE [--no-passphrase] [--reset] [--no-agent] [--s2k-count=N] [--cipher=<algo>] [--cipher-iterations=N] [--inquire-keyparam] [--keygrip=hexstring [--sign-keygrip=hexstring]]\n"
4286 "Writes the @abbr{XML} document to disk. The file written to is the file that "
4287 "was opened using the @code{OPEN} command (@pxref{OPEN}). If the file is a "
4288 "new one or the option @option{--inquire-keyparam} was passed, then a new "
4289 "keypair will be generated and a pinentry will be used to prompt for the "
4290 "passphrase to encrypt with unless the @option{--no-passphrase} option was "
4291 "passed, in which case the data file will not be passphrase protected."
4292 "\n"
4293 "The @option{--no-agent} option disables use of @command{gpg-agent} for "
4294 "passphrase retrieval and caching of new files and behaves as if the "
4295 "@option{--no-agent} commmand line option to @command{pwmd} was specified."
4296 "The datafile will be symmetrically encrypted and will not use or generate "
4297 "any keypair."
4298 "\n"
4299 "The @option{--reset} option will clear the cache entry for the current file "
4300 "and require a passphrase, if needed, before saving."
4301 "\n"
4302 "The @option{--cipher} option can be used to encrypt the @abbr{XML} data to "
4303 "an alternate cipher. The default is @code{aes256}. See the Configuration "
4304 "(@pxref{Configuration}) for available ciphers."
4305 "\n"
4306 "The @option{--cipher-iterations} option specifies the number of times to "
4307 "encrypt the XML data. The default is 0 although 1 iteration is still done."
4308 "\n"
4309 "The @option{--inquire-keyparam} option will send a server @emph{INQUIRE} to "
4310 "the client to obtain the key paramaters to use when generating a new "
4311 "keypair. The inquired data is expected to be an S-expression. If not "
4312 "specified then an @samp{RSA} key of @samp{2048} bits will be generated "
4313 "unless otherwise set in the configuration file (@pxref{Configuration}). Note "
4314 "that when this option is specified a new keypair will be generated "
4315 "reguardless if the file is a new one or not."
4316 "\n"
4317 "You can encrypt the data file to a public key other than the one that it "
4318 "was originally encrypted with by passing the @option{--keygrip} option with "
4319 "the hex encoded keygrip of the public key as its argument. The keygrip may "
4320 "be of any key that @command{gpg-agent} knows about. The "
4321 "@option{--sign-keygrip} option may also be used to sign with an alternate "
4322 "secret key. This option may be needed when using a smartcard. This option "
4323 "has no effect with symmetrically encrypted data files."
4324 "\n"
4325 "The @option{--s2k-count} option sets number of hash iterations for a "
4326 "passphrase. A value less-than @code{65536} will use the machine calibrated "
4327 "value which is the default. This setting only affects new files. To change "
4328 "the setting, use the @code{PASSWD} command (@pxref{PASSWD}). This option "
4329 "has no effect with symmetrically encrypted data files."
4332 new_command("ISCACHED", 1, 0, iscached_command, _(
4333 "ISCACHED [--lock] <filename>\n"
4334 "An @emph{OK} response is returned if the specified @var{filename} is found "
4335 "in the file cache. If not found in the cache but exists on the filesystem "
4336 "then @var{GPG_ERR_NO_DATA} is returned. Otherwise a filesystem error is "
4337 "returned."
4338 "\n"
4339 "The @option{lock} option will lock the file mutex of @var{filename} when the "
4340 "file exists; it does not need to be opened nor cached."
4343 new_command("CLEARCACHE", 1, 1, clearcache_command, _(
4344 "CLEARCACHE [<filename>]\n"
4345 "Clears a file cache entry for all or the specified @var{filename}."
4348 new_command("CACHETIMEOUT", 1, 1, cachetimeout_command, _(
4349 "CACHETIMEOUT <filename> <seconds>\n"
4350 "The time in @var{seconds} until @var{filename} will be removed from the "
4351 "cache. @code{-1} will keep the cache entry forever, @code{0} will require "
4352 "the passphrase for each @code{OPEN} or @code{SAVE} command (@pxref{OPEN}, "
4353 "@pxref{SAVE}). @xref{Configuration}, and the @code{cache_timeout} "
4354 "parameter."
4357 new_command("LIST", 0, 1, list_command, _(
4358 "LIST [--inquire] [--no-recurse] [--verbose] [--with-target] [--all] [[!]element[<TAB>[!]child[..]]]\n"
4359 "If no element path is given then a newline separated list of root elements "
4360 "is returned with a data response. If given, then all reachable elements "
4361 "of the specified element path are returned unless the @option{--no-recurse} "
4362 "option is specified. If specified, only the child elements of the element "
4363 "path are returned without recursing into grandchildren. Each resulting "
4364 "element is prefixed with the literal @code{!} character when the element "
4365 "contains no @code{target} attribute. @xref{Target Attribute}, for details."
4366 "\n"
4367 "When the @option{--verbose} option is passed then each element path "
4368 "returned will have zero or more flags appened to it. These flags are "
4369 "delimited from the element path by a single space character. A flag itself "
4370 "is a single character. Flag @code{+} indicates that there are child nodes of "
4371 "the current element path. Flag @code{E} indicates that an element of an "
4372 "element path contained in a @var{target} attribute could not be found. Flag "
4373 "@code{O} indicates that a @var{target} attribute recursion limit was reached "
4374 "(@pxref{Configuration}). Flag @code{T} will append the resolved element path "
4375 "of the @var{target} attribute contained in the current element (see below)."
4376 "\n"
4377 "The @option{--with-target} option implies @option{--verbose} and will append "
4378 "an additional flag @code{T} followed by a single space then an element path. "
4379 "The appended element path is the resolved path (@pxref{REALPATH}) of the "
4380 "current element when it contains a @var{target} attribute. When no "
4381 "@var{target} attribute is found then no flag will be appended."
4382 "\n"
4383 "The @option{--no-recurse} option limits the amount of data returned to only "
4384 "the listing of children of the specified element path and not any "
4385 "grandchildren."
4386 "\n"
4387 "The @option{--all} option lists the entire element tree for each root "
4388 "element. This option also implies option @option{--verbose}."
4389 "\n"
4390 "When the @option{--inquire} option is passed then all remaining non-option "
4391 "arguments are retrieved via a server @emph{INQUIRE}."
4394 new_command("REALPATH", 0, 1, realpath_command, _(
4395 "REALPATH [--inquire] [!]element[<TAB>[!]child[..]]\n"
4396 "Resolves all @code{target} attributes of the specified element path and "
4397 "returns the result with a data response. @xref{Target Attribute}, for details."
4398 "\n"
4399 "When the @option{--inquire} option is passed then all remaining non-option "
4400 "arguments are retrieved via a server @emph{INQUIRE}."
4403 new_command("STORE", 0, 1, store_command, _(
4404 "STORE [!]element[<TAB>[!]child[..]]<TAB>[content]\n"
4405 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
4406 "\n"
4407 "Creates a new element path or modifies the @var{content} of an existing "
4408 "element. If only a single element is specified then a new root element is "
4409 "created. Otherwise, elements are @key{TAB} delimited and the content will be "
4410 "set to the final @key{TAB} delimited element. If no @var{content} is "
4411 "specified after the final @key{TAB}, then the content of the element will "
4412 "be removed, or empty when creating a new element."
4413 "\n"
4414 "The only restriction of an element name is that it not contain whitespace "
4415 "or begin with the literal element character @code{!} unless specifying a "
4416 "literal element (@pxref{Target Attribute}). There is no whitespace between "
4417 "the @key{TAB} delimited elements. It is recommended that the content of an "
4418 "element be base64 encoded when it contains control or @key{TAB} characters "
4419 "to prevent @abbr{XML} parsing and @command{pwmd} syntax errors."
4422 new_command("RENAME", 0, 1, rename_command, _(
4423 "RENAME [--inquire] [!]element[<TAB>[!]child[..]] <value>\n"
4424 "Renames the specified @var{element} to the new @var{value}. If an element of "
4425 "the same name as the @var{value} already exists it will be overwritten."
4426 "\n"
4427 "When the @option{--inquire} option is passed then all remaining non-option "
4428 "arguments are retrieved via a server @emph{INQUIRE}."
4431 new_command("COPY", 0, 1, copy_command, _(
4432 "COPY [--inquire] [!]source[<TAB>[!]child[..]] [!]dest[<TAB>[!]child[..]]\n"
4433 "Copies the entire element tree starting from the child node of the source "
4434 "element, to the destination element path. If the destination element path "
4435 "does not exist then it will be created; otherwise it is overwritten."
4436 "\n"
4437 "Note that attributes from the source element are merged into the "
4438 "destination element when the destination element path exists. When an "
4439 "attribute of the same name exists in both the source and destination "
4440 "elements then the destination attribute will be updated to the source "
4441 "attribute value."
4442 "\n"
4443 "When the @option{--inquire} option is passed then all remaining non-option "
4444 "arguments are retrieved via a server @emph{INQUIRE}."
4447 new_command("MOVE", 0, 1, move_command, _(
4448 "MOVE [--inquire] [!]source[<TAB>[!]child[..]] [[!]dest[<TAB>[!]child[..]]]\n"
4449 "Moves the source element path to the destination element path. If the "
4450 "destination is not specified then it will be moved to the root node of the "
4451 "document. If the destination is specified and exists then it will be "
4452 "overwritten; otherwise non-existing elements of the destination element "
4453 "path will be created."
4454 "\n"
4455 "When the @option{--inquire} option is passed then all remaining non-option "
4456 "arguments are retrieved via a server @emph{INQUIRE}."
4459 new_command("DELETE", 0, 1, delete_command, _(
4460 "DELETE [--inquire] [!]element[<TAB>[!]child[..]]\n"
4461 "Removes the specified element path and all of its children. This may break "
4462 "an element with a @code{target} attribute (@pxref{Target Attribute}) that "
4463 "refers to this element or any of its children."
4464 "\n"
4465 "When the @option{--inquire} option is passed then all remaining non-option "
4466 "arguments are retrieved via a server @emph{INQUIRE}."
4469 new_command("GET", 0, 1, get_command, _(
4470 "GET [--inquire] [!]element[<TAB>[!]child[..]]\n"
4471 "Retrieves the content of the specified element. The content is returned "
4472 "with a data response."
4473 "\n"
4474 "When the @option{--inquire} option is passed then all remaining non-option "
4475 "arguments are retrieved via a server @emph{INQUIRE}."
4478 new_command("ATTR", 0, 1, attr_command, _(
4479 "ATTR [--inquire] SET|GET|DELETE|LIST [<attribute>] [!]element[<TAB>[!]child[..]] ..\n"
4480 "@table @asis\n"
4481 "@item ATTR SET attribute [!]element[<TAB>[!]child[..]] [value]\n"
4482 "\n"
4483 " Stores or updates an @var{attribute} name and optional @var{value} of an "
4484 "element. When no @var{value} is specified any existing value will be removed."
4485 "\n"
4486 "@item ATTR DELETE attribute [!]element[<TAB>[!]child[..]]\n"
4487 "\n"
4488 " Removes an @var{attribute} from an element."
4489 "\n"
4490 "@item ATTR LIST [!]element[<TAB>[!]child[..]]\n"
4491 "\n"
4492 " Retrieves a newline separated list of attributes names and values "
4493 "from the specified element. Each attribute name and value is space delimited."
4494 "\n"
4495 "@item ATTR GET attribute [!]element[<TAB>[!]child[..]]\n"
4496 "\n"
4497 " Retrieves the value of an @var{attribute} from an element."
4498 "@end table\n"
4499 "\n"
4500 "The @code{_name} attribute (case sensitive) cannot be removed nor modified. "
4501 "Use the @code{DELETE} (@pxref{DELETE}) or @code{RENAME} (@pxref{RENAME}) "
4502 "commands instead."
4503 "\n"
4504 "The @code{_mtime} attribute is updated each time an element is modified by "
4505 "either storing content, editing attributes or by deleting a child element. "
4506 "The @code{_ctime} attribute is created for each new element in an element "
4507 "path."
4508 "\n"
4509 "When the @option{--inquire} option is passed then all remaining non-option "
4510 "arguments are retrieved via a server @emph{INQUIRE}."
4511 "\n"
4512 "@xref{Target Attribute}, for details about this special attribute."
4515 new_command("XPATH", 0, 1, xpath_command, _(
4516 "XPATH [--inquire] <expression>[<TAB>[value]]\n"
4517 "Evaluates an XPath @var{expression}. If no @var{value} argument is "
4518 "specified, it is assumed the expression is a request to return a result. "
4519 "Otherwise, the result is set to the @var{value} argument and the document is "
4520 "updated. If there is no @var{value} after the @key{TAB} character, the value "
4521 "is assumed to be empty and the document is updated. For example:"
4522 "@sp 1\n"
4523 "@example\n"
4524 "XPATH //element[@@_name='password']@key{TAB}\n"
4525 "@end example\n"
4526 "@sp 1"
4527 "would clear the content of all @code{password} elements in the data file "
4528 "while leaving off the trailing @key{TAB} would return all @code{password} "
4529 "elements in @abbr{XML} format."
4530 "\n"
4531 "When the @option{--inquire} option is passed then all remaining non-option "
4532 "arguments are retrieved via a server @emph{INQUIRE}."
4533 "\n"
4534 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
4535 "expression syntax."
4538 new_command("XPATHATTR", 0, 1, xpathattr_command, _(
4539 "XPATHATTR [--inquire] SET|DELETE <name> <expression>[<TAB>[<value>]]\n"
4540 "Like the @code{XPATH} command (@pxref{XPATH}) but operates on element "
4541 "attributes and does not return a result. For the @var{SET} operation the "
4542 "@var{value} is optional but the field is required. If not specified then "
4543 "the attribute value will be empty. For example:"
4544 "@sp 1"
4545 "@example\n"
4546 "XPATHATTR SET password //element[@@_name='password']@key{TAB}\n"
4547 "@end example\n"
4548 "@sp 1"
4549 "would create an @code{password} attribute for each @code{password} element "
4550 "found in the document. The attribute value will be empty but still exist."
4551 "\n"
4552 "When the @option{--inquire} option is passed then all remaining non-option "
4553 "arguments are retrieved via a server @emph{INQUIRE}."
4554 "\n"
4555 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
4556 "expression syntax."
4559 new_command("IMPORT", 0, 1, import_command, _(
4560 "IMPORT <content>[<TAB>[!]element[<TAB>[!]child[..]]]\n"
4561 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
4562 "\n"
4563 "Like the @code{STORE} command (@pxref{STORE}), but the @var{content} "
4564 "argument is raw @abbr{XML} data. The content is created as a child of the "
4565 "specified element path and will overwrite an existing element of the same "
4566 "name. If an element of the element path does not exist then it will be "
4567 "created."
4568 "\n"
4569 "The content must begin with an @abbr{XML} element node. @xref{Introduction}, "
4570 "for details."
4573 new_command("DUMP", 0, 1, dump_command, _(
4574 "DUMP\n"
4575 "Shows the in memory @abbr{XML} document with indenting. @xref{XPATH}, for "
4576 "dumping a specific node."
4579 new_command("LOCK", 0, 0, lock_command, _(
4580 "LOCK\n"
4581 "Locks the mutex associated with the opened file. This prevents other clients "
4582 "from sending commands to the same opened file until the client "
4583 "that sent this command either disconnects or sends the @code{UNLOCK} "
4584 "command. @xref{UNLOCK}."
4587 new_command("UNLOCK", 1, 0, unlock_command, _(
4588 "UNLOCK\n"
4589 "Unlocks the file mutex which was locked with the @code{LOCK} command or "
4590 "a commands' @option{--lock} option (@pxref{LOCK}, @pxref{OPEN}, "
4591 "@pxref{ISCACHED})."
4594 new_command("GETCONFIG", 1, 1, getconfig_command, _(
4595 "GETCONFIG [filename] <parameter>\n"
4596 "Returns the value of a @command{pwmd} configuration @var{parameter} with a "
4597 "data response. If no file has been opened then the value for @var{filename} "
4598 "or the default from the @samp{global} section will be returned. If a file "
4599 "has been opened and no @var{filename} is specified, a value previously "
4600 "set with the @code{OPTION} command (@pxref{OPTION}) will be returned."
4603 new_command("OPTION", 1, 1, option_command, _(
4604 "OPTION <NAME>=<VALUE>\n"
4605 "Sets a client option @var{name} to @var{value}. The value for an option is "
4606 "kept for the duration of the connection."
4607 "\n"
4608 "@table @asis\n"
4609 "@item DISABLE-PINENTRY\n"
4610 " Disable use of @command{pinentry} for passphrase retrieval. When set, a "
4611 " server inquire is sent to the client to obtain the passphrase. This option "
4612 " may be set as needed before the @pxref{OPEN}, @pxref{PASSWD}, and "
4613 " @pxref{SAVE} commands."
4614 "\n"
4615 "@item TTYNAME\n"
4616 " Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4617 "\n"
4618 "@item TTYTYPE\n"
4619 " Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4620 "\n"
4621 "@item DISPLAY\n"
4622 " Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4623 "\n"
4624 "@item PINENTRY-DESC\n"
4625 " Sets the description string of the @command{gpg-agent} and @command{pinentry} dialog."
4626 "\n"
4627 "@item PINENTRY-TITLE\n"
4628 " Sets the title string of the @command{gpg-agent} and @command{pinentry} dialog."
4629 "\n"
4630 "@item PINENTRY-PROMPT\n"
4631 " Sets the prompt string of the @command{gpg-agent} and @command{pinentry} dialog."
4632 "\n"
4633 "@item LC-CTYPE\n"
4634 " Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4635 "\n"
4636 "@item LC-MESSAGES\n"
4637 " Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
4638 "\n"
4639 "@item NAME\n"
4640 " Associates the thread ID of the connection with the specified textual "
4641 "representation. Useful for debugging log messages."
4642 "\n"
4643 "@item LOCK-TIMEOUT\n"
4644 " When not @code{0}, the duration in tenths of a second to wait for the file "
4645 "mutex which has been locked by another thread to be released before returning "
4646 "an error. When @code{-1}, then an error will be returned immediately."
4647 "@end table\n"
4650 new_command("LS", 1, 1, ls_command, _(
4651 "LS\n"
4652 "Lists the available data files stored in the data directory "
4653 "(@file{~/.pwmd/data}). The result is a newline separated list of filenames."
4656 new_command("RESET", 1, 1, NULL, _(
4657 "RESET\n"
4658 "Closes the currently opened file but keeps any previously set client options."
4661 new_command("NOP", 1, 1, NULL, _(
4662 "NOP\n"
4663 "Does nothing. Always returns successfully."
4666 /* !END-HELP-TEXT! */
4667 new_command ("CANCEL", 1, 1, NULL, NULL);
4668 new_command ("END", 1, 1, NULL, NULL);
4669 new_command ("BYE", 1, 1, NULL, NULL);
4671 int i;
4672 for (i = 0; command_table[i]; i++);
4673 qsort (command_table, i - 1, sizeof (struct command_table_s *),
4674 sort_commands);
4677 gpg_error_t
4678 register_commands (assuan_context_t ctx)
4680 int i = 0, rc;
4682 for (; command_table[i]; i++)
4684 if (!command_table[i]->handler)
4685 continue;
4687 rc = assuan_register_command (ctx, command_table[i]->name,
4688 command_table[i]->handler,
4689 command_table[i]->help);
4690 if (rc)
4691 return rc;
4694 rc = assuan_register_bye_notify (ctx, bye_notify);
4695 if (rc)
4696 return rc;
4698 rc = assuan_register_reset_notify (ctx, reset_notify);
4699 if (rc)
4700 return rc;
4702 rc = assuan_register_pre_cmd_notify (ctx, command_startup);
4703 if (rc)
4704 return rc;
4706 return assuan_register_post_cmd_notify (ctx, command_finalize);