Fix ACL crash for non-existing user.
[pwmd.git] / src / commands.c
blobada1a6d2b3c59aad54ec39b760b7557a6e43479e
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)
1674 rc = GPG_ERR_NO_DATA;
1676 if (!rc)
1678 if (!rc)
1680 int i;
1682 for (i = 0; i < total; i++)
1684 char *tmp = slist_nth_data (elements->list, i);
1686 string_append_printf (result, "%s%s", tmp,
1687 i + 1 == total ? "" : "\n");
1691 else
1692 rc = GPG_ERR_NO_DATA;
1695 return rc;
1698 static int
1699 has_list_flag (char *path, char *flags)
1701 char *p = path;
1703 while (*p && *++p != ' ');
1705 if (!*p)
1706 return 0;
1708 for (; *p; p++)
1710 char *f;
1712 for (f = flags; *f && *f != ' '; f++)
1714 if (*p == *f)
1715 return 1;
1719 return 0;
1722 static gpg_error_t
1723 do_list (assuan_context_t ctx, char *line)
1725 struct client_s *client = assuan_get_pointer (ctx);
1726 gpg_error_t rc;
1727 struct element_list_s *elements = NULL;
1729 elements = xcalloc (1, sizeof (struct element_list_s));
1730 if (!elements)
1731 return GPG_ERR_ENOMEM;
1733 elements->recurse = client->opts & OPT_LIST_RECURSE;
1734 elements->verbose =
1735 (client->opts & OPT_VERBOSE) | (client->opts & OPT_LIST_WITH_TARGET);
1736 elements->with_target = client->opts & OPT_LIST_WITH_TARGET;
1738 if (!line || !*line)
1740 struct string_s *str = NULL;
1742 pthread_cleanup_push (list_command_cleanup2, elements);
1743 rc = list_root_elements (client, client->doc, &str, elements->verbose,
1744 elements->with_target);
1745 pthread_cleanup_pop (1);
1746 pthread_cleanup_push (list_command_cleanup1, str);
1748 if (!rc)
1750 if (client->opts & OPT_LIST_ALL)
1752 char **roots = str_split (str->str, "\n", 0);
1753 char **p;
1755 pthread_cleanup_push (req_cleanup, roots);
1756 string_truncate (str, 0);
1758 for (p = roots; *p; p++)
1760 if (strchr (*p, ' '))
1762 if (has_list_flag (*p, "EOP"))
1764 string_append_printf (str, "%s%s", *p,
1765 *(p + 1) ? "\n" : "");
1766 continue;
1770 elements = xcalloc (1, sizeof (struct element_list_s));
1771 if (!elements)
1773 rc = GPG_ERR_ENOMEM;
1774 break;
1777 elements->recurse = client->opts & OPT_LIST_RECURSE;
1778 elements->verbose =
1779 (client->opts & OPT_VERBOSE) | (client->opts &
1780 OPT_LIST_WITH_TARGET);
1781 elements->with_target = client->opts & OPT_LIST_WITH_TARGET;
1782 pthread_cleanup_push (list_command_cleanup2, elements);
1783 rc = list_path_once (client, *p, elements, str);
1784 pthread_cleanup_pop (1);
1785 if (rc)
1786 break;
1788 if (*(p + 1))
1789 string_append (str, "\n");
1792 pthread_cleanup_pop (1);
1795 if (!rc)
1796 rc = xfer_data (ctx, str->str, str->len);
1799 pthread_cleanup_pop (1);
1800 return rc;
1803 pthread_cleanup_push (list_command_cleanup2, elements);
1804 struct string_s *str = string_new (NULL);
1805 pthread_cleanup_push (list_command_cleanup1, str);
1806 rc = list_path_once (client, line, elements, str);
1807 if (!rc)
1808 rc = xfer_data (ctx, str->str, str->len);
1810 pthread_cleanup_pop (1);
1811 pthread_cleanup_pop (1);
1812 return rc;
1815 static gpg_error_t
1816 list_command (assuan_context_t ctx, char *line)
1818 struct client_s *client = assuan_get_pointer (ctx);
1819 gpg_error_t rc;
1820 struct argv_s *args[] = {
1821 &(struct argv_s) {"no-recurse", OPTION_TYPE_NOARG,
1822 parse_list_opt_norecurse},
1823 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_opt_verbose},
1824 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1825 &(struct argv_s) {"with-target", OPTION_TYPE_NOARG,
1826 parse_list_opt_target},
1827 &(struct argv_s) {"all", OPTION_TYPE_NOARG, parse_list_opt_all},
1828 NULL
1831 if (disable_list_and_dump == 1)
1832 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
1834 client->opts |= OPT_LIST_RECURSE;
1835 rc = parse_options (&line, args, client);
1836 if (rc)
1837 return send_error (ctx, rc);
1839 if (client->opts & OPT_LIST_ALL)
1840 client->opts |= OPT_LIST_RECURSE | OPT_VERBOSE;
1842 if (client->opts & OPT_INQUIRE)
1844 unsigned char *result;
1845 size_t len;
1847 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1848 if (rc)
1849 return send_error (ctx, rc);
1851 pthread_cleanup_push (xfree, result);
1852 rc = do_list (ctx, (char *)result);
1853 pthread_cleanup_pop (1);
1855 else
1856 rc = do_list (ctx, line);
1858 return send_error (ctx, rc);
1862 * req[0] - element path
1864 static gpg_error_t
1865 attribute_list (assuan_context_t ctx, char **req)
1867 struct client_s *client = assuan_get_pointer (ctx);
1868 char **attrlist = NULL;
1869 int i = 0;
1870 char **path = NULL;
1871 xmlAttrPtr a;
1872 xmlNodePtr n, an;
1873 char *line;
1874 gpg_error_t rc;
1876 if (!req || !req[0])
1877 return GPG_ERR_SYNTAX;
1879 client->flags |= FLAG_ACL_IGNORE;
1881 if ((path = str_split (req[0], "\t", 0)) == NULL)
1884 * The first argument may be only a root element.
1886 if ((path = str_split (req[0], " ", 0)) == NULL)
1887 return GPG_ERR_SYNTAX;
1890 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 0);
1891 if (!n)
1893 strv_free (path);
1894 return rc;
1897 if (client->flags & FLAG_ACL_ERROR)
1899 client->flags &= ~FLAG_ACL_IGNORE;
1900 if (path[1])
1902 strv_free (path);
1903 return GPG_ERR_EACCES;
1906 client->flags &= ~FLAG_ACL_ERROR;
1909 if (path[1])
1911 n = find_elements (client, client->doc, n->children, path + 1, &rc,
1912 NULL, NULL, NULL, 0, 0, NULL, 0);
1914 if (!n)
1916 strv_free (path);
1917 return rc;
1921 strv_free (path);
1923 for (a = n->properties; a; a = a->next)
1925 char **pa;
1927 if ((pa = xrealloc (attrlist, (i + 2) * sizeof (char *))) == NULL)
1929 if (attrlist)
1930 strv_free (attrlist);
1932 log_write ("%s(%i): %s", __FILE__, __LINE__,
1933 pwmd_strerror (GPG_ERR_ENOMEM));
1934 return GPG_ERR_ENOMEM;
1937 attrlist = pa;
1938 an = a->children;
1939 attrlist[i] = str_asprintf ("%s %s", (char *) a->name,
1941 && an->content ? (char *) an->content : "");
1943 if (!attrlist[i])
1945 strv_free (attrlist);
1946 log_write ("%s(%i): %s", __FILE__, __LINE__,
1947 pwmd_strerror (GPG_ERR_ENOMEM));
1948 return GPG_ERR_ENOMEM;
1951 attrlist[++i] = NULL;
1954 if (!attrlist)
1955 return GPG_ERR_NO_DATA;
1957 line = strv_join ("\n", attrlist);
1959 if (!line)
1961 log_write ("%s(%i): %s", __FILE__, __LINE__,
1962 pwmd_strerror (GPG_ERR_ENOMEM));
1963 strv_free (attrlist);
1964 return GPG_ERR_ENOMEM;
1967 pthread_cleanup_push (xfree, line);
1968 pthread_cleanup_push (req_cleanup, attrlist);
1969 rc = xfer_data (ctx, line, strlen (line));
1970 pthread_cleanup_pop (1);
1971 pthread_cleanup_pop (1);
1972 return rc;
1976 * req[0] - attribute
1977 * req[1] - element path
1979 static gpg_error_t
1980 attribute_delete (struct client_s *client, char **req)
1982 xmlNodePtr n;
1983 char **path = NULL;
1984 gpg_error_t rc;
1986 if (!req || !req[0] || !req[1])
1987 return GPG_ERR_SYNTAX;
1989 if (!strcmp (req[0], "_name"))
1990 return GPG_ERR_INV_ATTR;
1992 if ((path = str_split (req[1], "\t", 0)) == NULL)
1995 * The first argument may be only a root element.
1997 if ((path = str_split (req[1], " ", 0)) == NULL)
1998 return GPG_ERR_SYNTAX;
2001 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 0);
2002 if (!n)
2003 goto fail;
2005 if (path[1])
2007 n = find_elements (client, client->doc, n->children, path + 1, &rc,
2008 NULL, NULL, NULL, 0, 0, NULL, 0);
2009 if (!n)
2010 goto fail;
2013 if (!strcmp (req[0], (char *) "_acl"))
2015 rc = is_element_owner (client, n);
2016 if (rc)
2017 goto fail;
2020 rc = delete_attribute (client, n, (xmlChar *) req[0]);
2022 fail:
2023 strv_free (path);
2024 return rc;
2027 static xmlNodePtr
2028 create_element_path (struct client_s *client,
2029 char ***elements, gpg_error_t * rc, xmlNodePtr parent)
2031 char **req = *elements;
2032 char **req_orig = strv_dup (req);
2033 xmlNodePtr n = NULL;
2035 *rc = 0;
2037 if (!req_orig)
2039 *rc = GPG_ERR_ENOMEM;
2040 log_write ("%s(%i): %s", __FILE__, __LINE__,
2041 pwmd_strerror (GPG_ERR_ENOMEM));
2042 goto fail;
2045 again:
2046 n = find_root_element (client, client->doc, &req, rc, NULL, 0, 0);
2047 if (!n)
2049 if (*rc != GPG_ERR_ELEMENT_NOT_FOUND)
2050 goto fail;
2052 *rc = new_root_element (client, client->doc, req[0]);
2053 if (*rc)
2054 goto fail;
2056 goto again;
2058 else if (n == parent)
2060 *rc = GPG_ERR_CONFLICT;
2061 goto fail;
2064 if (req[1])
2066 if (!n->children)
2067 n = create_target_elements_cb (client, 1, n, req + 1, rc, NULL);
2068 else
2069 n = find_elements (client, client->doc, n->children, req + 1, rc,
2070 NULL, NULL, create_target_elements_cb, 0, 0,
2071 parent, 0);
2073 if (!n)
2074 goto fail;
2077 * Reset the position of the element tree now that the elements
2078 * have been created.
2080 strv_free (req);
2081 req = req_orig;
2082 req_orig = NULL;
2083 n = find_root_element (client, client->doc, &req, rc, NULL, 0, 0);
2084 if (!n)
2085 goto fail;
2087 n = find_elements (client, client->doc, n->children, req + 1, rc,
2088 NULL, NULL, NULL, 0, 0, NULL, 0);
2089 if (!n)
2090 goto fail;
2093 fail:
2094 if (req_orig)
2095 strv_free (req_orig);
2097 *elements = req;
2098 return n;
2102 * Creates a "target" attribute. When other commands encounter an element with
2103 * this attribute, the element path is modified to the target value. If the
2104 * source element path doesn't exist when using 'ATTR SET target', it is
2105 * created, but the destination element path must exist.
2107 * req[0] - source element path
2108 * req[1] - destination element path
2110 static gpg_error_t
2111 target_attribute (struct client_s *client, char **req)
2113 char **src, **dst, *line = NULL, **odst = NULL;
2114 gpg_error_t rc;
2115 xmlNodePtr n;
2117 if (!req || !req[0] || !req[1])
2118 return GPG_ERR_SYNTAX;
2120 if ((src = str_split (req[0], "\t", 0)) == NULL)
2123 * The first argument may be only a root element.
2125 if ((src = str_split (req[0], " ", 0)) == NULL)
2126 return GPG_ERR_SYNTAX;
2129 if (!valid_element_path (src, 0))
2130 return GPG_ERR_INV_VALUE;
2132 if ((dst = str_split (req[1], "\t", 0)) == NULL)
2135 * The first argument may be only a root element.
2137 if ((dst = str_split (req[1], " ", 0)) == NULL)
2139 rc = GPG_ERR_SYNTAX;
2140 goto fail;
2144 odst = strv_dup (dst);
2145 if (!odst)
2147 rc = GPG_ERR_ENOMEM;
2148 goto fail;
2151 n = find_root_element (client, client->doc, &dst, &rc, NULL, 0, 0);
2153 * Make sure the destination element path exists.
2155 if (!n)
2156 goto fail;
2158 if (dst[1])
2160 n = find_elements (client, client->doc, n->children, dst + 1, &rc,
2161 NULL, NULL, NULL, 0, 0, NULL, 0);
2162 if (!n)
2163 goto fail;
2166 rc = validate_target_attribute (client, client->doc, req[0], n);
2167 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2168 goto fail;
2170 n = create_element_path (client, &src, &rc, NULL);
2171 if (rc)
2172 goto fail;
2174 line = strv_join ("\t", odst);
2175 if (!line)
2177 rc = GPG_ERR_ENOMEM;
2178 goto fail;
2181 rc = add_attribute (client, n, "target", line);
2183 fail:
2184 xfree (line);
2185 strv_free (src);
2186 strv_free (dst);
2187 strv_free (odst);
2188 return rc;
2192 * req[0] - attribute
2193 * req[1] - element path
2195 static gpg_error_t
2196 attribute_get (assuan_context_t ctx, char **req)
2198 struct client_s *client = assuan_get_pointer (ctx);
2199 xmlNodePtr n;
2200 xmlChar *a;
2201 char **path = NULL;
2202 gpg_error_t rc;
2204 if (!req || !req[0] || !req[1])
2205 return GPG_ERR_SYNTAX;
2207 if (strchr (req[1], '\t'))
2209 if ((path = str_split (req[1], "\t", 0)) == NULL)
2210 return GPG_ERR_SYNTAX;
2212 else
2214 if ((path = str_split (req[1], " ", 0)) == NULL)
2215 return GPG_ERR_SYNTAX;
2218 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 0);
2220 if (!n)
2221 goto fail;
2223 if (path[1])
2225 n = find_elements (client, client->doc, n->children, path + 1, &rc,
2226 NULL, NULL, NULL, 0, 0, NULL, 0);
2228 if (!n)
2229 goto fail;
2232 strv_free (path);
2234 if ((a = xmlGetProp (n, (xmlChar *) req[0])) == NULL)
2235 return GPG_ERR_NOT_FOUND;
2237 pthread_cleanup_push (xmlFree, a);
2239 if (*a)
2240 rc = xfer_data (ctx, (char *) a, xmlStrlen (a));
2241 else
2242 rc = GPG_ERR_NO_DATA;
2244 pthread_cleanup_pop (1);
2245 return rc;
2247 fail:
2248 strv_free (path);
2249 return rc;
2253 * req[0] - attribute
2254 * req[1] - element path
2255 * req[2] - value
2257 static gpg_error_t
2258 attribute_set (struct client_s *client, char **req)
2260 char **path = NULL;
2261 gpg_error_t rc;
2262 xmlNodePtr n;
2264 if (!req || !req[0] || !req[1])
2265 return GPG_ERR_SYNTAX;
2268 * Reserved attribute names.
2270 if (!strcmp (req[0], "_name"))
2271 return GPG_ERR_INV_ATTR;
2272 else if (!strcmp (req[0], "target"))
2273 return target_attribute (client, req + 1);
2274 else if (!valid_xml_attribute (req[0]))
2275 return GPG_ERR_INV_VALUE;
2277 if ((path = str_split (req[1], "\t", 0)) == NULL)
2280 * The first argument may be only a root element.
2282 if ((path = str_split (req[1], " ", 0)) == NULL)
2283 return GPG_ERR_SYNTAX;
2286 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 0);
2288 if (!n)
2289 goto fail;
2291 if (path[1])
2293 n = find_elements (client, client->doc, n->children, path + 1, &rc,
2294 NULL, NULL, NULL, 0, 0, NULL, 0);
2296 if (!n)
2297 goto fail;
2300 if (!strcmp (req[0], (char *) "_acl"))
2302 rc = is_element_owner (client, n);
2303 if (rc)
2304 goto fail;
2307 rc = add_attribute (client, n, req[0], req[2]);
2309 fail:
2310 strv_free (path);
2311 return rc;
2315 * req[0] - command
2316 * req[1] - attribute name or element path if command is LIST
2317 * req[2] - element path
2318 * req[2] - element path or value
2321 static gpg_error_t
2322 do_attr (assuan_context_t ctx, char *line)
2324 struct client_s *client = assuan_get_pointer (ctx);
2325 gpg_error_t rc = 0;
2326 char **req;
2328 req = str_split (line, " ", 4);
2329 if (!req || !req[0] || !req[1])
2331 strv_free (req);
2332 return GPG_ERR_SYNTAX;
2335 pthread_cleanup_push (req_cleanup, req);
2337 if (strcasecmp (req[0], "SET") == 0)
2338 rc = attribute_set (client, req + 1);
2339 else if (strcasecmp (req[0], "GET") == 0)
2340 rc = attribute_get (ctx, req + 1);
2341 else if (strcasecmp (req[0], "DELETE") == 0)
2342 rc = attribute_delete (client, req + 1);
2343 else if (strcasecmp (req[0], "LIST") == 0)
2344 rc = attribute_list (ctx, req + 1);
2345 else
2346 rc = GPG_ERR_SYNTAX;
2348 client->flags &= ~(FLAG_ACL_IGNORE|FLAG_ACL_ERROR);
2349 pthread_cleanup_pop (1);
2350 return rc;
2353 static gpg_error_t
2354 attr_command (assuan_context_t ctx, char *line)
2356 struct client_s *client = assuan_get_pointer (ctx);
2357 gpg_error_t rc;
2358 struct argv_s *args[] = {
2359 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2360 NULL
2363 rc = parse_options (&line, args, client);
2364 if (rc)
2365 return send_error (ctx, rc);
2367 if (client->opts & OPT_INQUIRE)
2369 unsigned char *result;
2370 size_t len;
2372 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2373 if (rc)
2374 return send_error (ctx, rc);
2376 pthread_cleanup_push (xfree, result);
2377 rc = do_attr (ctx, (char *)result);
2378 pthread_cleanup_pop (1);
2380 else
2381 rc = do_attr (ctx, line);
2383 return send_error (ctx, rc);
2386 static gpg_error_t
2387 parse_iscached_opt_lock (void *data, void *value)
2389 struct client_s *client = data;
2391 (void) value;
2392 client->opts |= OPT_LOCK;
2393 return 0;
2396 static gpg_error_t
2397 iscached_command (assuan_context_t ctx, char *line)
2399 struct client_s *client = assuan_get_pointer (ctx);
2400 gpg_error_t rc;
2401 struct argv_s *args[] = {
2402 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_iscached_opt_lock},
2403 NULL
2406 if (!line || !*line)
2407 return send_error (ctx, GPG_ERR_SYNTAX);
2409 rc = parse_options (&line, args, client);
2410 if (rc)
2411 return send_error (ctx, rc);
2412 else if (!valid_filename (line))
2413 return send_error (ctx, GPG_ERR_INV_VALUE);
2415 rc = cache_iscached (line, NULL);
2416 if (client->opts & OPT_LOCK
2417 && (!rc || gpg_err_code (rc) == GPG_ERR_NO_DATA))
2419 unsigned char md5file[16];
2420 gpg_error_t trc = rc;
2422 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2423 if (memcmp (md5file, client->md5file, 16))
2424 cleanup_client (client);
2426 memcpy (client->md5file, md5file, 16);
2427 rc = do_lock (client, 1);
2428 if (!rc)
2429 rc = trc;
2432 return send_error (ctx, rc);
2435 static gpg_error_t
2436 clearcache_command (assuan_context_t ctx, char *line)
2438 gpg_error_t rc = 0, all_rc = 0;
2439 unsigned char md5file[16];
2440 int i;
2441 int t;
2442 int all = 0;
2443 struct client_thread_s *once = NULL;
2445 cache_lock ();
2446 MUTEX_LOCK (&cn_mutex);
2447 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
2449 if (!line || !*line)
2450 all = 1;
2452 t = slist_length (cn_thread_list);
2454 for (i = 0; i < t; i++)
2456 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2457 assuan_peercred_t peer;
2459 if (!thd->cl)
2460 continue;
2462 /* Lock each connected clients' file mutex to prevent any other client
2463 * from accessing the cache entry (the file mutex is locked upon
2464 * command startup). The cache for the entry is not cleared if the
2465 * file mutex is locked by another client to prevent this function
2466 * from blocking.
2468 if (all)
2470 if (thd->cl->filename)
2472 rc = do_validate_peer (ctx, thd->cl->filename, &peer);
2473 all_rc = !all_rc ? rc : all_rc;
2474 if (rc)
2476 rc = 0;
2477 continue;
2481 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0, -1);
2482 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2484 if (pthread_equal (pthread_self (), thd->tid))
2485 rc = 0;
2486 else
2488 if (!thd->cl->filename ||
2489 cache_iscached (thd->cl->filename,
2490 NULL) == GPG_ERR_NO_DATA)
2492 rc = 0;
2493 continue;
2496 cache_defer_clear (thd->cl->md5file);
2499 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
2501 rc = 0;
2502 continue;
2505 if (!rc)
2507 rc = cache_clear (thd->cl->md5file);
2508 cache_unlock_mutex (thd->cl->md5file, 0);
2511 if (rc)
2512 all_rc = rc;
2514 rc = 0;
2516 /* A single data filename was specified. Lock only this data file
2517 * mutex and free the cache entry. */
2518 else
2520 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2521 rc = do_validate_peer (ctx, line, &peer);
2523 if (!rc && !memcmp (thd->cl->md5file, md5file, sizeof (md5file)))
2525 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0,
2526 -1);
2527 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2529 if (pthread_equal (pthread_self (), thd->tid))
2530 rc = 0;
2533 if (!rc)
2535 once = thd;
2536 rc = cache_clear (thd->cl->md5file);
2537 cache_unlock_mutex (thd->cl->md5file, 0);
2539 else
2541 cache_defer_clear (thd->cl->md5file);
2544 break;
2549 /* Only connected clients' cache entries have been cleared. Now clear any
2550 * remaining cache entries without clients but only if there wasn't an
2551 * error from above since this would defeat the locking check of the
2552 * remaining entries. */
2553 if (!all_rc && all)
2555 cache_clear (NULL);
2558 /* No clients are using the specified file. */
2559 else if (!all_rc && !rc && !once)
2561 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2562 rc = cache_clear (md5file);
2565 /* Release the connection mutex. */
2566 pthread_cleanup_pop (1);
2567 cache_unlock ();
2569 if (!rc)
2570 send_status_all (STATUS_CACHE, NULL);
2572 /* One or more files were locked while clearing all cache entries. */
2573 if (all_rc)
2574 rc = all_rc;
2576 return send_error (ctx, rc);
2579 static gpg_error_t
2580 cachetimeout_command (assuan_context_t ctx, char *line)
2582 int timeout;
2583 char **req = str_split (line, " ", 0);
2584 char *p;
2585 gpg_error_t rc = 0;
2586 assuan_peercred_t peer;
2588 if (!req || !*req || !req[1])
2590 strv_free (req);
2591 return send_error (ctx, GPG_ERR_SYNTAX);
2594 errno = 0;
2595 timeout = (int) strtol (req[1], &p, 10);
2596 if (errno != 0 || *p || timeout < -1)
2598 strv_free (req);
2599 return send_error (ctx, GPG_ERR_SYNTAX);
2602 rc = do_validate_peer (ctx, req[0], &peer);
2603 if (!rc)
2605 unsigned char md5file[16];
2607 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, req[0], strlen (req[0]));
2608 rc = cache_set_timeout (md5file, timeout);
2609 if (!rc || gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
2611 rc = 0;
2612 MUTEX_LOCK (&rcfile_mutex);
2613 config_set_int_param (&global_config, req[0], "cache_timeout",
2614 req[1]);
2615 MUTEX_UNLOCK (&rcfile_mutex);
2619 strv_free (req);
2620 return send_error (ctx, rc);
2623 static gpg_error_t
2624 dump_command (assuan_context_t ctx, char *line)
2626 xmlChar *xml;
2627 int len;
2628 struct client_s *client = assuan_get_pointer (ctx);
2629 gpg_error_t rc;
2631 if (disable_list_and_dump == 1)
2632 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2634 rc = peer_is_invoker(client);
2635 if (rc)
2636 return send_error (ctx, rc);
2638 xmlDocDumpFormatMemory (client->doc, &xml, &len, 1);
2640 if (!xml)
2642 log_write ("%s(%i): %s", __FILE__, __LINE__,
2643 pwmd_strerror (GPG_ERR_ENOMEM));
2644 return send_error (ctx, GPG_ERR_ENOMEM);
2647 pthread_cleanup_push (xmlFree, xml);
2648 rc = xfer_data (ctx, (char *) xml, len);
2649 pthread_cleanup_pop (1);
2650 return send_error (ctx, rc);
2653 static gpg_error_t
2654 getconfig_command (assuan_context_t ctx, char *line)
2656 struct client_s *client = assuan_get_pointer (ctx);
2657 gpg_error_t rc = 0;
2658 char filename[255] = { 0 }, param[747] = { 0 };
2659 char *p, *tmp = NULL, *fp = client->filename, *paramp = line;
2661 if (!line || !*line)
2662 return send_error (ctx, GPG_ERR_SYNTAX);
2664 if (strchr (line, ' '))
2666 sscanf (line, " %254[^ ] %746c", filename, param);
2667 paramp = param;
2668 fp = filename;
2671 if (fp && !valid_filename (fp))
2672 return send_error (ctx, GPG_ERR_INV_VALUE);
2674 paramp = str_down (paramp);
2675 if (!strcmp (paramp, "cipher") && fp)
2677 struct crypto_s *crypto = NULL;
2679 rc = init_client_crypto (&crypto);
2680 if (!rc)
2682 rc = read_data_header (fp, &crypto->hdr, NULL, NULL);
2683 if (!rc)
2685 const char *t =
2686 gcry_cipher_algo_name (cipher_to_gcrypt (crypto->hdr.flags));
2687 if (t)
2689 tmp = str_dup (t);
2690 if (tmp)
2691 str_down (tmp);
2696 UPDATE_AGENT_CTX (client, crypto);
2697 cleanup_crypto (&crypto);
2698 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
2699 return send_error (ctx, rc);
2701 if (!rc && tmp)
2702 goto done;
2704 else if (!strcmp (paramp, "cipher_iterations") && fp)
2706 struct crypto_s *crypto = NULL;
2708 rc = init_client_crypto (&crypto);
2709 if (!rc)
2711 rc = read_data_header (fp, &crypto->hdr, NULL, NULL);
2712 if (!rc)
2714 tmp = str_asprintf ("%llu",
2715 (unsigned long long) crypto->hdr.
2716 iterations);
2717 if (!tmp)
2718 rc = GPG_ERR_ENOMEM;
2722 UPDATE_AGENT_CTX (client, crypto);
2723 cleanup_crypto (&crypto);
2724 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
2725 return send_error (ctx, rc);
2727 if (!rc && tmp)
2728 goto done;
2730 else if (!strcmp (paramp, "passphrase"))
2731 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2733 p = config_get_value (fp ? fp : "global", paramp);
2734 if (!p)
2735 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2737 tmp = expand_homedir (p);
2738 xfree (p);
2739 if (!tmp)
2741 log_write ("%s(%i): %s", __FILE__, __LINE__,
2742 pwmd_strerror (GPG_ERR_ENOMEM));
2743 return send_error (ctx, GPG_ERR_ENOMEM);
2746 done:
2747 p = tmp;
2748 pthread_cleanup_push (xfree, p);
2749 rc = xfer_data (ctx, p, strlen (p));
2750 pthread_cleanup_pop (1);
2751 return send_error (ctx, rc);
2754 struct xpath_s
2756 xmlXPathContextPtr xp;
2757 xmlXPathObjectPtr result;
2758 xmlBufferPtr buf;
2759 char **req;
2762 static void
2763 xpath_command_cleanup (void *arg)
2765 struct xpath_s *xpath = arg;
2767 if (!xpath)
2768 return;
2770 req_cleanup (xpath->req);
2772 if (xpath->buf)
2773 xmlBufferFree (xpath->buf);
2775 if (xpath->result)
2776 xmlXPathFreeObject (xpath->result);
2778 if (xpath->xp)
2779 xmlXPathFreeContext (xpath->xp);
2782 static gpg_error_t
2783 do_xpath (assuan_context_t ctx, char *line)
2785 gpg_error_t rc;
2786 struct client_s *client = assuan_get_pointer (ctx);
2787 struct xpath_s _x = { 0 };
2788 struct xpath_s *xpath = &_x;
2790 if (!line || !*line)
2791 return GPG_ERR_SYNTAX;
2793 if ((xpath->req = str_split (line, "\t", 2)) == NULL)
2795 if (strv_printf (&xpath->req, "%s", line) == 0)
2796 return GPG_ERR_ENOMEM;
2799 xpath->xp = xmlXPathNewContext (client->doc);
2800 if (!xpath->xp)
2802 rc = GPG_ERR_BAD_DATA;
2803 goto fail;
2806 xpath->result =
2807 xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2808 if (!xpath->result)
2810 rc = GPG_ERR_BAD_DATA;
2811 goto fail;
2814 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2816 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2817 goto fail;
2820 rc = recurse_xpath_nodeset (client, client->doc, xpath->result->nodesetval,
2821 (xmlChar *) xpath->req[1], &xpath->buf, 0,
2822 NULL);
2823 if (rc)
2824 goto fail;
2825 else if (!xpath->req[1] && !xmlBufferLength (xpath->buf))
2827 rc = GPG_ERR_NO_DATA;
2828 goto fail;
2830 else if (xpath->req[1])
2832 rc = 0;
2833 goto fail;
2836 pthread_cleanup_push (xpath_command_cleanup, &xpath);
2837 rc = xfer_data (ctx, (char *) xmlBufferContent (xpath->buf),
2838 xmlBufferLength (xpath->buf));
2839 pthread_cleanup_pop (0);
2840 fail:
2841 xpath_command_cleanup (xpath);
2842 return rc;
2845 static gpg_error_t
2846 xpath_command (assuan_context_t ctx, char *line)
2848 struct client_s *client = assuan_get_pointer (ctx);
2849 gpg_error_t rc;
2850 struct argv_s *args[] = {
2851 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2852 NULL
2855 if (disable_list_and_dump == 1)
2856 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2858 rc = peer_is_invoker(client);
2859 if (rc)
2860 return send_error (ctx, rc);
2862 rc = parse_options (&line, args, client);
2863 if (rc)
2864 return send_error (ctx, rc);
2866 if (client->opts & OPT_INQUIRE)
2868 unsigned char *result;
2869 size_t len;
2871 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2872 if (rc)
2873 return send_error (ctx, rc);
2875 pthread_cleanup_push (xfree, result);
2876 rc = do_xpath (ctx, (char *)result);
2877 pthread_cleanup_pop (1);
2879 else
2880 rc = do_xpath (ctx, line);
2882 return send_error (ctx, rc);
2885 static gpg_error_t
2886 do_xpathattr (assuan_context_t ctx, char *line)
2888 struct client_s *client = assuan_get_pointer (ctx);
2889 gpg_error_t rc;
2890 char **req = NULL;
2891 int cmd = 0; //SET
2892 struct xpath_s _x = { 0 };
2893 struct xpath_s *xpath = &_x;
2895 if (!line || !*line)
2896 return GPG_ERR_SYNTAX;
2898 if ((req = str_split (line, " ", 3)) == NULL)
2899 return GPG_ERR_ENOMEM;
2901 if (!req[0])
2903 rc = GPG_ERR_SYNTAX;
2904 goto fail;
2907 if (!strcasecmp (req[0], "SET"))
2908 cmd = 0;
2909 else if (!strcasecmp (req[0], "DELETE"))
2910 cmd = 1;
2911 else
2913 rc = GPG_ERR_SYNTAX;
2914 goto fail;
2917 if (!req[1] || !req[2])
2919 rc = GPG_ERR_SYNTAX;
2920 goto fail;
2923 if ((xpath->req = str_split (req[2], "\t", 3)) == NULL)
2925 rc = GPG_ERR_ENOMEM;
2926 goto fail;
2929 if (!xpath->req[0] || (!xpath->req[1] && !cmd) || (xpath->req[1] && cmd))
2931 rc = GPG_ERR_SYNTAX;
2932 goto fail;
2935 xpath->xp = xmlXPathNewContext (client->doc);
2936 if (!xpath->xp)
2938 rc = GPG_ERR_BAD_DATA;
2939 goto fail;
2942 xpath->result = xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2943 if (!xpath->result)
2945 rc = GPG_ERR_BAD_DATA;
2946 goto fail;
2949 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2951 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2952 goto fail;
2955 rc = recurse_xpath_nodeset (client, client->doc, xpath->result->nodesetval,
2956 (xmlChar *) xpath->req[1], &xpath->buf, cmd,
2957 (xmlChar *) req[1]);
2959 fail:
2960 xpath_command_cleanup (xpath);
2961 strv_free (req);
2962 return rc;
2965 /* XPATHATTR SET|DELETE <name> <expression>[<TAB>[value]] */
2966 static gpg_error_t
2967 xpathattr_command (assuan_context_t ctx, char *line)
2969 struct client_s *client = assuan_get_pointer (ctx);
2970 gpg_error_t rc;
2971 struct argv_s *args[] = {
2972 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2973 NULL
2976 if (disable_list_and_dump == 1)
2977 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2979 rc = peer_is_invoker(client);
2980 if (rc)
2981 return send_error (ctx, rc);
2983 rc = parse_options (&line, args, client);
2984 if (rc)
2985 return send_error (ctx, rc);
2987 if (client->opts & OPT_INQUIRE)
2989 unsigned char *result;
2990 size_t len;
2992 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2993 if (rc)
2994 return send_error (ctx, rc);
2996 pthread_cleanup_push (xfree, result);
2997 rc = do_xpathattr (ctx, (char *)result);
2998 pthread_cleanup_pop (1);
3000 else
3001 rc = do_xpathattr (ctx, line);
3003 return send_error (ctx, rc);
3006 static gpg_error_t
3007 do_import (struct client_s *client, const char *root_element,
3008 unsigned char *content)
3010 char **dst_path = NULL;
3011 xmlDocPtr doc = NULL;
3012 xmlNodePtr n, root, copy;
3013 gpg_error_t rc;
3015 if (!content || !*content)
3017 xfree (content);
3018 return GPG_ERR_SYNTAX;
3021 if (root_element)
3022 dst_path = str_split (root_element, "\t", 0);
3024 if (dst_path && !valid_element_path (dst_path, 0))
3026 if (dst_path)
3027 strv_free (dst_path);
3029 return GPG_ERR_INV_VALUE;
3032 struct string_s *str = string_new_content ((char *)content);
3033 str = string_prepend (str, "<pwmd>");
3034 str = string_append (str, "</pwmd>");
3035 doc = xmlReadDoc ((xmlChar *) str->str, NULL, "UTF-8", XML_PARSE_NOBLANKS);
3036 string_free (str, 1);
3037 if (!doc)
3039 rc = GPG_ERR_BAD_DATA;
3040 goto fail;
3043 root = xmlDocGetRootElement (doc);
3044 xmlNodePtr root_orig = root->children;
3045 root = root->children;
3046 rc = validate_import (client, root);
3047 if (rc)
3048 goto fail;
3052 again:
3053 if (dst_path)
3055 char **path = strv_dup (dst_path);
3056 if (!path)
3058 log_write ("%s(%i): %s", __FILE__, __LINE__,
3059 pwmd_strerror (GPG_ERR_ENOMEM));
3060 rc = GPG_ERR_ENOMEM;
3061 goto fail;
3064 xmlChar *a = xmlGetProp (root, (xmlChar *) "_name");
3065 if (!a)
3067 strv_free (path);
3068 rc = GPG_ERR_INV_VALUE;
3069 goto fail;
3072 if (strv_printf (&path, "%s", (char *) a) == 0)
3074 xmlFree (a);
3075 rc = GPG_ERR_ENOMEM;
3076 goto fail;
3079 xmlFree (a);
3080 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 0);
3081 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3083 strv_free (path);
3084 goto fail;
3087 if (!rc)
3089 n = find_elements (client, client->doc, n->children, path + 1, &rc,
3090 NULL, NULL, NULL, 0, 0, NULL, 1);
3091 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3093 strv_free (path);
3094 goto fail;
3096 else if (!rc)
3098 xmlUnlinkNode (n);
3099 xmlFreeNode (n);
3100 strv_free (path);
3101 path = NULL;
3102 goto again;
3106 if (rc == GPG_ERR_ELEMENT_NOT_FOUND)
3108 n = create_element_path (client, &path, &rc, NULL);
3109 if (rc)
3110 goto fail;
3113 if (root->children)
3115 copy = xmlCopyNodeList (root->children);
3116 n = xmlAddChildList (n, copy);
3117 if (!n)
3118 rc = GPG_ERR_ENOMEM;
3121 strv_free (path);
3123 else
3125 char **path = NULL;
3127 /* Check if the content root element can create a DTD root element. */
3128 if (!xmlStrEqual ((xmlChar *) "element", root->name))
3130 rc = GPG_ERR_SYNTAX;
3131 goto fail;
3134 xmlChar *a;
3136 if ((a = xmlGetProp (root, (xmlChar *) "_name")) == NULL)
3138 rc = GPG_ERR_SYNTAX;
3139 goto fail;
3142 char *tmp = str_dup ((char *) a);
3143 xmlFree (a);
3144 int literal = is_literal_element (&tmp);
3146 if (!valid_xml_element ((xmlChar *) tmp) || literal)
3148 xfree (tmp);
3149 rc = GPG_ERR_INV_VALUE;
3150 goto fail;
3153 if (strv_printf (&path, "%s", tmp) == 0)
3155 xfree (tmp);
3156 rc = GPG_ERR_ENOMEM;
3157 goto fail;
3160 xfree (tmp);
3161 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 1);
3162 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3164 rc = GPG_ERR_BAD_DATA;
3165 goto fail;
3168 /* Overwriting the existing tree. */
3169 if (!rc)
3171 xmlUnlinkNode (n);
3172 xmlFreeNodeList (n);
3175 rc = 0;
3176 xmlSetProp (root, (xmlChar *) "_name", (xmlChar *) path[0]);
3177 n = xmlCopyNode (root, 1);
3178 n = xmlAddChildList (xmlDocGetRootElement (client->doc), n);
3179 strv_free (path);
3182 if (n && !rc)
3183 rc = update_element_mtime (client, n->parent);
3185 for (root = root_orig->next; root; root = root->next)
3187 if (root->type == XML_ELEMENT_NODE)
3188 break;
3191 root_orig = root;
3193 while (root);
3195 fail:
3196 if (doc)
3197 xmlFreeDoc (doc);
3199 if (dst_path)
3200 strv_free (dst_path);
3202 return rc;
3205 static gpg_error_t
3206 parse_import_opt_root (void *data, void *value)
3208 struct client_s *client = data;
3210 client->import_root = str_dup (value);
3211 return client->import_root ? 0 : GPG_ERR_ENOMEM;
3214 static gpg_error_t
3215 import_command (assuan_context_t ctx, char *line)
3217 gpg_error_t rc;
3218 struct client_s *client = assuan_get_pointer (ctx);
3219 unsigned char *result;
3220 size_t len;
3221 struct argv_s *args[] = {
3222 &(struct argv_s) {"root", OPTION_TYPE_ARG, parse_import_opt_root},
3223 NULL
3226 xfree (client->import_root);
3227 client->import_root = NULL;
3228 rc = parse_options (&line, args, client);
3229 if (rc)
3230 return send_error (ctx, rc);
3232 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3233 if (rc)
3235 xfree (client->import_root);
3236 client->import_root = NULL;
3237 return send_error (ctx, rc);
3240 rc = do_import (client, client->import_root, result);
3241 xfree (client->import_root);
3242 client->import_root = NULL;
3243 return send_error (ctx, rc);
3246 static gpg_error_t
3247 do_lock (struct client_s *client, int add)
3249 gpg_error_t rc = lock_file_mutex (client, add);
3251 if (!rc)
3252 client->flags |= FLAG_LOCK_CMD;
3254 return rc;
3257 static gpg_error_t
3258 lock_command (assuan_context_t ctx, char *line)
3260 struct client_s *client = assuan_get_pointer (ctx);
3261 gpg_error_t rc = do_lock (client, 0);
3263 return send_error (ctx, rc);
3266 static gpg_error_t
3267 unlock_command (assuan_context_t ctx, char *line)
3269 struct client_s *client = assuan_get_pointer (ctx);
3270 gpg_error_t rc;
3272 rc = unlock_file_mutex (client, 0);
3273 return send_error (ctx, rc);
3276 static gpg_error_t
3277 option_command (assuan_context_t ctx, char *line)
3279 struct client_s *client = assuan_get_pointer (ctx);
3280 gpg_error_t rc = 0;
3281 struct pinentry_option_s *pin_opts = &client->pinentry_opts;
3282 #ifdef WITH_AGENT
3283 struct agent_s *agent = client->crypto->agent;
3284 #endif
3285 char namebuf[255] = { 0 };
3286 char *name = namebuf;
3287 char *value = NULL, *p, *tmp = NULL;
3289 p = strchr (line, '=');
3290 if (!p)
3292 strncpy (namebuf, line, sizeof(namebuf));
3293 namebuf[sizeof(namebuf)-1] = 0;
3295 else
3297 strncpy (namebuf, line, strlen (line)-strlen (p));
3298 namebuf[sizeof(namebuf)-1] = 0;
3299 value = p+1;
3302 log_write1 ("OPTION name='%s' value='%s'", name, value);
3304 if (strcasecmp (name, (char *) "log_level") == 0)
3306 long l = 0;
3308 if (value)
3310 l = strtol (value, NULL, 10);
3312 if (l < 0 || l > 2)
3313 return send_error (ctx, GPG_ERR_INV_VALUE);
3315 else
3316 return send_error (ctx, GPG_ERR_INV_VALUE);
3318 MUTEX_LOCK (&rcfile_mutex);
3319 config_set_int_param (&global_config, "global", "log_level", value);
3320 MUTEX_UNLOCK (&rcfile_mutex);
3321 goto done;
3323 else if (strcasecmp (name, (char *) "lock-timeout") == 0)
3325 long n = 0;
3327 if (value)
3329 n = strtol (value, &tmp, 10);
3330 if (tmp && *tmp)
3331 return send_error (ctx, GPG_ERR_INV_VALUE);
3334 client->lock_timeout = n;
3335 goto done;
3337 else if (strcasecmp (name, (char *) "NAME") == 0)
3339 if (value && strchr (value, ' '))
3340 rc = GPG_ERR_INV_VALUE;
3341 else
3343 tmp = pthread_getspecific (thread_name_key);
3344 xfree (tmp);
3345 MUTEX_LOCK (&cn_mutex);
3346 xfree (client->thd->name);
3347 client->thd->name = NULL;
3349 if (!value || !*value)
3350 pthread_setspecific (thread_name_key, str_dup (""));
3351 else
3353 client->thd->name = str_dup (value);
3354 pthread_setspecific (thread_name_key, str_dup (value));
3357 MUTEX_UNLOCK (&cn_mutex);
3359 goto done;
3361 else if (strcasecmp (name, (char *) "lc-messages") == 0)
3363 xfree (pin_opts->lc_messages);
3364 pin_opts->lc_messages = NULL;
3365 if (value && *value)
3366 pin_opts->lc_messages = str_dup (value);
3367 #ifdef WITH_AGENT
3368 if (use_agent)
3369 rc = set_agent_option (client->crypto->agent, "lc-messages", value);
3370 #endif
3372 else if (strcasecmp (name, (char *) "lc-ctype") == 0)
3374 xfree (pin_opts->lc_ctype);
3375 pin_opts->lc_ctype = NULL;
3376 if (value && *value)
3377 pin_opts->lc_ctype = str_dup (value);
3378 #ifdef WITH_AGENT
3379 if (use_agent)
3380 rc = set_agent_option (client->crypto->agent, "lc-ctype", value);
3381 #endif
3383 else if (strcasecmp (name, (char *) "ttyname") == 0)
3385 xfree (pin_opts->ttyname);
3386 pin_opts->ttyname = NULL;
3387 if (value && *value)
3388 pin_opts->ttyname = str_dup (value);
3389 #ifdef WITH_AGENT
3390 if (use_agent)
3391 rc = set_agent_option (client->crypto->agent, "ttyname", value);
3392 #endif
3394 else if (strcasecmp (name, (char *) "ttytype") == 0)
3396 xfree (pin_opts->ttytype);
3397 pin_opts->ttytype = NULL;
3398 if (value && *value)
3399 pin_opts->ttytype = str_dup (value);
3400 #ifdef WITH_AGENT
3401 if (use_agent)
3402 rc = set_agent_option (client->crypto->agent, "ttytype", value);
3403 #endif
3405 else if (strcasecmp (name, (char *) "display") == 0)
3407 xfree (pin_opts->display);
3408 pin_opts->display = NULL;
3409 if (value && *value)
3410 pin_opts->display = str_dup (value);
3411 #ifdef WITH_AGENT
3412 if (use_agent)
3413 rc = set_agent_option (client->crypto->agent, "display", value);
3414 #endif
3416 else if (strcasecmp (name, (char *) "pinentry-desc") == 0)
3418 xfree (pin_opts->desc);
3419 pin_opts->desc = NULL;
3420 if (value && *value)
3421 pin_opts->desc = str_dup (value);
3423 else if (strcasecmp (name, (char *) "pinentry-title") == 0)
3425 xfree (pin_opts->title);
3426 pin_opts->title = NULL;
3427 if (value && *value)
3428 pin_opts->title = str_dup (value);
3430 else if (strcasecmp (name, (char *) "pinentry-prompt") == 0)
3432 xfree (pin_opts->prompt);
3433 pin_opts->prompt = NULL;
3434 if (value && *value)
3435 pin_opts->prompt = str_dup (value);
3438 else if (strcasecmp (name, "pinentry-timeout") == 0)
3440 char *p = NULL;
3441 int n;
3443 if (!value)
3444 goto done;
3446 n = (int) strtol (value, &p, 10);
3448 if (*p || n < 0)
3449 return send_error (ctx, GPG_ERR_INV_VALUE);
3451 pin_opts->timeout = n;
3452 MUTEX_LOCK (&rcfile_mutex);
3453 config_set_int_param (&global_config,
3454 client->filename ? client->filename : "global",
3455 "pinentry_timeout", value);
3456 MUTEX_UNLOCK (&rcfile_mutex);
3457 goto done;
3459 else if (strcasecmp (name, "disable-pinentry") == 0)
3461 int n = 1;
3463 if (value && *value)
3465 n = (int) strtol (value, &tmp, 10);
3466 if (*tmp || n < 0 || n > 1)
3467 return send_error (ctx, GPG_ERR_INV_VALUE);
3470 if (n)
3471 client->flags |= FLAG_NO_PINENTRY;
3472 else
3473 client->flags &= ~FLAG_NO_PINENTRY;
3475 #ifdef WITH_AGENT
3476 if (use_agent)
3478 if (client->flags & FLAG_NO_PINENTRY)
3479 rc = set_agent_option (client->crypto->agent, "pinentry-mode",
3480 "loopback");
3481 else
3482 rc = set_agent_option (client->crypto->agent, "pinentry-mode",
3483 "ask");
3485 if (rc)
3486 return send_error (ctx, rc);
3488 #endif
3490 else
3491 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
3493 done:
3494 #ifdef WITH_AGENT
3495 if (!rc && use_agent && agent)
3497 rc = pinentry_merge_options (&client->crypto->agent->pinentry_opts,
3498 pin_opts);
3500 #endif
3502 return send_error (ctx, rc);
3505 static gpg_error_t
3506 do_rename (assuan_context_t ctx, char *line)
3508 struct client_s *client = assuan_get_pointer (ctx);
3509 gpg_error_t rc;
3510 char **req, **src, *dst;
3511 xmlNodePtr n, ndst;
3513 req = str_split (line, " ", 0);
3515 if (!req || !req[0] || !req[1])
3517 strv_free (req);
3518 return GPG_ERR_SYNTAX;
3521 dst = req[1];
3522 is_literal_element (&dst);
3524 if (!valid_xml_element ((xmlChar *) dst))
3526 strv_free (req);
3527 return GPG_ERR_INV_VALUE;
3530 if (strchr (req[0], '\t'))
3531 src = str_split (req[0], "\t", 0);
3532 else
3533 src = str_split (req[0], " ", 0);
3535 if (!src || !*src)
3537 rc = GPG_ERR_SYNTAX;
3538 goto fail;
3541 n = find_root_element (client, client->doc, &src, &rc, NULL, 0, 0);
3542 if (src[1] && n)
3543 n = find_elements (client, client->doc, n->children, src + 1, &rc, NULL, NULL,
3544 NULL, 0, 0, NULL, 0);
3546 if (!n)
3547 goto fail;
3549 rc = is_element_owner (client, n);
3550 if (rc)
3551 goto fail;
3553 xmlChar *a = xmlGetProp (n, (xmlChar *) "_name");
3554 if (!a)
3556 rc = GPG_ERR_ENOMEM;
3557 goto fail;
3560 /* To prevent unwanted effects:
3562 * <root name="a"><b/></root>
3564 * RENAME a<TAB>b b
3566 if (xmlStrEqual (a, (xmlChar *) dst))
3568 xmlFree (a);
3569 rc = GPG_ERR_AMBIGUOUS_NAME;
3570 goto fail;
3573 xmlFree (a);
3574 char **tmp = NULL;
3575 if (src[1])
3577 char **p;
3579 for (p = src; *p; p++)
3581 if (!*(p + 1))
3582 break;
3583 strv_printf (&tmp, "%s", *p);
3587 strv_printf (&tmp, "!%s", dst);
3588 ndst = find_root_element (client, client->doc, &tmp, &rc, NULL, 0, 0);
3589 if (!ndst && rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3591 strv_free (tmp);
3592 goto fail;
3595 if (tmp[1] && ndst)
3596 ndst = find_elements (client, client->doc, ndst->children, tmp + 1, &rc, NULL,
3597 NULL, NULL, 0, 0, NULL, 0);
3599 strv_free (tmp);
3600 if (!ndst && rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3601 goto fail;
3603 rc = 0;
3605 /* Target may exist:
3607 * <root name="a"/>
3608 * <root name="b" target="a"/>
3610 * RENAME b a
3612 * Would need to do:
3613 * RENAME !b a
3615 if (ndst == n)
3617 rc = GPG_ERR_AMBIGUOUS_NAME;
3618 goto fail;
3621 if (ndst)
3623 rc = is_element_owner (client, ndst);
3624 if (rc)
3625 goto fail;
3627 unlink_node (client, ndst);
3628 xmlFreeNodeList (ndst);
3631 rc = add_attribute (client, n, "_name", dst);
3633 fail:
3634 strv_free (req);
3635 strv_free (src);
3636 return rc;
3639 static gpg_error_t
3640 rename_command (assuan_context_t ctx, char *line)
3642 struct client_s *client = assuan_get_pointer (ctx);
3643 gpg_error_t rc;
3644 struct argv_s *args[] = {
3645 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3646 NULL
3649 rc = parse_options (&line, args, client);
3650 if (rc)
3651 return send_error (ctx, rc);
3653 if (client->opts & OPT_INQUIRE)
3655 unsigned char *result;
3656 size_t len;
3658 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3659 if (rc)
3660 return send_error (ctx, rc);
3662 pthread_cleanup_push (xfree, result);
3663 rc = do_rename (ctx, (char *)result);
3664 pthread_cleanup_pop (1);
3666 else
3667 rc = do_rename (ctx, line);
3669 return send_error (ctx, rc);
3672 static gpg_error_t
3673 do_copy (assuan_context_t ctx, char *line)
3675 struct client_s *client = assuan_get_pointer (ctx);
3676 gpg_error_t rc;
3677 char **req, **src = NULL, **dst = NULL;
3678 xmlNodePtr nsrc, ndst, new = NULL;
3680 req = str_split (line, " ", 0);
3681 if (!req || !req[0] || !req[1])
3683 strv_free (req);
3684 return GPG_ERR_SYNTAX;
3687 if (strchr (req[0], '\t'))
3688 src = str_split (req[0], "\t", 0);
3689 else
3690 src = str_split (req[0], " ", 0);
3692 if (!src || !*src)
3694 rc = GPG_ERR_SYNTAX;
3695 goto fail;
3698 if (strchr (req[1], '\t'))
3699 dst = str_split (req[1], "\t", 0);
3700 else
3701 dst = str_split (req[1], " ", 0);
3703 if (!dst || !*dst)
3705 rc = GPG_ERR_SYNTAX;
3706 goto fail;
3709 if (!valid_element_path (dst, 0))
3711 rc = GPG_ERR_INV_VALUE;
3712 goto fail;
3715 nsrc = find_root_element (client, client->doc, &src, &rc, NULL, 0, 0);
3716 if (nsrc && src[1])
3717 nsrc = find_elements (client, client->doc, nsrc->children, src + 1, &rc, NULL,
3718 NULL, NULL, 0, 0, NULL, 0);
3720 if (!nsrc)
3721 goto fail;
3723 new = xmlCopyNodeList (nsrc);
3724 if (!new)
3726 rc = GPG_ERR_ENOMEM;
3727 goto fail;
3730 int create = 0;
3731 ndst = find_root_element (client, client->doc, &dst, &rc, NULL, 0, 0);
3732 if (ndst && dst[1])
3734 if (ndst->children)
3735 ndst = find_elements (client, client->doc, ndst->children, dst + 1, &rc, NULL,
3736 NULL, create_target_elements_cb, 0, 0, NULL, 0);
3737 else
3738 create = 1;
3740 else
3741 create = 1;
3743 if (!ndst && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3744 goto fail;
3745 else if (!ndst || create)
3747 ndst = create_element_path (client, &dst, &rc, NULL);
3748 if (!ndst)
3749 goto fail;
3752 rc = is_element_owner (client, ndst);
3753 if (rc)
3754 goto fail;
3756 /* Merge any attributes from the src node to the initial dst node. */
3757 for (xmlAttrPtr attr = new->properties; attr; attr = attr->next)
3759 if (xmlStrEqual (attr->name, (xmlChar *) "_name"))
3760 continue;
3762 xmlAttrPtr a = xmlHasProp (ndst, attr->name);
3763 if (a)
3764 xmlRemoveProp (a);
3766 xmlChar *tmp = xmlNodeGetContent (attr->children);
3767 xmlNewProp (ndst, attr->name, tmp);
3768 xmlFree (tmp);
3769 rc = add_attribute (client, ndst, NULL, NULL);
3772 xmlNodePtr n = ndst->children;
3773 xmlUnlinkNode (n);
3774 xmlFreeNodeList (n);
3775 ndst->children = NULL;
3777 if (new->children)
3779 n = xmlCopyNodeList (new->children);
3780 if (!n)
3782 rc = GPG_ERR_ENOMEM;
3783 goto fail;
3786 n = xmlAddChildList (ndst, n);
3787 if (!n)
3789 rc = GPG_ERR_ENOMEM;
3790 goto fail;
3793 rc = update_element_mtime (client, xmlDocGetRootElement (client->doc) ==
3794 ndst->parent ? ndst : ndst->parent);
3797 fail:
3798 if (new)
3800 xmlUnlinkNode (new);
3801 xmlFreeNodeList (new);
3804 if (req)
3805 strv_free (req);
3807 if (src)
3808 strv_free (src);
3810 if (dst)
3811 strv_free (dst);
3813 return rc;
3816 static gpg_error_t
3817 copy_command (assuan_context_t ctx, char *line)
3819 struct client_s *client = assuan_get_pointer (ctx);
3820 gpg_error_t rc;
3821 struct argv_s *args[] = {
3822 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3823 NULL
3826 rc = parse_options (&line, args, client);
3827 if (rc)
3828 return send_error (ctx, rc);
3830 if (client->opts & OPT_INQUIRE)
3832 unsigned char *result;
3833 size_t len;
3835 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3836 if (rc)
3837 return send_error (ctx, rc);
3839 pthread_cleanup_push (xfree, result);
3840 rc = do_copy (ctx, (char *)result);
3841 pthread_cleanup_pop (1);
3843 else
3844 rc = do_copy (ctx, line);
3846 return send_error (ctx, rc);
3849 static gpg_error_t
3850 do_move (assuan_context_t ctx, char *line)
3852 struct client_s *client = assuan_get_pointer (ctx);
3853 gpg_error_t rc;
3854 char **req, **src = NULL, **dst = NULL;
3855 xmlNodePtr nsrc, ndst = NULL;
3857 req = str_split (line, " ", 0);
3859 if (!req || !req[0] || !req[1])
3861 strv_free (req);
3862 return GPG_ERR_SYNTAX;
3865 if (strchr (req[0], '\t'))
3866 src = str_split (req[0], "\t", 0);
3867 else
3868 src = str_split (req[0], " ", 0);
3870 if (!src || !*src)
3872 rc = GPG_ERR_SYNTAX;
3873 goto fail;
3876 if (strchr (req[1], '\t'))
3877 dst = str_split (req[1], "\t", 0);
3878 else
3879 dst = str_split (req[1], " ", 0);
3881 nsrc = find_root_element (client, client->doc, &src, &rc, NULL, 0, 0);
3882 if (nsrc && src[1])
3883 nsrc = find_elements (client, client->doc, nsrc->children, src + 1, &rc,
3884 NULL, NULL, NULL, 0, 0, NULL, 0);
3886 if (!nsrc)
3887 goto fail;
3889 rc = is_element_owner (client, nsrc);
3890 if (rc)
3891 goto fail;
3893 if (dst)
3895 if (!valid_element_path (dst, 0))
3897 rc = GPG_ERR_INV_VALUE;
3898 goto fail;
3901 ndst = find_root_element (client, client->doc, &dst, &rc, NULL, 0, 0);
3902 if (ndst && dst[1])
3903 ndst = find_elements (client, client->doc, ndst->children, dst + 1,
3904 &rc, NULL, NULL, NULL, 0, 0, NULL, 0);
3906 else
3907 ndst = xmlDocGetRootElement (client->doc);
3909 for (xmlNodePtr n = ndst; n; n = n->parent)
3911 if (n == nsrc)
3913 rc = GPG_ERR_CONFLICT;
3914 goto fail;
3918 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3919 goto fail;
3921 rc = 0;
3923 if (ndst)
3925 xmlChar *a = node_has_attribute (nsrc, (xmlChar *) "_name");
3927 xmlNodePtr dup = find_element (client, ndst->children, (char *) a,
3928 NULL, &rc);
3929 xmlFree (a);
3931 if (rc)
3932 goto fail;
3934 if (dup)
3936 if (dup == nsrc)
3937 goto fail;
3939 if (ndst == xmlDocGetRootElement (client->doc))
3941 xmlNodePtr n = nsrc;
3942 int match = 0;
3944 while (n->parent && n->parent != ndst)
3945 n = n->parent;
3947 xmlChar *a = node_has_attribute (n, (xmlChar *) "_name");
3948 xmlChar *b = node_has_attribute (nsrc, (xmlChar *) "_name");
3950 if (xmlStrEqual (a, b))
3952 match = 1;
3953 xmlUnlinkNode (nsrc);
3954 xmlUnlinkNode (n);
3955 xmlFreeNodeList (n);
3958 xmlFree (a);
3959 xmlFree (b);
3961 if (!match)
3963 xmlUnlinkNode (dup);
3964 xmlFreeNodeList (dup);
3967 else
3968 xmlUnlinkNode (dup);
3972 if (!ndst && dst)
3974 xmlChar *name = node_has_attribute (nsrc, (xmlChar *) "_name");
3976 if (nsrc->parent == xmlDocGetRootElement (client->doc)
3977 && !strcmp ((char *) name, *dst))
3979 xmlFree (name);
3980 rc = GPG_ERR_CONFLICT;
3981 goto fail;
3984 xmlFree (name);
3985 ndst = create_element_path (client, &dst, &rc, nsrc);
3988 if (!ndst)
3989 goto fail;
3991 update_element_mtime (client, nsrc->parent);
3992 xmlUnlinkNode (nsrc);
3993 ndst = xmlAddChildList (ndst, nsrc);
3995 if (!ndst)
3996 rc = GPG_ERR_ENOMEM;
3997 else
3998 update_element_mtime (client, ndst->parent);
4000 fail:
4001 if (req)
4002 strv_free (req);
4004 if (src)
4005 strv_free (src);
4007 if (dst)
4008 strv_free (dst);
4010 return rc;
4013 static gpg_error_t
4014 move_command (assuan_context_t ctx, char *line)
4016 struct client_s *client = assuan_get_pointer (ctx);
4017 gpg_error_t rc;
4018 struct argv_s *args[] = {
4019 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
4020 NULL
4023 rc = parse_options (&line, args, client);
4024 if (rc)
4025 return send_error (ctx, rc);
4027 if (client->opts & OPT_INQUIRE)
4029 unsigned char *result;
4030 size_t len;
4032 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
4033 if (rc)
4034 return send_error (ctx, rc);
4036 pthread_cleanup_push (xfree, result);
4037 rc = do_move (ctx, (char *)result);
4038 pthread_cleanup_pop (1);
4040 else
4041 rc = do_move (ctx, line);
4043 return send_error (ctx, rc);
4046 static gpg_error_t
4047 ls_command (assuan_context_t ctx, char *line)
4049 gpg_error_t rc;
4050 char *tmp = str_asprintf ("%s/data", homedir);
4051 char *dir = expand_homedir (tmp);
4052 DIR *d = opendir (dir);
4054 rc = gpg_error_from_errno (errno);
4055 xfree (tmp);
4057 if (!d)
4059 xfree (dir);
4060 return send_error (ctx, rc);
4063 size_t len =
4064 offsetof (struct dirent, d_name) +pathconf (dir, _PC_NAME_MAX) + 1;
4065 struct dirent *p = xmalloc (len), *cur = NULL;
4066 char *list = NULL;
4068 xfree (dir);
4069 pthread_cleanup_push (xfree, p);
4070 pthread_cleanup_push ((void *)(void *)closedir, d);
4071 rc = 0;
4073 while (!readdir_r (d, p, &cur) && cur)
4075 if (cur->d_name[0] == '.' && cur->d_name[1] == '\0')
4076 continue;
4077 else if (cur->d_name[0] == '.' && cur->d_name[1] == '.'
4078 && cur->d_name[2] == '\0')
4079 continue;
4081 tmp = str_asprintf ("%s%s\n", list ? list : "", cur->d_name);
4083 if (!tmp)
4085 if (list)
4086 xfree (list);
4088 rc = GPG_ERR_ENOMEM;
4089 break;
4092 xfree (list);
4093 list = tmp;
4096 pthread_cleanup_pop (1); // closedir (d)
4097 pthread_cleanup_pop (1); // xfree (p)
4099 if (rc)
4100 return send_error (ctx, rc);
4102 if (!list)
4103 return send_error (ctx, GPG_ERR_NO_DATA);
4105 list[strlen (list) - 1] = 0;
4106 pthread_cleanup_push (xfree, list);
4107 rc = xfer_data (ctx, list, strlen (list));
4108 pthread_cleanup_pop (1);
4109 return send_error (ctx, rc);
4112 static gpg_error_t
4113 bye_notify (assuan_context_t ctx, char *line)
4115 struct client_s *cl = assuan_get_pointer (ctx);
4117 cl->thd->state = CLIENT_STATE_DISCON;
4119 #ifdef WITH_GNUTLS
4120 if (cl->thd->remote)
4122 int rc;
4126 struct timeval tv = { 0, 50000 };
4128 rc = gnutls_bye (cl->thd->tls->ses, GNUTLS_SHUT_RDWR);
4129 if (rc == GNUTLS_E_AGAIN)
4130 select (0, NULL, NULL, NULL, &tv);
4132 while (rc == GNUTLS_E_AGAIN);
4134 #endif
4136 /* This will let assuan_process_next() return. */
4137 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
4139 cl->last_rc = gpg_error_from_errno (errno);
4140 return cl->last_rc;
4143 cl->last_rc = 0; // BYE command result
4144 return 0;
4147 static gpg_error_t
4148 reset_notify (assuan_context_t ctx, char *line)
4150 struct client_s *client = assuan_get_pointer (ctx);
4152 if (client)
4153 cleanup_client (client);
4155 return 0;
4159 * This is called before every Assuan command.
4161 static gpg_error_t
4162 command_startup (assuan_context_t ctx, const char *name)
4164 struct client_s *client = assuan_get_pointer (ctx);
4165 gpg_error_t rc;
4166 struct command_table_s *cmd = NULL;
4168 log_write1 ("command='%s'", name);
4169 client->last_rc = client->opts = 0;
4171 for (int i = 0; command_table[i]; i++)
4173 if (!strcasecmp (name, command_table[i]->name))
4175 if (command_table[i]->ignore_startup)
4176 return 0;
4177 cmd = command_table[i];
4178 break;
4182 if (!cmd)
4183 return GPG_ERR_UNKNOWN_COMMAND;
4185 client->last_rc = rc = gpg_error (file_modified (client, cmd));
4186 if (!rc)
4187 update_client_state (client, CLIENT_STATE_COMMAND);
4189 return rc;
4193 * This is called after every Assuan command.
4195 static void
4196 command_finalize (assuan_context_t ctx, gpg_error_t rc)
4198 struct client_s *client = assuan_get_pointer (ctx);
4200 if (!(client->flags & FLAG_LOCK_CMD))
4201 unlock_file_mutex (client, 0);
4203 log_write1 (_("command completed: rc=%u"), rc ? rc : client->last_rc);
4204 client->last_rc = gpg_error (GPG_ERR_UNKNOWN_COMMAND);
4205 #ifdef WITH_GNUTLS
4206 client->thd->buffer_timeout = client->thd->last_buffer_size = 0;
4207 #endif
4208 update_client_state (client, CLIENT_STATE_IDLE);
4211 static gpg_error_t
4212 help_command (assuan_context_t ctx, char *line)
4214 gpg_error_t rc;
4215 int i;
4217 if (!line || !*line)
4219 char *tmp;
4220 char *help = str_dup (_("Usage: HELP [<COMMAND>]\n"
4221 "For commands that take an element path as an argument, each element is "
4222 "separated with an ASCII @key{TAB} character (ASCII 0x09)."
4223 "\n" "COMMANDS:"));
4225 for (i = 0; command_table[i]; i++)
4227 if (!command_table[i]->help)
4228 continue;
4230 tmp = str_asprintf ("%s %s", help, command_table[i]->name);
4231 xfree (help);
4232 help = tmp;
4235 tmp = strip_texi_and_wrap (help);
4236 xfree (help);
4237 pthread_cleanup_push (xfree, tmp);
4238 rc = xfer_data (ctx, tmp, strlen (tmp));
4239 pthread_cleanup_pop (1);
4240 return send_error (ctx, rc);
4243 for (i = 0; command_table[i]; i++)
4245 if (!strcasecmp (line, command_table[i]->name))
4247 char *help, *tmp;
4249 if (!command_table[i]->help)
4250 break;
4252 help = strip_texi_and_wrap (command_table[i]->help);
4253 tmp = str_asprintf (_("Usage: %s"), help);
4254 xfree (help);
4255 pthread_cleanup_push (xfree, tmp);
4256 rc = xfer_data (ctx, tmp, strlen (tmp));
4257 pthread_cleanup_pop (1);
4258 return send_error (ctx, rc);
4262 return send_error (ctx, GPG_ERR_INV_NAME);
4265 static void
4266 new_command (const char *name, int ignore, int unlock,
4267 gpg_error_t (*handler) (assuan_context_t, char *),
4268 const char *help)
4270 int i = 0;
4272 if (command_table)
4273 for (i = 0; command_table[i]; i++);
4275 command_table =
4276 xrealloc (command_table, (i + 2) * sizeof (struct command_table_s *));
4277 command_table[i] = xcalloc (1, sizeof (struct command_table_s));
4278 command_table[i]->name = name;
4279 command_table[i]->handler = handler;
4280 command_table[i]->ignore_startup = ignore;
4281 command_table[i]->unlock = unlock;
4282 command_table[i++]->help = help;
4283 command_table[i] = NULL;
4286 void
4287 deinit_commands ()
4289 int i;
4291 for (i = 0; command_table[i]; i++)
4292 xfree (command_table[i]);
4294 xfree (command_table);
4297 static int
4298 sort_commands (const void *arg1, const void *arg2)
4300 struct command_table_s *const *a = arg1;
4301 struct command_table_s *const *b = arg2;
4303 if (!*a || !*b)
4304 return 0;
4305 else if (*a && !*b)
4306 return 1;
4307 else if (!*a && *b)
4308 return -1;
4310 return strcmp ((*a)->name, (*b)->name);
4313 // FIXME cleanup/implement options
4314 static gpg_error_t
4315 passwd_command (assuan_context_t ctx, char *line)
4317 struct client_s *client = assuan_get_pointer (ctx);
4318 gpg_error_t rc;
4319 struct argv_s *args[] = {
4320 &(struct argv_s) {"reset", OPTION_TYPE_NOARG, parse_opt_reset},
4321 &(struct argv_s) {"s2k-count", OPTION_TYPE_ARG, parse_opt_s2k_count},
4322 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG, parse_opt_no_passphrase},
4323 NULL
4326 rc = peer_is_invoker (client);
4327 if (rc == GPG_ERR_EACCES)
4328 return send_error (ctx, rc);
4330 if (client->flags & FLAG_NEW)
4331 return send_error (ctx, GPG_ERR_INV_STATE);
4333 client->crypto->save.s2k_count =
4334 config_get_ulong (client->filename, "s2k_count");
4335 rc = parse_options (&line, args, client);
4336 if (rc)
4337 return send_error (ctx, rc);
4339 if (!rc && client->opts & OPT_RESET)
4341 rc = cache_clear (client->md5file);
4342 if (!rc)
4343 send_status_all (STATUS_CACHE, NULL);
4346 if (!rc)
4348 if (!IS_PKI (client->crypto))
4350 struct crypto_s *crypto;
4352 xfree (client->crypto->filename);
4353 client->crypto->filename = str_dup (client->filename);
4354 rc = change_passwd (ctx, client->filename,
4355 client->flags & FLAG_NO_PINENTRY, &crypto,
4356 (client->opts & OPT_NO_PASSPHRASE));
4357 if (!rc)
4359 cleanup_crypto (&client->crypto);
4360 client->crypto = crypto;
4361 update_checksum (client);
4362 cleanup_crypto_stage1 (client->crypto);
4365 #ifdef WITH_AGENT
4366 else
4368 if (client->crypto->save.s2k_count)
4369 rc = send_to_agent (client->crypto->agent, NULL, NULL,
4370 "OPTION s2k-count=%lu",
4371 client->crypto->save.s2k_count);
4373 if (!rc)
4374 rc = agent_passwd (client->crypto);
4376 #endif
4379 return send_error (ctx, rc);
4382 static gpg_error_t
4383 parse_keygrip_opt_sign (void *data, void *value)
4385 struct client_s *client = data;
4387 (void) value;
4388 client->opts |= OPT_SIGN;
4389 return 0;
4392 static gpg_error_t
4393 keygrip_command (assuan_context_t ctx, char *line)
4395 struct client_s *client = assuan_get_pointer (ctx);
4396 gpg_error_t rc;
4397 struct crypto_s *crypto = NULL;
4398 struct argv_s *args[] = {
4399 &(struct argv_s) {"sign", OPTION_TYPE_NOARG, parse_keygrip_opt_sign},
4400 NULL
4403 if (!line || !*line)
4404 return send_error (ctx, GPG_ERR_SYNTAX);
4406 rc = parse_options (&line, args, client);
4407 if (rc)
4408 return send_error (ctx, rc);
4410 if (!valid_filename (line))
4411 return send_error (ctx, GPG_ERR_INV_VALUE);
4413 rc = init_client_crypto (&crypto);
4414 if (rc)
4415 return send_error (ctx, rc);
4417 rc = read_data_file (line, crypto);
4418 if (!rc)
4420 char *hexgrip = NULL;
4422 if (!IS_PKI (crypto))
4424 cleanup_crypto (&crypto);
4425 return send_error (ctx, GPG_ERR_NOT_SUPPORTED);
4428 if (client->opts & OPT_SIGN)
4430 if (valid_keygrip (crypto->sign_grip, sizeof (crypto->sign_grip)))
4431 hexgrip = bin2hex (crypto->sign_grip, sizeof (crypto->sign_grip));
4434 if (!hexgrip)
4435 hexgrip = bin2hex (crypto->grip, sizeof (crypto->grip));
4437 if (!hexgrip)
4438 rc = GPG_ERR_ENOMEM;
4439 else
4440 rc = xfer_data (ctx, hexgrip, strlen (hexgrip));
4442 xfree (hexgrip);
4445 UPDATE_AGENT_CTX (client, crypto);
4446 cleanup_crypto (&crypto);
4447 return send_error (ctx, rc);
4450 static gpg_error_t
4451 parse_opt_data (void *data, void *value)
4453 struct client_s *client = data;
4455 (void) value;
4456 client->opts |= OPT_DATA;
4457 return 0;
4460 static gpg_error_t
4461 send_client_list (assuan_context_t ctx)
4463 struct client_s *client = assuan_get_pointer (ctx);
4464 gpg_error_t rc = 0;
4465 char buf[ASSUAN_LINELENGTH];
4467 if (client->opts & OPT_VERBOSE)
4469 unsigned i, t;
4470 char **list = NULL;
4471 char *line;
4473 MUTEX_LOCK (&cn_mutex);
4474 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
4475 t = slist_length (cn_thread_list);
4477 for (i = 0; i < t; i++)
4479 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
4480 char *tmp;
4482 if (thd->state == CLIENT_STATE_UNKNOWN)
4483 continue;
4485 tmp = build_client_info_line (thd, 0);
4486 if (tmp)
4488 char **l = strv_cat (list, tmp);
4489 if (!l)
4490 rc = GPG_ERR_ENOMEM;
4491 else
4492 list = l;
4494 else
4495 rc = GPG_ERR_ENOMEM;
4497 if (rc)
4499 strv_free (list);
4500 break;
4504 pthread_cleanup_pop (1);
4505 if (rc)
4506 return rc;
4508 line = strv_join ("\n", list);
4509 strv_free (list);
4510 pthread_cleanup_push (xfree, line);
4511 rc = xfer_data (ctx, line, strlen (line));
4512 pthread_cleanup_pop (1);
4513 return rc;
4516 if (client->opts & OPT_DATA)
4518 MUTEX_LOCK (&cn_mutex);
4519 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
4520 snprintf (buf, sizeof (buf), "%i", slist_length (cn_thread_list));
4521 pthread_cleanup_pop (1);
4522 rc = xfer_data (ctx, buf, strlen (buf));
4524 else
4525 rc = send_status (ctx, STATUS_CLIENTS, NULL);
4527 return rc;
4530 static gpg_error_t
4531 getinfo_command (assuan_context_t ctx, char *line)
4533 struct client_s *client = assuan_get_pointer (ctx);
4534 gpg_error_t rc;
4535 char buf[ASSUAN_LINELENGTH];
4536 struct argv_s *args[] = {
4537 &(struct argv_s) {"data", OPTION_TYPE_NOARG, parse_opt_data},
4538 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_opt_verbose},
4539 NULL
4542 rc = parse_options (&line, args, client);
4543 if (rc)
4544 return send_error (ctx, rc);
4546 if (!strcasecmp (line, "clients"))
4548 rc = send_client_list (ctx);
4550 else if (!strcasecmp (line, "cache"))
4552 if (client->opts & OPT_DATA)
4554 snprintf (buf, sizeof (buf), "%u", cache_file_count ());
4555 rc = xfer_data (ctx, buf, strlen (buf));
4557 else
4558 rc = send_status (ctx, STATUS_CACHE, NULL);
4560 else if (!strcasecmp (line, "pid"))
4562 char buf[32];
4563 pid_t pid = getpid ();
4565 snprintf (buf, sizeof (buf), "%i", pid);
4566 rc = xfer_data (ctx, buf, strlen (buf));
4568 else if (!strcasecmp (line, "version"))
4570 char *buf = str_asprintf ("0x%06x %s%s", VERSION_HEX,
4571 #ifdef WITH_GNUTLS
4572 "GNUTLS "
4573 #endif
4574 #ifdef WITH_QUALITY
4575 "QUALITY "
4576 #endif
4577 "", use_agent ? "AGENT" : "");
4578 rc = xfer_data (ctx, buf, strlen (buf));
4579 xfree (buf);
4581 else if (!strcasecmp (line, "last_error"))
4583 if (client->last_error)
4584 rc = xfer_data (ctx, client->last_error, strlen (client->last_error));
4585 else
4586 rc = GPG_ERR_NO_DATA;
4588 else if (!strcasecmp (line, "user"))
4590 char *user = NULL;
4592 #ifdef WITH_GNUTLS
4593 if (client->thd->remote)
4594 user = str_asprintf ("#%s", client->thd->tls->fp);
4595 else
4596 user = get_username (client->thd->peer->uid);
4597 #else
4598 user = get_username (client->thd->peer->uid);
4599 #endif
4600 if (user)
4602 pthread_cleanup_push (xfree, user);
4603 rc = xfer_data (ctx, user, strlen (user));
4604 pthread_cleanup_pop (1);
4606 else
4607 rc = GPG_ERR_NO_DATA;
4609 else
4610 rc = gpg_error (GPG_ERR_SYNTAX);
4612 return send_error (ctx, rc);
4615 #ifdef WITH_AGENT
4616 static gpg_error_t
4617 send_data_cb (void *user, const void *buf, size_t len)
4619 assuan_context_t ctx = user;
4621 return assuan_send_data (ctx, buf, len);
4624 static gpg_error_t
4625 send_status_cb (void *user, const char *line)
4627 assuan_context_t ctx = user;
4628 char keyword[200], *k;
4629 const char *p;
4631 for (p = line, k = keyword; *p; p++)
4633 if (isspace (*p))
4634 break;
4636 *k++ = *p;
4639 *k = 0;
4640 if (*p == '#')
4641 p++;
4643 while (isspace (*p))
4644 p++;
4646 return assuan_write_status (ctx, keyword, *p ? p : NULL);
4648 #endif
4650 static gpg_error_t
4651 kill_command (assuan_context_t ctx, char *line)
4653 #ifdef HAVE_PTHREAD_CANCEL
4654 struct client_s *client = assuan_get_pointer (ctx);
4655 gpg_error_t rc;
4657 if (!line || !*line)
4658 return send_error (ctx, GPG_ERR_SYNTAX);
4660 rc = peer_is_invoker (client);
4661 if (!rc)
4663 unsigned i, t;
4665 MUTEX_LOCK (&cn_mutex);
4666 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
4667 t = slist_length (cn_thread_list);
4668 rc = GPG_ERR_ESRCH;
4670 for (i = 0; i < t; i++)
4672 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
4673 char *tmp = str_asprintf ("%p", thd->tid);
4675 if (strcmp (line, tmp))
4677 xfree (tmp);
4678 continue;
4681 xfree (tmp);
4682 rc = pthread_cancel (thd->tid);
4683 break;
4686 pthread_cleanup_pop (1);
4689 return send_error (ctx, rc);
4690 #else
4691 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
4692 #endif
4695 static gpg_error_t
4696 agent_command (assuan_context_t ctx, char *line)
4698 gpg_error_t rc = 0;
4700 if (!use_agent)
4701 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
4703 #ifdef WITH_AGENT
4704 struct client_s *client = assuan_get_pointer (ctx);
4706 if (!line || !*line)
4707 return send_error (ctx, GPG_ERR_SYNTAX);
4709 assuan_set_flag (client->crypto->agent->ctx, ASSUAN_CONVEY_COMMENTS, 1);
4710 rc = assuan_transact (client->crypto->agent->ctx, line, send_data_cb,
4711 client->ctx, agent_loopback_cb, client->crypto,
4712 send_status_cb, client->ctx);
4713 if (gpg_err_code (rc) == GPG_ERR_ASS_CANCELED)
4715 char *line;
4716 size_t len;
4718 rc = assuan_write_line (client->crypto->agent->ctx, "CAN");
4719 if (!rc)
4721 rc = assuan_read_line (client->crypto->agent->ctx, &line, &len);
4722 if (!rc)
4723 rc = gpg_error (GPG_ERR_ASS_CANCELED);
4727 assuan_set_flag (client->crypto->agent->ctx, ASSUAN_CONVEY_COMMENTS, 0);
4728 #endif
4729 return send_error (ctx, rc);
4732 void
4733 init_commands ()
4735 /* !BEGIN-HELP-TEXT!
4737 * This comment is used as a marker to generate the offline documentation
4738 * found in doc/pwmd.info. The indentation needs to be kept for the awk
4739 * script to determine where commands begin and end.
4741 new_command("HELP", 1, 1, help_command, _(
4742 "HELP [<COMMAND>]\n"
4743 "Show available commands or command specific help text."
4746 new_command("AGENT", 1, 1, agent_command, _(
4747 "AGENT <command>\n"
4748 "Send a @command{gpg-agent} protocol @var{command} directly to the "
4749 "@command{gpg-agent}."
4752 new_command("KILL", 1, 0, kill_command, _(
4753 "KILL <thread_id>\n"
4754 "Terminates the client identified by @var{thread_id} and releases any file "
4755 "lock or other resources it has held. @xref{GETINFO} for details about listing "
4756 "connected clients.\n"
4759 new_command("GETINFO", 1, 1, getinfo_command, _(
4760 "GETINFO [--data] [--verbose] CACHE | CLIENTS | PID | USER | LAST_ERROR | VERSION\n"
4761 "Get server and other information: @var{CACHE} returns the number of cached "
4762 "documents via a status message. @var{CLIENTS} returns the number of "
4763 "connected clients via a status message or a list of connected clients when "
4764 "the @option{--verbose} parameter is used. The list contains space delimited "
4765 "fields: the thread ID, client name, opened file (@code{/} if none opened), "
4766 "file lock status, whether the current client is self, client state and "
4767 "user ID or TLS fingerprint of the connected client. "
4768 "Client state @code{0} is an unknown client state, @code{1} indicates the "
4769 "client has connected but hasn't completed initializing, @code{2} indicates "
4770 "that the client is idle, @code{3} means the "
4771 "client is in a command and @code{4} means the client is disconnecting. This "
4772 "line is always returned with a data response. @var{PID} returns the process "
4773 "ID number of the server via a data response. @var{VERSION} returns the server "
4774 "version number and compile-time features with a data response with each "
4775 "being space delimited. @var{LAST_ERROR} returns a detailed description of "
4776 "the last failed command when available. @var{USER} returns the username or "
4777 "@abbr{TLS} hash of the connected client. @xref{Status Messages}. "
4778 "\n"
4779 "When the @option{--data} option is specified then the result will be sent "
4780 "via a data response rather than a status message."
4783 new_command("PASSWD", 0, 0, passwd_command, _(
4784 "PASSWD [--reset] [--s2k-count=N] [--no-passphrase]\n"
4785 "Changes the passphrase of the secret key required to open the current "
4786 "file or the passphrase of a symmetrically encrypted data file. When the "
4787 "@option{--reset} option is passed then the cache entry for the current "
4788 "file will be reset and the passphrase, if any, will be required during the "
4789 "next @code{OPEN} (@pxref{OPEN})."
4790 "\n"
4791 "The @option{--s2k-count} option sets or changes (@pxref{SAVE}) the number "
4792 "of hash iterations for a passphrase and must be either @code{0} to use "
4793 "the calibrated count of the machine (the default), or a value greater than "
4794 "or equal to @code{65536}. This option has no effect for symmetrically "
4795 "encrypted data files."
4796 "\n"
4797 "The @option{--no-passphrase} option will prevent requiring a passphrase for "
4798 "the data file, although a passphrase may be required when changing it."
4799 "\n"
4800 "This command is not available for non-invoking clients "
4801 "(@pxref{Access Control})."
4804 new_command("KEYGRIP", 1, 1, keygrip_command, _(
4805 "KEYGRIP [--sign] <filename>\n"
4806 "Returns the hex encoded keygrip of the specified @var{filename} with a "
4807 "data response."
4808 "\n"
4809 "When the @option{--sign} option is specified then the key used for signing "
4810 "of the specified @var{filename} will be returned."
4811 "\n"
4812 "For symmetrically encrypted data files this command returns the error "
4813 "GPG_ERR_NOT_SUPPORTED."
4816 new_command("OPEN", 1, 1, open_command, _(
4817 "OPEN [--lock] <filename> [<passphrase>]\n"
4818 "Opens @var{filename} using @var{passphrase}. When the filename is not "
4819 "found on the file-system then a new document will be created. If the file "
4820 "is found, it is looked for in the file cache. If cached and no "
4821 "@var{passphrase} was specified then the cached document is opened. When not "
4822 "cached, @cite{pinentry(1)} will be used to retrieve the passphrase to use "
4823 "for decryption unless @option{disable-pinentry} (@pxref{OPTION}) was "
4824 "specified."
4825 "\n"
4826 "When the @option{--lock} option is passed then the file mutex will be "
4827 "locked as if the @code{LOCK} command (@pxref{LOCK}) had been sent after the "
4828 "file has been opened."
4831 new_command("SAVE", 0, 0, save_command, _(
4832 "SAVE [--no-passphrase] [--reset] [--no-agent] [--s2k-count=N] [--cipher=<algo>] [--cipher-iterations=N] [--inquire-keyparam] [--keygrip=hexstring] [--sign-keygrip=hexstring]\n"
4833 "Writes the @abbr{XML} document to disk. The file written to is the file that "
4834 "was opened using the @code{OPEN} command (@pxref{OPEN}). If the file is a "
4835 "new one or the option @option{--inquire-keyparam} was passed, then a new "
4836 "keypair will be generated and a pinentry will be used to prompt for the "
4837 "passphrase to encrypt with unless the @option{--no-passphrase} option was "
4838 "passed in which case the data file will not be passphrase protected. "
4839 "\n"
4840 "The @option{--no-agent} option disables use of @command{gpg-agent} for "
4841 "passphrase retrieval and caching of new files when @command{gpg-agent} "
4842 "use is enabled. The datafile will be symmetrically encrypted and will not "
4843 "use or generate any keypair."
4844 "\n"
4845 "The @option{--reset} option will clear the cache entry for the current file "
4846 "and require a passphrase, if needed, before saving."
4847 "\n"
4848 "The @option{--cipher} option can be used to encrypt the @abbr{XML} data to "
4849 "an alternate cipher. The default is @code{aes256}. See the Configuration "
4850 "(@pxref{Configuration}) for available ciphers."
4851 "\n"
4852 "The @option{--cipher-iterations} option specifies the number of times to "
4853 "encrypt the XML data. The default is 0 although 1 iteration is still done."
4854 "\n"
4855 "The @option{--inquire-keyparam} option will send a server @emph{INQUIRE} to "
4856 "the client to obtain the key paramaters to use when generating a new "
4857 "keypair. The inquired data is expected to be an S-expression. If not "
4858 "specified then an @samp{RSA} key of @samp{2048} bits will be generated "
4859 "unless otherwise set in the configuration file (@pxref{Configuration}). Note "
4860 "that when this option is specified a new keypair will be generated "
4861 "reguardless if the file is a new one and that if the data file is protected "
4862 "the passphrase to open it will be required before generating the new "
4863 "keypair. This option is not available for non-invoking clients "
4864 "(@pxref{Access Control})."
4865 "\n"
4866 "You can encrypt the data file to a public key other than the one that it "
4867 "was originally encrypted with by passing the @option{--keygrip} option with "
4868 "the hex encoded keygrip of the public key as its argument. The keygrip may "
4869 "be of any key that @command{gpg-agent} knows about. The "
4870 "@option{--sign-keygrip} option may also be used to sign with an alternate "
4871 "secret key. Use the @code{KEYGRIP} (@pxref{KEYGRIP}) command to obtain the "
4872 "keygrip of an existing data file. This option may be needed when using a "
4873 "smartcard. This option has no effect with symmetrically encrypted data "
4874 "files. These options are not available for non-invoking clients "
4875 "(@pxref{Access Control})."
4876 "\n"
4877 "The @option{--s2k-count} option sets number of hash iterations for a "
4878 "passphrase. A value less-than @code{65536} will use the machine calibrated "
4879 "value and is the default. This setting only affects new files. To change "
4880 "the setting use the @code{PASSWD} command (@pxref{PASSWD}). This option "
4881 "has no effect with symmetrically encrypted data files."
4884 new_command("ISCACHED", 1, 0, iscached_command, _(
4885 "ISCACHED [--lock] <filename>\n"
4886 "An @emph{OK} response is returned if the specified @var{filename} is found "
4887 "in the file cache. If not found in the cache but exists on the filesystem "
4888 "then @var{GPG_ERR_NO_DATA} is returned. Otherwise a filesystem error is "
4889 "returned."
4890 "\n"
4891 "The @option{lock} option will lock the file mutex of @var{filename} when the "
4892 "file exists; it does not need to be opened nor cached. The lock will be "
4893 "released when the client exits or sends the @code{UNLOCK} (@pxref{UNLOCK}) "
4894 "command."
4897 new_command("CLEARCACHE", 1, 1, clearcache_command, _(
4898 "CLEARCACHE [<filename>]\n"
4899 "Clears a file cache entry for all or the specified @var{filename}."
4902 new_command("CACHETIMEOUT", 1, 1, cachetimeout_command, _(
4903 "CACHETIMEOUT <filename> <seconds>\n"
4904 "The time in @var{seconds} until @var{filename} will be removed from the "
4905 "cache. @code{-1} will keep the cache entry forever, @code{0} will require "
4906 "the passphrase for each @code{OPEN} or @code{SAVE} command (@pxref{OPEN}, "
4907 "@pxref{SAVE}). @xref{Configuration}, and the @code{cache_timeout} "
4908 "parameter."
4911 new_command("LIST", 0, 1, list_command, _(
4912 "LIST [--inquire] [--no-recurse] [--verbose] [--with-target] [--all] [[!]element[<TAB>[!]child[..]]]\n"
4913 "If no element path is given then a newline separated list of root elements "
4914 "is returned with a data response. If given, then all reachable elements "
4915 "of the specified element path are returned unless the @option{--no-recurse} "
4916 "option is specified. If specified, only the child elements of the element "
4917 "path are returned without recursing into grandchildren. Each resulting "
4918 "element is prefixed with the literal @code{!} character when the element "
4919 "contains no @code{target} attribute. @xref{Target Attribute}, for details."
4920 "\n"
4921 "When the @option{--verbose} option is passed then each element path "
4922 "returned will have zero or more flags appened to it. These flags are "
4923 "delimited from the element path by a single space character. A flag itself "
4924 "is a single character. Flag @code{P} indicates that access to the element "
4925 "is denied. Flag @code{+} indicates that there are child nodes of "
4926 "the current element path. Flag @code{E} indicates that an element of an "
4927 "element path contained in a @var{target} attribute could not be found. Flag "
4928 "@code{O} indicates that a @var{target} attribute recursion limit was reached "
4929 "(@pxref{Configuration}). Flag @code{T} will append the resolved element path "
4930 "of the @var{target} attribute contained in the current element (see below)."
4931 "\n"
4932 "The @option{--with-target} option implies @option{--verbose} and will append "
4933 "an additional flag @code{T} followed by a single space then an element path. "
4934 "The appended element path is the resolved path (@pxref{REALPATH}) of the "
4935 "current element when it contains a @var{target} attribute. When no "
4936 "@var{target} attribute is found then no flag will be appended."
4937 "\n"
4938 "The @option{--no-recurse} option limits the amount of data returned to only "
4939 "the listing of children of the specified element path and not any "
4940 "grandchildren."
4941 "\n"
4942 "The @option{--all} option lists the entire element tree for each root "
4943 "element. This option also implies option @option{--verbose}."
4944 "\n"
4945 "When the @option{--inquire} option is passed then all remaining non-option "
4946 "arguments are retrieved via a server @emph{INQUIRE}."
4949 new_command("REALPATH", 0, 1, realpath_command, _(
4950 "REALPATH [--inquire] [!]element[<TAB>[!]child[..]]\n"
4951 "Resolves all @code{target} attributes of the specified element path and "
4952 "returns the result with a data response. @xref{Target Attribute}, for details."
4953 "\n"
4954 "When the @option{--inquire} option is passed then all remaining non-option "
4955 "arguments are retrieved via a server @emph{INQUIRE}."
4958 new_command("STORE", 0, 1, store_command, _(
4959 "STORE [!]element[<TAB>[!]child[..]]<TAB>[content]\n"
4960 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
4961 "\n"
4962 "Creates a new element path or modifies the @var{content} of an existing "
4963 "element. If only a single element is specified then a new root element is "
4964 "created. Otherwise, elements are @key{TAB} delimited and the content will be "
4965 "set to the final @key{TAB} delimited element. If no @var{content} is "
4966 "specified after the final @key{TAB}, then the content of an existing "
4967 "element will be removed; or empty when creating a new element."
4968 "\n"
4969 "The only restriction of an element name is that it not contain whitespace "
4970 "or begin with the literal element character @code{!} unless specifying a "
4971 "literal element (@pxref{Target Attribute}). There is no whitespace between "
4972 "the @key{TAB} delimited elements. It is recommended that the content of an "
4973 "element be base64 encoded when it contains control or @key{TAB} characters "
4974 "to prevent @abbr{XML} parsing and @command{pwmd} syntax errors."
4977 new_command("RENAME", 0, 1, rename_command, _(
4978 "RENAME [--inquire] [!]element[<TAB>[!]child[..]] <value>\n"
4979 "Renames the specified @var{element} to the new @var{value}. If an element of "
4980 "the same name as the @var{value} already exists it will be overwritten."
4981 "\n"
4982 "When the @option{--inquire} option is passed then all remaining non-option "
4983 "arguments are retrieved via a server @emph{INQUIRE}."
4986 new_command("COPY", 0, 1, copy_command, _(
4987 "COPY [--inquire] [!]source[<TAB>[!]child[..]] [!]dest[<TAB>[!]child[..]]\n"
4988 "Copies the entire element tree starting from the child node of the source "
4989 "element, to the destination element path. If the destination element path "
4990 "does not exist then it will be created; otherwise it is overwritten."
4991 "\n"
4992 "Note that attributes from the source element are merged into the "
4993 "destination element when the destination element path exists. When an "
4994 "attribute of the same name exists in both the source and destination "
4995 "elements then the destination attribute will be updated to the source "
4996 "attribute value."
4997 "\n"
4998 "When the @option{--inquire} option is passed then all remaining non-option "
4999 "arguments are retrieved via a server @emph{INQUIRE}."
5002 new_command("MOVE", 0, 1, move_command, _(
5003 "MOVE [--inquire] [!]source[<TAB>[!]child[..]] [[!]dest[<TAB>[!]child[..]]]\n"
5004 "Moves the source element path to the destination element path. If the "
5005 "destination is not specified then it will be moved to the root node of the "
5006 "document. If the destination is specified and exists then it will be "
5007 "overwritten; otherwise non-existing elements of the destination element "
5008 "path will be created."
5009 "\n"
5010 "When the @option{--inquire} option is passed then all remaining non-option "
5011 "arguments are retrieved via a server @emph{INQUIRE}."
5014 new_command("DELETE", 0, 1, delete_command, _(
5015 "DELETE [--inquire] [!]element[<TAB>[!]child[..]]\n"
5016 "Removes the specified element path and all of its children. This may break "
5017 "an element with a @code{target} attribute (@pxref{Target Attribute}) that "
5018 "refers to this element or any of its children."
5019 "\n"
5020 "When the @option{--inquire} option is passed then all remaining non-option "
5021 "arguments are retrieved via a server @emph{INQUIRE}."
5024 new_command("GET", 0, 1, get_command, _(
5025 "GET [--inquire] [!]element[<TAB>[!]child[..]]\n"
5026 "Retrieves the content of the specified element. The content is returned "
5027 "with a data response."
5028 "\n"
5029 "When the @option{--inquire} option is passed then all remaining non-option "
5030 "arguments are retrieved via a server @emph{INQUIRE}."
5033 new_command("ATTR", 0, 1, attr_command, _(
5034 "ATTR [--inquire] SET|GET|DELETE|LIST [<attribute>] [!]element[<TAB>[!]child[..]] ..\n"
5035 "@table @asis\n"
5036 "@item ATTR SET attribute [!]element[<TAB>[!]child[..]] [value]\n"
5037 "\n"
5038 " Stores or updates an @var{attribute} name and optional @var{value} of an "
5039 "element. When no @var{value} is specified any existing value will be removed."
5040 "\n"
5041 "@item ATTR DELETE attribute [!]element[<TAB>[!]child[..]]\n"
5042 "\n"
5043 " Removes an @var{attribute} from an element."
5044 "\n"
5045 "@item ATTR LIST [!]element[<TAB>[!]child[..]]\n"
5046 "\n"
5047 " Retrieves a newline separated list of attributes names and values "
5048 "from the specified element. Each attribute name and value is space delimited."
5049 "\n"
5050 "@item ATTR GET attribute [!]element[<TAB>[!]child[..]]\n"
5051 "\n"
5052 " Retrieves the value of an @var{attribute} from an element."
5053 "@end table\n"
5054 "\n"
5055 "The @code{_name} attribute (case sensitive) cannot be removed nor modified. "
5056 "Use the @code{DELETE} (@pxref{DELETE}) or @code{RENAME} (@pxref{RENAME}) "
5057 "commands instead."
5058 "\n"
5059 "The @code{_mtime} attribute is updated each time an element is modified by "
5060 "either storing content, editing attributes or by deleting a child element. "
5061 "The @code{_ctime} attribute is created for each new element in an element "
5062 "path."
5063 "\n"
5064 "When the @option{--inquire} option is passed then all remaining non-option "
5065 "arguments are retrieved via a server @emph{INQUIRE}."
5066 "\n"
5067 "@xref{Target Attribute}, for details about this special attribute."
5070 new_command("XPATH", 0, 1, xpath_command, _(
5071 "XPATH [--inquire] <expression>[<TAB>[value]]\n"
5072 "Evaluates an XPath @var{expression}. If no @var{value} argument is "
5073 "specified it is assumed the expression is a request to return a result. "
5074 "Otherwise, the result is set to the @var{value} argument and the document is "
5075 "updated. If there is no @var{value} after the @key{TAB} character, the value "
5076 "is assumed to be empty and the document is updated. For example:"
5077 "@sp 1\n"
5078 "@example\n"
5079 "XPATH //element[@@_name='password']@key{TAB}\n"
5080 "@end example\n"
5081 "@sp 1"
5082 "would clear the content of all @code{password} elements in the data file "
5083 "while leaving off the trailing @key{TAB} would return all @code{password} "
5084 "elements in @abbr{XML} format."
5085 "\n"
5086 "When the @option{--inquire} option is passed then all remaining non-option "
5087 "arguments are retrieved via a server @emph{INQUIRE}."
5088 "\n"
5089 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
5090 "expression syntax."
5093 new_command("XPATHATTR", 0, 1, xpathattr_command, _(
5094 "XPATHATTR [--inquire] SET|DELETE <name> <expression>[<TAB>[<value>]]\n"
5095 "Like the @code{XPATH} command (@pxref{XPATH}) but operates on element "
5096 "attributes and does not return a result. For the @var{SET} operation the "
5097 "@var{value} is optional but the field is required. If not specified then "
5098 "the attribute value will be empty. For example:"
5099 "@sp 1"
5100 "@example\n"
5101 "XPATHATTR SET password //element[@@_name='password']@key{TAB}\n"
5102 "@end example\n"
5103 "@sp 1"
5104 "would create an @code{password} attribute for each @code{password} element "
5105 "found in the document. The attribute value will be empty but still exist."
5106 "\n"
5107 "When the @option{--inquire} option is passed then all remaining non-option "
5108 "arguments are retrieved via a server @emph{INQUIRE}."
5109 "\n"
5110 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
5111 "expression syntax."
5114 new_command("IMPORT", 0, 1, import_command, _(
5115 "IMPORT [--root [!]element[<TAB>[!]child[..]]] <content>\n"
5116 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
5117 "\n"
5118 "Like the @code{STORE} command (@pxref{STORE}), but the @var{content} "
5119 "argument is raw @abbr{XML} data. The content is created as a child of "
5120 "the element path specified with the @option{--root} option or at the "
5121 "document root when not specified. Existing elements of the same name will "
5122 "be overwritten."
5123 "\n"
5124 "The content must begin with an @abbr{XML} element node. @xref{Introduction}, "
5125 "for details."
5128 new_command("DUMP", 0, 1, dump_command, _(
5129 "DUMP\n"
5130 "Shows the in memory @abbr{XML} document with indenting. @xref{XPATH}, for "
5131 "dumping a specific node."
5134 new_command("LOCK", 0, 0, lock_command, _(
5135 "LOCK\n"
5136 "Locks the mutex associated with the opened file. This prevents other clients "
5137 "from sending commands to the same opened file until the client "
5138 "that sent this command either disconnects or sends the @code{UNLOCK} "
5139 "command. @xref{UNLOCK}."
5142 new_command("UNLOCK", 1, 0, unlock_command, _(
5143 "UNLOCK\n"
5144 "Unlocks the file mutex which was locked with the @code{LOCK} command or "
5145 "a commands' @option{--lock} option (@pxref{LOCK}, @pxref{OPEN}, "
5146 "@pxref{ISCACHED})."
5149 new_command("GETCONFIG", 1, 1, getconfig_command, _(
5150 "GETCONFIG [filename] <parameter>\n"
5151 "Returns the value of a @command{pwmd} configuration @var{parameter} with a "
5152 "data response. If no file has been opened then the value for @var{filename} "
5153 "or the default from the @samp{global} section will be returned. If a file "
5154 "has been opened and no @var{filename} is specified, a value previously "
5155 "set with the @code{OPTION} command (@pxref{OPTION}) will be returned."
5158 new_command("OPTION", 1, 1, option_command, _(
5159 "OPTION <NAME>=<VALUE>\n"
5160 "Sets a client option @var{name} to @var{value}. The value for an option is "
5161 "kept for the duration of the connection."
5162 "\n"
5163 "@table @asis\n"
5164 "@item DISABLE-PINENTRY\n"
5165 "Disable use of @command{pinentry} for passphrase retrieval. When set, a "
5166 "server inquire is sent to the client to obtain the passphrase. This option "
5167 "may be set as needed before the @code{OPEN} (@pxref{OPEN}), @code{PASSWD} "
5168 "(@pxref{PASSWD}) and @code{SAVE} (@pxref{SAVE}) commands."
5169 "\n"
5170 "@item PINENTRY-TIMEOUT\n"
5171 "Sets the number of seconds before a pinentry prompt will return an error "
5172 "while waiting for user input."
5173 "\n"
5174 "@item TTYNAME\n"
5175 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
5176 "\n"
5177 "@item TTYTYPE\n"
5178 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
5179 "\n"
5180 "@item DISPLAY\n"
5181 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
5182 "\n"
5183 "@item PINENTRY-DESC\n"
5184 "Sets the description string of the @command{gpg-agent} and @command{pinentry} dialog."
5185 "\n"
5186 "@item PINENTRY-TITLE\n"
5187 "Sets the title string of the @command{gpg-agent} and @command{pinentry} dialog."
5188 "\n"
5189 "@item PINENTRY-PROMPT\n"
5190 "Sets the prompt string of the @command{gpg-agent} and @command{pinentry} dialog."
5191 "\n"
5192 "@item LC-CTYPE\n"
5193 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
5194 "\n"
5195 "@item LC-MESSAGES\n"
5196 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
5197 "\n"
5198 "@item NAME\n"
5199 "Associates the thread ID of the connection with the specified textual "
5200 "representation. Useful for debugging log messages. May not contain whitespace."
5201 "\n"
5202 "@item LOCK-TIMEOUT\n"
5203 "When not @code{0}, the duration in tenths of a second to wait for the file "
5204 "mutex which has been locked by another thread to be released before returning "
5205 "an error. When @code{-1}, then an error will be returned immediately."
5206 "\n"
5207 "@item LOG-LEVEL\n"
5208 "An integer specifiying the logging level."
5209 "@end table\n"
5212 new_command("LS", 1, 1, ls_command, _(
5213 "LS\n"
5214 "Lists the available data files stored in the data directory "
5215 "(@file{~/.pwmd/data}). The result is a newline separated list of filenames."
5218 new_command("RESET", 1, 1, NULL, _(
5219 "RESET\n"
5220 "Closes the currently opened file but keeps any previously set client options."
5223 new_command("NOP", 1, 1, NULL, _(
5224 "NOP\n"
5225 "Does nothing. Always returns successfully."
5228 /* !END-HELP-TEXT! */
5229 new_command ("CANCEL", 1, 1, NULL, NULL);
5230 new_command ("END", 1, 1, NULL, NULL);
5231 new_command ("BYE", 1, 1, NULL, NULL);
5233 int i;
5234 for (i = 0; command_table[i]; i++);
5235 qsort (command_table, i - 1, sizeof (struct command_table_s *),
5236 sort_commands);
5239 gpg_error_t
5240 register_commands (assuan_context_t ctx)
5242 int i = 0, rc;
5244 for (; command_table[i]; i++)
5246 if (!command_table[i]->handler)
5247 continue;
5249 rc = assuan_register_command (ctx, command_table[i]->name,
5250 command_table[i]->handler,
5251 command_table[i]->help);
5252 if (rc)
5253 return rc;
5256 rc = assuan_register_bye_notify (ctx, bye_notify);
5257 if (rc)
5258 return rc;
5260 rc = assuan_register_reset_notify (ctx, reset_notify);
5261 if (rc)
5262 return rc;
5264 rc = assuan_register_pre_cmd_notify (ctx, command_startup);
5265 if (rc)
5266 return rc;
5268 return assuan_register_post_cmd_notify (ctx, command_finalize);