Release the data file mutex during data transfer.
[pwmd.git] / src / commands.c
blob56e54e0960818065cf2ff25e4cebe0b8231495ed
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 #ifdef WITH_LIBACL
38 #include <sys/acl.h>
39 #endif
41 #include "pwmd-error.h"
42 #include <gcrypt.h>
44 #include "mem.h"
45 #include "xml.h"
46 #include "util-misc.h"
47 #include "common.h"
48 #include "rcfile.h"
49 #include "cache.h"
50 #include "commands.h"
51 #include "mutex.h"
52 #include "crypto.h"
53 #include "pinentry.h"
55 /* These are command option flags. */
56 #define OPT_INQUIRE 0x0001
57 #define OPT_NO_PASSPHRASE 0x0002
58 #define OPT_RESET 0x0004
59 #define OPT_LIST_RECURSE 0x0008
60 #define OPT_VERBOSE 0x0010
61 #define OPT_LOCK 0x0020
62 #define OPT_LOCK_ON_OPEN 0x0040
63 #define OPT_SIGN 0x0080
64 #define OPT_LIST_ALL 0x0100
65 #define OPT_LIST_WITH_TARGET 0x0200
66 #define OPT_DATA 0x0400
67 #define OPT_NO_AGENT 0x0800
68 #define OPT_ASK 0x1000
70 #ifdef WITH_AGENT
71 /* The GETCONFIG command, for example, may fail because pwmd lost the
72 * gpg-agent connection. Update the recovered agent ctx. */
73 #define UPDATE_AGENT_CTX(client, crypto) do { \
74 if (crypto && crypto->agent && crypto->agent->did_restart \
75 && client->crypto && client->crypto->agent \
76 && client->crypto->agent->ctx && \
77 crypto->agent->ctx != client->crypto->agent->ctx) \
78 { \
79 client->crypto->agent->ctx = crypto->agent->ctx; \
80 crypto->agent->ctx = NULL; \
81 } \
82 } while (0)
83 #else
84 #define UPDATE_AGENT_CTX(client, crypto)
85 #endif
87 #define FLOCK_TYPE_NONE 0
88 #define FLOCK_TYPE_SH 0x0001
89 #define FLOCK_TYPE_EX 0x0002
90 #define FLOCK_TYPE_KEEP 0x0004
92 struct command_table_s
94 const char *name;
95 gpg_error_t (*handler) (assuan_context_t, char *line);
96 const char *help;
97 int ignore_startup;
98 int unlock; // unlock the file mutex after validating the checksum
99 uint32_t flock_type;
102 static struct command_table_s **command_table;
104 static gpg_error_t do_lock (struct client_s *client, int add);
105 static gpg_error_t validate_checksum (struct client_s *,
106 struct cache_data_s *);
107 static gpg_error_t update_checksum (struct client_s *client);
109 /* When 'status' is true the 'self' field of the status line will be false
110 * because we never send the STATE status message to the same client that
111 * initiated it. */
112 static char *
113 build_client_info_line (struct client_thread_s *thd, int status)
115 MUTEX_LOCK (&cn_mutex);
116 int with_state = config_get_boolean ("global", "send_state");
117 char *uid, *username = NULL;
118 char *line;
120 #ifdef WITH_GNUTLS
121 if (thd->remote)
122 uid = str_asprintf("#%s", thd->tls->fp);
123 else
125 uid = str_asprintf("%u", thd->peer->uid);
126 username = get_username (thd->peer->uid);
128 #else
129 uid = str_asprintf("%u", thd->peer->uid);
130 username = get_username (thd->peer->uid);
131 #endif
132 line = str_asprintf ("%p %s %s %s %u %u %u %s %s",
133 thd->tid,
134 thd->name ? thd->name : "-",
135 thd->cl && thd->cl->filename
136 && (thd->cl->flags & FLAG_OPEN)
137 ? thd->cl->filename : "/",
138 #ifdef WITH_GNUTLS
139 thd->remote ? thd->peeraddr : "-",
140 #else
141 "-",
142 #endif
143 thd->cl && thd->cl->flags & FLAG_HAS_LOCK ? 1 : 0,
144 !status && pthread_equal (pthread_self (), thd->tid) ? 1 : 0,
145 with_state ? thd->state : CLIENT_STATE_UNKNOWN, uid,
146 #ifdef WITH_GNUTLS
147 thd->remote ? "" : username
148 #else
149 username
150 #endif
153 xfree (username);
154 xfree (uid);
155 MUTEX_UNLOCK (&cn_mutex);
156 return line;
159 void
160 update_client_state (struct client_s *client, unsigned s)
162 client->thd->state = s;
163 int n = config_get_boolean ("global", "send_state");
165 if (n && client->thd->state != CLIENT_STATE_UNKNOWN)
167 char *line = build_client_info_line (client->thd, 1);
169 if (line)
170 send_status_all_not_self (n == 2, STATUS_STATE, "%s", line);
174 static gpg_error_t
175 unlock_file_mutex (struct client_s *client, int remove)
177 gpg_error_t rc = 0;
179 // OPEN: keep the lock for the same file being reopened.
180 if (client->flags & FLAG_KEEP_LOCK && client->flags & FLAG_HAS_LOCK)
181 return 0;
183 if (!(client->flags & FLAG_HAS_LOCK))
184 return GPG_ERR_NOT_LOCKED;
186 rc = cache_unlock_mutex (client->md5file, remove);
187 if (rc)
188 rc = GPG_ERR_INV_STATE;
189 else
190 client->flags &= ~(FLAG_HAS_LOCK | FLAG_LOCK_CMD);
192 return rc;
195 static gpg_error_t
196 lock_file_mutex (struct client_s *client, int add)
198 gpg_error_t rc = 0;
199 int timeout = config_get_integer (client->filename, "cache_timeout");
201 if (client->flags & FLAG_HAS_LOCK)
202 return 0;
204 rc = cache_lock_mutex (client->ctx, client->md5file,
205 client->lock_timeout, add, timeout);
206 if (!rc)
207 client->flags |= FLAG_HAS_LOCK;
209 return rc;
212 static gpg_error_t
213 file_modified (struct client_s *client, struct command_table_s *cmd)
215 gpg_error_t rc = 0;
216 int type = !cmd->flock_type || (cmd->flock_type & FLOCK_TYPE_SH)
217 ? LOCK_SH : LOCK_EX;
219 if (!(client->flags & FLAG_OPEN))
220 return GPG_ERR_INV_STATE;
222 rc = lock_file_mutex (client, 0);
223 if (rc && rc != GPG_ERR_NO_DATA)
224 return rc;
226 rc = lock_flock (client->ctx, client->filename, type, &client->flock_fd);
227 if (!rc)
229 rc = validate_checksum (client, NULL);
230 if (gpg_err_code (rc) == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
231 rc = 0;
232 else if (rc)
233 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
235 else if (gpg_err_code(rc) == GPG_ERR_ENOENT)
236 rc = 0;
238 if ((cmd->unlock && !(client->flags & FLAG_HAS_LOCK)) || rc)
239 unlock_file_mutex (client, 0);
241 if (rc || !(cmd->flock_type & FLOCK_TYPE_KEEP))
242 unlock_flock (&client->flock_fd);
244 return rc;
247 static gpg_error_t
248 parse_xml (assuan_context_t ctx, int new)
250 struct client_s *client = assuan_get_pointer (ctx);
251 int cached = client->doc != NULL;
252 gpg_error_t rc = 0;
254 if (new)
256 client->doc = new_document ();
257 if (client->doc)
259 xmlChar *result;
260 int len;
262 xmlDocDumpFormatMemory (client->doc, &result, &len, 0);
263 client->crypto->plaintext = result;
264 client->crypto->plaintext_len = len;
265 if (!client->crypto->plaintext)
267 xmlFreeDoc (client->doc);
268 client->doc = NULL;
269 rc = GPG_ERR_ENOMEM;
272 else
273 rc = GPG_ERR_ENOMEM;
275 else if (!cached)
276 rc = parse_doc ((char *) client->crypto->plaintext,
277 client->crypto->plaintext_len, (xmlDocPtr *)&client->doc);
279 return rc;
282 static void
283 free_client (struct client_s *client)
285 if (client->doc)
286 xmlFreeDoc (client->doc);
288 xfree (client->crc);
289 xfree (client->filename);
290 xfree (client->last_error);
292 if (client->crypto)
294 cleanup_crypto_stage2 (client->crypto);
295 if (client->crypto->pkey_sexp)
296 gcry_sexp_release (client->crypto->pkey_sexp);
298 if (client->crypto->sigpkey_sexp)
299 gcry_sexp_release (client->crypto->sigpkey_sexp);
301 client->crypto->pkey_sexp = NULL;
302 client->crypto->sigpkey_sexp = NULL;
303 memset (client->crypto->sign_grip, 0,
304 sizeof (client->crypto->sign_grip));
305 memset (client->crypto->grip, 0, sizeof(client->crypto->grip));
309 void
310 cleanup_client (struct client_s *client)
312 assuan_context_t ctx = client->ctx;
313 struct client_thread_s *thd = client->thd;
314 struct crypto_s *crypto = client->crypto;
315 long lock_timeout = client->lock_timeout;
316 int no_pinentry = (client->flags & FLAG_NO_PINENTRY);
317 struct pinentry_option_s pin_opts;
318 xmlErrorPtr xml_error = client->xml_error;
319 int flock_fd = client->flock_fd;
320 #ifdef WITH_AGENT
321 struct pinentry_option_s agent_pin_opts;
323 if (crypto && crypto->agent)
324 memcpy (&agent_pin_opts, &crypto->agent->pinentry_opts,
325 sizeof(struct pinentry_option_s));
326 #endif
328 memcpy (&pin_opts, &client->pinentry_opts, sizeof(struct pinentry_option_s));
329 unlock_file_mutex (client, client->flags & FLAG_NEW);
330 free_client (client);
331 memset (client, 0, sizeof (struct client_s));
332 client->flock_fd = flock_fd;
333 client->xml_error = xml_error;
334 client->crypto = crypto;
335 client->ctx = ctx;
336 client->thd = thd;
337 client->lock_timeout = lock_timeout;
338 memcpy (&client->pinentry_opts, &pin_opts, sizeof(struct pinentry_option_s));
339 client->flags |= no_pinentry ? FLAG_NO_PINENTRY : 0;
340 #ifdef WITH_AGENT
341 if (crypto && crypto->agent)
342 memcpy (&crypto->agent->pinentry_opts, &agent_pin_opts,
343 sizeof(struct pinentry_option_s));
344 #endif
347 static gpg_error_t
348 open_finalize (assuan_context_t ctx, char *key, size_t keylen)
350 struct client_s *client = assuan_get_pointer (ctx);
351 gpg_error_t rc = 0;
352 struct cache_data_s *cdata = cache_get_data (client->md5file);
353 int cached = 0, keyarg = key ? 1 : 0;
354 size_t keysize;
355 unsigned char *salted_key = NULL;
356 int algo;
357 int pin_try = 1;
358 int pin_tries = 3;
359 char *pin_title = client->pinentry_opts.title;
361 client->crypto->filename = str_dup (client->filename);
362 if (cdata || client->flags & FLAG_NEW)
364 if (cdata && !(client->flags & FLAG_NEW))
366 rc = decrypt_cache (client->crypto, cdata->doc, cdata->doclen);
367 if (rc)
368 return rc;
371 cached = cdata != NULL;
372 goto done;
375 if (!key && !IS_PKI (client->crypto)
376 && !(client->crypto->hdr.flags & PWMD_FLAG_NO_PASSPHRASE))
378 if (client->flags & FLAG_NO_PINENTRY)
380 rc = inquire_passphrase (ctx, "PASSPHRASE", (unsigned char **)&key,
381 &keylen);
382 if (rc)
383 return rc;
385 else
387 client->pinentry_opts.timeout = config_get_integer (client->filename,
388 "pinentry_timeout");
389 pin_again:
390 rc = getpin_common (client->ctx, client->filename, PINENTRY_OPEN,
391 &key, &keylen);
392 if (rc)
393 return rc;
397 if (!IS_PKI (client->crypto))
399 if (client->crypto->hdr.flags & PWMD_FLAG_NO_PASSPHRASE)
401 keylen = 1;
402 key = gcry_malloc (keylen);
403 memset (key, 0, keylen);
406 algo = cipher_to_gcrypt (client->crypto->hdr.flags);
407 rc = hash_key (algo, client->crypto->hdr.salt,
408 sizeof(client->crypto->hdr.salt), key, keylen,
409 (void **)&salted_key, &keysize,
410 client->crypto->hdr.version <= 0x03000e ? COMPAT_KDFS2K_ITERATIONS : client->crypto->hdr.s2k_count);
411 if (!keyarg)
412 gcry_free (key);
414 if (!rc)
416 rc = decrypt_data (client->ctx, client->crypto, salted_key, keysize);
417 if (gpg_err_code (rc) == GPG_ERR_BAD_PASSPHRASE
418 && ++pin_try <= pin_tries && !(client->flags & FLAG_NO_PINENTRY))
420 gcry_free (salted_key);
421 salted_key = NULL;
422 key = NULL;
423 keylen = 0;
424 client->pinentry_opts.title = str_asprintf (_ ("Bad passphrase (try %i of %i)"), pin_try, pin_tries);
425 goto pin_again;
429 if (client->pinentry_opts.title != pin_title)
430 xfree (client->pinentry_opts.title);
432 client->pinentry_opts.title = pin_title;
433 if (rc)
435 gcry_free (salted_key);
436 return rc;
439 cdata = xcalloc (1, sizeof (struct cache_data_s));
440 if (!cdata)
442 gcry_free (salted_key);
443 return GPG_ERR_ENOMEM;
446 cdata->key = salted_key;
447 cdata->keylen = keysize;
449 else
450 #ifdef WITH_AGENT
451 rc = decrypt_data (client->ctx, client->crypto, NULL, 0);
452 #else
453 rc = GPG_ERR_NOT_IMPLEMENTED;
454 #endif
456 done:
457 if (!rc)
459 rc = parse_xml (ctx, client->flags & FLAG_NEW);
460 if (rc && !cached)
461 free_cache_data_once (cdata);
463 if (!rc)
465 int timeout = config_get_integer (client->filename,
466 "cache_timeout");
468 if (!cached)
470 if (!cdata)
471 cdata = xcalloc (1, sizeof (struct cache_data_s));
473 rc = encrypt_xml (NULL, cache_key, cache_keysize,
474 GCRY_CIPHER_AES, client->crypto->plaintext,
475 client->crypto->plaintext_len, &cdata->doc,
476 &cdata->doclen, &cache_iv, &cache_blocksize);
477 if (!rc && !(client->flags & FLAG_NEW) && IS_PKI (client->crypto))
479 rc = gcry_sexp_build ((gcry_sexp_t *) & cdata->pubkey, NULL,
480 "%S", client->crypto->pkey_sexp);
484 if (cdata->sigkey)
485 gcry_sexp_release (cdata->sigkey);
487 cdata->sigkey = NULL;
488 if (!rc && IS_PKI (client->crypto))
489 rc = gcry_sexp_build ((gcry_sexp_t *) &cdata->sigkey, NULL,
490 "%S", client->crypto->sigpkey_sexp);
492 if (!rc)
494 rc = cache_add_file (client->md5file,
495 (client->flags & FLAG_NEW) ? NULL
496 : client->crypto->grip, cdata, timeout);
497 if (rc)
499 if (!cached)
501 free_cache_data_once (cdata);
502 xmlFreeDoc (client->doc);
503 client->doc = NULL;
508 if (!rc)
509 client->flags |= FLAG_OPEN;
513 if (!rc)
515 rc = update_checksum (client);
516 if (gpg_err_code (rc) == GPG_ERR_ENOENT)
517 rc = 0;
520 if (!rc && (client->opts & OPT_LOCK_ON_OPEN))
521 rc = do_lock (client, 0);
523 return rc;
526 static void
527 req_cleanup (void *arg)
529 if (!arg)
530 return;
532 strv_free ((char **) arg);
535 static gpg_error_t
536 parse_open_opt_lock (void *data, void *value)
538 struct client_s *client = data;
540 client->opts |= OPT_LOCK_ON_OPEN;
541 return 0;
544 static gpg_error_t
545 parse_save_opt_inquire (void *data, void *value)
547 struct client_s *client = data;
548 gpg_error_t rc;
550 if (!(client->flags & FLAG_NEW))
552 rc = peer_is_invoker (client);
553 if (rc == GPG_ERR_EACCES)
554 return rc;
557 (void) value;
558 client->opts |= OPT_INQUIRE;
559 return 0;
562 static gpg_error_t
563 parse_opt_inquire (void *data, void *value)
565 struct client_s *client = data;
567 (void) value;
568 client->opts |= OPT_INQUIRE;
569 return 0;
572 static gpg_error_t
573 update_checksum (struct client_s *client)
575 unsigned char *crc;
576 size_t len;
577 struct cache_data_s *cdata;
578 gpg_error_t rc = get_checksum (client->filename, &crc, &len);
580 if (rc)
581 return rc;
583 xfree (client->crc);
584 client->crc = crc;
585 cdata = cache_get_data (client->md5file);
586 if (cdata)
588 xfree (cdata->crc);
589 cdata->crc = xmalloc (len);
590 memcpy (cdata->crc, crc, len);
593 return 0;
596 static gpg_error_t
597 validate_checksum (struct client_s *client, struct cache_data_s *cdata)
599 unsigned char *crc;
600 size_t len;
601 gpg_error_t rc;
602 int n = 0;
604 if (cdata && !cdata->crc)
605 return GPG_ERR_CHECKSUM;
607 rc = get_checksum (client->filename, &crc, &len);
608 if (rc)
609 return rc;
611 if (cdata)
612 n = memcmp (cdata->crc, crc, len);
613 else if (client->crc)
614 n = memcmp (client->crc, crc, len);
616 xfree (crc);
617 return n ? GPG_ERR_CHECKSUM : 0;
620 static gpg_error_t
621 do_open (assuan_context_t ctx, const char *password)
623 struct client_s *client = assuan_get_pointer (ctx);
624 struct cache_data_s *cdata;
625 gpg_error_t rc = 0;
626 int done = 0;
628 // Cached document?
629 cdata = cache_get_data (client->md5file);
630 if (cdata && cdata->doc)
632 int defer = 0;
634 /* This will check that the key is cached in the agent which needs to
635 * be determined for files that share a keygrip. */
636 if (!rc)
638 rc = cache_iscached (client->filename, &defer);
639 if ((!rc || rc == GPG_ERR_ENOENT) && defer)
640 rc = GPG_ERR_KEY_EXPIRED;
643 if (!rc && !(client->flags & FLAG_NEW))
644 rc = validate_checksum (client, cdata);
646 #ifdef WITH_GNUTLS
647 if (!rc && client->thd->remote
648 && config_get_boolean (client->filename, "tcp_require_key"))
649 rc = GPG_ERR_KEY_EXPIRED;
650 #endif
652 if (!rc && !password)
654 rc = read_data_header (client->filename, &client->crypto->hdr,
655 NULL, NULL);
656 if (!rc)
658 if (IS_PKI (client->crypto))
660 gcry_sexp_build (&client->crypto->pkey_sexp, NULL, "%S",
661 cdata->pubkey);
662 gcry_pk_get_keygrip (client->crypto->pkey_sexp,
663 client->crypto->grip);
664 gcry_sexp_build (&client->crypto->sigpkey_sexp, NULL, "%S",
665 cdata->sigkey);
666 gcry_pk_get_keygrip (client->crypto->sigpkey_sexp,
667 client->crypto->sign_grip);
670 if (!rc)
672 rc = open_finalize (ctx, NULL, 0);
673 done = 1;
678 /* There was an error accessing the file so clear the cache entry. The
679 * real error will be returned from read_data_file() since the file
680 * may have only disappeared. */
681 if (!done)
683 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
684 rc = cache_clear (client->md5file);
685 send_status_all (STATUS_CACHE, NULL);
689 if (done || rc)
690 return rc;
692 rc = read_data_file (client->filename, client->crypto);
693 if (rc)
695 if (gpg_err_source (rc) != GPG_ERR_SOURCE_DEFAULT ||
696 gpg_err_code (rc) != GPG_ERR_ENOENT)
698 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
699 return rc;
702 client->flags |= FLAG_NEW;
703 memset (client->crypto->grip, 0, sizeof (client->crypto->grip));
704 memset (client->crypto->sign_grip, 0,
705 sizeof (client->crypto->sign_grip));
706 rc = open_finalize (ctx, NULL, 0);
707 return rc;
710 if (password && IS_PKI (client->crypto))
712 #ifdef WITH_AGENT
713 rc = set_agent_passphrase (client->crypto, password, strlen (password));
714 if (rc)
715 return rc;
716 #endif
719 rc = open_finalize (ctx, (char *)password, password ? strlen (password) : 0);
720 return rc;
723 static gpg_error_t
724 open_command (assuan_context_t ctx, char *line)
726 gpg_error_t rc;
727 struct client_s *client = assuan_get_pointer (ctx);
728 char **req, *filename;
729 unsigned char md5file[16];
730 int same_file = 0;
731 assuan_peercred_t peer;
732 struct argv_s *args[] = {
733 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_open_opt_lock},
734 NULL
737 rc = parse_options (&line, args, client, 1);
738 if (rc)
739 return send_error (ctx, rc);
741 req = str_split (line, " ", 2);
742 if (!req)
743 return send_error (ctx, GPG_ERR_SYNTAX);
745 rc = do_validate_peer (ctx, req[0], &peer);
746 if (rc)
748 strv_free (req);
749 return send_error (ctx, rc);
752 filename = req[0];
753 if (!valid_filename (filename))
755 strv_free (req);
756 return send_error (ctx, GPG_ERR_INV_VALUE);
759 pthread_cleanup_push (req_cleanup, req);
760 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
761 /* This client may have locked a different file with ISCACHED --lock than
762 * the current filename. This will remove that lock. */
763 same_file = !memcmp (md5file, client->md5file, 16) ? 1 : 0;
764 if (client->flags & FLAG_OPEN ||
765 (client->flags & FLAG_HAS_LOCK && !same_file))
767 uint32_t opts = client->opts;
768 uint32_t flags = client->flags;
770 if (same_file)
771 client->flags |= FLAG_KEEP_LOCK;
772 else if (client->flags & FLAG_NEW)
773 cache_clear (client->md5file);
775 cleanup_client (client);
776 client->opts = opts;
777 client->flags |= flags;
778 client->flags &= ~(FLAG_LOCK_CMD);
779 if (!same_file)
780 client->flags &= ~(FLAG_HAS_LOCK | FLAG_NEW);
783 /* Need to lock the mutex here because file_modified() cannot without
784 * knowing the filename. */
785 memcpy (client->md5file, md5file, 16);
786 rc = lock_file_mutex (client, 1);
787 if (rc)
788 client->flags &= ~FLAG_OPEN;
790 if (!rc)
792 rc = lock_flock (ctx, filename, LOCK_SH, &client->flock_fd);
793 if (!rc || gpg_err_code (rc) == GPG_ERR_ENOENT)
795 rc = 0;
796 client->filename = str_dup (filename);
797 if (!client->filename)
798 rc = GPG_ERR_ENOMEM;
802 if (!rc)
804 char *password = req[1] && *req[1] ? req[1] : NULL;
806 #ifdef WITH_AGENT
807 if (IS_PKI (client->crypto))
808 rc = set_pinentry_mode (client->crypto->agent,
809 (client->flags & FLAG_NO_PINENTRY) ? "loopback"
810 : "ask");
811 #endif
812 if (!rc)
814 rc = do_open (ctx, password);
815 if (rc)
816 cleanup_client (client);
818 cleanup_crypto_stage1 (client->crypto);
822 pthread_cleanup_pop (1);
824 if (!rc && client->flags & FLAG_NEW)
825 rc = send_status (ctx, STATUS_NEWFILE, NULL);
827 #ifdef WITH_AGENT
828 (void) kill_scd (client->crypto->agent);
829 #endif
831 return send_error (ctx, rc);
834 static gpg_error_t
835 parse_opt_no_passphrase (void *data, void *value)
837 struct client_s *client = data;
839 (void) value;
840 client->opts |= OPT_NO_PASSPHRASE;
841 return 0;
844 static gpg_error_t
845 parse_save_opt_no_agent (void *data, void *value)
847 struct client_s *client = data;
849 client->opts |= OPT_NO_AGENT;
850 return 0;
853 static gpg_error_t
854 parse_save_opt_cipher (void *data, void *value)
856 struct client_s *client = data;
857 int algo = cipher_string_to_gcrypt ((char *) value);
858 file_header_t *hdr = &client->crypto->save.hdr;
859 gpg_error_t rc = 0;
861 if (algo == -1)
862 return GPG_ERR_INV_VALUE;
864 if (!(client->flags & FLAG_NEW))
866 rc = peer_is_invoker (client);
867 if (rc == GPG_ERR_EACCES)
869 uint64_t flags = 0;
871 flags &= ((uint16_t) ((uint32_t) (flags & 0xFFFFFFFF)));
872 if (!(client->crypto->hdr.flags & gcrypt_to_cipher (algo)))
873 return rc;
875 rc = 0;
877 else if (rc)
878 return rc;
881 if (!rc)
882 hdr->flags = set_cipher_flag (hdr->flags, algo);
884 return rc;
887 #ifdef WITH_AGENT
888 static gpg_error_t
889 permitted_to_save (struct client_s *client, const unsigned char *grip,
890 size_t size, const char *value)
892 char *hexgrip;
893 gpg_error_t rc = 0;
895 if (!(client->flags & FLAG_NEW))
897 hexgrip = bin2hex (grip, size);
898 rc = !strcmp (hexgrip, (char *)value) ? 0 : GPG_ERR_EACCES;
899 xfree (hexgrip);
900 if (rc)
901 rc = peer_is_invoker (client);
904 return rc;
906 #endif
908 static gpg_error_t
909 parse_save_opt_keygrip (void *data, void *value)
911 #ifdef WITH_AGENT
912 struct client_s *client = data;
913 gpg_error_t rc = permitted_to_save (client, client->crypto->grip,
914 sizeof (client->crypto->grip),
915 value);
917 if (!IS_PKI (client->crypto))
918 return GPG_ERR_INV_ARG;
920 if (rc)
921 return rc;
923 if (client->crypto->save.pkey)
924 gcry_sexp_release (client->crypto->save.pkey);
926 client->crypto->save.pkey = NULL;
927 return get_pubkey (client->crypto, value, &client->crypto->save.pkey);
928 #else
929 return GPG_ERR_INV_ARG;
930 #endif
933 static gpg_error_t
934 parse_save_opt_sign_keygrip (void *data, void *value)
936 #ifdef WITH_AGENT
937 struct client_s *client = data;
938 gpg_error_t rc = permitted_to_save (client, client->crypto->sign_grip,
939 sizeof (client->crypto->sign_grip),
940 value);
942 if (!IS_PKI (client->crypto))
943 return GPG_ERR_INV_ARG;
945 if (rc)
946 return rc;
948 if (client->crypto->save.sigpkey)
949 gcry_sexp_release (client->crypto->save.sigpkey);
951 client->crypto->save.sigpkey = NULL;
952 return get_pubkey (client->crypto, value, &client->crypto->save.sigpkey);
953 #else
954 return GPG_ERR_INV_ARG;
955 #endif
958 static gpg_error_t
959 parse_opt_s2k_count (void *data, void *value)
961 struct client_s *client = data;
962 char *v = value, *p;
963 uint64_t n;
965 if (!v || !*v)
966 return GPG_ERR_INV_VALUE;
968 errno = 0;
969 n = strtoull (v, &p, 10);
970 if (n == UINT64_MAX && errno)
971 return gpg_error_from_errno (errno);
972 else if (p && *p)
973 return GPG_ERR_INV_VALUE;
975 if (!(client->flags & FLAG_NEW))
977 gpg_error_t rc = peer_is_invoker (client);
979 if (rc == GPG_ERR_EACCES)
981 if (n && client->crypto->hdr.s2k_count != n)
982 return rc;
984 rc = 0;
986 else if (rc)
987 return rc;
990 // Keep compatibility with libpwmd passing --s2k-count=0. If somehow
991 // s2k_count == 0 it will be set to DEFAULT_KDFS2K_ITERATIONS in
992 // save_command().
993 if (n)
994 client->crypto->save.hdr.s2k_count = n;
996 return 0;
999 static gpg_error_t
1000 save_finalize (assuan_context_t ctx)
1002 struct client_s *client = assuan_get_pointer (ctx);
1003 gpg_error_t rc = 0;
1004 xmlChar *xmlbuf = NULL;
1005 int xmlbuflen;
1006 void *key = NULL;
1007 size_t keylen = 0;
1009 xmlDocDumpFormatMemory (client->doc, &xmlbuf, &xmlbuflen, 0);
1010 if (!xmlbuf)
1011 return GPG_ERR_ENOMEM;
1013 pthread_cleanup_push (xmlFree, xmlbuf);
1015 if (!use_agent || ((client->flags & FLAG_NEW)
1016 && (client->opts & OPT_NO_AGENT))
1017 || !(client->crypto->hdr.flags & PWMD_FLAG_PKI))
1019 rc = export_common (ctx, client->flags & FLAG_NO_PINENTRY,
1020 client->crypto, xmlbuf, xmlbuflen, client->filename,
1021 NULL, &key, &keylen, 1, 1,
1022 (client->opts & OPT_NO_PASSPHRASE));
1024 #ifdef WITH_AGENT
1025 else
1027 gcry_sexp_t pubkey = client->crypto->save.pkey;
1028 gcry_sexp_t sigkey = client->crypto->save.sigpkey;
1030 if (!pubkey)
1031 pubkey = client->crypto->pkey_sexp;
1033 if (!sigkey)
1035 sigkey = client->crypto->sigpkey_sexp;
1036 if (!sigkey)
1038 gcry_sexp_build (&client->crypto->save.sigpkey, 0, "%S", pubkey);
1039 sigkey = client->crypto->save.sigpkey;
1043 rc = encrypt_data_file (client->ctx, client->crypto, pubkey, sigkey,
1044 client->filename, xmlbuf, xmlbuflen);
1045 if (pubkey == client->crypto->save.pkey)
1047 if (!rc)
1049 gcry_sexp_release (client->crypto->pkey_sexp);
1050 client->crypto->pkey_sexp = client->crypto->save.pkey;
1051 gcry_pk_get_keygrip (client->crypto->pkey_sexp,
1052 client->crypto->grip);
1054 else
1055 gcry_sexp_release (pubkey);
1057 client->crypto->save.pkey = NULL;
1060 if (!rc)
1061 gcry_pk_get_keygrip (sigkey, client->crypto->sign_grip);
1063 if (sigkey == client->crypto->save.sigpkey)
1065 if (!rc)
1067 if (client->crypto->sigpkey_sexp)
1068 gcry_sexp_release (client->crypto->sigpkey_sexp);
1070 client->crypto->sigpkey_sexp = client->crypto->save.sigpkey;
1071 gcry_pk_get_keygrip (client->crypto->sigpkey_sexp,
1072 client->crypto->sign_grip);
1074 else
1075 gcry_sexp_release (sigkey);
1077 client->crypto->save.sigpkey = NULL;
1080 #endif
1082 if (!rc)
1084 int cached;
1086 rc = save_common (client->filename, client->crypto, xmlbuf, xmlbuflen,
1087 key, keylen, &cached, client->opts & OPT_NO_AGENT);
1088 gcry_free (key);
1090 if (!rc && (!cached || (client->flags & FLAG_NEW)))
1091 send_status_all (STATUS_CACHE, NULL);
1093 if (!rc)
1095 rc = update_checksum (client);
1096 client->flags &= ~(FLAG_NEW);
1100 pthread_cleanup_pop (1); // xmlFree
1101 return rc;
1104 static gpg_error_t
1105 parse_opt_reset (void *data, void *value)
1107 struct client_s *client = data;
1109 (void) value;
1110 client->opts |= OPT_RESET;
1111 return 0;
1114 static gpg_error_t
1115 parse_opt_ask (void *data, void *value)
1117 struct client_s *client = data;
1119 (void) value;
1120 client->opts |= OPT_ASK;
1121 return 0;
1124 static gpg_error_t
1125 save_command (assuan_context_t ctx, char *line)
1127 struct client_s *client = assuan_get_pointer (ctx);
1128 gpg_error_t rc;
1129 struct stat st;
1130 struct argv_s *args[] = {
1131 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG,
1132 parse_opt_no_passphrase},
1133 &(struct argv_s) {"cipher", OPTION_TYPE_ARG, parse_save_opt_cipher},
1134 &(struct argv_s) {"inquire-keyparam", OPTION_TYPE_NOARG,
1135 parse_save_opt_inquire},
1136 &(struct argv_s) {"keygrip", OPTION_TYPE_ARG, parse_save_opt_keygrip},
1137 &(struct argv_s) {"sign-keygrip", OPTION_TYPE_ARG,
1138 parse_save_opt_sign_keygrip},
1139 &(struct argv_s) {"s2k-count", OPTION_TYPE_ARG, parse_opt_s2k_count},
1140 &(struct argv_s) {"reset", OPTION_TYPE_NOARG, parse_opt_reset},
1141 &(struct argv_s) {"cipher-iterations", OPTION_TYPE_ARG,
1142 parse_opt_s2k_count},
1143 &(struct argv_s) {"no-agent", OPTION_TYPE_NOARG,
1144 parse_save_opt_no_agent},
1145 &(struct argv_s) {"ask", OPTION_TYPE_NOARG,
1146 parse_opt_ask},
1147 NULL
1150 cleanup_save (&client->crypto->save);
1151 memcpy (&client->crypto->save.hdr, &client->crypto->hdr,
1152 sizeof (file_header_t));
1154 rc = parse_options (&line, args, client, 0);
1155 if (rc)
1156 return send_error (ctx, rc);
1158 if (!(client->flags & FLAG_NEW))
1159 client->opts &= ~OPT_NO_AGENT;
1160 else if (client->opts & OPT_NO_AGENT)
1162 client->crypto->save.hdr.flags &= ~PWMD_FLAG_PKI;
1163 client->crypto->hdr.flags &= ~PWMD_FLAG_PKI;
1166 /* Update to the default hash iteration count for data file
1167 * versions <= 3.0.14. */
1168 #ifdef WITH_AGENT
1169 if ((!IS_PKI (client->crypto) && client->crypto->hdr.version <= 0x03000e
1170 && client->crypto->save.hdr.s2k_count < DEFAULT_KDFS2K_ITERATIONS)
1171 || (!IS_PKI (client->crypto) && !client->crypto->save.hdr.s2k_count))
1172 #else
1173 if ((client->crypto->hdr.version <= 0x03000e
1174 && client->crypto->save.hdr.s2k_count < DEFAULT_KDFS2K_ITERATIONS)
1175 || !client->crypto->save.hdr.s2k_count)
1176 #endif
1178 client->crypto->save.hdr.s2k_count =
1179 config_get_ulonglong (client->filename, "s2k_count");
1180 if (!client->crypto->save.hdr.s2k_count)
1181 client->crypto->save.hdr.s2k_count = DEFAULT_KDFS2K_ITERATIONS;
1184 /* Deal with the hashed vs non-hashed cached key mess by clearing the cached
1185 * key entry. */
1186 if (client->crypto->hdr.version <= 0x03000e && !IS_PKI (client->crypto))
1187 client->opts |= OPT_RESET;
1188 else if (!IS_PKI (client->crypto) && !(client->flags & FLAG_NEW)
1189 && client->crypto->hdr.s2k_count !=
1190 client->crypto->save.hdr.s2k_count)
1191 client->opts |= OPT_RESET;
1193 if ((client->opts & OPT_NO_PASSPHRASE) && !(client->flags & FLAG_NEW)
1194 && !(client->opts & OPT_INQUIRE))
1195 return send_error (ctx, GPG_ERR_WRONG_KEY_USAGE);
1197 if (lstat (client->filename, &st) == -1 && errno != ENOENT)
1198 return send_error (ctx, gpg_error_from_errno (errno));
1200 if (errno != ENOENT && !S_ISREG (st.st_mode))
1202 log_write ("%s: %s", client->filename, pwmd_strerror (GPG_ERR_ENOANO));
1203 return send_error (ctx, GPG_ERR_ENOANO);
1206 int defer = 0;
1207 rc = cache_iscached (client->filename, &defer);
1208 if (gpg_err_code (rc) == GPG_ERR_ENOENT && client->flags & FLAG_NEW)
1209 rc = 0;
1210 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
1211 rc = 0;
1213 if ((!rc && defer))
1214 client->opts |= OPT_RESET;
1215 else if (config_get_boolean ("global", "require_save_key"))
1216 client->opts |= OPT_ASK;
1218 if (!rc && (client->opts & OPT_RESET))
1220 rc = cache_clear (client->md5file);
1221 if (rc)
1222 return send_error (ctx, rc);
1224 log_write ("%s: %s", client->filename,
1225 pwmd_strerror (GPG_ERR_KEY_EXPIRED));
1226 send_status_all (STATUS_CACHE, NULL);
1229 if (!rc && client->opts & OPT_ASK)
1230 rc = crypto_try_decrypt (ctx, client->flags & FLAG_NO_PINENTRY,
1231 client->filename, NULL, NULL, NULL);
1233 if (!rc)
1234 rc = update_element_mtime (client, xmlDocGetRootElement (client->doc));
1236 if (rc)
1237 return send_error (ctx, rc);
1239 #ifdef WITH_AGENT
1240 if (!rc && use_agent && !client->crypto->save.pkey &&
1241 (client->flags & FLAG_NEW || client->opts & OPT_INQUIRE)
1242 && !(client->opts & OPT_NO_AGENT))
1244 rc = set_pinentry_mode (client->crypto->agent,
1245 (client->flags & FLAG_NO_PINENTRY) ? "loopback"
1246 : "ask");
1248 if (!(client->flags & FLAG_NEW))
1250 struct crypto_s *crypto;
1251 void *key = NULL;
1252 size_t keylen = 0;
1254 /* Wanting to generate a new key. Require the key to open the
1255 current file before proceeding reguardless of the
1256 require_save_key configuration parameter. */
1257 rc = cache_clear (client->md5file);
1258 if (!rc)
1260 rc = init_client_crypto (&crypto);
1261 if (!rc)
1262 crypto->client_ctx = client->ctx;
1265 if (!rc)
1266 rc = decrypt_common (client->ctx, client->opts&OPT_INQUIRE, crypto,
1267 client->filename, &key, &keylen, NULL, NULL);
1269 xfree (key);
1270 cleanup_crypto (&crypto);
1273 if (!rc)
1274 rc = send_status (client->ctx, STATUS_GENKEY, NULL);
1276 if (!rc)
1278 struct inquire_data_s idata = { 0 };
1279 char *params = client->opts & OPT_INQUIRE
1280 ? NULL : default_key_params (client->crypto);
1282 pthread_cleanup_push (xfree, params);
1283 idata.crypto = client->crypto;
1285 if (params)
1287 idata.line = params;
1288 idata.len = strlen (params);
1290 else
1291 idata.preset = 1;
1293 client->crypto->agent->inquire_data = &idata;
1294 client->crypto->agent->inquire_cb = NULL;
1295 rc = generate_key (client->crypto, params,
1296 (client->opts & OPT_NO_PASSPHRASE), 1);
1297 pthread_cleanup_pop (1);
1300 #endif
1302 if (!rc)
1303 rc = save_finalize (ctx);
1305 cleanup_crypto_stage1 (client->crypto);
1306 #ifdef WITH_AGENT
1307 (void) kill_scd (client->crypto->agent);
1308 #endif
1309 return send_error (ctx, rc);
1312 static gpg_error_t
1313 do_delete (assuan_context_t ctx, char *line)
1315 struct client_s *client = assuan_get_pointer (ctx);
1316 gpg_error_t rc;
1317 char **req;
1318 xmlNodePtr n;
1320 if (strchr (line, '\t'))
1321 req = str_split (line, "\t", 0);
1322 else
1323 req = str_split (line, " ", 0);
1325 if (!req || !*req)
1326 return GPG_ERR_SYNTAX;
1328 n = find_root_element (client, client->doc, &req, &rc, NULL, 0, 0);
1329 if (!n || rc)
1331 strv_free (req);
1332 return rc;
1336 * No sub-node defined. Remove the entire node (root element).
1338 if (!req[1])
1340 if (n)
1342 rc = is_element_owner (client, n);
1343 if (!rc)
1345 rc = unlink_node (client, n);
1346 xmlFreeNode (n);
1350 strv_free (req);
1351 return rc;
1354 n = find_elements (client, client->doc, n->children, req + 1, &rc, NULL,
1355 NULL, NULL, 0, 0, NULL, 0);
1356 strv_free (req);
1357 if (!n || rc)
1358 return rc;
1360 rc = is_element_owner (client, n);
1361 if (!rc)
1363 rc = unlink_node (client, n);
1364 xmlFreeNode (n);
1367 return rc;
1370 static gpg_error_t
1371 delete_command (assuan_context_t ctx, char *line)
1373 struct client_s *client = assuan_get_pointer (ctx);
1374 gpg_error_t rc;
1375 struct argv_s *args[] = {
1376 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1377 NULL
1380 rc = parse_options (&line, args, client, 1);
1381 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1382 rc = GPG_ERR_SYNTAX;
1383 if (rc)
1384 return send_error (ctx, rc);
1386 if (client->opts & OPT_INQUIRE)
1388 unsigned char *result;
1389 size_t len;
1391 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1392 if (rc)
1393 return send_error (ctx, rc);
1395 pthread_cleanup_push (xfree, result);
1396 rc = do_delete (ctx, (char *)result);
1397 pthread_cleanup_pop (1);
1399 else
1400 rc = do_delete (ctx, line);
1402 return send_error (ctx, rc);
1405 static gpg_error_t
1406 store_command (assuan_context_t ctx, char *line)
1408 struct client_s *client = assuan_get_pointer (ctx);
1409 gpg_error_t rc;
1410 size_t len;
1411 unsigned char *result;
1412 char **req;
1413 xmlNodePtr n, parent;
1414 int has_content;
1415 char *content = NULL;
1417 if (line && *line)
1418 return send_error (ctx, GPG_ERR_SYNTAX);
1420 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1421 if (rc)
1422 return send_error (ctx, rc);
1424 req = str_split ((char *) result, "\t", 0);
1425 xfree (result);
1427 if (!req || !*req)
1428 return send_error (ctx, GPG_ERR_SYNTAX);
1430 len = strv_length (req);
1431 has_content = line[strlen (line) - 1] != '\t' && len > 1;
1432 if (*(req + 1) && !valid_element_path (req, has_content))
1434 strv_free (req);
1435 return send_error (ctx, GPG_ERR_INV_VALUE);
1438 if (has_content || !*req[len - 1])
1440 has_content = 1;
1441 content = req[len - 1];
1442 req[len - 1] = NULL;
1445 again:
1446 n = find_root_element (client, client->doc, &req, &rc, NULL, 0, 0);
1447 if (rc && rc == GPG_ERR_ELEMENT_NOT_FOUND)
1449 rc = new_root_element (client, client->doc, *req);
1450 if (rc)
1452 strv_free (req);
1453 return send_error (ctx, rc);
1456 goto again;
1459 if (!n || rc)
1461 strv_free (req);
1462 return send_error (ctx, rc);
1465 parent = n;
1467 if (req[1] && *req[1])
1469 if (!n->children)
1470 parent = create_elements_cb (client, 1, n, req + 1, &rc, NULL);
1471 else
1472 parent = find_elements (client, client->doc, n->children, req + 1, &rc,
1473 NULL, NULL, create_elements_cb, 0, 0, NULL,
1477 if (!rc && len > 1)
1479 rc = is_element_owner (client, parent);
1480 if (!rc)
1482 n = find_text_node (parent->children);
1483 if (n)
1484 xmlNodeSetContent (n, (xmlChar *) content);
1485 else
1486 xmlNodeAddContent (parent, (xmlChar *) content);
1488 update_element_mtime (client, parent);
1492 xfree (content);
1493 strv_free (req);
1494 return send_error (ctx, rc);
1497 static gpg_error_t
1498 xfer_data (assuan_context_t ctx, const char *line, int total)
1500 struct client_s *client = assuan_get_pointer (ctx);
1501 int to_send;
1502 int sent = 0;
1503 gpg_error_t rc = 0;
1504 int progress = config_get_integer ("global", "xfer_progress");
1505 int flush = 0;
1507 if (!(client->flags & FLAG_LOCK_CMD))
1508 rc = unlock_file_mutex (client, 0);
1509 if (rc && rc != GPG_ERR_NOT_LOCKED)
1510 return rc;
1512 progress =
1513 progress > 0 ? (progress / ASSUAN_LINELENGTH) * ASSUAN_LINELENGTH : 0;
1514 to_send = total < ASSUAN_LINELENGTH ? total : ASSUAN_LINELENGTH;
1515 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1517 if (rc)
1518 return rc;
1520 again:
1523 if (sent + to_send > total)
1524 to_send = total - sent;
1526 rc = assuan_send_data (ctx, flush ? NULL : (char *) line + sent,
1527 flush ? 0 : to_send);
1528 if (!rc)
1530 sent += flush ? 0 : to_send;
1532 if ((progress && !(sent % progress) && sent != total) ||
1533 (sent == total && flush))
1534 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1536 if (!flush && !rc && sent == total)
1538 flush = 1;
1539 goto again;
1543 while (!rc && sent < total);
1545 return rc;
1548 static gpg_error_t
1549 do_get (assuan_context_t ctx, char *line)
1551 struct client_s *client = assuan_get_pointer (ctx);
1552 gpg_error_t rc;
1553 char **req;
1554 xmlNodePtr n;
1556 req = str_split (line, "\t", 0);
1558 if (!req || !*req)
1560 strv_free (req);
1561 return GPG_ERR_SYNTAX;
1564 n = find_root_element (client, client->doc, &req, &rc, NULL, 0, 0);
1565 if (!n || rc)
1567 strv_free (req);
1568 return rc;
1571 if (req[1])
1572 n = find_elements (client, client->doc, n->children, req + 1, &rc,
1573 NULL, NULL, NULL, 0, 0, NULL, 0);
1575 strv_free (req);
1576 if (rc)
1577 return rc;
1579 if (!n || !n->children)
1580 return GPG_ERR_NO_DATA;
1582 n = find_text_node (n->children);
1583 if (!n || !n->content || !*n->content)
1584 return GPG_ERR_NO_DATA;
1586 rc = xfer_data (ctx, (char *) n->content, xmlStrlen (n->content));
1587 return rc;
1590 static gpg_error_t
1591 get_command (assuan_context_t ctx, char *line)
1593 struct client_s *client = assuan_get_pointer (ctx);
1594 gpg_error_t rc;
1595 struct argv_s *args[] = {
1596 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1597 NULL
1600 rc = parse_options (&line, args, client, 1);
1601 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1602 rc = GPG_ERR_SYNTAX;
1603 if (rc)
1604 return send_error (ctx, rc);
1606 if (client->opts & OPT_INQUIRE)
1608 unsigned char *result;
1609 size_t len;
1611 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1612 if (rc)
1613 return send_error (ctx, rc);
1615 pthread_cleanup_push (xfree, result);
1616 rc = do_get (ctx, (char *)result);
1617 pthread_cleanup_pop (1);
1619 else
1620 rc = do_get (ctx, line);
1622 return send_error (ctx, rc);
1625 static void list_command_cleanup1 (void *arg);
1626 static gpg_error_t
1627 realpath_command (assuan_context_t ctx, char *line)
1629 struct string_s *string = NULL;
1630 gpg_error_t rc;
1631 struct client_s *client = assuan_get_pointer (ctx);
1632 struct argv_s *args[] = {
1633 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1634 NULL
1637 rc = parse_options (&line, args, client, 1);
1638 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1639 rc = GPG_ERR_SYNTAX;
1640 if (rc)
1641 return send_error (ctx, rc);
1643 if (client->opts & OPT_INQUIRE)
1645 unsigned char *result;
1646 size_t len;
1648 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1649 if (rc)
1650 return send_error (ctx, rc);
1652 pthread_cleanup_push (xfree, result);
1653 rc = build_realpath (client, client->doc, (char *)result, &string);
1654 pthread_cleanup_pop (1);
1656 else
1657 rc = build_realpath (client, client->doc, line, &string);
1659 if (!rc)
1661 pthread_cleanup_push (list_command_cleanup1, string);
1662 rc = xfer_data (ctx, string->str, string->len);
1663 pthread_cleanup_pop (1);
1666 return send_error (ctx, rc);
1669 static void
1670 list_command_cleanup1 (void *arg)
1672 if (arg)
1673 string_free ((struct string_s *) arg, 1);
1676 static void
1677 list_command_cleanup2 (void *arg)
1679 struct element_list_s *elements = arg;
1681 if (elements)
1683 if (elements->list)
1685 int total = slist_length (elements->list);
1686 int i;
1688 for (i = 0; i < total; i++)
1690 char *tmp = slist_nth_data (elements->list, i);
1691 xfree (tmp);
1694 slist_free (elements->list);
1697 if (elements->prefix)
1698 xfree (elements->prefix);
1700 if (elements->req)
1701 strv_free (elements->req);
1703 xfree (elements);
1707 static gpg_error_t
1708 parse_list_opt_norecurse (void *data, void *value)
1710 struct client_s *client = data;
1712 client->opts &= ~(OPT_LIST_RECURSE);
1713 return 0;
1716 static gpg_error_t
1717 parse_opt_verbose (void *data, void *value)
1719 struct client_s *client = data;
1721 client->opts |= OPT_VERBOSE;
1722 return 0;
1725 static gpg_error_t
1726 parse_list_opt_target (void *data, void *value)
1728 struct client_s *client = data;
1730 client->opts |= OPT_LIST_WITH_TARGET;
1731 return 0;
1734 static gpg_error_t
1735 parse_list_opt_all (void *data, void *value)
1737 struct client_s *client = data;
1739 client->opts |= OPT_LIST_ALL;
1740 return 0;
1743 static gpg_error_t
1744 list_path_once (struct client_s *client, char *line,
1745 struct element_list_s *elements, struct string_s *result)
1747 gpg_error_t rc;
1749 elements->req = str_split (line, " ", 0);
1750 if (!elements->req)
1751 strv_printf (&elements->req, "%s", line);
1753 rc = create_path_list (client, client->doc, elements, *elements->req);
1754 if ((rc == GPG_ERR_ELOOP || rc == GPG_ERR_EACCES) && elements->verbose)
1755 rc = 0;
1757 if (!rc)
1759 int total = slist_length (elements->list);
1761 if (total)
1763 int i;
1765 for (i = 0; i < total; i++)
1767 char *tmp = slist_nth_data (elements->list, i);
1769 string_append_printf (result, "%s%s", tmp,
1770 i + 1 == total ? "" : "\n");
1773 else
1774 rc = GPG_ERR_NO_DATA;
1777 return rc;
1780 static int
1781 has_list_flag (char *path, char *flags)
1783 char *p = path;
1785 while (*p && *++p != ' ');
1787 if (!*p)
1788 return 0;
1790 for (; *p; p++)
1792 char *f;
1794 for (f = flags; *f && *f != ' '; f++)
1796 if (*p == *f)
1797 return 1;
1801 return 0;
1804 static gpg_error_t
1805 do_list (assuan_context_t ctx, char *line)
1807 struct client_s *client = assuan_get_pointer (ctx);
1808 gpg_error_t rc;
1809 struct element_list_s *elements = NULL;
1811 elements = xcalloc (1, sizeof (struct element_list_s));
1812 if (!elements)
1813 return GPG_ERR_ENOMEM;
1815 elements->recurse = client->opts & OPT_LIST_RECURSE;
1816 elements->verbose =
1817 (client->opts & OPT_VERBOSE) | (client->opts & OPT_LIST_WITH_TARGET);
1818 elements->with_target = client->opts & OPT_LIST_WITH_TARGET;
1820 if (!line || !*line)
1822 struct string_s *str = NULL;
1824 pthread_cleanup_push (list_command_cleanup2, elements);
1825 rc = list_root_elements (client, client->doc, &str, elements->verbose,
1826 elements->with_target);
1827 pthread_cleanup_pop (1);
1828 pthread_cleanup_push (list_command_cleanup1, str);
1830 if (!rc)
1832 if (client->opts & OPT_LIST_ALL)
1834 char **roots = str_split (str->str, "\n", 0);
1835 char **p;
1837 pthread_cleanup_push (req_cleanup, roots);
1838 string_truncate (str, 0);
1840 for (p = roots; *p; p++)
1842 if (strchr (*p, ' '))
1844 if (has_list_flag (*p, "EOP"))
1846 string_append_printf (str, "%s%s", *p,
1847 *(p + 1) ? "\n" : "");
1848 continue;
1852 elements = xcalloc (1, sizeof (struct element_list_s));
1853 if (!elements)
1855 rc = GPG_ERR_ENOMEM;
1856 break;
1859 elements->recurse = client->opts & OPT_LIST_RECURSE;
1860 elements->verbose =
1861 (client->opts & OPT_VERBOSE) | (client->opts &
1862 OPT_LIST_WITH_TARGET);
1863 elements->with_target = client->opts & OPT_LIST_WITH_TARGET;
1864 pthread_cleanup_push (list_command_cleanup2, elements);
1865 rc = list_path_once (client, *p, elements, str);
1866 pthread_cleanup_pop (1);
1867 if (rc)
1868 break;
1870 if (*(p + 1))
1871 string_append (str, "\n");
1874 pthread_cleanup_pop (1);
1877 if (!rc)
1878 rc = xfer_data (ctx, str->str, str->len);
1881 pthread_cleanup_pop (1);
1882 return rc;
1885 pthread_cleanup_push (list_command_cleanup2, elements);
1886 struct string_s *str = string_new (NULL);
1887 pthread_cleanup_push (list_command_cleanup1, str);
1888 rc = list_path_once (client, line, elements, str);
1889 if (!rc)
1890 rc = xfer_data (ctx, str->str, str->len);
1892 pthread_cleanup_pop (1);
1893 pthread_cleanup_pop (1);
1894 return rc;
1897 static gpg_error_t
1898 list_command (assuan_context_t ctx, char *line)
1900 struct client_s *client = assuan_get_pointer (ctx);
1901 gpg_error_t rc;
1902 struct argv_s *args[] = {
1903 &(struct argv_s) {"no-recurse", OPTION_TYPE_NOARG,
1904 parse_list_opt_norecurse},
1905 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_opt_verbose},
1906 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1907 &(struct argv_s) {"with-target", OPTION_TYPE_NOARG,
1908 parse_list_opt_target},
1909 &(struct argv_s) {"all", OPTION_TYPE_NOARG, parse_list_opt_all},
1910 NULL
1913 if (disable_list_and_dump == 1)
1914 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
1916 client->opts |= OPT_LIST_RECURSE;
1917 rc = parse_options (&line, args, client, 1);
1918 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1919 rc = GPG_ERR_SYNTAX;
1920 if (rc)
1921 return send_error (ctx, rc);
1923 if (client->opts & OPT_LIST_ALL)
1924 client->opts |= OPT_LIST_RECURSE | OPT_VERBOSE;
1926 if (client->opts & OPT_INQUIRE)
1928 unsigned char *result;
1929 size_t len;
1931 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1932 if (rc)
1933 return send_error (ctx, rc);
1935 pthread_cleanup_push (xfree, result);
1936 rc = do_list (ctx, (char *)result);
1937 pthread_cleanup_pop (1);
1939 else
1940 rc = do_list (ctx, line);
1942 return send_error (ctx, rc);
1946 * req[0] - element path
1948 static gpg_error_t
1949 attribute_list (assuan_context_t ctx, char **req)
1951 struct client_s *client = assuan_get_pointer (ctx);
1952 char **attrlist = NULL;
1953 int i = 0;
1954 char **path = NULL;
1955 xmlAttrPtr a;
1956 xmlNodePtr n, an;
1957 char *line;
1958 gpg_error_t rc;
1960 if (!req || !req[0])
1961 return GPG_ERR_SYNTAX;
1963 client->flags |= FLAG_ACL_IGNORE;
1965 if ((path = str_split (req[0], "\t", 0)) == NULL)
1968 * The first argument may be only a root element.
1970 if ((path = str_split (req[0], " ", 0)) == NULL)
1971 return GPG_ERR_SYNTAX;
1974 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 0);
1975 if (!n || rc)
1977 strv_free (path);
1978 return rc;
1981 if (client->flags & FLAG_ACL_ERROR)
1983 client->flags &= ~FLAG_ACL_IGNORE;
1984 if (path[1])
1986 strv_free (path);
1987 return GPG_ERR_EACCES;
1990 client->flags &= ~FLAG_ACL_ERROR;
1993 if (path[1])
1995 n = find_elements (client, client->doc, n->children, path + 1, &rc,
1996 NULL, NULL, NULL, 0, 0, NULL, 0);
1997 if (!n || rc)
1999 strv_free (path);
2000 return rc;
2004 strv_free (path);
2006 for (a = n->properties; a; a = a->next)
2008 char **pa;
2010 if ((pa = xrealloc (attrlist, (i + 2) * sizeof (char *))) == NULL)
2012 if (attrlist)
2013 strv_free (attrlist);
2015 log_write ("%s(%i): %s", __FILE__, __LINE__,
2016 pwmd_strerror (GPG_ERR_ENOMEM));
2017 return GPG_ERR_ENOMEM;
2020 attrlist = pa;
2021 an = a->children;
2022 attrlist[i] = str_asprintf ("%s %s", (char *) a->name,
2024 && an->content ? (char *) an->content : "");
2026 if (!attrlist[i])
2028 strv_free (attrlist);
2029 log_write ("%s(%i): %s", __FILE__, __LINE__,
2030 pwmd_strerror (GPG_ERR_ENOMEM));
2031 return GPG_ERR_ENOMEM;
2034 attrlist[++i] = NULL;
2037 if (!attrlist)
2038 return GPG_ERR_NO_DATA;
2040 line = strv_join ("\n", attrlist);
2042 if (!line)
2044 log_write ("%s(%i): %s", __FILE__, __LINE__,
2045 pwmd_strerror (GPG_ERR_ENOMEM));
2046 strv_free (attrlist);
2047 return GPG_ERR_ENOMEM;
2050 pthread_cleanup_push (xfree, line);
2051 pthread_cleanup_push (req_cleanup, attrlist);
2052 rc = xfer_data (ctx, line, strlen (line));
2053 pthread_cleanup_pop (1);
2054 pthread_cleanup_pop (1);
2055 return rc;
2059 * req[0] - attribute
2060 * req[1] - element path
2062 static gpg_error_t
2063 attribute_delete (struct client_s *client, char **req)
2065 xmlNodePtr n;
2066 char **path = NULL;
2067 gpg_error_t rc;
2069 if (!req || !req[0] || !req[1])
2070 return GPG_ERR_SYNTAX;
2072 if (!strcmp (req[0], "_name"))
2073 return GPG_ERR_INV_ATTR;
2075 if ((path = str_split (req[1], "\t", 0)) == NULL)
2078 * The first argument may be only a root element.
2080 if ((path = str_split (req[1], " ", 0)) == NULL)
2081 return GPG_ERR_SYNTAX;
2084 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 0);
2085 if (!n || rc)
2086 goto fail;
2088 if (path[1])
2090 n = find_elements (client, client->doc, n->children, path + 1, &rc,
2091 NULL, NULL, NULL, 0, 0, NULL, 0);
2092 if (!n || rc)
2093 goto fail;
2096 if (!strcmp (req[0], (char *) "_acl"))
2098 rc = is_element_owner (client, n);
2099 if (rc)
2100 goto fail;
2103 rc = delete_attribute (client, n, (xmlChar *) req[0]);
2105 fail:
2106 strv_free (path);
2107 return rc;
2110 static xmlNodePtr
2111 create_element_path (struct client_s *client,
2112 char ***elements, gpg_error_t * rc, xmlNodePtr parent)
2114 char **req = *elements;
2115 char **req_orig = strv_dup (req);
2116 xmlNodePtr n = NULL;
2118 *rc = 0;
2120 if (!req_orig)
2122 *rc = GPG_ERR_ENOMEM;
2123 log_write ("%s(%i): %s", __FILE__, __LINE__,
2124 pwmd_strerror (GPG_ERR_ENOMEM));
2125 goto fail;
2128 again:
2129 n = find_root_element (client, client->doc, &req, rc, NULL, 0, 0);
2130 if (!n)
2132 if (*rc != GPG_ERR_ELEMENT_NOT_FOUND)
2133 goto fail;
2135 *rc = new_root_element (client, client->doc, req[0]);
2136 if (*rc)
2137 goto fail;
2139 goto again;
2141 else if (n == parent)
2143 *rc = GPG_ERR_CONFLICT;
2144 goto fail;
2147 if (req[1])
2149 if (!n->children)
2150 n = create_target_elements_cb (client, 1, n, req + 1, rc, NULL);
2151 else
2152 n = find_elements (client, client->doc, n->children, req + 1, rc,
2153 NULL, NULL, create_target_elements_cb, 0, 0,
2154 parent, 0);
2156 if (!n)
2157 goto fail;
2160 * Reset the position of the element tree now that the elements
2161 * have been created.
2163 strv_free (req);
2164 req = req_orig;
2165 req_orig = NULL;
2166 n = find_root_element (client, client->doc, &req, rc, NULL, 0, 0);
2167 if (!n)
2168 goto fail;
2170 n = find_elements (client, client->doc, n->children, req + 1, rc,
2171 NULL, NULL, NULL, 0, 0, NULL, 0);
2172 if (!n)
2173 goto fail;
2176 fail:
2177 if (req_orig)
2178 strv_free (req_orig);
2180 *elements = req;
2181 return n;
2185 * Creates a "target" attribute. When other commands encounter an element with
2186 * this attribute, the element path is modified to the target value. If the
2187 * source element path doesn't exist when using 'ATTR SET target', it is
2188 * created, but the destination element path must exist.
2190 * req[0] - source element path
2191 * req[1] - destination element path
2193 static gpg_error_t
2194 target_attribute (struct client_s *client, char **req)
2196 char **src, **dst, *line = NULL, **odst = NULL;
2197 gpg_error_t rc;
2198 xmlNodePtr n;
2200 if (!req || !req[0] || !req[1])
2201 return GPG_ERR_SYNTAX;
2203 if ((src = str_split (req[0], "\t", 0)) == NULL)
2206 * The first argument may be only a root element.
2208 if ((src = str_split (req[0], " ", 0)) == NULL)
2209 return GPG_ERR_SYNTAX;
2212 if (!valid_element_path (src, 0))
2213 return GPG_ERR_INV_VALUE;
2215 if ((dst = str_split (req[1], "\t", 0)) == NULL)
2218 * The first argument may be only a root element.
2220 if ((dst = str_split (req[1], " ", 0)) == NULL)
2222 rc = GPG_ERR_SYNTAX;
2223 goto fail;
2227 odst = strv_dup (dst);
2228 if (!odst)
2230 rc = GPG_ERR_ENOMEM;
2231 goto fail;
2234 n = find_root_element (client, client->doc, &dst, &rc, NULL, 0, 0);
2236 * Make sure the destination element path exists.
2238 if (rc && rc != GPG_ERR_EACCES)
2239 goto fail;
2241 rc = 0;
2242 if (dst[1])
2244 n = find_elements (client, client->doc, n->children, dst + 1, &rc,
2245 NULL, NULL, NULL, 0, 0, NULL, 0);
2246 if (rc && rc != GPG_ERR_EACCES)
2247 goto fail;
2250 rc = validate_target_attribute (client, client->doc, req[0], n);
2251 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2252 goto fail;
2254 n = create_element_path (client, &src, &rc, NULL);
2255 if (rc)
2256 goto fail;
2258 line = strv_join ("\t", odst);
2259 if (!line)
2261 rc = GPG_ERR_ENOMEM;
2262 goto fail;
2265 rc = add_attribute (client, n, "target", line);
2267 fail:
2268 xfree (line);
2269 strv_free (src);
2270 strv_free (dst);
2271 strv_free (odst);
2272 return rc;
2276 * req[0] - attribute
2277 * req[1] - element path
2279 static gpg_error_t
2280 attribute_get (assuan_context_t ctx, char **req)
2282 struct client_s *client = assuan_get_pointer (ctx);
2283 xmlNodePtr n;
2284 xmlChar *a;
2285 char **path = NULL;
2286 gpg_error_t rc;
2288 if (!req || !req[0] || !req[1])
2289 return GPG_ERR_SYNTAX;
2291 if (strchr (req[1], '\t'))
2293 if ((path = str_split (req[1], "\t", 0)) == NULL)
2294 return GPG_ERR_SYNTAX;
2296 else
2298 if ((path = str_split (req[1], " ", 0)) == NULL)
2299 return GPG_ERR_SYNTAX;
2302 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 0);
2303 if (!n || rc)
2304 goto fail;
2306 if (path[1])
2308 n = find_elements (client, client->doc, n->children, path + 1, &rc,
2309 NULL, NULL, NULL, 0, 0, NULL, 0);
2310 if (!n || rc)
2311 goto fail;
2314 strv_free (path);
2316 if ((a = xmlGetProp (n, (xmlChar *) req[0])) == NULL)
2317 return GPG_ERR_NOT_FOUND;
2319 pthread_cleanup_push (xmlFree, a);
2321 if (*a)
2322 rc = xfer_data (ctx, (char *) a, xmlStrlen (a));
2323 else
2324 rc = GPG_ERR_NO_DATA;
2326 pthread_cleanup_pop (1);
2327 return rc;
2329 fail:
2330 strv_free (path);
2331 return rc;
2335 * req[0] - attribute
2336 * req[1] - element path
2337 * req[2] - value
2339 static gpg_error_t
2340 attribute_set (struct client_s *client, char **req)
2342 char **path = NULL;
2343 gpg_error_t rc;
2344 xmlNodePtr n;
2346 if (!req || !req[0] || !req[1])
2347 return GPG_ERR_SYNTAX;
2350 * Reserved attribute names.
2352 if (!strcmp (req[0], "_name"))
2353 return GPG_ERR_INV_ATTR;
2354 else if (!strcmp (req[0], "target"))
2355 return target_attribute (client, req + 1);
2356 else if (!valid_xml_attribute (req[0]))
2357 return GPG_ERR_INV_VALUE;
2359 if ((path = str_split (req[1], "\t", 0)) == NULL)
2362 * The first argument may be only a root element.
2364 if ((path = str_split (req[1], " ", 0)) == NULL)
2365 return GPG_ERR_SYNTAX;
2368 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 0);
2369 if (!n || rc)
2370 goto fail;
2372 if (path[1])
2374 n = find_elements (client, client->doc, n->children, path + 1, &rc,
2375 NULL, NULL, NULL, 0, 0, NULL, 0);
2376 if (!n || rc)
2377 goto fail;
2380 if (!strcmp (req[0], (char *) "_acl"))
2382 rc = is_element_owner (client, n);
2383 if (rc)
2384 goto fail;
2387 rc = add_attribute (client, n, req[0], req[2]);
2389 fail:
2390 strv_free (path);
2391 return rc;
2395 * req[0] - command
2396 * req[1] - attribute name or element path if command is LIST
2397 * req[2] - element path
2398 * req[2] - element path or value
2401 static gpg_error_t
2402 do_attr (assuan_context_t ctx, char *line)
2404 struct client_s *client = assuan_get_pointer (ctx);
2405 gpg_error_t rc = 0;
2406 char **req;
2408 req = str_split (line, " ", 4);
2409 if (!req || !req[0] || !req[1])
2411 strv_free (req);
2412 return GPG_ERR_SYNTAX;
2415 pthread_cleanup_push (req_cleanup, req);
2417 if (strcasecmp (req[0], "SET") == 0)
2418 rc = attribute_set (client, req + 1);
2419 else if (strcasecmp (req[0], "GET") == 0)
2420 rc = attribute_get (ctx, req + 1);
2421 else if (strcasecmp (req[0], "DELETE") == 0)
2422 rc = attribute_delete (client, req + 1);
2423 else if (strcasecmp (req[0], "LIST") == 0)
2424 rc = attribute_list (ctx, req + 1);
2425 else
2426 rc = GPG_ERR_SYNTAX;
2428 client->flags &= ~(FLAG_ACL_IGNORE|FLAG_ACL_ERROR);
2429 pthread_cleanup_pop (1);
2430 return rc;
2433 static gpg_error_t
2434 attr_command (assuan_context_t ctx, char *line)
2436 struct client_s *client = assuan_get_pointer (ctx);
2437 gpg_error_t rc;
2438 struct argv_s *args[] = {
2439 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2440 NULL
2443 rc = parse_options (&line, args, client, 1);
2444 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2445 rc = GPG_ERR_SYNTAX;
2446 if (rc)
2447 return send_error (ctx, rc);
2449 if (client->opts & OPT_INQUIRE)
2451 unsigned char *result;
2452 size_t len;
2454 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2455 if (rc)
2456 return send_error (ctx, rc);
2458 pthread_cleanup_push (xfree, result);
2459 rc = do_attr (ctx, (char *)result);
2460 pthread_cleanup_pop (1);
2462 else
2463 rc = do_attr (ctx, line);
2465 return send_error (ctx, rc);
2468 static gpg_error_t
2469 parse_iscached_opt_lock (void *data, void *value)
2471 struct client_s *client = data;
2473 (void) value;
2474 client->opts |= OPT_LOCK;
2475 return 0;
2478 static gpg_error_t
2479 iscached_command (assuan_context_t ctx, char *line)
2481 struct client_s *client = assuan_get_pointer (ctx);
2482 gpg_error_t rc;
2483 struct argv_s *args[] = {
2484 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_iscached_opt_lock},
2485 NULL
2488 if (!line || !*line)
2489 return send_error (ctx, GPG_ERR_SYNTAX);
2491 rc = parse_options (&line, args, client, 1);
2492 if (rc)
2493 return send_error (ctx, rc);
2494 else if (!valid_filename (line))
2495 return send_error (ctx, GPG_ERR_INV_VALUE);
2497 rc = cache_iscached (line, NULL);
2498 if (client->opts & OPT_LOCK
2499 && (!rc || gpg_err_code (rc) == GPG_ERR_NO_DATA))
2501 unsigned char md5file[16];
2502 gpg_error_t trc = rc;
2504 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2505 if (memcmp (md5file, client->md5file, 16))
2506 cleanup_client (client);
2508 memcpy (client->md5file, md5file, 16);
2509 rc = do_lock (client, 1);
2510 if (!rc)
2511 rc = trc;
2514 return send_error (ctx, rc);
2517 static gpg_error_t
2518 clearcache_command (assuan_context_t ctx, char *line)
2520 gpg_error_t rc = 0, all_rc = 0;
2521 unsigned char md5file[16];
2522 int i;
2523 int t;
2524 int all = 0;
2525 struct client_thread_s *once = NULL;
2527 cache_lock ();
2528 MUTEX_LOCK (&cn_mutex);
2529 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
2531 if (!line || !*line)
2532 all = 1;
2534 t = slist_length (cn_thread_list);
2536 for (i = 0; i < t; i++)
2538 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2539 assuan_peercred_t peer;
2541 if (!thd->cl)
2542 continue;
2544 /* Lock each connected clients' file mutex to prevent any other client
2545 * from accessing the cache entry (the file mutex is locked upon
2546 * command startup). The cache for the entry is not cleared if the
2547 * file mutex is locked by another client to prevent this function
2548 * from blocking.
2550 if (all)
2552 if (thd->cl->filename)
2554 rc = do_validate_peer (ctx, thd->cl->filename, &peer);
2555 all_rc = !all_rc ? rc : all_rc;
2556 if (rc)
2558 rc = 0;
2559 continue;
2563 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0, -1);
2564 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2566 if (pthread_equal (pthread_self (), thd->tid))
2567 rc = 0;
2568 else
2570 if (!thd->cl->filename ||
2571 cache_iscached (thd->cl->filename,
2572 NULL) == GPG_ERR_NO_DATA)
2574 rc = 0;
2575 continue;
2578 cache_defer_clear (thd->cl->md5file);
2581 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
2583 rc = 0;
2584 continue;
2587 if (!rc)
2589 rc = cache_clear (thd->cl->md5file);
2590 cache_unlock_mutex (thd->cl->md5file, 0);
2593 if (rc)
2594 all_rc = rc;
2596 rc = 0;
2598 /* A single data filename was specified. Lock only this data file
2599 * mutex and free the cache entry. */
2600 else
2602 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2603 rc = do_validate_peer (ctx, line, &peer);
2605 if (!rc && !memcmp (thd->cl->md5file, md5file, sizeof (md5file)))
2607 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0,
2608 -1);
2609 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2611 if (pthread_equal (pthread_self (), thd->tid))
2612 rc = 0;
2615 if (!rc)
2617 once = thd;
2618 rc = cache_clear (thd->cl->md5file);
2619 cache_unlock_mutex (thd->cl->md5file, 0);
2621 else
2623 cache_defer_clear (thd->cl->md5file);
2626 break;
2631 /* Only connected clients' cache entries have been cleared. Now clear any
2632 * remaining cache entries without clients but only if there wasn't an
2633 * error from above since this would defeat the locking check of the
2634 * remaining entries. */
2635 if (!all_rc && all)
2637 cache_clear (NULL);
2640 /* No clients are using the specified file. */
2641 else if (!all_rc && !rc && !once)
2643 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2644 rc = cache_clear (md5file);
2647 /* Release the connection mutex. */
2648 pthread_cleanup_pop (1);
2649 cache_unlock ();
2651 if (!rc)
2652 send_status_all (STATUS_CACHE, NULL);
2654 /* One or more files were locked while clearing all cache entries. */
2655 if (all_rc)
2656 rc = all_rc;
2658 return send_error (ctx, rc);
2661 static gpg_error_t
2662 cachetimeout_command (assuan_context_t ctx, char *line)
2664 int timeout;
2665 char **req = str_split (line, " ", 0);
2666 char *p;
2667 gpg_error_t rc = 0;
2668 assuan_peercred_t peer;
2670 if (!req || !*req || !req[1])
2672 strv_free (req);
2673 return send_error (ctx, GPG_ERR_SYNTAX);
2676 errno = 0;
2677 timeout = (int) strtol (req[1], &p, 10);
2678 if (errno != 0 || *p || timeout < -1)
2680 strv_free (req);
2681 return send_error (ctx, GPG_ERR_SYNTAX);
2684 rc = do_validate_peer (ctx, req[0], &peer);
2685 if (!rc)
2687 unsigned char md5file[16];
2689 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, req[0], strlen (req[0]));
2690 rc = cache_set_timeout (md5file, timeout);
2691 if (!rc || gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
2693 rc = 0;
2694 MUTEX_LOCK (&rcfile_mutex);
2695 config_set_int_param (&global_config, req[0], "cache_timeout",
2696 req[1]);
2697 MUTEX_UNLOCK (&rcfile_mutex);
2701 strv_free (req);
2702 return send_error (ctx, rc);
2705 static gpg_error_t
2706 dump_command (assuan_context_t ctx, char *line)
2708 xmlChar *xml;
2709 int len;
2710 struct client_s *client = assuan_get_pointer (ctx);
2711 gpg_error_t rc;
2713 if (disable_list_and_dump == 1)
2714 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2716 if (line && *line)
2717 return send_error (ctx, GPG_ERR_SYNTAX);
2719 rc = peer_is_invoker(client);
2720 if (rc)
2721 return send_error (ctx, rc);
2723 xmlDocDumpFormatMemory (client->doc, &xml, &len, 1);
2725 if (!xml)
2727 log_write ("%s(%i): %s", __FILE__, __LINE__,
2728 pwmd_strerror (GPG_ERR_ENOMEM));
2729 return send_error (ctx, GPG_ERR_ENOMEM);
2732 pthread_cleanup_push (xmlFree, xml);
2733 rc = xfer_data (ctx, (char *) xml, len);
2734 pthread_cleanup_pop (1);
2735 return send_error (ctx, rc);
2738 static gpg_error_t
2739 getconfig_command (assuan_context_t ctx, char *line)
2741 struct client_s *client = assuan_get_pointer (ctx);
2742 gpg_error_t rc = 0;
2743 char filename[255] = { 0 }, param[747] = { 0 };
2744 char *p, *tmp = NULL, *fp = client->filename, *paramp = line;
2746 if (!line || !*line)
2747 return send_error (ctx, GPG_ERR_SYNTAX);
2749 if (strchr (line, ' '))
2751 sscanf (line, " %254[^ ] %746c", filename, param);
2752 paramp = param;
2753 fp = filename;
2756 if (fp && !valid_filename (fp))
2757 return send_error (ctx, GPG_ERR_INV_VALUE);
2759 paramp = str_down (paramp);
2760 if (!strcmp (paramp, "cipher") && fp)
2762 struct crypto_s *crypto = NULL;
2764 rc = init_client_crypto (&crypto);
2765 if (!rc)
2767 rc = read_data_header (fp, &crypto->hdr, NULL, NULL);
2768 if (!rc)
2770 const char *t =
2771 gcry_cipher_algo_name (cipher_to_gcrypt (crypto->hdr.flags));
2772 if (t)
2774 tmp = str_dup (t);
2775 if (tmp)
2776 str_down (tmp);
2781 UPDATE_AGENT_CTX (client, crypto);
2782 cleanup_crypto (&crypto);
2783 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
2784 return send_error (ctx, rc);
2786 if (!rc && tmp)
2787 goto done;
2789 else if (!strcmp (paramp, "cipher_iterations") && fp)
2791 struct crypto_s *crypto = NULL;
2793 rc = init_client_crypto (&crypto);
2794 if (!rc)
2796 rc = read_data_header (fp, &crypto->hdr, NULL, NULL);
2797 if (!rc)
2799 tmp = str_asprintf ("%llu",
2800 (unsigned long long) crypto->hdr.s2k_count);
2801 if (!tmp)
2802 rc = GPG_ERR_ENOMEM;
2806 UPDATE_AGENT_CTX (client, crypto);
2807 cleanup_crypto (&crypto);
2808 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
2809 return send_error (ctx, rc);
2811 if (!rc && tmp)
2812 goto done;
2814 else if (!strcmp (paramp, "passphrase"))
2815 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2817 p = config_get_value (fp ? fp : "global", paramp);
2818 if (!p)
2819 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2821 tmp = expand_homedir (p);
2822 xfree (p);
2823 if (!tmp)
2825 log_write ("%s(%i): %s", __FILE__, __LINE__,
2826 pwmd_strerror (GPG_ERR_ENOMEM));
2827 return send_error (ctx, GPG_ERR_ENOMEM);
2830 done:
2831 p = tmp;
2832 pthread_cleanup_push (xfree, p);
2833 rc = xfer_data (ctx, p, strlen (p));
2834 pthread_cleanup_pop (1);
2835 return send_error (ctx, rc);
2838 struct xpath_s
2840 xmlXPathContextPtr xp;
2841 xmlXPathObjectPtr result;
2842 xmlBufferPtr buf;
2843 char **req;
2846 static void
2847 xpath_command_cleanup (void *arg)
2849 struct xpath_s *xpath = arg;
2851 if (!xpath)
2852 return;
2854 req_cleanup (xpath->req);
2856 if (xpath->buf)
2857 xmlBufferFree (xpath->buf);
2859 if (xpath->result)
2860 xmlXPathFreeObject (xpath->result);
2862 if (xpath->xp)
2863 xmlXPathFreeContext (xpath->xp);
2866 static gpg_error_t
2867 do_xpath (assuan_context_t ctx, char *line)
2869 gpg_error_t rc;
2870 struct client_s *client = assuan_get_pointer (ctx);
2871 struct xpath_s _x = { 0 };
2872 struct xpath_s *xpath = &_x;
2874 if (!line || !*line)
2875 return GPG_ERR_SYNTAX;
2877 if ((xpath->req = str_split (line, "\t", 2)) == NULL)
2879 if (strv_printf (&xpath->req, "%s", line) == 0)
2880 return GPG_ERR_ENOMEM;
2883 xpath->xp = xmlXPathNewContext (client->doc);
2884 if (!xpath->xp)
2886 rc = GPG_ERR_BAD_DATA;
2887 goto fail;
2890 xpath->result =
2891 xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2892 if (!xpath->result)
2894 rc = GPG_ERR_BAD_DATA;
2895 goto fail;
2898 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2900 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2901 goto fail;
2904 rc = recurse_xpath_nodeset (client, client->doc, xpath->result->nodesetval,
2905 (xmlChar *) xpath->req[1], &xpath->buf, 0,
2906 NULL);
2907 if (rc)
2908 goto fail;
2909 else if (!xpath->req[1] && !xmlBufferLength (xpath->buf))
2911 rc = GPG_ERR_NO_DATA;
2912 goto fail;
2914 else if (xpath->req[1])
2916 rc = 0;
2917 goto fail;
2920 pthread_cleanup_push (xpath_command_cleanup, &xpath);
2921 rc = xfer_data (ctx, (char *) xmlBufferContent (xpath->buf),
2922 xmlBufferLength (xpath->buf));
2923 pthread_cleanup_pop (0);
2924 fail:
2925 xpath_command_cleanup (xpath);
2926 return rc;
2929 static gpg_error_t
2930 xpath_command (assuan_context_t ctx, char *line)
2932 struct client_s *client = assuan_get_pointer (ctx);
2933 gpg_error_t rc;
2934 struct argv_s *args[] = {
2935 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2936 NULL
2939 if (disable_list_and_dump == 1)
2940 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2942 rc = peer_is_invoker(client);
2943 if (rc)
2944 return send_error (ctx, rc);
2946 rc = parse_options (&line, args, client, 1);
2947 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2948 rc = GPG_ERR_SYNTAX;
2949 if (rc)
2950 return send_error (ctx, rc);
2952 if (client->opts & OPT_INQUIRE)
2954 unsigned char *result;
2955 size_t len;
2957 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2958 if (rc)
2959 return send_error (ctx, rc);
2961 pthread_cleanup_push (xfree, result);
2962 rc = do_xpath (ctx, (char *)result);
2963 pthread_cleanup_pop (1);
2965 else
2966 rc = do_xpath (ctx, line);
2968 return send_error (ctx, rc);
2971 static gpg_error_t
2972 do_xpathattr (assuan_context_t ctx, char *line)
2974 struct client_s *client = assuan_get_pointer (ctx);
2975 gpg_error_t rc;
2976 char **req = NULL;
2977 int cmd = 0; //SET
2978 struct xpath_s _x = { 0 };
2979 struct xpath_s *xpath = &_x;
2981 if (!line || !*line)
2982 return GPG_ERR_SYNTAX;
2984 if ((req = str_split (line, " ", 3)) == NULL)
2985 return GPG_ERR_ENOMEM;
2987 if (!req[0])
2989 rc = GPG_ERR_SYNTAX;
2990 goto fail;
2993 if (!strcasecmp (req[0], "SET"))
2994 cmd = 0;
2995 else if (!strcasecmp (req[0], "DELETE"))
2996 cmd = 1;
2997 else
2999 rc = GPG_ERR_SYNTAX;
3000 goto fail;
3003 if (!req[1] || !req[2])
3005 rc = GPG_ERR_SYNTAX;
3006 goto fail;
3009 if ((xpath->req = str_split (req[2], "\t", 3)) == NULL)
3011 rc = GPG_ERR_ENOMEM;
3012 goto fail;
3015 if (!xpath->req[0] || (!xpath->req[1] && !cmd) || (xpath->req[1] && cmd))
3017 rc = GPG_ERR_SYNTAX;
3018 goto fail;
3021 xpath->xp = xmlXPathNewContext (client->doc);
3022 if (!xpath->xp)
3024 rc = GPG_ERR_BAD_DATA;
3025 goto fail;
3028 xpath->result = xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
3029 if (!xpath->result)
3031 rc = GPG_ERR_BAD_DATA;
3032 goto fail;
3035 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
3037 rc = GPG_ERR_ELEMENT_NOT_FOUND;
3038 goto fail;
3041 rc = recurse_xpath_nodeset (client, client->doc, xpath->result->nodesetval,
3042 (xmlChar *) xpath->req[1], &xpath->buf, cmd,
3043 (xmlChar *) req[1]);
3045 fail:
3046 xpath_command_cleanup (xpath);
3047 strv_free (req);
3048 return rc;
3051 /* XPATHATTR SET|DELETE <name> <expression>[<TAB>[value]] */
3052 static gpg_error_t
3053 xpathattr_command (assuan_context_t ctx, char *line)
3055 struct client_s *client = assuan_get_pointer (ctx);
3056 gpg_error_t rc;
3057 struct argv_s *args[] = {
3058 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3059 NULL
3062 if (disable_list_and_dump == 1)
3063 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
3065 rc = peer_is_invoker(client);
3066 if (rc)
3067 return send_error (ctx, rc);
3069 rc = parse_options (&line, args, client, 1);
3070 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3071 rc = GPG_ERR_SYNTAX;
3072 if (rc)
3073 return send_error (ctx, rc);
3075 if (client->opts & OPT_INQUIRE)
3077 unsigned char *result;
3078 size_t len;
3080 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3081 if (rc)
3082 return send_error (ctx, rc);
3084 pthread_cleanup_push (xfree, result);
3085 rc = do_xpathattr (ctx, (char *)result);
3086 pthread_cleanup_pop (1);
3088 else
3089 rc = do_xpathattr (ctx, line);
3091 return send_error (ctx, rc);
3094 static gpg_error_t
3095 do_import (struct client_s *client, const char *root_element,
3096 unsigned char *content)
3098 char **dst_path = NULL;
3099 xmlDocPtr doc = NULL;
3100 xmlNodePtr n, root, copy;
3101 gpg_error_t rc;
3103 if (!content || !*content)
3105 xfree (content);
3106 return GPG_ERR_SYNTAX;
3109 if (root_element)
3110 dst_path = str_split (root_element, "\t", 0);
3112 if (dst_path && !valid_element_path (dst_path, 0))
3114 if (dst_path)
3115 strv_free (dst_path);
3117 return GPG_ERR_INV_VALUE;
3120 struct string_s *str = string_new_content ((char *)content);
3121 str = string_prepend (str, "<pwmd>");
3122 str = string_append (str, "</pwmd>");
3123 doc = xmlReadDoc ((xmlChar *) str->str, NULL, "UTF-8", XML_PARSE_NOBLANKS);
3124 string_free (str, 1);
3125 if (!doc)
3127 rc = GPG_ERR_BAD_DATA;
3128 goto fail;
3131 root = xmlDocGetRootElement (doc);
3132 xmlNodePtr root_orig = root->children;
3133 root = root->children;
3134 rc = validate_import (client, root);
3135 if (rc)
3136 goto fail;
3140 again:
3141 if (dst_path)
3143 char **path = strv_dup (dst_path);
3144 if (!path)
3146 log_write ("%s(%i): %s", __FILE__, __LINE__,
3147 pwmd_strerror (GPG_ERR_ENOMEM));
3148 rc = GPG_ERR_ENOMEM;
3149 goto fail;
3152 xmlChar *a = xmlGetProp (root, (xmlChar *) "_name");
3153 if (!a)
3155 strv_free (path);
3156 rc = GPG_ERR_INV_VALUE;
3157 goto fail;
3160 if (strv_printf (&path, "%s", (char *) a) == 0)
3162 xmlFree (a);
3163 rc = GPG_ERR_ENOMEM;
3164 goto fail;
3167 xmlFree (a);
3168 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 0);
3169 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3171 strv_free (path);
3172 goto fail;
3175 if (!rc)
3177 n = find_elements (client, client->doc, n->children, path + 1, &rc,
3178 NULL, NULL, NULL, 0, 0, NULL, 1);
3179 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3181 strv_free (path);
3182 goto fail;
3184 else if (!rc)
3186 xmlUnlinkNode (n);
3187 xmlFreeNode (n);
3188 strv_free (path);
3189 path = NULL;
3190 goto again;
3194 if (rc == GPG_ERR_ELEMENT_NOT_FOUND)
3196 n = create_element_path (client, &path, &rc, NULL);
3197 if (rc)
3198 goto fail;
3201 if (root->children)
3203 copy = xmlCopyNodeList (root->children);
3204 n = xmlAddChildList (n, copy);
3205 if (!n)
3206 rc = GPG_ERR_ENOMEM;
3209 strv_free (path);
3211 else
3213 char **path = NULL;
3215 /* Check if the content root element can create a DTD root element. */
3216 if (!xmlStrEqual ((xmlChar *) "element", root->name))
3218 rc = GPG_ERR_SYNTAX;
3219 goto fail;
3222 xmlChar *a;
3224 if ((a = xmlGetProp (root, (xmlChar *) "_name")) == NULL)
3226 rc = GPG_ERR_SYNTAX;
3227 goto fail;
3230 char *tmp = str_dup ((char *) a);
3231 xmlFree (a);
3232 int literal = is_literal_element (&tmp);
3234 if (!valid_xml_element ((xmlChar *) tmp) || literal)
3236 xfree (tmp);
3237 rc = GPG_ERR_INV_VALUE;
3238 goto fail;
3241 if (strv_printf (&path, "%s", tmp) == 0)
3243 xfree (tmp);
3244 rc = GPG_ERR_ENOMEM;
3245 goto fail;
3248 xfree (tmp);
3249 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 1);
3250 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3252 rc = GPG_ERR_BAD_DATA;
3253 goto fail;
3256 /* Overwriting the existing tree. */
3257 if (!rc)
3259 xmlUnlinkNode (n);
3260 xmlFreeNodeList (n);
3263 rc = 0;
3264 xmlSetProp (root, (xmlChar *) "_name", (xmlChar *) path[0]);
3265 n = xmlCopyNode (root, 1);
3266 n = xmlAddChildList (xmlDocGetRootElement (client->doc), n);
3267 strv_free (path);
3270 if (n && !rc)
3271 rc = update_element_mtime (client, n->parent);
3273 for (root = root_orig->next; root; root = root->next)
3275 if (root->type == XML_ELEMENT_NODE)
3276 break;
3279 root_orig = root;
3281 while (root);
3283 fail:
3284 if (doc)
3285 xmlFreeDoc (doc);
3287 if (dst_path)
3288 strv_free (dst_path);
3290 return rc;
3293 static gpg_error_t
3294 parse_import_opt_root (void *data, void *value)
3296 struct client_s *client = data;
3298 client->import_root = str_dup (value);
3299 return client->import_root ? 0 : GPG_ERR_ENOMEM;
3302 static gpg_error_t
3303 import_command (assuan_context_t ctx, char *line)
3305 gpg_error_t rc;
3306 struct client_s *client = assuan_get_pointer (ctx);
3307 unsigned char *result;
3308 size_t len;
3309 struct argv_s *args[] = {
3310 &(struct argv_s) {"root", OPTION_TYPE_ARG, parse_import_opt_root},
3311 NULL
3314 xfree (client->import_root);
3315 client->import_root = NULL;
3316 rc = parse_options (&line, args, client, 0);
3317 if (rc)
3318 return send_error (ctx, rc);
3320 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3321 if (rc)
3323 xfree (client->import_root);
3324 client->import_root = NULL;
3325 return send_error (ctx, rc);
3328 rc = do_import (client, client->import_root, result);
3329 xfree (client->import_root);
3330 client->import_root = NULL;
3331 return send_error (ctx, rc);
3334 static gpg_error_t
3335 do_lock (struct client_s *client, int add)
3337 gpg_error_t rc = lock_file_mutex (client, add);
3339 if (!rc)
3340 client->flags |= FLAG_LOCK_CMD;
3342 return rc;
3345 static gpg_error_t
3346 lock_command (assuan_context_t ctx, char *line)
3348 struct client_s *client = assuan_get_pointer (ctx);
3349 gpg_error_t rc;
3351 if (line && *line)
3352 return send_error (ctx, GPG_ERR_SYNTAX);
3354 rc = do_lock (client, 0);
3355 return send_error (ctx, rc);
3358 static gpg_error_t
3359 unlock_command (assuan_context_t ctx, char *line)
3361 struct client_s *client = assuan_get_pointer (ctx);
3362 gpg_error_t rc;
3364 if (line && *line)
3365 return send_error (ctx, GPG_ERR_SYNTAX);
3367 rc = unlock_file_mutex (client, 0);
3368 return send_error (ctx, rc);
3371 static gpg_error_t
3372 option_command (assuan_context_t ctx, char *line)
3374 struct client_s *client = assuan_get_pointer (ctx);
3375 gpg_error_t rc = 0;
3376 struct pinentry_option_s *pin_opts = &client->pinentry_opts;
3377 #ifdef WITH_AGENT
3378 struct agent_s *agent = client->crypto->agent;
3379 #endif
3380 char namebuf[255] = { 0 };
3381 char *name = namebuf;
3382 char *value = NULL, *p, *tmp = NULL;
3384 p = strchr (line, '=');
3385 if (!p)
3387 strncpy (namebuf, line, sizeof(namebuf));
3388 namebuf[sizeof(namebuf)-1] = 0;
3390 else
3392 strncpy (namebuf, line, strlen (line)-strlen (p));
3393 namebuf[sizeof(namebuf)-1] = 0;
3394 value = p+1;
3397 log_write1 ("OPTION name='%s' value='%s'", name, value);
3399 if (strcasecmp (name, (char *) "lock-timeout") == 0)
3401 long n = 0;
3403 if (value)
3405 n = strtol (value, &tmp, 10);
3406 if (tmp && *tmp)
3407 return send_error (ctx, GPG_ERR_INV_VALUE);
3410 client->lock_timeout = n;
3411 goto done;
3413 else if (strcasecmp (name, (char *) "NAME") == 0)
3415 if (value && strchr (value, ' '))
3416 rc = GPG_ERR_INV_VALUE;
3417 else
3419 tmp = pthread_getspecific (thread_name_key);
3420 xfree (tmp);
3421 MUTEX_LOCK (&cn_mutex);
3422 xfree (client->thd->name);
3423 client->thd->name = NULL;
3425 if (!value || !*value)
3426 pthread_setspecific (thread_name_key, str_dup (""));
3427 else
3429 client->thd->name = str_dup (value);
3430 pthread_setspecific (thread_name_key, str_dup (value));
3433 MUTEX_UNLOCK (&cn_mutex);
3435 goto done;
3437 else if (strcasecmp (name, (char *) "lc-messages") == 0)
3439 xfree (pin_opts->lc_messages);
3440 pin_opts->lc_messages = NULL;
3441 if (value && *value)
3442 pin_opts->lc_messages = str_dup (value);
3443 #ifdef WITH_AGENT
3444 if (use_agent)
3445 rc = set_agent_option (client->crypto->agent, "lc-messages", value);
3446 #endif
3448 else if (strcasecmp (name, (char *) "lc-ctype") == 0)
3450 xfree (pin_opts->lc_ctype);
3451 pin_opts->lc_ctype = NULL;
3452 if (value && *value)
3453 pin_opts->lc_ctype = str_dup (value);
3454 #ifdef WITH_AGENT
3455 if (use_agent)
3456 rc = set_agent_option (client->crypto->agent, "lc-ctype", value);
3457 #endif
3459 else if (strcasecmp (name, (char *) "ttyname") == 0)
3461 xfree (pin_opts->ttyname);
3462 pin_opts->ttyname = NULL;
3463 if (value && *value)
3464 pin_opts->ttyname = str_dup (value);
3465 #ifdef WITH_AGENT
3466 if (use_agent)
3467 rc = set_agent_option (client->crypto->agent, "ttyname", value);
3468 #endif
3470 else if (strcasecmp (name, (char *) "ttytype") == 0)
3472 xfree (pin_opts->ttytype);
3473 pin_opts->ttytype = NULL;
3474 if (value && *value)
3475 pin_opts->ttytype = str_dup (value);
3476 #ifdef WITH_AGENT
3477 if (use_agent)
3478 rc = set_agent_option (client->crypto->agent, "ttytype", value);
3479 #endif
3481 else if (strcasecmp (name, (char *) "display") == 0)
3483 xfree (pin_opts->display);
3484 pin_opts->display = NULL;
3485 if (value && *value)
3486 pin_opts->display = str_dup (value);
3487 #ifdef WITH_AGENT
3488 if (use_agent)
3489 rc = set_agent_option (client->crypto->agent, "display", value);
3490 #endif
3492 else if (strcasecmp (name, (char *) "pinentry-desc") == 0)
3494 xfree (pin_opts->desc);
3495 pin_opts->desc = NULL;
3496 if (value && *value)
3497 pin_opts->desc = str_dup (value);
3499 else if (strcasecmp (name, (char *) "pinentry-title") == 0)
3501 xfree (pin_opts->title);
3502 pin_opts->title = NULL;
3503 if (value && *value)
3504 pin_opts->title = str_dup (value);
3506 else if (strcasecmp (name, (char *) "pinentry-prompt") == 0)
3508 xfree (pin_opts->prompt);
3509 pin_opts->prompt = NULL;
3510 if (value && *value)
3511 pin_opts->prompt = str_dup (value);
3514 else if (strcasecmp (name, "pinentry-timeout") == 0)
3516 char *p = NULL;
3517 int n;
3519 if (!value)
3520 goto done;
3522 n = (int) strtol (value, &p, 10);
3524 if (*p || n < 0)
3525 return send_error (ctx, GPG_ERR_INV_VALUE);
3527 pin_opts->timeout = n;
3528 MUTEX_LOCK (&rcfile_mutex);
3529 config_set_int_param (&global_config,
3530 client->filename ? client->filename : "global",
3531 "pinentry_timeout", value);
3532 MUTEX_UNLOCK (&rcfile_mutex);
3533 goto done;
3535 else if (strcasecmp (name, "disable-pinentry") == 0)
3537 int n = 1;
3539 if (value && *value)
3541 n = (int) strtol (value, &tmp, 10);
3542 if (*tmp || n < 0 || n > 1)
3543 return send_error (ctx, GPG_ERR_INV_VALUE);
3546 if (n)
3547 client->flags |= FLAG_NO_PINENTRY;
3548 else
3549 client->flags &= ~FLAG_NO_PINENTRY;
3551 #ifdef WITH_AGENT
3552 if (use_agent)
3554 if (client->flags & FLAG_NO_PINENTRY)
3555 rc = set_agent_option (client->crypto->agent, "pinentry-mode",
3556 "loopback");
3557 else
3558 rc = set_agent_option (client->crypto->agent, "pinentry-mode",
3559 "ask");
3561 if (rc)
3562 return send_error (ctx, rc);
3564 #endif
3566 else
3567 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
3569 done:
3570 #ifdef WITH_AGENT
3571 if (!rc && use_agent && agent)
3573 rc = pinentry_merge_options (&client->crypto->agent->pinentry_opts,
3574 pin_opts);
3576 #endif
3578 return send_error (ctx, rc);
3581 static gpg_error_t
3582 do_rename (assuan_context_t ctx, char *line)
3584 struct client_s *client = assuan_get_pointer (ctx);
3585 gpg_error_t rc;
3586 char **req, **src, *dst;
3587 xmlNodePtr n, ndst;
3589 req = str_split (line, " ", 0);
3591 if (!req || !req[0] || !req[1])
3593 strv_free (req);
3594 return GPG_ERR_SYNTAX;
3597 dst = req[1];
3598 is_literal_element (&dst);
3600 if (!valid_xml_element ((xmlChar *) dst))
3602 strv_free (req);
3603 return GPG_ERR_INV_VALUE;
3606 if (strchr (req[0], '\t'))
3607 src = str_split (req[0], "\t", 0);
3608 else
3609 src = str_split (req[0], " ", 0);
3611 if (!src || !*src)
3613 rc = GPG_ERR_SYNTAX;
3614 goto fail;
3617 n = find_root_element (client, client->doc, &src, &rc, NULL, 0, 0);
3618 if (rc)
3619 goto fail;
3621 if (src[1] && n)
3622 n = find_elements (client, client->doc, n->children, src + 1, &rc, NULL, NULL,
3623 NULL, 0, 0, NULL, 0);
3625 if (!n || rc)
3626 goto fail;
3628 rc = is_element_owner (client, n);
3629 if (rc)
3630 goto fail;
3632 xmlChar *a = xmlGetProp (n, (xmlChar *) "_name");
3633 if (!a)
3635 rc = GPG_ERR_ENOMEM;
3636 goto fail;
3639 /* To prevent unwanted effects:
3641 * <root name="a"><b/></root>
3643 * RENAME a<TAB>b b
3645 if (xmlStrEqual (a, (xmlChar *) dst))
3647 xmlFree (a);
3648 rc = GPG_ERR_AMBIGUOUS_NAME;
3649 goto fail;
3652 xmlFree (a);
3653 char **tmp = NULL;
3654 if (src[1])
3656 char **p;
3658 for (p = src; *p; p++)
3660 if (!*(p + 1))
3661 break;
3662 strv_printf (&tmp, "%s", *p);
3666 strv_printf (&tmp, "!%s", dst);
3667 ndst = find_root_element (client, client->doc, &tmp, &rc, NULL, 0, 0);
3668 if (!ndst && rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3670 strv_free (tmp);
3671 goto fail;
3674 if (tmp[1] && ndst)
3675 ndst = find_elements (client, client->doc, ndst->children, tmp + 1, &rc, NULL,
3676 NULL, NULL, 0, 0, NULL, 0);
3678 strv_free (tmp);
3679 if (!ndst && rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3680 goto fail;
3682 rc = 0;
3684 /* Target may exist:
3686 * <root name="a"/>
3687 * <root name="b" target="a"/>
3689 * RENAME b a
3691 * Would need to do:
3692 * RENAME !b a
3694 if (ndst == n)
3696 rc = GPG_ERR_AMBIGUOUS_NAME;
3697 goto fail;
3700 if (ndst)
3702 rc = is_element_owner (client, ndst);
3703 if (rc)
3704 goto fail;
3706 unlink_node (client, ndst);
3707 xmlFreeNodeList (ndst);
3710 rc = add_attribute (client, n, "_name", dst);
3712 fail:
3713 strv_free (req);
3714 strv_free (src);
3715 return rc;
3718 static gpg_error_t
3719 rename_command (assuan_context_t ctx, char *line)
3721 struct client_s *client = assuan_get_pointer (ctx);
3722 gpg_error_t rc;
3723 struct argv_s *args[] = {
3724 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3725 NULL
3728 rc = parse_options (&line, args, client, 1);
3729 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3730 rc = GPG_ERR_SYNTAX;
3731 if (rc)
3732 return send_error (ctx, rc);
3734 if (client->opts & OPT_INQUIRE)
3736 unsigned char *result;
3737 size_t len;
3739 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3740 if (rc)
3741 return send_error (ctx, rc);
3743 pthread_cleanup_push (xfree, result);
3744 rc = do_rename (ctx, (char *)result);
3745 pthread_cleanup_pop (1);
3747 else
3748 rc = do_rename (ctx, line);
3750 return send_error (ctx, rc);
3753 static gpg_error_t
3754 do_copy (assuan_context_t ctx, char *line)
3756 struct client_s *client = assuan_get_pointer (ctx);
3757 gpg_error_t rc;
3758 char **req, **src = NULL, **dst = NULL;
3759 xmlNodePtr nsrc, ndst, new = NULL;
3761 req = str_split (line, " ", 0);
3762 if (!req || !req[0] || !req[1])
3764 strv_free (req);
3765 return GPG_ERR_SYNTAX;
3768 if (strchr (req[0], '\t'))
3769 src = str_split (req[0], "\t", 0);
3770 else
3771 src = str_split (req[0], " ", 0);
3773 if (!src || !*src)
3775 rc = GPG_ERR_SYNTAX;
3776 goto fail;
3779 if (strchr (req[1], '\t'))
3780 dst = str_split (req[1], "\t", 0);
3781 else
3782 dst = str_split (req[1], " ", 0);
3784 if (!dst || !*dst)
3786 rc = GPG_ERR_SYNTAX;
3787 goto fail;
3790 if (!valid_element_path (dst, 0))
3792 rc = GPG_ERR_INV_VALUE;
3793 goto fail;
3796 nsrc = find_root_element (client, client->doc, &src, &rc, NULL, 0, 0);
3797 if (rc)
3798 goto fail;
3800 if (nsrc && src[1])
3801 nsrc = find_elements (client, client->doc, nsrc->children, src + 1, &rc, NULL,
3802 NULL, NULL, 0, 0, NULL, 0);
3804 if (!nsrc || rc)
3805 goto fail;
3807 new = xmlCopyNodeList (nsrc);
3808 if (!new)
3810 rc = GPG_ERR_ENOMEM;
3811 goto fail;
3814 int create = 0;
3815 ndst = find_root_element (client, client->doc, &dst, &rc, NULL, 0, 0);
3816 if (rc == GPG_ERR_EACCES)
3817 goto fail;
3819 if (ndst && dst[1])
3821 if (ndst->children)
3822 ndst = find_elements (client, client->doc, ndst->children, dst + 1, &rc, NULL,
3823 NULL, create_target_elements_cb, 0, 0, NULL, 0);
3824 else
3825 create = 1;
3827 else
3828 create = 1;
3830 if (!ndst && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3831 goto fail;
3832 else if (!ndst || create)
3834 ndst = create_element_path (client, &dst, &rc, NULL);
3835 if (!ndst || rc)
3836 goto fail;
3839 rc = is_element_owner (client, ndst);
3840 if (rc)
3841 goto fail;
3843 /* Merge any attributes from the src node to the initial dst node. */
3844 for (xmlAttrPtr attr = new->properties; attr; attr = attr->next)
3846 if (xmlStrEqual (attr->name, (xmlChar *) "_name"))
3847 continue;
3849 xmlAttrPtr a = xmlHasProp (ndst, attr->name);
3850 if (a)
3851 xmlRemoveProp (a);
3853 xmlChar *tmp = xmlNodeGetContent (attr->children);
3854 xmlNewProp (ndst, attr->name, tmp);
3855 xmlFree (tmp);
3856 rc = add_attribute (client, ndst, NULL, NULL);
3859 xmlNodePtr n = ndst->children;
3860 xmlUnlinkNode (n);
3861 xmlFreeNodeList (n);
3862 ndst->children = NULL;
3864 if (new->children)
3866 n = xmlCopyNodeList (new->children);
3867 if (!n)
3869 rc = GPG_ERR_ENOMEM;
3870 goto fail;
3873 n = xmlAddChildList (ndst, n);
3874 if (!n)
3876 rc = GPG_ERR_ENOMEM;
3877 goto fail;
3880 rc = update_element_mtime (client, xmlDocGetRootElement (client->doc) ==
3881 ndst->parent ? ndst : ndst->parent);
3884 fail:
3885 if (new)
3887 xmlUnlinkNode (new);
3888 xmlFreeNodeList (new);
3891 if (req)
3892 strv_free (req);
3894 if (src)
3895 strv_free (src);
3897 if (dst)
3898 strv_free (dst);
3900 return rc;
3903 static gpg_error_t
3904 copy_command (assuan_context_t ctx, char *line)
3906 struct client_s *client = assuan_get_pointer (ctx);
3907 gpg_error_t rc;
3908 struct argv_s *args[] = {
3909 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3910 NULL
3913 rc = parse_options (&line, args, client, 1);
3914 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3915 rc = GPG_ERR_SYNTAX;
3916 if (rc)
3917 return send_error (ctx, rc);
3919 if (client->opts & OPT_INQUIRE)
3921 unsigned char *result;
3922 size_t len;
3924 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3925 if (rc)
3926 return send_error (ctx, rc);
3928 pthread_cleanup_push (xfree, result);
3929 rc = do_copy (ctx, (char *)result);
3930 pthread_cleanup_pop (1);
3932 else
3933 rc = do_copy (ctx, line);
3935 return send_error (ctx, rc);
3938 static gpg_error_t
3939 do_move (assuan_context_t ctx, char *line)
3941 struct client_s *client = assuan_get_pointer (ctx);
3942 gpg_error_t rc;
3943 char **req, **src = NULL, **dst = NULL;
3944 xmlNodePtr nsrc, ndst = NULL;
3946 req = str_split (line, " ", 0);
3948 if (!req || !req[0] || !req[1])
3950 strv_free (req);
3951 return GPG_ERR_SYNTAX;
3954 if (strchr (req[0], '\t'))
3955 src = str_split (req[0], "\t", 0);
3956 else
3957 src = str_split (req[0], " ", 0);
3959 if (!src || !*src)
3961 rc = GPG_ERR_SYNTAX;
3962 goto fail;
3965 if (strchr (req[1], '\t'))
3966 dst = str_split (req[1], "\t", 0);
3967 else
3968 dst = str_split (req[1], " ", 0);
3970 nsrc = find_root_element (client, client->doc, &src, &rc, NULL, 0, 0);
3971 if (rc)
3972 goto fail;
3974 if (nsrc && src[1])
3975 nsrc = find_elements (client, client->doc, nsrc->children, src + 1, &rc,
3976 NULL, NULL, NULL, 0, 0, NULL, 0);
3978 if (!nsrc)
3979 goto fail;
3981 rc = is_element_owner (client, nsrc);
3982 if (rc)
3983 goto fail;
3985 if (dst)
3987 if (!valid_element_path (dst, 0))
3989 rc = GPG_ERR_INV_VALUE;
3990 goto fail;
3993 ndst = find_root_element (client, client->doc, &dst, &rc, NULL, 0, 0);
3994 if (rc)
3995 goto fail;
3997 if (ndst && dst[1])
3998 ndst = find_elements (client, client->doc, ndst->children, dst + 1,
3999 &rc, NULL, NULL, NULL, 0, 0, NULL, 0);
4001 else
4002 ndst = xmlDocGetRootElement (client->doc);
4004 for (xmlNodePtr n = ndst; n; n = n->parent)
4006 if (n == nsrc)
4008 rc = GPG_ERR_CONFLICT;
4009 goto fail;
4013 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
4014 goto fail;
4016 rc = 0;
4018 if (ndst)
4020 xmlChar *a = node_has_attribute (nsrc, (xmlChar *) "_name");
4022 xmlNodePtr dup = find_element (client, ndst->children, (char *) a,
4023 NULL, &rc);
4024 xmlFree (a);
4026 if (rc)
4027 goto fail;
4029 if (dup)
4031 if (dup == nsrc)
4032 goto fail;
4034 if (ndst == xmlDocGetRootElement (client->doc))
4036 xmlNodePtr n = nsrc;
4037 int match = 0;
4039 while (n->parent && n->parent != ndst)
4040 n = n->parent;
4042 xmlChar *a = node_has_attribute (n, (xmlChar *) "_name");
4043 xmlChar *b = node_has_attribute (nsrc, (xmlChar *) "_name");
4045 if (xmlStrEqual (a, b))
4047 match = 1;
4048 xmlUnlinkNode (nsrc);
4049 xmlUnlinkNode (n);
4050 xmlFreeNodeList (n);
4053 xmlFree (a);
4054 xmlFree (b);
4056 if (!match)
4058 xmlUnlinkNode (dup);
4059 xmlFreeNodeList (dup);
4062 else
4063 xmlUnlinkNode (dup);
4067 if (!ndst && dst)
4069 xmlChar *name = node_has_attribute (nsrc, (xmlChar *) "_name");
4071 if (nsrc->parent == xmlDocGetRootElement (client->doc)
4072 && !strcmp ((char *) name, *dst))
4074 xmlFree (name);
4075 rc = GPG_ERR_CONFLICT;
4076 goto fail;
4079 xmlFree (name);
4080 ndst = create_element_path (client, &dst, &rc, nsrc);
4081 if (rc)
4082 goto fail;
4085 if (!ndst)
4086 goto fail;
4088 update_element_mtime (client, nsrc->parent);
4089 xmlUnlinkNode (nsrc);
4090 ndst = xmlAddChildList (ndst, nsrc);
4092 if (!ndst)
4093 rc = GPG_ERR_ENOMEM;
4094 else
4095 update_element_mtime (client, ndst->parent);
4097 fail:
4098 if (req)
4099 strv_free (req);
4101 if (src)
4102 strv_free (src);
4104 if (dst)
4105 strv_free (dst);
4107 return rc;
4110 static gpg_error_t
4111 move_command (assuan_context_t ctx, char *line)
4113 struct client_s *client = assuan_get_pointer (ctx);
4114 gpg_error_t rc;
4115 struct argv_s *args[] = {
4116 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
4117 NULL
4120 rc = parse_options (&line, args, client, 1);
4121 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
4122 rc = GPG_ERR_SYNTAX;
4123 if (rc)
4124 return send_error (ctx, rc);
4126 if (client->opts & OPT_INQUIRE)
4128 unsigned char *result;
4129 size_t len;
4131 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
4132 if (rc)
4133 return send_error (ctx, rc);
4135 pthread_cleanup_push (xfree, result);
4136 rc = do_move (ctx, (char *)result);
4137 pthread_cleanup_pop (1);
4139 else
4140 rc = do_move (ctx, line);
4142 return send_error (ctx, rc);
4145 static gpg_error_t
4146 ls_command (assuan_context_t ctx, char *line)
4148 gpg_error_t rc;
4149 char *tmp;
4150 char *dir;
4151 DIR *d;
4153 if (line && *line)
4154 return send_error (ctx, GPG_ERR_SYNTAX);
4156 tmp = str_asprintf ("%s/data", homedir);
4157 dir = expand_homedir (tmp);
4158 xfree (tmp);
4159 d = opendir (dir);
4160 rc = gpg_error_from_errno (errno);
4162 if (!d)
4164 xfree (dir);
4165 return send_error (ctx, rc);
4168 size_t len =
4169 offsetof (struct dirent, d_name) +pathconf (dir, _PC_NAME_MAX) + 1;
4170 struct dirent *p = xmalloc (len), *cur = NULL;
4171 char *list = NULL;
4173 xfree (dir);
4174 pthread_cleanup_push (xfree, p);
4175 pthread_cleanup_push ((void *)(void *)closedir, d);
4176 rc = 0;
4178 while (!readdir_r (d, p, &cur) && cur)
4180 if (cur->d_name[0] == '.' && cur->d_name[1] == '\0')
4181 continue;
4182 else if (cur->d_name[0] == '.' && cur->d_name[1] == '.'
4183 && cur->d_name[2] == '\0')
4184 continue;
4186 tmp = str_asprintf ("%s%s\n", list ? list : "", cur->d_name);
4188 if (!tmp)
4190 if (list)
4191 xfree (list);
4193 rc = GPG_ERR_ENOMEM;
4194 break;
4197 xfree (list);
4198 list = tmp;
4201 pthread_cleanup_pop (1); // closedir (d)
4202 pthread_cleanup_pop (1); // xfree (p)
4204 if (rc)
4205 return send_error (ctx, rc);
4207 if (!list)
4208 return send_error (ctx, GPG_ERR_NO_DATA);
4210 list[strlen (list) - 1] = 0;
4211 pthread_cleanup_push (xfree, list);
4212 rc = xfer_data (ctx, list, strlen (list));
4213 pthread_cleanup_pop (1);
4214 return send_error (ctx, rc);
4217 static gpg_error_t
4218 bye_notify (assuan_context_t ctx, char *line)
4220 struct client_s *cl = assuan_get_pointer (ctx);
4222 cl->thd->state = CLIENT_STATE_DISCON;
4224 #ifdef WITH_GNUTLS
4225 if (cl->thd->remote)
4227 int rc;
4231 struct timeval tv = { 0, 50000 };
4233 rc = gnutls_bye (cl->thd->tls->ses, GNUTLS_SHUT_RDWR);
4234 if (rc == GNUTLS_E_AGAIN)
4235 select (0, NULL, NULL, NULL, &tv);
4237 while (rc == GNUTLS_E_AGAIN);
4239 #endif
4241 /* This will let assuan_process_next() return. */
4242 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
4244 cl->last_rc = gpg_error_from_errno (errno);
4245 return cl->last_rc;
4248 cl->last_rc = 0; // BYE command result
4249 return 0;
4252 static gpg_error_t
4253 reset_notify (assuan_context_t ctx, char *line)
4255 struct client_s *client = assuan_get_pointer (ctx);
4257 if (client)
4258 cleanup_client (client);
4260 return 0;
4264 * This is called before every Assuan command.
4266 static gpg_error_t
4267 command_startup (assuan_context_t ctx, const char *name)
4269 struct client_s *client = assuan_get_pointer (ctx);
4270 gpg_error_t rc;
4271 struct command_table_s *cmd = NULL;
4273 log_write1 ("command='%s'", name);
4274 client->last_rc = client->opts = 0;
4276 for (int i = 0; command_table[i]; i++)
4278 if (!strcasecmp (name, command_table[i]->name))
4280 if (command_table[i]->ignore_startup)
4281 return 0;
4282 cmd = command_table[i];
4283 break;
4287 if (!cmd)
4288 return GPG_ERR_UNKNOWN_COMMAND;
4290 client->last_rc = rc = gpg_error (file_modified (client, cmd));
4291 if (!rc)
4292 update_client_state (client, CLIENT_STATE_COMMAND);
4294 return rc;
4298 * This is called after every Assuan command.
4300 static void
4301 command_finalize (assuan_context_t ctx, gpg_error_t rc)
4303 struct client_s *client = assuan_get_pointer (ctx);
4305 if (!(client->flags & FLAG_LOCK_CMD))
4306 unlock_file_mutex (client, 0);
4308 unlock_flock (&client->flock_fd);
4309 log_write1 (_("command completed: rc=%u"), rc ? rc : client->last_rc);
4310 client->last_rc = gpg_error (GPG_ERR_UNKNOWN_COMMAND);
4311 #ifdef WITH_GNUTLS
4312 client->thd->buffer_timeout = client->thd->last_buffer_size = 0;
4313 #endif
4314 update_client_state (client, CLIENT_STATE_IDLE);
4317 static gpg_error_t
4318 help_command (assuan_context_t ctx, char *line)
4320 gpg_error_t rc;
4321 int i;
4323 if (!line || !*line)
4325 char *tmp;
4326 char *help = str_dup (_("Usage: HELP [<COMMAND>]\n"
4327 "For commands that take an element path as an argument, each element is "
4328 "separated with an ASCII @key{TAB} character (ASCII 0x09)."
4329 "\n" "COMMANDS:"));
4331 for (i = 0; command_table[i]; i++)
4333 if (!command_table[i]->help)
4334 continue;
4336 tmp = str_asprintf ("%s %s", help, command_table[i]->name);
4337 xfree (help);
4338 help = tmp;
4341 tmp = strip_texi_and_wrap (help);
4342 xfree (help);
4343 pthread_cleanup_push (xfree, tmp);
4344 rc = xfer_data (ctx, tmp, strlen (tmp));
4345 pthread_cleanup_pop (1);
4346 return send_error (ctx, rc);
4349 for (i = 0; command_table[i]; i++)
4351 if (!strcasecmp (line, command_table[i]->name))
4353 char *help, *tmp;
4355 if (!command_table[i]->help)
4356 break;
4358 help = strip_texi_and_wrap (command_table[i]->help);
4359 tmp = str_asprintf (_("Usage: %s"), help);
4360 xfree (help);
4361 pthread_cleanup_push (xfree, tmp);
4362 rc = xfer_data (ctx, tmp, strlen (tmp));
4363 pthread_cleanup_pop (1);
4364 return send_error (ctx, rc);
4368 return send_error (ctx, GPG_ERR_INV_NAME);
4371 static void
4372 new_command (const char *name, int ignore, int unlock, int flock_type,
4373 gpg_error_t (*handler) (assuan_context_t, char *),
4374 const char *help)
4376 int i = 0;
4378 if (command_table)
4379 for (i = 0; command_table[i]; i++);
4381 command_table =
4382 xrealloc (command_table, (i + 2) * sizeof (struct command_table_s *));
4383 command_table[i] = xcalloc (1, sizeof (struct command_table_s));
4384 command_table[i]->name = name;
4385 command_table[i]->handler = handler;
4386 command_table[i]->ignore_startup = ignore;
4387 command_table[i]->unlock = unlock;
4388 command_table[i]->flock_type = flock_type;
4389 command_table[i++]->help = help;
4390 command_table[i] = NULL;
4393 void
4394 deinit_commands ()
4396 int i;
4398 for (i = 0; command_table[i]; i++)
4399 xfree (command_table[i]);
4401 xfree (command_table);
4404 static int
4405 sort_commands (const void *arg1, const void *arg2)
4407 struct command_table_s *const *a = arg1;
4408 struct command_table_s *const *b = arg2;
4410 if (!*a || !*b)
4411 return 0;
4412 else if (*a && !*b)
4413 return 1;
4414 else if (!*a && *b)
4415 return -1;
4417 return strcmp ((*a)->name, (*b)->name);
4420 static gpg_error_t
4421 passwd_command (assuan_context_t ctx, char *line)
4423 struct client_s *client = assuan_get_pointer (ctx);
4424 gpg_error_t rc;
4425 struct argv_s *args[] = {
4426 &(struct argv_s) {"reset", OPTION_TYPE_NOARG, parse_opt_reset},
4427 &(struct argv_s) {"s2k-count", OPTION_TYPE_ARG, parse_opt_s2k_count},
4428 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG, parse_opt_no_passphrase},
4429 NULL
4432 rc = peer_is_invoker (client);
4433 if (rc == GPG_ERR_EACCES)
4434 return send_error (ctx, rc);
4436 if (client->flags & FLAG_NEW)
4437 return send_error (ctx, GPG_ERR_INV_STATE);
4439 client->crypto->save.hdr.s2k_count =
4440 config_get_ulonglong (client->filename, "s2k_count");
4441 rc = parse_options (&line, args, client, 0);
4442 if (rc)
4443 return send_error (ctx, rc);
4445 if (!rc && client->opts & OPT_RESET)
4447 rc = cache_clear (client->md5file);
4448 if (!rc)
4449 send_status_all (STATUS_CACHE, NULL);
4452 if (!rc)
4454 if (!IS_PKI (client->crypto))
4456 struct crypto_s *crypto;
4458 xfree (client->crypto->filename);
4459 client->crypto->filename = str_dup (client->filename);
4460 rc = change_passwd (ctx, client->filename,
4461 client->flags & FLAG_NO_PINENTRY, &crypto,
4462 (client->opts & OPT_NO_PASSPHRASE));
4463 if (!rc)
4465 cleanup_crypto (&client->crypto);
4466 client->crypto = crypto;
4467 update_checksum (client);
4468 cleanup_crypto_stage1 (client->crypto);
4471 #ifdef WITH_AGENT
4472 else
4474 if (client->crypto->save.hdr.s2k_count)
4475 rc = send_to_agent (client->crypto->agent, NULL, NULL,
4476 "OPTION s2k-count=%lu",
4477 client->crypto->save.hdr.s2k_count);
4479 if (!rc)
4480 rc = agent_passwd (client->crypto);
4482 (void) kill_scd (client->crypto->agent);
4484 #endif
4487 return send_error (ctx, rc);
4490 static gpg_error_t
4491 parse_keygrip_opt_sign (void *data, void *value)
4493 struct client_s *client = data;
4495 (void) value;
4496 client->opts |= OPT_SIGN;
4497 return 0;
4500 static gpg_error_t
4501 keygrip_command (assuan_context_t ctx, char *line)
4503 struct client_s *client = assuan_get_pointer (ctx);
4504 gpg_error_t rc;
4505 struct crypto_s *crypto = NULL;
4506 struct argv_s *args[] = {
4507 &(struct argv_s) {"sign", OPTION_TYPE_NOARG, parse_keygrip_opt_sign},
4508 NULL
4511 if (!line || !*line)
4512 return send_error (ctx, GPG_ERR_SYNTAX);
4514 rc = parse_options (&line, args, client, 1);
4515 if (rc)
4516 return send_error (ctx, rc);
4518 if (!valid_filename (line))
4519 return send_error (ctx, GPG_ERR_INV_VALUE);
4521 rc = init_client_crypto (&crypto);
4522 if (rc)
4523 return send_error (ctx, rc);
4525 rc = read_data_file (line, crypto);
4526 if (!rc)
4528 char *hexgrip = NULL;
4530 if (!IS_PKI (crypto))
4532 cleanup_crypto (&crypto);
4533 return send_error (ctx, GPG_ERR_NOT_SUPPORTED);
4536 if (client->opts & OPT_SIGN)
4538 if (valid_keygrip (crypto->sign_grip, sizeof (crypto->sign_grip)))
4539 hexgrip = bin2hex (crypto->sign_grip, sizeof (crypto->sign_grip));
4542 if (!hexgrip)
4543 hexgrip = bin2hex (crypto->grip, sizeof (crypto->grip));
4545 if (!hexgrip)
4546 rc = GPG_ERR_ENOMEM;
4547 else
4548 rc = xfer_data (ctx, hexgrip, strlen (hexgrip));
4550 xfree (hexgrip);
4553 UPDATE_AGENT_CTX (client, crypto);
4554 cleanup_crypto (&crypto);
4555 return send_error (ctx, rc);
4558 static gpg_error_t
4559 parse_opt_data (void *data, void *value)
4561 struct client_s *client = data;
4563 (void) value;
4564 client->opts |= OPT_DATA;
4565 return 0;
4568 static gpg_error_t
4569 send_client_list (assuan_context_t ctx)
4571 struct client_s *client = assuan_get_pointer (ctx);
4572 gpg_error_t rc = 0;
4573 char buf[ASSUAN_LINELENGTH];
4575 if (client->opts & OPT_VERBOSE)
4577 unsigned i, t;
4578 char **list = NULL;
4579 char *line;
4581 MUTEX_LOCK (&cn_mutex);
4582 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
4583 t = slist_length (cn_thread_list);
4585 for (i = 0; i < t; i++)
4587 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
4588 char *tmp;
4590 if (thd->state == CLIENT_STATE_UNKNOWN)
4591 continue;
4593 tmp = build_client_info_line (thd, 0);
4594 if (tmp)
4596 char **l = strv_cat (list, tmp);
4597 if (!l)
4598 rc = GPG_ERR_ENOMEM;
4599 else
4600 list = l;
4602 else
4603 rc = GPG_ERR_ENOMEM;
4605 if (rc)
4607 strv_free (list);
4608 break;
4612 pthread_cleanup_pop (1);
4613 if (rc)
4614 return rc;
4616 line = strv_join ("\n", list);
4617 strv_free (list);
4618 pthread_cleanup_push (xfree, line);
4619 rc = xfer_data (ctx, line, strlen (line));
4620 pthread_cleanup_pop (1);
4621 return rc;
4624 if (client->opts & OPT_DATA)
4626 MUTEX_LOCK (&cn_mutex);
4627 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
4628 snprintf (buf, sizeof (buf), "%i", slist_length (cn_thread_list));
4629 pthread_cleanup_pop (1);
4630 rc = xfer_data (ctx, buf, strlen (buf));
4632 else
4633 rc = send_status (ctx, STATUS_CLIENTS, NULL);
4635 return rc;
4638 static gpg_error_t
4639 getinfo_command (assuan_context_t ctx, char *line)
4641 struct client_s *client = assuan_get_pointer (ctx);
4642 gpg_error_t rc;
4643 char buf[ASSUAN_LINELENGTH];
4644 struct argv_s *args[] = {
4645 &(struct argv_s) {"data", OPTION_TYPE_NOARG, parse_opt_data},
4646 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_opt_verbose},
4647 NULL
4650 rc = parse_options (&line, args, client, 1);
4651 if (rc)
4652 return send_error (ctx, rc);
4654 if (!strcasecmp (line, "clients"))
4656 rc = send_client_list (ctx);
4658 else if (!strcasecmp (line, "cache"))
4660 if (client->opts & OPT_DATA)
4662 snprintf (buf, sizeof (buf), "%u", cache_file_count ());
4663 rc = xfer_data (ctx, buf, strlen (buf));
4665 else
4666 rc = send_status (ctx, STATUS_CACHE, NULL);
4668 else if (!strcasecmp (line, "pid"))
4670 char buf[32];
4671 pid_t pid = getpid ();
4673 snprintf (buf, sizeof (buf), "%i", pid);
4674 rc = xfer_data (ctx, buf, strlen (buf));
4676 else if (!strcasecmp (line, "version"))
4678 char *buf = str_asprintf ("0x%06x %s%s", VERSION_HEX,
4679 #ifdef WITH_LIBACL
4680 "ACL "
4681 #endif
4682 #ifdef WITH_GNUTLS
4683 "GNUTLS "
4684 #endif
4685 #ifdef WITH_QUALITY
4686 "QUALITY "
4687 #endif
4688 "", use_agent ? "AGENT" : "");
4689 rc = xfer_data (ctx, buf, strlen (buf));
4690 xfree (buf);
4692 else if (!strcasecmp (line, "last_error"))
4694 if (client->last_error)
4695 rc = xfer_data (ctx, client->last_error, strlen (client->last_error));
4696 else
4697 rc = GPG_ERR_NO_DATA;
4699 else if (!strcasecmp (line, "user"))
4701 char *user = NULL;
4703 #ifdef WITH_GNUTLS
4704 if (client->thd->remote)
4705 user = str_asprintf ("#%s", client->thd->tls->fp);
4706 else
4707 user = get_username (client->thd->peer->uid);
4708 #else
4709 user = get_username (client->thd->peer->uid);
4710 #endif
4711 if (user)
4713 pthread_cleanup_push (xfree, user);
4714 rc = xfer_data (ctx, user, strlen (user));
4715 pthread_cleanup_pop (1);
4717 else
4718 rc = GPG_ERR_NO_DATA;
4720 else
4721 rc = gpg_error (GPG_ERR_SYNTAX);
4723 return send_error (ctx, rc);
4726 #ifdef WITH_AGENT
4727 static gpg_error_t
4728 send_data_cb (void *user, const void *buf, size_t len)
4730 assuan_context_t ctx = user;
4732 return assuan_send_data (ctx, buf, len);
4735 static gpg_error_t
4736 send_status_cb (void *user, const char *line)
4738 assuan_context_t ctx = user;
4739 char keyword[200], *k;
4740 const char *p;
4742 for (p = line, k = keyword; *p; p++)
4744 if (isspace (*p))
4745 break;
4747 *k++ = *p;
4750 *k = 0;
4751 if (*p == '#')
4752 p++;
4754 while (isspace (*p))
4755 p++;
4757 return assuan_write_status (ctx, keyword, *p ? p : NULL);
4759 #endif
4761 static gpg_error_t
4762 kill_command (assuan_context_t ctx, char *line)
4764 struct client_s *client = assuan_get_pointer (ctx);
4765 gpg_error_t rc;
4766 unsigned i, t;
4768 if (!line || !*line)
4769 return send_error (ctx, GPG_ERR_SYNTAX);
4771 MUTEX_LOCK (&cn_mutex);
4772 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
4773 t = slist_length (cn_thread_list);
4774 rc = GPG_ERR_ESRCH;
4776 for (i = 0; i < t; i++)
4778 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
4779 char *tmp = str_asprintf ("%p", thd->tid);
4781 if (strcmp (line, tmp))
4783 xfree (tmp);
4784 continue;
4787 xfree (tmp);
4788 rc = peer_is_invoker (client);
4789 if (!rc)
4791 #ifdef HAVE_PTHREAD_CANCEL
4792 rc = pthread_cancel (thd->tid);
4793 #else
4794 close (thd->fd);
4795 thd->fd = -1;
4796 #endif
4797 break;
4800 rc = GPG_ERR_EACCES;
4801 if (config_get_boolean ("global", "strict_kill"))
4802 break;
4804 #ifdef WITH_GNUTLS
4805 if (client->thd->remote && thd->remote)
4807 if (!strcmp (client->thd->tls->fp, thd->tls->fp))
4809 #ifdef HAVE_PTHREAD_CANCEL
4810 rc = pthread_cancel (thd->tid);
4811 #else
4812 close (thd->fd);
4813 thd->fd = -1;
4814 #endif
4815 break;
4818 else if (!client->thd->remote && !thd->remote)
4819 #endif
4821 if (client->thd->peer->uid == thd->peer->uid)
4823 #ifdef HAVE_PTHREAD_CANCEL
4824 rc = pthread_cancel (thd->tid);
4825 #else
4826 close (thd->fd);
4827 thd->fd = -1;
4828 #endif
4831 break;
4834 pthread_cleanup_pop (1);
4835 return send_error (ctx, rc);
4838 static gpg_error_t
4839 agent_command (assuan_context_t ctx, char *line)
4841 gpg_error_t rc = 0;
4843 if (!use_agent)
4844 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
4846 #ifdef WITH_AGENT
4847 struct client_s *client = assuan_get_pointer (ctx);
4849 if (!line || !*line)
4850 return send_error (ctx, GPG_ERR_SYNTAX);
4852 assuan_set_flag (client->crypto->agent->ctx, ASSUAN_CONVEY_COMMENTS, 1);
4853 rc = assuan_transact (client->crypto->agent->ctx, line, send_data_cb,
4854 client->ctx, agent_loopback_cb, client->crypto,
4855 send_status_cb, client->ctx);
4856 if (gpg_err_code (rc) == GPG_ERR_ASS_CANCELED)
4858 char *line;
4859 size_t len;
4861 rc = assuan_write_line (client->crypto->agent->ctx, "CAN");
4862 if (!rc)
4864 rc = assuan_read_line (client->crypto->agent->ctx, &line, &len);
4865 if (!rc)
4866 rc = gpg_error (GPG_ERR_ASS_CANCELED);
4870 assuan_set_flag (client->crypto->agent->ctx, ASSUAN_CONVEY_COMMENTS, 0);
4871 #endif
4872 return send_error (ctx, rc);
4875 void
4876 init_commands ()
4878 /* !BEGIN-HELP-TEXT!
4880 * This comment is used as a marker to generate the offline documentation
4881 * found in doc/pwmd.info. The indentation needs to be kept for the awk
4882 * script to determine where commands begin and end.
4884 new_command("HELP", 1, 1, 0, help_command, _(
4885 "HELP [<COMMAND>]\n"
4886 "Show available commands or command specific help text."
4889 new_command("AGENT", 1, 1, 0, agent_command, _(
4890 "AGENT <command>\n"
4891 "Send a @command{gpg-agent} protocol @var{command} directly to the "
4892 "@command{gpg-agent}."
4895 new_command("KILL", 1, 0, 0, kill_command, _(
4896 "KILL <thread_id>\n"
4897 "Terminates the client identified by @var{thread_id} and releases any file "
4898 "lock or other resources it has held. See @code{GETINFO} (@pxref{GETINFO}) "
4899 "for details about listing connected clients. The @code{invoking_user} "
4900 "(@pxref{Configuration}) may kill any client while others may only kill "
4901 "clients of the same @code{UID} or @abbr{TLS} fingerprint.\n"
4904 new_command("GETINFO", 1, 1, 0, getinfo_command, _(
4905 "GETINFO [--data] [--verbose] CACHE | CLIENTS | PID | USER | LAST_ERROR | VERSION\n"
4906 "Get server and other information: @var{CACHE} returns the number of cached "
4907 "documents via a status message. @var{CLIENTS} returns the number of "
4908 "connected clients via a status message or a list of connected clients when "
4909 "the @option{--verbose} parameter is used. The list contains space delimited "
4910 "fields: the thread ID, client name, opened file (@code{/} if none opened), "
4911 "file lock status, whether the current client is self, client state, "
4912 "user ID or TLS fingerprint of the connected client and username if the "
4913 "client is a local one. "
4914 "Client state @code{0} is an unknown client state, @code{1} indicates the "
4915 "client has connected but hasn't completed initializing, @code{2} indicates "
4916 "that the client is idle, @code{3} means the "
4917 "client is in a command and @code{4} means the client is disconnecting. This "
4918 "line is always returned with a data response. @var{PID} returns the process "
4919 "ID number of the server via a data response. @var{VERSION} returns the server "
4920 "version number and compile-time features with a data response with each "
4921 "being space delimited. @var{LAST_ERROR} returns a detailed description of "
4922 "the last failed command when available. @var{USER} returns the username or "
4923 "@abbr{TLS} hash of the connected client. @xref{Status Messages}. "
4924 "\n"
4925 "When the @option{--data} option is specified then the result will be sent "
4926 "via a data response rather than a status message."
4929 new_command("PASSWD", 0, 0, FLOCK_TYPE_EX|FLOCK_TYPE_KEEP, passwd_command, _(
4930 "PASSWD [--reset] [--s2k-count=N] [--no-passphrase]\n"
4931 "Changes the passphrase of the secret key required to open the current "
4932 "file or the passphrase of a symmetrically encrypted data file. When the "
4933 "@option{--reset} option is passed then the cache entry for the current "
4934 "file will be reset and the passphrase, if any, will be required during the "
4935 "next @code{OPEN} (@pxref{OPEN})."
4936 "\n"
4937 "The @option{--s2k-count} option sets or changes (@pxref{SAVE}) the number "
4938 "of hash iterations for a passphrase and must be either @code{0} to use "
4939 "the calibrated count of the machine (the default), or a value greater than "
4940 "or equal to @code{65536}. This option has no effect for symmetrically "
4941 "encrypted data files."
4942 "\n"
4943 "The @option{--no-passphrase} option will prevent requiring a passphrase for "
4944 "the data file, although a passphrase may be required when changing it."
4945 "\n"
4946 "This command is not available for non-invoking clients "
4947 "(@pxref{Access Control})."
4950 new_command("KEYGRIP", 1, 1, FLOCK_TYPE_SH|FLOCK_TYPE_KEEP, keygrip_command, _(
4951 "KEYGRIP [--sign] <filename>\n"
4952 "Returns the hex encoded keygrip of the specified @var{filename} with a "
4953 "data response."
4954 "\n"
4955 "When the @option{--sign} option is specified then the key used for signing "
4956 "of the specified @var{filename} will be returned."
4957 "\n"
4958 "For symmetrically encrypted data files this command returns the error "
4959 "GPG_ERR_NOT_SUPPORTED."
4962 new_command("OPEN", 1, 1, FLOCK_TYPE_SH|FLOCK_TYPE_KEEP, open_command, _(
4963 "OPEN [--lock] <filename> [<passphrase>]\n"
4964 "Opens @var{filename} using @var{passphrase}. When the filename is not "
4965 "found on the file-system then a new document will be created. If the file "
4966 "is found, it is looked for in the file cache. If cached and no "
4967 "@var{passphrase} was specified then the cached document is opened. When not "
4968 "cached, @cite{pinentry(1)} will be used to retrieve the passphrase to use "
4969 "for decryption unless @option{disable-pinentry} (@pxref{OPTION}) was "
4970 "specified."
4971 "\n"
4972 "When the @option{--lock} option is passed then the file mutex will be "
4973 "locked as if the @code{LOCK} command (@pxref{LOCK}) had been sent after the "
4974 "file has been opened."
4977 new_command("SAVE", 0, 0, FLOCK_TYPE_EX|FLOCK_TYPE_KEEP, save_command, _(
4978 "SAVE [--no-passphrase] [--reset] [--ask] [--no-agent] [--s2k-count=N] [--cipher=<algo>] [--cipher-iterations=N] [--inquire-keyparam] [--keygrip=hexstring] [--sign-keygrip=hexstring]\n"
4979 "Writes the @abbr{XML} document to disk. The file written to is the file that "
4980 "was opened using the @code{OPEN} command (@pxref{OPEN}). If the file is a "
4981 "new one or the option @option{--inquire-keyparam} was passed, then a new "
4982 "keypair will be generated and a pinentry will be used to prompt for the "
4983 "passphrase to encrypt with unless the @option{--no-passphrase} option was "
4984 "passed in which case the data file will not be passphrase protected. "
4985 "\n"
4986 "The @option{--no-agent} option disables use of @command{gpg-agent} for "
4987 "passphrase retrieval and caching of new files when @command{gpg-agent} "
4988 "use is enabled. The datafile will be symmetrically encrypted and will not "
4989 "use or generate any keypair."
4990 "\n"
4991 "The @option{--reset} option will clear the cache entry for the current file "
4992 "and require a passphrase, if needed, before saving."
4993 "\n"
4994 "The @option{--ask} option will prompt for the passphrase of the current file, "
4995 "if needed, before saving. This differs from the @option{--reset} option by "
4996 "keeping the cache entry in case of an invalid passphrase or some other failure "
4997 "which may otherwise cause a denial of service for other clients."
4998 "\n"
4999 "The @option{--cipher} option can be used to encrypt the @abbr{XML} data to "
5000 "an alternate cipher. The default is @code{aes256}. See the Configuration "
5001 "(@pxref{Configuration}) for available ciphers."
5002 "\n"
5003 "The @option{--cipher-iterations} option specifies the number of times to "
5004 "hash the passphrase before encrypting the XML data. The default is "
5005 "@code{5000000}. This option is an alias for @option{--s2k-count} since "
5006 "version @var{3.0.15} of @command{pwmd}."
5007 "\n"
5008 "The @option{--inquire-keyparam} option will send a server @emph{INQUIRE} to "
5009 "the client to obtain the key paramaters to use when generating a new "
5010 "keypair. The inquired data is expected to be an S-expression. If not "
5011 "specified then an @samp{RSA} key of @samp{2048} bits will be generated "
5012 "unless otherwise set in the configuration file (@pxref{Configuration}). Note "
5013 "that when this option is specified a new keypair will be generated "
5014 "reguardless if the file is a new one and that if the data file is protected "
5015 "the passphrase to open it will be required before generating the new "
5016 "keypair. This option is not available for non-invoking clients "
5017 "(@pxref{Access Control})."
5018 "\n"
5019 "You can encrypt the data file to a public key other than the one that it "
5020 "was originally encrypted with by passing the @option{--keygrip} option with "
5021 "the hex encoded keygrip of the public key as its argument. The keygrip may "
5022 "be of any key that @command{gpg-agent} knows about. The "
5023 "@option{--sign-keygrip} option may also be used to sign with an alternate "
5024 "secret key. Use the @code{KEYGRIP} (@pxref{KEYGRIP}) command to obtain the "
5025 "keygrip of an existing data file. This option may be needed when using a "
5026 "smartcard. This option has no effect with symmetrically encrypted data "
5027 "files. These options are not available for non-invoking clients "
5028 "(@pxref{Access Control})."
5029 "\n"
5030 "The @option{--s2k-count} option sets number of hash iterations for a "
5031 "passphrase. A value less-than @code{65536} will use the machine calibrated "
5032 "value and is the default when using @command{gpg-agent}. This setting only "
5033 "affects new files when using @command{gpg-agent}. To change the setting use "
5034 "the @code{PASSWD} command (@pxref{PASSWD}). This option is an alias for "
5035 "option @option{--cipher-iterations} when not using @command{gpg-agent}."
5038 new_command("ISCACHED", 1, 0, 0, iscached_command, _(
5039 "ISCACHED [--lock] <filename>\n"
5040 "An @emph{OK} response is returned if the specified @var{filename} is found "
5041 "in the file cache. If not found in the cache but exists on the filesystem "
5042 "then @var{GPG_ERR_NO_DATA} is returned. Otherwise a filesystem error is "
5043 "returned."
5044 "\n"
5045 "The @option{lock} option will lock the file mutex of @var{filename} when the "
5046 "file exists; it does not need to be opened nor cached. The lock will be "
5047 "released when the client exits or sends the @code{UNLOCK} (@pxref{UNLOCK}) "
5048 "command."
5051 new_command("CLEARCACHE", 1, 1, 0, clearcache_command, _(
5052 "CLEARCACHE [<filename>]\n"
5053 "Clears a file cache entry for all or the specified @var{filename}."
5056 new_command("CACHETIMEOUT", 1, 1, 0, cachetimeout_command, _(
5057 "CACHETIMEOUT <filename> <seconds>\n"
5058 "The time in @var{seconds} until @var{filename} will be removed from the "
5059 "cache. @code{-1} will keep the cache entry forever, @code{0} will require "
5060 "the passphrase for each @code{OPEN} or @code{SAVE} command (@pxref{OPEN}, "
5061 "@pxref{SAVE}). @xref{Configuration}, and the @code{cache_timeout} "
5062 "parameter."
5065 new_command("LIST", 0, 1, 0, list_command, _(
5066 "LIST [--inquire] [--no-recurse] [--verbose] [--with-target] [--all] [[!]element[<TAB>[!]child[..]]]\n"
5067 "If no element path is given then a newline separated list of root elements "
5068 "is returned with a data response. If given, then all reachable elements "
5069 "of the specified element path are returned unless the @option{--no-recurse} "
5070 "option is specified. If specified, only the child elements of the element "
5071 "path are returned without recursing into grandchildren. Each resulting "
5072 "element is prefixed with the literal @code{!} character when the element "
5073 "contains no @code{target} attribute. @xref{Target Attribute}, for details."
5074 "\n"
5075 "When the @option{--verbose} option is passed then each element path "
5076 "returned will have zero or more flags appened to it. These flags are "
5077 "delimited from the element path by a single space character. A flag itself "
5078 "is a single character. Flag @code{P} indicates that access to the element "
5079 "is denied. Flag @code{+} indicates that there are child nodes of "
5080 "the current element path. Flag @code{E} indicates that an element of an "
5081 "element path contained in a @var{target} attribute could not be found. Flag "
5082 "@code{O} indicates that a @var{target} attribute recursion limit was reached "
5083 "(@pxref{Configuration}). Flag @code{T} will append the resolved element path "
5084 "of the @var{target} attribute contained in the current element (see below)."
5085 "\n"
5086 "The @option{--with-target} option implies @option{--verbose} and will append "
5087 "an additional flag @code{T} followed by a single space then an element path. "
5088 "The appended element path is the resolved path (@pxref{REALPATH}) of the "
5089 "current element when it contains a @var{target} attribute. When no "
5090 "@var{target} attribute is found then no flag will be appended."
5091 "\n"
5092 "The @option{--no-recurse} option limits the amount of data returned to only "
5093 "the listing of children of the specified element path and not any "
5094 "grandchildren."
5095 "\n"
5096 "The @option{--all} option lists the entire element tree for each root "
5097 "element. This option also implies option @option{--verbose}."
5098 "\n"
5099 "When the @option{--inquire} option is passed then all remaining non-option "
5100 "arguments are retrieved via a server @emph{INQUIRE}."
5103 new_command("REALPATH", 0, 1, 0, realpath_command, _(
5104 "REALPATH [--inquire] [!]element[<TAB>[!]child[..]]\n"
5105 "Resolves all @code{target} attributes of the specified element path and "
5106 "returns the result with a data response. @xref{Target Attribute}, for details."
5107 "\n"
5108 "When the @option{--inquire} option is passed then all remaining non-option "
5109 "arguments are retrieved via a server @emph{INQUIRE}."
5112 new_command("STORE", 0, 1, 0, store_command, _(
5113 "STORE [!]element[<TAB>[!]child[..]]<TAB>[content]\n"
5114 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
5115 "\n"
5116 "Creates a new element path or modifies the @var{content} of an existing "
5117 "element. If only a single element is specified then a new root element is "
5118 "created. Otherwise, elements are @key{TAB} delimited and the content will be "
5119 "set to the final @key{TAB} delimited element. If no @var{content} is "
5120 "specified after the final @key{TAB}, then the content of an existing "
5121 "element will be removed; or empty when creating a new element."
5122 "\n"
5123 "The only restriction of an element name is that it not contain whitespace "
5124 "or begin with the literal element character @code{!} unless specifying a "
5125 "literal element (@pxref{Target Attribute}). There is no whitespace between "
5126 "the @key{TAB} delimited elements. It is recommended that the content of an "
5127 "element be base64 encoded when it contains control or @key{TAB} characters "
5128 "to prevent @abbr{XML} parsing and @command{pwmd} syntax errors."
5131 new_command("RENAME", 0, 1, 0, rename_command, _(
5132 "RENAME [--inquire] [!]element[<TAB>[!]child[..]] <value>\n"
5133 "Renames the specified @var{element} to the new @var{value}. If an element of "
5134 "the same name as the @var{value} already exists it will be overwritten."
5135 "\n"
5136 "When the @option{--inquire} option is passed then all remaining non-option "
5137 "arguments are retrieved via a server @emph{INQUIRE}."
5140 new_command("COPY", 0, 1, 0, copy_command, _(
5141 "COPY [--inquire] [!]source[<TAB>[!]child[..]] [!]dest[<TAB>[!]child[..]]\n"
5142 "Copies the entire element tree starting from the child node of the source "
5143 "element, to the destination element path. If the destination element path "
5144 "does not exist then it will be created; otherwise it is overwritten."
5145 "\n"
5146 "Note that attributes from the source element are merged into the "
5147 "destination element when the destination element path exists. When an "
5148 "attribute of the same name exists in both the source and destination "
5149 "elements then the destination attribute will be updated to the source "
5150 "attribute value."
5151 "\n"
5152 "When the @option{--inquire} option is passed then all remaining non-option "
5153 "arguments are retrieved via a server @emph{INQUIRE}."
5156 new_command("MOVE", 0, 1, 0, move_command, _(
5157 "MOVE [--inquire] [!]source[<TAB>[!]child[..]] [[!]dest[<TAB>[!]child[..]]]\n"
5158 "Moves the source element path to the destination element path. If the "
5159 "destination is not specified then it will be moved to the root node of the "
5160 "document. If the destination is specified and exists then it will be "
5161 "overwritten; otherwise non-existing elements of the destination element "
5162 "path will be created."
5163 "\n"
5164 "When the @option{--inquire} option is passed then all remaining non-option "
5165 "arguments are retrieved via a server @emph{INQUIRE}."
5168 new_command("DELETE", 0, 1, 0, delete_command, _(
5169 "DELETE [--inquire] [!]element[<TAB>[!]child[..]]\n"
5170 "Removes the specified element path and all of its children. This may break "
5171 "an element with a @code{target} attribute (@pxref{Target Attribute}) that "
5172 "refers to this element or any of its children."
5173 "\n"
5174 "When the @option{--inquire} option is passed then all remaining non-option "
5175 "arguments are retrieved via a server @emph{INQUIRE}."
5178 new_command("GET", 0, 1, 0, get_command, _(
5179 "GET [--inquire] [!]element[<TAB>[!]child[..]]\n"
5180 "Retrieves the content of the specified element. The content is returned "
5181 "with a data response."
5182 "\n"
5183 "When the @option{--inquire} option is passed then all remaining non-option "
5184 "arguments are retrieved via a server @emph{INQUIRE}."
5187 new_command("ATTR", 0, 1, 0, attr_command, _(
5188 "ATTR [--inquire] SET|GET|DELETE|LIST [<attribute>] [!]element[<TAB>[!]child[..]] ..\n"
5189 "@table @asis\n"
5190 "@item ATTR SET attribute [!]element[<TAB>[!]child[..]] [value]\n"
5191 "\n"
5192 " Stores or updates an @var{attribute} name and optional @var{value} of an "
5193 "element. When no @var{value} is specified any existing value will be removed."
5194 "\n"
5195 "@item ATTR DELETE attribute [!]element[<TAB>[!]child[..]]\n"
5196 "\n"
5197 " Removes an @var{attribute} from an element."
5198 "\n"
5199 "@item ATTR LIST [!]element[<TAB>[!]child[..]]\n"
5200 "\n"
5201 " Retrieves a newline separated list of attributes names and values "
5202 "from the specified element. Each attribute name and value is space delimited."
5203 "\n"
5204 "@item ATTR GET attribute [!]element[<TAB>[!]child[..]]\n"
5205 "\n"
5206 " Retrieves the value of an @var{attribute} from an element."
5207 "@end table\n"
5208 "\n"
5209 "The @code{_name} attribute (case sensitive) cannot be removed nor modified. "
5210 "Use the @code{DELETE} (@pxref{DELETE}) or @code{RENAME} (@pxref{RENAME}) "
5211 "commands instead."
5212 "\n"
5213 "The @code{_mtime} attribute is updated each time an element is modified by "
5214 "either storing content, editing attributes or by deleting a child element. "
5215 "The @code{_ctime} attribute is created for each new element in an element "
5216 "path."
5217 "\n"
5218 "When the @option{--inquire} option is passed then all remaining non-option "
5219 "arguments are retrieved via a server @emph{INQUIRE}."
5220 "\n"
5221 "@xref{Target Attribute}, for details about this special attribute."
5224 new_command("XPATH", 0, 1, 0, xpath_command, _(
5225 "XPATH [--inquire] <expression>[<TAB>[value]]\n"
5226 "Evaluates an XPath @var{expression}. If no @var{value} argument is "
5227 "specified it is assumed the expression is a request to return a result. "
5228 "Otherwise, the result is set to the @var{value} argument and the document is "
5229 "updated. If there is no @var{value} after the @key{TAB} character, the value "
5230 "is assumed to be empty and the document is updated. For example:"
5231 "@sp 1\n"
5232 "@example\n"
5233 "XPATH //element[@@_name='password']@key{TAB}\n"
5234 "@end example\n"
5235 "@sp 1"
5236 "would clear the content of all @code{password} elements in the data file "
5237 "while leaving off the trailing @key{TAB} would return all @code{password} "
5238 "elements in @abbr{XML} format."
5239 "\n"
5240 "When the @option{--inquire} option is passed then all remaining non-option "
5241 "arguments are retrieved via a server @emph{INQUIRE}."
5242 "\n"
5243 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
5244 "expression syntax."
5247 new_command("XPATHATTR", 0, 1, 0, xpathattr_command, _(
5248 "XPATHATTR [--inquire] SET|DELETE <name> <expression>[<TAB>[<value>]]\n"
5249 "Like the @code{XPATH} command (@pxref{XPATH}) but operates on element "
5250 "attributes and does not return a result. For the @var{SET} operation the "
5251 "@var{value} is optional but the field is required. If not specified then "
5252 "the attribute value will be empty. For example:"
5253 "@sp 1"
5254 "@example\n"
5255 "XPATHATTR SET password //element[@@_name='password']@key{TAB}\n"
5256 "@end example\n"
5257 "@sp 1"
5258 "would create an @code{password} attribute for each @code{password} element "
5259 "found in the document. The attribute value will be empty but still exist."
5260 "\n"
5261 "When the @option{--inquire} option is passed then all remaining non-option "
5262 "arguments are retrieved via a server @emph{INQUIRE}."
5263 "\n"
5264 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
5265 "expression syntax."
5268 new_command("IMPORT", 0, 1, 0, import_command, _(
5269 "IMPORT [--root=[!]element[<TAB>[!]child[..]]] <content>\n"
5270 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
5271 "\n"
5272 "Like the @code{STORE} command (@pxref{STORE}), but the @var{content} "
5273 "argument is raw @abbr{XML} data. The content is created as a child of "
5274 "the element path specified with the @option{--root} option or at the "
5275 "document root when not specified. Existing elements of the same name will "
5276 "be overwritten."
5277 "\n"
5278 "The content must begin with an @abbr{XML} element node. @xref{Introduction}, "
5279 "for details."
5282 new_command("DUMP", 0, 1, 0, dump_command, _(
5283 "DUMP\n"
5284 "Shows the in memory @abbr{XML} document with indenting. @xref{XPATH}, for "
5285 "dumping a specific node."
5288 new_command("LOCK", 0, 0, 0, lock_command, _(
5289 "LOCK\n"
5290 "Locks the mutex associated with the opened file. This prevents other clients "
5291 "from sending commands to the same opened file until the client "
5292 "that sent this command either disconnects or sends the @code{UNLOCK} "
5293 "command. @xref{UNLOCK}."
5296 new_command("UNLOCK", 1, 0, 0, unlock_command, _(
5297 "UNLOCK\n"
5298 "Unlocks the file mutex which was locked with the @code{LOCK} command or "
5299 "a commands' @option{--lock} option (@pxref{LOCK}, @pxref{OPEN}, "
5300 "@pxref{ISCACHED})."
5303 new_command("GETCONFIG", 1, 1, FLOCK_TYPE_SH|FLOCK_TYPE_KEEP, getconfig_command, _(
5304 "GETCONFIG [filename] <parameter>\n"
5305 "Returns the value of a @command{pwmd} configuration @var{parameter} with a "
5306 "data response. If no file has been opened then the value for @var{filename} "
5307 "or the default from the @samp{global} section will be returned. If a file "
5308 "has been opened and no @var{filename} is specified, a value previously "
5309 "set with the @code{OPTION} command (@pxref{OPTION}) will be returned."
5312 new_command("OPTION", 1, 1, 0, option_command, _(
5313 "OPTION <NAME>=<VALUE>\n"
5314 "Sets a client option @var{name} to @var{value}. The value for an option is "
5315 "kept for the duration of the connection."
5316 "\n"
5317 "@table @asis\n"
5318 "@item DISABLE-PINENTRY\n"
5319 "Disable use of @command{pinentry} for passphrase retrieval. When set, a "
5320 "server inquire is sent to the client to obtain the passphrase. This option "
5321 "may be set as needed before the @code{OPEN} (@pxref{OPEN}), @code{PASSWD} "
5322 "(@pxref{PASSWD}) and @code{SAVE} (@pxref{SAVE}) commands."
5323 "\n"
5324 "@item PINENTRY-TIMEOUT\n"
5325 "Sets the number of seconds before a pinentry prompt will return an error "
5326 "while waiting for user input."
5327 "\n"
5328 "@item TTYNAME\n"
5329 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
5330 "\n"
5331 "@item TTYTYPE\n"
5332 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
5333 "\n"
5334 "@item DISPLAY\n"
5335 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
5336 "\n"
5337 "@item PINENTRY-DESC\n"
5338 "Sets the description string of the @command{gpg-agent} and @command{pinentry} dialog."
5339 "\n"
5340 "@item PINENTRY-TITLE\n"
5341 "Sets the title string of the @command{gpg-agent} and @command{pinentry} dialog."
5342 "\n"
5343 "@item PINENTRY-PROMPT\n"
5344 "Sets the prompt string of the @command{gpg-agent} and @command{pinentry} dialog."
5345 "\n"
5346 "@item LC-CTYPE\n"
5347 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
5348 "\n"
5349 "@item LC-MESSAGES\n"
5350 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
5351 "\n"
5352 "@item NAME\n"
5353 "Associates the thread ID of the connection with the specified textual "
5354 "representation. Useful for debugging log messages. May not contain whitespace."
5355 "\n"
5356 "@item LOCK-TIMEOUT\n"
5357 "When not @code{0}, the duration in tenths of a second to wait for the file "
5358 "mutex which has been locked by another thread to be released before returning "
5359 "an error. When @code{-1}, then an error will be returned immediately."
5360 "@end table\n"
5363 new_command("LS", 1, 1, 0, ls_command, _(
5364 "LS\n"
5365 "Lists the available data files stored in the data directory "
5366 "(@file{~/.pwmd/data}). The result is a newline separated list of filenames."
5369 new_command("RESET", 1, 1, 0, NULL, _(
5370 "RESET\n"
5371 "Closes the currently opened file but keeps any previously set client options."
5374 new_command("NOP", 1, 1, 0, NULL, _(
5375 "NOP\n"
5376 "Does nothing. Always returns successfully."
5379 /* !END-HELP-TEXT! */
5380 new_command ("CANCEL", 1, 1, 0, NULL, NULL);
5381 new_command ("END", 1, 1, 0, NULL, NULL);
5382 new_command ("BYE", 1, 1, 0, NULL, NULL);
5384 int i;
5385 for (i = 0; command_table[i]; i++);
5386 qsort (command_table, i - 1, sizeof (struct command_table_s *),
5387 sort_commands);
5390 gpg_error_t
5391 register_commands (assuan_context_t ctx)
5393 int i = 0, rc;
5395 for (; command_table[i]; i++)
5397 if (!command_table[i]->handler)
5398 continue;
5400 rc = assuan_register_command (ctx, command_table[i]->name,
5401 command_table[i]->handler,
5402 command_table[i]->help);
5403 if (rc)
5404 return rc;
5407 rc = assuan_register_bye_notify (ctx, bye_notify);
5408 if (rc)
5409 return rc;
5411 rc = assuan_register_reset_notify (ctx, reset_notify);
5412 if (rc)
5413 return rc;
5415 rc = assuan_register_pre_cmd_notify (ctx, command_startup);
5416 if (rc)
5417 return rc;
5419 return assuan_register_post_cmd_notify (ctx, command_finalize);