Fix LIST showing non-existant element paths.
[pwmd.git] / src / commands.c
blob5ae949607df67df2a329042ab0bec5b6eb2567d3
1 /*
2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015
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 #include "pwmd-error.h"
38 #include <gcrypt.h>
40 #include "mem.h"
41 #include "xml.h"
42 #include "util-misc.h"
43 #include "common.h"
44 #include "rcfile.h"
45 #include "cache.h"
46 #include "commands.h"
47 #include "mutex.h"
48 #include "crypto.h"
49 #include "pinentry.h"
51 /* These are command option flags. */
52 #define OPT_INQUIRE 0x0001
53 #define OPT_NO_PASSPHRASE 0x0002
54 #define OPT_RESET 0x0004
55 #define OPT_LIST_RECURSE 0x0008
56 #define OPT_VERBOSE 0x0010
57 #define OPT_LOCK 0x0020
58 #define OPT_LOCK_ON_OPEN 0x0040
59 #define OPT_SIGN 0x0080
60 #define OPT_LIST_ALL 0x0100
61 #define OPT_LIST_WITH_TARGET 0x0200
62 #define OPT_DATA 0x0400
63 #define OPT_NO_AGENT 0x0800
65 #ifdef WITH_AGENT
66 /* The GETCONFIG command, for example, may fail because pwmd lost the
67 * gpg-agent connection. Update the recovered agent ctx. */
68 #define UPDATE_AGENT_CTX(client, crypto) do { \
69 if (crypto && crypto->agent && crypto->agent->did_restart \
70 && client->crypto && client->crypto->agent \
71 && client->crypto->agent->ctx && \
72 crypto->agent->ctx != client->crypto->agent->ctx) \
73 { \
74 client->crypto->agent->ctx = crypto->agent->ctx; \
75 crypto->agent->ctx = NULL; \
76 } \
77 } while (0)
78 #else
79 #define UPDATE_AGENT_CTX(client, crypto)
80 #endif
82 struct command_table_s
84 const char *name;
85 gpg_error_t (*handler) (assuan_context_t, char *line);
86 const char *help;
87 int ignore_startup;
88 int unlock; // unlock the file mutex after validating the checksum
91 static struct command_table_s **command_table;
93 static gpg_error_t do_lock (struct client_s *client, int add);
94 static gpg_error_t validate_checksum (struct client_s *,
95 struct cache_data_s *);
96 static gpg_error_t update_checksum (struct client_s *client);
98 /* When 'status' is true the 'self' field of the status line will be false
99 * because we never send the STATE status message to the same client that
100 * initiated it. */
101 static char *
102 build_client_info_line (struct client_thread_s *thd, int status)
104 MUTEX_LOCK (&cn_mutex);
105 int with_state = config_get_boolean ("global", "send_state");
106 char *uid;
107 char *line;
109 #ifdef WITH_GNUTLS
110 if (thd->remote)
111 uid = str_asprintf("#%s", thd->tls->fp);
112 else
113 uid = str_asprintf("%u", thd->peer->uid);
114 #else
115 uid = str_asprintf("%u", thd->peer->uid);
116 #endif
117 line = str_asprintf ("%p %s %s %s %u %u %u %s",
118 thd->tid,
119 thd->name ? thd->name : "-",
120 thd->cl && thd->cl->filename
121 ? thd->cl->filename : "/",
122 #ifdef WITH_GNUTLS
123 thd->remote ? thd->peeraddr : "-",
124 #else
125 "-",
126 #endif
127 thd->cl && thd->cl->flags & FLAG_HAS_LOCK ? 1 : 0,
128 !status && pthread_equal (pthread_self (), thd->tid) ? 1 : 0,
129 with_state ? thd->state : CLIENT_STATE_UNKNOWN, uid
132 xfree (uid);
133 MUTEX_UNLOCK (&cn_mutex);
134 return line;
137 void
138 update_client_state (struct client_s *client, unsigned s)
140 client->thd->state = s;
141 int n = config_get_boolean ("global", "send_state");
143 if (n && client->thd->state != CLIENT_STATE_UNKNOWN)
145 char *line = build_client_info_line (client->thd, 1);
147 if (line)
148 send_status_all_not_self (n == 2, STATUS_STATE, "%s", line);
152 static gpg_error_t
153 unlock_file_mutex (struct client_s *client, int remove)
155 gpg_error_t rc = 0;
157 // OPEN: keep the lock for the same file being reopened.
158 if (client->flags & FLAG_KEEP_LOCK && client->flags & FLAG_HAS_LOCK)
159 return 0;
161 if (!(client->flags & FLAG_HAS_LOCK))
162 return GPG_ERR_NOT_LOCKED;
164 rc = cache_unlock_mutex (client->md5file, remove);
165 if (rc)
166 rc = GPG_ERR_INV_STATE;
167 else
168 client->flags &= ~(FLAG_HAS_LOCK | FLAG_LOCK_CMD);
170 return rc;
173 static gpg_error_t
174 lock_file_mutex (struct client_s *client, int add)
176 gpg_error_t rc = 0;
177 int timeout = config_get_integer (client->filename, "cache_timeout");
179 if (client->flags & FLAG_HAS_LOCK)
180 return 0;
182 rc = cache_lock_mutex (client->ctx, client->md5file,
183 client->lock_timeout, add, timeout);
184 if (!rc)
185 client->flags |= FLAG_HAS_LOCK;
187 return rc;
190 static gpg_error_t
191 file_modified (struct client_s *client, struct command_table_s *cmd)
193 gpg_error_t rc = 0;
195 if (!(client->flags & FLAG_OPEN))
196 return GPG_ERR_INV_STATE;
198 rc = lock_file_mutex (client, 0);
199 if (!rc || rc == GPG_ERR_NO_DATA)
201 rc = validate_checksum (client, NULL);
202 if (gpg_err_code (rc) == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
203 rc = 0;
204 else if (rc)
205 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
208 if ((cmd->unlock && !(client->flags & FLAG_HAS_LOCK)) || rc)
209 unlock_file_mutex (client, 0);
211 return rc;
214 static gpg_error_t
215 parse_xml (assuan_context_t ctx, int new)
217 struct client_s *client = assuan_get_pointer (ctx);
218 int cached = client->doc != NULL;
219 gpg_error_t rc = 0;
221 if (new)
223 client->doc = new_document ();
224 if (client->doc)
226 xmlChar *result;
227 int len;
229 xmlDocDumpFormatMemory (client->doc, &result, &len, 0);
230 client->crypto->plaintext = result;
231 client->crypto->plaintext_len = len;
232 if (!client->crypto->plaintext)
234 xmlFreeDoc (client->doc);
235 client->doc = NULL;
236 rc = GPG_ERR_ENOMEM;
239 else
240 rc = GPG_ERR_ENOMEM;
242 else if (!cached)
243 rc = parse_doc ((char *) client->crypto->plaintext,
244 client->crypto->plaintext_len, (xmlDocPtr *)&client->doc);
246 return rc;
249 static void
250 free_client (struct client_s *client)
252 if (client->doc)
253 xmlFreeDoc (client->doc);
255 xfree (client->crc);
256 xfree (client->filename);
257 xfree (client->last_error);
259 if (client->crypto)
261 cleanup_crypto_stage2 (client->crypto);
262 if (client->crypto->pkey_sexp)
263 gcry_sexp_release (client->crypto->pkey_sexp);
265 if (client->crypto->sigpkey_sexp)
266 gcry_sexp_release (client->crypto->sigpkey_sexp);
268 client->crypto->pkey_sexp = NULL;
269 client->crypto->sigpkey_sexp = NULL;
270 memset (client->crypto->sign_grip, 0,
271 sizeof (client->crypto->sign_grip));
272 memset (client->crypto->grip, 0, sizeof(client->crypto->grip));
276 void
277 cleanup_client (struct client_s *client)
279 assuan_context_t ctx = client->ctx;
280 struct client_thread_s *thd = client->thd;
281 struct crypto_s *crypto = client->crypto;
282 long lock_timeout = client->lock_timeout;
283 int no_pinentry = (client->flags & FLAG_NO_PINENTRY);
284 struct pinentry_option_s pin_opts;
285 xmlErrorPtr xml_error = client->xml_error;
286 #ifdef WITH_AGENT
287 struct pinentry_option_s agent_pin_opts;
289 if (crypto && crypto->agent)
290 memcpy (&agent_pin_opts, &crypto->agent->pinentry_opts,
291 sizeof(struct pinentry_option_s));
292 #endif
294 memcpy (&pin_opts, &client->pinentry_opts, sizeof(struct pinentry_option_s));
295 unlock_file_mutex (client, client->flags & FLAG_NEW);
296 free_client (client);
297 memset (client, 0, sizeof (struct client_s));
298 client->xml_error = xml_error;
299 client->crypto = crypto;
300 client->ctx = ctx;
301 client->thd = thd;
302 client->lock_timeout = lock_timeout;
303 memcpy (&client->pinentry_opts, &pin_opts, sizeof(struct pinentry_option_s));
304 client->flags |= no_pinentry ? FLAG_NO_PINENTRY : 0;
305 #ifdef WITH_AGENT
306 if (crypto && crypto->agent)
307 memcpy (&crypto->agent->pinentry_opts, &agent_pin_opts,
308 sizeof(struct pinentry_option_s));
309 #endif
312 static gpg_error_t
313 open_finalize (assuan_context_t ctx, char *key, size_t keylen)
315 struct client_s *client = assuan_get_pointer (ctx);
316 gpg_error_t rc = 0;
317 struct cache_data_s *cdata = cache_get_data (client->md5file);
318 int cached = 0, keyarg = key ? 1 : 0;
319 size_t keysize;
320 unsigned char *salted_key = NULL;
321 int algo;
322 int pin_try = 1;
323 int pin_tries = 3;
324 char *pin_title = client->pinentry_opts.title;
326 client->crypto->filename = str_dup (client->filename);
327 if (cdata || client->flags & FLAG_NEW)
329 if (cdata && !(client->flags & FLAG_NEW))
331 rc = decrypt_cache (client->crypto, cdata->doc, cdata->doclen);
332 if (rc)
333 return rc;
336 cached = cdata != NULL;
337 goto done;
340 if (!key && !IS_PKI (client->crypto)
341 && !(client->crypto->hdr.flags & PWMD_FLAG_NO_PASSPHRASE))
343 if (client->flags & FLAG_NO_PINENTRY)
345 rc = inquire_passphrase (ctx, "PASSPHRASE", (unsigned char **)&key,
346 &keylen);
347 if (rc)
348 return rc;
350 else
352 client->pinentry_opts.timeout = config_get_integer (client->filename,
353 "pinentry_timeout");
354 pin_again:
355 rc = getpin_common (client->ctx, client->filename, PINENTRY_OPEN,
356 &key, &keylen);
357 if (rc)
358 return rc;
362 if (!IS_PKI (client->crypto))
364 if (client->crypto->hdr.flags & PWMD_FLAG_NO_PASSPHRASE)
366 keylen = 1;
367 key = gcry_malloc (keylen);
368 memset (key, 0, keylen);
371 algo = cipher_to_gcrypt (client->crypto->hdr.flags);
372 rc = hash_key (algo, client->crypto->hdr.salt,
373 sizeof(client->crypto->hdr.salt), key, keylen,
374 (void **)&salted_key, &keysize);
375 if (!keyarg)
376 gcry_free (key);
378 if (!rc)
380 rc = decrypt_data (client->ctx, client->crypto, salted_key, keysize);
381 if (gpg_err_code (rc) == GPG_ERR_BAD_PASSPHRASE
382 && ++pin_try <= pin_tries && !(client->flags & FLAG_NO_PINENTRY))
384 gcry_free (salted_key);
385 salted_key = NULL;
386 key = NULL;
387 keylen = 0;
388 client->pinentry_opts.title = str_asprintf (_ ("Bad passphrase (try %i of %i)"), pin_try, pin_tries);
389 goto pin_again;
393 if (client->pinentry_opts.title != pin_title)
394 xfree (client->pinentry_opts.title);
396 client->pinentry_opts.title = pin_title;
397 if (rc)
399 gcry_free (salted_key);
400 return rc;
403 cdata = xcalloc (1, sizeof (struct cache_data_s));
404 if (!cdata)
406 gcry_free (salted_key);
407 return GPG_ERR_ENOMEM;
410 cdata->key = salted_key;
411 cdata->keylen = keysize;
413 else
414 #ifdef WITH_AGENT
415 rc = decrypt_data (client->ctx, client->crypto, NULL, 0);
416 #else
417 rc = GPG_ERR_NOT_IMPLEMENTED;
418 #endif
420 done:
421 if (!rc)
423 rc = parse_xml (ctx, client->flags & FLAG_NEW);
424 if (rc && !cached)
425 free_cache_data_once (cdata);
427 if (!rc)
429 int timeout = config_get_integer (client->filename,
430 "cache_timeout");
432 if (!cached)
434 if (!cdata)
435 cdata = xcalloc (1, sizeof (struct cache_data_s));
437 rc = encrypt_xml (NULL, cache_key, cache_keysize,
438 GCRY_CIPHER_AES, client->crypto->plaintext,
439 client->crypto->plaintext_len, &cdata->doc,
440 &cdata->doclen, &cache_iv, &cache_blocksize,
442 if (!rc && !(client->flags & FLAG_NEW) && IS_PKI (client->crypto))
444 rc = gcry_sexp_build ((gcry_sexp_t *) & cdata->pubkey, NULL,
445 "%S", client->crypto->pkey_sexp);
449 if (cdata->sigkey)
450 gcry_sexp_release (cdata->sigkey);
452 cdata->sigkey = NULL;
453 if (!rc && IS_PKI (client->crypto))
454 rc = gcry_sexp_build ((gcry_sexp_t *) &cdata->sigkey, NULL,
455 "%S", client->crypto->sigpkey_sexp);
457 if (!rc)
459 rc = cache_add_file (client->md5file,
460 (client->flags & FLAG_NEW) ? NULL
461 : client->crypto->grip, cdata, timeout);
462 if (rc)
464 if (!cached)
466 free_cache_data_once (cdata);
467 xmlFreeDoc (client->doc);
468 client->doc = NULL;
473 if (!rc)
474 client->flags |= FLAG_OPEN;
478 if (!rc)
479 update_checksum (client);
481 if (!rc && (client->opts & OPT_LOCK_ON_OPEN))
482 rc = do_lock (client, 0);
484 return rc;
487 static void
488 req_cleanup (void *arg)
490 if (!arg)
491 return;
493 strv_free ((char **) arg);
496 static gpg_error_t
497 parse_open_opt_lock (void *data, void *value)
499 struct client_s *client = data;
501 client->opts |= OPT_LOCK_ON_OPEN;
502 return 0;
505 static gpg_error_t
506 parse_save_opt_inquire (void *data, void *value)
508 struct client_s *client = data;
509 gpg_error_t rc;
511 if (!(client->flags & FLAG_NEW))
513 rc = peer_is_invoker (client);
514 if (rc == GPG_ERR_EACCES)
515 return rc;
518 (void) value;
519 client->opts |= OPT_INQUIRE;
520 return 0;
523 static gpg_error_t
524 parse_opt_inquire (void *data, void *value)
526 struct client_s *client = data;
528 (void) value;
529 client->opts |= OPT_INQUIRE;
530 return 0;
533 static gpg_error_t
534 update_checksum (struct client_s *client)
536 unsigned char *crc;
537 size_t len;
538 struct cache_data_s *cdata;
539 gpg_error_t rc = get_checksum (client->filename, &crc, &len);
541 if (rc)
542 return rc;
544 xfree (client->crc);
545 client->crc = crc;
546 cdata = cache_get_data (client->md5file);
547 if (cdata)
549 xfree (cdata->crc);
550 cdata->crc = xmalloc (len);
551 memcpy (cdata->crc, crc, len);
554 return 0;
557 static gpg_error_t
558 validate_checksum (struct client_s *client, struct cache_data_s *cdata)
560 unsigned char *crc;
561 size_t len;
562 gpg_error_t rc;
563 int n = 0;
565 if (cdata && !cdata->crc)
566 return GPG_ERR_CHECKSUM;
568 rc = get_checksum (client->filename, &crc, &len);
569 if (rc)
570 return rc;
572 if (cdata)
573 n = memcmp (cdata->crc, crc, len);
574 else if (client->crc)
575 n = memcmp (client->crc, crc, len);
577 xfree (crc);
578 return n ? GPG_ERR_CHECKSUM : 0;
581 static gpg_error_t
582 do_open (assuan_context_t ctx, const char *password)
584 struct client_s *client = assuan_get_pointer (ctx);
585 struct cache_data_s *cdata;
586 gpg_error_t rc = 0;
587 int done = 0;
589 // Cached document?
590 cdata = cache_get_data (client->md5file);
591 if (cdata && cdata->doc)
593 int defer = 0;
595 /* This will check that the key is cached in the agent which needs to
596 * be determined for files that share a keygrip. */
597 if (!rc)
599 rc = cache_iscached (client->filename, &defer);
600 if ((!rc || rc == GPG_ERR_ENOENT) && defer)
601 rc = GPG_ERR_KEY_EXPIRED;
604 if (!rc && !(client->flags & FLAG_NEW))
605 rc = validate_checksum (client, cdata);
607 #ifdef WITH_GNUTLS
608 if (!rc && client->thd->remote
609 && config_get_boolean (client->filename, "tcp_require_key"))
610 rc = GPG_ERR_KEY_EXPIRED;
611 #endif
613 if (!rc && !password)
615 rc = read_data_header (client->filename, &client->crypto->hdr,
616 NULL, NULL);
617 if (!rc)
619 if (IS_PKI (client->crypto))
621 gcry_sexp_build (&client->crypto->pkey_sexp, NULL, "%S",
622 cdata->pubkey);
623 gcry_pk_get_keygrip (client->crypto->pkey_sexp,
624 client->crypto->grip);
625 gcry_sexp_build (&client->crypto->sigpkey_sexp, NULL, "%S",
626 cdata->sigkey);
627 gcry_pk_get_keygrip (client->crypto->sigpkey_sexp,
628 client->crypto->sign_grip);
631 if (!rc)
633 rc = open_finalize (ctx, NULL, 0);
634 done = 1;
639 /* There was an error accessing the file so clear the cache entry. The
640 * real error will be returned from read_data_file() since the file
641 * may have only disappeared. */
642 if (!done)
644 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
645 rc = cache_clear (client->md5file);
646 send_status_all (STATUS_CACHE, NULL);
650 if (done || rc)
651 return rc;
653 rc = read_data_file (client->filename, client->crypto);
654 if (rc)
656 if (gpg_err_source (rc) != GPG_ERR_SOURCE_DEFAULT ||
657 gpg_err_code (rc) != GPG_ERR_ENOENT)
659 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
660 return rc;
663 client->flags |= FLAG_NEW;
664 memset (client->crypto->grip, 0, sizeof (client->crypto->grip));
665 memset (client->crypto->sign_grip, 0,
666 sizeof (client->crypto->sign_grip));
667 rc = open_finalize (ctx, NULL, 0);
668 return rc;
671 if (password && IS_PKI (client->crypto))
673 #ifdef WITH_AGENT
674 rc = set_agent_passphrase (client->crypto, password, strlen (password));
675 if (rc)
676 return rc;
677 #endif
680 rc = open_finalize (ctx, (char *)password, password ? strlen (password) : 0);
681 return rc;
684 static gpg_error_t
685 open_command (assuan_context_t ctx, char *line)
687 gpg_error_t rc;
688 struct client_s *client = assuan_get_pointer (ctx);
689 char **req, *filename;
690 unsigned char md5file[16];
691 int same_file = 0;
692 assuan_peercred_t peer;
693 struct argv_s *args[] = {
694 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_open_opt_lock},
695 NULL
698 rc = parse_options (&line, args, client);
699 if (rc)
700 return send_error (ctx, rc);
702 req = str_split (line, " ", 2);
703 if (!req)
704 return send_error (ctx, GPG_ERR_SYNTAX);
706 rc = do_validate_peer (ctx, req[0], &peer);
707 if (rc)
709 strv_free (req);
710 return send_error (ctx, rc);
713 filename = req[0];
714 if (!valid_filename (filename))
716 strv_free (req);
717 return send_error (ctx, GPG_ERR_INV_VALUE);
720 pthread_cleanup_push (req_cleanup, req);
721 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
722 /* This client may have locked a different file with ISCACHED --lock than
723 * the current filename. This will remove that lock. */
724 same_file = !memcmp (md5file, client->md5file, 16) ? 1 : 0;
725 if (client->flags & FLAG_OPEN ||
726 (client->flags & FLAG_HAS_LOCK && !same_file))
728 uint32_t opts = client->opts;
729 uint32_t flags = client->flags;
731 if (same_file)
732 client->flags |= FLAG_KEEP_LOCK;
733 else if (client->flags & FLAG_NEW)
734 cache_clear (client->md5file);
736 cleanup_client (client);
737 client->opts = opts;
738 client->flags |= flags;
739 client->flags &= ~(FLAG_LOCK_CMD);
740 if (!same_file)
741 client->flags &= ~(FLAG_HAS_LOCK | FLAG_NEW);
744 memcpy (client->md5file, md5file, 16);
745 client->filename = str_dup (filename);
746 if (!client->filename)
748 strv_free (req);
749 return send_error(ctx, GPG_ERR_ENOMEM);
752 /* Need to lock the mutex here because file_modified() cannot without
753 * knowing the filename. */
754 rc = lock_file_mutex (client, 1);
755 if (rc)
756 client->flags &= ~FLAG_OPEN;
758 if (!rc)
760 char *password = req[1] && *req[1] ? req[1] : NULL;
762 #ifdef WITH_AGENT
763 if (IS_PKI (client->crypto))
764 rc = set_pinentry_mode (client->crypto->agent,
765 (client->flags & FLAG_NO_PINENTRY) ? "loopback"
766 : "ask");
767 #endif
768 if (!rc)
770 rc = do_open (ctx, password);
771 if (rc)
772 cleanup_client (client);
774 cleanup_crypto_stage1 (client->crypto);
778 pthread_cleanup_pop (1);
780 if (!rc && client->flags & FLAG_NEW)
781 rc = send_status (ctx, STATUS_NEWFILE, NULL);
783 #ifdef WITH_AGENT
784 (void) kill_scd (client->crypto->agent);
785 #endif
787 return send_error (ctx, rc);
790 static gpg_error_t
791 parse_opt_no_passphrase (void *data, void *value)
793 struct client_s *client = data;
795 (void) value;
796 client->opts |= OPT_NO_PASSPHRASE;
797 return 0;
800 static gpg_error_t
801 parse_save_opt_no_agent (void *data, void *value)
803 struct client_s *client = data;
805 client->opts |= OPT_NO_AGENT;
806 return 0;
809 static gpg_error_t
810 parse_save_opt_cipher (void *data, void *value)
812 struct client_s *client = data;
813 int algo = cipher_string_to_gcrypt ((char *) value);
814 file_header_t *hdr = &client->crypto->save.hdr;
815 gpg_error_t rc = 0;
817 if (algo == -1)
818 return GPG_ERR_INV_VALUE;
820 if (!(client->flags & FLAG_NEW))
822 rc = peer_is_invoker (client);
823 if (rc == GPG_ERR_EACCES)
825 uint64_t flags = 0;
827 flags &= ((uint16_t) ((uint32_t) (flags & 0xFFFFFFFF)));
828 if (!(client->crypto->hdr.flags & gcrypt_to_cipher (algo)))
829 return rc;
831 rc = 0;
833 else if (rc)
834 return rc;
837 if (!rc)
838 hdr->flags = set_cipher_flag (hdr->flags, algo);
840 return rc;
843 #ifdef WITH_AGENT
844 static gpg_error_t
845 permitted_to_save (struct client_s *client, const unsigned char *grip,
846 size_t size, const char *value)
848 char *hexgrip;
849 gpg_error_t rc = 0;
851 if (!(client->flags & FLAG_NEW))
853 hexgrip = bin2hex (grip, size);
854 rc = !strcmp (hexgrip, (char *)value) ? 0 : GPG_ERR_EACCES;
855 xfree (hexgrip);
856 if (rc)
857 rc = peer_is_invoker (client);
860 return rc;
862 #endif
864 static gpg_error_t
865 parse_save_opt_keygrip (void *data, void *value)
867 #ifdef WITH_AGENT
868 struct client_s *client = data;
869 gpg_error_t rc = permitted_to_save (client, client->crypto->grip,
870 sizeof (client->crypto->grip),
871 value);
873 if (!IS_PKI (client->crypto))
874 return GPG_ERR_INV_ARG;
876 if (rc)
877 return rc;
879 if (client->crypto->save.pkey)
880 gcry_sexp_release (client->crypto->save.pkey);
882 client->crypto->save.pkey = NULL;
883 return get_pubkey (client->crypto, value, &client->crypto->save.pkey);
884 #else
885 return GPG_ERR_INV_ARG;
886 #endif
889 static gpg_error_t
890 parse_save_opt_sign_keygrip (void *data, void *value)
892 #ifdef WITH_AGENT
893 struct client_s *client = data;
894 gpg_error_t rc = permitted_to_save (client, client->crypto->sign_grip,
895 sizeof (client->crypto->sign_grip),
896 value);
898 if (!IS_PKI (client->crypto))
899 return GPG_ERR_INV_ARG;
901 if (rc)
902 return rc;
904 if (client->crypto->save.sigpkey)
905 gcry_sexp_release (client->crypto->save.sigpkey);
907 client->crypto->save.sigpkey = NULL;
908 return get_pubkey (client->crypto, value, &client->crypto->save.sigpkey);
909 #else
910 return GPG_ERR_INV_ARG;
911 #endif
914 static gpg_error_t
915 parse_opt_s2k_count (void *data, void *value)
917 struct client_s *client = data;
918 char *v = value;
920 if (!v || !*v)
921 return GPG_ERR_INV_VALUE;
923 client->crypto->save.s2k_count = strtoul (v, NULL, 10);
924 return 0;
927 static gpg_error_t
928 parse_save_opt_iterations (void *data, void *value)
930 struct client_s *client = data;
931 char *v = value, *p;
932 uint64_t n;
934 if (!v || !*v)
935 return GPG_ERR_INV_VALUE;
937 errno = 0;
938 n = strtoull (v, &p, 10);
939 if (n == UINT64_MAX && errno)
940 return gpg_error_from_errno (errno);
941 else if (p && *p)
942 return GPG_ERR_INV_VALUE;
944 if (!(client->flags & FLAG_NEW))
946 gpg_error_t rc = peer_is_invoker (client);
948 if (rc == GPG_ERR_EACCES)
950 if (client->crypto->hdr.iterations != n)
951 return rc;
953 rc = 0;
955 else if (rc)
956 return rc;
959 client->crypto->save.hdr.iterations = n;
960 return 0;
963 static gpg_error_t
964 save_finalize (assuan_context_t ctx)
966 struct client_s *client = assuan_get_pointer (ctx);
967 gpg_error_t rc = 0;
968 xmlChar *xmlbuf = NULL;
969 int xmlbuflen;
970 void *key = NULL;
971 size_t keylen = 0;
973 xmlDocDumpFormatMemory (client->doc, &xmlbuf, &xmlbuflen, 0);
974 if (!xmlbuf)
975 return GPG_ERR_ENOMEM;
977 pthread_cleanup_push (xmlFree, xmlbuf);
979 if (!use_agent || ((client->flags & FLAG_NEW)
980 && (client->opts & OPT_NO_AGENT))
981 || !(client->crypto->hdr.flags & PWMD_FLAG_PKI))
983 rc = export_common (ctx, client->flags & FLAG_NO_PINENTRY,
984 client->crypto, xmlbuf, xmlbuflen, client->filename,
985 NULL, &key, &keylen, 1, 1,
986 (client->opts & OPT_NO_PASSPHRASE));
988 #ifdef WITH_AGENT
989 else
991 gcry_sexp_t pubkey = client->crypto->save.pkey;
992 gcry_sexp_t sigkey = client->crypto->save.sigpkey;
994 if (!pubkey)
995 pubkey = client->crypto->pkey_sexp;
997 if (!sigkey)
999 sigkey = client->crypto->sigpkey_sexp;
1000 if (!sigkey)
1002 gcry_sexp_build (&client->crypto->save.sigpkey, 0, "%S", pubkey);
1003 sigkey = client->crypto->save.sigpkey;
1007 rc = encrypt_data_file (client->ctx, client->crypto, pubkey, sigkey,
1008 client->filename, xmlbuf, xmlbuflen);
1009 if (pubkey == client->crypto->save.pkey)
1011 if (!rc)
1013 gcry_sexp_release (client->crypto->pkey_sexp);
1014 client->crypto->pkey_sexp = client->crypto->save.pkey;
1015 gcry_pk_get_keygrip (client->crypto->pkey_sexp,
1016 client->crypto->grip);
1018 else
1019 gcry_sexp_release (pubkey);
1021 client->crypto->save.pkey = NULL;
1024 if (!rc)
1025 gcry_pk_get_keygrip (sigkey, client->crypto->sign_grip);
1027 if (sigkey == client->crypto->save.sigpkey)
1029 if (!rc)
1031 if (client->crypto->sigpkey_sexp)
1032 gcry_sexp_release (client->crypto->sigpkey_sexp);
1034 client->crypto->sigpkey_sexp = client->crypto->save.sigpkey;
1035 gcry_pk_get_keygrip (client->crypto->sigpkey_sexp,
1036 client->crypto->sign_grip);
1038 else
1039 gcry_sexp_release (sigkey);
1041 client->crypto->save.sigpkey = NULL;
1044 #endif
1046 if (!rc)
1048 int cached;
1050 rc = save_common (client->filename, client->crypto, xmlbuf, xmlbuflen,
1051 key, keylen, &cached, client->opts & OPT_NO_AGENT);
1052 if (rc)
1053 gcry_free (key);
1055 if (!rc && (!cached || (client->flags & FLAG_NEW)))
1056 send_status_all (STATUS_CACHE, NULL);
1058 if (!rc)
1060 rc = update_checksum (client);
1061 client->flags &= ~(FLAG_NEW);
1065 pthread_cleanup_pop (1); // xmlFree
1066 return rc;
1069 static gpg_error_t
1070 parse_opt_reset (void *data, void *value)
1072 struct client_s *client = data;
1074 (void) value;
1075 client->opts |= OPT_RESET;
1076 return 0;
1079 static gpg_error_t
1080 save_command (assuan_context_t ctx, char *line)
1082 struct client_s *client = assuan_get_pointer (ctx);
1083 gpg_error_t rc;
1084 struct stat st;
1085 struct argv_s *args[] = {
1086 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG,
1087 parse_opt_no_passphrase},
1088 &(struct argv_s) {"cipher", OPTION_TYPE_ARG, parse_save_opt_cipher},
1089 &(struct argv_s) {"inquire-keyparam", OPTION_TYPE_NOARG,
1090 parse_save_opt_inquire},
1091 &(struct argv_s) {"keygrip", OPTION_TYPE_ARG, parse_save_opt_keygrip},
1092 &(struct argv_s) {"sign-keygrip", OPTION_TYPE_ARG,
1093 parse_save_opt_sign_keygrip},
1094 &(struct argv_s) {"s2k-count", OPTION_TYPE_ARG, parse_opt_s2k_count},
1095 &(struct argv_s) {"reset", OPTION_TYPE_NOARG, parse_opt_reset},
1096 &(struct argv_s) {"cipher-iterations", OPTION_TYPE_ARG,
1097 parse_save_opt_iterations},
1098 &(struct argv_s) {"no-agent", OPTION_TYPE_NOARG,
1099 parse_save_opt_no_agent},
1100 NULL
1103 cleanup_save (&client->crypto->save);
1104 memcpy (&client->crypto->save.hdr, &client->crypto->hdr,
1105 sizeof (file_header_t));
1106 client->crypto->save.s2k_count =
1107 config_get_ulong (client->filename, "s2k_count");
1109 if (client->flags & FLAG_NEW)
1110 client->crypto->save.hdr.iterations =
1111 config_get_ulonglong (client->filename, "cipher_iterations");
1113 rc = parse_options (&line, args, client);
1114 if (rc)
1115 return send_error (ctx, rc);
1117 if (!(client->flags & FLAG_NEW))
1118 client->opts &= ~OPT_NO_AGENT;
1119 else if (client->opts & OPT_NO_AGENT)
1121 client->crypto->save.hdr.flags &= ~PWMD_FLAG_PKI;
1122 client->crypto->hdr.flags &= ~PWMD_FLAG_PKI;
1125 if ((client->opts & OPT_NO_PASSPHRASE) && !(client->flags & FLAG_NEW)
1126 && !(client->opts & OPT_INQUIRE))
1127 return send_error (ctx, GPG_ERR_WRONG_KEY_USAGE);
1129 if (lstat (client->filename, &st) == -1 && errno != ENOENT)
1130 return send_error (ctx, gpg_error_from_errno (errno));
1132 if (errno != ENOENT && !S_ISREG (st.st_mode))
1134 log_write ("%s: %s", client->filename, pwmd_strerror (GPG_ERR_ENOANO));
1135 return send_error (ctx, GPG_ERR_ENOANO);
1138 int defer = 0;
1139 rc = cache_iscached (client->filename, &defer);
1140 if (gpg_err_code (rc) == GPG_ERR_ENOENT && client->flags & FLAG_NEW)
1141 rc = 0;
1142 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
1143 rc = 0;
1145 if ((!rc && defer) || config_get_boolean ("global", "require_save_key"))
1146 client->opts |= OPT_RESET;
1148 if (!rc && (client->opts & OPT_RESET))
1150 rc = cache_clear (client->md5file);
1151 if (rc)
1152 return send_error (ctx, rc);
1154 log_write ("%s: %s", client->filename,
1155 pwmd_strerror (GPG_ERR_KEY_EXPIRED));
1156 send_status_all (STATUS_CACHE, NULL);
1159 if (!rc)
1160 rc = update_element_mtime (client, xmlDocGetRootElement (client->doc));
1162 if (rc)
1163 return send_error (ctx, rc);
1165 #ifdef WITH_AGENT
1166 if (!rc && use_agent && !client->crypto->save.pkey &&
1167 (client->flags & FLAG_NEW || client->opts & OPT_INQUIRE)
1168 && !(client->opts & OPT_NO_AGENT))
1170 rc = set_pinentry_mode (client->crypto->agent,
1171 (client->flags & FLAG_NO_PINENTRY) ? "loopback"
1172 : "ask");
1174 if (!(client->flags & FLAG_NEW))
1176 struct crypto_s *crypto;
1177 char *key = NULL;
1178 size_t keylen = 0;
1180 /* Wanting to generate a new key. Require the key to open the
1181 current file before proceeding reguardless of the
1182 require_save_key configuration parameter. */
1183 rc = cache_clear (client->md5file);
1184 if (!rc)
1186 rc = init_client_crypto (&crypto);
1187 if (!rc)
1188 crypto->client_ctx = client->ctx;
1191 if (!rc)
1192 rc = decrypt_common (client->ctx, client->opts&OPT_INQUIRE, crypto,
1193 client->filename, &key, &keylen);
1195 xfree (key);
1196 cleanup_crypto (&crypto);
1199 if (!rc)
1200 rc = send_status (client->ctx, STATUS_GENKEY, NULL);
1202 if (!rc)
1204 struct inquire_data_s idata = { 0 };
1205 char *params = client->opts & OPT_INQUIRE
1206 ? NULL : default_key_params (client->crypto);
1208 pthread_cleanup_push (xfree, params);
1209 idata.crypto = client->crypto;
1211 if (params)
1213 idata.line = params;
1214 idata.len = strlen (params);
1216 else
1217 idata.preset = 1;
1219 client->crypto->agent->inquire_data = &idata;
1220 client->crypto->agent->inquire_cb = NULL;
1221 rc = generate_key (client->crypto, params,
1222 (client->opts & OPT_NO_PASSPHRASE), 1);
1223 pthread_cleanup_pop (1);
1226 #endif
1228 if (!rc)
1229 rc = save_finalize (ctx);
1231 cleanup_crypto_stage1 (client->crypto);
1232 #ifdef WITH_AGENT
1233 (void) kill_scd (client->crypto->agent);
1234 #endif
1235 return send_error (ctx, rc);
1238 static gpg_error_t
1239 do_delete (assuan_context_t ctx, char *line)
1241 struct client_s *client = assuan_get_pointer (ctx);
1242 gpg_error_t rc;
1243 char **req;
1244 xmlNodePtr n;
1246 if (strchr (line, '\t'))
1247 req = str_split (line, "\t", 0);
1248 else
1249 req = str_split (line, " ", 0);
1251 if (!req || !*req)
1252 return GPG_ERR_SYNTAX;
1254 n = find_root_element (client, client->doc, &req, &rc, NULL, 0, 0);
1255 if (!n)
1257 strv_free (req);
1258 return rc;
1262 * No sub-node defined. Remove the entire node (root element).
1264 if (!req[1])
1266 if (n)
1268 rc = is_element_owner (client, n);
1269 if (!rc)
1271 rc = unlink_node (client, n);
1272 xmlFreeNode (n);
1276 strv_free (req);
1277 return rc;
1280 n = find_elements (client, client->doc, n->children, req + 1, &rc, NULL,
1281 NULL, NULL, 0, 0, NULL, 0);
1282 strv_free (req);
1283 if (!n)
1284 return rc;
1286 rc = is_element_owner (client, n);
1287 if (!rc)
1289 rc = unlink_node (client, n);
1290 xmlFreeNode (n);
1293 return rc;
1296 static gpg_error_t
1297 delete_command (assuan_context_t ctx, char *line)
1299 struct client_s *client = assuan_get_pointer (ctx);
1300 gpg_error_t rc;
1301 struct argv_s *args[] = {
1302 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1303 NULL
1306 rc = parse_options (&line, args, client);
1307 if (rc)
1308 return send_error (ctx, rc);
1310 if (client->opts & OPT_INQUIRE)
1312 unsigned char *result;
1313 size_t len;
1315 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1316 if (rc)
1317 return send_error (ctx, rc);
1319 pthread_cleanup_push (xfree, result);
1320 rc = do_delete (ctx, (char *)result);
1321 pthread_cleanup_pop (1);
1323 else
1324 rc = do_delete (ctx, line);
1326 return send_error (ctx, rc);
1329 static gpg_error_t
1330 store_command (assuan_context_t ctx, char *line)
1332 struct client_s *client = assuan_get_pointer (ctx);
1333 gpg_error_t rc;
1334 size_t len;
1335 unsigned char *result;
1336 char **req;
1337 xmlNodePtr n, parent;
1338 int has_content;
1339 char *content = NULL;
1341 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1342 if (rc)
1343 return send_error (ctx, rc);
1345 req = str_split ((char *) result, "\t", 0);
1346 xfree (result);
1348 if (!req || !*req)
1349 return send_error (ctx, GPG_ERR_SYNTAX);
1351 len = strv_length (req);
1352 has_content = line[strlen (line) - 1] != '\t' && len > 1;
1353 if (*(req + 1) && !valid_element_path (req, has_content))
1355 strv_free (req);
1356 return send_error (ctx, GPG_ERR_INV_VALUE);
1359 if (has_content || !*req[len - 1])
1361 has_content = 1;
1362 content = req[len - 1];
1363 req[len - 1] = NULL;
1366 again:
1367 n = find_root_element (client, client->doc, &req, &rc, NULL, 0, 0);
1368 if (rc && rc == GPG_ERR_ELEMENT_NOT_FOUND)
1370 rc = new_root_element (client, client->doc, *req);
1371 if (rc)
1373 strv_free (req);
1374 return send_error (ctx, rc);
1377 goto again;
1380 if (!n)
1382 strv_free (req);
1383 return send_error (ctx, rc);
1386 parent = n;
1388 if (req[1] && *req[1])
1390 if (!n->children)
1391 parent = create_elements_cb (client, 1, n, req + 1, &rc, NULL);
1392 else
1393 parent = find_elements (client, client->doc, n->children, req + 1, &rc,
1394 NULL, NULL, create_elements_cb, 0, 0, NULL,
1398 if (!rc && len > 1)
1400 rc = is_element_owner (client, parent);
1401 if (!rc)
1403 n = find_text_node (parent->children);
1404 if (n)
1405 xmlNodeSetContent (n, (xmlChar *) content);
1406 else
1407 xmlNodeAddContent (parent, (xmlChar *) content);
1409 update_element_mtime (client, parent);
1413 xfree (content);
1414 strv_free (req);
1415 return send_error (ctx, rc);
1418 static gpg_error_t
1419 xfer_data (assuan_context_t ctx, const char *line, int total)
1421 int to_send;
1422 int sent = 0;
1423 gpg_error_t rc;
1424 int progress = config_get_integer ("global", "xfer_progress");
1425 int flush = 0;
1427 progress =
1428 progress > 0 ? (progress / ASSUAN_LINELENGTH) * ASSUAN_LINELENGTH : 0;
1429 to_send = total < ASSUAN_LINELENGTH ? total : ASSUAN_LINELENGTH;
1430 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1432 if (rc)
1433 return rc;
1435 again:
1438 if (sent + to_send > total)
1439 to_send = total - sent;
1441 rc = assuan_send_data (ctx, flush ? NULL : (char *) line + sent,
1442 flush ? 0 : to_send);
1443 if (!rc)
1445 sent += flush ? 0 : to_send;
1447 if ((progress && !(sent % progress) && sent != total) ||
1448 (sent == total && flush))
1449 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1451 if (!flush && !rc && sent == total)
1453 flush = 1;
1454 goto again;
1458 while (!rc && sent < total);
1460 return rc;
1463 static gpg_error_t
1464 do_get (assuan_context_t ctx, char *line)
1466 struct client_s *client = assuan_get_pointer (ctx);
1467 gpg_error_t rc;
1468 char **req;
1469 xmlNodePtr n;
1471 req = str_split (line, "\t", 0);
1473 if (!req || !*req)
1475 strv_free (req);
1476 return GPG_ERR_SYNTAX;
1479 n = find_root_element (client, client->doc, &req, &rc, NULL, 0, 0);
1480 if (!n)
1482 strv_free (req);
1483 return rc;
1486 if (req[1])
1488 find_elements (client, client->doc, n->children, req + 1, &rc, NULL, NULL, NULL,
1489 0, 0, NULL, 0);
1491 strv_free (req);
1492 if (rc)
1493 return rc;
1495 if (!n || !n->children)
1496 return GPG_ERR_NO_DATA;
1498 n = find_text_node (n->children);
1499 if (!n || !n->content || !*n->content)
1500 return GPG_ERR_NO_DATA;
1502 rc = xfer_data (ctx, (char *) n->content, xmlStrlen (n->content));
1503 return rc;
1506 static gpg_error_t
1507 get_command (assuan_context_t ctx, char *line)
1509 struct client_s *client = assuan_get_pointer (ctx);
1510 gpg_error_t rc;
1511 struct argv_s *args[] = {
1512 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1513 NULL
1516 rc = parse_options (&line, args, client);
1517 if (rc)
1518 return send_error (ctx, rc);
1520 if (client->opts & OPT_INQUIRE)
1522 unsigned char *result;
1523 size_t len;
1525 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1526 if (rc)
1527 return send_error (ctx, rc);
1529 pthread_cleanup_push (xfree, result);
1530 rc = do_get (ctx, (char *)result);
1531 pthread_cleanup_pop (1);
1533 else
1534 rc = do_get (ctx, line);
1536 return send_error (ctx, rc);
1539 static void list_command_cleanup1 (void *arg);
1540 static gpg_error_t
1541 realpath_command (assuan_context_t ctx, char *line)
1543 struct string_s *string = NULL;
1544 gpg_error_t rc;
1545 struct client_s *client = assuan_get_pointer (ctx);
1546 struct argv_s *args[] = {
1547 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1548 NULL
1551 rc = parse_options (&line, args, client);
1552 if (rc)
1553 return send_error (ctx, rc);
1555 if (client->opts & OPT_INQUIRE)
1557 unsigned char *result;
1558 size_t len;
1560 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1561 if (rc)
1562 return send_error (ctx, rc);
1564 pthread_cleanup_push (xfree, result);
1565 rc = build_realpath (client, client->doc, (char *)result, &string);
1566 pthread_cleanup_pop (1);
1568 else
1569 rc = build_realpath (client, client->doc, line, &string);
1571 if (!rc)
1573 pthread_cleanup_push (list_command_cleanup1, string);
1574 rc = xfer_data (ctx, string->str, string->len);
1575 pthread_cleanup_pop (1);
1578 return send_error (ctx, rc);
1581 static void
1582 list_command_cleanup1 (void *arg)
1584 if (arg)
1585 string_free ((struct string_s *) arg, 1);
1588 static void
1589 list_command_cleanup2 (void *arg)
1591 struct element_list_s *elements = arg;
1593 if (elements)
1595 if (elements->list)
1597 int total = slist_length (elements->list);
1598 int i;
1600 for (i = 0; i < total; i++)
1602 char *tmp = slist_nth_data (elements->list, i);
1603 xfree (tmp);
1606 slist_free (elements->list);
1609 if (elements->prefix)
1610 xfree (elements->prefix);
1612 if (elements->req)
1613 strv_free (elements->req);
1615 xfree (elements);
1619 static gpg_error_t
1620 parse_list_opt_norecurse (void *data, void *value)
1622 struct client_s *client = data;
1624 client->opts &= ~(OPT_LIST_RECURSE);
1625 return 0;
1628 static gpg_error_t
1629 parse_opt_verbose (void *data, void *value)
1631 struct client_s *client = data;
1633 client->opts |= OPT_VERBOSE;
1634 return 0;
1637 static gpg_error_t
1638 parse_list_opt_target (void *data, void *value)
1640 struct client_s *client = data;
1642 client->opts |= OPT_LIST_WITH_TARGET;
1643 return 0;
1646 static gpg_error_t
1647 parse_list_opt_all (void *data, void *value)
1649 struct client_s *client = data;
1651 client->opts |= OPT_LIST_ALL;
1652 return 0;
1655 static gpg_error_t
1656 list_path_once (struct client_s *client, char *line,
1657 struct element_list_s *elements, struct string_s *result)
1659 gpg_error_t rc;
1661 elements->req = str_split (line, " ", 0);
1662 if (!elements->req)
1663 strv_printf (&elements->req, "%s", line);
1665 rc = create_path_list (client, client->doc, elements, *elements->req);
1666 if ((rc == GPG_ERR_ELOOP || rc == GPG_ERR_EACCES) && elements->verbose)
1667 rc = 0;
1669 if (!rc)
1671 int total = slist_length (elements->list);
1673 if (total)
1675 int i;
1677 for (i = 0; i < total; i++)
1679 char *tmp = slist_nth_data (elements->list, i);
1681 string_append_printf (result, "%s%s", tmp,
1682 i + 1 == total ? "" : "\n");
1685 else
1686 rc = GPG_ERR_NO_DATA;
1689 return rc;
1692 static int
1693 has_list_flag (char *path, char *flags)
1695 char *p = path;
1697 while (*p && *++p != ' ');
1699 if (!*p)
1700 return 0;
1702 for (; *p; p++)
1704 char *f;
1706 for (f = flags; *f && *f != ' '; f++)
1708 if (*p == *f)
1709 return 1;
1713 return 0;
1716 static gpg_error_t
1717 do_list (assuan_context_t ctx, char *line)
1719 struct client_s *client = assuan_get_pointer (ctx);
1720 gpg_error_t rc;
1721 struct element_list_s *elements = NULL;
1723 elements = xcalloc (1, sizeof (struct element_list_s));
1724 if (!elements)
1725 return GPG_ERR_ENOMEM;
1727 elements->recurse = client->opts & OPT_LIST_RECURSE;
1728 elements->verbose =
1729 (client->opts & OPT_VERBOSE) | (client->opts & OPT_LIST_WITH_TARGET);
1730 elements->with_target = client->opts & OPT_LIST_WITH_TARGET;
1732 if (!line || !*line)
1734 struct string_s *str = NULL;
1736 pthread_cleanup_push (list_command_cleanup2, elements);
1737 rc = list_root_elements (client, client->doc, &str, elements->verbose,
1738 elements->with_target);
1739 pthread_cleanup_pop (1);
1740 pthread_cleanup_push (list_command_cleanup1, str);
1742 if (!rc)
1744 if (client->opts & OPT_LIST_ALL)
1746 char **roots = str_split (str->str, "\n", 0);
1747 char **p;
1749 pthread_cleanup_push (req_cleanup, roots);
1750 string_truncate (str, 0);
1752 for (p = roots; *p; p++)
1754 if (strchr (*p, ' '))
1756 if (has_list_flag (*p, "EOP"))
1758 string_append_printf (str, "%s%s", *p,
1759 *(p + 1) ? "\n" : "");
1760 continue;
1764 elements = xcalloc (1, sizeof (struct element_list_s));
1765 if (!elements)
1767 rc = GPG_ERR_ENOMEM;
1768 break;
1771 elements->recurse = client->opts & OPT_LIST_RECURSE;
1772 elements->verbose =
1773 (client->opts & OPT_VERBOSE) | (client->opts &
1774 OPT_LIST_WITH_TARGET);
1775 elements->with_target = client->opts & OPT_LIST_WITH_TARGET;
1776 pthread_cleanup_push (list_command_cleanup2, elements);
1777 rc = list_path_once (client, *p, elements, str);
1778 pthread_cleanup_pop (1);
1779 if (rc)
1780 break;
1782 if (*(p + 1))
1783 string_append (str, "\n");
1786 pthread_cleanup_pop (1);
1789 if (!rc)
1790 rc = xfer_data (ctx, str->str, str->len);
1793 pthread_cleanup_pop (1);
1794 return rc;
1797 pthread_cleanup_push (list_command_cleanup2, elements);
1798 struct string_s *str = string_new (NULL);
1799 pthread_cleanup_push (list_command_cleanup1, str);
1800 rc = list_path_once (client, line, elements, str);
1801 if (!rc)
1802 rc = xfer_data (ctx, str->str, str->len);
1804 pthread_cleanup_pop (1);
1805 pthread_cleanup_pop (1);
1806 return rc;
1809 static gpg_error_t
1810 list_command (assuan_context_t ctx, char *line)
1812 struct client_s *client = assuan_get_pointer (ctx);
1813 gpg_error_t rc;
1814 struct argv_s *args[] = {
1815 &(struct argv_s) {"no-recurse", OPTION_TYPE_NOARG,
1816 parse_list_opt_norecurse},
1817 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_opt_verbose},
1818 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1819 &(struct argv_s) {"with-target", OPTION_TYPE_NOARG,
1820 parse_list_opt_target},
1821 &(struct argv_s) {"all", OPTION_TYPE_NOARG, parse_list_opt_all},
1822 NULL
1825 if (disable_list_and_dump == 1)
1826 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
1828 client->opts |= OPT_LIST_RECURSE;
1829 rc = parse_options (&line, args, client);
1830 if (rc)
1831 return send_error (ctx, rc);
1833 if (client->opts & OPT_LIST_ALL)
1834 client->opts |= OPT_LIST_RECURSE | OPT_VERBOSE;
1836 if (client->opts & OPT_INQUIRE)
1838 unsigned char *result;
1839 size_t len;
1841 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1842 if (rc)
1843 return send_error (ctx, rc);
1845 pthread_cleanup_push (xfree, result);
1846 rc = do_list (ctx, (char *)result);
1847 pthread_cleanup_pop (1);
1849 else
1850 rc = do_list (ctx, line);
1852 return send_error (ctx, rc);
1856 * req[0] - element path
1858 static gpg_error_t
1859 attribute_list (assuan_context_t ctx, char **req)
1861 struct client_s *client = assuan_get_pointer (ctx);
1862 char **attrlist = NULL;
1863 int i = 0;
1864 char **path = NULL;
1865 xmlAttrPtr a;
1866 xmlNodePtr n, an;
1867 char *line;
1868 gpg_error_t rc;
1870 if (!req || !req[0])
1871 return GPG_ERR_SYNTAX;
1873 client->flags |= FLAG_ACL_IGNORE;
1875 if ((path = str_split (req[0], "\t", 0)) == NULL)
1878 * The first argument may be only a root element.
1880 if ((path = str_split (req[0], " ", 0)) == NULL)
1881 return GPG_ERR_SYNTAX;
1884 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 0);
1885 if (!n)
1887 strv_free (path);
1888 return rc;
1891 if (client->flags & FLAG_ACL_ERROR)
1893 client->flags &= ~FLAG_ACL_IGNORE;
1894 if (path[1])
1896 strv_free (path);
1897 return GPG_ERR_EACCES;
1900 client->flags &= ~FLAG_ACL_ERROR;
1903 if (path[1])
1905 n = find_elements (client, client->doc, n->children, path + 1, &rc,
1906 NULL, NULL, NULL, 0, 0, NULL, 0);
1908 if (!n)
1910 strv_free (path);
1911 return rc;
1915 strv_free (path);
1917 for (a = n->properties; a; a = a->next)
1919 char **pa;
1921 if ((pa = xrealloc (attrlist, (i + 2) * sizeof (char *))) == NULL)
1923 if (attrlist)
1924 strv_free (attrlist);
1926 log_write ("%s(%i): %s", __FILE__, __LINE__,
1927 pwmd_strerror (GPG_ERR_ENOMEM));
1928 return GPG_ERR_ENOMEM;
1931 attrlist = pa;
1932 an = a->children;
1933 attrlist[i] = str_asprintf ("%s %s", (char *) a->name,
1935 && an->content ? (char *) an->content : "");
1937 if (!attrlist[i])
1939 strv_free (attrlist);
1940 log_write ("%s(%i): %s", __FILE__, __LINE__,
1941 pwmd_strerror (GPG_ERR_ENOMEM));
1942 return GPG_ERR_ENOMEM;
1945 attrlist[++i] = NULL;
1948 if (!attrlist)
1949 return GPG_ERR_NO_DATA;
1951 line = strv_join ("\n", attrlist);
1953 if (!line)
1955 log_write ("%s(%i): %s", __FILE__, __LINE__,
1956 pwmd_strerror (GPG_ERR_ENOMEM));
1957 strv_free (attrlist);
1958 return GPG_ERR_ENOMEM;
1961 pthread_cleanup_push (xfree, line);
1962 pthread_cleanup_push (req_cleanup, attrlist);
1963 rc = xfer_data (ctx, line, strlen (line));
1964 pthread_cleanup_pop (1);
1965 pthread_cleanup_pop (1);
1966 return rc;
1970 * req[0] - attribute
1971 * req[1] - element path
1973 static gpg_error_t
1974 attribute_delete (struct client_s *client, char **req)
1976 xmlNodePtr n;
1977 char **path = NULL;
1978 gpg_error_t rc;
1980 if (!req || !req[0] || !req[1])
1981 return GPG_ERR_SYNTAX;
1983 if (!strcmp (req[0], "_name"))
1984 return GPG_ERR_INV_ATTR;
1986 if ((path = str_split (req[1], "\t", 0)) == NULL)
1989 * The first argument may be only a root element.
1991 if ((path = str_split (req[1], " ", 0)) == NULL)
1992 return GPG_ERR_SYNTAX;
1995 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 0);
1996 if (!n)
1997 goto fail;
1999 if (path[1])
2001 n = find_elements (client, client->doc, n->children, path + 1, &rc,
2002 NULL, NULL, NULL, 0, 0, NULL, 0);
2003 if (!n)
2004 goto fail;
2007 if (!strcmp (req[0], (char *) "_acl"))
2009 rc = is_element_owner (client, n);
2010 if (rc)
2011 goto fail;
2014 rc = delete_attribute (client, n, (xmlChar *) req[0]);
2016 fail:
2017 strv_free (path);
2018 return rc;
2021 static xmlNodePtr
2022 create_element_path (struct client_s *client,
2023 char ***elements, gpg_error_t * rc, xmlNodePtr parent)
2025 char **req = *elements;
2026 char **req_orig = strv_dup (req);
2027 xmlNodePtr n = NULL;
2029 *rc = 0;
2031 if (!req_orig)
2033 *rc = GPG_ERR_ENOMEM;
2034 log_write ("%s(%i): %s", __FILE__, __LINE__,
2035 pwmd_strerror (GPG_ERR_ENOMEM));
2036 goto fail;
2039 again:
2040 n = find_root_element (client, client->doc, &req, rc, NULL, 0, 0);
2041 if (!n)
2043 if (*rc != GPG_ERR_ELEMENT_NOT_FOUND)
2044 goto fail;
2046 *rc = new_root_element (client, client->doc, req[0]);
2047 if (*rc)
2048 goto fail;
2050 goto again;
2052 else if (n == parent)
2054 *rc = GPG_ERR_CONFLICT;
2055 goto fail;
2058 if (req[1])
2060 if (!n->children)
2061 n = create_target_elements_cb (client, 1, n, req + 1, rc, NULL);
2062 else
2063 n = find_elements (client, client->doc, n->children, req + 1, rc,
2064 NULL, NULL, create_target_elements_cb, 0, 0,
2065 parent, 0);
2067 if (!n)
2068 goto fail;
2071 * Reset the position of the element tree now that the elements
2072 * have been created.
2074 strv_free (req);
2075 req = req_orig;
2076 req_orig = NULL;
2077 n = find_root_element (client, client->doc, &req, rc, NULL, 0, 0);
2078 if (!n)
2079 goto fail;
2081 n = find_elements (client, client->doc, n->children, req + 1, rc,
2082 NULL, NULL, NULL, 0, 0, NULL, 0);
2083 if (!n)
2084 goto fail;
2087 fail:
2088 if (req_orig)
2089 strv_free (req_orig);
2091 *elements = req;
2092 return n;
2096 * Creates a "target" attribute. When other commands encounter an element with
2097 * this attribute, the element path is modified to the target value. If the
2098 * source element path doesn't exist when using 'ATTR SET target', it is
2099 * created, but the destination element path must exist.
2101 * req[0] - source element path
2102 * req[1] - destination element path
2104 static gpg_error_t
2105 target_attribute (struct client_s *client, char **req)
2107 char **src, **dst, *line = NULL, **odst = NULL;
2108 gpg_error_t rc;
2109 xmlNodePtr n;
2111 if (!req || !req[0] || !req[1])
2112 return GPG_ERR_SYNTAX;
2114 if ((src = str_split (req[0], "\t", 0)) == NULL)
2117 * The first argument may be only a root element.
2119 if ((src = str_split (req[0], " ", 0)) == NULL)
2120 return GPG_ERR_SYNTAX;
2123 if (!valid_element_path (src, 0))
2124 return GPG_ERR_INV_VALUE;
2126 if ((dst = str_split (req[1], "\t", 0)) == NULL)
2129 * The first argument may be only a root element.
2131 if ((dst = str_split (req[1], " ", 0)) == NULL)
2133 rc = GPG_ERR_SYNTAX;
2134 goto fail;
2138 odst = strv_dup (dst);
2139 if (!odst)
2141 rc = GPG_ERR_ENOMEM;
2142 goto fail;
2145 n = find_root_element (client, client->doc, &dst, &rc, NULL, 0, 0);
2147 * Make sure the destination element path exists.
2149 if (!n)
2150 goto fail;
2152 if (dst[1])
2154 n = find_elements (client, client->doc, n->children, dst + 1, &rc,
2155 NULL, NULL, NULL, 0, 0, NULL, 0);
2156 if (!n)
2157 goto fail;
2160 rc = validate_target_attribute (client, client->doc, req[0], n);
2161 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2162 goto fail;
2164 n = create_element_path (client, &src, &rc, NULL);
2165 if (rc)
2166 goto fail;
2168 line = strv_join ("\t", odst);
2169 if (!line)
2171 rc = GPG_ERR_ENOMEM;
2172 goto fail;
2175 rc = add_attribute (client, n, "target", line);
2177 fail:
2178 xfree (line);
2179 strv_free (src);
2180 strv_free (dst);
2181 strv_free (odst);
2182 return rc;
2186 * req[0] - attribute
2187 * req[1] - element path
2189 static gpg_error_t
2190 attribute_get (assuan_context_t ctx, char **req)
2192 struct client_s *client = assuan_get_pointer (ctx);
2193 xmlNodePtr n;
2194 xmlChar *a;
2195 char **path = NULL;
2196 gpg_error_t rc;
2198 if (!req || !req[0] || !req[1])
2199 return GPG_ERR_SYNTAX;
2201 if (strchr (req[1], '\t'))
2203 if ((path = str_split (req[1], "\t", 0)) == NULL)
2204 return GPG_ERR_SYNTAX;
2206 else
2208 if ((path = str_split (req[1], " ", 0)) == NULL)
2209 return GPG_ERR_SYNTAX;
2212 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 0);
2214 if (!n)
2215 goto fail;
2217 if (path[1])
2219 n = find_elements (client, client->doc, n->children, path + 1, &rc,
2220 NULL, NULL, NULL, 0, 0, NULL, 0);
2222 if (!n)
2223 goto fail;
2226 strv_free (path);
2228 if ((a = xmlGetProp (n, (xmlChar *) req[0])) == NULL)
2229 return GPG_ERR_NOT_FOUND;
2231 pthread_cleanup_push (xmlFree, a);
2233 if (*a)
2234 rc = xfer_data (ctx, (char *) a, xmlStrlen (a));
2235 else
2236 rc = GPG_ERR_NO_DATA;
2238 pthread_cleanup_pop (1);
2239 return rc;
2241 fail:
2242 strv_free (path);
2243 return rc;
2247 * req[0] - attribute
2248 * req[1] - element path
2249 * req[2] - value
2251 static gpg_error_t
2252 attribute_set (struct client_s *client, char **req)
2254 char **path = NULL;
2255 gpg_error_t rc;
2256 xmlNodePtr n;
2258 if (!req || !req[0] || !req[1])
2259 return GPG_ERR_SYNTAX;
2262 * Reserved attribute names.
2264 if (!strcmp (req[0], "_name"))
2265 return GPG_ERR_INV_ATTR;
2266 else if (!strcmp (req[0], "target"))
2267 return target_attribute (client, req + 1);
2268 else if (!valid_xml_attribute (req[0]))
2269 return GPG_ERR_INV_VALUE;
2271 if ((path = str_split (req[1], "\t", 0)) == NULL)
2274 * The first argument may be only a root element.
2276 if ((path = str_split (req[1], " ", 0)) == NULL)
2277 return GPG_ERR_SYNTAX;
2280 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 0);
2282 if (!n)
2283 goto fail;
2285 if (path[1])
2287 n = find_elements (client, client->doc, n->children, path + 1, &rc,
2288 NULL, NULL, NULL, 0, 0, NULL, 0);
2290 if (!n)
2291 goto fail;
2294 if (!strcmp (req[0], (char *) "_acl"))
2296 rc = is_element_owner (client, n);
2297 if (rc)
2298 goto fail;
2301 rc = add_attribute (client, n, req[0], req[2]);
2303 fail:
2304 strv_free (path);
2305 return rc;
2309 * req[0] - command
2310 * req[1] - attribute name or element path if command is LIST
2311 * req[2] - element path
2312 * req[2] - element path or value
2315 static gpg_error_t
2316 do_attr (assuan_context_t ctx, char *line)
2318 struct client_s *client = assuan_get_pointer (ctx);
2319 gpg_error_t rc = 0;
2320 char **req;
2322 req = str_split (line, " ", 4);
2323 if (!req || !req[0] || !req[1])
2325 strv_free (req);
2326 return GPG_ERR_SYNTAX;
2329 pthread_cleanup_push (req_cleanup, req);
2331 if (strcasecmp (req[0], "SET") == 0)
2332 rc = attribute_set (client, req + 1);
2333 else if (strcasecmp (req[0], "GET") == 0)
2334 rc = attribute_get (ctx, req + 1);
2335 else if (strcasecmp (req[0], "DELETE") == 0)
2336 rc = attribute_delete (client, req + 1);
2337 else if (strcasecmp (req[0], "LIST") == 0)
2338 rc = attribute_list (ctx, req + 1);
2339 else
2340 rc = GPG_ERR_SYNTAX;
2342 client->flags &= ~(FLAG_ACL_IGNORE|FLAG_ACL_ERROR);
2343 pthread_cleanup_pop (1);
2344 return rc;
2347 static gpg_error_t
2348 attr_command (assuan_context_t ctx, char *line)
2350 struct client_s *client = assuan_get_pointer (ctx);
2351 gpg_error_t rc;
2352 struct argv_s *args[] = {
2353 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2354 NULL
2357 rc = parse_options (&line, args, client);
2358 if (rc)
2359 return send_error (ctx, rc);
2361 if (client->opts & OPT_INQUIRE)
2363 unsigned char *result;
2364 size_t len;
2366 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2367 if (rc)
2368 return send_error (ctx, rc);
2370 pthread_cleanup_push (xfree, result);
2371 rc = do_attr (ctx, (char *)result);
2372 pthread_cleanup_pop (1);
2374 else
2375 rc = do_attr (ctx, line);
2377 return send_error (ctx, rc);
2380 static gpg_error_t
2381 parse_iscached_opt_lock (void *data, void *value)
2383 struct client_s *client = data;
2385 (void) value;
2386 client->opts |= OPT_LOCK;
2387 return 0;
2390 static gpg_error_t
2391 iscached_command (assuan_context_t ctx, char *line)
2393 struct client_s *client = assuan_get_pointer (ctx);
2394 gpg_error_t rc;
2395 struct argv_s *args[] = {
2396 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_iscached_opt_lock},
2397 NULL
2400 if (!line || !*line)
2401 return send_error (ctx, GPG_ERR_SYNTAX);
2403 rc = parse_options (&line, args, client);
2404 if (rc)
2405 return send_error (ctx, rc);
2406 else if (!valid_filename (line))
2407 return send_error (ctx, GPG_ERR_INV_VALUE);
2409 rc = cache_iscached (line, NULL);
2410 if (client->opts & OPT_LOCK
2411 && (!rc || gpg_err_code (rc) == GPG_ERR_NO_DATA))
2413 unsigned char md5file[16];
2414 gpg_error_t trc = rc;
2416 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2417 if (memcmp (md5file, client->md5file, 16))
2418 cleanup_client (client);
2420 memcpy (client->md5file, md5file, 16);
2421 rc = do_lock (client, 1);
2422 if (!rc)
2423 rc = trc;
2426 return send_error (ctx, rc);
2429 static gpg_error_t
2430 clearcache_command (assuan_context_t ctx, char *line)
2432 gpg_error_t rc = 0, all_rc = 0;
2433 unsigned char md5file[16];
2434 int i;
2435 int t;
2436 int all = 0;
2437 struct client_thread_s *once = NULL;
2439 cache_lock ();
2440 MUTEX_LOCK (&cn_mutex);
2441 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
2443 if (!line || !*line)
2444 all = 1;
2446 t = slist_length (cn_thread_list);
2448 for (i = 0; i < t; i++)
2450 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2451 assuan_peercred_t peer;
2453 if (!thd->cl)
2454 continue;
2456 /* Lock each connected clients' file mutex to prevent any other client
2457 * from accessing the cache entry (the file mutex is locked upon
2458 * command startup). The cache for the entry is not cleared if the
2459 * file mutex is locked by another client to prevent this function
2460 * from blocking.
2462 if (all)
2464 if (thd->cl->filename)
2466 rc = do_validate_peer (ctx, thd->cl->filename, &peer);
2467 all_rc = !all_rc ? rc : all_rc;
2468 if (rc)
2470 rc = 0;
2471 continue;
2475 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0, -1);
2476 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2478 if (pthread_equal (pthread_self (), thd->tid))
2479 rc = 0;
2480 else
2482 if (!thd->cl->filename ||
2483 cache_iscached (thd->cl->filename,
2484 NULL) == GPG_ERR_NO_DATA)
2486 rc = 0;
2487 continue;
2490 cache_defer_clear (thd->cl->md5file);
2493 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
2495 rc = 0;
2496 continue;
2499 if (!rc)
2501 rc = cache_clear (thd->cl->md5file);
2502 cache_unlock_mutex (thd->cl->md5file, 0);
2505 if (rc)
2506 all_rc = rc;
2508 rc = 0;
2510 /* A single data filename was specified. Lock only this data file
2511 * mutex and free the cache entry. */
2512 else
2514 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2515 rc = do_validate_peer (ctx, line, &peer);
2517 if (!rc && !memcmp (thd->cl->md5file, md5file, sizeof (md5file)))
2519 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0,
2520 -1);
2521 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2523 if (pthread_equal (pthread_self (), thd->tid))
2524 rc = 0;
2527 if (!rc)
2529 once = thd;
2530 rc = cache_clear (thd->cl->md5file);
2531 cache_unlock_mutex (thd->cl->md5file, 0);
2533 else
2535 cache_defer_clear (thd->cl->md5file);
2538 break;
2543 /* Only connected clients' cache entries have been cleared. Now clear any
2544 * remaining cache entries without clients but only if there wasn't an
2545 * error from above since this would defeat the locking check of the
2546 * remaining entries. */
2547 if (!all_rc && all)
2549 cache_clear (NULL);
2552 /* No clients are using the specified file. */
2553 else if (!all_rc && !rc && !once)
2555 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2556 rc = cache_clear (md5file);
2559 /* Release the connection mutex. */
2560 pthread_cleanup_pop (1);
2561 cache_unlock ();
2563 if (!rc)
2564 send_status_all (STATUS_CACHE, NULL);
2566 /* One or more files were locked while clearing all cache entries. */
2567 if (all_rc)
2568 rc = all_rc;
2570 return send_error (ctx, rc);
2573 static gpg_error_t
2574 cachetimeout_command (assuan_context_t ctx, char *line)
2576 int timeout;
2577 char **req = str_split (line, " ", 0);
2578 char *p;
2579 gpg_error_t rc = 0;
2580 assuan_peercred_t peer;
2582 if (!req || !*req || !req[1])
2584 strv_free (req);
2585 return send_error (ctx, GPG_ERR_SYNTAX);
2588 errno = 0;
2589 timeout = (int) strtol (req[1], &p, 10);
2590 if (errno != 0 || *p || timeout < -1)
2592 strv_free (req);
2593 return send_error (ctx, GPG_ERR_SYNTAX);
2596 rc = do_validate_peer (ctx, req[0], &peer);
2597 if (!rc)
2599 unsigned char md5file[16];
2601 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, req[0], strlen (req[0]));
2602 rc = cache_set_timeout (md5file, timeout);
2603 if (!rc || gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
2605 rc = 0;
2606 MUTEX_LOCK (&rcfile_mutex);
2607 config_set_int_param (&global_config, req[0], "cache_timeout",
2608 req[1]);
2609 MUTEX_UNLOCK (&rcfile_mutex);
2613 strv_free (req);
2614 return send_error (ctx, rc);
2617 static gpg_error_t
2618 dump_command (assuan_context_t ctx, char *line)
2620 xmlChar *xml;
2621 int len;
2622 struct client_s *client = assuan_get_pointer (ctx);
2623 gpg_error_t rc;
2625 if (disable_list_and_dump == 1)
2626 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2628 rc = peer_is_invoker(client);
2629 if (rc)
2630 return send_error (ctx, rc);
2632 xmlDocDumpFormatMemory (client->doc, &xml, &len, 1);
2634 if (!xml)
2636 log_write ("%s(%i): %s", __FILE__, __LINE__,
2637 pwmd_strerror (GPG_ERR_ENOMEM));
2638 return send_error (ctx, GPG_ERR_ENOMEM);
2641 pthread_cleanup_push (xmlFree, xml);
2642 rc = xfer_data (ctx, (char *) xml, len);
2643 pthread_cleanup_pop (1);
2644 return send_error (ctx, rc);
2647 static gpg_error_t
2648 getconfig_command (assuan_context_t ctx, char *line)
2650 struct client_s *client = assuan_get_pointer (ctx);
2651 gpg_error_t rc = 0;
2652 char filename[255] = { 0 }, param[747] = { 0 };
2653 char *p, *tmp = NULL, *fp = client->filename, *paramp = line;
2655 if (!line || !*line)
2656 return send_error (ctx, GPG_ERR_SYNTAX);
2658 if (strchr (line, ' '))
2660 sscanf (line, " %254[^ ] %746c", filename, param);
2661 paramp = param;
2662 fp = filename;
2665 if (fp && !valid_filename (fp))
2666 return send_error (ctx, GPG_ERR_INV_VALUE);
2668 paramp = str_down (paramp);
2669 if (!strcmp (paramp, "cipher") && fp)
2671 struct crypto_s *crypto = NULL;
2673 rc = init_client_crypto (&crypto);
2674 if (!rc)
2676 rc = read_data_header (fp, &crypto->hdr, NULL, NULL);
2677 if (!rc)
2679 const char *t =
2680 gcry_cipher_algo_name (cipher_to_gcrypt (crypto->hdr.flags));
2681 if (t)
2683 tmp = str_dup (t);
2684 if (tmp)
2685 str_down (tmp);
2690 UPDATE_AGENT_CTX (client, crypto);
2691 cleanup_crypto (&crypto);
2692 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
2693 return send_error (ctx, rc);
2695 if (!rc && tmp)
2696 goto done;
2698 else if (!strcmp (paramp, "cipher_iterations") && fp)
2700 struct crypto_s *crypto = NULL;
2702 rc = init_client_crypto (&crypto);
2703 if (!rc)
2705 rc = read_data_header (fp, &crypto->hdr, NULL, NULL);
2706 if (!rc)
2708 tmp = str_asprintf ("%llu",
2709 (unsigned long long) crypto->hdr.
2710 iterations);
2711 if (!tmp)
2712 rc = GPG_ERR_ENOMEM;
2716 UPDATE_AGENT_CTX (client, crypto);
2717 cleanup_crypto (&crypto);
2718 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
2719 return send_error (ctx, rc);
2721 if (!rc && tmp)
2722 goto done;
2724 else if (!strcmp (paramp, "passphrase"))
2725 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2727 p = config_get_value (fp ? fp : "global", paramp);
2728 if (!p)
2729 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2731 tmp = expand_homedir (p);
2732 xfree (p);
2733 if (!tmp)
2735 log_write ("%s(%i): %s", __FILE__, __LINE__,
2736 pwmd_strerror (GPG_ERR_ENOMEM));
2737 return send_error (ctx, GPG_ERR_ENOMEM);
2740 done:
2741 p = tmp;
2742 pthread_cleanup_push (xfree, p);
2743 rc = xfer_data (ctx, p, strlen (p));
2744 pthread_cleanup_pop (1);
2745 return send_error (ctx, rc);
2748 struct xpath_s
2750 xmlXPathContextPtr xp;
2751 xmlXPathObjectPtr result;
2752 xmlBufferPtr buf;
2753 char **req;
2756 static void
2757 xpath_command_cleanup (void *arg)
2759 struct xpath_s *xpath = arg;
2761 if (!xpath)
2762 return;
2764 req_cleanup (xpath->req);
2766 if (xpath->buf)
2767 xmlBufferFree (xpath->buf);
2769 if (xpath->result)
2770 xmlXPathFreeObject (xpath->result);
2772 if (xpath->xp)
2773 xmlXPathFreeContext (xpath->xp);
2776 static gpg_error_t
2777 do_xpath (assuan_context_t ctx, char *line)
2779 gpg_error_t rc;
2780 struct client_s *client = assuan_get_pointer (ctx);
2781 struct xpath_s _x = { 0 };
2782 struct xpath_s *xpath = &_x;
2784 if (!line || !*line)
2785 return GPG_ERR_SYNTAX;
2787 if ((xpath->req = str_split (line, "\t", 2)) == NULL)
2789 if (strv_printf (&xpath->req, "%s", line) == 0)
2790 return GPG_ERR_ENOMEM;
2793 xpath->xp = xmlXPathNewContext (client->doc);
2794 if (!xpath->xp)
2796 rc = GPG_ERR_BAD_DATA;
2797 goto fail;
2800 xpath->result =
2801 xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2802 if (!xpath->result)
2804 rc = GPG_ERR_BAD_DATA;
2805 goto fail;
2808 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2810 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2811 goto fail;
2814 rc = recurse_xpath_nodeset (client, client->doc, xpath->result->nodesetval,
2815 (xmlChar *) xpath->req[1], &xpath->buf, 0,
2816 NULL);
2817 if (rc)
2818 goto fail;
2819 else if (!xpath->req[1] && !xmlBufferLength (xpath->buf))
2821 rc = GPG_ERR_NO_DATA;
2822 goto fail;
2824 else if (xpath->req[1])
2826 rc = 0;
2827 goto fail;
2830 pthread_cleanup_push (xpath_command_cleanup, &xpath);
2831 rc = xfer_data (ctx, (char *) xmlBufferContent (xpath->buf),
2832 xmlBufferLength (xpath->buf));
2833 pthread_cleanup_pop (0);
2834 fail:
2835 xpath_command_cleanup (xpath);
2836 return rc;
2839 static gpg_error_t
2840 xpath_command (assuan_context_t ctx, char *line)
2842 struct client_s *client = assuan_get_pointer (ctx);
2843 gpg_error_t rc;
2844 struct argv_s *args[] = {
2845 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2846 NULL
2849 if (disable_list_and_dump == 1)
2850 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2852 rc = peer_is_invoker(client);
2853 if (rc)
2854 return send_error (ctx, rc);
2856 rc = parse_options (&line, args, client);
2857 if (rc)
2858 return send_error (ctx, rc);
2860 if (client->opts & OPT_INQUIRE)
2862 unsigned char *result;
2863 size_t len;
2865 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2866 if (rc)
2867 return send_error (ctx, rc);
2869 pthread_cleanup_push (xfree, result);
2870 rc = do_xpath (ctx, (char *)result);
2871 pthread_cleanup_pop (1);
2873 else
2874 rc = do_xpath (ctx, line);
2876 return send_error (ctx, rc);
2879 static gpg_error_t
2880 do_xpathattr (assuan_context_t ctx, char *line)
2882 struct client_s *client = assuan_get_pointer (ctx);
2883 gpg_error_t rc;
2884 char **req = NULL;
2885 int cmd = 0; //SET
2886 struct xpath_s _x = { 0 };
2887 struct xpath_s *xpath = &_x;
2889 if (!line || !*line)
2890 return GPG_ERR_SYNTAX;
2892 if ((req = str_split (line, " ", 3)) == NULL)
2893 return GPG_ERR_ENOMEM;
2895 if (!req[0])
2897 rc = GPG_ERR_SYNTAX;
2898 goto fail;
2901 if (!strcasecmp (req[0], "SET"))
2902 cmd = 0;
2903 else if (!strcasecmp (req[0], "DELETE"))
2904 cmd = 1;
2905 else
2907 rc = GPG_ERR_SYNTAX;
2908 goto fail;
2911 if (!req[1] || !req[2])
2913 rc = GPG_ERR_SYNTAX;
2914 goto fail;
2917 if ((xpath->req = str_split (req[2], "\t", 3)) == NULL)
2919 rc = GPG_ERR_ENOMEM;
2920 goto fail;
2923 if (!xpath->req[0] || (!xpath->req[1] && !cmd) || (xpath->req[1] && cmd))
2925 rc = GPG_ERR_SYNTAX;
2926 goto fail;
2929 xpath->xp = xmlXPathNewContext (client->doc);
2930 if (!xpath->xp)
2932 rc = GPG_ERR_BAD_DATA;
2933 goto fail;
2936 xpath->result = xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2937 if (!xpath->result)
2939 rc = GPG_ERR_BAD_DATA;
2940 goto fail;
2943 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2945 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2946 goto fail;
2949 rc = recurse_xpath_nodeset (client, client->doc, xpath->result->nodesetval,
2950 (xmlChar *) xpath->req[1], &xpath->buf, cmd,
2951 (xmlChar *) req[1]);
2953 fail:
2954 xpath_command_cleanup (xpath);
2955 strv_free (req);
2956 return rc;
2959 /* XPATHATTR SET|DELETE <name> <expression>[<TAB>[value]] */
2960 static gpg_error_t
2961 xpathattr_command (assuan_context_t ctx, char *line)
2963 struct client_s *client = assuan_get_pointer (ctx);
2964 gpg_error_t rc;
2965 struct argv_s *args[] = {
2966 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2967 NULL
2970 if (disable_list_and_dump == 1)
2971 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2973 rc = peer_is_invoker(client);
2974 if (rc)
2975 return send_error (ctx, rc);
2977 rc = parse_options (&line, args, client);
2978 if (rc)
2979 return send_error (ctx, rc);
2981 if (client->opts & OPT_INQUIRE)
2983 unsigned char *result;
2984 size_t len;
2986 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2987 if (rc)
2988 return send_error (ctx, rc);
2990 pthread_cleanup_push (xfree, result);
2991 rc = do_xpathattr (ctx, (char *)result);
2992 pthread_cleanup_pop (1);
2994 else
2995 rc = do_xpathattr (ctx, line);
2997 return send_error (ctx, rc);
3000 static gpg_error_t
3001 do_import (struct client_s *client, const char *root_element,
3002 unsigned char *content)
3004 char **dst_path = NULL;
3005 xmlDocPtr doc = NULL;
3006 xmlNodePtr n, root, copy;
3007 gpg_error_t rc;
3009 if (!content || !*content)
3011 xfree (content);
3012 return GPG_ERR_SYNTAX;
3015 if (root_element)
3016 dst_path = str_split (root_element, "\t", 0);
3018 if (dst_path && !valid_element_path (dst_path, 0))
3020 if (dst_path)
3021 strv_free (dst_path);
3023 return GPG_ERR_INV_VALUE;
3026 struct string_s *str = string_new_content ((char *)content);
3027 str = string_prepend (str, "<pwmd>");
3028 str = string_append (str, "</pwmd>");
3029 doc = xmlReadDoc ((xmlChar *) str->str, NULL, "UTF-8", XML_PARSE_NOBLANKS);
3030 string_free (str, 1);
3031 if (!doc)
3033 rc = GPG_ERR_BAD_DATA;
3034 goto fail;
3037 root = xmlDocGetRootElement (doc);
3038 xmlNodePtr root_orig = root->children;
3039 root = root->children;
3040 rc = validate_import (client, root);
3041 if (rc)
3042 goto fail;
3046 again:
3047 if (dst_path)
3049 char **path = strv_dup (dst_path);
3050 if (!path)
3052 log_write ("%s(%i): %s", __FILE__, __LINE__,
3053 pwmd_strerror (GPG_ERR_ENOMEM));
3054 rc = GPG_ERR_ENOMEM;
3055 goto fail;
3058 xmlChar *a = xmlGetProp (root, (xmlChar *) "_name");
3059 if (!a)
3061 strv_free (path);
3062 rc = GPG_ERR_INV_VALUE;
3063 goto fail;
3066 if (strv_printf (&path, "%s", (char *) a) == 0)
3068 xmlFree (a);
3069 rc = GPG_ERR_ENOMEM;
3070 goto fail;
3073 xmlFree (a);
3074 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 0);
3075 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3077 strv_free (path);
3078 goto fail;
3081 if (!rc)
3083 n = find_elements (client, client->doc, n->children, path + 1, &rc,
3084 NULL, NULL, NULL, 0, 0, NULL, 1);
3085 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3087 strv_free (path);
3088 goto fail;
3090 else if (!rc)
3092 xmlUnlinkNode (n);
3093 xmlFreeNode (n);
3094 strv_free (path);
3095 path = NULL;
3096 goto again;
3100 if (rc == GPG_ERR_ELEMENT_NOT_FOUND)
3102 n = create_element_path (client, &path, &rc, NULL);
3103 if (rc)
3104 goto fail;
3107 if (root->children)
3109 copy = xmlCopyNodeList (root->children);
3110 n = xmlAddChildList (n, copy);
3111 if (!n)
3112 rc = GPG_ERR_ENOMEM;
3115 strv_free (path);
3117 else
3119 char **path = NULL;
3121 /* Check if the content root element can create a DTD root element. */
3122 if (!xmlStrEqual ((xmlChar *) "element", root->name))
3124 rc = GPG_ERR_SYNTAX;
3125 goto fail;
3128 xmlChar *a;
3130 if ((a = xmlGetProp (root, (xmlChar *) "_name")) == NULL)
3132 rc = GPG_ERR_SYNTAX;
3133 goto fail;
3136 char *tmp = str_dup ((char *) a);
3137 xmlFree (a);
3138 int literal = is_literal_element (&tmp);
3140 if (!valid_xml_element ((xmlChar *) tmp) || literal)
3142 xfree (tmp);
3143 rc = GPG_ERR_INV_VALUE;
3144 goto fail;
3147 if (strv_printf (&path, "%s", tmp) == 0)
3149 xfree (tmp);
3150 rc = GPG_ERR_ENOMEM;
3151 goto fail;
3154 xfree (tmp);
3155 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 1);
3156 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3158 rc = GPG_ERR_BAD_DATA;
3159 goto fail;
3162 /* Overwriting the existing tree. */
3163 if (!rc)
3165 xmlUnlinkNode (n);
3166 xmlFreeNodeList (n);
3169 rc = 0;
3170 xmlSetProp (root, (xmlChar *) "_name", (xmlChar *) path[0]);
3171 n = xmlCopyNode (root, 1);
3172 n = xmlAddChildList (xmlDocGetRootElement (client->doc), n);
3173 strv_free (path);
3176 if (n && !rc)
3177 rc = update_element_mtime (client, n->parent);
3179 for (root = root_orig->next; root; root = root->next)
3181 if (root->type == XML_ELEMENT_NODE)
3182 break;
3185 root_orig = root;
3187 while (root);
3189 fail:
3190 if (doc)
3191 xmlFreeDoc (doc);
3193 if (dst_path)
3194 strv_free (dst_path);
3196 return rc;
3199 static gpg_error_t
3200 parse_import_opt_root (void *data, void *value)
3202 struct client_s *client = data;
3204 client->import_root = str_dup (value);
3205 return client->import_root ? 0 : GPG_ERR_ENOMEM;
3208 static gpg_error_t
3209 import_command (assuan_context_t ctx, char *line)
3211 gpg_error_t rc;
3212 struct client_s *client = assuan_get_pointer (ctx);
3213 unsigned char *result;
3214 size_t len;
3215 struct argv_s *args[] = {
3216 &(struct argv_s) {"root", OPTION_TYPE_ARG, parse_import_opt_root},
3217 NULL
3220 xfree (client->import_root);
3221 client->import_root = NULL;
3222 rc = parse_options (&line, args, client);
3223 if (rc)
3224 return send_error (ctx, rc);
3226 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3227 if (rc)
3229 xfree (client->import_root);
3230 client->import_root = NULL;
3231 return send_error (ctx, rc);
3234 rc = do_import (client, client->import_root, result);
3235 xfree (client->import_root);
3236 client->import_root = NULL;
3237 return send_error (ctx, rc);
3240 static gpg_error_t
3241 do_lock (struct client_s *client, int add)
3243 gpg_error_t rc = lock_file_mutex (client, add);
3245 if (!rc)
3246 client->flags |= FLAG_LOCK_CMD;
3248 return rc;
3251 static gpg_error_t
3252 lock_command (assuan_context_t ctx, char *line)
3254 struct client_s *client = assuan_get_pointer (ctx);
3255 gpg_error_t rc = do_lock (client, 0);
3257 return send_error (ctx, rc);
3260 static gpg_error_t
3261 unlock_command (assuan_context_t ctx, char *line)
3263 struct client_s *client = assuan_get_pointer (ctx);
3264 gpg_error_t rc;
3266 rc = unlock_file_mutex (client, 0);
3267 return send_error (ctx, rc);
3270 static gpg_error_t
3271 option_command (assuan_context_t ctx, char *line)
3273 struct client_s *client = assuan_get_pointer (ctx);
3274 gpg_error_t rc = 0;
3275 struct pinentry_option_s *pin_opts = &client->pinentry_opts;
3276 #ifdef WITH_AGENT
3277 struct agent_s *agent = client->crypto->agent;
3278 #endif
3279 char namebuf[255] = { 0 };
3280 char *name = namebuf;
3281 char *value = NULL, *p, *tmp = NULL;
3283 p = strchr (line, '=');
3284 if (!p)
3286 strncpy (namebuf, line, sizeof(namebuf));
3287 namebuf[sizeof(namebuf)-1] = 0;
3289 else
3291 strncpy (namebuf, line, strlen (line)-strlen (p));
3292 namebuf[sizeof(namebuf)-1] = 0;
3293 value = p+1;
3296 log_write1 ("OPTION name='%s' value='%s'", name, value);
3298 if (strcasecmp (name, (char *) "log_level") == 0)
3300 long l = 0;
3302 if (value)
3304 l = strtol (value, NULL, 10);
3306 if (l < 0 || l > 2)
3307 return send_error (ctx, GPG_ERR_INV_VALUE);
3309 else
3310 return send_error (ctx, GPG_ERR_INV_VALUE);
3312 MUTEX_LOCK (&rcfile_mutex);
3313 config_set_int_param (&global_config, "global", "log_level", value);
3314 MUTEX_UNLOCK (&rcfile_mutex);
3315 goto done;
3317 else if (strcasecmp (name, (char *) "lock-timeout") == 0)
3319 long n = 0;
3321 if (value)
3323 n = strtol (value, &tmp, 10);
3324 if (tmp && *tmp)
3325 return send_error (ctx, GPG_ERR_INV_VALUE);
3328 client->lock_timeout = n;
3329 goto done;
3331 else if (strcasecmp (name, (char *) "NAME") == 0)
3333 if (value && strchr (value, ' '))
3334 rc = GPG_ERR_INV_VALUE;
3335 else
3337 tmp = pthread_getspecific (thread_name_key);
3338 xfree (tmp);
3339 MUTEX_LOCK (&cn_mutex);
3340 xfree (client->thd->name);
3341 client->thd->name = NULL;
3343 if (!value || !*value)
3344 pthread_setspecific (thread_name_key, str_dup (""));
3345 else
3347 client->thd->name = str_dup (value);
3348 pthread_setspecific (thread_name_key, str_dup (value));
3351 MUTEX_UNLOCK (&cn_mutex);
3353 goto done;
3355 else if (strcasecmp (name, (char *) "lc-messages") == 0)
3357 xfree (pin_opts->lc_messages);
3358 pin_opts->lc_messages = NULL;
3359 if (value && *value)
3360 pin_opts->lc_messages = str_dup (value);
3361 #ifdef WITH_AGENT
3362 if (use_agent)
3363 rc = set_agent_option (client->crypto->agent, "lc-messages", value);
3364 #endif
3366 else if (strcasecmp (name, (char *) "lc-ctype") == 0)
3368 xfree (pin_opts->lc_ctype);
3369 pin_opts->lc_ctype = NULL;
3370 if (value && *value)
3371 pin_opts->lc_ctype = str_dup (value);
3372 #ifdef WITH_AGENT
3373 if (use_agent)
3374 rc = set_agent_option (client->crypto->agent, "lc-ctype", value);
3375 #endif
3377 else if (strcasecmp (name, (char *) "ttyname") == 0)
3379 xfree (pin_opts->ttyname);
3380 pin_opts->ttyname = NULL;
3381 if (value && *value)
3382 pin_opts->ttyname = str_dup (value);
3383 #ifdef WITH_AGENT
3384 if (use_agent)
3385 rc = set_agent_option (client->crypto->agent, "ttyname", value);
3386 #endif
3388 else if (strcasecmp (name, (char *) "ttytype") == 0)
3390 xfree (pin_opts->ttytype);
3391 pin_opts->ttytype = NULL;
3392 if (value && *value)
3393 pin_opts->ttytype = str_dup (value);
3394 #ifdef WITH_AGENT
3395 if (use_agent)
3396 rc = set_agent_option (client->crypto->agent, "ttytype", value);
3397 #endif
3399 else if (strcasecmp (name, (char *) "display") == 0)
3401 xfree (pin_opts->display);
3402 pin_opts->display = NULL;
3403 if (value && *value)
3404 pin_opts->display = str_dup (value);
3405 #ifdef WITH_AGENT
3406 if (use_agent)
3407 rc = set_agent_option (client->crypto->agent, "display", value);
3408 #endif
3410 else if (strcasecmp (name, (char *) "pinentry-desc") == 0)
3412 xfree (pin_opts->desc);
3413 pin_opts->desc = NULL;
3414 if (value && *value)
3415 pin_opts->desc = str_dup (value);
3417 else if (strcasecmp (name, (char *) "pinentry-title") == 0)
3419 xfree (pin_opts->title);
3420 pin_opts->title = NULL;
3421 if (value && *value)
3422 pin_opts->title = str_dup (value);
3424 else if (strcasecmp (name, (char *) "pinentry-prompt") == 0)
3426 xfree (pin_opts->prompt);
3427 pin_opts->prompt = NULL;
3428 if (value && *value)
3429 pin_opts->prompt = str_dup (value);
3432 else if (strcasecmp (name, "pinentry-timeout") == 0)
3434 char *p = NULL;
3435 int n;
3437 if (!value)
3438 goto done;
3440 n = (int) strtol (value, &p, 10);
3442 if (*p || n < 0)
3443 return send_error (ctx, GPG_ERR_INV_VALUE);
3445 pin_opts->timeout = n;
3446 MUTEX_LOCK (&rcfile_mutex);
3447 config_set_int_param (&global_config,
3448 client->filename ? client->filename : "global",
3449 "pinentry_timeout", value);
3450 MUTEX_UNLOCK (&rcfile_mutex);
3451 goto done;
3453 else if (strcasecmp (name, "disable-pinentry") == 0)
3455 int n = 1;
3457 if (value && *value)
3459 n = (int) strtol (value, &tmp, 10);
3460 if (*tmp || n < 0 || n > 1)
3461 return send_error (ctx, GPG_ERR_INV_VALUE);
3464 if (n)
3465 client->flags |= FLAG_NO_PINENTRY;
3466 else
3467 client->flags &= ~FLAG_NO_PINENTRY;
3469 #ifdef WITH_AGENT
3470 if (use_agent)
3472 if (client->flags & FLAG_NO_PINENTRY)
3473 rc = set_agent_option (client->crypto->agent, "pinentry-mode",
3474 "loopback");
3475 else
3476 rc = set_agent_option (client->crypto->agent, "pinentry-mode",
3477 "ask");
3479 if (rc)
3480 return send_error (ctx, rc);
3482 #endif
3484 else
3485 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
3487 done:
3488 #ifdef WITH_AGENT
3489 if (!rc && use_agent && agent)
3491 rc = pinentry_merge_options (&client->crypto->agent->pinentry_opts,
3492 pin_opts);
3494 #endif
3496 return send_error (ctx, rc);
3499 static gpg_error_t
3500 do_rename (assuan_context_t ctx, char *line)
3502 struct client_s *client = assuan_get_pointer (ctx);
3503 gpg_error_t rc;
3504 char **req, **src, *dst;
3505 xmlNodePtr n, ndst;
3507 req = str_split (line, " ", 0);
3509 if (!req || !req[0] || !req[1])
3511 strv_free (req);
3512 return GPG_ERR_SYNTAX;
3515 dst = req[1];
3516 is_literal_element (&dst);
3518 if (!valid_xml_element ((xmlChar *) dst))
3520 strv_free (req);
3521 return GPG_ERR_INV_VALUE;
3524 if (strchr (req[0], '\t'))
3525 src = str_split (req[0], "\t", 0);
3526 else
3527 src = str_split (req[0], " ", 0);
3529 if (!src || !*src)
3531 rc = GPG_ERR_SYNTAX;
3532 goto fail;
3535 n = find_root_element (client, client->doc, &src, &rc, NULL, 0, 0);
3536 if (src[1] && n)
3537 n = find_elements (client, client->doc, n->children, src + 1, &rc, NULL, NULL,
3538 NULL, 0, 0, NULL, 0);
3540 if (!n)
3541 goto fail;
3543 rc = is_element_owner (client, n);
3544 if (rc)
3545 goto fail;
3547 xmlChar *a = xmlGetProp (n, (xmlChar *) "_name");
3548 if (!a)
3550 rc = GPG_ERR_ENOMEM;
3551 goto fail;
3554 /* To prevent unwanted effects:
3556 * <root name="a"><b/></root>
3558 * RENAME a<TAB>b b
3560 if (xmlStrEqual (a, (xmlChar *) dst))
3562 xmlFree (a);
3563 rc = GPG_ERR_AMBIGUOUS_NAME;
3564 goto fail;
3567 xmlFree (a);
3568 char **tmp = NULL;
3569 if (src[1])
3571 char **p;
3573 for (p = src; *p; p++)
3575 if (!*(p + 1))
3576 break;
3577 strv_printf (&tmp, "%s", *p);
3581 strv_printf (&tmp, "!%s", dst);
3582 ndst = find_root_element (client, client->doc, &tmp, &rc, NULL, 0, 0);
3583 if (!ndst && rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3585 strv_free (tmp);
3586 goto fail;
3589 if (tmp[1] && ndst)
3590 ndst = find_elements (client, client->doc, ndst->children, tmp + 1, &rc, NULL,
3591 NULL, NULL, 0, 0, NULL, 0);
3593 strv_free (tmp);
3594 if (!ndst && rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3595 goto fail;
3597 rc = 0;
3599 /* Target may exist:
3601 * <root name="a"/>
3602 * <root name="b" target="a"/>
3604 * RENAME b a
3606 * Would need to do:
3607 * RENAME !b a
3609 if (ndst == n)
3611 rc = GPG_ERR_AMBIGUOUS_NAME;
3612 goto fail;
3615 if (ndst)
3617 rc = is_element_owner (client, ndst);
3618 if (rc)
3619 goto fail;
3621 unlink_node (client, ndst);
3622 xmlFreeNodeList (ndst);
3625 rc = add_attribute (client, n, "_name", dst);
3627 fail:
3628 strv_free (req);
3629 strv_free (src);
3630 return rc;
3633 static gpg_error_t
3634 rename_command (assuan_context_t ctx, char *line)
3636 struct client_s *client = assuan_get_pointer (ctx);
3637 gpg_error_t rc;
3638 struct argv_s *args[] = {
3639 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3640 NULL
3643 rc = parse_options (&line, args, client);
3644 if (rc)
3645 return send_error (ctx, rc);
3647 if (client->opts & OPT_INQUIRE)
3649 unsigned char *result;
3650 size_t len;
3652 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3653 if (rc)
3654 return send_error (ctx, rc);
3656 pthread_cleanup_push (xfree, result);
3657 rc = do_rename (ctx, (char *)result);
3658 pthread_cleanup_pop (1);
3660 else
3661 rc = do_rename (ctx, line);
3663 return send_error (ctx, rc);
3666 static gpg_error_t
3667 do_copy (assuan_context_t ctx, char *line)
3669 struct client_s *client = assuan_get_pointer (ctx);
3670 gpg_error_t rc;
3671 char **req, **src = NULL, **dst = NULL;
3672 xmlNodePtr nsrc, ndst, new = NULL;
3674 req = str_split (line, " ", 0);
3675 if (!req || !req[0] || !req[1])
3677 strv_free (req);
3678 return GPG_ERR_SYNTAX;
3681 if (strchr (req[0], '\t'))
3682 src = str_split (req[0], "\t", 0);
3683 else
3684 src = str_split (req[0], " ", 0);
3686 if (!src || !*src)
3688 rc = GPG_ERR_SYNTAX;
3689 goto fail;
3692 if (strchr (req[1], '\t'))
3693 dst = str_split (req[1], "\t", 0);
3694 else
3695 dst = str_split (req[1], " ", 0);
3697 if (!dst || !*dst)
3699 rc = GPG_ERR_SYNTAX;
3700 goto fail;
3703 if (!valid_element_path (dst, 0))
3705 rc = GPG_ERR_INV_VALUE;
3706 goto fail;
3709 nsrc = find_root_element (client, client->doc, &src, &rc, NULL, 0, 0);
3710 if (nsrc && src[1])
3711 nsrc = find_elements (client, client->doc, nsrc->children, src + 1, &rc, NULL,
3712 NULL, NULL, 0, 0, NULL, 0);
3714 if (!nsrc)
3715 goto fail;
3717 new = xmlCopyNodeList (nsrc);
3718 if (!new)
3720 rc = GPG_ERR_ENOMEM;
3721 goto fail;
3724 int create = 0;
3725 ndst = find_root_element (client, client->doc, &dst, &rc, NULL, 0, 0);
3726 if (ndst && dst[1])
3728 if (ndst->children)
3729 ndst = find_elements (client, client->doc, ndst->children, dst + 1, &rc, NULL,
3730 NULL, create_target_elements_cb, 0, 0, NULL, 0);
3731 else
3732 create = 1;
3734 else
3735 create = 1;
3737 if (!ndst && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3738 goto fail;
3739 else if (!ndst || create)
3741 ndst = create_element_path (client, &dst, &rc, NULL);
3742 if (!ndst)
3743 goto fail;
3746 rc = is_element_owner (client, ndst);
3747 if (rc)
3748 goto fail;
3750 /* Merge any attributes from the src node to the initial dst node. */
3751 for (xmlAttrPtr attr = new->properties; attr; attr = attr->next)
3753 if (xmlStrEqual (attr->name, (xmlChar *) "_name"))
3754 continue;
3756 xmlAttrPtr a = xmlHasProp (ndst, attr->name);
3757 if (a)
3758 xmlRemoveProp (a);
3760 xmlChar *tmp = xmlNodeGetContent (attr->children);
3761 xmlNewProp (ndst, attr->name, tmp);
3762 xmlFree (tmp);
3763 rc = add_attribute (client, ndst, NULL, NULL);
3766 xmlNodePtr n = ndst->children;
3767 xmlUnlinkNode (n);
3768 xmlFreeNodeList (n);
3769 ndst->children = NULL;
3771 if (new->children)
3773 n = xmlCopyNodeList (new->children);
3774 if (!n)
3776 rc = GPG_ERR_ENOMEM;
3777 goto fail;
3780 n = xmlAddChildList (ndst, n);
3781 if (!n)
3783 rc = GPG_ERR_ENOMEM;
3784 goto fail;
3787 rc = update_element_mtime (client, xmlDocGetRootElement (client->doc) ==
3788 ndst->parent ? ndst : ndst->parent);
3791 fail:
3792 if (new)
3794 xmlUnlinkNode (new);
3795 xmlFreeNodeList (new);
3798 if (req)
3799 strv_free (req);
3801 if (src)
3802 strv_free (src);
3804 if (dst)
3805 strv_free (dst);
3807 return rc;
3810 static gpg_error_t
3811 copy_command (assuan_context_t ctx, char *line)
3813 struct client_s *client = assuan_get_pointer (ctx);
3814 gpg_error_t rc;
3815 struct argv_s *args[] = {
3816 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3817 NULL
3820 rc = parse_options (&line, args, client);
3821 if (rc)
3822 return send_error (ctx, rc);
3824 if (client->opts & OPT_INQUIRE)
3826 unsigned char *result;
3827 size_t len;
3829 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3830 if (rc)
3831 return send_error (ctx, rc);
3833 pthread_cleanup_push (xfree, result);
3834 rc = do_copy (ctx, (char *)result);
3835 pthread_cleanup_pop (1);
3837 else
3838 rc = do_copy (ctx, line);
3840 return send_error (ctx, rc);
3843 static gpg_error_t
3844 do_move (assuan_context_t ctx, char *line)
3846 struct client_s *client = assuan_get_pointer (ctx);
3847 gpg_error_t rc;
3848 char **req, **src = NULL, **dst = NULL;
3849 xmlNodePtr nsrc, ndst = NULL;
3851 req = str_split (line, " ", 0);
3853 if (!req || !req[0] || !req[1])
3855 strv_free (req);
3856 return GPG_ERR_SYNTAX;
3859 if (strchr (req[0], '\t'))
3860 src = str_split (req[0], "\t", 0);
3861 else
3862 src = str_split (req[0], " ", 0);
3864 if (!src || !*src)
3866 rc = GPG_ERR_SYNTAX;
3867 goto fail;
3870 if (strchr (req[1], '\t'))
3871 dst = str_split (req[1], "\t", 0);
3872 else
3873 dst = str_split (req[1], " ", 0);
3875 nsrc = find_root_element (client, client->doc, &src, &rc, NULL, 0, 0);
3876 if (nsrc && src[1])
3877 nsrc = find_elements (client, client->doc, nsrc->children, src + 1, &rc,
3878 NULL, NULL, NULL, 0, 0, NULL, 0);
3880 if (!nsrc)
3881 goto fail;
3883 rc = is_element_owner (client, nsrc);
3884 if (rc)
3885 goto fail;
3887 if (dst)
3889 if (!valid_element_path (dst, 0))
3891 rc = GPG_ERR_INV_VALUE;
3892 goto fail;
3895 ndst = find_root_element (client, client->doc, &dst, &rc, NULL, 0, 0);
3896 if (ndst && dst[1])
3897 ndst = find_elements (client, client->doc, ndst->children, dst + 1,
3898 &rc, NULL, NULL, NULL, 0, 0, NULL, 0);
3900 else
3901 ndst = xmlDocGetRootElement (client->doc);
3903 for (xmlNodePtr n = ndst; n; n = n->parent)
3905 if (n == nsrc)
3907 rc = GPG_ERR_CONFLICT;
3908 goto fail;
3912 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3913 goto fail;
3915 rc = 0;
3917 if (ndst)
3919 xmlChar *a = node_has_attribute (nsrc, (xmlChar *) "_name");
3921 xmlNodePtr dup = find_element (client, ndst->children, (char *) a,
3922 NULL, &rc);
3923 xmlFree (a);
3925 if (rc)
3926 goto fail;
3928 if (dup)
3930 if (dup == nsrc)
3931 goto fail;
3933 if (ndst == xmlDocGetRootElement (client->doc))
3935 xmlNodePtr n = nsrc;
3936 int match = 0;
3938 while (n->parent && n->parent != ndst)
3939 n = n->parent;
3941 xmlChar *a = node_has_attribute (n, (xmlChar *) "_name");
3942 xmlChar *b = node_has_attribute (nsrc, (xmlChar *) "_name");
3944 if (xmlStrEqual (a, b))
3946 match = 1;
3947 xmlUnlinkNode (nsrc);
3948 xmlUnlinkNode (n);
3949 xmlFreeNodeList (n);
3952 xmlFree (a);
3953 xmlFree (b);
3955 if (!match)
3957 xmlUnlinkNode (dup);
3958 xmlFreeNodeList (dup);
3961 else
3962 xmlUnlinkNode (dup);
3966 if (!ndst && dst)
3968 xmlChar *name = node_has_attribute (nsrc, (xmlChar *) "_name");
3970 if (nsrc->parent == xmlDocGetRootElement (client->doc)
3971 && !strcmp ((char *) name, *dst))
3973 xmlFree (name);
3974 rc = GPG_ERR_CONFLICT;
3975 goto fail;
3978 xmlFree (name);
3979 ndst = create_element_path (client, &dst, &rc, nsrc);
3982 if (!ndst)
3983 goto fail;
3985 update_element_mtime (client, nsrc->parent);
3986 xmlUnlinkNode (nsrc);
3987 ndst = xmlAddChildList (ndst, nsrc);
3989 if (!ndst)
3990 rc = GPG_ERR_ENOMEM;
3991 else
3992 update_element_mtime (client, ndst->parent);
3994 fail:
3995 if (req)
3996 strv_free (req);
3998 if (src)
3999 strv_free (src);
4001 if (dst)
4002 strv_free (dst);
4004 return rc;
4007 static gpg_error_t
4008 move_command (assuan_context_t ctx, char *line)
4010 struct client_s *client = assuan_get_pointer (ctx);
4011 gpg_error_t rc;
4012 struct argv_s *args[] = {
4013 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
4014 NULL
4017 rc = parse_options (&line, args, client);
4018 if (rc)
4019 return send_error (ctx, rc);
4021 if (client->opts & OPT_INQUIRE)
4023 unsigned char *result;
4024 size_t len;
4026 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
4027 if (rc)
4028 return send_error (ctx, rc);
4030 pthread_cleanup_push (xfree, result);
4031 rc = do_move (ctx, (char *)result);
4032 pthread_cleanup_pop (1);
4034 else
4035 rc = do_move (ctx, line);
4037 return send_error (ctx, rc);
4040 static gpg_error_t
4041 ls_command (assuan_context_t ctx, char *line)
4043 gpg_error_t rc;
4044 char *tmp = str_asprintf ("%s/data", homedir);
4045 char *dir = expand_homedir (tmp);
4046 DIR *d = opendir (dir);
4048 rc = gpg_error_from_errno (errno);
4049 xfree (tmp);
4051 if (!d)
4053 xfree (dir);
4054 return send_error (ctx, rc);
4057 size_t len =
4058 offsetof (struct dirent, d_name) +pathconf (dir, _PC_NAME_MAX) + 1;
4059 struct dirent *p = xmalloc (len), *cur = NULL;
4060 char *list = NULL;
4062 xfree (dir);
4063 pthread_cleanup_push (xfree, p);
4064 pthread_cleanup_push ((void *)(void *)closedir, d);
4065 rc = 0;
4067 while (!readdir_r (d, p, &cur) && cur)
4069 if (cur->d_name[0] == '.' && cur->d_name[1] == '\0')
4070 continue;
4071 else if (cur->d_name[0] == '.' && cur->d_name[1] == '.'
4072 && cur->d_name[2] == '\0')
4073 continue;
4075 tmp = str_asprintf ("%s%s\n", list ? list : "", cur->d_name);
4077 if (!tmp)
4079 if (list)
4080 xfree (list);
4082 rc = GPG_ERR_ENOMEM;
4083 break;
4086 xfree (list);
4087 list = tmp;
4090 pthread_cleanup_pop (1); // closedir (d)
4091 pthread_cleanup_pop (1); // xfree (p)
4093 if (rc)
4094 return send_error (ctx, rc);
4096 if (!list)
4097 return send_error (ctx, GPG_ERR_NO_DATA);
4099 list[strlen (list) - 1] = 0;
4100 pthread_cleanup_push (xfree, list);
4101 rc = xfer_data (ctx, list, strlen (list));
4102 pthread_cleanup_pop (1);
4103 return send_error (ctx, rc);
4106 static gpg_error_t
4107 bye_notify (assuan_context_t ctx, char *line)
4109 struct client_s *cl = assuan_get_pointer (ctx);
4111 cl->thd->state = CLIENT_STATE_DISCON;
4113 #ifdef WITH_GNUTLS
4114 if (cl->thd->remote)
4116 int rc;
4120 struct timeval tv = { 0, 50000 };
4122 rc = gnutls_bye (cl->thd->tls->ses, GNUTLS_SHUT_RDWR);
4123 if (rc == GNUTLS_E_AGAIN)
4124 select (0, NULL, NULL, NULL, &tv);
4126 while (rc == GNUTLS_E_AGAIN);
4128 #endif
4130 /* This will let assuan_process_next() return. */
4131 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
4133 cl->last_rc = gpg_error_from_errno (errno);
4134 return cl->last_rc;
4137 cl->last_rc = 0; // BYE command result
4138 return 0;
4141 static gpg_error_t
4142 reset_notify (assuan_context_t ctx, char *line)
4144 struct client_s *client = assuan_get_pointer (ctx);
4146 if (client)
4147 cleanup_client (client);
4149 return 0;
4153 * This is called before every Assuan command.
4155 static gpg_error_t
4156 command_startup (assuan_context_t ctx, const char *name)
4158 struct client_s *client = assuan_get_pointer (ctx);
4159 gpg_error_t rc;
4160 struct command_table_s *cmd = NULL;
4162 log_write1 ("command='%s'", name);
4163 client->last_rc = client->opts = 0;
4165 for (int i = 0; command_table[i]; i++)
4167 if (!strcasecmp (name, command_table[i]->name))
4169 if (command_table[i]->ignore_startup)
4170 return 0;
4171 cmd = command_table[i];
4172 break;
4176 if (!cmd)
4177 return GPG_ERR_UNKNOWN_COMMAND;
4179 client->last_rc = rc = gpg_error (file_modified (client, cmd));
4180 if (!rc)
4181 update_client_state (client, CLIENT_STATE_COMMAND);
4183 return rc;
4187 * This is called after every Assuan command.
4189 static void
4190 command_finalize (assuan_context_t ctx, gpg_error_t rc)
4192 struct client_s *client = assuan_get_pointer (ctx);
4194 if (!(client->flags & FLAG_LOCK_CMD))
4195 unlock_file_mutex (client, 0);
4197 log_write1 (_("command completed: rc=%u"), rc ? rc : client->last_rc);
4198 client->last_rc = gpg_error (GPG_ERR_UNKNOWN_COMMAND);
4199 #ifdef WITH_GNUTLS
4200 client->thd->buffer_timeout = client->thd->last_buffer_size = 0;
4201 #endif
4202 update_client_state (client, CLIENT_STATE_IDLE);
4205 static gpg_error_t
4206 help_command (assuan_context_t ctx, char *line)
4208 gpg_error_t rc;
4209 int i;
4211 if (!line || !*line)
4213 char *tmp;
4214 char *help = str_dup (_("Usage: HELP [<COMMAND>]\n"
4215 "For commands that take an element path as an argument, each element is "
4216 "separated with an ASCII @key{TAB} character (ASCII 0x09)."
4217 "\n" "COMMANDS:"));
4219 for (i = 0; command_table[i]; i++)
4221 if (!command_table[i]->help)
4222 continue;
4224 tmp = str_asprintf ("%s %s", help, command_table[i]->name);
4225 xfree (help);
4226 help = tmp;
4229 tmp = strip_texi_and_wrap (help);
4230 xfree (help);
4231 pthread_cleanup_push (xfree, tmp);
4232 rc = xfer_data (ctx, tmp, strlen (tmp));
4233 pthread_cleanup_pop (1);
4234 return send_error (ctx, rc);
4237 for (i = 0; command_table[i]; i++)
4239 if (!strcasecmp (line, command_table[i]->name))
4241 char *help, *tmp;
4243 if (!command_table[i]->help)
4244 break;
4246 help = strip_texi_and_wrap (command_table[i]->help);
4247 tmp = str_asprintf (_("Usage: %s"), help);
4248 xfree (help);
4249 pthread_cleanup_push (xfree, tmp);
4250 rc = xfer_data (ctx, tmp, strlen (tmp));
4251 pthread_cleanup_pop (1);
4252 return send_error (ctx, rc);
4256 return send_error (ctx, GPG_ERR_INV_NAME);
4259 static void
4260 new_command (const char *name, int ignore, int unlock,
4261 gpg_error_t (*handler) (assuan_context_t, char *),
4262 const char *help)
4264 int i = 0;
4266 if (command_table)
4267 for (i = 0; command_table[i]; i++);
4269 command_table =
4270 xrealloc (command_table, (i + 2) * sizeof (struct command_table_s *));
4271 command_table[i] = xcalloc (1, sizeof (struct command_table_s));
4272 command_table[i]->name = name;
4273 command_table[i]->handler = handler;
4274 command_table[i]->ignore_startup = ignore;
4275 command_table[i]->unlock = unlock;
4276 command_table[i++]->help = help;
4277 command_table[i] = NULL;
4280 void
4281 deinit_commands ()
4283 int i;
4285 for (i = 0; command_table[i]; i++)
4286 xfree (command_table[i]);
4288 xfree (command_table);
4291 static int
4292 sort_commands (const void *arg1, const void *arg2)
4294 struct command_table_s *const *a = arg1;
4295 struct command_table_s *const *b = arg2;
4297 if (!*a || !*b)
4298 return 0;
4299 else if (*a && !*b)
4300 return 1;
4301 else if (!*a && *b)
4302 return -1;
4304 return strcmp ((*a)->name, (*b)->name);
4307 // FIXME cleanup/implement options
4308 static gpg_error_t
4309 passwd_command (assuan_context_t ctx, char *line)
4311 struct client_s *client = assuan_get_pointer (ctx);
4312 gpg_error_t rc;
4313 struct argv_s *args[] = {
4314 &(struct argv_s) {"reset", OPTION_TYPE_NOARG, parse_opt_reset},
4315 &(struct argv_s) {"s2k-count", OPTION_TYPE_ARG, parse_opt_s2k_count},
4316 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG, parse_opt_no_passphrase},
4317 NULL
4320 rc = peer_is_invoker (client);
4321 if (rc == GPG_ERR_EACCES)
4322 return send_error (ctx, rc);
4324 if (client->flags & FLAG_NEW)
4325 return send_error (ctx, GPG_ERR_INV_STATE);
4327 client->crypto->save.s2k_count =
4328 config_get_ulong (client->filename, "s2k_count");
4329 rc = parse_options (&line, args, client);
4330 if (rc)
4331 return send_error (ctx, rc);
4333 if (!rc && client->opts & OPT_RESET)
4335 rc = cache_clear (client->md5file);
4336 if (!rc)
4337 send_status_all (STATUS_CACHE, NULL);
4340 if (!rc)
4342 if (!IS_PKI (client->crypto))
4344 struct crypto_s *crypto;
4346 xfree (client->crypto->filename);
4347 client->crypto->filename = str_dup (client->filename);
4348 rc = change_passwd (ctx, client->filename,
4349 client->flags & FLAG_NO_PINENTRY, &crypto,
4350 (client->opts & OPT_NO_PASSPHRASE));
4351 if (!rc)
4353 cleanup_crypto (&client->crypto);
4354 client->crypto = crypto;
4355 update_checksum (client);
4356 cleanup_crypto_stage1 (client->crypto);
4359 #ifdef WITH_AGENT
4360 else
4362 if (client->crypto->save.s2k_count)
4363 rc = send_to_agent (client->crypto->agent, NULL, NULL,
4364 "OPTION s2k-count=%lu",
4365 client->crypto->save.s2k_count);
4367 if (!rc)
4368 rc = agent_passwd (client->crypto);
4370 #endif
4373 return send_error (ctx, rc);
4376 static gpg_error_t
4377 parse_keygrip_opt_sign (void *data, void *value)
4379 struct client_s *client = data;
4381 (void) value;
4382 client->opts |= OPT_SIGN;
4383 return 0;
4386 static gpg_error_t
4387 keygrip_command (assuan_context_t ctx, char *line)
4389 struct client_s *client = assuan_get_pointer (ctx);
4390 gpg_error_t rc;
4391 struct crypto_s *crypto = NULL;
4392 struct argv_s *args[] = {
4393 &(struct argv_s) {"sign", OPTION_TYPE_NOARG, parse_keygrip_opt_sign},
4394 NULL
4397 if (!line || !*line)
4398 return send_error (ctx, GPG_ERR_SYNTAX);
4400 rc = parse_options (&line, args, client);
4401 if (rc)
4402 return send_error (ctx, rc);
4404 if (!valid_filename (line))
4405 return send_error (ctx, GPG_ERR_INV_VALUE);
4407 rc = init_client_crypto (&crypto);
4408 if (rc)
4409 return send_error (ctx, rc);
4411 rc = read_data_file (line, crypto);
4412 if (!rc)
4414 char *hexgrip = NULL;
4416 if (!IS_PKI (crypto))
4418 cleanup_crypto (&crypto);
4419 return send_error (ctx, GPG_ERR_NOT_SUPPORTED);
4422 if (client->opts & OPT_SIGN)
4424 if (valid_keygrip (crypto->sign_grip, sizeof (crypto->sign_grip)))
4425 hexgrip = bin2hex (crypto->sign_grip, sizeof (crypto->sign_grip));
4428 if (!hexgrip)
4429 hexgrip = bin2hex (crypto->grip, sizeof (crypto->grip));
4431 if (!hexgrip)
4432 rc = GPG_ERR_ENOMEM;
4433 else
4434 rc = xfer_data (ctx, hexgrip, strlen (hexgrip));
4436 xfree (hexgrip);
4439 UPDATE_AGENT_CTX (client, crypto);
4440 cleanup_crypto (&crypto);
4441 return send_error (ctx, rc);
4444 static gpg_error_t
4445 parse_opt_data (void *data, void *value)
4447 struct client_s *client = data;
4449 (void) value;
4450 client->opts |= OPT_DATA;
4451 return 0;
4454 static gpg_error_t
4455 send_client_list (assuan_context_t ctx)
4457 struct client_s *client = assuan_get_pointer (ctx);
4458 gpg_error_t rc = 0;
4459 char buf[ASSUAN_LINELENGTH];
4461 if (client->opts & OPT_VERBOSE)
4463 unsigned i, t;
4464 char **list = NULL;
4465 char *line;
4467 MUTEX_LOCK (&cn_mutex);
4468 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
4469 t = slist_length (cn_thread_list);
4471 for (i = 0; i < t; i++)
4473 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
4474 char *tmp;
4476 if (thd->state == CLIENT_STATE_UNKNOWN)
4477 continue;
4479 tmp = build_client_info_line (thd, 0);
4480 if (tmp)
4482 char **l = strv_cat (list, tmp);
4483 if (!l)
4484 rc = GPG_ERR_ENOMEM;
4485 else
4486 list = l;
4488 else
4489 rc = GPG_ERR_ENOMEM;
4491 if (rc)
4493 strv_free (list);
4494 break;
4498 pthread_cleanup_pop (1);
4499 if (rc)
4500 return rc;
4502 line = strv_join ("\n", list);
4503 strv_free (list);
4504 pthread_cleanup_push (xfree, line);
4505 rc = xfer_data (ctx, line, strlen (line));
4506 pthread_cleanup_pop (1);
4507 return rc;
4510 if (client->opts & OPT_DATA)
4512 MUTEX_LOCK (&cn_mutex);
4513 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
4514 snprintf (buf, sizeof (buf), "%i", slist_length (cn_thread_list));
4515 pthread_cleanup_pop (1);
4516 rc = xfer_data (ctx, buf, strlen (buf));
4518 else
4519 rc = send_status (ctx, STATUS_CLIENTS, NULL);
4521 return rc;
4524 static gpg_error_t
4525 getinfo_command (assuan_context_t ctx, char *line)
4527 struct client_s *client = assuan_get_pointer (ctx);
4528 gpg_error_t rc;
4529 char buf[ASSUAN_LINELENGTH];
4530 struct argv_s *args[] = {
4531 &(struct argv_s) {"data", OPTION_TYPE_NOARG, parse_opt_data},
4532 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_opt_verbose},
4533 NULL
4536 rc = parse_options (&line, args, client);
4537 if (rc)
4538 return send_error (ctx, rc);
4540 if (!strcasecmp (line, "clients"))
4542 rc = send_client_list (ctx);
4544 else if (!strcasecmp (line, "cache"))
4546 if (client->opts & OPT_DATA)
4548 snprintf (buf, sizeof (buf), "%u", cache_file_count ());
4549 rc = xfer_data (ctx, buf, strlen (buf));
4551 else
4552 rc = send_status (ctx, STATUS_CACHE, NULL);
4554 else if (!strcasecmp (line, "pid"))
4556 char buf[32];
4557 pid_t pid = getpid ();
4559 snprintf (buf, sizeof (buf), "%i", pid);
4560 rc = xfer_data (ctx, buf, strlen (buf));
4562 else if (!strcasecmp (line, "version"))
4564 char *buf = str_asprintf ("0x%06x %s%s", VERSION_HEX,
4565 #ifdef WITH_GNUTLS
4566 "GNUTLS "
4567 #endif
4568 #ifdef WITH_QUALITY
4569 "QUALITY "
4570 #endif
4571 "", use_agent ? "AGENT" : "");
4572 rc = xfer_data (ctx, buf, strlen (buf));
4573 xfree (buf);
4575 else if (!strcasecmp (line, "last_error"))
4577 if (client->last_error)
4578 rc = xfer_data (ctx, client->last_error, strlen (client->last_error));
4579 else
4580 rc = GPG_ERR_NO_DATA;
4582 else if (!strcasecmp (line, "user"))
4584 char *user = NULL;
4586 #ifdef WITH_GNUTLS
4587 if (client->thd->remote)
4588 user = str_asprintf ("#%s", client->thd->tls->fp);
4589 else
4590 user = get_username (client->thd->peer->uid);
4591 #else
4592 user = get_username (client->thd->peer->uid);
4593 #endif
4594 if (user)
4596 pthread_cleanup_push (xfree, user);
4597 rc = xfer_data (ctx, user, strlen (user));
4598 pthread_cleanup_pop (1);
4600 else
4601 rc = GPG_ERR_NO_DATA;
4603 else
4604 rc = gpg_error (GPG_ERR_SYNTAX);
4606 return send_error (ctx, rc);
4609 #ifdef WITH_AGENT
4610 static gpg_error_t
4611 send_data_cb (void *user, const void *buf, size_t len)
4613 assuan_context_t ctx = user;
4615 return assuan_send_data (ctx, buf, len);
4618 static gpg_error_t
4619 send_status_cb (void *user, const char *line)
4621 assuan_context_t ctx = user;
4622 char keyword[200], *k;
4623 const char *p;
4625 for (p = line, k = keyword; *p; p++)
4627 if (isspace (*p))
4628 break;
4630 *k++ = *p;
4633 *k = 0;
4634 if (*p == '#')
4635 p++;
4637 while (isspace (*p))
4638 p++;
4640 return assuan_write_status (ctx, keyword, *p ? p : NULL);
4642 #endif
4644 static gpg_error_t
4645 kill_command (assuan_context_t ctx, char *line)
4647 #ifdef HAVE_PTHREAD_CANCEL
4648 struct client_s *client = assuan_get_pointer (ctx);
4649 gpg_error_t rc;
4651 if (!line || !*line)
4652 return send_error (ctx, GPG_ERR_SYNTAX);
4654 rc = peer_is_invoker (client);
4655 if (!rc)
4657 unsigned i, t;
4659 MUTEX_LOCK (&cn_mutex);
4660 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
4661 t = slist_length (cn_thread_list);
4662 rc = GPG_ERR_ESRCH;
4664 for (i = 0; i < t; i++)
4666 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
4667 char *tmp = str_asprintf ("%p", thd->tid);
4669 if (strcmp (line, tmp))
4671 xfree (tmp);
4672 continue;
4675 xfree (tmp);
4676 rc = pthread_cancel (thd->tid);
4677 break;
4680 pthread_cleanup_pop (1);
4683 return send_error (ctx, rc);
4684 #else
4685 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
4686 #endif
4689 static gpg_error_t
4690 agent_command (assuan_context_t ctx, char *line)
4692 gpg_error_t rc = 0;
4694 if (!use_agent)
4695 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
4697 #ifdef WITH_AGENT
4698 struct client_s *client = assuan_get_pointer (ctx);
4700 if (!line || !*line)
4701 return send_error (ctx, GPG_ERR_SYNTAX);
4703 assuan_set_flag (client->crypto->agent->ctx, ASSUAN_CONVEY_COMMENTS, 1);
4704 rc = assuan_transact (client->crypto->agent->ctx, line, send_data_cb,
4705 client->ctx, agent_loopback_cb, client->crypto,
4706 send_status_cb, client->ctx);
4707 if (gpg_err_code (rc) == GPG_ERR_ASS_CANCELED)
4709 char *line;
4710 size_t len;
4712 rc = assuan_write_line (client->crypto->agent->ctx, "CAN");
4713 if (!rc)
4715 rc = assuan_read_line (client->crypto->agent->ctx, &line, &len);
4716 if (!rc)
4717 rc = gpg_error (GPG_ERR_ASS_CANCELED);
4721 assuan_set_flag (client->crypto->agent->ctx, ASSUAN_CONVEY_COMMENTS, 0);
4722 #endif
4723 return send_error (ctx, rc);
4726 void
4727 init_commands ()
4729 /* !BEGIN-HELP-TEXT!
4731 * This comment is used as a marker to generate the offline documentation
4732 * found in doc/pwmd.info. The indentation needs to be kept for the awk
4733 * script to determine where commands begin and end.
4735 new_command("HELP", 1, 1, help_command, _(
4736 "HELP [<COMMAND>]\n"
4737 "Show available commands or command specific help text."
4740 new_command("AGENT", 1, 1, agent_command, _(
4741 "AGENT <command>\n"
4742 "Send a @command{gpg-agent} protocol @var{command} directly to the "
4743 "@command{gpg-agent}."
4746 new_command("KILL", 1, 0, kill_command, _(
4747 "KILL <thread_id>\n"
4748 "Terminates the client identified by @var{thread_id} and releases any file "
4749 "lock or other resources it has held. @xref{GETINFO} for details about listing "
4750 "connected clients.\n"
4753 new_command("GETINFO", 1, 1, getinfo_command, _(
4754 "GETINFO [--data] [--verbose] CACHE | CLIENTS | PID | USER | LAST_ERROR | VERSION\n"
4755 "Get server and other information: @var{CACHE} returns the number of cached "
4756 "documents via a status message. @var{CLIENTS} returns the number of "
4757 "connected clients via a status message or a list of connected clients when "
4758 "the @option{--verbose} parameter is used. The list contains space delimited "
4759 "fields: the thread ID, client name, opened file (@code{/} if none opened), "
4760 "file lock status, whether the current client is self, client state and "
4761 "user ID or TLS fingerprint of the connected client. "
4762 "Client state @code{0} is an unknown client state, @code{1} indicates the "
4763 "client has connected but hasn't completed initializing, @code{2} indicates "
4764 "that the client is idle, @code{3} means the "
4765 "client is in a command and @code{4} means the client is disconnecting. This "
4766 "line is always returned with a data response. @var{PID} returns the process "
4767 "ID number of the server via a data response. @var{VERSION} returns the server "
4768 "version number and compile-time features with a data response with each "
4769 "being space delimited. @var{LAST_ERROR} returns a detailed description of "
4770 "the last failed command when available. @var{USER} returns the username or "
4771 "@abbr{TLS} hash of the connected client. @xref{Status Messages}. "
4772 "\n"
4773 "When the @option{--data} option is specified then the result will be sent "
4774 "via a data response rather than a status message."
4777 new_command("PASSWD", 0, 0, passwd_command, _(
4778 "PASSWD [--reset] [--s2k-count=N] [--no-passphrase]\n"
4779 "Changes the passphrase of the secret key required to open the current "
4780 "file or the passphrase of a symmetrically encrypted data file. When the "
4781 "@option{--reset} option is passed then the cache entry for the current "
4782 "file will be reset and the passphrase, if any, will be required during the "
4783 "next @code{OPEN} (@pxref{OPEN})."
4784 "\n"
4785 "The @option{--s2k-count} option sets or changes (@pxref{SAVE}) the number "
4786 "of hash iterations for a passphrase and must be either @code{0} to use "
4787 "the calibrated count of the machine (the default), or a value greater than "
4788 "or equal to @code{65536}. This option has no effect for symmetrically "
4789 "encrypted data files."
4790 "\n"
4791 "The @option{--no-passphrase} option will prevent requiring a passphrase for "
4792 "the data file, although a passphrase may be required when changing it."
4793 "\n"
4794 "This command is not available for non-invoking clients "
4795 "(@pxref{Access Control})."
4798 new_command("KEYGRIP", 1, 1, keygrip_command, _(
4799 "KEYGRIP [--sign] <filename>\n"
4800 "Returns the hex encoded keygrip of the specified @var{filename} with a "
4801 "data response."
4802 "\n"
4803 "When the @option{--sign} option is specified then the key used for signing "
4804 "of the specified @var{filename} will be returned."
4805 "\n"
4806 "For symmetrically encrypted data files this command returns the error "
4807 "GPG_ERR_NOT_SUPPORTED."
4810 new_command("OPEN", 1, 1, open_command, _(
4811 "OPEN [--lock] <filename> [<passphrase>]\n"
4812 "Opens @var{filename} using @var{passphrase}. When the filename is not "
4813 "found on the file-system then a new document will be created. If the file "
4814 "is found, it is looked for in the file cache. If cached and no "
4815 "@var{passphrase} was specified then the cached document is opened. When not "
4816 "cached, @cite{pinentry(1)} will be used to retrieve the passphrase to use "
4817 "for decryption unless @option{disable-pinentry} (@pxref{OPTION}) was "
4818 "specified."
4819 "\n"
4820 "When the @option{--lock} option is passed then the file mutex will be "
4821 "locked as if the @code{LOCK} command (@pxref{LOCK}) had been sent after the "
4822 "file has been opened."
4825 new_command("SAVE", 0, 0, save_command, _(
4826 "SAVE [--no-passphrase] [--reset] [--no-agent] [--s2k-count=N] [--cipher=<algo>] [--cipher-iterations=N] [--inquire-keyparam] [--keygrip=hexstring] [--sign-keygrip=hexstring]\n"
4827 "Writes the @abbr{XML} document to disk. The file written to is the file that "
4828 "was opened using the @code{OPEN} command (@pxref{OPEN}). If the file is a "
4829 "new one or the option @option{--inquire-keyparam} was passed, then a new "
4830 "keypair will be generated and a pinentry will be used to prompt for the "
4831 "passphrase to encrypt with unless the @option{--no-passphrase} option was "
4832 "passed in which case the data file will not be passphrase protected. "
4833 "\n"
4834 "The @option{--no-agent} option disables use of @command{gpg-agent} for "
4835 "passphrase retrieval and caching of new files when @command{gpg-agent} "
4836 "use is enabled. The datafile will be symmetrically encrypted and will not "
4837 "use or generate any keypair."
4838 "\n"
4839 "The @option{--reset} option will clear the cache entry for the current file "
4840 "and require a passphrase, if needed, before saving."
4841 "\n"
4842 "The @option{--cipher} option can be used to encrypt the @abbr{XML} data to "
4843 "an alternate cipher. The default is @code{aes256}. See the Configuration "
4844 "(@pxref{Configuration}) for available ciphers."
4845 "\n"
4846 "The @option{--cipher-iterations} option specifies the number of times to "
4847 "encrypt the XML data. The default is 0 although 1 iteration is still done."
4848 "\n"
4849 "The @option{--inquire-keyparam} option will send a server @emph{INQUIRE} to "
4850 "the client to obtain the key paramaters to use when generating a new "
4851 "keypair. The inquired data is expected to be an S-expression. If not "
4852 "specified then an @samp{RSA} key of @samp{2048} bits will be generated "
4853 "unless otherwise set in the configuration file (@pxref{Configuration}). Note "
4854 "that when this option is specified a new keypair will be generated "
4855 "reguardless if the file is a new one and that if the data file is protected "
4856 "the passphrase to open it will be required before generating the new "
4857 "keypair. This option is not available for non-invoking clients "
4858 "(@pxref{Access Control})."
4859 "\n"
4860 "You can encrypt the data file to a public key other than the one that it "
4861 "was originally encrypted with by passing the @option{--keygrip} option with "
4862 "the hex encoded keygrip of the public key as its argument. The keygrip may "
4863 "be of any key that @command{gpg-agent} knows about. The "
4864 "@option{--sign-keygrip} option may also be used to sign with an alternate "
4865 "secret key. Use the @code{KEYGRIP} (@pxref{KEYGRIP}) command to obtain the "
4866 "keygrip of an existing data file. This option may be needed when using a "
4867 "smartcard. This option has no effect with symmetrically encrypted data "
4868 "files. These options are not available for non-invoking clients "
4869 "(@pxref{Access Control})."
4870 "\n"
4871 "The @option{--s2k-count} option sets number of hash iterations for a "
4872 "passphrase. A value less-than @code{65536} will use the machine calibrated "
4873 "value and is the default. This setting only affects new files. To change "
4874 "the setting use the @code{PASSWD} command (@pxref{PASSWD}). This option "
4875 "has no effect with symmetrically encrypted data files."
4878 new_command("ISCACHED", 1, 0, iscached_command, _(
4879 "ISCACHED [--lock] <filename>\n"
4880 "An @emph{OK} response is returned if the specified @var{filename} is found "
4881 "in the file cache. If not found in the cache but exists on the filesystem "
4882 "then @var{GPG_ERR_NO_DATA} is returned. Otherwise a filesystem error is "
4883 "returned."
4884 "\n"
4885 "The @option{lock} option will lock the file mutex of @var{filename} when the "
4886 "file exists; it does not need to be opened nor cached. The lock will be "
4887 "released when the client exits or sends the @code{UNLOCK} (@pxref{UNLOCK}) "
4888 "command."
4891 new_command("CLEARCACHE", 1, 1, clearcache_command, _(
4892 "CLEARCACHE [<filename>]\n"
4893 "Clears a file cache entry for all or the specified @var{filename}."
4896 new_command("CACHETIMEOUT", 1, 1, cachetimeout_command, _(
4897 "CACHETIMEOUT <filename> <seconds>\n"
4898 "The time in @var{seconds} until @var{filename} will be removed from the "
4899 "cache. @code{-1} will keep the cache entry forever, @code{0} will require "
4900 "the passphrase for each @code{OPEN} or @code{SAVE} command (@pxref{OPEN}, "
4901 "@pxref{SAVE}). @xref{Configuration}, and the @code{cache_timeout} "
4902 "parameter."
4905 new_command("LIST", 0, 1, list_command, _(
4906 "LIST [--inquire] [--no-recurse] [--verbose] [--with-target] [--all] [[!]element[<TAB>[!]child[..]]]\n"
4907 "If no element path is given then a newline separated list of root elements "
4908 "is returned with a data response. If given, then all reachable elements "
4909 "of the specified element path are returned unless the @option{--no-recurse} "
4910 "option is specified. If specified, only the child elements of the element "
4911 "path are returned without recursing into grandchildren. Each resulting "
4912 "element is prefixed with the literal @code{!} character when the element "
4913 "contains no @code{target} attribute. @xref{Target Attribute}, for details."
4914 "\n"
4915 "When the @option{--verbose} option is passed then each element path "
4916 "returned will have zero or more flags appened to it. These flags are "
4917 "delimited from the element path by a single space character. A flag itself "
4918 "is a single character. Flag @code{P} indicates that access to the element "
4919 "is denied. Flag @code{+} indicates that there are child nodes of "
4920 "the current element path. Flag @code{E} indicates that an element of an "
4921 "element path contained in a @var{target} attribute could not be found. Flag "
4922 "@code{O} indicates that a @var{target} attribute recursion limit was reached "
4923 "(@pxref{Configuration}). Flag @code{T} will append the resolved element path "
4924 "of the @var{target} attribute contained in the current element (see below)."
4925 "\n"
4926 "The @option{--with-target} option implies @option{--verbose} and will append "
4927 "an additional flag @code{T} followed by a single space then an element path. "
4928 "The appended element path is the resolved path (@pxref{REALPATH}) of the "
4929 "current element when it contains a @var{target} attribute. When no "
4930 "@var{target} attribute is found then no flag will be appended."
4931 "\n"
4932 "The @option{--no-recurse} option limits the amount of data returned to only "
4933 "the listing of children of the specified element path and not any "
4934 "grandchildren."
4935 "\n"
4936 "The @option{--all} option lists the entire element tree for each root "
4937 "element. This option also implies option @option{--verbose}."
4938 "\n"
4939 "When the @option{--inquire} option is passed then all remaining non-option "
4940 "arguments are retrieved via a server @emph{INQUIRE}."
4943 new_command("REALPATH", 0, 1, realpath_command, _(
4944 "REALPATH [--inquire] [!]element[<TAB>[!]child[..]]\n"
4945 "Resolves all @code{target} attributes of the specified element path and "
4946 "returns the result with a data response. @xref{Target Attribute}, for details."
4947 "\n"
4948 "When the @option{--inquire} option is passed then all remaining non-option "
4949 "arguments are retrieved via a server @emph{INQUIRE}."
4952 new_command("STORE", 0, 1, store_command, _(
4953 "STORE [!]element[<TAB>[!]child[..]]<TAB>[content]\n"
4954 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
4955 "\n"
4956 "Creates a new element path or modifies the @var{content} of an existing "
4957 "element. If only a single element is specified then a new root element is "
4958 "created. Otherwise, elements are @key{TAB} delimited and the content will be "
4959 "set to the final @key{TAB} delimited element. If no @var{content} is "
4960 "specified after the final @key{TAB}, then the content of an existing "
4961 "element will be removed; or empty when creating a new element."
4962 "\n"
4963 "The only restriction of an element name is that it not contain whitespace "
4964 "or begin with the literal element character @code{!} unless specifying a "
4965 "literal element (@pxref{Target Attribute}). There is no whitespace between "
4966 "the @key{TAB} delimited elements. It is recommended that the content of an "
4967 "element be base64 encoded when it contains control or @key{TAB} characters "
4968 "to prevent @abbr{XML} parsing and @command{pwmd} syntax errors."
4971 new_command("RENAME", 0, 1, rename_command, _(
4972 "RENAME [--inquire] [!]element[<TAB>[!]child[..]] <value>\n"
4973 "Renames the specified @var{element} to the new @var{value}. If an element of "
4974 "the same name as the @var{value} already exists it will be overwritten."
4975 "\n"
4976 "When the @option{--inquire} option is passed then all remaining non-option "
4977 "arguments are retrieved via a server @emph{INQUIRE}."
4980 new_command("COPY", 0, 1, copy_command, _(
4981 "COPY [--inquire] [!]source[<TAB>[!]child[..]] [!]dest[<TAB>[!]child[..]]\n"
4982 "Copies the entire element tree starting from the child node of the source "
4983 "element, to the destination element path. If the destination element path "
4984 "does not exist then it will be created; otherwise it is overwritten."
4985 "\n"
4986 "Note that attributes from the source element are merged into the "
4987 "destination element when the destination element path exists. When an "
4988 "attribute of the same name exists in both the source and destination "
4989 "elements then the destination attribute will be updated to the source "
4990 "attribute value."
4991 "\n"
4992 "When the @option{--inquire} option is passed then all remaining non-option "
4993 "arguments are retrieved via a server @emph{INQUIRE}."
4996 new_command("MOVE", 0, 1, move_command, _(
4997 "MOVE [--inquire] [!]source[<TAB>[!]child[..]] [[!]dest[<TAB>[!]child[..]]]\n"
4998 "Moves the source element path to the destination element path. If the "
4999 "destination is not specified then it will be moved to the root node of the "
5000 "document. If the destination is specified and exists then it will be "
5001 "overwritten; otherwise non-existing elements of the destination element "
5002 "path will be created."
5003 "\n"
5004 "When the @option{--inquire} option is passed then all remaining non-option "
5005 "arguments are retrieved via a server @emph{INQUIRE}."
5008 new_command("DELETE", 0, 1, delete_command, _(
5009 "DELETE [--inquire] [!]element[<TAB>[!]child[..]]\n"
5010 "Removes the specified element path and all of its children. This may break "
5011 "an element with a @code{target} attribute (@pxref{Target Attribute}) that "
5012 "refers to this element or any of its children."
5013 "\n"
5014 "When the @option{--inquire} option is passed then all remaining non-option "
5015 "arguments are retrieved via a server @emph{INQUIRE}."
5018 new_command("GET", 0, 1, get_command, _(
5019 "GET [--inquire] [!]element[<TAB>[!]child[..]]\n"
5020 "Retrieves the content of the specified element. The content is returned "
5021 "with a data response."
5022 "\n"
5023 "When the @option{--inquire} option is passed then all remaining non-option "
5024 "arguments are retrieved via a server @emph{INQUIRE}."
5027 new_command("ATTR", 0, 1, attr_command, _(
5028 "ATTR [--inquire] SET|GET|DELETE|LIST [<attribute>] [!]element[<TAB>[!]child[..]] ..\n"
5029 "@table @asis\n"
5030 "@item ATTR SET attribute [!]element[<TAB>[!]child[..]] [value]\n"
5031 "\n"
5032 " Stores or updates an @var{attribute} name and optional @var{value} of an "
5033 "element. When no @var{value} is specified any existing value will be removed."
5034 "\n"
5035 "@item ATTR DELETE attribute [!]element[<TAB>[!]child[..]]\n"
5036 "\n"
5037 " Removes an @var{attribute} from an element."
5038 "\n"
5039 "@item ATTR LIST [!]element[<TAB>[!]child[..]]\n"
5040 "\n"
5041 " Retrieves a newline separated list of attributes names and values "
5042 "from the specified element. Each attribute name and value is space delimited."
5043 "\n"
5044 "@item ATTR GET attribute [!]element[<TAB>[!]child[..]]\n"
5045 "\n"
5046 " Retrieves the value of an @var{attribute} from an element."
5047 "@end table\n"
5048 "\n"
5049 "The @code{_name} attribute (case sensitive) cannot be removed nor modified. "
5050 "Use the @code{DELETE} (@pxref{DELETE}) or @code{RENAME} (@pxref{RENAME}) "
5051 "commands instead."
5052 "\n"
5053 "The @code{_mtime} attribute is updated each time an element is modified by "
5054 "either storing content, editing attributes or by deleting a child element. "
5055 "The @code{_ctime} attribute is created for each new element in an element "
5056 "path."
5057 "\n"
5058 "When the @option{--inquire} option is passed then all remaining non-option "
5059 "arguments are retrieved via a server @emph{INQUIRE}."
5060 "\n"
5061 "@xref{Target Attribute}, for details about this special attribute."
5064 new_command("XPATH", 0, 1, xpath_command, _(
5065 "XPATH [--inquire] <expression>[<TAB>[value]]\n"
5066 "Evaluates an XPath @var{expression}. If no @var{value} argument is "
5067 "specified it is assumed the expression is a request to return a result. "
5068 "Otherwise, the result is set to the @var{value} argument and the document is "
5069 "updated. If there is no @var{value} after the @key{TAB} character, the value "
5070 "is assumed to be empty and the document is updated. For example:"
5071 "@sp 1\n"
5072 "@example\n"
5073 "XPATH //element[@@_name='password']@key{TAB}\n"
5074 "@end example\n"
5075 "@sp 1"
5076 "would clear the content of all @code{password} elements in the data file "
5077 "while leaving off the trailing @key{TAB} would return all @code{password} "
5078 "elements in @abbr{XML} format."
5079 "\n"
5080 "When the @option{--inquire} option is passed then all remaining non-option "
5081 "arguments are retrieved via a server @emph{INQUIRE}."
5082 "\n"
5083 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
5084 "expression syntax."
5087 new_command("XPATHATTR", 0, 1, xpathattr_command, _(
5088 "XPATHATTR [--inquire] SET|DELETE <name> <expression>[<TAB>[<value>]]\n"
5089 "Like the @code{XPATH} command (@pxref{XPATH}) but operates on element "
5090 "attributes and does not return a result. For the @var{SET} operation the "
5091 "@var{value} is optional but the field is required. If not specified then "
5092 "the attribute value will be empty. For example:"
5093 "@sp 1"
5094 "@example\n"
5095 "XPATHATTR SET password //element[@@_name='password']@key{TAB}\n"
5096 "@end example\n"
5097 "@sp 1"
5098 "would create an @code{password} attribute for each @code{password} element "
5099 "found in the document. The attribute value will be empty but still exist."
5100 "\n"
5101 "When the @option{--inquire} option is passed then all remaining non-option "
5102 "arguments are retrieved via a server @emph{INQUIRE}."
5103 "\n"
5104 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
5105 "expression syntax."
5108 new_command("IMPORT", 0, 1, import_command, _(
5109 "IMPORT [--root [!]element[<TAB>[!]child[..]]] <content>\n"
5110 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
5111 "\n"
5112 "Like the @code{STORE} command (@pxref{STORE}), but the @var{content} "
5113 "argument is raw @abbr{XML} data. The content is created as a child of "
5114 "the element path specified with the @option{--root} option or at the "
5115 "document root when not specified. Existing elements of the same name will "
5116 "be overwritten."
5117 "\n"
5118 "The content must begin with an @abbr{XML} element node. @xref{Introduction}, "
5119 "for details."
5122 new_command("DUMP", 0, 1, dump_command, _(
5123 "DUMP\n"
5124 "Shows the in memory @abbr{XML} document with indenting. @xref{XPATH}, for "
5125 "dumping a specific node."
5128 new_command("LOCK", 0, 0, lock_command, _(
5129 "LOCK\n"
5130 "Locks the mutex associated with the opened file. This prevents other clients "
5131 "from sending commands to the same opened file until the client "
5132 "that sent this command either disconnects or sends the @code{UNLOCK} "
5133 "command. @xref{UNLOCK}."
5136 new_command("UNLOCK", 1, 0, unlock_command, _(
5137 "UNLOCK\n"
5138 "Unlocks the file mutex which was locked with the @code{LOCK} command or "
5139 "a commands' @option{--lock} option (@pxref{LOCK}, @pxref{OPEN}, "
5140 "@pxref{ISCACHED})."
5143 new_command("GETCONFIG", 1, 1, getconfig_command, _(
5144 "GETCONFIG [filename] <parameter>\n"
5145 "Returns the value of a @command{pwmd} configuration @var{parameter} with a "
5146 "data response. If no file has been opened then the value for @var{filename} "
5147 "or the default from the @samp{global} section will be returned. If a file "
5148 "has been opened and no @var{filename} is specified, a value previously "
5149 "set with the @code{OPTION} command (@pxref{OPTION}) will be returned."
5152 new_command("OPTION", 1, 1, option_command, _(
5153 "OPTION <NAME>=<VALUE>\n"
5154 "Sets a client option @var{name} to @var{value}. The value for an option is "
5155 "kept for the duration of the connection."
5156 "\n"
5157 "@table @asis\n"
5158 "@item DISABLE-PINENTRY\n"
5159 "Disable use of @command{pinentry} for passphrase retrieval. When set, a "
5160 "server inquire is sent to the client to obtain the passphrase. This option "
5161 "may be set as needed before the @code{OPEN} (@pxref{OPEN}), @code{PASSWD} "
5162 "(@pxref{PASSWD}) and @code{SAVE} (@pxref{SAVE}) commands."
5163 "\n"
5164 "@item PINENTRY-TIMEOUT\n"
5165 "Sets the number of seconds before a pinentry prompt will return an error "
5166 "while waiting for user input."
5167 "\n"
5168 "@item TTYNAME\n"
5169 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
5170 "\n"
5171 "@item TTYTYPE\n"
5172 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
5173 "\n"
5174 "@item DISPLAY\n"
5175 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
5176 "\n"
5177 "@item PINENTRY-DESC\n"
5178 "Sets the description string of the @command{gpg-agent} and @command{pinentry} dialog."
5179 "\n"
5180 "@item PINENTRY-TITLE\n"
5181 "Sets the title string of the @command{gpg-agent} and @command{pinentry} dialog."
5182 "\n"
5183 "@item PINENTRY-PROMPT\n"
5184 "Sets the prompt string of the @command{gpg-agent} and @command{pinentry} dialog."
5185 "\n"
5186 "@item LC-CTYPE\n"
5187 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
5188 "\n"
5189 "@item LC-MESSAGES\n"
5190 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
5191 "\n"
5192 "@item NAME\n"
5193 "Associates the thread ID of the connection with the specified textual "
5194 "representation. Useful for debugging log messages. May not contain whitespace."
5195 "\n"
5196 "@item LOCK-TIMEOUT\n"
5197 "When not @code{0}, the duration in tenths of a second to wait for the file "
5198 "mutex which has been locked by another thread to be released before returning "
5199 "an error. When @code{-1}, then an error will be returned immediately."
5200 "\n"
5201 "@item LOG-LEVEL\n"
5202 "An integer specifiying the logging level."
5203 "@end table\n"
5206 new_command("LS", 1, 1, ls_command, _(
5207 "LS\n"
5208 "Lists the available data files stored in the data directory "
5209 "(@file{~/.pwmd/data}). The result is a newline separated list of filenames."
5212 new_command("RESET", 1, 1, NULL, _(
5213 "RESET\n"
5214 "Closes the currently opened file but keeps any previously set client options."
5217 new_command("NOP", 1, 1, NULL, _(
5218 "NOP\n"
5219 "Does nothing. Always returns successfully."
5222 /* !END-HELP-TEXT! */
5223 new_command ("CANCEL", 1, 1, NULL, NULL);
5224 new_command ("END", 1, 1, NULL, NULL);
5225 new_command ("BYE", 1, 1, NULL, NULL);
5227 int i;
5228 for (i = 0; command_table[i]; i++);
5229 qsort (command_table, i - 1, sizeof (struct command_table_s *),
5230 sort_commands);
5233 gpg_error_t
5234 register_commands (assuan_context_t ctx)
5236 int i = 0, rc;
5238 for (; command_table[i]; i++)
5240 if (!command_table[i]->handler)
5241 continue;
5243 rc = assuan_register_command (ctx, command_table[i]->name,
5244 command_table[i]->handler,
5245 command_table[i]->help);
5246 if (rc)
5247 return rc;
5250 rc = assuan_register_bye_notify (ctx, bye_notify);
5251 if (rc)
5252 return rc;
5254 rc = assuan_register_reset_notify (ctx, reset_notify);
5255 if (rc)
5256 return rc;
5258 rc = assuan_register_pre_cmd_notify (ctx, command_startup);
5259 if (rc)
5260 return rc;
5262 return assuan_register_post_cmd_notify (ctx, command_finalize);