Fix a few cppcheck warnings.
[pwmd.git] / src / commands.c
blobf3fcd192f85477fb7dab96b09168d5b5196b0d68
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>
36 #include <assert.h>
38 #ifdef WITH_LIBACL
39 #include <sys/acl.h>
40 #endif
42 #include "pwmd-error.h"
43 #include <gcrypt.h>
45 #include "mem.h"
46 #include "xml.h"
47 #include "util-misc.h"
48 #include "common.h"
49 #include "rcfile.h"
50 #include "cache.h"
51 #include "commands.h"
52 #include "mutex.h"
53 #include "crypto.h"
54 #include "pinentry.h"
56 /* These are command option flags. */
57 #define OPT_INQUIRE 0x0001
58 #define OPT_NO_PASSPHRASE 0x0002
59 #define OPT_RESET 0x0004
60 #define OPT_LIST_RECURSE 0x0008
61 #define OPT_VERBOSE 0x0010
62 #define OPT_LOCK 0x0020
63 #define OPT_LOCK_ON_OPEN 0x0040
64 #define OPT_SIGN 0x0080
65 #define OPT_LIST_ALL 0x0100
66 #define OPT_LIST_WITH_TARGET 0x0200
67 #define OPT_DATA 0x0400
68 #define OPT_NO_AGENT 0x0800
69 #define OPT_ASK 0x1000
71 #ifdef WITH_AGENT
72 /* The GETCONFIG command, for example, may fail because pwmd lost the
73 * gpg-agent connection. Update the recovered agent ctx. */
74 #define UPDATE_AGENT_CTX(client, crypto) do { \
75 if (crypto && crypto->agent && crypto->agent->did_restart \
76 && client->crypto && client->crypto->agent \
77 && client->crypto->agent->ctx && \
78 crypto->agent->ctx != client->crypto->agent->ctx) \
79 { \
80 client->crypto->agent->ctx = crypto->agent->ctx; \
81 crypto->agent->ctx = NULL; \
82 } \
83 } while (0)
84 #else
85 #define UPDATE_AGENT_CTX(client, crypto)
86 #endif
88 #define FLOCK_TYPE_NONE 0
89 #define FLOCK_TYPE_SH 0x0001
90 #define FLOCK_TYPE_EX 0x0002
91 #define FLOCK_TYPE_KEEP 0x0004
93 struct command_table_s
95 const char *name;
96 gpg_error_t (*handler) (assuan_context_t, char *line);
97 const char *help;
98 int ignore_startup;
99 int unlock; // unlock the file mutex after validating the checksum
100 uint32_t flock_type;
103 static struct command_table_s **command_table;
105 static gpg_error_t do_lock (struct client_s *client, int add);
106 static gpg_error_t validate_checksum (struct client_s *,
107 struct cache_data_s *);
108 static gpg_error_t update_checksum (struct client_s *client);
110 /* When 'status' is true the 'self' field of the status line will be false
111 * because we never send the STATE status message to the same client that
112 * initiated it. */
113 static char *
114 build_client_info_line (struct client_thread_s *thd, int status)
116 MUTEX_LOCK (&cn_mutex);
117 int with_state = config_get_boolean ("global", "send_state");
118 char *uid, *username = NULL;
119 char *line;
121 #ifdef WITH_GNUTLS
122 if (thd->remote)
123 uid = str_asprintf("#%s", thd->tls->fp);
124 else
126 uid = str_asprintf("%u", thd->peer->uid);
127 username = get_username (thd->peer->uid);
129 #else
130 uid = str_asprintf("%u", thd->peer->uid);
131 username = get_username (thd->peer->uid);
132 #endif
133 line = str_asprintf ("%p %s %s %s %u %u %u %s %s",
134 thd->tid,
135 thd->name ? thd->name : "-",
136 thd->cl && thd->cl->filename
137 && (thd->cl->flags & FLAG_OPEN)
138 ? thd->cl->filename : "/",
139 #ifdef WITH_GNUTLS
140 thd->remote ? thd->peeraddr : "-",
141 #else
142 "-",
143 #endif
144 thd->cl && thd->cl->flags & FLAG_HAS_LOCK ? 1 : 0,
145 !status && pthread_equal (pthread_self (), thd->tid) ? 1 : 0,
146 with_state ? thd->state : CLIENT_STATE_UNKNOWN, uid,
147 #ifdef WITH_GNUTLS
148 thd->remote ? "" : username
149 #else
150 username
151 #endif
154 xfree (username);
155 xfree (uid);
156 MUTEX_UNLOCK (&cn_mutex);
157 return line;
160 void
161 update_client_state (struct client_s *client, unsigned s)
163 client->thd->state = s;
164 int n = config_get_boolean ("global", "send_state");
166 if (n && client->thd->state != CLIENT_STATE_UNKNOWN)
168 char *line = build_client_info_line (client->thd, 1);
170 if (line)
171 send_status_all_not_self (n == 2, STATUS_STATE, "%s", line);
175 static gpg_error_t
176 unlock_file_mutex (struct client_s *client, int remove)
178 gpg_error_t rc = 0;
180 // OPEN: keep the lock for the same file being reopened.
181 if (client->flags & FLAG_KEEP_LOCK && client->flags & FLAG_HAS_LOCK)
182 return 0;
184 if (!(client->flags & FLAG_HAS_LOCK))
185 return GPG_ERR_NOT_LOCKED;
187 rc = cache_unlock_mutex (client->md5file, remove);
188 if (rc)
189 rc = GPG_ERR_INV_STATE;
190 else
191 client->flags &= ~(FLAG_HAS_LOCK | FLAG_LOCK_CMD);
193 return rc;
196 static gpg_error_t
197 lock_file_mutex (struct client_s *client, int add)
199 gpg_error_t rc = 0;
200 int timeout = config_get_integer (client->filename, "cache_timeout");
202 if (client->flags & FLAG_HAS_LOCK)
203 return 0;
205 rc = cache_lock_mutex (client->ctx, client->md5file,
206 client->lock_timeout, add, timeout);
207 if (!rc)
208 client->flags |= FLAG_HAS_LOCK;
210 return rc;
213 static gpg_error_t
214 file_modified (struct client_s *client, struct command_table_s *cmd)
216 gpg_error_t rc = 0;
217 int type = !cmd->flock_type || (cmd->flock_type & FLOCK_TYPE_SH)
218 ? LOCK_SH : LOCK_EX;
220 if (!(client->flags & FLAG_OPEN))
221 return GPG_ERR_INV_STATE;
223 rc = lock_file_mutex (client, 0);
224 if (rc && rc != GPG_ERR_NO_DATA)
225 return rc;
227 rc = lock_flock (client->ctx, client->filename, type, &client->flock_fd);
228 if (!rc)
230 rc = validate_checksum (client, NULL);
231 if (gpg_err_code (rc) == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
232 rc = 0;
233 else if (rc)
234 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
236 else if (gpg_err_code(rc) == GPG_ERR_ENOENT)
237 rc = 0;
239 if ((cmd->unlock && !(client->flags & FLAG_HAS_LOCK)) || rc)
240 unlock_file_mutex (client, 0);
242 if (rc || !(cmd->flock_type & FLOCK_TYPE_KEEP))
243 unlock_flock (&client->flock_fd);
245 return rc;
248 static gpg_error_t
249 parse_xml (assuan_context_t ctx, int new)
251 struct client_s *client = assuan_get_pointer (ctx);
252 int cached = client->doc != NULL;
253 gpg_error_t rc = 0;
255 if (new)
257 client->doc = new_document ();
258 if (client->doc)
260 xmlChar *result;
261 int len;
263 xmlDocDumpFormatMemory (client->doc, &result, &len, 0);
264 client->crypto->plaintext = result;
265 client->crypto->plaintext_len = len;
266 if (!client->crypto->plaintext)
268 xmlFreeDoc (client->doc);
269 client->doc = NULL;
270 rc = GPG_ERR_ENOMEM;
273 else
274 rc = GPG_ERR_ENOMEM;
276 else if (!cached)
277 rc = parse_doc ((char *) client->crypto->plaintext,
278 client->crypto->plaintext_len, (xmlDocPtr *)&client->doc);
280 return rc;
283 static void
284 free_client (struct client_s *client)
286 if (client->doc)
287 xmlFreeDoc (client->doc);
289 xfree (client->crc);
290 xfree (client->filename);
291 xfree (client->last_error);
293 if (client->crypto)
295 cleanup_crypto_stage2 (client->crypto);
296 if (client->crypto->pkey_sexp)
297 gcry_sexp_release (client->crypto->pkey_sexp);
299 if (client->crypto->sigpkey_sexp)
300 gcry_sexp_release (client->crypto->sigpkey_sexp);
302 client->crypto->pkey_sexp = NULL;
303 client->crypto->sigpkey_sexp = NULL;
304 memset (client->crypto->sign_grip, 0,
305 sizeof (client->crypto->sign_grip));
306 memset (client->crypto->grip, 0, sizeof(client->crypto->grip));
310 void
311 cleanup_client (struct client_s *client)
313 assuan_context_t ctx = client->ctx;
314 struct client_thread_s *thd = client->thd;
315 struct crypto_s *crypto = client->crypto;
316 long lock_timeout = client->lock_timeout;
317 int no_pinentry = (client->flags & FLAG_NO_PINENTRY);
318 struct pinentry_option_s pin_opts;
319 xmlErrorPtr xml_error = client->xml_error;
320 int flock_fd = client->flock_fd;
321 #ifdef WITH_AGENT
322 struct pinentry_option_s agent_pin_opts;
324 if (crypto && crypto->agent)
325 memcpy (&agent_pin_opts, &crypto->agent->pinentry_opts,
326 sizeof(struct pinentry_option_s));
327 #endif
329 memcpy (&pin_opts, &client->pinentry_opts, sizeof(struct pinentry_option_s));
330 unlock_file_mutex (client, client->flags & FLAG_NEW);
331 free_client (client);
332 memset (client, 0, sizeof (struct client_s));
333 client->flock_fd = flock_fd;
334 client->xml_error = xml_error;
335 client->crypto = crypto;
336 client->ctx = ctx;
337 client->thd = thd;
338 client->lock_timeout = lock_timeout;
339 memcpy (&client->pinentry_opts, &pin_opts, sizeof(struct pinentry_option_s));
340 client->flags |= no_pinentry ? FLAG_NO_PINENTRY : 0;
341 #ifdef WITH_AGENT
342 if (crypto && crypto->agent)
343 memcpy (&crypto->agent->pinentry_opts, &agent_pin_opts,
344 sizeof(struct pinentry_option_s));
345 #endif
348 static gpg_error_t
349 open_finalize (assuan_context_t ctx, char *key, size_t keylen)
351 struct client_s *client = assuan_get_pointer (ctx);
352 gpg_error_t rc = 0;
353 struct cache_data_s *cdata = cache_get_data (client->md5file);
354 int cached = 0, keyarg = key ? 1 : 0;
355 size_t keysize;
356 unsigned char *salted_key = NULL;
357 int algo;
358 int pin_try = 1;
359 int pin_tries = 3;
360 char *pin_title = client->pinentry_opts.title;
362 client->crypto->filename = str_dup (client->filename);
363 if (cdata || client->flags & FLAG_NEW)
365 if (cdata && !(client->flags & FLAG_NEW))
367 rc = decrypt_cache (client->crypto, cdata->doc, cdata->doclen);
368 if (rc)
369 return rc;
372 cached = cdata != NULL;
373 goto done;
376 if (!key && !IS_PKI (client->crypto)
377 && !(client->crypto->hdr.flags & PWMD_FLAG_NO_PASSPHRASE))
379 if (client->flags & FLAG_NO_PINENTRY)
381 rc = inquire_passphrase (ctx, "PASSPHRASE", (unsigned char **)&key,
382 &keylen);
383 if (rc)
384 return rc;
386 else
388 client->pinentry_opts.timeout = config_get_integer (client->filename,
389 "pinentry_timeout");
390 pin_again:
391 rc = getpin_common (client->ctx, client->filename, PINENTRY_OPEN,
392 &key, &keylen);
393 if (rc)
394 return rc;
398 if (!IS_PKI (client->crypto))
400 if (client->crypto->hdr.flags & PWMD_FLAG_NO_PASSPHRASE)
402 keylen = 1;
403 key = gcry_malloc (keylen);
404 memset (key, 0, keylen);
407 algo = cipher_to_gcrypt (client->crypto->hdr.flags);
408 rc = hash_key (algo, client->crypto->hdr.salt,
409 sizeof(client->crypto->hdr.salt), key, keylen,
410 (void **)&salted_key, &keysize,
411 client->crypto->hdr.version <= 0x03000e ? COMPAT_KDFS2K_ITERATIONS : client->crypto->hdr.s2k_count);
412 if (!keyarg)
413 gcry_free (key);
415 if (!rc)
417 rc = decrypt_data (client->ctx, client->crypto, salted_key, keysize);
418 if (gpg_err_code (rc) == GPG_ERR_BAD_PASSPHRASE
419 && ++pin_try <= pin_tries && !(client->flags & FLAG_NO_PINENTRY))
421 gcry_free (salted_key);
422 salted_key = NULL;
423 key = NULL;
424 keylen = 0;
425 client->pinentry_opts.title = str_asprintf (_ ("Bad passphrase (try %i of %i)"), pin_try, pin_tries);
426 goto pin_again;
430 if (client->pinentry_opts.title != pin_title)
431 xfree (client->pinentry_opts.title);
433 client->pinentry_opts.title = pin_title;
434 if (rc)
436 gcry_free (salted_key);
437 return rc;
440 cdata = xcalloc (1, sizeof (struct cache_data_s));
441 if (!cdata)
443 gcry_free (salted_key);
444 return GPG_ERR_ENOMEM;
447 cdata->key = salted_key;
448 cdata->keylen = keysize;
450 else
451 #ifdef WITH_AGENT
452 rc = decrypt_data (client->ctx, client->crypto, NULL, 0);
453 #else
454 rc = GPG_ERR_NOT_IMPLEMENTED;
455 #endif
457 done:
458 if (!rc)
460 rc = parse_xml (ctx, client->flags & FLAG_NEW);
461 if (rc && !cached)
462 free_cache_data_once (cdata);
464 if (!rc)
466 int timeout = config_get_integer (client->filename,
467 "cache_timeout");
469 if (!cached)
471 if (!cdata)
472 cdata = xcalloc (1, sizeof (struct cache_data_s));
474 rc = encrypt_xml (NULL, cache_key, cache_keysize,
475 GCRY_CIPHER_AES, client->crypto->plaintext,
476 client->crypto->plaintext_len, &cdata->doc,
477 &cdata->doclen, &cache_iv, &cache_blocksize);
478 if (!rc && !(client->flags & FLAG_NEW) && IS_PKI (client->crypto))
480 rc = gcry_sexp_build ((gcry_sexp_t *) & cdata->pubkey, NULL,
481 "%S", client->crypto->pkey_sexp);
485 if (cdata->sigkey)
486 gcry_sexp_release (cdata->sigkey);
488 cdata->sigkey = NULL;
489 if (!rc && IS_PKI (client->crypto))
490 rc = gcry_sexp_build ((gcry_sexp_t *) &cdata->sigkey, NULL,
491 "%S", client->crypto->sigpkey_sexp);
493 if (!rc)
495 rc = cache_add_file (client->md5file,
496 (client->flags & FLAG_NEW) ? NULL
497 : client->crypto->grip, cdata, timeout);
498 if (rc)
500 if (!cached)
502 free_cache_data_once (cdata);
503 xmlFreeDoc (client->doc);
504 client->doc = NULL;
509 if (!rc)
510 client->flags |= FLAG_OPEN;
514 if (!rc)
516 rc = update_checksum (client);
517 if (gpg_err_code (rc) == GPG_ERR_ENOENT)
518 rc = 0;
521 if (!rc && (client->opts & OPT_LOCK_ON_OPEN))
522 rc = do_lock (client, 0);
524 return rc;
527 static void
528 req_cleanup (void *arg)
530 if (!arg)
531 return;
533 strv_free ((char **) arg);
536 static gpg_error_t
537 parse_open_opt_lock (void *data, void *value)
539 struct client_s *client = data;
541 client->opts |= OPT_LOCK_ON_OPEN;
542 return 0;
545 static gpg_error_t
546 parse_save_opt_inquire (void *data, void *value)
548 struct client_s *client = data;
549 gpg_error_t rc;
551 if (!(client->flags & FLAG_NEW))
553 rc = peer_is_invoker (client);
554 if (rc == GPG_ERR_EACCES)
555 return rc;
558 (void) value;
559 client->opts |= OPT_INQUIRE;
560 return 0;
563 static gpg_error_t
564 parse_opt_inquire (void *data, void *value)
566 struct client_s *client = data;
568 (void) value;
569 client->opts |= OPT_INQUIRE;
570 return 0;
573 static gpg_error_t
574 update_checksum (struct client_s *client)
576 unsigned char *crc;
577 size_t len;
578 struct cache_data_s *cdata;
579 gpg_error_t rc = get_checksum (client->filename, &crc, &len);
581 if (rc)
582 return rc;
584 xfree (client->crc);
585 client->crc = crc;
586 cdata = cache_get_data (client->md5file);
587 if (cdata)
589 xfree (cdata->crc);
590 cdata->crc = xmalloc (len);
591 memcpy (cdata->crc, crc, len);
594 return 0;
597 static gpg_error_t
598 validate_checksum (struct client_s *client, struct cache_data_s *cdata)
600 unsigned char *crc;
601 size_t len;
602 gpg_error_t rc;
603 int n = 0;
605 if (cdata && !cdata->crc)
606 return GPG_ERR_CHECKSUM;
608 rc = get_checksum (client->filename, &crc, &len);
609 if (rc)
610 return rc;
612 if (cdata)
613 n = memcmp (cdata->crc, crc, len);
614 else if (client->crc)
615 n = memcmp (client->crc, crc, len);
617 xfree (crc);
618 return n ? GPG_ERR_CHECKSUM : 0;
621 static gpg_error_t
622 do_open (assuan_context_t ctx, const char *password)
624 struct client_s *client = assuan_get_pointer (ctx);
625 struct cache_data_s *cdata;
626 gpg_error_t rc = 0;
627 int done = 0;
629 // Cached document?
630 cdata = cache_get_data (client->md5file);
631 if (cdata && cdata->doc)
633 int defer = 0;
635 /* This will check that the key is cached in the agent which needs to
636 * be determined for files that share a keygrip. */
637 if (!rc)
639 rc = cache_iscached (client->filename, &defer);
640 if ((!rc || rc == GPG_ERR_ENOENT) && defer)
641 rc = GPG_ERR_KEY_EXPIRED;
644 if (!rc && !(client->flags & FLAG_NEW))
645 rc = validate_checksum (client, cdata);
647 #ifdef WITH_GNUTLS
648 if (!rc && client->thd->remote
649 && config_get_boolean (client->filename, "tcp_require_key"))
650 rc = crypto_try_decrypt (ctx, client->flags & FLAG_NO_PINENTRY,
651 client->filename, NULL, NULL, NULL);
652 #endif
654 if (!rc && !password)
656 rc = read_data_header (client->filename, &client->crypto->hdr,
657 NULL, NULL);
658 if (!rc)
660 if (IS_PKI (client->crypto))
662 gcry_sexp_build (&client->crypto->pkey_sexp, NULL, "%S",
663 cdata->pubkey);
664 gcry_pk_get_keygrip (client->crypto->pkey_sexp,
665 client->crypto->grip);
666 gcry_sexp_build (&client->crypto->sigpkey_sexp, NULL, "%S",
667 cdata->sigkey);
668 gcry_pk_get_keygrip (client->crypto->sigpkey_sexp,
669 client->crypto->sign_grip);
672 if (!rc)
674 rc = open_finalize (ctx, NULL, 0);
675 done = 1;
680 /* There was an error accessing the file so clear the cache entry. The
681 * real error will be returned from read_data_file() since the file
682 * may have only disappeared. */
683 if (!done)
685 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
686 rc = cache_clear (client->md5file);
687 send_status_all (STATUS_CACHE, NULL);
691 if (done || rc)
692 return rc;
694 rc = read_data_file (client->filename, client->crypto);
695 if (rc)
697 if (gpg_err_source (rc) != GPG_ERR_SOURCE_DEFAULT ||
698 gpg_err_code (rc) != GPG_ERR_ENOENT)
700 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
701 return rc;
704 client->flags |= FLAG_NEW;
705 memset (client->crypto->grip, 0, sizeof (client->crypto->grip));
706 memset (client->crypto->sign_grip, 0,
707 sizeof (client->crypto->sign_grip));
708 rc = open_finalize (ctx, NULL, 0);
709 return rc;
712 if (password && IS_PKI (client->crypto))
714 #ifdef WITH_AGENT
715 rc = set_agent_passphrase (client->crypto, password, strlen (password));
716 if (rc)
717 return rc;
718 #endif
721 rc = open_finalize (ctx, (char *)password, password ? strlen (password) : 0);
722 return rc;
725 static gpg_error_t
726 open_command (assuan_context_t ctx, char *line)
728 gpg_error_t rc;
729 struct client_s *client = assuan_get_pointer (ctx);
730 char **req, *filename;
731 unsigned char md5file[16];
732 int same_file = 0;
733 assuan_peercred_t peer;
734 struct argv_s *args[] = {
735 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_open_opt_lock},
736 NULL
739 rc = parse_options (&line, args, client, 1);
740 if (rc)
741 return send_error (ctx, rc);
743 req = str_split (line, " ", 2);
744 if (!req)
745 return send_error (ctx, GPG_ERR_SYNTAX);
747 rc = do_validate_peer (ctx, req[0], &peer);
748 if (rc)
750 strv_free (req);
751 return send_error (ctx, rc);
754 filename = req[0];
755 if (!valid_filename (filename))
757 strv_free (req);
758 return send_error (ctx, GPG_ERR_INV_VALUE);
761 pthread_cleanup_push (req_cleanup, req);
762 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
763 /* This client may have locked a different file with ISCACHED --lock than
764 * the current filename. This will remove that lock. */
765 same_file = !memcmp (md5file, client->md5file, 16) ? 1 : 0;
766 if (client->flags & FLAG_OPEN ||
767 (client->flags & FLAG_HAS_LOCK && !same_file))
769 uint32_t opts = client->opts;
770 uint32_t flags = client->flags;
772 if (same_file)
773 client->flags |= FLAG_KEEP_LOCK;
774 else if (client->flags & FLAG_NEW)
775 cache_clear (client->md5file);
777 cleanup_client (client);
778 client->opts = opts;
779 client->flags |= flags;
780 client->flags &= ~(FLAG_LOCK_CMD);
781 if (!same_file)
782 client->flags &= ~(FLAG_HAS_LOCK | FLAG_NEW);
785 memcpy (client->md5file, md5file, 16);
786 client->filename = str_dup (filename);
787 if (!client->filename)
788 rc = GPG_ERR_ENOMEM;
790 /* Need to lock the mutex here because file_modified() cannot without
791 * knowing the filename. */
792 if (!rc)
794 rc = lock_file_mutex (client, 1);
795 if (rc)
796 client->flags &= ~FLAG_OPEN;
799 if (!rc)
801 rc = lock_flock (ctx, filename, LOCK_SH, &client->flock_fd);
802 if (!rc || gpg_err_code (rc) == GPG_ERR_ENOENT)
803 rc = 0;
806 if (!rc)
808 struct stat st;
810 if (stat (filename, &st) == -1 && errno != ENOENT)
811 rc = gpg_error_from_syserror ();
812 else if (!errno)
814 if (!rc && !S_ISREG (st.st_mode)) // to match LS output
815 rc = gpg_error_from_errno (ENOANO);
819 if (!rc)
821 char *password = req[1] && *req[1] ? req[1] : NULL;
823 #ifdef WITH_AGENT
824 if (IS_PKI (client->crypto))
825 rc = set_pinentry_mode (client->crypto->agent,
826 (client->flags & FLAG_NO_PINENTRY) ? "loopback"
827 : "ask");
828 #endif
829 if (!rc)
831 rc = do_open (ctx, password);
832 if (rc)
833 cleanup_client (client);
835 cleanup_crypto_stage1 (client->crypto);
839 pthread_cleanup_pop (1);
841 if (!rc && client->flags & FLAG_NEW)
842 rc = send_status (ctx, STATUS_NEWFILE, NULL);
844 #ifdef WITH_AGENT
845 (void) kill_scd (client->crypto->agent);
846 #endif
848 return send_error (ctx, rc);
851 static gpg_error_t
852 parse_opt_no_passphrase (void *data, void *value)
854 struct client_s *client = data;
856 (void) value;
857 client->opts |= OPT_NO_PASSPHRASE;
858 return 0;
861 static gpg_error_t
862 parse_save_opt_no_agent (void *data, void *value)
864 struct client_s *client = data;
866 client->opts |= OPT_NO_AGENT;
867 return 0;
870 static gpg_error_t
871 parse_save_opt_cipher (void *data, void *value)
873 struct client_s *client = data;
874 int algo = cipher_string_to_gcrypt ((char *) value);
875 file_header_t *hdr = &client->crypto->save.hdr;
876 gpg_error_t rc = 0;
878 if (algo == -1)
879 return GPG_ERR_INV_VALUE;
881 if (!(client->flags & FLAG_NEW))
883 rc = peer_is_invoker (client);
884 if (rc == GPG_ERR_EACCES)
886 uint64_t flags = 0;
888 flags &= ((uint16_t) ((uint32_t) (flags & 0xFFFFFFFF)));
889 if (!(client->crypto->hdr.flags & gcrypt_to_cipher (algo)))
890 return rc;
892 rc = 0;
894 else if (rc)
895 return rc;
898 if (!rc)
899 hdr->flags = set_cipher_flag (hdr->flags, algo);
901 return rc;
904 #ifdef WITH_AGENT
905 static gpg_error_t
906 permitted_to_save (struct client_s *client, const unsigned char *grip,
907 size_t size, const char *value)
909 gpg_error_t rc = 0;
911 if (!(client->flags & FLAG_NEW))
913 char *hexgrip = bin2hex (grip, size);
915 rc = !strcmp (hexgrip, (char *)value) ? 0 : GPG_ERR_EACCES;
916 xfree (hexgrip);
917 if (rc)
918 rc = peer_is_invoker (client);
921 return rc;
923 #endif
925 static gpg_error_t
926 parse_save_opt_keygrip (void *data, void *value)
928 #ifdef WITH_AGENT
929 struct client_s *client = data;
930 gpg_error_t rc = permitted_to_save (client, client->crypto->grip,
931 sizeof (client->crypto->grip),
932 value);
934 if (!IS_PKI (client->crypto))
935 return GPG_ERR_INV_ARG;
937 if (rc)
938 return rc;
940 if (client->crypto->save.pkey)
941 gcry_sexp_release (client->crypto->save.pkey);
943 client->crypto->save.pkey = NULL;
944 return get_pubkey (client->crypto, value, &client->crypto->save.pkey);
945 #else
946 return GPG_ERR_INV_ARG;
947 #endif
950 static gpg_error_t
951 parse_save_opt_sign_keygrip (void *data, void *value)
953 #ifdef WITH_AGENT
954 struct client_s *client = data;
955 gpg_error_t rc = permitted_to_save (client, client->crypto->sign_grip,
956 sizeof (client->crypto->sign_grip),
957 value);
959 if (!IS_PKI (client->crypto))
960 return GPG_ERR_INV_ARG;
962 if (rc)
963 return rc;
965 if (client->crypto->save.sigpkey)
966 gcry_sexp_release (client->crypto->save.sigpkey);
968 client->crypto->save.sigpkey = NULL;
969 return get_pubkey (client->crypto, value, &client->crypto->save.sigpkey);
970 #else
971 return GPG_ERR_INV_ARG;
972 #endif
975 static gpg_error_t
976 parse_opt_s2k_count (void *data, void *value)
978 struct client_s *client = data;
979 char *v = value, *p;
980 uint64_t n;
982 if (!v || !*v)
983 return GPG_ERR_INV_VALUE;
985 errno = 0;
986 n = strtoull (v, &p, 10);
987 if (n == UINT64_MAX && errno)
988 return gpg_error_from_errno (errno);
989 else if (p && *p)
990 return GPG_ERR_INV_VALUE;
992 if (!(client->flags & FLAG_NEW))
994 gpg_error_t rc = peer_is_invoker (client);
996 if (rc == GPG_ERR_EACCES)
998 if (n && client->crypto->hdr.s2k_count != n)
999 return rc;
1001 rc = 0;
1003 else if (rc)
1004 return rc;
1007 // Keep compatibility with libpwmd passing --s2k-count=0. If somehow
1008 // s2k_count == 0 it will be set to DEFAULT_KDFS2K_ITERATIONS in
1009 // save_command().
1010 if (n)
1011 client->crypto->save.hdr.s2k_count = n;
1013 return 0;
1016 static gpg_error_t
1017 save_finalize (assuan_context_t ctx)
1019 struct client_s *client = assuan_get_pointer (ctx);
1020 gpg_error_t rc = 0;
1021 xmlChar *xmlbuf = NULL;
1022 int xmlbuflen;
1023 void *key = NULL;
1024 size_t keylen = 0;
1026 xmlDocDumpFormatMemory (client->doc, &xmlbuf, &xmlbuflen, 0);
1027 if (!xmlbuf)
1028 return GPG_ERR_ENOMEM;
1030 pthread_cleanup_push (xmlFree, xmlbuf);
1032 if (!use_agent || ((client->flags & FLAG_NEW)
1033 && (client->opts & OPT_NO_AGENT))
1034 || !(client->crypto->hdr.flags & PWMD_FLAG_PKI))
1036 rc = export_common (ctx, client->flags & FLAG_NO_PINENTRY,
1037 client->crypto, xmlbuf, xmlbuflen, client->filename,
1038 NULL, &key, &keylen, 1, 1,
1039 (client->opts & OPT_NO_PASSPHRASE));
1041 #ifdef WITH_AGENT
1042 else
1044 gcry_sexp_t pubkey = client->crypto->save.pkey;
1045 gcry_sexp_t sigkey = client->crypto->save.sigpkey;
1047 if (!pubkey)
1048 pubkey = client->crypto->pkey_sexp;
1050 if (!sigkey)
1052 sigkey = client->crypto->sigpkey_sexp;
1053 if (!sigkey)
1055 gcry_sexp_build (&client->crypto->save.sigpkey, 0, "%S", pubkey);
1056 sigkey = client->crypto->save.sigpkey;
1060 rc = encrypt_data_file (client->ctx, client->crypto, pubkey, sigkey,
1061 client->filename, xmlbuf, xmlbuflen);
1062 if (pubkey == client->crypto->save.pkey)
1064 if (!rc)
1066 gcry_sexp_release (client->crypto->pkey_sexp);
1067 client->crypto->pkey_sexp = client->crypto->save.pkey;
1068 gcry_pk_get_keygrip (client->crypto->pkey_sexp,
1069 client->crypto->grip);
1071 else
1072 gcry_sexp_release (pubkey);
1074 client->crypto->save.pkey = NULL;
1077 if (!rc)
1078 gcry_pk_get_keygrip (sigkey, client->crypto->sign_grip);
1080 if (sigkey == client->crypto->save.sigpkey)
1082 if (!rc)
1084 if (client->crypto->sigpkey_sexp)
1085 gcry_sexp_release (client->crypto->sigpkey_sexp);
1087 client->crypto->sigpkey_sexp = client->crypto->save.sigpkey;
1088 gcry_pk_get_keygrip (client->crypto->sigpkey_sexp,
1089 client->crypto->sign_grip);
1091 else
1092 gcry_sexp_release (sigkey);
1094 client->crypto->save.sigpkey = NULL;
1097 #endif
1099 if (!rc)
1101 int cached;
1103 rc = save_common (client->filename, client->crypto, xmlbuf, xmlbuflen,
1104 key, keylen, &cached, client->opts & OPT_NO_AGENT);
1105 gcry_free (key);
1107 if (!rc && (!cached || (client->flags & FLAG_NEW)))
1108 send_status_all (STATUS_CACHE, NULL);
1110 if (!rc)
1112 rc = update_checksum (client);
1113 client->flags &= ~(FLAG_NEW);
1117 pthread_cleanup_pop (1); // xmlFree
1118 return rc;
1121 static gpg_error_t
1122 parse_opt_reset (void *data, void *value)
1124 struct client_s *client = data;
1126 (void) value;
1127 client->opts |= OPT_RESET;
1128 return 0;
1131 static gpg_error_t
1132 parse_opt_ask (void *data, void *value)
1134 struct client_s *client = data;
1136 (void) value;
1137 client->opts |= OPT_ASK;
1138 return 0;
1141 static gpg_error_t
1142 save_command (assuan_context_t ctx, char *line)
1144 struct client_s *client = assuan_get_pointer (ctx);
1145 gpg_error_t rc;
1146 struct stat st;
1147 struct argv_s *args[] = {
1148 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG,
1149 parse_opt_no_passphrase},
1150 &(struct argv_s) {"cipher", OPTION_TYPE_ARG, parse_save_opt_cipher},
1151 &(struct argv_s) {"inquire-keyparam", OPTION_TYPE_NOARG,
1152 parse_save_opt_inquire},
1153 &(struct argv_s) {"keygrip", OPTION_TYPE_ARG, parse_save_opt_keygrip},
1154 &(struct argv_s) {"sign-keygrip", OPTION_TYPE_ARG,
1155 parse_save_opt_sign_keygrip},
1156 &(struct argv_s) {"s2k-count", OPTION_TYPE_ARG, parse_opt_s2k_count},
1157 &(struct argv_s) {"reset", OPTION_TYPE_NOARG, parse_opt_reset},
1158 &(struct argv_s) {"cipher-iterations", OPTION_TYPE_ARG,
1159 parse_opt_s2k_count},
1160 &(struct argv_s) {"no-agent", OPTION_TYPE_NOARG,
1161 parse_save_opt_no_agent},
1162 &(struct argv_s) {"ask", OPTION_TYPE_NOARG,
1163 parse_opt_ask},
1164 NULL
1167 cleanup_save (&client->crypto->save);
1168 memcpy (&client->crypto->save.hdr, &client->crypto->hdr,
1169 sizeof (file_header_t));
1171 rc = parse_options (&line, args, client, 0);
1172 if (rc)
1173 return send_error (ctx, rc);
1175 if (!(client->flags & FLAG_NEW))
1176 client->opts &= ~OPT_NO_AGENT;
1177 else if (client->opts & OPT_NO_AGENT)
1179 client->crypto->save.hdr.flags &= ~PWMD_FLAG_PKI;
1180 client->crypto->hdr.flags &= ~PWMD_FLAG_PKI;
1183 /* Update to the default hash iteration count for data file
1184 * versions <= 3.0.14. */
1185 #ifdef WITH_AGENT
1186 if ((!IS_PKI (client->crypto) && client->crypto->hdr.version <= 0x03000e
1187 && client->crypto->save.hdr.s2k_count < DEFAULT_KDFS2K_ITERATIONS)
1188 || (!IS_PKI (client->crypto) && !client->crypto->save.hdr.s2k_count))
1189 #else
1190 if ((client->crypto->hdr.version <= 0x03000e
1191 && client->crypto->save.hdr.s2k_count < DEFAULT_KDFS2K_ITERATIONS)
1192 || !client->crypto->save.hdr.s2k_count)
1193 #endif
1195 client->crypto->save.hdr.s2k_count =
1196 config_get_ulonglong (client->filename, "s2k_count");
1197 if (!client->crypto->save.hdr.s2k_count)
1198 client->crypto->save.hdr.s2k_count = DEFAULT_KDFS2K_ITERATIONS;
1201 /* Deal with the hashed vs non-hashed cached key mess by clearing the cached
1202 * key entry. */
1203 if (client->crypto->hdr.version <= 0x03000e && !IS_PKI (client->crypto))
1204 client->opts |= OPT_RESET;
1205 else if (!IS_PKI (client->crypto) && !(client->flags & FLAG_NEW)
1206 && client->crypto->hdr.s2k_count !=
1207 client->crypto->save.hdr.s2k_count)
1208 client->opts |= OPT_RESET;
1210 if ((client->opts & OPT_NO_PASSPHRASE) && !(client->flags & FLAG_NEW)
1211 && !(client->opts & OPT_INQUIRE))
1212 return send_error (ctx, GPG_ERR_WRONG_KEY_USAGE);
1214 if (lstat (client->filename, &st) == -1 && errno != ENOENT)
1215 return send_error (ctx, gpg_error_from_errno (errno));
1217 if (errno != ENOENT && !S_ISREG (st.st_mode))
1219 log_write ("%s: %s", client->filename, pwmd_strerror (GPG_ERR_ENOANO));
1220 return send_error (ctx, GPG_ERR_ENOANO);
1223 int defer = 0;
1224 rc = cache_iscached (client->filename, &defer);
1225 if (gpg_err_code (rc) == GPG_ERR_ENOENT && client->flags & FLAG_NEW)
1226 rc = 0;
1227 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
1228 rc = 0;
1230 if ((!rc && defer))
1231 client->opts |= OPT_RESET;
1232 else if (config_get_boolean ("global", "require_save_key"))
1233 client->opts |= OPT_ASK;
1235 if (!rc && (client->opts & OPT_RESET))
1237 rc = cache_clear (client->md5file);
1238 if (rc)
1239 return send_error (ctx, rc);
1241 log_write ("%s: %s", client->filename,
1242 pwmd_strerror (GPG_ERR_KEY_EXPIRED));
1243 send_status_all (STATUS_CACHE, NULL);
1246 if (!rc && client->opts & OPT_ASK)
1247 rc = crypto_try_decrypt (ctx, client->flags & FLAG_NO_PINENTRY,
1248 client->filename, NULL, NULL, NULL);
1250 if (!rc)
1251 rc = update_element_mtime (client, xmlDocGetRootElement (client->doc));
1253 if (rc)
1254 return send_error (ctx, rc);
1256 #ifdef WITH_AGENT
1257 if (!rc && use_agent && !client->crypto->save.pkey &&
1258 (client->flags & FLAG_NEW || client->opts & OPT_INQUIRE)
1259 && !(client->opts & OPT_NO_AGENT))
1261 rc = set_pinentry_mode (client->crypto->agent,
1262 (client->flags & FLAG_NO_PINENTRY) ? "loopback"
1263 : "ask");
1265 if (!(client->flags & FLAG_NEW))
1267 struct crypto_s *crypto;
1268 void *key = NULL;
1269 size_t keylen = 0;
1271 /* Wanting to generate a new key. Require the key to open the
1272 current file before proceeding reguardless of the
1273 require_save_key configuration parameter. */
1274 rc = cache_clear (client->md5file);
1275 if (!rc)
1277 rc = init_client_crypto (&crypto);
1278 if (!rc)
1279 crypto->client_ctx = client->ctx;
1282 if (!rc)
1283 rc = decrypt_common (client->ctx, client->opts&OPT_INQUIRE, crypto,
1284 client->filename, &key, &keylen, NULL, NULL);
1286 xfree (key);
1287 cleanup_crypto (&crypto);
1290 if (!rc)
1291 rc = send_status (client->ctx, STATUS_GENKEY, NULL);
1293 if (!rc)
1295 struct inquire_data_s idata = { 0 };
1296 char *params = (client->opts & OPT_INQUIRE)
1297 ? NULL : default_key_params (client->crypto);
1299 pthread_cleanup_push (xfree, params);
1300 idata.crypto = client->crypto;
1302 if (params)
1304 idata.line = params;
1305 idata.len = strlen (params);
1307 else
1308 idata.preset = 1;
1310 client->crypto->agent->inquire_data = &idata;
1311 client->crypto->agent->inquire_cb = NULL;
1312 rc = generate_key (client->crypto, params,
1313 (client->opts & OPT_NO_PASSPHRASE), 1);
1314 pthread_cleanup_pop (1);
1317 #endif
1319 if (!rc)
1320 rc = save_finalize (ctx);
1322 cleanup_crypto_stage1 (client->crypto);
1323 #ifdef WITH_AGENT
1324 (void) kill_scd (client->crypto->agent);
1325 #endif
1326 return send_error (ctx, rc);
1329 static gpg_error_t
1330 do_delete (assuan_context_t ctx, char *line)
1332 struct client_s *client = assuan_get_pointer (ctx);
1333 gpg_error_t rc;
1334 char **req;
1335 xmlNodePtr n;
1337 if (strchr (line, '\t'))
1338 req = str_split (line, "\t", 0);
1339 else
1340 req = str_split (line, " ", 0);
1342 if (!req || !*req)
1343 return GPG_ERR_SYNTAX;
1345 n = find_root_element (client, client->doc, &req, &rc, NULL, 0, 0);
1346 if (!n || rc)
1348 strv_free (req);
1349 return rc;
1353 * No sub-node defined. Remove the entire node (root element).
1355 if (!req[1])
1357 if (n)
1359 rc = is_element_owner (client, n);
1360 if (!rc)
1362 rc = unlink_node (client, n);
1363 xmlFreeNode (n);
1367 strv_free (req);
1368 return rc;
1371 n = find_elements (client, client->doc, n->children, req + 1, &rc, NULL,
1372 NULL, NULL, 0, 0, NULL, 0);
1373 strv_free (req);
1374 if (!n || rc)
1375 return rc;
1377 rc = is_element_owner (client, n);
1378 if (!rc)
1380 rc = unlink_node (client, n);
1381 xmlFreeNode (n);
1384 return rc;
1387 static gpg_error_t
1388 delete_command (assuan_context_t ctx, char *line)
1390 struct client_s *client = assuan_get_pointer (ctx);
1391 gpg_error_t rc;
1392 struct argv_s *args[] = {
1393 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1394 NULL
1397 rc = parse_options (&line, args, client, 1);
1398 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1399 rc = GPG_ERR_SYNTAX;
1400 if (rc)
1401 return send_error (ctx, rc);
1403 if (client->opts & OPT_INQUIRE)
1405 unsigned char *result;
1406 size_t len;
1408 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1409 if (rc)
1410 return send_error (ctx, rc);
1412 pthread_cleanup_push (xfree, result);
1413 rc = do_delete (ctx, (char *)result);
1414 pthread_cleanup_pop (1);
1416 else
1417 rc = do_delete (ctx, line);
1419 return send_error (ctx, rc);
1422 static gpg_error_t
1423 store_command (assuan_context_t ctx, char *line)
1425 struct client_s *client = assuan_get_pointer (ctx);
1426 gpg_error_t rc;
1427 size_t len;
1428 unsigned char *result;
1429 char **req;
1430 xmlNodePtr n, parent;
1431 int has_content;
1432 char *content = NULL;
1434 if (line && *line)
1435 return send_error (ctx, GPG_ERR_SYNTAX);
1437 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1438 if (rc)
1439 return send_error (ctx, rc);
1441 req = str_split ((char *) result, "\t", 0);
1442 xfree (result);
1444 if (!req || !*req)
1445 return send_error (ctx, GPG_ERR_SYNTAX);
1447 len = strv_length (req);
1448 has_content = line[strlen (line) - 1] != '\t' && len > 1;
1449 if (*(req + 1) && !valid_element_path (req, has_content))
1451 strv_free (req);
1452 return send_error (ctx, GPG_ERR_INV_VALUE);
1455 if (has_content || !*req[len - 1])
1457 has_content = 1;
1458 content = req[len - 1];
1459 req[len - 1] = NULL;
1462 again:
1463 n = find_root_element (client, client->doc, &req, &rc, NULL, 0, 0);
1464 if (rc && rc == GPG_ERR_ELEMENT_NOT_FOUND)
1466 rc = new_root_element (client, client->doc, *req);
1467 if (rc)
1469 strv_free (req);
1470 return send_error (ctx, rc);
1473 goto again;
1476 if (!n || rc)
1478 strv_free (req);
1479 return send_error (ctx, rc);
1482 parent = n;
1484 if (req[1] && *req[1])
1486 if (!n->children)
1487 parent = create_elements_cb (client, 1, n, req + 1, &rc, NULL);
1488 else
1489 parent = find_elements (client, client->doc, n->children, req + 1, &rc,
1490 NULL, NULL, create_elements_cb, 0, 0, NULL,
1494 if (!rc && len > 1)
1496 rc = is_element_owner (client, parent);
1497 if (!rc)
1499 n = find_text_node (parent->children);
1500 if (n)
1501 xmlNodeSetContent (n, (xmlChar *) content);
1502 else
1503 xmlNodeAddContent (parent, (xmlChar *) content);
1505 update_element_mtime (client, parent);
1509 xfree (content);
1510 strv_free (req);
1511 return send_error (ctx, rc);
1514 static gpg_error_t
1515 xfer_data (assuan_context_t ctx, const char *line, int total)
1517 struct client_s *client = assuan_get_pointer (ctx);
1518 int to_send;
1519 int sent = 0;
1520 gpg_error_t rc = 0;
1521 int progress = config_get_integer ("global", "xfer_progress");
1522 int flush = 0;
1524 if (!(client->flags & FLAG_LOCK_CMD))
1525 rc = unlock_file_mutex (client, 0);
1526 if (rc && rc != GPG_ERR_NOT_LOCKED)
1527 return rc;
1529 progress =
1530 progress > 0 ? (progress / ASSUAN_LINELENGTH) * ASSUAN_LINELENGTH : 0;
1531 to_send = total < ASSUAN_LINELENGTH ? total : ASSUAN_LINELENGTH;
1532 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1534 if (rc)
1535 return rc;
1537 again:
1540 if (sent + to_send > total)
1541 to_send = total - sent;
1543 rc = assuan_send_data (ctx, flush ? NULL : (char *) line + sent,
1544 flush ? 0 : to_send);
1545 if (!rc)
1547 sent += flush ? 0 : to_send;
1549 if ((progress && !(sent % progress) && sent != total) ||
1550 (sent == total && flush))
1551 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1553 if (!flush && !rc && sent == total)
1555 flush = 1;
1556 goto again;
1560 while (!rc && sent < total);
1562 return rc;
1565 static gpg_error_t
1566 do_get (assuan_context_t ctx, char *line)
1568 struct client_s *client = assuan_get_pointer (ctx);
1569 gpg_error_t rc;
1570 char **req;
1571 xmlNodePtr n;
1573 req = str_split (line, "\t", 0);
1575 if (!req || !*req)
1577 strv_free (req);
1578 return GPG_ERR_SYNTAX;
1581 n = find_root_element (client, client->doc, &req, &rc, NULL, 0, 0);
1582 if (!n || rc)
1584 strv_free (req);
1585 return rc;
1588 if (req[1])
1589 n = find_elements (client, client->doc, n->children, req + 1, &rc,
1590 NULL, NULL, NULL, 0, 0, NULL, 0);
1592 strv_free (req);
1593 if (rc)
1594 return rc;
1596 if (!n || !n->children)
1597 return GPG_ERR_NO_DATA;
1599 n = find_text_node (n->children);
1600 if (!n || !n->content || !*n->content)
1601 return GPG_ERR_NO_DATA;
1603 rc = xfer_data (ctx, (char *) n->content, xmlStrlen (n->content));
1604 return rc;
1607 static gpg_error_t
1608 get_command (assuan_context_t ctx, char *line)
1610 struct client_s *client = assuan_get_pointer (ctx);
1611 gpg_error_t rc;
1612 struct argv_s *args[] = {
1613 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1614 NULL
1617 rc = parse_options (&line, args, client, 1);
1618 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1619 rc = GPG_ERR_SYNTAX;
1620 if (rc)
1621 return send_error (ctx, rc);
1623 if (client->opts & OPT_INQUIRE)
1625 unsigned char *result;
1626 size_t len;
1628 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1629 if (rc)
1630 return send_error (ctx, rc);
1632 pthread_cleanup_push (xfree, result);
1633 rc = do_get (ctx, (char *)result);
1634 pthread_cleanup_pop (1);
1636 else
1637 rc = do_get (ctx, line);
1639 return send_error (ctx, rc);
1642 static void list_command_cleanup1 (void *arg);
1643 static gpg_error_t
1644 realpath_command (assuan_context_t ctx, char *line)
1646 struct string_s *string = NULL;
1647 gpg_error_t rc;
1648 struct client_s *client = assuan_get_pointer (ctx);
1649 struct argv_s *args[] = {
1650 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1651 NULL
1654 rc = parse_options (&line, args, client, 1);
1655 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1656 rc = GPG_ERR_SYNTAX;
1657 if (rc)
1658 return send_error (ctx, rc);
1660 if (client->opts & OPT_INQUIRE)
1662 unsigned char *result;
1663 size_t len;
1665 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1666 if (rc)
1667 return send_error (ctx, rc);
1669 pthread_cleanup_push (xfree, result);
1670 rc = build_realpath (client, client->doc, (char *)result, &string);
1671 pthread_cleanup_pop (1);
1673 else
1674 rc = build_realpath (client, client->doc, line, &string);
1676 if (!rc)
1678 pthread_cleanup_push (list_command_cleanup1, string);
1679 rc = xfer_data (ctx, string->str, string->len);
1680 pthread_cleanup_pop (1);
1683 return send_error (ctx, rc);
1686 static void
1687 list_command_cleanup1 (void *arg)
1689 if (arg)
1690 string_free ((struct string_s *) arg, 1);
1693 static void
1694 list_command_cleanup2 (void *arg)
1696 struct element_list_s *elements = arg;
1698 if (elements)
1700 if (elements->list)
1702 int total = slist_length (elements->list);
1703 int i;
1705 for (i = 0; i < total; i++)
1707 char *tmp = slist_nth_data (elements->list, i);
1708 xfree (tmp);
1711 slist_free (elements->list);
1714 if (elements->prefix)
1715 xfree (elements->prefix);
1717 if (elements->req)
1718 strv_free (elements->req);
1720 xfree (elements);
1724 static gpg_error_t
1725 parse_list_opt_norecurse (void *data, void *value)
1727 struct client_s *client = data;
1729 client->opts &= ~(OPT_LIST_RECURSE);
1730 return 0;
1733 static gpg_error_t
1734 parse_opt_verbose (void *data, void *value)
1736 struct client_s *client = data;
1738 client->opts |= OPT_VERBOSE;
1739 return 0;
1742 static gpg_error_t
1743 parse_list_opt_target (void *data, void *value)
1745 struct client_s *client = data;
1747 client->opts |= OPT_LIST_WITH_TARGET;
1748 return 0;
1751 static gpg_error_t
1752 parse_list_opt_all (void *data, void *value)
1754 struct client_s *client = data;
1756 client->opts |= OPT_LIST_ALL;
1757 return 0;
1760 static gpg_error_t
1761 list_path_once (struct client_s *client, char *line,
1762 struct element_list_s *elements, struct string_s *result)
1764 gpg_error_t rc;
1766 elements->req = str_split (line, " ", 0);
1767 if (!elements->req)
1768 strv_printf (&elements->req, "%s", line);
1770 rc = create_path_list (client, client->doc, elements, *elements->req);
1771 if ((rc == GPG_ERR_ELOOP || rc == GPG_ERR_EACCES) && elements->verbose)
1772 rc = 0;
1774 if (!rc)
1776 int total = slist_length (elements->list);
1778 if (total)
1780 int i;
1782 for (i = 0; i < total; i++)
1784 char *tmp = slist_nth_data (elements->list, i);
1786 string_append_printf (result, "%s%s", tmp,
1787 i + 1 == total ? "" : "\n");
1790 else
1791 rc = GPG_ERR_NO_DATA;
1794 return rc;
1797 static int
1798 has_list_flag (char *path, char *flags)
1800 char *p = path;
1802 while (*p && *++p != ' ');
1804 if (!*p)
1805 return 0;
1807 for (; *p; p++)
1809 char *f;
1811 for (f = flags; *f && *f != ' '; f++)
1813 if (*p == *f)
1814 return 1;
1818 return 0;
1821 static gpg_error_t
1822 do_list (assuan_context_t ctx, char *line)
1824 struct client_s *client = assuan_get_pointer (ctx);
1825 gpg_error_t rc;
1826 struct element_list_s *elements = NULL;
1828 elements = xcalloc (1, sizeof (struct element_list_s));
1829 if (!elements)
1830 return GPG_ERR_ENOMEM;
1832 elements->recurse = client->opts & OPT_LIST_RECURSE;
1833 elements->verbose =
1834 (client->opts & OPT_VERBOSE) | (client->opts & OPT_LIST_WITH_TARGET);
1835 elements->with_target = client->opts & OPT_LIST_WITH_TARGET;
1837 if (!line || !*line)
1839 struct string_s *str = NULL;
1841 pthread_cleanup_push (list_command_cleanup2, elements);
1842 rc = list_root_elements (client, client->doc, &str, elements->verbose,
1843 elements->with_target);
1844 pthread_cleanup_pop (1);
1845 pthread_cleanup_push (list_command_cleanup1, str);
1847 if (!rc)
1849 if (client->opts & OPT_LIST_ALL)
1851 char **roots = str_split (str->str, "\n", 0);
1852 char **p;
1854 pthread_cleanup_push (req_cleanup, roots);
1855 string_truncate (str, 0);
1857 for (p = roots; *p; p++)
1859 if (strchr (*p, ' '))
1861 if (has_list_flag (*p, "EOP"))
1863 string_append_printf (str, "%s%s", *p,
1864 *(p + 1) ? "\n" : "");
1865 continue;
1869 elements = xcalloc (1, sizeof (struct element_list_s));
1870 if (!elements)
1872 rc = GPG_ERR_ENOMEM;
1873 break;
1876 elements->recurse = client->opts & OPT_LIST_RECURSE;
1877 elements->verbose =
1878 (client->opts & OPT_VERBOSE) | (client->opts &
1879 OPT_LIST_WITH_TARGET);
1880 elements->with_target = client->opts & OPT_LIST_WITH_TARGET;
1881 pthread_cleanup_push (list_command_cleanup2, elements);
1882 rc = list_path_once (client, *p, elements, str);
1883 pthread_cleanup_pop (1);
1884 if (rc)
1885 break;
1887 if (*(p + 1))
1888 string_append (str, "\n");
1891 pthread_cleanup_pop (1);
1894 if (!rc)
1895 rc = xfer_data (ctx, str->str, str->len);
1898 pthread_cleanup_pop (1);
1899 return rc;
1902 pthread_cleanup_push (list_command_cleanup2, elements);
1903 struct string_s *str = string_new (NULL);
1904 pthread_cleanup_push (list_command_cleanup1, str);
1905 rc = list_path_once (client, line, elements, str);
1906 if (!rc)
1907 rc = xfer_data (ctx, str->str, str->len);
1909 pthread_cleanup_pop (1);
1910 pthread_cleanup_pop (1);
1911 return rc;
1914 static gpg_error_t
1915 list_command (assuan_context_t ctx, char *line)
1917 struct client_s *client = assuan_get_pointer (ctx);
1918 gpg_error_t rc;
1919 struct argv_s *args[] = {
1920 &(struct argv_s) {"no-recurse", OPTION_TYPE_NOARG,
1921 parse_list_opt_norecurse},
1922 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_opt_verbose},
1923 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1924 &(struct argv_s) {"with-target", OPTION_TYPE_NOARG,
1925 parse_list_opt_target},
1926 &(struct argv_s) {"all", OPTION_TYPE_NOARG, parse_list_opt_all},
1927 NULL
1930 if (disable_list_and_dump == 1)
1931 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
1933 client->opts |= OPT_LIST_RECURSE;
1934 rc = parse_options (&line, args, client, 1);
1935 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1936 rc = GPG_ERR_SYNTAX;
1937 if (rc)
1938 return send_error (ctx, rc);
1940 if (client->opts & OPT_LIST_ALL)
1941 client->opts |= OPT_LIST_RECURSE | OPT_VERBOSE;
1943 if (client->opts & OPT_INQUIRE)
1945 unsigned char *result;
1946 size_t len;
1948 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1949 if (rc)
1950 return send_error (ctx, rc);
1952 pthread_cleanup_push (xfree, result);
1953 rc = do_list (ctx, (char *)result);
1954 pthread_cleanup_pop (1);
1956 else
1957 rc = do_list (ctx, line);
1959 return send_error (ctx, rc);
1963 * req[0] - element path
1965 static gpg_error_t
1966 attribute_list (assuan_context_t ctx, char **req)
1968 struct client_s *client = assuan_get_pointer (ctx);
1969 char **attrlist = NULL;
1970 int i = 0;
1971 char **path = NULL;
1972 xmlAttrPtr a;
1973 xmlNodePtr n, an;
1974 char *line;
1975 gpg_error_t rc;
1977 if (!req || !req[0])
1978 return GPG_ERR_SYNTAX;
1980 client->flags |= FLAG_ACL_IGNORE;
1982 if ((path = str_split (req[0], "\t", 0)) == NULL)
1985 * The first argument may be only a root element.
1987 if ((path = str_split (req[0], " ", 0)) == NULL)
1988 return GPG_ERR_SYNTAX;
1991 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 0);
1992 if (!n || rc)
1994 strv_free (path);
1995 return rc;
1998 if (client->flags & FLAG_ACL_ERROR)
2000 client->flags &= ~FLAG_ACL_IGNORE;
2001 if (path[1])
2003 strv_free (path);
2004 return GPG_ERR_EACCES;
2007 client->flags &= ~FLAG_ACL_ERROR;
2010 if (path[1])
2012 n = find_elements (client, client->doc, n->children, path + 1, &rc,
2013 NULL, NULL, NULL, 0, 0, NULL, 0);
2014 if (!n || rc)
2016 strv_free (path);
2017 return rc;
2021 strv_free (path);
2023 for (a = n->properties; a; a = a->next)
2025 char **pa;
2027 if ((pa = xrealloc (attrlist, (i + 2) * sizeof (char *))) == NULL)
2029 if (attrlist)
2030 strv_free (attrlist);
2032 log_write ("%s(%i): %s", __FILE__, __LINE__,
2033 pwmd_strerror (GPG_ERR_ENOMEM));
2034 return GPG_ERR_ENOMEM;
2037 attrlist = pa;
2038 an = a->children;
2039 attrlist[i] = str_asprintf ("%s %s", (char *) a->name,
2041 && an->content ? (char *) an->content : "");
2043 if (!attrlist[i])
2045 strv_free (attrlist);
2046 log_write ("%s(%i): %s", __FILE__, __LINE__,
2047 pwmd_strerror (GPG_ERR_ENOMEM));
2048 return GPG_ERR_ENOMEM;
2051 attrlist[++i] = NULL;
2054 if (!attrlist)
2055 return GPG_ERR_NO_DATA;
2057 line = strv_join ("\n", attrlist);
2059 if (!line)
2061 log_write ("%s(%i): %s", __FILE__, __LINE__,
2062 pwmd_strerror (GPG_ERR_ENOMEM));
2063 strv_free (attrlist);
2064 return GPG_ERR_ENOMEM;
2067 pthread_cleanup_push (xfree, line);
2068 pthread_cleanup_push (req_cleanup, attrlist);
2069 rc = xfer_data (ctx, line, strlen (line));
2070 pthread_cleanup_pop (1);
2071 pthread_cleanup_pop (1);
2072 return rc;
2076 * req[0] - attribute
2077 * req[1] - element path
2079 static gpg_error_t
2080 attribute_delete (struct client_s *client, char **req)
2082 xmlNodePtr n;
2083 char **path = NULL;
2084 gpg_error_t rc;
2086 if (!req || !req[0] || !req[1])
2087 return GPG_ERR_SYNTAX;
2089 if (!strcmp (req[0], "_name"))
2090 return GPG_ERR_INV_ATTR;
2092 if ((path = str_split (req[1], "\t", 0)) == NULL)
2095 * The first argument may be only a root element.
2097 if ((path = str_split (req[1], " ", 0)) == NULL)
2098 return GPG_ERR_SYNTAX;
2101 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 0);
2102 if (!n || rc)
2103 goto fail;
2105 if (path[1])
2107 n = find_elements (client, client->doc, n->children, path + 1, &rc,
2108 NULL, NULL, NULL, 0, 0, NULL, 0);
2109 if (!n || rc)
2110 goto fail;
2113 if (!strcmp (req[0], (char *) "_acl"))
2115 rc = is_element_owner (client, n);
2116 if (rc)
2117 goto fail;
2120 rc = delete_attribute (client, n, (xmlChar *) req[0]);
2122 fail:
2123 strv_free (path);
2124 return rc;
2127 static xmlNodePtr
2128 create_element_path (struct client_s *client,
2129 char ***elements, gpg_error_t * rc, xmlNodePtr parent)
2131 char **req = *elements;
2132 char **req_orig = strv_dup (req);
2133 xmlNodePtr n = NULL;
2135 *rc = 0;
2137 if (!req_orig)
2139 *rc = GPG_ERR_ENOMEM;
2140 log_write ("%s(%i): %s", __FILE__, __LINE__,
2141 pwmd_strerror (GPG_ERR_ENOMEM));
2142 goto fail;
2145 again:
2146 n = find_root_element (client, client->doc, &req, rc, NULL, 0, 0);
2147 if (!n)
2149 if (*rc != GPG_ERR_ELEMENT_NOT_FOUND)
2150 goto fail;
2152 *rc = new_root_element (client, client->doc, req[0]);
2153 if (*rc)
2154 goto fail;
2156 goto again;
2158 else if (n == parent)
2160 *rc = GPG_ERR_CONFLICT;
2161 goto fail;
2164 if (req[1])
2166 if (!n->children)
2167 n = create_target_elements_cb (client, 1, n, req + 1, rc, NULL);
2168 else
2169 n = find_elements (client, client->doc, n->children, req + 1, rc,
2170 NULL, NULL, create_target_elements_cb, 0, 0,
2171 parent, 0);
2173 if (!n)
2174 goto fail;
2177 * Reset the position of the element tree now that the elements
2178 * have been created.
2180 strv_free (req);
2181 req = req_orig;
2182 req_orig = NULL;
2183 n = find_root_element (client, client->doc, &req, rc, NULL, 0, 0);
2184 if (!n)
2185 goto fail;
2187 n = find_elements (client, client->doc, n->children, req + 1, rc,
2188 NULL, NULL, NULL, 0, 0, NULL, 0);
2189 if (!n)
2190 goto fail;
2193 fail:
2194 if (req_orig)
2195 strv_free (req_orig);
2197 *elements = req;
2198 return n;
2202 * Creates a "target" attribute. When other commands encounter an element with
2203 * this attribute, the element path is modified to the target value. If the
2204 * source element path doesn't exist when using 'ATTR SET target', it is
2205 * created, but the destination element path must exist.
2207 * req[0] - source element path
2208 * req[1] - destination element path
2210 static gpg_error_t
2211 target_attribute (struct client_s *client, char **req)
2213 char **src, **dst, *line = NULL, **odst = NULL;
2214 gpg_error_t rc;
2215 xmlNodePtr n;
2217 if (!req || !req[0] || !req[1])
2218 return GPG_ERR_SYNTAX;
2220 if ((src = str_split (req[0], "\t", 0)) == NULL)
2223 * The first argument may be only a root element.
2225 if ((src = str_split (req[0], " ", 0)) == NULL)
2226 return GPG_ERR_SYNTAX;
2229 if (!valid_element_path (src, 0))
2230 return GPG_ERR_INV_VALUE;
2232 if ((dst = str_split (req[1], "\t", 0)) == NULL)
2235 * The first argument may be only a root element.
2237 if ((dst = str_split (req[1], " ", 0)) == NULL)
2239 rc = GPG_ERR_SYNTAX;
2240 goto fail;
2244 odst = strv_dup (dst);
2245 if (!odst)
2247 rc = GPG_ERR_ENOMEM;
2248 goto fail;
2251 n = find_root_element (client, client->doc, &dst, &rc, NULL, 0, 0);
2253 * Make sure the destination element path exists.
2255 if (rc && rc != GPG_ERR_EACCES)
2256 goto fail;
2258 rc = 0;
2259 if (dst[1])
2261 n = find_elements (client, client->doc, n->children, dst + 1, &rc,
2262 NULL, NULL, NULL, 0, 0, NULL, 0);
2263 if (rc && rc != GPG_ERR_EACCES)
2264 goto fail;
2267 rc = validate_target_attribute (client, client->doc, req[0], n);
2268 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2269 goto fail;
2271 n = create_element_path (client, &src, &rc, NULL);
2272 if (rc)
2273 goto fail;
2275 line = strv_join ("\t", odst);
2276 if (!line)
2278 rc = GPG_ERR_ENOMEM;
2279 goto fail;
2282 rc = add_attribute (client, n, "target", line);
2284 fail:
2285 xfree (line);
2286 strv_free (src);
2287 strv_free (dst);
2288 strv_free (odst);
2289 return rc;
2293 * req[0] - attribute
2294 * req[1] - element path
2296 static gpg_error_t
2297 attribute_get (assuan_context_t ctx, char **req)
2299 struct client_s *client = assuan_get_pointer (ctx);
2300 xmlNodePtr n;
2301 xmlChar *a;
2302 char **path = NULL;
2303 gpg_error_t rc;
2305 if (!req || !req[0] || !req[1])
2306 return GPG_ERR_SYNTAX;
2308 if (strchr (req[1], '\t'))
2310 if ((path = str_split (req[1], "\t", 0)) == NULL)
2311 return GPG_ERR_SYNTAX;
2313 else
2315 if ((path = str_split (req[1], " ", 0)) == NULL)
2316 return GPG_ERR_SYNTAX;
2319 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 0);
2320 if (!n || rc)
2321 goto fail;
2323 if (path[1])
2325 n = find_elements (client, client->doc, n->children, path + 1, &rc,
2326 NULL, NULL, NULL, 0, 0, NULL, 0);
2327 if (!n || rc)
2328 goto fail;
2331 strv_free (path);
2333 if ((a = xmlGetProp (n, (xmlChar *) req[0])) == NULL)
2334 return GPG_ERR_NOT_FOUND;
2336 pthread_cleanup_push (xmlFree, a);
2338 if (*a)
2339 rc = xfer_data (ctx, (char *) a, xmlStrlen (a));
2340 else
2341 rc = GPG_ERR_NO_DATA;
2343 pthread_cleanup_pop (1);
2344 return rc;
2346 fail:
2347 strv_free (path);
2348 return rc;
2352 * req[0] - attribute
2353 * req[1] - element path
2354 * req[2] - value
2356 static gpg_error_t
2357 attribute_set (struct client_s *client, char **req)
2359 char **path = NULL;
2360 gpg_error_t rc;
2361 xmlNodePtr n;
2363 if (!req || !req[0] || !req[1])
2364 return GPG_ERR_SYNTAX;
2367 * Reserved attribute names.
2369 if (!strcmp (req[0], "_name"))
2370 return GPG_ERR_INV_ATTR;
2371 else if (!strcmp (req[0], "target"))
2372 return target_attribute (client, req + 1);
2373 else if (!valid_xml_attribute (req[0]))
2374 return GPG_ERR_INV_VALUE;
2376 if (!valid_xml_attribute_value (req[2]))
2377 return GPG_ERR_INV_VALUE;
2379 if ((path = str_split (req[1], "\t", 0)) == NULL)
2382 * The first argument may be only a root element.
2384 if ((path = str_split (req[1], " ", 0)) == NULL)
2385 return GPG_ERR_SYNTAX;
2388 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 0);
2389 if (!n || rc)
2390 goto fail;
2392 if (path[1])
2394 n = find_elements (client, client->doc, n->children, path + 1, &rc,
2395 NULL, NULL, NULL, 0, 0, NULL, 0);
2396 if (!n || rc)
2397 goto fail;
2400 if (!strcmp (req[0], (char *) "_acl"))
2402 rc = is_element_owner (client, n);
2403 if (rc)
2404 goto fail;
2407 rc = add_attribute (client, n, req[0], req[2]);
2409 fail:
2410 strv_free (path);
2411 return rc;
2415 * req[0] - command
2416 * req[1] - attribute name or element path if command is LIST
2417 * req[2] - element path
2418 * req[2] - element path or value
2421 static gpg_error_t
2422 do_attr (assuan_context_t ctx, char *line)
2424 struct client_s *client = assuan_get_pointer (ctx);
2425 gpg_error_t rc = 0;
2426 char **req;
2428 req = str_split (line, " ", 4);
2429 if (!req || !req[0] || !req[1])
2431 strv_free (req);
2432 return GPG_ERR_SYNTAX;
2435 pthread_cleanup_push (req_cleanup, req);
2437 if (strcasecmp (req[0], "SET") == 0)
2438 rc = attribute_set (client, req + 1);
2439 else if (strcasecmp (req[0], "GET") == 0)
2440 rc = attribute_get (ctx, req + 1);
2441 else if (strcasecmp (req[0], "DELETE") == 0)
2442 rc = attribute_delete (client, req + 1);
2443 else if (strcasecmp (req[0], "LIST") == 0)
2444 rc = attribute_list (ctx, req + 1);
2445 else
2446 rc = GPG_ERR_SYNTAX;
2448 client->flags &= ~(FLAG_ACL_IGNORE|FLAG_ACL_ERROR);
2449 pthread_cleanup_pop (1);
2450 return rc;
2453 static gpg_error_t
2454 attr_command (assuan_context_t ctx, char *line)
2456 struct client_s *client = assuan_get_pointer (ctx);
2457 gpg_error_t rc;
2458 struct argv_s *args[] = {
2459 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2460 NULL
2463 rc = parse_options (&line, args, client, 1);
2464 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2465 rc = GPG_ERR_SYNTAX;
2466 if (rc)
2467 return send_error (ctx, rc);
2469 if (client->opts & OPT_INQUIRE)
2471 unsigned char *result;
2472 size_t len;
2474 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2475 if (rc)
2476 return send_error (ctx, rc);
2478 pthread_cleanup_push (xfree, result);
2479 rc = do_attr (ctx, (char *)result);
2480 pthread_cleanup_pop (1);
2482 else
2483 rc = do_attr (ctx, line);
2485 return send_error (ctx, rc);
2488 static gpg_error_t
2489 parse_iscached_opt_lock (void *data, void *value)
2491 struct client_s *client = data;
2493 (void) value;
2494 client->opts |= OPT_LOCK;
2495 return 0;
2498 static gpg_error_t
2499 iscached_command (assuan_context_t ctx, char *line)
2501 struct client_s *client = assuan_get_pointer (ctx);
2502 gpg_error_t rc;
2503 struct argv_s *args[] = {
2504 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_iscached_opt_lock},
2505 NULL
2508 if (!line || !*line)
2509 return send_error (ctx, GPG_ERR_SYNTAX);
2511 rc = parse_options (&line, args, client, 1);
2512 if (rc)
2513 return send_error (ctx, rc);
2514 else if (!valid_filename (line))
2515 return send_error (ctx, GPG_ERR_INV_VALUE);
2517 rc = cache_iscached (line, NULL);
2518 if (client->opts & OPT_LOCK
2519 && (!rc || gpg_err_code (rc) == GPG_ERR_NO_DATA))
2521 unsigned char md5file[16];
2522 gpg_error_t trc = rc;
2524 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2525 if (memcmp (md5file, client->md5file, 16))
2526 cleanup_client (client);
2528 memcpy (client->md5file, md5file, 16);
2529 rc = do_lock (client, 1);
2530 if (!rc)
2531 rc = trc;
2534 return send_error (ctx, rc);
2537 static gpg_error_t
2538 clearcache_command (assuan_context_t ctx, char *line)
2540 gpg_error_t rc = 0, all_rc = 0;
2541 unsigned char md5file[16];
2542 int i;
2543 int t;
2544 int all = 0;
2545 struct client_thread_s *once = NULL;
2547 cache_lock ();
2548 MUTEX_LOCK (&cn_mutex);
2549 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
2551 if (!line || !*line)
2552 all = 1;
2554 t = slist_length (cn_thread_list);
2556 for (i = 0; i < t; i++)
2558 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2559 assuan_peercred_t peer;
2561 if (!thd->cl)
2562 continue;
2564 /* Lock each connected clients' file mutex to prevent any other client
2565 * from accessing the cache entry (the file mutex is locked upon
2566 * command startup). The cache for the entry is not cleared if the
2567 * file mutex is locked by another client to prevent this function
2568 * from blocking.
2570 if (all)
2572 if (thd->cl->filename)
2574 rc = do_validate_peer (ctx, thd->cl->filename, &peer);
2575 all_rc = !all_rc ? rc : all_rc;
2576 if (rc)
2578 rc = 0;
2579 continue;
2583 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0, -1);
2584 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2586 if (pthread_equal (pthread_self (), thd->tid))
2587 rc = 0;
2588 else
2590 if (!thd->cl->filename ||
2591 cache_iscached (thd->cl->filename,
2592 NULL) == GPG_ERR_NO_DATA)
2594 rc = 0;
2595 continue;
2598 cache_defer_clear (thd->cl->md5file);
2601 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
2603 rc = 0;
2604 continue;
2607 if (!rc)
2609 rc = cache_clear (thd->cl->md5file);
2610 cache_unlock_mutex (thd->cl->md5file, 0);
2613 if (rc)
2614 all_rc = rc;
2616 rc = 0;
2618 /* A single data filename was specified. Lock only this data file
2619 * mutex and free the cache entry. */
2620 else
2622 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2623 rc = do_validate_peer (ctx, line, &peer);
2625 if (!rc && !memcmp (thd->cl->md5file, md5file, sizeof (md5file)))
2627 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0,
2628 -1);
2629 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2631 if (pthread_equal (pthread_self (), thd->tid))
2632 rc = 0;
2635 if (!rc)
2637 once = thd;
2638 rc = cache_clear (thd->cl->md5file);
2639 cache_unlock_mutex (thd->cl->md5file, 0);
2641 else
2643 cache_defer_clear (thd->cl->md5file);
2646 break;
2651 /* Only connected clients' cache entries have been cleared. Now clear any
2652 * remaining cache entries without clients but only if there wasn't an
2653 * error from above since this would defeat the locking check of the
2654 * remaining entries. */
2655 if (!all_rc && all)
2657 cache_clear (NULL);
2660 /* No clients are using the specified file. */
2661 else if (!all_rc && !rc && !once)
2663 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2664 rc = cache_clear (md5file);
2667 /* Release the connection mutex. */
2668 pthread_cleanup_pop (1);
2669 cache_unlock ();
2671 if (!rc)
2672 send_status_all (STATUS_CACHE, NULL);
2674 /* One or more files were locked while clearing all cache entries. */
2675 if (all_rc)
2676 rc = all_rc;
2678 return send_error (ctx, rc);
2681 static gpg_error_t
2682 cachetimeout_command (assuan_context_t ctx, char *line)
2684 int timeout;
2685 char **req = str_split (line, " ", 0);
2686 char *p;
2687 gpg_error_t rc = 0;
2688 assuan_peercred_t peer;
2690 if (!req || !*req || !req[1])
2692 strv_free (req);
2693 return send_error (ctx, GPG_ERR_SYNTAX);
2696 errno = 0;
2697 timeout = (int) strtol (req[1], &p, 10);
2698 if (errno != 0 || *p || timeout < -1)
2700 strv_free (req);
2701 return send_error (ctx, GPG_ERR_SYNTAX);
2704 rc = do_validate_peer (ctx, req[0], &peer);
2705 if (!rc)
2707 unsigned char md5file[16];
2709 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, req[0], strlen (req[0]));
2710 rc = cache_set_timeout (md5file, timeout);
2711 if (!rc || gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
2713 rc = 0;
2714 MUTEX_LOCK (&rcfile_mutex);
2715 config_set_int_param (&global_config, req[0], "cache_timeout",
2716 req[1]);
2717 MUTEX_UNLOCK (&rcfile_mutex);
2721 strv_free (req);
2722 return send_error (ctx, rc);
2725 static gpg_error_t
2726 dump_command (assuan_context_t ctx, char *line)
2728 xmlChar *xml;
2729 int len;
2730 struct client_s *client = assuan_get_pointer (ctx);
2731 gpg_error_t rc;
2733 if (disable_list_and_dump == 1)
2734 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2736 if (line && *line)
2737 return send_error (ctx, GPG_ERR_SYNTAX);
2739 rc = peer_is_invoker(client);
2740 if (rc)
2741 return send_error (ctx, rc);
2743 xmlDocDumpFormatMemory (client->doc, &xml, &len, 1);
2745 if (!xml)
2747 log_write ("%s(%i): %s", __FILE__, __LINE__,
2748 pwmd_strerror (GPG_ERR_ENOMEM));
2749 return send_error (ctx, GPG_ERR_ENOMEM);
2752 pthread_cleanup_push (xmlFree, xml);
2753 rc = xfer_data (ctx, (char *) xml, len);
2754 pthread_cleanup_pop (1);
2755 return send_error (ctx, rc);
2758 static gpg_error_t
2759 getconfig_command (assuan_context_t ctx, char *line)
2761 struct client_s *client = assuan_get_pointer (ctx);
2762 gpg_error_t rc = 0;
2763 char filename[255] = { 0 }, param[747] = { 0 };
2764 char *p, *tmp = NULL, *fp = client->filename, *paramp = line;
2766 if (!line || !*line)
2767 return send_error (ctx, GPG_ERR_SYNTAX);
2769 if (strchr (line, ' '))
2771 sscanf (line, " %254[^ ] %746c", filename, param);
2772 paramp = param;
2773 fp = filename;
2776 if (fp && !valid_filename (fp))
2777 return send_error (ctx, GPG_ERR_INV_VALUE);
2779 paramp = str_down (paramp);
2780 if (!strcmp (paramp, "cipher") && fp)
2782 struct crypto_s *crypto = NULL;
2784 rc = init_client_crypto (&crypto);
2785 if (!rc)
2787 rc = read_data_header (fp, &crypto->hdr, NULL, NULL);
2788 if (!rc)
2790 const char *t =
2791 gcry_cipher_algo_name (cipher_to_gcrypt (crypto->hdr.flags));
2792 if (t)
2794 tmp = str_dup (t);
2795 if (tmp)
2796 str_down (tmp);
2801 UPDATE_AGENT_CTX (client, crypto);
2802 cleanup_crypto (&crypto);
2803 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
2804 return send_error (ctx, rc);
2806 if (!rc && tmp)
2807 goto done;
2809 else if (!strcmp (paramp, "cipher_iterations") && fp)
2811 struct crypto_s *crypto = NULL;
2813 rc = init_client_crypto (&crypto);
2814 if (!rc)
2816 rc = read_data_header (fp, &crypto->hdr, NULL, NULL);
2817 if (!rc)
2819 tmp = str_asprintf ("%llu",
2820 (unsigned long long) crypto->hdr.s2k_count);
2821 if (!tmp)
2822 rc = GPG_ERR_ENOMEM;
2826 UPDATE_AGENT_CTX (client, crypto);
2827 cleanup_crypto (&crypto);
2828 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
2829 return send_error (ctx, rc);
2831 if (!rc && tmp)
2832 goto done;
2834 else if (!strcmp (paramp, "passphrase"))
2835 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2837 p = config_get_value (fp ? fp : "global", paramp);
2838 if (!p)
2839 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2841 tmp = expand_homedir (p);
2842 xfree (p);
2843 if (!tmp)
2845 log_write ("%s(%i): %s", __FILE__, __LINE__,
2846 pwmd_strerror (GPG_ERR_ENOMEM));
2847 return send_error (ctx, GPG_ERR_ENOMEM);
2850 done:
2851 p = tmp;
2852 pthread_cleanup_push (xfree, p);
2853 rc = xfer_data (ctx, p, strlen (p));
2854 pthread_cleanup_pop (1);
2855 return send_error (ctx, rc);
2858 struct xpath_s
2860 xmlXPathContextPtr xp;
2861 xmlXPathObjectPtr result;
2862 xmlBufferPtr buf;
2863 char **req;
2866 static void
2867 xpath_command_cleanup (void *arg)
2869 struct xpath_s *xpath = arg;
2871 if (!xpath)
2872 return;
2874 req_cleanup (xpath->req);
2876 if (xpath->buf)
2877 xmlBufferFree (xpath->buf);
2879 if (xpath->result)
2880 xmlXPathFreeObject (xpath->result);
2882 if (xpath->xp)
2883 xmlXPathFreeContext (xpath->xp);
2886 static gpg_error_t
2887 do_xpath (assuan_context_t ctx, char *line)
2889 gpg_error_t rc;
2890 struct client_s *client = assuan_get_pointer (ctx);
2891 struct xpath_s _x = { 0 };
2892 struct xpath_s *xpath = &_x;
2894 if (!line || !*line)
2895 return GPG_ERR_SYNTAX;
2897 if ((xpath->req = str_split (line, "\t", 2)) == NULL)
2899 if (strv_printf (&xpath->req, "%s", line) == 0)
2900 return GPG_ERR_ENOMEM;
2903 xpath->xp = xmlXPathNewContext (client->doc);
2904 if (!xpath->xp)
2906 rc = GPG_ERR_BAD_DATA;
2907 goto fail;
2910 xpath->result =
2911 xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2912 if (!xpath->result)
2914 rc = GPG_ERR_BAD_DATA;
2915 goto fail;
2918 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2920 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2921 goto fail;
2924 rc = recurse_xpath_nodeset (client, client->doc, xpath->result->nodesetval,
2925 (xmlChar *) xpath->req[1], &xpath->buf, 0,
2926 NULL);
2927 if (rc)
2928 goto fail;
2929 else if (!xpath->req[1] && !xmlBufferLength (xpath->buf))
2931 rc = GPG_ERR_NO_DATA;
2932 goto fail;
2934 else if (xpath->req[1])
2936 rc = 0;
2937 goto fail;
2940 pthread_cleanup_push (xpath_command_cleanup, &xpath);
2941 rc = xfer_data (ctx, (char *) xmlBufferContent (xpath->buf),
2942 xmlBufferLength (xpath->buf));
2943 pthread_cleanup_pop (0);
2944 fail:
2945 xpath_command_cleanup (xpath);
2946 return rc;
2949 static gpg_error_t
2950 xpath_command (assuan_context_t ctx, char *line)
2952 struct client_s *client = assuan_get_pointer (ctx);
2953 gpg_error_t rc;
2954 struct argv_s *args[] = {
2955 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2956 NULL
2959 if (disable_list_and_dump == 1)
2960 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2962 rc = peer_is_invoker(client);
2963 if (rc)
2964 return send_error (ctx, rc);
2966 rc = parse_options (&line, args, client, 1);
2967 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2968 rc = GPG_ERR_SYNTAX;
2969 if (rc)
2970 return send_error (ctx, rc);
2972 if (client->opts & OPT_INQUIRE)
2974 unsigned char *result;
2975 size_t len;
2977 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2978 if (rc)
2979 return send_error (ctx, rc);
2981 pthread_cleanup_push (xfree, result);
2982 rc = do_xpath (ctx, (char *)result);
2983 pthread_cleanup_pop (1);
2985 else
2986 rc = do_xpath (ctx, line);
2988 return send_error (ctx, rc);
2991 static gpg_error_t
2992 do_xpathattr (assuan_context_t ctx, char *line)
2994 struct client_s *client = assuan_get_pointer (ctx);
2995 gpg_error_t rc;
2996 char **req = NULL;
2997 int cmd = 0; //SET
2998 struct xpath_s _x = { 0 };
2999 struct xpath_s *xpath = &_x;
3001 if (!line || !*line)
3002 return GPG_ERR_SYNTAX;
3004 if ((req = str_split (line, " ", 3)) == NULL)
3005 return GPG_ERR_ENOMEM;
3007 if (!req[0])
3009 rc = GPG_ERR_SYNTAX;
3010 goto fail;
3013 if (!strcasecmp (req[0], "SET"))
3014 cmd = 0;
3015 else if (!strcasecmp (req[0], "DELETE"))
3016 cmd = 1;
3017 else
3019 rc = GPG_ERR_SYNTAX;
3020 goto fail;
3023 if (!req[1] || !req[2])
3025 rc = GPG_ERR_SYNTAX;
3026 goto fail;
3029 if ((xpath->req = str_split (req[2], "\t", 3)) == NULL)
3031 rc = GPG_ERR_ENOMEM;
3032 goto fail;
3035 if (!xpath->req[0] || (!xpath->req[1] && !cmd) || (xpath->req[1] && cmd))
3037 rc = GPG_ERR_SYNTAX;
3038 goto fail;
3041 xpath->xp = xmlXPathNewContext (client->doc);
3042 if (!xpath->xp)
3044 rc = GPG_ERR_BAD_DATA;
3045 goto fail;
3048 xpath->result = xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
3049 if (!xpath->result)
3051 rc = GPG_ERR_BAD_DATA;
3052 goto fail;
3055 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
3057 rc = GPG_ERR_ELEMENT_NOT_FOUND;
3058 goto fail;
3061 rc = recurse_xpath_nodeset (client, client->doc, xpath->result->nodesetval,
3062 (xmlChar *) xpath->req[1], &xpath->buf, cmd,
3063 (xmlChar *) req[1]);
3065 fail:
3066 xpath_command_cleanup (xpath);
3067 strv_free (req);
3068 return rc;
3071 /* XPATHATTR SET|DELETE <name> <expression>[<TAB>[value]] */
3072 static gpg_error_t
3073 xpathattr_command (assuan_context_t ctx, char *line)
3075 struct client_s *client = assuan_get_pointer (ctx);
3076 gpg_error_t rc;
3077 struct argv_s *args[] = {
3078 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3079 NULL
3082 if (disable_list_and_dump == 1)
3083 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
3085 rc = peer_is_invoker(client);
3086 if (rc)
3087 return send_error (ctx, rc);
3089 rc = parse_options (&line, args, client, 1);
3090 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3091 rc = GPG_ERR_SYNTAX;
3092 if (rc)
3093 return send_error (ctx, rc);
3095 if (client->opts & OPT_INQUIRE)
3097 unsigned char *result;
3098 size_t len;
3100 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3101 if (rc)
3102 return send_error (ctx, rc);
3104 pthread_cleanup_push (xfree, result);
3105 rc = do_xpathattr (ctx, (char *)result);
3106 pthread_cleanup_pop (1);
3108 else
3109 rc = do_xpathattr (ctx, line);
3111 return send_error (ctx, rc);
3114 static gpg_error_t
3115 do_import (struct client_s *client, const char *root_element,
3116 unsigned char *content)
3118 char **dst_path = NULL;
3119 xmlDocPtr doc = NULL;
3120 xmlNodePtr n, root, copy;
3121 gpg_error_t rc;
3123 if (!content || !*content)
3125 xfree (content);
3126 return GPG_ERR_SYNTAX;
3129 if (root_element)
3130 dst_path = str_split (root_element, "\t", 0);
3132 if (dst_path && !valid_element_path (dst_path, 0))
3134 if (dst_path)
3135 strv_free (dst_path);
3137 return GPG_ERR_INV_VALUE;
3140 struct string_s *str = string_new_content ((char *)content);
3141 str = string_prepend (str, "<pwmd>");
3142 str = string_append (str, "</pwmd>");
3143 doc = xmlReadDoc ((xmlChar *) str->str, NULL, "UTF-8", XML_PARSE_NOBLANKS);
3144 string_free (str, 1);
3145 if (!doc)
3147 rc = GPG_ERR_BAD_DATA;
3148 goto fail;
3151 root = xmlDocGetRootElement (doc);
3152 xmlNodePtr root_orig = root->children;
3153 root = root->children;
3154 rc = validate_import (client, root);
3155 if (rc)
3156 goto fail;
3160 again:
3161 if (dst_path)
3163 char **path = strv_dup (dst_path);
3164 if (!path)
3166 log_write ("%s(%i): %s", __FILE__, __LINE__,
3167 pwmd_strerror (GPG_ERR_ENOMEM));
3168 rc = GPG_ERR_ENOMEM;
3169 goto fail;
3172 xmlChar *a = xmlGetProp (root, (xmlChar *) "_name");
3173 if (!a)
3175 strv_free (path);
3176 rc = GPG_ERR_INV_VALUE;
3177 goto fail;
3180 if (strv_printf (&path, "%s", (char *) a) == 0)
3182 xmlFree (a);
3183 rc = GPG_ERR_ENOMEM;
3184 goto fail;
3187 xmlFree (a);
3188 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 0);
3189 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3191 strv_free (path);
3192 goto fail;
3195 if (!rc)
3197 n = find_elements (client, client->doc, n->children, path + 1, &rc,
3198 NULL, NULL, NULL, 0, 0, NULL, 1);
3199 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3201 strv_free (path);
3202 goto fail;
3204 else if (!rc)
3206 xmlUnlinkNode (n);
3207 xmlFreeNode (n);
3208 strv_free (path);
3209 path = NULL;
3210 goto again;
3214 if (rc == GPG_ERR_ELEMENT_NOT_FOUND)
3216 n = create_element_path (client, &path, &rc, NULL);
3217 if (rc)
3218 goto fail;
3221 if (root->children)
3223 copy = xmlCopyNodeList (root->children);
3224 n = xmlAddChildList (n, copy);
3225 if (!n)
3226 rc = GPG_ERR_ENOMEM;
3229 strv_free (path);
3231 else
3233 char **path = NULL;
3235 /* Check if the content root element can create a DTD root element. */
3236 if (!xmlStrEqual ((xmlChar *) "element", root->name))
3238 rc = GPG_ERR_SYNTAX;
3239 goto fail;
3242 xmlChar *a;
3244 if ((a = xmlGetProp (root, (xmlChar *) "_name")) == NULL)
3246 rc = GPG_ERR_SYNTAX;
3247 goto fail;
3250 char *tmp = str_dup ((char *) a);
3251 xmlFree (a);
3252 int literal = is_literal_element (&tmp);
3254 if (!valid_xml_element ((xmlChar *) tmp) || literal)
3256 xfree (tmp);
3257 rc = GPG_ERR_INV_VALUE;
3258 goto fail;
3261 if (strv_printf (&path, "%s", tmp) == 0)
3263 xfree (tmp);
3264 rc = GPG_ERR_ENOMEM;
3265 goto fail;
3268 xfree (tmp);
3269 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 1);
3270 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3272 rc = GPG_ERR_BAD_DATA;
3273 goto fail;
3276 /* Overwriting the existing tree. */
3277 if (!rc)
3279 xmlUnlinkNode (n);
3280 xmlFreeNodeList (n);
3283 rc = 0;
3284 xmlSetProp (root, (xmlChar *) "_name", (xmlChar *) path[0]);
3285 n = xmlCopyNode (root, 1);
3286 n = xmlAddChildList (xmlDocGetRootElement (client->doc), n);
3287 strv_free (path);
3290 if (n && !rc)
3291 rc = update_element_mtime (client, n->parent);
3293 for (root = root_orig->next; root; root = root->next)
3295 if (root->type == XML_ELEMENT_NODE)
3296 break;
3299 root_orig = root;
3301 while (root);
3303 fail:
3304 if (doc)
3305 xmlFreeDoc (doc);
3307 if (dst_path)
3308 strv_free (dst_path);
3310 return rc;
3313 static gpg_error_t
3314 parse_import_opt_root (void *data, void *value)
3316 struct client_s *client = data;
3318 client->import_root = str_dup (value);
3319 return client->import_root ? 0 : GPG_ERR_ENOMEM;
3322 static gpg_error_t
3323 import_command (assuan_context_t ctx, char *line)
3325 gpg_error_t rc;
3326 struct client_s *client = assuan_get_pointer (ctx);
3327 unsigned char *result;
3328 size_t len;
3329 struct argv_s *args[] = {
3330 &(struct argv_s) {"root", OPTION_TYPE_ARG, parse_import_opt_root},
3331 NULL
3334 xfree (client->import_root);
3335 client->import_root = NULL;
3336 rc = parse_options (&line, args, client, 0);
3337 if (rc)
3338 return send_error (ctx, rc);
3340 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3341 if (rc)
3343 xfree (client->import_root);
3344 client->import_root = NULL;
3345 return send_error (ctx, rc);
3348 rc = do_import (client, client->import_root, result);
3349 xfree (client->import_root);
3350 client->import_root = NULL;
3351 return send_error (ctx, rc);
3354 static gpg_error_t
3355 do_lock (struct client_s *client, int add)
3357 gpg_error_t rc = lock_file_mutex (client, add);
3359 if (!rc)
3360 client->flags |= FLAG_LOCK_CMD;
3362 return rc;
3365 static gpg_error_t
3366 lock_command (assuan_context_t ctx, char *line)
3368 struct client_s *client = assuan_get_pointer (ctx);
3369 gpg_error_t rc;
3371 if (line && *line)
3372 return send_error (ctx, GPG_ERR_SYNTAX);
3374 rc = do_lock (client, 0);
3375 return send_error (ctx, rc);
3378 static gpg_error_t
3379 unlock_command (assuan_context_t ctx, char *line)
3381 struct client_s *client = assuan_get_pointer (ctx);
3382 gpg_error_t rc;
3384 if (line && *line)
3385 return send_error (ctx, GPG_ERR_SYNTAX);
3387 rc = unlock_file_mutex (client, 0);
3388 return send_error (ctx, rc);
3391 static gpg_error_t
3392 option_command (assuan_context_t ctx, char *line)
3394 struct client_s *client = assuan_get_pointer (ctx);
3395 gpg_error_t rc = 0;
3396 struct pinentry_option_s *pin_opts = &client->pinentry_opts;
3397 #ifdef WITH_AGENT
3398 struct agent_s *agent = client->crypto->agent;
3399 #endif
3400 char namebuf[255] = { 0 };
3401 char *name = namebuf;
3402 char *value = NULL, *p, *tmp = NULL;
3404 p = strchr (line, '=');
3405 if (!p)
3407 strncpy (namebuf, line, sizeof(namebuf));
3408 namebuf[sizeof(namebuf)-1] = 0;
3410 else
3412 strncpy (namebuf, line, strlen (line)-strlen (p));
3413 namebuf[sizeof(namebuf)-1] = 0;
3414 value = p+1;
3417 log_write1 ("OPTION name='%s' value='%s'", name, value);
3419 if (strcasecmp (name, (char *) "lock-timeout") == 0)
3421 long n = 0;
3423 if (value)
3425 n = strtol (value, &tmp, 10);
3426 if (tmp && *tmp)
3427 return send_error (ctx, GPG_ERR_INV_VALUE);
3430 client->lock_timeout = n;
3431 goto done;
3433 else if (strcasecmp (name, (char *) "NAME") == 0)
3435 if (value && strchr (value, ' '))
3436 rc = GPG_ERR_INV_VALUE;
3437 else
3439 tmp = pthread_getspecific (thread_name_key);
3440 xfree (tmp);
3441 MUTEX_LOCK (&cn_mutex);
3442 xfree (client->thd->name);
3443 client->thd->name = NULL;
3445 if (!value || !*value)
3446 pthread_setspecific (thread_name_key, str_dup (""));
3447 else
3449 client->thd->name = str_dup (value);
3450 pthread_setspecific (thread_name_key, str_dup (value));
3453 MUTEX_UNLOCK (&cn_mutex);
3455 goto done;
3457 else if (strcasecmp (name, (char *) "lc-messages") == 0)
3459 xfree (pin_opts->lc_messages);
3460 pin_opts->lc_messages = NULL;
3461 if (value && *value)
3462 pin_opts->lc_messages = str_dup (value);
3463 #ifdef WITH_AGENT
3464 if (use_agent)
3465 rc = set_agent_option (client->crypto->agent, "lc-messages", value);
3466 #endif
3468 else if (strcasecmp (name, (char *) "lc-ctype") == 0)
3470 xfree (pin_opts->lc_ctype);
3471 pin_opts->lc_ctype = NULL;
3472 if (value && *value)
3473 pin_opts->lc_ctype = str_dup (value);
3474 #ifdef WITH_AGENT
3475 if (use_agent)
3476 rc = set_agent_option (client->crypto->agent, "lc-ctype", value);
3477 #endif
3479 else if (strcasecmp (name, (char *) "ttyname") == 0)
3481 xfree (pin_opts->ttyname);
3482 pin_opts->ttyname = NULL;
3483 if (value && *value)
3484 pin_opts->ttyname = str_dup (value);
3485 #ifdef WITH_AGENT
3486 if (use_agent)
3487 rc = set_agent_option (client->crypto->agent, "ttyname", value);
3488 #endif
3490 else if (strcasecmp (name, (char *) "ttytype") == 0)
3492 xfree (pin_opts->ttytype);
3493 pin_opts->ttytype = NULL;
3494 if (value && *value)
3495 pin_opts->ttytype = str_dup (value);
3496 #ifdef WITH_AGENT
3497 if (use_agent)
3498 rc = set_agent_option (client->crypto->agent, "ttytype", value);
3499 #endif
3501 else if (strcasecmp (name, (char *) "display") == 0)
3503 xfree (pin_opts->display);
3504 pin_opts->display = NULL;
3505 if (value && *value)
3506 pin_opts->display = str_dup (value);
3507 #ifdef WITH_AGENT
3508 if (use_agent)
3509 rc = set_agent_option (client->crypto->agent, "display", value);
3510 #endif
3512 else if (strcasecmp (name, (char *) "pinentry-desc") == 0)
3514 xfree (pin_opts->desc);
3515 pin_opts->desc = NULL;
3516 if (value && *value)
3517 pin_opts->desc = str_dup (value);
3519 else if (strcasecmp (name, (char *) "pinentry-title") == 0)
3521 xfree (pin_opts->title);
3522 pin_opts->title = NULL;
3523 if (value && *value)
3524 pin_opts->title = str_dup (value);
3526 else if (strcasecmp (name, (char *) "pinentry-prompt") == 0)
3528 xfree (pin_opts->prompt);
3529 pin_opts->prompt = NULL;
3530 if (value && *value)
3531 pin_opts->prompt = str_dup (value);
3534 else if (strcasecmp (name, "pinentry-timeout") == 0)
3536 char *p = NULL;
3537 int n;
3539 if (!value)
3540 goto done;
3542 n = (int) strtol (value, &p, 10);
3544 if (*p || n < 0)
3545 return send_error (ctx, GPG_ERR_INV_VALUE);
3547 pin_opts->timeout = n;
3548 MUTEX_LOCK (&rcfile_mutex);
3549 config_set_int_param (&global_config,
3550 client->filename ? client->filename : "global",
3551 "pinentry_timeout", value);
3552 MUTEX_UNLOCK (&rcfile_mutex);
3553 goto done;
3555 else if (strcasecmp (name, "disable-pinentry") == 0)
3557 int n = 1;
3559 if (value && *value)
3561 n = (int) strtol (value, &tmp, 10);
3562 if (*tmp || n < 0 || n > 1)
3563 return send_error (ctx, GPG_ERR_INV_VALUE);
3566 if (n)
3567 client->flags |= FLAG_NO_PINENTRY;
3568 else
3569 client->flags &= ~FLAG_NO_PINENTRY;
3571 #ifdef WITH_AGENT
3572 if (use_agent)
3574 if (client->flags & FLAG_NO_PINENTRY)
3575 rc = set_agent_option (client->crypto->agent, "pinentry-mode",
3576 "loopback");
3577 else
3578 rc = set_agent_option (client->crypto->agent, "pinentry-mode",
3579 "ask");
3581 if (rc)
3582 return send_error (ctx, rc);
3584 #endif
3586 else
3587 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
3589 done:
3590 #ifdef WITH_AGENT
3591 if (!rc && use_agent && agent)
3593 rc = pinentry_merge_options (&client->crypto->agent->pinentry_opts,
3594 pin_opts);
3596 #endif
3598 return send_error (ctx, rc);
3601 static gpg_error_t
3602 do_rename (assuan_context_t ctx, char *line)
3604 struct client_s *client = assuan_get_pointer (ctx);
3605 gpg_error_t rc;
3606 char **req, **src, *dst;
3607 xmlNodePtr n, ndst;
3609 req = str_split (line, " ", 0);
3611 if (!req || !req[0] || !req[1])
3613 strv_free (req);
3614 return GPG_ERR_SYNTAX;
3617 dst = req[1];
3618 is_literal_element (&dst);
3620 if (!valid_xml_element ((xmlChar *) dst))
3622 strv_free (req);
3623 return GPG_ERR_INV_VALUE;
3626 if (strchr (req[0], '\t'))
3627 src = str_split (req[0], "\t", 0);
3628 else
3629 src = str_split (req[0], " ", 0);
3631 if (!src || !*src)
3633 rc = GPG_ERR_SYNTAX;
3634 goto fail;
3637 n = find_root_element (client, client->doc, &src, &rc, NULL, 0, 0);
3638 if (rc)
3639 goto fail;
3641 if (src[1] && n)
3642 n = find_elements (client, client->doc, n->children, src + 1, &rc, NULL, NULL,
3643 NULL, 0, 0, NULL, 0);
3645 if (!n || rc)
3646 goto fail;
3648 rc = is_element_owner (client, n);
3649 if (rc)
3650 goto fail;
3652 xmlChar *a = xmlGetProp (n, (xmlChar *) "_name");
3653 if (!a)
3655 rc = GPG_ERR_ENOMEM;
3656 goto fail;
3659 /* To prevent unwanted effects:
3661 * <root name="a"><b/></root>
3663 * RENAME a<TAB>b b
3665 if (xmlStrEqual (a, (xmlChar *) dst))
3667 xmlFree (a);
3668 rc = GPG_ERR_AMBIGUOUS_NAME;
3669 goto fail;
3672 xmlFree (a);
3673 char **tmp = NULL;
3674 if (src[1])
3676 char **p;
3678 for (p = src; *p; p++)
3680 if (!*(p + 1))
3681 break;
3682 strv_printf (&tmp, "%s", *p);
3686 strv_printf (&tmp, "!%s", dst);
3687 ndst = find_root_element (client, client->doc, &tmp, &rc, NULL, 0, 0);
3688 if (!ndst && rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3690 strv_free (tmp);
3691 goto fail;
3694 if (tmp[1] && ndst)
3695 ndst = find_elements (client, client->doc, ndst->children, tmp + 1, &rc, NULL,
3696 NULL, NULL, 0, 0, NULL, 0);
3698 strv_free (tmp);
3699 if (!ndst && rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3700 goto fail;
3702 rc = 0;
3704 /* Target may exist:
3706 * <root name="a"/>
3707 * <root name="b" target="a"/>
3709 * RENAME b a
3711 * Would need to do:
3712 * RENAME !b a
3714 if (ndst == n)
3716 rc = GPG_ERR_AMBIGUOUS_NAME;
3717 goto fail;
3720 if (ndst)
3722 rc = is_element_owner (client, ndst);
3723 if (rc)
3724 goto fail;
3726 unlink_node (client, ndst);
3727 xmlFreeNodeList (ndst);
3730 rc = add_attribute (client, n, "_name", dst);
3732 fail:
3733 strv_free (req);
3734 strv_free (src);
3735 return rc;
3738 static gpg_error_t
3739 rename_command (assuan_context_t ctx, char *line)
3741 struct client_s *client = assuan_get_pointer (ctx);
3742 gpg_error_t rc;
3743 struct argv_s *args[] = {
3744 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3745 NULL
3748 rc = parse_options (&line, args, client, 1);
3749 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3750 rc = GPG_ERR_SYNTAX;
3751 if (rc)
3752 return send_error (ctx, rc);
3754 if (client->opts & OPT_INQUIRE)
3756 unsigned char *result;
3757 size_t len;
3759 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3760 if (rc)
3761 return send_error (ctx, rc);
3763 pthread_cleanup_push (xfree, result);
3764 rc = do_rename (ctx, (char *)result);
3765 pthread_cleanup_pop (1);
3767 else
3768 rc = do_rename (ctx, line);
3770 return send_error (ctx, rc);
3773 static gpg_error_t
3774 do_copy (assuan_context_t ctx, char *line)
3776 struct client_s *client = assuan_get_pointer (ctx);
3777 gpg_error_t rc;
3778 char **req, **src = NULL, **dst = NULL;
3779 xmlNodePtr nsrc, ndst, new = NULL;
3781 req = str_split (line, " ", 0);
3782 if (!req || !req[0] || !req[1])
3784 strv_free (req);
3785 return GPG_ERR_SYNTAX;
3788 if (strchr (req[0], '\t'))
3789 src = str_split (req[0], "\t", 0);
3790 else
3791 src = str_split (req[0], " ", 0);
3793 if (!src || !*src)
3795 rc = GPG_ERR_SYNTAX;
3796 goto fail;
3799 if (strchr (req[1], '\t'))
3800 dst = str_split (req[1], "\t", 0);
3801 else
3802 dst = str_split (req[1], " ", 0);
3804 if (!dst || !*dst)
3806 rc = GPG_ERR_SYNTAX;
3807 goto fail;
3810 if (!valid_element_path (dst, 0))
3812 rc = GPG_ERR_INV_VALUE;
3813 goto fail;
3816 nsrc = find_root_element (client, client->doc, &src, &rc, NULL, 0, 0);
3817 if (rc)
3818 goto fail;
3820 if (nsrc && src[1])
3821 nsrc = find_elements (client, client->doc, nsrc->children, src + 1, &rc, NULL,
3822 NULL, NULL, 0, 0, NULL, 0);
3824 if (!nsrc || rc)
3825 goto fail;
3827 new = xmlCopyNodeList (nsrc);
3828 if (!new)
3830 rc = GPG_ERR_ENOMEM;
3831 goto fail;
3834 int create = 0;
3835 ndst = find_root_element (client, client->doc, &dst, &rc, NULL, 0, 0);
3836 if (rc == GPG_ERR_EACCES)
3837 goto fail;
3839 if (ndst && dst[1])
3841 if (ndst->children)
3842 ndst = find_elements (client, client->doc, ndst->children, dst + 1, &rc, NULL,
3843 NULL, create_target_elements_cb, 0, 0, NULL, 0);
3844 else
3845 create = 1;
3847 else
3848 create = 1;
3850 if (!ndst && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3851 goto fail;
3852 else if (!ndst || create)
3854 ndst = create_element_path (client, &dst, &rc, NULL);
3855 if (!ndst || rc)
3856 goto fail;
3859 rc = is_element_owner (client, ndst);
3860 if (rc)
3861 goto fail;
3863 /* Merge any attributes from the src node to the initial dst node. */
3864 for (xmlAttrPtr attr = new->properties; attr; attr = attr->next)
3866 if (xmlStrEqual (attr->name, (xmlChar *) "_name"))
3867 continue;
3869 xmlAttrPtr a = xmlHasProp (ndst, attr->name);
3870 if (a)
3871 xmlRemoveProp (a);
3873 xmlChar *tmp = xmlNodeGetContent (attr->children);
3874 xmlNewProp (ndst, attr->name, tmp);
3875 xmlFree (tmp);
3876 rc = add_attribute (client, ndst, NULL, NULL);
3879 xmlNodePtr n = ndst->children;
3880 xmlUnlinkNode (n);
3881 xmlFreeNodeList (n);
3882 ndst->children = NULL;
3884 if (new->children)
3886 n = xmlCopyNodeList (new->children);
3887 if (!n)
3889 rc = GPG_ERR_ENOMEM;
3890 goto fail;
3893 n = xmlAddChildList (ndst, n);
3894 if (!n)
3896 rc = GPG_ERR_ENOMEM;
3897 goto fail;
3900 rc = update_element_mtime (client, xmlDocGetRootElement (client->doc) ==
3901 ndst->parent ? ndst : ndst->parent);
3904 fail:
3905 if (new)
3907 xmlUnlinkNode (new);
3908 xmlFreeNodeList (new);
3911 if (req)
3912 strv_free (req);
3914 if (src)
3915 strv_free (src);
3917 if (dst)
3918 strv_free (dst);
3920 return rc;
3923 static gpg_error_t
3924 copy_command (assuan_context_t ctx, char *line)
3926 struct client_s *client = assuan_get_pointer (ctx);
3927 gpg_error_t rc;
3928 struct argv_s *args[] = {
3929 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3930 NULL
3933 rc = parse_options (&line, args, client, 1);
3934 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3935 rc = GPG_ERR_SYNTAX;
3936 if (rc)
3937 return send_error (ctx, rc);
3939 if (client->opts & OPT_INQUIRE)
3941 unsigned char *result;
3942 size_t len;
3944 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3945 if (rc)
3946 return send_error (ctx, rc);
3948 pthread_cleanup_push (xfree, result);
3949 rc = do_copy (ctx, (char *)result);
3950 pthread_cleanup_pop (1);
3952 else
3953 rc = do_copy (ctx, line);
3955 return send_error (ctx, rc);
3958 static gpg_error_t
3959 do_move (assuan_context_t ctx, char *line)
3961 struct client_s *client = assuan_get_pointer (ctx);
3962 gpg_error_t rc;
3963 char **req, **src = NULL, **dst = NULL;
3964 xmlNodePtr nsrc, ndst = NULL;
3966 req = str_split (line, " ", 0);
3968 if (!req || !req[0] || !req[1])
3970 strv_free (req);
3971 return GPG_ERR_SYNTAX;
3974 if (strchr (req[0], '\t'))
3975 src = str_split (req[0], "\t", 0);
3976 else
3977 src = str_split (req[0], " ", 0);
3979 if (!src || !*src)
3981 rc = GPG_ERR_SYNTAX;
3982 goto fail;
3985 if (strchr (req[1], '\t'))
3986 dst = str_split (req[1], "\t", 0);
3987 else
3988 dst = str_split (req[1], " ", 0);
3990 nsrc = find_root_element (client, client->doc, &src, &rc, NULL, 0, 0);
3991 if (rc)
3992 goto fail;
3994 if (nsrc && src[1])
3995 nsrc = find_elements (client, client->doc, nsrc->children, src + 1, &rc,
3996 NULL, NULL, NULL, 0, 0, NULL, 0);
3998 if (!nsrc)
3999 goto fail;
4001 rc = is_element_owner (client, nsrc);
4002 if (rc)
4003 goto fail;
4005 if (dst)
4007 if (!valid_element_path (dst, 0))
4009 rc = GPG_ERR_INV_VALUE;
4010 goto fail;
4013 ndst = find_root_element (client, client->doc, &dst, &rc, NULL, 0, 0);
4014 if (rc)
4015 goto fail;
4017 if (ndst && dst[1])
4018 ndst = find_elements (client, client->doc, ndst->children, dst + 1,
4019 &rc, NULL, NULL, NULL, 0, 0, NULL, 0);
4021 else
4022 ndst = xmlDocGetRootElement (client->doc);
4024 for (xmlNodePtr n = ndst; n; n = n->parent)
4026 if (n == nsrc)
4028 rc = GPG_ERR_CONFLICT;
4029 goto fail;
4033 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
4034 goto fail;
4036 rc = 0;
4038 if (ndst)
4040 xmlChar *a = node_has_attribute (nsrc, (xmlChar *) "_name");
4042 xmlNodePtr dup = find_element (client, ndst->children, (char *) a,
4043 NULL, &rc);
4044 xmlFree (a);
4046 if (rc)
4047 goto fail;
4049 if (dup)
4051 if (dup == nsrc)
4052 goto fail;
4054 if (ndst == xmlDocGetRootElement (client->doc))
4056 xmlNodePtr n = nsrc;
4057 int match = 0;
4059 while (n->parent && n->parent != ndst)
4060 n = n->parent;
4062 xmlChar *a = node_has_attribute (n, (xmlChar *) "_name");
4063 xmlChar *b = node_has_attribute (nsrc, (xmlChar *) "_name");
4065 if (xmlStrEqual (a, b))
4067 match = 1;
4068 xmlUnlinkNode (nsrc);
4069 xmlUnlinkNode (n);
4070 xmlFreeNodeList (n);
4073 xmlFree (a);
4074 xmlFree (b);
4076 if (!match)
4078 xmlUnlinkNode (dup);
4079 xmlFreeNodeList (dup);
4082 else
4083 xmlUnlinkNode (dup);
4087 if (!ndst && dst)
4089 xmlChar *name = node_has_attribute (nsrc, (xmlChar *) "_name");
4091 if (nsrc->parent == xmlDocGetRootElement (client->doc)
4092 && !strcmp ((char *) name, *dst))
4094 xmlFree (name);
4095 rc = GPG_ERR_CONFLICT;
4096 goto fail;
4099 xmlFree (name);
4100 ndst = create_element_path (client, &dst, &rc, nsrc);
4101 if (rc)
4102 goto fail;
4105 if (!ndst)
4106 goto fail;
4108 update_element_mtime (client, nsrc->parent);
4109 xmlUnlinkNode (nsrc);
4110 ndst = xmlAddChildList (ndst, nsrc);
4112 if (!ndst)
4113 rc = GPG_ERR_ENOMEM;
4114 else
4115 update_element_mtime (client, ndst->parent);
4117 fail:
4118 if (req)
4119 strv_free (req);
4121 if (src)
4122 strv_free (src);
4124 if (dst)
4125 strv_free (dst);
4127 return rc;
4130 static gpg_error_t
4131 move_command (assuan_context_t ctx, char *line)
4133 struct client_s *client = assuan_get_pointer (ctx);
4134 gpg_error_t rc;
4135 struct argv_s *args[] = {
4136 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
4137 NULL
4140 rc = parse_options (&line, args, client, 1);
4141 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
4142 rc = GPG_ERR_SYNTAX;
4143 if (rc)
4144 return send_error (ctx, rc);
4146 if (client->opts & OPT_INQUIRE)
4148 unsigned char *result;
4149 size_t len;
4151 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
4152 if (rc)
4153 return send_error (ctx, rc);
4155 pthread_cleanup_push (xfree, result);
4156 rc = do_move (ctx, (char *)result);
4157 pthread_cleanup_pop (1);
4159 else
4160 rc = do_move (ctx, line);
4162 return send_error (ctx, rc);
4165 static gpg_error_t
4166 ls_command (assuan_context_t ctx, char *line)
4168 gpg_error_t rc;
4169 char *tmp;
4170 char *dir;
4171 DIR *d;
4173 if (line && *line)
4174 return send_error (ctx, GPG_ERR_SYNTAX);
4176 tmp = str_asprintf ("%s/data", homedir);
4177 dir = expand_homedir (tmp);
4178 xfree (tmp);
4179 d = opendir (dir);
4180 rc = gpg_error_from_errno (errno);
4182 if (!d)
4184 xfree (dir);
4185 return send_error (ctx, rc);
4188 size_t len =
4189 offsetof (struct dirent, d_name) +pathconf (dir, _PC_NAME_MAX) + 1;
4190 struct dirent *p = xmalloc (len), *cur = NULL;
4191 char *list = NULL;
4193 xfree (dir);
4194 pthread_cleanup_push (xfree, p);
4195 pthread_cleanup_push ((void *)(void *)closedir, d);
4196 rc = 0;
4198 while (!readdir_r (d, p, &cur) && cur)
4200 struct stat st;
4202 if (stat (cur->d_name, &st) == -1 || !S_ISREG (st.st_mode))
4203 continue;
4205 tmp = str_asprintf ("%s%s\n", list ? list : "", cur->d_name);
4207 if (!tmp)
4209 if (list)
4210 xfree (list);
4212 rc = GPG_ERR_ENOMEM;
4213 break;
4216 xfree (list);
4217 list = tmp;
4220 pthread_cleanup_pop (1); // closedir (d)
4221 pthread_cleanup_pop (1); // xfree (p)
4223 if (rc)
4224 return send_error (ctx, rc);
4226 if (!list)
4227 return send_error (ctx, GPG_ERR_NO_DATA);
4229 list[strlen (list) - 1] = 0;
4230 pthread_cleanup_push (xfree, list);
4231 rc = xfer_data (ctx, list, strlen (list));
4232 pthread_cleanup_pop (1);
4233 return send_error (ctx, rc);
4236 static gpg_error_t
4237 bye_notify (assuan_context_t ctx, char *line)
4239 struct client_s *cl = assuan_get_pointer (ctx);
4241 cl->thd->state = CLIENT_STATE_DISCON;
4243 #ifdef WITH_GNUTLS
4244 if (cl->thd->remote)
4246 int rc;
4250 struct timeval tv = { 0, 50000 };
4252 rc = gnutls_bye (cl->thd->tls->ses, GNUTLS_SHUT_RDWR);
4253 if (rc == GNUTLS_E_AGAIN)
4254 select (0, NULL, NULL, NULL, &tv);
4256 while (rc == GNUTLS_E_AGAIN);
4258 #endif
4260 /* This will let assuan_process_next() return. */
4261 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
4263 cl->last_rc = gpg_error_from_errno (errno);
4264 return cl->last_rc;
4267 cl->last_rc = 0; // BYE command result
4268 return 0;
4271 static gpg_error_t
4272 reset_notify (assuan_context_t ctx, char *line)
4274 struct client_s *client = assuan_get_pointer (ctx);
4276 if (client)
4277 cleanup_client (client);
4279 return 0;
4283 * This is called before every Assuan command.
4285 static gpg_error_t
4286 command_startup (assuan_context_t ctx, const char *name)
4288 struct client_s *client = assuan_get_pointer (ctx);
4289 gpg_error_t rc;
4290 struct command_table_s *cmd = NULL;
4292 log_write1 ("command='%s'", name);
4293 client->last_rc = client->opts = 0;
4295 for (int i = 0; command_table[i]; i++)
4297 if (!strcasecmp (name, command_table[i]->name))
4299 if (command_table[i]->ignore_startup)
4300 return 0;
4301 cmd = command_table[i];
4302 break;
4306 if (!cmd)
4307 return GPG_ERR_UNKNOWN_COMMAND;
4309 client->last_rc = rc = gpg_error (file_modified (client, cmd));
4310 if (!rc)
4311 update_client_state (client, CLIENT_STATE_COMMAND);
4313 return rc;
4317 * This is called after every Assuan command.
4319 static void
4320 command_finalize (assuan_context_t ctx, gpg_error_t rc)
4322 struct client_s *client = assuan_get_pointer (ctx);
4324 if (!(client->flags & FLAG_LOCK_CMD))
4325 unlock_file_mutex (client, 0);
4327 unlock_flock (&client->flock_fd);
4328 log_write1 (_("command completed: rc=%u"), rc ? rc : client->last_rc);
4329 client->last_rc = gpg_error (GPG_ERR_UNKNOWN_COMMAND);
4330 #ifdef WITH_GNUTLS
4331 client->thd->buffer_timeout = client->thd->last_buffer_size = 0;
4332 #endif
4333 update_client_state (client, CLIENT_STATE_IDLE);
4336 static gpg_error_t
4337 help_command (assuan_context_t ctx, char *line)
4339 gpg_error_t rc;
4340 int i;
4342 if (!line || !*line)
4344 char *tmp;
4345 char *help = str_dup (_("Usage: HELP [<COMMAND>]\n"
4346 "For commands that take an element path as an argument, each element is "
4347 "separated with an ASCII @key{TAB} character (ASCII 0x09)."
4348 "\n" "COMMANDS:"));
4350 for (i = 0; command_table[i]; i++)
4352 if (!command_table[i]->help)
4353 continue;
4355 tmp = str_asprintf ("%s %s", help, command_table[i]->name);
4356 xfree (help);
4357 help = tmp;
4360 tmp = strip_texi_and_wrap (help);
4361 xfree (help);
4362 pthread_cleanup_push (xfree, tmp);
4363 rc = xfer_data (ctx, tmp, strlen (tmp));
4364 pthread_cleanup_pop (1);
4365 return send_error (ctx, rc);
4368 for (i = 0; command_table[i]; i++)
4370 if (!strcasecmp (line, command_table[i]->name))
4372 char *help, *tmp;
4374 if (!command_table[i]->help)
4375 break;
4377 help = strip_texi_and_wrap (command_table[i]->help);
4378 tmp = str_asprintf (_("Usage: %s"), help);
4379 xfree (help);
4380 pthread_cleanup_push (xfree, tmp);
4381 rc = xfer_data (ctx, tmp, strlen (tmp));
4382 pthread_cleanup_pop (1);
4383 return send_error (ctx, rc);
4387 return send_error (ctx, GPG_ERR_INV_NAME);
4390 static void
4391 new_command (const char *name, int ignore, int unlock, int flock_type,
4392 gpg_error_t (*handler) (assuan_context_t, char *),
4393 const char *help)
4395 struct command_table_s **tmp;
4396 int i = 0;
4398 if (command_table)
4399 for (i = 0; command_table[i]; i++);
4401 tmp = xrealloc (command_table, (i + 2) * sizeof (struct command_table_s *));
4402 assert (tmp);
4403 command_table = tmp;
4404 command_table[i] = xcalloc (1, sizeof (struct command_table_s));
4405 command_table[i]->name = name;
4406 command_table[i]->handler = handler;
4407 command_table[i]->ignore_startup = ignore;
4408 command_table[i]->unlock = unlock;
4409 command_table[i]->flock_type = flock_type;
4410 command_table[i++]->help = help;
4411 command_table[i] = NULL;
4414 void
4415 deinit_commands ()
4417 int i;
4419 for (i = 0; command_table[i]; i++)
4420 xfree (command_table[i]);
4422 xfree (command_table);
4425 static int
4426 sort_commands (const void *arg1, const void *arg2)
4428 struct command_table_s *const *a = arg1;
4429 struct command_table_s *const *b = arg2;
4431 if (!*a || !*b)
4432 return 0;
4433 else if (*a && !*b)
4434 return 1;
4435 else if (!*a && *b)
4436 return -1;
4438 return strcmp ((*a)->name, (*b)->name);
4441 static gpg_error_t
4442 passwd_command (assuan_context_t ctx, char *line)
4444 struct client_s *client = assuan_get_pointer (ctx);
4445 gpg_error_t rc;
4446 struct argv_s *args[] = {
4447 &(struct argv_s) {"reset", OPTION_TYPE_NOARG, parse_opt_reset},
4448 &(struct argv_s) {"s2k-count", OPTION_TYPE_ARG, parse_opt_s2k_count},
4449 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG, parse_opt_no_passphrase},
4450 NULL
4453 rc = peer_is_invoker (client);
4454 if (rc == GPG_ERR_EACCES)
4455 return send_error (ctx, rc);
4457 if (client->flags & FLAG_NEW)
4458 return send_error (ctx, GPG_ERR_INV_STATE);
4460 client->crypto->save.hdr.s2k_count =
4461 config_get_ulonglong (client->filename, "s2k_count");
4462 rc = parse_options (&line, args, client, 0);
4463 if (rc)
4464 return send_error (ctx, rc);
4466 if (!rc && client->opts & OPT_RESET)
4468 rc = cache_clear (client->md5file);
4469 if (!rc)
4470 send_status_all (STATUS_CACHE, NULL);
4473 if (!rc)
4475 if (!IS_PKI (client->crypto))
4477 struct crypto_s *crypto;
4479 xfree (client->crypto->filename);
4480 client->crypto->filename = str_dup (client->filename);
4481 rc = change_passwd (ctx, client->filename,
4482 client->flags & FLAG_NO_PINENTRY, &crypto,
4483 (client->opts & OPT_NO_PASSPHRASE));
4484 if (!rc)
4486 cleanup_crypto (&client->crypto);
4487 client->crypto = crypto;
4488 update_checksum (client);
4489 cleanup_crypto_stage1 (client->crypto);
4492 #ifdef WITH_AGENT
4493 else
4495 if (client->crypto->save.hdr.s2k_count)
4496 rc = send_to_agent (client->crypto->agent, NULL, NULL,
4497 "OPTION s2k-count=%lu",
4498 client->crypto->save.hdr.s2k_count);
4500 if (!rc)
4501 rc = agent_passwd (client->crypto);
4503 (void) kill_scd (client->crypto->agent);
4505 #endif
4508 return send_error (ctx, rc);
4511 static gpg_error_t
4512 parse_keygrip_opt_sign (void *data, void *value)
4514 struct client_s *client = data;
4516 (void) value;
4517 client->opts |= OPT_SIGN;
4518 return 0;
4521 static gpg_error_t
4522 keygrip_command (assuan_context_t ctx, char *line)
4524 struct client_s *client = assuan_get_pointer (ctx);
4525 gpg_error_t rc;
4526 struct crypto_s *crypto = NULL;
4527 struct argv_s *args[] = {
4528 &(struct argv_s) {"sign", OPTION_TYPE_NOARG, parse_keygrip_opt_sign},
4529 NULL
4532 if (!line || !*line)
4533 return send_error (ctx, GPG_ERR_SYNTAX);
4535 rc = parse_options (&line, args, client, 1);
4536 if (rc)
4537 return send_error (ctx, rc);
4539 if (!valid_filename (line))
4540 return send_error (ctx, GPG_ERR_INV_VALUE);
4542 rc = init_client_crypto (&crypto);
4543 if (rc)
4544 return send_error (ctx, rc);
4546 rc = read_data_file (line, crypto);
4547 if (!rc)
4549 char *hexgrip = NULL;
4551 if (!IS_PKI (crypto))
4553 cleanup_crypto (&crypto);
4554 return send_error (ctx, GPG_ERR_NOT_SUPPORTED);
4557 if (client->opts & OPT_SIGN)
4559 if (valid_keygrip (crypto->sign_grip, sizeof (crypto->sign_grip)))
4560 hexgrip = bin2hex (crypto->sign_grip, sizeof (crypto->sign_grip));
4563 if (!hexgrip)
4564 hexgrip = bin2hex (crypto->grip, sizeof (crypto->grip));
4566 if (!hexgrip)
4567 rc = GPG_ERR_ENOMEM;
4568 else
4569 rc = xfer_data (ctx, hexgrip, strlen (hexgrip));
4571 xfree (hexgrip);
4574 UPDATE_AGENT_CTX (client, crypto);
4575 cleanup_crypto (&crypto);
4576 return send_error (ctx, rc);
4579 static gpg_error_t
4580 parse_opt_data (void *data, void *value)
4582 struct client_s *client = data;
4584 (void) value;
4585 client->opts |= OPT_DATA;
4586 return 0;
4589 static gpg_error_t
4590 send_client_list (assuan_context_t ctx)
4592 struct client_s *client = assuan_get_pointer (ctx);
4593 gpg_error_t rc = 0;
4595 if (client->opts & OPT_VERBOSE)
4597 unsigned i, t;
4598 char **list = NULL;
4599 char *line;
4601 MUTEX_LOCK (&cn_mutex);
4602 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
4603 t = slist_length (cn_thread_list);
4605 for (i = 0; i < t; i++)
4607 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
4608 char *tmp;
4610 if (thd->state == CLIENT_STATE_UNKNOWN)
4611 continue;
4613 tmp = build_client_info_line (thd, 0);
4614 if (tmp)
4616 char **l = strv_cat (list, tmp);
4617 if (!l)
4618 rc = GPG_ERR_ENOMEM;
4619 else
4620 list = l;
4622 else
4623 rc = GPG_ERR_ENOMEM;
4625 if (rc)
4627 strv_free (list);
4628 break;
4632 pthread_cleanup_pop (1);
4633 if (rc)
4634 return rc;
4636 line = strv_join ("\n", list);
4637 strv_free (list);
4638 pthread_cleanup_push (xfree, line);
4639 rc = xfer_data (ctx, line, strlen (line));
4640 pthread_cleanup_pop (1);
4641 return rc;
4644 if (client->opts & OPT_DATA)
4646 char buf[ASSUAN_LINELENGTH];
4648 MUTEX_LOCK (&cn_mutex);
4649 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
4650 snprintf (buf, sizeof (buf), "%u", slist_length (cn_thread_list));
4651 pthread_cleanup_pop (1);
4652 rc = xfer_data (ctx, buf, strlen (buf));
4654 else
4655 rc = send_status (ctx, STATUS_CLIENTS, NULL);
4657 return rc;
4660 static gpg_error_t
4661 getinfo_command (assuan_context_t ctx, char *line)
4663 struct client_s *client = assuan_get_pointer (ctx);
4664 gpg_error_t rc;
4665 char buf[ASSUAN_LINELENGTH];
4666 struct argv_s *args[] = {
4667 &(struct argv_s) {"data", OPTION_TYPE_NOARG, parse_opt_data},
4668 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_opt_verbose},
4669 NULL
4672 rc = parse_options (&line, args, client, 1);
4673 if (rc)
4674 return send_error (ctx, rc);
4676 if (!strcasecmp (line, "clients"))
4678 rc = send_client_list (ctx);
4680 else if (!strcasecmp (line, "cache"))
4682 if (client->opts & OPT_DATA)
4684 snprintf (buf, sizeof (buf), "%u", cache_file_count ());
4685 rc = xfer_data (ctx, buf, strlen (buf));
4687 else
4688 rc = send_status (ctx, STATUS_CACHE, NULL);
4690 else if (!strcasecmp (line, "pid"))
4692 char buf[32];
4693 pid_t pid = getpid ();
4695 snprintf (buf, sizeof (buf), "%i", pid);
4696 rc = xfer_data (ctx, buf, strlen (buf));
4698 else if (!strcasecmp (line, "version"))
4700 char *buf = str_asprintf ("0x%06x %s%s", VERSION_HEX,
4701 #ifdef WITH_LIBACL
4702 "ACL "
4703 #endif
4704 #ifdef WITH_GNUTLS
4705 "GNUTLS "
4706 #endif
4707 #ifdef WITH_QUALITY
4708 "QUALITY "
4709 #endif
4710 "", use_agent ? "AGENT" : "");
4711 rc = xfer_data (ctx, buf, strlen (buf));
4712 xfree (buf);
4714 else if (!strcasecmp (line, "last_error"))
4716 if (client->last_error)
4717 rc = xfer_data (ctx, client->last_error, strlen (client->last_error));
4718 else
4719 rc = GPG_ERR_NO_DATA;
4721 else if (!strcasecmp (line, "user"))
4723 char *user = NULL;
4725 #ifdef WITH_GNUTLS
4726 if (client->thd->remote)
4727 user = str_asprintf ("#%s", client->thd->tls->fp);
4728 else
4729 user = get_username (client->thd->peer->uid);
4730 #else
4731 user = get_username (client->thd->peer->uid);
4732 #endif
4733 if (user)
4735 pthread_cleanup_push (xfree, user);
4736 rc = xfer_data (ctx, user, strlen (user));
4737 pthread_cleanup_pop (1);
4739 else
4740 rc = GPG_ERR_NO_DATA;
4742 else
4743 rc = gpg_error (GPG_ERR_SYNTAX);
4745 return send_error (ctx, rc);
4748 #ifdef WITH_AGENT
4749 static gpg_error_t
4750 send_data_cb (void *user, const void *buf, size_t len)
4752 assuan_context_t ctx = user;
4754 return assuan_send_data (ctx, buf, len);
4757 static gpg_error_t
4758 send_status_cb (void *user, const char *line)
4760 assuan_context_t ctx = user;
4761 char keyword[200], *k;
4762 const char *p;
4764 for (p = line, k = keyword; *p; p++)
4766 if (isspace (*p))
4767 break;
4769 *k++ = *p;
4772 *k = 0;
4773 if (*p == '#')
4774 p++;
4776 while (isspace (*p))
4777 p++;
4779 return assuan_write_status (ctx, keyword, *p ? p : NULL);
4781 #endif
4783 static gpg_error_t
4784 kill_command (assuan_context_t ctx, char *line)
4786 struct client_s *client = assuan_get_pointer (ctx);
4787 gpg_error_t rc;
4788 unsigned i, t;
4790 if (!line || !*line)
4791 return send_error (ctx, GPG_ERR_SYNTAX);
4793 MUTEX_LOCK (&cn_mutex);
4794 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
4795 t = slist_length (cn_thread_list);
4796 rc = GPG_ERR_ESRCH;
4798 for (i = 0; i < t; i++)
4800 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
4801 char *tmp = str_asprintf ("%p", thd->tid);
4803 if (strcmp (line, tmp))
4805 xfree (tmp);
4806 continue;
4809 xfree (tmp);
4810 rc = peer_is_invoker (client);
4811 if (!rc)
4813 #ifdef HAVE_PTHREAD_CANCEL
4814 rc = pthread_cancel (thd->tid);
4815 #else
4816 close (thd->fd);
4817 thd->fd = -1;
4818 #endif
4819 break;
4822 rc = GPG_ERR_EACCES;
4823 if (config_get_boolean ("global", "strict_kill"))
4824 break;
4826 #ifdef WITH_GNUTLS
4827 if (client->thd->remote && thd->remote)
4829 if (!strcmp (client->thd->tls->fp, thd->tls->fp))
4831 #ifdef HAVE_PTHREAD_CANCEL
4832 rc = pthread_cancel (thd->tid);
4833 #else
4834 close (thd->fd);
4835 thd->fd = -1;
4836 #endif
4837 break;
4840 else if (!client->thd->remote && !thd->remote)
4841 #endif
4843 if (client->thd->peer->uid == thd->peer->uid)
4845 #ifdef HAVE_PTHREAD_CANCEL
4846 rc = pthread_cancel (thd->tid);
4847 #else
4848 close (thd->fd);
4849 thd->fd = -1;
4850 #endif
4853 break;
4856 pthread_cleanup_pop (1);
4857 return send_error (ctx, rc);
4860 static gpg_error_t
4861 agent_command (assuan_context_t ctx, char *line)
4863 gpg_error_t rc = 0;
4865 if (!use_agent)
4866 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
4868 #ifdef WITH_AGENT
4869 struct client_s *client = assuan_get_pointer (ctx);
4871 if (!line || !*line)
4872 return send_error (ctx, GPG_ERR_SYNTAX);
4874 assuan_set_flag (client->crypto->agent->ctx, ASSUAN_CONVEY_COMMENTS, 1);
4875 rc = assuan_transact (client->crypto->agent->ctx, line, send_data_cb,
4876 client->ctx, agent_loopback_cb, client->crypto,
4877 send_status_cb, client->ctx);
4878 if (gpg_err_code (rc) == GPG_ERR_ASS_CANCELED)
4880 char *line;
4881 size_t len;
4883 rc = assuan_write_line (client->crypto->agent->ctx, "CAN");
4884 if (!rc)
4886 rc = assuan_read_line (client->crypto->agent->ctx, &line, &len);
4887 if (!rc)
4888 rc = gpg_error (GPG_ERR_ASS_CANCELED);
4892 assuan_set_flag (client->crypto->agent->ctx, ASSUAN_CONVEY_COMMENTS, 0);
4893 #endif
4894 return send_error (ctx, rc);
4897 void
4898 init_commands ()
4900 /* !BEGIN-HELP-TEXT!
4902 * This comment is used as a marker to generate the offline documentation
4903 * found in doc/pwmd.info. The indentation needs to be kept for the awk
4904 * script to determine where commands begin and end.
4906 new_command("HELP", 1, 1, 0, help_command, _(
4907 "HELP [<COMMAND>]\n"
4908 "Show available commands or command specific help text."
4911 new_command("AGENT", 1, 1, 0, agent_command, _(
4912 "AGENT <command>\n"
4913 "Send a @command{gpg-agent} protocol @var{command} directly to the "
4914 "@command{gpg-agent}."
4917 new_command("KILL", 1, 0, 0, kill_command, _(
4918 "KILL <thread_id>\n"
4919 "Terminates the client identified by @var{thread_id} and releases any file "
4920 "lock or other resources it has held. See @code{GETINFO} (@pxref{GETINFO}) "
4921 "for details about listing connected clients. The @code{invoking_user} "
4922 "(@pxref{Configuration}) may kill any client while others may only kill "
4923 "clients of the same @code{UID} or @abbr{TLS} fingerprint.\n"
4926 new_command("GETINFO", 1, 1, 0, getinfo_command, _(
4927 "GETINFO [--data] [--verbose] CACHE | CLIENTS | PID | USER | LAST_ERROR | VERSION\n"
4928 "Get server and other information: @var{CACHE} returns the number of cached "
4929 "documents via a status message. @var{CLIENTS} returns the number of "
4930 "connected clients via a status message or a list of connected clients when "
4931 "the @option{--verbose} parameter is used. The list contains space delimited "
4932 "fields: the thread ID, client name, opened file (@code{/} if none opened), "
4933 "file lock status, whether the current client is self, client state, "
4934 "user ID or TLS fingerprint of the connected client and username if the "
4935 "client is a local one. "
4936 "Client state @code{0} is an unknown client state, @code{1} indicates the "
4937 "client has connected but hasn't completed initializing, @code{2} indicates "
4938 "that the client is idle, @code{3} means the "
4939 "client is in a command and @code{4} means the client is disconnecting. This "
4940 "line is always returned with a data response. @var{PID} returns the process "
4941 "ID number of the server via a data response. @var{VERSION} returns the server "
4942 "version number and compile-time features with a data response with each "
4943 "being space delimited. @var{LAST_ERROR} returns a detailed description of "
4944 "the last failed command when available. @var{USER} returns the username or "
4945 "@abbr{TLS} hash of the connected client. @xref{Status Messages}. "
4946 "\n"
4947 "When the @option{--data} option is specified then the result will be sent "
4948 "via a data response rather than a status message."
4951 new_command("PASSWD", 0, 0, FLOCK_TYPE_EX|FLOCK_TYPE_KEEP, passwd_command, _(
4952 "PASSWD [--reset] [--s2k-count=N] [--no-passphrase]\n"
4953 "Changes the passphrase of the secret key required to open the current "
4954 "file or the passphrase of a symmetrically encrypted data file. When the "
4955 "@option{--reset} option is passed then the cache entry for the current "
4956 "file will be reset and the passphrase, if any, will be required during the "
4957 "next @code{OPEN} (@pxref{OPEN})."
4958 "\n"
4959 "The @option{--s2k-count} option sets or changes (@pxref{SAVE}) the number "
4960 "of hash iterations for a passphrase and must be either @code{0} to use "
4961 "the calibrated count of the machine (the default), or a value greater than "
4962 "or equal to @code{65536}. This option has no effect for symmetrically "
4963 "encrypted data files."
4964 "\n"
4965 "The @option{--no-passphrase} option will prevent requiring a passphrase for "
4966 "the data file, although a passphrase may be required when changing it."
4967 "\n"
4968 "This command is not available for non-invoking clients "
4969 "(@pxref{Access Control})."
4972 new_command("KEYGRIP", 1, 1, FLOCK_TYPE_SH|FLOCK_TYPE_KEEP, keygrip_command, _(
4973 "KEYGRIP [--sign] <filename>\n"
4974 "Returns the hex encoded keygrip of the specified @var{filename} with a "
4975 "data response."
4976 "\n"
4977 "When the @option{--sign} option is specified then the key used for signing "
4978 "of the specified @var{filename} will be returned."
4979 "\n"
4980 "For symmetrically encrypted data files this command returns the error "
4981 "GPG_ERR_NOT_SUPPORTED."
4984 new_command("OPEN", 1, 1, FLOCK_TYPE_SH|FLOCK_TYPE_KEEP, open_command, _(
4985 "OPEN [--lock] <filename> [<passphrase>]\n"
4986 "Opens @var{filename} using @var{passphrase}. When the filename is not "
4987 "found on the file-system then a new document will be created. If the file "
4988 "is found, it is looked for in the file cache. If cached and no "
4989 "@var{passphrase} was specified then the cached document is opened. When not "
4990 "cached, @cite{pinentry(1)} will be used to retrieve the passphrase to use "
4991 "for decryption unless @option{disable-pinentry} (@pxref{OPTION}) was "
4992 "specified."
4993 "\n"
4994 "When the @option{--lock} option is passed then the file mutex will be "
4995 "locked as if the @code{LOCK} command (@pxref{LOCK}) had been sent after the "
4996 "file has been opened."
4999 new_command("SAVE", 0, 0, FLOCK_TYPE_EX|FLOCK_TYPE_KEEP, save_command, _(
5000 "SAVE [--no-passphrase] [--reset] [--ask] [--no-agent] [--s2k-count=N] [--cipher=<algo>] [--cipher-iterations=N] [--inquire-keyparam] [--keygrip=hexstring] [--sign-keygrip=hexstring]\n"
5001 "Writes the @abbr{XML} document to disk. The file written to is the file that "
5002 "was opened using the @code{OPEN} command (@pxref{OPEN}). If the file is a "
5003 "new one or the option @option{--inquire-keyparam} was passed, then a new "
5004 "keypair will be generated and a pinentry will be used to prompt for the "
5005 "passphrase to encrypt with unless the @option{--no-passphrase} option was "
5006 "passed in which case the data file will not be passphrase protected. "
5007 "\n"
5008 "The @option{--no-agent} option disables use of @command{gpg-agent} for "
5009 "passphrase retrieval and caching of new files when @command{gpg-agent} "
5010 "use is enabled. The datafile will be symmetrically encrypted and will not "
5011 "use or generate any keypair."
5012 "\n"
5013 "The @option{--reset} option will clear the cache entry for the current file "
5014 "and require a passphrase, if needed, before saving."
5015 "\n"
5016 "The @option{--ask} option will prompt for the passphrase of the current file, "
5017 "if needed, before saving. This differs from the @option{--reset} option by "
5018 "keeping the cache entry in case of an invalid passphrase or some other failure "
5019 "which may otherwise cause a denial of service for other clients."
5020 "\n"
5021 "The @option{--cipher} option can be used to encrypt the @abbr{XML} data to "
5022 "an alternate cipher. The default is @code{aes256}. See the Configuration "
5023 "(@pxref{Configuration}) for available ciphers."
5024 "\n"
5025 "The @option{--cipher-iterations} option specifies the number of times to "
5026 "hash the passphrase before encrypting the XML data. The default is "
5027 "@code{5000000}. This option is an alias for @option{--s2k-count} since "
5028 "version @var{3.0.15} of @command{pwmd}."
5029 "\n"
5030 "The @option{--inquire-keyparam} option will send a server @emph{INQUIRE} to "
5031 "the client to obtain the key paramaters to use when generating a new "
5032 "keypair. The inquired data is expected to be an S-expression. If not "
5033 "specified then an @samp{RSA} key of @samp{2048} bits will be generated "
5034 "unless otherwise set in the configuration file (@pxref{Configuration}). Note "
5035 "that when this option is specified a new keypair will be generated "
5036 "reguardless if the file is a new one and that if the data file is protected "
5037 "the passphrase to open it will be required before generating the new "
5038 "keypair. This option is not available for non-invoking clients "
5039 "(@pxref{Access Control})."
5040 "\n"
5041 "You can encrypt the data file to a public key other than the one that it "
5042 "was originally encrypted with by passing the @option{--keygrip} option with "
5043 "the hex encoded keygrip of the public key as its argument. The keygrip may "
5044 "be of any key that @command{gpg-agent} knows about. The "
5045 "@option{--sign-keygrip} option may also be used to sign with an alternate "
5046 "secret key. Use the @code{KEYGRIP} (@pxref{KEYGRIP}) command to obtain the "
5047 "keygrip of an existing data file. This option may be needed when using a "
5048 "smartcard. This option has no effect with symmetrically encrypted data "
5049 "files. These options are not available for non-invoking clients "
5050 "(@pxref{Access Control})."
5051 "\n"
5052 "The @option{--s2k-count} option sets number of hash iterations for a "
5053 "passphrase. A value less-than @code{65536} will use the machine calibrated "
5054 "value and is the default when using @command{gpg-agent}. This setting only "
5055 "affects new files when using @command{gpg-agent}. To change the setting use "
5056 "the @code{PASSWD} command (@pxref{PASSWD}). This option is an alias for "
5057 "option @option{--cipher-iterations} when not using @command{gpg-agent}."
5060 new_command("ISCACHED", 1, 0, 0, iscached_command, _(
5061 "ISCACHED [--lock] <filename>\n"
5062 "An @emph{OK} response is returned if the specified @var{filename} is found "
5063 "in the file cache. If not found in the cache but exists on the filesystem "
5064 "then @var{GPG_ERR_NO_DATA} is returned. Otherwise a filesystem error is "
5065 "returned."
5066 "\n"
5067 "The @option{lock} option will lock the file mutex of @var{filename} when the "
5068 "file exists; it does not need to be opened nor cached. The lock will be "
5069 "released when the client exits or sends the @code{UNLOCK} (@pxref{UNLOCK}) "
5070 "command."
5073 new_command("CLEARCACHE", 1, 1, 0, clearcache_command, _(
5074 "CLEARCACHE [<filename>]\n"
5075 "Clears a file cache entry for all or the specified @var{filename}."
5078 new_command("CACHETIMEOUT", 1, 1, 0, cachetimeout_command, _(
5079 "CACHETIMEOUT <filename> <seconds>\n"
5080 "The time in @var{seconds} until @var{filename} will be removed from the "
5081 "cache. @code{-1} will keep the cache entry forever, @code{0} will require "
5082 "the passphrase for each @code{OPEN} or @code{SAVE} command (@pxref{OPEN}, "
5083 "@pxref{SAVE}). @xref{Configuration}, and the @code{cache_timeout} "
5084 "parameter."
5087 new_command("LIST", 0, 1, 0, list_command, _(
5088 "LIST [--inquire] [--no-recurse] [--verbose] [--with-target] [--all] [[!]element[<TAB>[!]child[..]]]\n"
5089 "If no element path is given then a newline separated list of root elements "
5090 "is returned with a data response. If given, then all reachable elements "
5091 "of the specified element path are returned unless the @option{--no-recurse} "
5092 "option is specified. If specified, only the child elements of the element "
5093 "path are returned without recursing into grandchildren. Each resulting "
5094 "element is prefixed with the literal @code{!} character when the element "
5095 "contains no @code{target} attribute. @xref{Target Attribute}, for details."
5096 "\n"
5097 "When the @option{--verbose} option is passed then each element path "
5098 "returned will have zero or more flags appened to it. These flags are "
5099 "delimited from the element path by a single space character. A flag itself "
5100 "is a single character. Flag @code{P} indicates that access to the element "
5101 "is denied. Flag @code{+} indicates that there are child nodes of "
5102 "the current element path. Flag @code{E} indicates that an element of an "
5103 "element path contained in a @var{target} attribute could not be found. Flag "
5104 "@code{O} indicates that a @var{target} attribute recursion limit was reached "
5105 "(@pxref{Configuration}). Flag @code{T} will append the resolved element path "
5106 "of the @var{target} attribute contained in the current element (see below)."
5107 "\n"
5108 "The @option{--with-target} option implies @option{--verbose} and will append "
5109 "an additional flag @code{T} followed by a single space then an element path. "
5110 "The appended element path is the resolved path (@pxref{REALPATH}) of the "
5111 "current element when it contains a @var{target} attribute. When no "
5112 "@var{target} attribute is found then no flag will be appended."
5113 "\n"
5114 "The @option{--no-recurse} option limits the amount of data returned to only "
5115 "the listing of children of the specified element path and not any "
5116 "grandchildren."
5117 "\n"
5118 "The @option{--all} option lists the entire element tree for each root "
5119 "element. This option also implies option @option{--verbose}."
5120 "\n"
5121 "When the @option{--inquire} option is passed then all remaining non-option "
5122 "arguments are retrieved via a server @emph{INQUIRE}."
5125 new_command("REALPATH", 0, 1, 0, realpath_command, _(
5126 "REALPATH [--inquire] [!]element[<TAB>[!]child[..]]\n"
5127 "Resolves all @code{target} attributes of the specified element path and "
5128 "returns the result with a data response. @xref{Target Attribute}, for details."
5129 "\n"
5130 "When the @option{--inquire} option is passed then all remaining non-option "
5131 "arguments are retrieved via a server @emph{INQUIRE}."
5134 new_command("STORE", 0, 1, 0, store_command, _(
5135 "STORE [!]element[<TAB>[!]child[..]]<TAB>[content]\n"
5136 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
5137 "\n"
5138 "Creates a new element path or modifies the @var{content} of an existing "
5139 "element. If only a single element is specified then a new root element is "
5140 "created. Otherwise, elements are @key{TAB} delimited and the content will be "
5141 "set to the final @key{TAB} delimited element. If no @var{content} is "
5142 "specified after the final @key{TAB}, then the content of an existing "
5143 "element will be removed; or empty when creating a new element."
5144 "\n"
5145 "The only restriction of an element name is that it not contain whitespace "
5146 "or begin with the literal element character @code{!} unless specifying a "
5147 "literal element (@pxref{Target Attribute}). There is no whitespace between "
5148 "the @key{TAB} delimited elements. It is recommended that the content of an "
5149 "element be base64 encoded when it contains control or @key{TAB} characters "
5150 "to prevent @abbr{XML} parsing and @command{pwmd} syntax errors."
5153 new_command("RENAME", 0, 1, 0, rename_command, _(
5154 "RENAME [--inquire] [!]element[<TAB>[!]child[..]] <value>\n"
5155 "Renames the specified @var{element} to the new @var{value}. If an element of "
5156 "the same name as the @var{value} already exists it will be overwritten."
5157 "\n"
5158 "When the @option{--inquire} option is passed then all remaining non-option "
5159 "arguments are retrieved via a server @emph{INQUIRE}."
5162 new_command("COPY", 0, 1, 0, copy_command, _(
5163 "COPY [--inquire] [!]source[<TAB>[!]child[..]] [!]dest[<TAB>[!]child[..]]\n"
5164 "Copies the entire element tree starting from the child node of the source "
5165 "element, to the destination element path. If the destination element path "
5166 "does not exist then it will be created; otherwise it is overwritten."
5167 "\n"
5168 "Note that attributes from the source element are merged into the "
5169 "destination element when the destination element path exists. When an "
5170 "attribute of the same name exists in both the source and destination "
5171 "elements then the destination attribute will be updated to the source "
5172 "attribute value."
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("MOVE", 0, 1, 0, move_command, _(
5179 "MOVE [--inquire] [!]source[<TAB>[!]child[..]] [[!]dest[<TAB>[!]child[..]]]\n"
5180 "Moves the source element path to the destination element path. If the "
5181 "destination is not specified then it will be moved to the root node of the "
5182 "document. If the destination is specified and exists then it will be "
5183 "overwritten; otherwise non-existing elements of the destination element "
5184 "path will be created."
5185 "\n"
5186 "When the @option{--inquire} option is passed then all remaining non-option "
5187 "arguments are retrieved via a server @emph{INQUIRE}."
5190 new_command("DELETE", 0, 1, 0, delete_command, _(
5191 "DELETE [--inquire] [!]element[<TAB>[!]child[..]]\n"
5192 "Removes the specified element path and all of its children. This may break "
5193 "an element with a @code{target} attribute (@pxref{Target Attribute}) that "
5194 "refers to this element or any of its children."
5195 "\n"
5196 "When the @option{--inquire} option is passed then all remaining non-option "
5197 "arguments are retrieved via a server @emph{INQUIRE}."
5200 new_command("GET", 0, 1, 0, get_command, _(
5201 "GET [--inquire] [!]element[<TAB>[!]child[..]]\n"
5202 "Retrieves the content of the specified element. The content is returned "
5203 "with a data response."
5204 "\n"
5205 "When the @option{--inquire} option is passed then all remaining non-option "
5206 "arguments are retrieved via a server @emph{INQUIRE}."
5209 new_command("ATTR", 0, 1, 0, attr_command, _(
5210 "ATTR [--inquire] SET|GET|DELETE|LIST [<attribute>] [!]element[<TAB>[!]child[..]] ..\n"
5211 "@table @asis\n"
5212 "@item ATTR SET attribute [!]element[<TAB>[!]child[..]] [value]\n"
5213 "\n"
5214 " Stores or updates an @var{attribute} name and optional @var{value} of an "
5215 "element. When no @var{value} is specified any existing value will be removed."
5216 "\n"
5217 "@item ATTR DELETE attribute [!]element[<TAB>[!]child[..]]\n"
5218 "\n"
5219 " Removes an @var{attribute} from an element."
5220 "\n"
5221 "@item ATTR LIST [!]element[<TAB>[!]child[..]]\n"
5222 "\n"
5223 " Retrieves a newline separated list of attributes names and values "
5224 "from the specified element. Each attribute name and value is space delimited."
5225 "\n"
5226 "@item ATTR GET attribute [!]element[<TAB>[!]child[..]]\n"
5227 "\n"
5228 " Retrieves the value of an @var{attribute} from an element."
5229 "@end table\n"
5230 "\n"
5231 "The @code{_name} attribute (case sensitive) cannot be removed nor modified. "
5232 "Use the @code{DELETE} (@pxref{DELETE}) or @code{RENAME} (@pxref{RENAME}) "
5233 "commands instead."
5234 "\n"
5235 "The @code{_mtime} attribute is updated each time an element is modified by "
5236 "either storing content, editing attributes or by deleting a child element. "
5237 "The @code{_ctime} attribute is created for each new element in an element "
5238 "path."
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 "@xref{Target Attribute}, for details about this special attribute."
5246 new_command("XPATH", 0, 1, 0, xpath_command, _(
5247 "XPATH [--inquire] <expression>[<TAB>[value]]\n"
5248 "Evaluates an XPath @var{expression}. If no @var{value} argument is "
5249 "specified it is assumed the expression is a request to return a result. "
5250 "Otherwise, the result is set to the @var{value} argument and the document is "
5251 "updated. If there is no @var{value} after the @key{TAB} character, the value "
5252 "is assumed to be empty and the document is updated. For example:"
5253 "@sp 1\n"
5254 "@example\n"
5255 "XPATH //element[@@_name='password']@key{TAB}\n"
5256 "@end example\n"
5257 "@sp 1"
5258 "would clear the content of all @code{password} elements in the data file "
5259 "while leaving off the trailing @key{TAB} would return all @code{password} "
5260 "elements in @abbr{XML} format."
5261 "\n"
5262 "When the @option{--inquire} option is passed then all remaining non-option "
5263 "arguments are retrieved via a server @emph{INQUIRE}."
5264 "\n"
5265 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
5266 "expression syntax."
5269 new_command("XPATHATTR", 0, 1, 0, xpathattr_command, _(
5270 "XPATHATTR [--inquire] SET|DELETE <name> <expression>[<TAB>[<value>]]\n"
5271 "Like the @code{XPATH} command (@pxref{XPATH}) but operates on element "
5272 "attributes and does not return a result. For the @var{SET} operation the "
5273 "@var{value} is optional but the field is required. If not specified then "
5274 "the attribute value will be empty. For example:"
5275 "@sp 1"
5276 "@example\n"
5277 "XPATHATTR SET password //element[@@_name='password']@key{TAB}\n"
5278 "@end example\n"
5279 "@sp 1"
5280 "would create an @code{password} attribute for each @code{password} element "
5281 "found in the document. The attribute value will be empty but still exist."
5282 "\n"
5283 "When the @option{--inquire} option is passed then all remaining non-option "
5284 "arguments are retrieved via a server @emph{INQUIRE}."
5285 "\n"
5286 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
5287 "expression syntax."
5290 new_command("IMPORT", 0, 1, 0, import_command, _(
5291 "IMPORT [--root=[!]element[<TAB>[!]child[..]]] <content>\n"
5292 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
5293 "\n"
5294 "Like the @code{STORE} command (@pxref{STORE}), but the @var{content} "
5295 "argument is raw @abbr{XML} data. The content is created as a child of "
5296 "the element path specified with the @option{--root} option or at the "
5297 "document root when not specified. Existing elements of the same name will "
5298 "be overwritten."
5299 "\n"
5300 "The content must begin with an @abbr{XML} element node. @xref{Introduction}, "
5301 "for details."
5304 new_command("DUMP", 0, 1, 0, dump_command, _(
5305 "DUMP\n"
5306 "Shows the in memory @abbr{XML} document with indenting. @xref{XPATH}, for "
5307 "dumping a specific node."
5310 new_command("LOCK", 0, 0, 0, lock_command, _(
5311 "LOCK\n"
5312 "Locks the mutex associated with the opened file. This prevents other clients "
5313 "from sending commands to the same opened file until the client "
5314 "that sent this command either disconnects or sends the @code{UNLOCK} "
5315 "command. @xref{UNLOCK}."
5318 new_command("UNLOCK", 1, 0, 0, unlock_command, _(
5319 "UNLOCK\n"
5320 "Unlocks the file mutex which was locked with the @code{LOCK} command or "
5321 "a commands' @option{--lock} option (@pxref{LOCK}, @pxref{OPEN}, "
5322 "@pxref{ISCACHED})."
5325 new_command("GETCONFIG", 1, 1, FLOCK_TYPE_SH|FLOCK_TYPE_KEEP, getconfig_command, _(
5326 "GETCONFIG [filename] <parameter>\n"
5327 "Returns the value of a @command{pwmd} configuration @var{parameter} with a "
5328 "data response. If no file has been opened then the value for @var{filename} "
5329 "or the default from the @samp{global} section will be returned. If a file "
5330 "has been opened and no @var{filename} is specified, a value previously "
5331 "set with the @code{OPTION} command (@pxref{OPTION}) will be returned."
5334 new_command("OPTION", 1, 1, 0, option_command, _(
5335 "OPTION <NAME>=<VALUE>\n"
5336 "Sets a client option @var{name} to @var{value}. The value for an option is "
5337 "kept for the duration of the connection."
5338 "\n"
5339 "@table @asis\n"
5340 "@item DISABLE-PINENTRY\n"
5341 "Disable use of @command{pinentry} for passphrase retrieval. When set, a "
5342 "server inquire is sent to the client to obtain the passphrase. This option "
5343 "may be set as needed before the @code{OPEN} (@pxref{OPEN}), @code{PASSWD} "
5344 "(@pxref{PASSWD}) and @code{SAVE} (@pxref{SAVE}) commands."
5345 "\n"
5346 "@item PINENTRY-TIMEOUT\n"
5347 "Sets the number of seconds before a pinentry prompt will return an error "
5348 "while waiting for user input."
5349 "\n"
5350 "@item TTYNAME\n"
5351 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
5352 "\n"
5353 "@item TTYTYPE\n"
5354 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
5355 "\n"
5356 "@item DISPLAY\n"
5357 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
5358 "\n"
5359 "@item PINENTRY-DESC\n"
5360 "Sets the description string of the @command{gpg-agent} and @command{pinentry} dialog."
5361 "\n"
5362 "@item PINENTRY-TITLE\n"
5363 "Sets the title string of the @command{gpg-agent} and @command{pinentry} dialog."
5364 "\n"
5365 "@item PINENTRY-PROMPT\n"
5366 "Sets the prompt string of the @command{gpg-agent} and @command{pinentry} dialog."
5367 "\n"
5368 "@item LC-CTYPE\n"
5369 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
5370 "\n"
5371 "@item LC-MESSAGES\n"
5372 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
5373 "\n"
5374 "@item NAME\n"
5375 "Associates the thread ID of the connection with the specified textual "
5376 "representation. Useful for debugging log messages. May not contain whitespace."
5377 "\n"
5378 "@item LOCK-TIMEOUT\n"
5379 "When not @code{0}, the duration in tenths of a second to wait for the file "
5380 "mutex which has been locked by another thread to be released before returning "
5381 "an error. When @code{-1}, then an error will be returned immediately."
5382 "@end table\n"
5385 new_command("LS", 1, 1, 0, ls_command, _(
5386 "LS\n"
5387 "Lists the available data files stored in the data directory "
5388 "(@file{~/.pwmd/data}). The result is a newline separated list of filenames."
5391 new_command("RESET", 1, 1, 0, NULL, _(
5392 "RESET\n"
5393 "Closes the currently opened file but keeps any previously set client options."
5396 new_command("NOP", 1, 1, 0, NULL, _(
5397 "NOP\n"
5398 "Does nothing. Always returns successfully."
5401 /* !END-HELP-TEXT! */
5402 new_command ("CANCEL", 1, 1, 0, NULL, NULL);
5403 new_command ("END", 1, 1, 0, NULL, NULL);
5404 new_command ("BYE", 1, 1, 0, NULL, NULL);
5406 int i;
5407 for (i = 0; command_table[i]; i++);
5408 qsort (command_table, i - 1, sizeof (struct command_table_s *),
5409 sort_commands);
5412 gpg_error_t
5413 register_commands (assuan_context_t ctx)
5415 int i = 0, rc;
5417 for (; command_table[i]; i++)
5419 if (!command_table[i]->handler)
5420 continue;
5422 rc = assuan_register_command (ctx, command_table[i]->name,
5423 command_table[i]->handler,
5424 command_table[i]->help);
5425 if (rc)
5426 return rc;
5429 rc = assuan_register_bye_notify (ctx, bye_notify);
5430 if (rc)
5431 return rc;
5433 rc = assuan_register_reset_notify (ctx, reset_notify);
5434 if (rc)
5435 return rc;
5437 rc = assuan_register_pre_cmd_notify (ctx, command_startup);
5438 if (rc)
5439 return rc;
5441 return assuan_register_post_cmd_notify (ctx, command_finalize);