Kill the scdaemon after PASSWD.
[pwmd.git] / src / commands.c
blob6ce4f6a115b92ed41434c651f4ae3af06d0eea80
1 /*
2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015
3 Ben Kibbey <bjk@luxsci.net>
5 This file is part of pwmd.
7 Pwmd is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 2 of the License, or
10 (at your option) any later version.
12 Pwmd is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
20 #ifdef HAVE_CONFIG_H
21 #include <config.h>
22 #endif
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <unistd.h>
27 #include <err.h>
28 #include <errno.h>
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <fcntl.h>
32 #include <ctype.h>
33 #include <dirent.h>
34 #include <pthread.h>
35 #include <stdint.h>
37 #include "pwmd-error.h"
38 #include <gcrypt.h>
40 #include "mem.h"
41 #include "xml.h"
42 #include "util-misc.h"
43 #include "common.h"
44 #include "rcfile.h"
45 #include "cache.h"
46 #include "commands.h"
47 #include "mutex.h"
48 #include "crypto.h"
49 #include "pinentry.h"
51 /* These are command option flags. */
52 #define OPT_INQUIRE 0x0001
53 #define OPT_NO_PASSPHRASE 0x0002
54 #define OPT_RESET 0x0004
55 #define OPT_LIST_RECURSE 0x0008
56 #define OPT_VERBOSE 0x0010
57 #define OPT_LOCK 0x0020
58 #define OPT_LOCK_ON_OPEN 0x0040
59 #define OPT_SIGN 0x0080
60 #define OPT_LIST_ALL 0x0100
61 #define OPT_LIST_WITH_TARGET 0x0200
62 #define OPT_DATA 0x0400
63 #define OPT_NO_AGENT 0x0800
64 #define OPT_ASK 0x1000
66 #ifdef WITH_AGENT
67 /* The GETCONFIG command, for example, may fail because pwmd lost the
68 * gpg-agent connection. Update the recovered agent ctx. */
69 #define UPDATE_AGENT_CTX(client, crypto) do { \
70 if (crypto && crypto->agent && crypto->agent->did_restart \
71 && client->crypto && client->crypto->agent \
72 && client->crypto->agent->ctx && \
73 crypto->agent->ctx != client->crypto->agent->ctx) \
74 { \
75 client->crypto->agent->ctx = crypto->agent->ctx; \
76 crypto->agent->ctx = NULL; \
77 } \
78 } while (0)
79 #else
80 #define UPDATE_AGENT_CTX(client, crypto)
81 #endif
83 struct command_table_s
85 const char *name;
86 gpg_error_t (*handler) (assuan_context_t, char *line);
87 const char *help;
88 int ignore_startup;
89 int unlock; // unlock the file mutex after validating the checksum
92 static struct command_table_s **command_table;
94 static gpg_error_t do_lock (struct client_s *client, int add);
95 static gpg_error_t validate_checksum (struct client_s *,
96 struct cache_data_s *);
97 static gpg_error_t update_checksum (struct client_s *client);
99 /* When 'status' is true the 'self' field of the status line will be false
100 * because we never send the STATE status message to the same client that
101 * initiated it. */
102 static char *
103 build_client_info_line (struct client_thread_s *thd, int status)
105 MUTEX_LOCK (&cn_mutex);
106 int with_state = config_get_boolean ("global", "send_state");
107 char *uid, *username = NULL;
108 char *line;
110 #ifdef WITH_GNUTLS
111 if (thd->remote)
112 uid = str_asprintf("#%s", thd->tls->fp);
113 else
115 uid = str_asprintf("%u", thd->peer->uid);
116 username = get_username (thd->peer->uid);
118 #else
119 uid = str_asprintf("%u", thd->peer->uid);
120 username = get_username (thd->peer->uid);
121 #endif
122 line = str_asprintf ("%p %s %s %s %u %u %u %s %s",
123 thd->tid,
124 thd->name ? thd->name : "-",
125 thd->cl && thd->cl->filename
126 ? thd->cl->filename : "/",
127 #ifdef WITH_GNUTLS
128 thd->remote ? thd->peeraddr : "-",
129 #else
130 "-",
131 #endif
132 thd->cl && thd->cl->flags & FLAG_HAS_LOCK ? 1 : 0,
133 !status && pthread_equal (pthread_self (), thd->tid) ? 1 : 0,
134 with_state ? thd->state : CLIENT_STATE_UNKNOWN, uid,
135 #ifdef WITH_GNUTLS
136 thd->remote ? "" : username
137 #else
138 username
139 #endif
142 xfree (username);
143 xfree (uid);
144 MUTEX_UNLOCK (&cn_mutex);
145 return line;
148 void
149 update_client_state (struct client_s *client, unsigned s)
151 client->thd->state = s;
152 int n = config_get_boolean ("global", "send_state");
154 if (n && client->thd->state != CLIENT_STATE_UNKNOWN)
156 char *line = build_client_info_line (client->thd, 1);
158 if (line)
159 send_status_all_not_self (n == 2, STATUS_STATE, "%s", line);
163 static gpg_error_t
164 unlock_file_mutex (struct client_s *client, int remove)
166 gpg_error_t rc = 0;
168 // OPEN: keep the lock for the same file being reopened.
169 if (client->flags & FLAG_KEEP_LOCK && client->flags & FLAG_HAS_LOCK)
170 return 0;
172 if (!(client->flags & FLAG_HAS_LOCK))
173 return GPG_ERR_NOT_LOCKED;
175 rc = cache_unlock_mutex (client->md5file, remove);
176 if (rc)
177 rc = GPG_ERR_INV_STATE;
178 else
179 client->flags &= ~(FLAG_HAS_LOCK | FLAG_LOCK_CMD);
181 return rc;
184 static gpg_error_t
185 lock_file_mutex (struct client_s *client, int add)
187 gpg_error_t rc = 0;
188 int timeout = config_get_integer (client->filename, "cache_timeout");
190 if (client->flags & FLAG_HAS_LOCK)
191 return 0;
193 rc = cache_lock_mutex (client->ctx, client->md5file,
194 client->lock_timeout, add, timeout);
195 if (!rc)
196 client->flags |= FLAG_HAS_LOCK;
198 return rc;
201 static gpg_error_t
202 file_modified (struct client_s *client, struct command_table_s *cmd)
204 gpg_error_t rc = 0;
206 if (!(client->flags & FLAG_OPEN))
207 return GPG_ERR_INV_STATE;
209 rc = lock_file_mutex (client, 0);
210 if (!rc || rc == GPG_ERR_NO_DATA)
212 rc = validate_checksum (client, NULL);
213 if (gpg_err_code (rc) == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
214 rc = 0;
215 else if (rc)
216 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
219 if ((cmd->unlock && !(client->flags & FLAG_HAS_LOCK)) || rc)
220 unlock_file_mutex (client, 0);
222 return rc;
225 static gpg_error_t
226 parse_xml (assuan_context_t ctx, int new)
228 struct client_s *client = assuan_get_pointer (ctx);
229 int cached = client->doc != NULL;
230 gpg_error_t rc = 0;
232 if (new)
234 client->doc = new_document ();
235 if (client->doc)
237 xmlChar *result;
238 int len;
240 xmlDocDumpFormatMemory (client->doc, &result, &len, 0);
241 client->crypto->plaintext = result;
242 client->crypto->plaintext_len = len;
243 if (!client->crypto->plaintext)
245 xmlFreeDoc (client->doc);
246 client->doc = NULL;
247 rc = GPG_ERR_ENOMEM;
250 else
251 rc = GPG_ERR_ENOMEM;
253 else if (!cached)
254 rc = parse_doc ((char *) client->crypto->plaintext,
255 client->crypto->plaintext_len, (xmlDocPtr *)&client->doc);
257 return rc;
260 static void
261 free_client (struct client_s *client)
263 if (client->doc)
264 xmlFreeDoc (client->doc);
266 xfree (client->crc);
267 xfree (client->filename);
268 xfree (client->last_error);
270 if (client->crypto)
272 cleanup_crypto_stage2 (client->crypto);
273 if (client->crypto->pkey_sexp)
274 gcry_sexp_release (client->crypto->pkey_sexp);
276 if (client->crypto->sigpkey_sexp)
277 gcry_sexp_release (client->crypto->sigpkey_sexp);
279 client->crypto->pkey_sexp = NULL;
280 client->crypto->sigpkey_sexp = NULL;
281 memset (client->crypto->sign_grip, 0,
282 sizeof (client->crypto->sign_grip));
283 memset (client->crypto->grip, 0, sizeof(client->crypto->grip));
287 void
288 cleanup_client (struct client_s *client)
290 assuan_context_t ctx = client->ctx;
291 struct client_thread_s *thd = client->thd;
292 struct crypto_s *crypto = client->crypto;
293 long lock_timeout = client->lock_timeout;
294 int no_pinentry = (client->flags & FLAG_NO_PINENTRY);
295 struct pinentry_option_s pin_opts;
296 xmlErrorPtr xml_error = client->xml_error;
297 #ifdef WITH_AGENT
298 struct pinentry_option_s agent_pin_opts;
300 if (crypto && crypto->agent)
301 memcpy (&agent_pin_opts, &crypto->agent->pinentry_opts,
302 sizeof(struct pinentry_option_s));
303 #endif
305 memcpy (&pin_opts, &client->pinentry_opts, sizeof(struct pinentry_option_s));
306 unlock_file_mutex (client, client->flags & FLAG_NEW);
307 free_client (client);
308 memset (client, 0, sizeof (struct client_s));
309 client->xml_error = xml_error;
310 client->crypto = crypto;
311 client->ctx = ctx;
312 client->thd = thd;
313 client->lock_timeout = lock_timeout;
314 memcpy (&client->pinentry_opts, &pin_opts, sizeof(struct pinentry_option_s));
315 client->flags |= no_pinentry ? FLAG_NO_PINENTRY : 0;
316 #ifdef WITH_AGENT
317 if (crypto && crypto->agent)
318 memcpy (&crypto->agent->pinentry_opts, &agent_pin_opts,
319 sizeof(struct pinentry_option_s));
320 #endif
323 static gpg_error_t
324 open_finalize (assuan_context_t ctx, char *key, size_t keylen)
326 struct client_s *client = assuan_get_pointer (ctx);
327 gpg_error_t rc = 0;
328 struct cache_data_s *cdata = cache_get_data (client->md5file);
329 int cached = 0, keyarg = key ? 1 : 0;
330 size_t keysize;
331 unsigned char *salted_key = NULL;
332 int algo;
333 int pin_try = 1;
334 int pin_tries = 3;
335 char *pin_title = client->pinentry_opts.title;
337 client->crypto->filename = str_dup (client->filename);
338 if (cdata || client->flags & FLAG_NEW)
340 if (cdata && !(client->flags & FLAG_NEW))
342 rc = decrypt_cache (client->crypto, cdata->doc, cdata->doclen);
343 if (rc)
344 return rc;
347 cached = cdata != NULL;
348 goto done;
351 if (!key && !IS_PKI (client->crypto)
352 && !(client->crypto->hdr.flags & PWMD_FLAG_NO_PASSPHRASE))
354 if (client->flags & FLAG_NO_PINENTRY)
356 rc = inquire_passphrase (ctx, "PASSPHRASE", (unsigned char **)&key,
357 &keylen);
358 if (rc)
359 return rc;
361 else
363 client->pinentry_opts.timeout = config_get_integer (client->filename,
364 "pinentry_timeout");
365 pin_again:
366 rc = getpin_common (client->ctx, client->filename, PINENTRY_OPEN,
367 &key, &keylen);
368 if (rc)
369 return rc;
373 if (!IS_PKI (client->crypto))
375 if (client->crypto->hdr.flags & PWMD_FLAG_NO_PASSPHRASE)
377 keylen = 1;
378 key = gcry_malloc (keylen);
379 memset (key, 0, keylen);
382 algo = cipher_to_gcrypt (client->crypto->hdr.flags);
383 rc = hash_key (algo, client->crypto->hdr.salt,
384 sizeof(client->crypto->hdr.salt), key, keylen,
385 (void **)&salted_key, &keysize,
386 client->crypto->hdr.version <= 0x03000e ? COMPAT_KDFS2K_ITERATIONS : client->crypto->hdr.s2k_count);
387 if (!keyarg)
388 gcry_free (key);
390 if (!rc)
392 rc = decrypt_data (client->ctx, client->crypto, salted_key, keysize);
393 if (gpg_err_code (rc) == GPG_ERR_BAD_PASSPHRASE
394 && ++pin_try <= pin_tries && !(client->flags & FLAG_NO_PINENTRY))
396 gcry_free (salted_key);
397 salted_key = NULL;
398 key = NULL;
399 keylen = 0;
400 client->pinentry_opts.title = str_asprintf (_ ("Bad passphrase (try %i of %i)"), pin_try, pin_tries);
401 goto pin_again;
405 if (client->pinentry_opts.title != pin_title)
406 xfree (client->pinentry_opts.title);
408 client->pinentry_opts.title = pin_title;
409 if (rc)
411 gcry_free (salted_key);
412 return rc;
415 cdata = xcalloc (1, sizeof (struct cache_data_s));
416 if (!cdata)
418 gcry_free (salted_key);
419 return GPG_ERR_ENOMEM;
422 cdata->key = salted_key;
423 cdata->keylen = keysize;
425 else
426 #ifdef WITH_AGENT
427 rc = decrypt_data (client->ctx, client->crypto, NULL, 0);
428 #else
429 rc = GPG_ERR_NOT_IMPLEMENTED;
430 #endif
432 done:
433 if (!rc)
435 rc = parse_xml (ctx, client->flags & FLAG_NEW);
436 if (rc && !cached)
437 free_cache_data_once (cdata);
439 if (!rc)
441 int timeout = config_get_integer (client->filename,
442 "cache_timeout");
444 if (!cached)
446 if (!cdata)
447 cdata = xcalloc (1, sizeof (struct cache_data_s));
449 rc = encrypt_xml (NULL, cache_key, cache_keysize,
450 GCRY_CIPHER_AES, client->crypto->plaintext,
451 client->crypto->plaintext_len, &cdata->doc,
452 &cdata->doclen, &cache_iv, &cache_blocksize);
453 if (!rc && !(client->flags & FLAG_NEW) && IS_PKI (client->crypto))
455 rc = gcry_sexp_build ((gcry_sexp_t *) & cdata->pubkey, NULL,
456 "%S", client->crypto->pkey_sexp);
460 if (cdata->sigkey)
461 gcry_sexp_release (cdata->sigkey);
463 cdata->sigkey = NULL;
464 if (!rc && IS_PKI (client->crypto))
465 rc = gcry_sexp_build ((gcry_sexp_t *) &cdata->sigkey, NULL,
466 "%S", client->crypto->sigpkey_sexp);
468 if (!rc)
470 rc = cache_add_file (client->md5file,
471 (client->flags & FLAG_NEW) ? NULL
472 : client->crypto->grip, cdata, timeout);
473 if (rc)
475 if (!cached)
477 free_cache_data_once (cdata);
478 xmlFreeDoc (client->doc);
479 client->doc = NULL;
484 if (!rc)
485 client->flags |= FLAG_OPEN;
489 if (!rc)
490 update_checksum (client);
492 if (!rc && (client->opts & OPT_LOCK_ON_OPEN))
493 rc = do_lock (client, 0);
495 return rc;
498 static void
499 req_cleanup (void *arg)
501 if (!arg)
502 return;
504 strv_free ((char **) arg);
507 static gpg_error_t
508 parse_open_opt_lock (void *data, void *value)
510 struct client_s *client = data;
512 client->opts |= OPT_LOCK_ON_OPEN;
513 return 0;
516 static gpg_error_t
517 parse_save_opt_inquire (void *data, void *value)
519 struct client_s *client = data;
520 gpg_error_t rc;
522 if (!(client->flags & FLAG_NEW))
524 rc = peer_is_invoker (client);
525 if (rc == GPG_ERR_EACCES)
526 return rc;
529 (void) value;
530 client->opts |= OPT_INQUIRE;
531 return 0;
534 static gpg_error_t
535 parse_opt_inquire (void *data, void *value)
537 struct client_s *client = data;
539 (void) value;
540 client->opts |= OPT_INQUIRE;
541 return 0;
544 static gpg_error_t
545 update_checksum (struct client_s *client)
547 unsigned char *crc;
548 size_t len;
549 struct cache_data_s *cdata;
550 gpg_error_t rc = get_checksum (client->filename, &crc, &len);
552 if (rc)
553 return rc;
555 xfree (client->crc);
556 client->crc = crc;
557 cdata = cache_get_data (client->md5file);
558 if (cdata)
560 xfree (cdata->crc);
561 cdata->crc = xmalloc (len);
562 memcpy (cdata->crc, crc, len);
565 return 0;
568 static gpg_error_t
569 validate_checksum (struct client_s *client, struct cache_data_s *cdata)
571 unsigned char *crc;
572 size_t len;
573 gpg_error_t rc;
574 int n = 0;
576 if (cdata && !cdata->crc)
577 return GPG_ERR_CHECKSUM;
579 rc = get_checksum (client->filename, &crc, &len);
580 if (rc)
581 return rc;
583 if (cdata)
584 n = memcmp (cdata->crc, crc, len);
585 else if (client->crc)
586 n = memcmp (client->crc, crc, len);
588 xfree (crc);
589 return n ? GPG_ERR_CHECKSUM : 0;
592 static gpg_error_t
593 do_open (assuan_context_t ctx, const char *password)
595 struct client_s *client = assuan_get_pointer (ctx);
596 struct cache_data_s *cdata;
597 gpg_error_t rc = 0;
598 int done = 0;
600 // Cached document?
601 cdata = cache_get_data (client->md5file);
602 if (cdata && cdata->doc)
604 int defer = 0;
606 /* This will check that the key is cached in the agent which needs to
607 * be determined for files that share a keygrip. */
608 if (!rc)
610 rc = cache_iscached (client->filename, &defer);
611 if ((!rc || rc == GPG_ERR_ENOENT) && defer)
612 rc = GPG_ERR_KEY_EXPIRED;
615 if (!rc && !(client->flags & FLAG_NEW))
616 rc = validate_checksum (client, cdata);
618 #ifdef WITH_GNUTLS
619 if (!rc && client->thd->remote
620 && config_get_boolean (client->filename, "tcp_require_key"))
621 rc = GPG_ERR_KEY_EXPIRED;
622 #endif
624 if (!rc && !password)
626 rc = read_data_header (client->filename, &client->crypto->hdr,
627 NULL, NULL);
628 if (!rc)
630 if (IS_PKI (client->crypto))
632 gcry_sexp_build (&client->crypto->pkey_sexp, NULL, "%S",
633 cdata->pubkey);
634 gcry_pk_get_keygrip (client->crypto->pkey_sexp,
635 client->crypto->grip);
636 gcry_sexp_build (&client->crypto->sigpkey_sexp, NULL, "%S",
637 cdata->sigkey);
638 gcry_pk_get_keygrip (client->crypto->sigpkey_sexp,
639 client->crypto->sign_grip);
642 if (!rc)
644 rc = open_finalize (ctx, NULL, 0);
645 done = 1;
650 /* There was an error accessing the file so clear the cache entry. The
651 * real error will be returned from read_data_file() since the file
652 * may have only disappeared. */
653 if (!done)
655 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
656 rc = cache_clear (client->md5file);
657 send_status_all (STATUS_CACHE, NULL);
661 if (done || rc)
662 return rc;
664 rc = read_data_file (client->filename, client->crypto);
665 if (rc)
667 if (gpg_err_source (rc) != GPG_ERR_SOURCE_DEFAULT ||
668 gpg_err_code (rc) != GPG_ERR_ENOENT)
670 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
671 return rc;
674 client->flags |= FLAG_NEW;
675 memset (client->crypto->grip, 0, sizeof (client->crypto->grip));
676 memset (client->crypto->sign_grip, 0,
677 sizeof (client->crypto->sign_grip));
678 rc = open_finalize (ctx, NULL, 0);
679 return rc;
682 if (password && IS_PKI (client->crypto))
684 #ifdef WITH_AGENT
685 rc = set_agent_passphrase (client->crypto, password, strlen (password));
686 if (rc)
687 return rc;
688 #endif
691 rc = open_finalize (ctx, (char *)password, password ? strlen (password) : 0);
692 return rc;
695 static gpg_error_t
696 open_command (assuan_context_t ctx, char *line)
698 gpg_error_t rc;
699 struct client_s *client = assuan_get_pointer (ctx);
700 char **req, *filename;
701 unsigned char md5file[16];
702 int same_file = 0;
703 assuan_peercred_t peer;
704 struct argv_s *args[] = {
705 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_open_opt_lock},
706 NULL
709 rc = parse_options (&line, args, client);
710 if (rc)
711 return send_error (ctx, rc);
713 req = str_split (line, " ", 2);
714 if (!req)
715 return send_error (ctx, GPG_ERR_SYNTAX);
717 rc = do_validate_peer (ctx, req[0], &peer);
718 if (rc)
720 strv_free (req);
721 return send_error (ctx, rc);
724 filename = req[0];
725 if (!valid_filename (filename))
727 strv_free (req);
728 return send_error (ctx, GPG_ERR_INV_VALUE);
731 pthread_cleanup_push (req_cleanup, req);
732 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
733 /* This client may have locked a different file with ISCACHED --lock than
734 * the current filename. This will remove that lock. */
735 same_file = !memcmp (md5file, client->md5file, 16) ? 1 : 0;
736 if (client->flags & FLAG_OPEN ||
737 (client->flags & FLAG_HAS_LOCK && !same_file))
739 uint32_t opts = client->opts;
740 uint32_t flags = client->flags;
742 if (same_file)
743 client->flags |= FLAG_KEEP_LOCK;
744 else if (client->flags & FLAG_NEW)
745 cache_clear (client->md5file);
747 cleanup_client (client);
748 client->opts = opts;
749 client->flags |= flags;
750 client->flags &= ~(FLAG_LOCK_CMD);
751 if (!same_file)
752 client->flags &= ~(FLAG_HAS_LOCK | FLAG_NEW);
755 memcpy (client->md5file, md5file, 16);
756 client->filename = str_dup (filename);
757 if (!client->filename)
759 strv_free (req);
760 return send_error(ctx, GPG_ERR_ENOMEM);
763 /* Need to lock the mutex here because file_modified() cannot without
764 * knowing the filename. */
765 rc = lock_file_mutex (client, 1);
766 if (rc)
767 client->flags &= ~FLAG_OPEN;
769 if (!rc)
771 char *password = req[1] && *req[1] ? req[1] : NULL;
773 #ifdef WITH_AGENT
774 if (IS_PKI (client->crypto))
775 rc = set_pinentry_mode (client->crypto->agent,
776 (client->flags & FLAG_NO_PINENTRY) ? "loopback"
777 : "ask");
778 #endif
779 if (!rc)
781 rc = do_open (ctx, password);
782 if (rc)
783 cleanup_client (client);
785 cleanup_crypto_stage1 (client->crypto);
789 pthread_cleanup_pop (1);
791 if (!rc && client->flags & FLAG_NEW)
792 rc = send_status (ctx, STATUS_NEWFILE, NULL);
794 #ifdef WITH_AGENT
795 (void) kill_scd (client->crypto->agent);
796 #endif
798 return send_error (ctx, rc);
801 static gpg_error_t
802 parse_opt_no_passphrase (void *data, void *value)
804 struct client_s *client = data;
806 (void) value;
807 client->opts |= OPT_NO_PASSPHRASE;
808 return 0;
811 static gpg_error_t
812 parse_save_opt_no_agent (void *data, void *value)
814 struct client_s *client = data;
816 client->opts |= OPT_NO_AGENT;
817 return 0;
820 static gpg_error_t
821 parse_save_opt_cipher (void *data, void *value)
823 struct client_s *client = data;
824 int algo = cipher_string_to_gcrypt ((char *) value);
825 file_header_t *hdr = &client->crypto->save.hdr;
826 gpg_error_t rc = 0;
828 if (algo == -1)
829 return GPG_ERR_INV_VALUE;
831 if (!(client->flags & FLAG_NEW))
833 rc = peer_is_invoker (client);
834 if (rc == GPG_ERR_EACCES)
836 uint64_t flags = 0;
838 flags &= ((uint16_t) ((uint32_t) (flags & 0xFFFFFFFF)));
839 if (!(client->crypto->hdr.flags & gcrypt_to_cipher (algo)))
840 return rc;
842 rc = 0;
844 else if (rc)
845 return rc;
848 if (!rc)
849 hdr->flags = set_cipher_flag (hdr->flags, algo);
851 return rc;
854 #ifdef WITH_AGENT
855 static gpg_error_t
856 permitted_to_save (struct client_s *client, const unsigned char *grip,
857 size_t size, const char *value)
859 char *hexgrip;
860 gpg_error_t rc = 0;
862 if (!(client->flags & FLAG_NEW))
864 hexgrip = bin2hex (grip, size);
865 rc = !strcmp (hexgrip, (char *)value) ? 0 : GPG_ERR_EACCES;
866 xfree (hexgrip);
867 if (rc)
868 rc = peer_is_invoker (client);
871 return rc;
873 #endif
875 static gpg_error_t
876 parse_save_opt_keygrip (void *data, void *value)
878 #ifdef WITH_AGENT
879 struct client_s *client = data;
880 gpg_error_t rc = permitted_to_save (client, client->crypto->grip,
881 sizeof (client->crypto->grip),
882 value);
884 if (!IS_PKI (client->crypto))
885 return GPG_ERR_INV_ARG;
887 if (rc)
888 return rc;
890 if (client->crypto->save.pkey)
891 gcry_sexp_release (client->crypto->save.pkey);
893 client->crypto->save.pkey = NULL;
894 return get_pubkey (client->crypto, value, &client->crypto->save.pkey);
895 #else
896 return GPG_ERR_INV_ARG;
897 #endif
900 static gpg_error_t
901 parse_save_opt_sign_keygrip (void *data, void *value)
903 #ifdef WITH_AGENT
904 struct client_s *client = data;
905 gpg_error_t rc = permitted_to_save (client, client->crypto->sign_grip,
906 sizeof (client->crypto->sign_grip),
907 value);
909 if (!IS_PKI (client->crypto))
910 return GPG_ERR_INV_ARG;
912 if (rc)
913 return rc;
915 if (client->crypto->save.sigpkey)
916 gcry_sexp_release (client->crypto->save.sigpkey);
918 client->crypto->save.sigpkey = NULL;
919 return get_pubkey (client->crypto, value, &client->crypto->save.sigpkey);
920 #else
921 return GPG_ERR_INV_ARG;
922 #endif
925 static gpg_error_t
926 parse_opt_s2k_count (void *data, void *value)
928 struct client_s *client = data;
929 char *v = value, *p;
930 uint64_t n;
932 if (!v || !*v)
933 return GPG_ERR_INV_VALUE;
935 errno = 0;
936 n = strtoull (v, &p, 10);
937 if (n == UINT64_MAX && errno)
938 return gpg_error_from_errno (errno);
939 else if (p && *p)
940 return GPG_ERR_INV_VALUE;
942 if (!(client->flags & FLAG_NEW))
944 gpg_error_t rc = peer_is_invoker (client);
946 if (rc == GPG_ERR_EACCES)
948 if (n && client->crypto->hdr.s2k_count != n)
949 return rc;
951 rc = 0;
953 else if (rc)
954 return rc;
957 // Keep compatibility with libpwmd passing --s2k-count=0. If somehow
958 // s2k_count == 0 it will be set to DEFAULT_KDFS2K_ITERATIONS in
959 // save_command().
960 if (n)
961 client->crypto->save.hdr.s2k_count = n;
963 return 0;
966 static gpg_error_t
967 save_finalize (assuan_context_t ctx)
969 struct client_s *client = assuan_get_pointer (ctx);
970 gpg_error_t rc = 0;
971 xmlChar *xmlbuf = NULL;
972 int xmlbuflen;
973 void *key = NULL;
974 size_t keylen = 0;
976 xmlDocDumpFormatMemory (client->doc, &xmlbuf, &xmlbuflen, 0);
977 if (!xmlbuf)
978 return GPG_ERR_ENOMEM;
980 pthread_cleanup_push (xmlFree, xmlbuf);
982 if (!use_agent || ((client->flags & FLAG_NEW)
983 && (client->opts & OPT_NO_AGENT))
984 || !(client->crypto->hdr.flags & PWMD_FLAG_PKI))
986 rc = export_common (ctx, client->flags & FLAG_NO_PINENTRY,
987 client->crypto, xmlbuf, xmlbuflen, client->filename,
988 NULL, &key, &keylen, 1, 1,
989 (client->opts & OPT_NO_PASSPHRASE));
991 #ifdef WITH_AGENT
992 else
994 gcry_sexp_t pubkey = client->crypto->save.pkey;
995 gcry_sexp_t sigkey = client->crypto->save.sigpkey;
997 if (!pubkey)
998 pubkey = client->crypto->pkey_sexp;
1000 if (!sigkey)
1002 sigkey = client->crypto->sigpkey_sexp;
1003 if (!sigkey)
1005 gcry_sexp_build (&client->crypto->save.sigpkey, 0, "%S", pubkey);
1006 sigkey = client->crypto->save.sigpkey;
1010 rc = encrypt_data_file (client->ctx, client->crypto, pubkey, sigkey,
1011 client->filename, xmlbuf, xmlbuflen);
1012 if (pubkey == client->crypto->save.pkey)
1014 if (!rc)
1016 gcry_sexp_release (client->crypto->pkey_sexp);
1017 client->crypto->pkey_sexp = client->crypto->save.pkey;
1018 gcry_pk_get_keygrip (client->crypto->pkey_sexp,
1019 client->crypto->grip);
1021 else
1022 gcry_sexp_release (pubkey);
1024 client->crypto->save.pkey = NULL;
1027 if (!rc)
1028 gcry_pk_get_keygrip (sigkey, client->crypto->sign_grip);
1030 if (sigkey == client->crypto->save.sigpkey)
1032 if (!rc)
1034 if (client->crypto->sigpkey_sexp)
1035 gcry_sexp_release (client->crypto->sigpkey_sexp);
1037 client->crypto->sigpkey_sexp = client->crypto->save.sigpkey;
1038 gcry_pk_get_keygrip (client->crypto->sigpkey_sexp,
1039 client->crypto->sign_grip);
1041 else
1042 gcry_sexp_release (sigkey);
1044 client->crypto->save.sigpkey = NULL;
1047 #endif
1049 if (!rc)
1051 int cached;
1053 rc = save_common (client->filename, client->crypto, xmlbuf, xmlbuflen,
1054 key, keylen, &cached, client->opts & OPT_NO_AGENT);
1055 gcry_free (key);
1057 if (!rc && (!cached || (client->flags & FLAG_NEW)))
1058 send_status_all (STATUS_CACHE, NULL);
1060 if (!rc)
1062 rc = update_checksum (client);
1063 client->flags &= ~(FLAG_NEW);
1067 pthread_cleanup_pop (1); // xmlFree
1068 return rc;
1071 static gpg_error_t
1072 parse_opt_reset (void *data, void *value)
1074 struct client_s *client = data;
1076 (void) value;
1077 client->opts |= OPT_RESET;
1078 return 0;
1081 static gpg_error_t
1082 parse_opt_ask (void *data, void *value)
1084 struct client_s *client = data;
1086 (void) value;
1087 client->opts |= OPT_ASK;
1088 return 0;
1091 static gpg_error_t
1092 save_command (assuan_context_t ctx, char *line)
1094 struct client_s *client = assuan_get_pointer (ctx);
1095 gpg_error_t rc;
1096 struct stat st;
1097 struct argv_s *args[] = {
1098 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG,
1099 parse_opt_no_passphrase},
1100 &(struct argv_s) {"cipher", OPTION_TYPE_ARG, parse_save_opt_cipher},
1101 &(struct argv_s) {"inquire-keyparam", OPTION_TYPE_NOARG,
1102 parse_save_opt_inquire},
1103 &(struct argv_s) {"keygrip", OPTION_TYPE_ARG, parse_save_opt_keygrip},
1104 &(struct argv_s) {"sign-keygrip", OPTION_TYPE_ARG,
1105 parse_save_opt_sign_keygrip},
1106 &(struct argv_s) {"s2k-count", OPTION_TYPE_ARG, parse_opt_s2k_count},
1107 &(struct argv_s) {"reset", OPTION_TYPE_NOARG, parse_opt_reset},
1108 &(struct argv_s) {"cipher-iterations", OPTION_TYPE_ARG,
1109 parse_opt_s2k_count},
1110 &(struct argv_s) {"no-agent", OPTION_TYPE_NOARG,
1111 parse_save_opt_no_agent},
1112 &(struct argv_s) {"ask", OPTION_TYPE_NOARG,
1113 parse_opt_ask},
1114 NULL
1117 cleanup_save (&client->crypto->save);
1118 memcpy (&client->crypto->save.hdr, &client->crypto->hdr,
1119 sizeof (file_header_t));
1120 client->crypto->save.s2k_count =
1121 config_get_ulong (client->filename, "s2k_count");
1123 if (client->flags & FLAG_NEW && !client->crypto->save.s2k_count)
1124 client->crypto->save.hdr.s2k_count =
1125 config_get_ulonglong (client->filename, "cipher_iterations");
1127 rc = parse_options (&line, args, client);
1128 if (rc)
1129 return send_error (ctx, rc);
1131 if (!(client->flags & FLAG_NEW))
1132 client->opts &= ~OPT_NO_AGENT;
1133 else if (client->opts & OPT_NO_AGENT)
1135 client->crypto->save.hdr.flags &= ~PWMD_FLAG_PKI;
1136 client->crypto->hdr.flags &= ~PWMD_FLAG_PKI;
1139 /* Update to the default hash iteration count for data file
1140 * versions <= 3.0.14. */
1141 #ifdef WITH_AGENT
1142 if ((!IS_PKI (client->crypto) && client->crypto->hdr.version <= 0x03000e
1143 && client->crypto->save.hdr.s2k_count < DEFAULT_KDFS2K_ITERATIONS)
1144 || (!IS_PKI (client->crypto) && !client->crypto->save.hdr.s2k_count))
1145 #else
1146 if ((client->crypto->hdr.version <= 0x03000e
1147 && client->crypto->save.hdr.s2k_count < DEFAULT_KDFS2K_ITERATIONS)
1148 || !client->crypto->save.hdr.s2k_count)
1149 #endif
1150 client->crypto->save.hdr.s2k_count = DEFAULT_KDFS2K_ITERATIONS;
1152 if ((client->opts & OPT_NO_PASSPHRASE) && !(client->flags & FLAG_NEW)
1153 && !(client->opts & OPT_INQUIRE))
1154 return send_error (ctx, GPG_ERR_WRONG_KEY_USAGE);
1156 if (lstat (client->filename, &st) == -1 && errno != ENOENT)
1157 return send_error (ctx, gpg_error_from_errno (errno));
1159 if (errno != ENOENT && !S_ISREG (st.st_mode))
1161 log_write ("%s: %s", client->filename, pwmd_strerror (GPG_ERR_ENOANO));
1162 return send_error (ctx, GPG_ERR_ENOANO);
1165 int defer = 0;
1166 rc = cache_iscached (client->filename, &defer);
1167 if (gpg_err_code (rc) == GPG_ERR_ENOENT && client->flags & FLAG_NEW)
1168 rc = 0;
1169 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
1170 rc = 0;
1172 if ((!rc && defer))
1173 client->opts |= OPT_RESET;
1174 else if (config_get_boolean ("global", "require_save_key"))
1175 client->opts |= OPT_ASK;
1177 if (!rc && (client->opts & OPT_RESET))
1179 rc = cache_clear (client->md5file);
1180 if (rc)
1181 return send_error (ctx, rc);
1183 log_write ("%s: %s", client->filename,
1184 pwmd_strerror (GPG_ERR_KEY_EXPIRED));
1185 send_status_all (STATUS_CACHE, NULL);
1188 if (!rc && client->opts & OPT_ASK)
1189 rc = crypto_try_decrypt (ctx, client->flags & FLAG_NO_PINENTRY,
1190 client->filename, NULL, NULL, NULL);
1192 if (!rc)
1193 rc = update_element_mtime (client, xmlDocGetRootElement (client->doc));
1195 if (rc)
1196 return send_error (ctx, rc);
1198 #ifdef WITH_AGENT
1199 if (!rc && use_agent && !client->crypto->save.pkey &&
1200 (client->flags & FLAG_NEW || client->opts & OPT_INQUIRE)
1201 && !(client->opts & OPT_NO_AGENT))
1203 rc = set_pinentry_mode (client->crypto->agent,
1204 (client->flags & FLAG_NO_PINENTRY) ? "loopback"
1205 : "ask");
1207 if (!(client->flags & FLAG_NEW))
1209 struct crypto_s *crypto;
1210 void *key = NULL;
1211 size_t keylen = 0;
1213 /* Wanting to generate a new key. Require the key to open the
1214 current file before proceeding reguardless of the
1215 require_save_key configuration parameter. */
1216 rc = cache_clear (client->md5file);
1217 if (!rc)
1219 rc = init_client_crypto (&crypto);
1220 if (!rc)
1221 crypto->client_ctx = client->ctx;
1224 if (!rc)
1225 rc = decrypt_common (client->ctx, client->opts&OPT_INQUIRE, crypto,
1226 client->filename, &key, &keylen, NULL, NULL);
1228 xfree (key);
1229 cleanup_crypto (&crypto);
1232 if (!rc)
1233 rc = send_status (client->ctx, STATUS_GENKEY, NULL);
1235 if (!rc)
1237 struct inquire_data_s idata = { 0 };
1238 char *params = client->opts & OPT_INQUIRE
1239 ? NULL : default_key_params (client->crypto);
1241 pthread_cleanup_push (xfree, params);
1242 idata.crypto = client->crypto;
1244 if (params)
1246 idata.line = params;
1247 idata.len = strlen (params);
1249 else
1250 idata.preset = 1;
1252 client->crypto->agent->inquire_data = &idata;
1253 client->crypto->agent->inquire_cb = NULL;
1254 rc = generate_key (client->crypto, params,
1255 (client->opts & OPT_NO_PASSPHRASE), 1);
1256 pthread_cleanup_pop (1);
1259 #endif
1261 if (!rc)
1262 rc = save_finalize (ctx);
1264 cleanup_crypto_stage1 (client->crypto);
1265 #ifdef WITH_AGENT
1266 (void) kill_scd (client->crypto->agent);
1267 #endif
1268 return send_error (ctx, rc);
1271 static gpg_error_t
1272 do_delete (assuan_context_t ctx, char *line)
1274 struct client_s *client = assuan_get_pointer (ctx);
1275 gpg_error_t rc;
1276 char **req;
1277 xmlNodePtr n;
1279 if (strchr (line, '\t'))
1280 req = str_split (line, "\t", 0);
1281 else
1282 req = str_split (line, " ", 0);
1284 if (!req || !*req)
1285 return GPG_ERR_SYNTAX;
1287 n = find_root_element (client, client->doc, &req, &rc, NULL, 0, 0);
1288 if (!n || rc)
1290 strv_free (req);
1291 return rc;
1295 * No sub-node defined. Remove the entire node (root element).
1297 if (!req[1])
1299 if (n)
1301 rc = is_element_owner (client, n);
1302 if (!rc)
1304 rc = unlink_node (client, n);
1305 xmlFreeNode (n);
1309 strv_free (req);
1310 return rc;
1313 n = find_elements (client, client->doc, n->children, req + 1, &rc, NULL,
1314 NULL, NULL, 0, 0, NULL, 0);
1315 strv_free (req);
1316 if (!n || rc)
1317 return rc;
1319 rc = is_element_owner (client, n);
1320 if (!rc)
1322 rc = unlink_node (client, n);
1323 xmlFreeNode (n);
1326 return rc;
1329 static gpg_error_t
1330 delete_command (assuan_context_t ctx, char *line)
1332 struct client_s *client = assuan_get_pointer (ctx);
1333 gpg_error_t rc;
1334 struct argv_s *args[] = {
1335 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1336 NULL
1339 rc = parse_options (&line, args, client);
1340 if (rc)
1341 return send_error (ctx, rc);
1343 if (client->opts & OPT_INQUIRE)
1345 unsigned char *result;
1346 size_t len;
1348 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1349 if (rc)
1350 return send_error (ctx, rc);
1352 pthread_cleanup_push (xfree, result);
1353 rc = do_delete (ctx, (char *)result);
1354 pthread_cleanup_pop (1);
1356 else
1357 rc = do_delete (ctx, line);
1359 return send_error (ctx, rc);
1362 static gpg_error_t
1363 store_command (assuan_context_t ctx, char *line)
1365 struct client_s *client = assuan_get_pointer (ctx);
1366 gpg_error_t rc;
1367 size_t len;
1368 unsigned char *result;
1369 char **req;
1370 xmlNodePtr n, parent;
1371 int has_content;
1372 char *content = NULL;
1374 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1375 if (rc)
1376 return send_error (ctx, rc);
1378 req = str_split ((char *) result, "\t", 0);
1379 xfree (result);
1381 if (!req || !*req)
1382 return send_error (ctx, GPG_ERR_SYNTAX);
1384 len = strv_length (req);
1385 has_content = line[strlen (line) - 1] != '\t' && len > 1;
1386 if (*(req + 1) && !valid_element_path (req, has_content))
1388 strv_free (req);
1389 return send_error (ctx, GPG_ERR_INV_VALUE);
1392 if (has_content || !*req[len - 1])
1394 has_content = 1;
1395 content = req[len - 1];
1396 req[len - 1] = NULL;
1399 again:
1400 n = find_root_element (client, client->doc, &req, &rc, NULL, 0, 0);
1401 if (rc && rc == GPG_ERR_ELEMENT_NOT_FOUND)
1403 rc = new_root_element (client, client->doc, *req);
1404 if (rc)
1406 strv_free (req);
1407 return send_error (ctx, rc);
1410 goto again;
1413 if (!n || rc)
1415 strv_free (req);
1416 return send_error (ctx, rc);
1419 parent = n;
1421 if (req[1] && *req[1])
1423 if (!n->children)
1424 parent = create_elements_cb (client, 1, n, req + 1, &rc, NULL);
1425 else
1426 parent = find_elements (client, client->doc, n->children, req + 1, &rc,
1427 NULL, NULL, create_elements_cb, 0, 0, NULL,
1431 if (!rc && len > 1)
1433 rc = is_element_owner (client, parent);
1434 if (!rc)
1436 n = find_text_node (parent->children);
1437 if (n)
1438 xmlNodeSetContent (n, (xmlChar *) content);
1439 else
1440 xmlNodeAddContent (parent, (xmlChar *) content);
1442 update_element_mtime (client, parent);
1446 xfree (content);
1447 strv_free (req);
1448 return send_error (ctx, rc);
1451 static gpg_error_t
1452 xfer_data (assuan_context_t ctx, const char *line, int total)
1454 int to_send;
1455 int sent = 0;
1456 gpg_error_t rc;
1457 int progress = config_get_integer ("global", "xfer_progress");
1458 int flush = 0;
1460 progress =
1461 progress > 0 ? (progress / ASSUAN_LINELENGTH) * ASSUAN_LINELENGTH : 0;
1462 to_send = total < ASSUAN_LINELENGTH ? total : ASSUAN_LINELENGTH;
1463 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1465 if (rc)
1466 return rc;
1468 again:
1471 if (sent + to_send > total)
1472 to_send = total - sent;
1474 rc = assuan_send_data (ctx, flush ? NULL : (char *) line + sent,
1475 flush ? 0 : to_send);
1476 if (!rc)
1478 sent += flush ? 0 : to_send;
1480 if ((progress && !(sent % progress) && sent != total) ||
1481 (sent == total && flush))
1482 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1484 if (!flush && !rc && sent == total)
1486 flush = 1;
1487 goto again;
1491 while (!rc && sent < total);
1493 return rc;
1496 static gpg_error_t
1497 do_get (assuan_context_t ctx, char *line)
1499 struct client_s *client = assuan_get_pointer (ctx);
1500 gpg_error_t rc;
1501 char **req;
1502 xmlNodePtr n;
1504 req = str_split (line, "\t", 0);
1506 if (!req || !*req)
1508 strv_free (req);
1509 return GPG_ERR_SYNTAX;
1512 n = find_root_element (client, client->doc, &req, &rc, NULL, 0, 0);
1513 if (!n || rc)
1515 strv_free (req);
1516 return rc;
1519 if (req[1])
1520 n = find_elements (client, client->doc, n->children, req + 1, &rc,
1521 NULL, NULL, NULL, 0, 0, NULL, 0);
1523 strv_free (req);
1524 if (rc)
1525 return rc;
1527 if (!n || !n->children)
1528 return GPG_ERR_NO_DATA;
1530 n = find_text_node (n->children);
1531 if (!n || !n->content || !*n->content)
1532 return GPG_ERR_NO_DATA;
1534 rc = xfer_data (ctx, (char *) n->content, xmlStrlen (n->content));
1535 return rc;
1538 static gpg_error_t
1539 get_command (assuan_context_t ctx, char *line)
1541 struct client_s *client = assuan_get_pointer (ctx);
1542 gpg_error_t rc;
1543 struct argv_s *args[] = {
1544 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1545 NULL
1548 rc = parse_options (&line, args, client);
1549 if (rc)
1550 return send_error (ctx, rc);
1552 if (client->opts & OPT_INQUIRE)
1554 unsigned char *result;
1555 size_t len;
1557 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1558 if (rc)
1559 return send_error (ctx, rc);
1561 pthread_cleanup_push (xfree, result);
1562 rc = do_get (ctx, (char *)result);
1563 pthread_cleanup_pop (1);
1565 else
1566 rc = do_get (ctx, line);
1568 return send_error (ctx, rc);
1571 static void list_command_cleanup1 (void *arg);
1572 static gpg_error_t
1573 realpath_command (assuan_context_t ctx, char *line)
1575 struct string_s *string = NULL;
1576 gpg_error_t rc;
1577 struct client_s *client = assuan_get_pointer (ctx);
1578 struct argv_s *args[] = {
1579 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1580 NULL
1583 rc = parse_options (&line, args, client);
1584 if (rc)
1585 return send_error (ctx, rc);
1587 if (client->opts & OPT_INQUIRE)
1589 unsigned char *result;
1590 size_t len;
1592 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1593 if (rc)
1594 return send_error (ctx, rc);
1596 pthread_cleanup_push (xfree, result);
1597 rc = build_realpath (client, client->doc, (char *)result, &string);
1598 pthread_cleanup_pop (1);
1600 else
1601 rc = build_realpath (client, client->doc, line, &string);
1603 if (!rc)
1605 pthread_cleanup_push (list_command_cleanup1, string);
1606 rc = xfer_data (ctx, string->str, string->len);
1607 pthread_cleanup_pop (1);
1610 return send_error (ctx, rc);
1613 static void
1614 list_command_cleanup1 (void *arg)
1616 if (arg)
1617 string_free ((struct string_s *) arg, 1);
1620 static void
1621 list_command_cleanup2 (void *arg)
1623 struct element_list_s *elements = arg;
1625 if (elements)
1627 if (elements->list)
1629 int total = slist_length (elements->list);
1630 int i;
1632 for (i = 0; i < total; i++)
1634 char *tmp = slist_nth_data (elements->list, i);
1635 xfree (tmp);
1638 slist_free (elements->list);
1641 if (elements->prefix)
1642 xfree (elements->prefix);
1644 if (elements->req)
1645 strv_free (elements->req);
1647 xfree (elements);
1651 static gpg_error_t
1652 parse_list_opt_norecurse (void *data, void *value)
1654 struct client_s *client = data;
1656 client->opts &= ~(OPT_LIST_RECURSE);
1657 return 0;
1660 static gpg_error_t
1661 parse_opt_verbose (void *data, void *value)
1663 struct client_s *client = data;
1665 client->opts |= OPT_VERBOSE;
1666 return 0;
1669 static gpg_error_t
1670 parse_list_opt_target (void *data, void *value)
1672 struct client_s *client = data;
1674 client->opts |= OPT_LIST_WITH_TARGET;
1675 return 0;
1678 static gpg_error_t
1679 parse_list_opt_all (void *data, void *value)
1681 struct client_s *client = data;
1683 client->opts |= OPT_LIST_ALL;
1684 return 0;
1687 static gpg_error_t
1688 list_path_once (struct client_s *client, char *line,
1689 struct element_list_s *elements, struct string_s *result)
1691 gpg_error_t rc;
1693 elements->req = str_split (line, " ", 0);
1694 if (!elements->req)
1695 strv_printf (&elements->req, "%s", line);
1697 rc = create_path_list (client, client->doc, elements, *elements->req);
1698 if ((rc == GPG_ERR_ELOOP || rc == GPG_ERR_EACCES) && elements->verbose)
1699 rc = 0;
1701 if (!rc)
1703 int total = slist_length (elements->list);
1705 if (total)
1707 int i;
1709 for (i = 0; i < total; i++)
1711 char *tmp = slist_nth_data (elements->list, i);
1713 string_append_printf (result, "%s%s", tmp,
1714 i + 1 == total ? "" : "\n");
1717 else
1718 rc = GPG_ERR_NO_DATA;
1721 return rc;
1724 static int
1725 has_list_flag (char *path, char *flags)
1727 char *p = path;
1729 while (*p && *++p != ' ');
1731 if (!*p)
1732 return 0;
1734 for (; *p; p++)
1736 char *f;
1738 for (f = flags; *f && *f != ' '; f++)
1740 if (*p == *f)
1741 return 1;
1745 return 0;
1748 static gpg_error_t
1749 do_list (assuan_context_t ctx, char *line)
1751 struct client_s *client = assuan_get_pointer (ctx);
1752 gpg_error_t rc;
1753 struct element_list_s *elements = NULL;
1755 elements = xcalloc (1, sizeof (struct element_list_s));
1756 if (!elements)
1757 return GPG_ERR_ENOMEM;
1759 elements->recurse = client->opts & OPT_LIST_RECURSE;
1760 elements->verbose =
1761 (client->opts & OPT_VERBOSE) | (client->opts & OPT_LIST_WITH_TARGET);
1762 elements->with_target = client->opts & OPT_LIST_WITH_TARGET;
1764 if (!line || !*line)
1766 struct string_s *str = NULL;
1768 pthread_cleanup_push (list_command_cleanup2, elements);
1769 rc = list_root_elements (client, client->doc, &str, elements->verbose,
1770 elements->with_target);
1771 pthread_cleanup_pop (1);
1772 pthread_cleanup_push (list_command_cleanup1, str);
1774 if (!rc)
1776 if (client->opts & OPT_LIST_ALL)
1778 char **roots = str_split (str->str, "\n", 0);
1779 char **p;
1781 pthread_cleanup_push (req_cleanup, roots);
1782 string_truncate (str, 0);
1784 for (p = roots; *p; p++)
1786 if (strchr (*p, ' '))
1788 if (has_list_flag (*p, "EOP"))
1790 string_append_printf (str, "%s%s", *p,
1791 *(p + 1) ? "\n" : "");
1792 continue;
1796 elements = xcalloc (1, sizeof (struct element_list_s));
1797 if (!elements)
1799 rc = GPG_ERR_ENOMEM;
1800 break;
1803 elements->recurse = client->opts & OPT_LIST_RECURSE;
1804 elements->verbose =
1805 (client->opts & OPT_VERBOSE) | (client->opts &
1806 OPT_LIST_WITH_TARGET);
1807 elements->with_target = client->opts & OPT_LIST_WITH_TARGET;
1808 pthread_cleanup_push (list_command_cleanup2, elements);
1809 rc = list_path_once (client, *p, elements, str);
1810 pthread_cleanup_pop (1);
1811 if (rc)
1812 break;
1814 if (*(p + 1))
1815 string_append (str, "\n");
1818 pthread_cleanup_pop (1);
1821 if (!rc)
1822 rc = xfer_data (ctx, str->str, str->len);
1825 pthread_cleanup_pop (1);
1826 return rc;
1829 pthread_cleanup_push (list_command_cleanup2, elements);
1830 struct string_s *str = string_new (NULL);
1831 pthread_cleanup_push (list_command_cleanup1, str);
1832 rc = list_path_once (client, line, elements, str);
1833 if (!rc)
1834 rc = xfer_data (ctx, str->str, str->len);
1836 pthread_cleanup_pop (1);
1837 pthread_cleanup_pop (1);
1838 return rc;
1841 static gpg_error_t
1842 list_command (assuan_context_t ctx, char *line)
1844 struct client_s *client = assuan_get_pointer (ctx);
1845 gpg_error_t rc;
1846 struct argv_s *args[] = {
1847 &(struct argv_s) {"no-recurse", OPTION_TYPE_NOARG,
1848 parse_list_opt_norecurse},
1849 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_opt_verbose},
1850 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1851 &(struct argv_s) {"with-target", OPTION_TYPE_NOARG,
1852 parse_list_opt_target},
1853 &(struct argv_s) {"all", OPTION_TYPE_NOARG, parse_list_opt_all},
1854 NULL
1857 if (disable_list_and_dump == 1)
1858 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
1860 client->opts |= OPT_LIST_RECURSE;
1861 rc = parse_options (&line, args, client);
1862 if (rc)
1863 return send_error (ctx, rc);
1865 if (client->opts & OPT_LIST_ALL)
1866 client->opts |= OPT_LIST_RECURSE | OPT_VERBOSE;
1868 if (client->opts & OPT_INQUIRE)
1870 unsigned char *result;
1871 size_t len;
1873 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1874 if (rc)
1875 return send_error (ctx, rc);
1877 pthread_cleanup_push (xfree, result);
1878 rc = do_list (ctx, (char *)result);
1879 pthread_cleanup_pop (1);
1881 else
1882 rc = do_list (ctx, line);
1884 return send_error (ctx, rc);
1888 * req[0] - element path
1890 static gpg_error_t
1891 attribute_list (assuan_context_t ctx, char **req)
1893 struct client_s *client = assuan_get_pointer (ctx);
1894 char **attrlist = NULL;
1895 int i = 0;
1896 char **path = NULL;
1897 xmlAttrPtr a;
1898 xmlNodePtr n, an;
1899 char *line;
1900 gpg_error_t rc;
1902 if (!req || !req[0])
1903 return GPG_ERR_SYNTAX;
1905 client->flags |= FLAG_ACL_IGNORE;
1907 if ((path = str_split (req[0], "\t", 0)) == NULL)
1910 * The first argument may be only a root element.
1912 if ((path = str_split (req[0], " ", 0)) == NULL)
1913 return GPG_ERR_SYNTAX;
1916 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 0);
1917 if (!n || rc)
1919 strv_free (path);
1920 return rc;
1923 if (client->flags & FLAG_ACL_ERROR)
1925 client->flags &= ~FLAG_ACL_IGNORE;
1926 if (path[1])
1928 strv_free (path);
1929 return GPG_ERR_EACCES;
1932 client->flags &= ~FLAG_ACL_ERROR;
1935 if (path[1])
1937 n = find_elements (client, client->doc, n->children, path + 1, &rc,
1938 NULL, NULL, NULL, 0, 0, NULL, 0);
1939 if (!n || rc)
1941 strv_free (path);
1942 return rc;
1946 strv_free (path);
1948 for (a = n->properties; a; a = a->next)
1950 char **pa;
1952 if ((pa = xrealloc (attrlist, (i + 2) * sizeof (char *))) == NULL)
1954 if (attrlist)
1955 strv_free (attrlist);
1957 log_write ("%s(%i): %s", __FILE__, __LINE__,
1958 pwmd_strerror (GPG_ERR_ENOMEM));
1959 return GPG_ERR_ENOMEM;
1962 attrlist = pa;
1963 an = a->children;
1964 attrlist[i] = str_asprintf ("%s %s", (char *) a->name,
1966 && an->content ? (char *) an->content : "");
1968 if (!attrlist[i])
1970 strv_free (attrlist);
1971 log_write ("%s(%i): %s", __FILE__, __LINE__,
1972 pwmd_strerror (GPG_ERR_ENOMEM));
1973 return GPG_ERR_ENOMEM;
1976 attrlist[++i] = NULL;
1979 if (!attrlist)
1980 return GPG_ERR_NO_DATA;
1982 line = strv_join ("\n", attrlist);
1984 if (!line)
1986 log_write ("%s(%i): %s", __FILE__, __LINE__,
1987 pwmd_strerror (GPG_ERR_ENOMEM));
1988 strv_free (attrlist);
1989 return GPG_ERR_ENOMEM;
1992 pthread_cleanup_push (xfree, line);
1993 pthread_cleanup_push (req_cleanup, attrlist);
1994 rc = xfer_data (ctx, line, strlen (line));
1995 pthread_cleanup_pop (1);
1996 pthread_cleanup_pop (1);
1997 return rc;
2001 * req[0] - attribute
2002 * req[1] - element path
2004 static gpg_error_t
2005 attribute_delete (struct client_s *client, char **req)
2007 xmlNodePtr n;
2008 char **path = NULL;
2009 gpg_error_t rc;
2011 if (!req || !req[0] || !req[1])
2012 return GPG_ERR_SYNTAX;
2014 if (!strcmp (req[0], "_name"))
2015 return GPG_ERR_INV_ATTR;
2017 if ((path = str_split (req[1], "\t", 0)) == NULL)
2020 * The first argument may be only a root element.
2022 if ((path = str_split (req[1], " ", 0)) == NULL)
2023 return GPG_ERR_SYNTAX;
2026 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 0);
2027 if (!n || rc)
2028 goto fail;
2030 if (path[1])
2032 n = find_elements (client, client->doc, n->children, path + 1, &rc,
2033 NULL, NULL, NULL, 0, 0, NULL, 0);
2034 if (!n || rc)
2035 goto fail;
2038 if (!strcmp (req[0], (char *) "_acl"))
2040 rc = is_element_owner (client, n);
2041 if (rc)
2042 goto fail;
2045 rc = delete_attribute (client, n, (xmlChar *) req[0]);
2047 fail:
2048 strv_free (path);
2049 return rc;
2052 static xmlNodePtr
2053 create_element_path (struct client_s *client,
2054 char ***elements, gpg_error_t * rc, xmlNodePtr parent)
2056 char **req = *elements;
2057 char **req_orig = strv_dup (req);
2058 xmlNodePtr n = NULL;
2060 *rc = 0;
2062 if (!req_orig)
2064 *rc = GPG_ERR_ENOMEM;
2065 log_write ("%s(%i): %s", __FILE__, __LINE__,
2066 pwmd_strerror (GPG_ERR_ENOMEM));
2067 goto fail;
2070 again:
2071 n = find_root_element (client, client->doc, &req, rc, NULL, 0, 0);
2072 if (!n)
2074 if (*rc != GPG_ERR_ELEMENT_NOT_FOUND)
2075 goto fail;
2077 *rc = new_root_element (client, client->doc, req[0]);
2078 if (*rc)
2079 goto fail;
2081 goto again;
2083 else if (n == parent)
2085 *rc = GPG_ERR_CONFLICT;
2086 goto fail;
2089 if (req[1])
2091 if (!n->children)
2092 n = create_target_elements_cb (client, 1, n, req + 1, rc, NULL);
2093 else
2094 n = find_elements (client, client->doc, n->children, req + 1, rc,
2095 NULL, NULL, create_target_elements_cb, 0, 0,
2096 parent, 0);
2098 if (!n)
2099 goto fail;
2102 * Reset the position of the element tree now that the elements
2103 * have been created.
2105 strv_free (req);
2106 req = req_orig;
2107 req_orig = NULL;
2108 n = find_root_element (client, client->doc, &req, rc, NULL, 0, 0);
2109 if (!n)
2110 goto fail;
2112 n = find_elements (client, client->doc, n->children, req + 1, rc,
2113 NULL, NULL, NULL, 0, 0, NULL, 0);
2114 if (!n)
2115 goto fail;
2118 fail:
2119 if (req_orig)
2120 strv_free (req_orig);
2122 *elements = req;
2123 return n;
2127 * Creates a "target" attribute. When other commands encounter an element with
2128 * this attribute, the element path is modified to the target value. If the
2129 * source element path doesn't exist when using 'ATTR SET target', it is
2130 * created, but the destination element path must exist.
2132 * req[0] - source element path
2133 * req[1] - destination element path
2135 static gpg_error_t
2136 target_attribute (struct client_s *client, char **req)
2138 char **src, **dst, *line = NULL, **odst = NULL;
2139 gpg_error_t rc;
2140 xmlNodePtr n;
2142 if (!req || !req[0] || !req[1])
2143 return GPG_ERR_SYNTAX;
2145 if ((src = str_split (req[0], "\t", 0)) == NULL)
2148 * The first argument may be only a root element.
2150 if ((src = str_split (req[0], " ", 0)) == NULL)
2151 return GPG_ERR_SYNTAX;
2154 if (!valid_element_path (src, 0))
2155 return GPG_ERR_INV_VALUE;
2157 if ((dst = str_split (req[1], "\t", 0)) == NULL)
2160 * The first argument may be only a root element.
2162 if ((dst = str_split (req[1], " ", 0)) == NULL)
2164 rc = GPG_ERR_SYNTAX;
2165 goto fail;
2169 odst = strv_dup (dst);
2170 if (!odst)
2172 rc = GPG_ERR_ENOMEM;
2173 goto fail;
2176 n = find_root_element (client, client->doc, &dst, &rc, NULL, 0, 0);
2178 * Make sure the destination element path exists.
2180 if (rc && rc != GPG_ERR_EACCES)
2181 goto fail;
2183 rc = 0;
2184 if (dst[1])
2186 n = find_elements (client, client->doc, n->children, dst + 1, &rc,
2187 NULL, NULL, NULL, 0, 0, NULL, 0);
2188 if (rc && rc != GPG_ERR_EACCES)
2189 goto fail;
2192 rc = validate_target_attribute (client, client->doc, req[0], n);
2193 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2194 goto fail;
2196 n = create_element_path (client, &src, &rc, NULL);
2197 if (rc)
2198 goto fail;
2200 line = strv_join ("\t", odst);
2201 if (!line)
2203 rc = GPG_ERR_ENOMEM;
2204 goto fail;
2207 rc = add_attribute (client, n, "target", line);
2209 fail:
2210 xfree (line);
2211 strv_free (src);
2212 strv_free (dst);
2213 strv_free (odst);
2214 return rc;
2218 * req[0] - attribute
2219 * req[1] - element path
2221 static gpg_error_t
2222 attribute_get (assuan_context_t ctx, char **req)
2224 struct client_s *client = assuan_get_pointer (ctx);
2225 xmlNodePtr n;
2226 xmlChar *a;
2227 char **path = NULL;
2228 gpg_error_t rc;
2230 if (!req || !req[0] || !req[1])
2231 return GPG_ERR_SYNTAX;
2233 if (strchr (req[1], '\t'))
2235 if ((path = str_split (req[1], "\t", 0)) == NULL)
2236 return GPG_ERR_SYNTAX;
2238 else
2240 if ((path = str_split (req[1], " ", 0)) == NULL)
2241 return GPG_ERR_SYNTAX;
2244 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 0);
2245 if (!n || rc)
2246 goto fail;
2248 if (path[1])
2250 n = find_elements (client, client->doc, n->children, path + 1, &rc,
2251 NULL, NULL, NULL, 0, 0, NULL, 0);
2252 if (!n || rc)
2253 goto fail;
2256 strv_free (path);
2258 if ((a = xmlGetProp (n, (xmlChar *) req[0])) == NULL)
2259 return GPG_ERR_NOT_FOUND;
2261 pthread_cleanup_push (xmlFree, a);
2263 if (*a)
2264 rc = xfer_data (ctx, (char *) a, xmlStrlen (a));
2265 else
2266 rc = GPG_ERR_NO_DATA;
2268 pthread_cleanup_pop (1);
2269 return rc;
2271 fail:
2272 strv_free (path);
2273 return rc;
2277 * req[0] - attribute
2278 * req[1] - element path
2279 * req[2] - value
2281 static gpg_error_t
2282 attribute_set (struct client_s *client, char **req)
2284 char **path = NULL;
2285 gpg_error_t rc;
2286 xmlNodePtr n;
2288 if (!req || !req[0] || !req[1])
2289 return GPG_ERR_SYNTAX;
2292 * Reserved attribute names.
2294 if (!strcmp (req[0], "_name"))
2295 return GPG_ERR_INV_ATTR;
2296 else if (!strcmp (req[0], "target"))
2297 return target_attribute (client, req + 1);
2298 else if (!valid_xml_attribute (req[0]))
2299 return GPG_ERR_INV_VALUE;
2301 if ((path = str_split (req[1], "\t", 0)) == NULL)
2304 * The first argument may be only a root element.
2306 if ((path = str_split (req[1], " ", 0)) == NULL)
2307 return GPG_ERR_SYNTAX;
2310 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 0);
2311 if (!n || rc)
2312 goto fail;
2314 if (path[1])
2316 n = find_elements (client, client->doc, n->children, path + 1, &rc,
2317 NULL, NULL, NULL, 0, 0, NULL, 0);
2318 if (!n || rc)
2319 goto fail;
2322 if (!strcmp (req[0], (char *) "_acl"))
2324 rc = is_element_owner (client, n);
2325 if (rc)
2326 goto fail;
2329 rc = add_attribute (client, n, req[0], req[2]);
2331 fail:
2332 strv_free (path);
2333 return rc;
2337 * req[0] - command
2338 * req[1] - attribute name or element path if command is LIST
2339 * req[2] - element path
2340 * req[2] - element path or value
2343 static gpg_error_t
2344 do_attr (assuan_context_t ctx, char *line)
2346 struct client_s *client = assuan_get_pointer (ctx);
2347 gpg_error_t rc = 0;
2348 char **req;
2350 req = str_split (line, " ", 4);
2351 if (!req || !req[0] || !req[1])
2353 strv_free (req);
2354 return GPG_ERR_SYNTAX;
2357 pthread_cleanup_push (req_cleanup, req);
2359 if (strcasecmp (req[0], "SET") == 0)
2360 rc = attribute_set (client, req + 1);
2361 else if (strcasecmp (req[0], "GET") == 0)
2362 rc = attribute_get (ctx, req + 1);
2363 else if (strcasecmp (req[0], "DELETE") == 0)
2364 rc = attribute_delete (client, req + 1);
2365 else if (strcasecmp (req[0], "LIST") == 0)
2366 rc = attribute_list (ctx, req + 1);
2367 else
2368 rc = GPG_ERR_SYNTAX;
2370 client->flags &= ~(FLAG_ACL_IGNORE|FLAG_ACL_ERROR);
2371 pthread_cleanup_pop (1);
2372 return rc;
2375 static gpg_error_t
2376 attr_command (assuan_context_t ctx, char *line)
2378 struct client_s *client = assuan_get_pointer (ctx);
2379 gpg_error_t rc;
2380 struct argv_s *args[] = {
2381 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2382 NULL
2385 rc = parse_options (&line, args, client);
2386 if (rc)
2387 return send_error (ctx, rc);
2389 if (client->opts & OPT_INQUIRE)
2391 unsigned char *result;
2392 size_t len;
2394 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2395 if (rc)
2396 return send_error (ctx, rc);
2398 pthread_cleanup_push (xfree, result);
2399 rc = do_attr (ctx, (char *)result);
2400 pthread_cleanup_pop (1);
2402 else
2403 rc = do_attr (ctx, line);
2405 return send_error (ctx, rc);
2408 static gpg_error_t
2409 parse_iscached_opt_lock (void *data, void *value)
2411 struct client_s *client = data;
2413 (void) value;
2414 client->opts |= OPT_LOCK;
2415 return 0;
2418 static gpg_error_t
2419 iscached_command (assuan_context_t ctx, char *line)
2421 struct client_s *client = assuan_get_pointer (ctx);
2422 gpg_error_t rc;
2423 struct argv_s *args[] = {
2424 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_iscached_opt_lock},
2425 NULL
2428 if (!line || !*line)
2429 return send_error (ctx, GPG_ERR_SYNTAX);
2431 rc = parse_options (&line, args, client);
2432 if (rc)
2433 return send_error (ctx, rc);
2434 else if (!valid_filename (line))
2435 return send_error (ctx, GPG_ERR_INV_VALUE);
2437 rc = cache_iscached (line, NULL);
2438 if (client->opts & OPT_LOCK
2439 && (!rc || gpg_err_code (rc) == GPG_ERR_NO_DATA))
2441 unsigned char md5file[16];
2442 gpg_error_t trc = rc;
2444 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2445 if (memcmp (md5file, client->md5file, 16))
2446 cleanup_client (client);
2448 memcpy (client->md5file, md5file, 16);
2449 rc = do_lock (client, 1);
2450 if (!rc)
2451 rc = trc;
2454 return send_error (ctx, rc);
2457 static gpg_error_t
2458 clearcache_command (assuan_context_t ctx, char *line)
2460 gpg_error_t rc = 0, all_rc = 0;
2461 unsigned char md5file[16];
2462 int i;
2463 int t;
2464 int all = 0;
2465 struct client_thread_s *once = NULL;
2467 cache_lock ();
2468 MUTEX_LOCK (&cn_mutex);
2469 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
2471 if (!line || !*line)
2472 all = 1;
2474 t = slist_length (cn_thread_list);
2476 for (i = 0; i < t; i++)
2478 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2479 assuan_peercred_t peer;
2481 if (!thd->cl)
2482 continue;
2484 /* Lock each connected clients' file mutex to prevent any other client
2485 * from accessing the cache entry (the file mutex is locked upon
2486 * command startup). The cache for the entry is not cleared if the
2487 * file mutex is locked by another client to prevent this function
2488 * from blocking.
2490 if (all)
2492 if (thd->cl->filename)
2494 rc = do_validate_peer (ctx, thd->cl->filename, &peer);
2495 all_rc = !all_rc ? rc : all_rc;
2496 if (rc)
2498 rc = 0;
2499 continue;
2503 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0, -1);
2504 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2506 if (pthread_equal (pthread_self (), thd->tid))
2507 rc = 0;
2508 else
2510 if (!thd->cl->filename ||
2511 cache_iscached (thd->cl->filename,
2512 NULL) == GPG_ERR_NO_DATA)
2514 rc = 0;
2515 continue;
2518 cache_defer_clear (thd->cl->md5file);
2521 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
2523 rc = 0;
2524 continue;
2527 if (!rc)
2529 rc = cache_clear (thd->cl->md5file);
2530 cache_unlock_mutex (thd->cl->md5file, 0);
2533 if (rc)
2534 all_rc = rc;
2536 rc = 0;
2538 /* A single data filename was specified. Lock only this data file
2539 * mutex and free the cache entry. */
2540 else
2542 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2543 rc = do_validate_peer (ctx, line, &peer);
2545 if (!rc && !memcmp (thd->cl->md5file, md5file, sizeof (md5file)))
2547 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0,
2548 -1);
2549 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2551 if (pthread_equal (pthread_self (), thd->tid))
2552 rc = 0;
2555 if (!rc)
2557 once = thd;
2558 rc = cache_clear (thd->cl->md5file);
2559 cache_unlock_mutex (thd->cl->md5file, 0);
2561 else
2563 cache_defer_clear (thd->cl->md5file);
2566 break;
2571 /* Only connected clients' cache entries have been cleared. Now clear any
2572 * remaining cache entries without clients but only if there wasn't an
2573 * error from above since this would defeat the locking check of the
2574 * remaining entries. */
2575 if (!all_rc && all)
2577 cache_clear (NULL);
2580 /* No clients are using the specified file. */
2581 else if (!all_rc && !rc && !once)
2583 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2584 rc = cache_clear (md5file);
2587 /* Release the connection mutex. */
2588 pthread_cleanup_pop (1);
2589 cache_unlock ();
2591 if (!rc)
2592 send_status_all (STATUS_CACHE, NULL);
2594 /* One or more files were locked while clearing all cache entries. */
2595 if (all_rc)
2596 rc = all_rc;
2598 return send_error (ctx, rc);
2601 static gpg_error_t
2602 cachetimeout_command (assuan_context_t ctx, char *line)
2604 int timeout;
2605 char **req = str_split (line, " ", 0);
2606 char *p;
2607 gpg_error_t rc = 0;
2608 assuan_peercred_t peer;
2610 if (!req || !*req || !req[1])
2612 strv_free (req);
2613 return send_error (ctx, GPG_ERR_SYNTAX);
2616 errno = 0;
2617 timeout = (int) strtol (req[1], &p, 10);
2618 if (errno != 0 || *p || timeout < -1)
2620 strv_free (req);
2621 return send_error (ctx, GPG_ERR_SYNTAX);
2624 rc = do_validate_peer (ctx, req[0], &peer);
2625 if (!rc)
2627 unsigned char md5file[16];
2629 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, req[0], strlen (req[0]));
2630 rc = cache_set_timeout (md5file, timeout);
2631 if (!rc || gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
2633 rc = 0;
2634 MUTEX_LOCK (&rcfile_mutex);
2635 config_set_int_param (&global_config, req[0], "cache_timeout",
2636 req[1]);
2637 MUTEX_UNLOCK (&rcfile_mutex);
2641 strv_free (req);
2642 return send_error (ctx, rc);
2645 static gpg_error_t
2646 dump_command (assuan_context_t ctx, char *line)
2648 xmlChar *xml;
2649 int len;
2650 struct client_s *client = assuan_get_pointer (ctx);
2651 gpg_error_t rc;
2653 if (disable_list_and_dump == 1)
2654 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2656 rc = peer_is_invoker(client);
2657 if (rc)
2658 return send_error (ctx, rc);
2660 xmlDocDumpFormatMemory (client->doc, &xml, &len, 1);
2662 if (!xml)
2664 log_write ("%s(%i): %s", __FILE__, __LINE__,
2665 pwmd_strerror (GPG_ERR_ENOMEM));
2666 return send_error (ctx, GPG_ERR_ENOMEM);
2669 pthread_cleanup_push (xmlFree, xml);
2670 rc = xfer_data (ctx, (char *) xml, len);
2671 pthread_cleanup_pop (1);
2672 return send_error (ctx, rc);
2675 static gpg_error_t
2676 getconfig_command (assuan_context_t ctx, char *line)
2678 struct client_s *client = assuan_get_pointer (ctx);
2679 gpg_error_t rc = 0;
2680 char filename[255] = { 0 }, param[747] = { 0 };
2681 char *p, *tmp = NULL, *fp = client->filename, *paramp = line;
2683 if (!line || !*line)
2684 return send_error (ctx, GPG_ERR_SYNTAX);
2686 if (strchr (line, ' '))
2688 sscanf (line, " %254[^ ] %746c", filename, param);
2689 paramp = param;
2690 fp = filename;
2693 if (fp && !valid_filename (fp))
2694 return send_error (ctx, GPG_ERR_INV_VALUE);
2696 paramp = str_down (paramp);
2697 if (!strcmp (paramp, "cipher") && fp)
2699 struct crypto_s *crypto = NULL;
2701 rc = init_client_crypto (&crypto);
2702 if (!rc)
2704 rc = read_data_header (fp, &crypto->hdr, NULL, NULL);
2705 if (!rc)
2707 const char *t =
2708 gcry_cipher_algo_name (cipher_to_gcrypt (crypto->hdr.flags));
2709 if (t)
2711 tmp = str_dup (t);
2712 if (tmp)
2713 str_down (tmp);
2718 UPDATE_AGENT_CTX (client, crypto);
2719 cleanup_crypto (&crypto);
2720 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
2721 return send_error (ctx, rc);
2723 if (!rc && tmp)
2724 goto done;
2726 else if (!strcmp (paramp, "cipher_iterations") && fp)
2728 struct crypto_s *crypto = NULL;
2730 rc = init_client_crypto (&crypto);
2731 if (!rc)
2733 rc = read_data_header (fp, &crypto->hdr, NULL, NULL);
2734 if (!rc)
2736 tmp = str_asprintf ("%llu",
2737 (unsigned long long) crypto->hdr.s2k_count);
2738 if (!tmp)
2739 rc = GPG_ERR_ENOMEM;
2743 UPDATE_AGENT_CTX (client, crypto);
2744 cleanup_crypto (&crypto);
2745 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
2746 return send_error (ctx, rc);
2748 if (!rc && tmp)
2749 goto done;
2751 else if (!strcmp (paramp, "passphrase"))
2752 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2754 p = config_get_value (fp ? fp : "global", paramp);
2755 if (!p)
2756 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2758 tmp = expand_homedir (p);
2759 xfree (p);
2760 if (!tmp)
2762 log_write ("%s(%i): %s", __FILE__, __LINE__,
2763 pwmd_strerror (GPG_ERR_ENOMEM));
2764 return send_error (ctx, GPG_ERR_ENOMEM);
2767 done:
2768 p = tmp;
2769 pthread_cleanup_push (xfree, p);
2770 rc = xfer_data (ctx, p, strlen (p));
2771 pthread_cleanup_pop (1);
2772 return send_error (ctx, rc);
2775 struct xpath_s
2777 xmlXPathContextPtr xp;
2778 xmlXPathObjectPtr result;
2779 xmlBufferPtr buf;
2780 char **req;
2783 static void
2784 xpath_command_cleanup (void *arg)
2786 struct xpath_s *xpath = arg;
2788 if (!xpath)
2789 return;
2791 req_cleanup (xpath->req);
2793 if (xpath->buf)
2794 xmlBufferFree (xpath->buf);
2796 if (xpath->result)
2797 xmlXPathFreeObject (xpath->result);
2799 if (xpath->xp)
2800 xmlXPathFreeContext (xpath->xp);
2803 static gpg_error_t
2804 do_xpath (assuan_context_t ctx, char *line)
2806 gpg_error_t rc;
2807 struct client_s *client = assuan_get_pointer (ctx);
2808 struct xpath_s _x = { 0 };
2809 struct xpath_s *xpath = &_x;
2811 if (!line || !*line)
2812 return GPG_ERR_SYNTAX;
2814 if ((xpath->req = str_split (line, "\t", 2)) == NULL)
2816 if (strv_printf (&xpath->req, "%s", line) == 0)
2817 return GPG_ERR_ENOMEM;
2820 xpath->xp = xmlXPathNewContext (client->doc);
2821 if (!xpath->xp)
2823 rc = GPG_ERR_BAD_DATA;
2824 goto fail;
2827 xpath->result =
2828 xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2829 if (!xpath->result)
2831 rc = GPG_ERR_BAD_DATA;
2832 goto fail;
2835 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2837 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2838 goto fail;
2841 rc = recurse_xpath_nodeset (client, client->doc, xpath->result->nodesetval,
2842 (xmlChar *) xpath->req[1], &xpath->buf, 0,
2843 NULL);
2844 if (rc)
2845 goto fail;
2846 else if (!xpath->req[1] && !xmlBufferLength (xpath->buf))
2848 rc = GPG_ERR_NO_DATA;
2849 goto fail;
2851 else if (xpath->req[1])
2853 rc = 0;
2854 goto fail;
2857 pthread_cleanup_push (xpath_command_cleanup, &xpath);
2858 rc = xfer_data (ctx, (char *) xmlBufferContent (xpath->buf),
2859 xmlBufferLength (xpath->buf));
2860 pthread_cleanup_pop (0);
2861 fail:
2862 xpath_command_cleanup (xpath);
2863 return rc;
2866 static gpg_error_t
2867 xpath_command (assuan_context_t ctx, char *line)
2869 struct client_s *client = assuan_get_pointer (ctx);
2870 gpg_error_t rc;
2871 struct argv_s *args[] = {
2872 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2873 NULL
2876 if (disable_list_and_dump == 1)
2877 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2879 rc = peer_is_invoker(client);
2880 if (rc)
2881 return send_error (ctx, rc);
2883 rc = parse_options (&line, args, client);
2884 if (rc)
2885 return send_error (ctx, rc);
2887 if (client->opts & OPT_INQUIRE)
2889 unsigned char *result;
2890 size_t len;
2892 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2893 if (rc)
2894 return send_error (ctx, rc);
2896 pthread_cleanup_push (xfree, result);
2897 rc = do_xpath (ctx, (char *)result);
2898 pthread_cleanup_pop (1);
2900 else
2901 rc = do_xpath (ctx, line);
2903 return send_error (ctx, rc);
2906 static gpg_error_t
2907 do_xpathattr (assuan_context_t ctx, char *line)
2909 struct client_s *client = assuan_get_pointer (ctx);
2910 gpg_error_t rc;
2911 char **req = NULL;
2912 int cmd = 0; //SET
2913 struct xpath_s _x = { 0 };
2914 struct xpath_s *xpath = &_x;
2916 if (!line || !*line)
2917 return GPG_ERR_SYNTAX;
2919 if ((req = str_split (line, " ", 3)) == NULL)
2920 return GPG_ERR_ENOMEM;
2922 if (!req[0])
2924 rc = GPG_ERR_SYNTAX;
2925 goto fail;
2928 if (!strcasecmp (req[0], "SET"))
2929 cmd = 0;
2930 else if (!strcasecmp (req[0], "DELETE"))
2931 cmd = 1;
2932 else
2934 rc = GPG_ERR_SYNTAX;
2935 goto fail;
2938 if (!req[1] || !req[2])
2940 rc = GPG_ERR_SYNTAX;
2941 goto fail;
2944 if ((xpath->req = str_split (req[2], "\t", 3)) == NULL)
2946 rc = GPG_ERR_ENOMEM;
2947 goto fail;
2950 if (!xpath->req[0] || (!xpath->req[1] && !cmd) || (xpath->req[1] && cmd))
2952 rc = GPG_ERR_SYNTAX;
2953 goto fail;
2956 xpath->xp = xmlXPathNewContext (client->doc);
2957 if (!xpath->xp)
2959 rc = GPG_ERR_BAD_DATA;
2960 goto fail;
2963 xpath->result = xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2964 if (!xpath->result)
2966 rc = GPG_ERR_BAD_DATA;
2967 goto fail;
2970 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2972 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2973 goto fail;
2976 rc = recurse_xpath_nodeset (client, client->doc, xpath->result->nodesetval,
2977 (xmlChar *) xpath->req[1], &xpath->buf, cmd,
2978 (xmlChar *) req[1]);
2980 fail:
2981 xpath_command_cleanup (xpath);
2982 strv_free (req);
2983 return rc;
2986 /* XPATHATTR SET|DELETE <name> <expression>[<TAB>[value]] */
2987 static gpg_error_t
2988 xpathattr_command (assuan_context_t ctx, char *line)
2990 struct client_s *client = assuan_get_pointer (ctx);
2991 gpg_error_t rc;
2992 struct argv_s *args[] = {
2993 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2994 NULL
2997 if (disable_list_and_dump == 1)
2998 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
3000 rc = peer_is_invoker(client);
3001 if (rc)
3002 return send_error (ctx, rc);
3004 rc = parse_options (&line, args, client);
3005 if (rc)
3006 return send_error (ctx, rc);
3008 if (client->opts & OPT_INQUIRE)
3010 unsigned char *result;
3011 size_t len;
3013 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3014 if (rc)
3015 return send_error (ctx, rc);
3017 pthread_cleanup_push (xfree, result);
3018 rc = do_xpathattr (ctx, (char *)result);
3019 pthread_cleanup_pop (1);
3021 else
3022 rc = do_xpathattr (ctx, line);
3024 return send_error (ctx, rc);
3027 static gpg_error_t
3028 do_import (struct client_s *client, const char *root_element,
3029 unsigned char *content)
3031 char **dst_path = NULL;
3032 xmlDocPtr doc = NULL;
3033 xmlNodePtr n, root, copy;
3034 gpg_error_t rc;
3036 if (!content || !*content)
3038 xfree (content);
3039 return GPG_ERR_SYNTAX;
3042 if (root_element)
3043 dst_path = str_split (root_element, "\t", 0);
3045 if (dst_path && !valid_element_path (dst_path, 0))
3047 if (dst_path)
3048 strv_free (dst_path);
3050 return GPG_ERR_INV_VALUE;
3053 struct string_s *str = string_new_content ((char *)content);
3054 str = string_prepend (str, "<pwmd>");
3055 str = string_append (str, "</pwmd>");
3056 doc = xmlReadDoc ((xmlChar *) str->str, NULL, "UTF-8", XML_PARSE_NOBLANKS);
3057 string_free (str, 1);
3058 if (!doc)
3060 rc = GPG_ERR_BAD_DATA;
3061 goto fail;
3064 root = xmlDocGetRootElement (doc);
3065 xmlNodePtr root_orig = root->children;
3066 root = root->children;
3067 rc = validate_import (client, root);
3068 if (rc)
3069 goto fail;
3073 again:
3074 if (dst_path)
3076 char **path = strv_dup (dst_path);
3077 if (!path)
3079 log_write ("%s(%i): %s", __FILE__, __LINE__,
3080 pwmd_strerror (GPG_ERR_ENOMEM));
3081 rc = GPG_ERR_ENOMEM;
3082 goto fail;
3085 xmlChar *a = xmlGetProp (root, (xmlChar *) "_name");
3086 if (!a)
3088 strv_free (path);
3089 rc = GPG_ERR_INV_VALUE;
3090 goto fail;
3093 if (strv_printf (&path, "%s", (char *) a) == 0)
3095 xmlFree (a);
3096 rc = GPG_ERR_ENOMEM;
3097 goto fail;
3100 xmlFree (a);
3101 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 0);
3102 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3104 strv_free (path);
3105 goto fail;
3108 if (!rc)
3110 n = find_elements (client, client->doc, n->children, path + 1, &rc,
3111 NULL, NULL, NULL, 0, 0, NULL, 1);
3112 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3114 strv_free (path);
3115 goto fail;
3117 else if (!rc)
3119 xmlUnlinkNode (n);
3120 xmlFreeNode (n);
3121 strv_free (path);
3122 path = NULL;
3123 goto again;
3127 if (rc == GPG_ERR_ELEMENT_NOT_FOUND)
3129 n = create_element_path (client, &path, &rc, NULL);
3130 if (rc)
3131 goto fail;
3134 if (root->children)
3136 copy = xmlCopyNodeList (root->children);
3137 n = xmlAddChildList (n, copy);
3138 if (!n)
3139 rc = GPG_ERR_ENOMEM;
3142 strv_free (path);
3144 else
3146 char **path = NULL;
3148 /* Check if the content root element can create a DTD root element. */
3149 if (!xmlStrEqual ((xmlChar *) "element", root->name))
3151 rc = GPG_ERR_SYNTAX;
3152 goto fail;
3155 xmlChar *a;
3157 if ((a = xmlGetProp (root, (xmlChar *) "_name")) == NULL)
3159 rc = GPG_ERR_SYNTAX;
3160 goto fail;
3163 char *tmp = str_dup ((char *) a);
3164 xmlFree (a);
3165 int literal = is_literal_element (&tmp);
3167 if (!valid_xml_element ((xmlChar *) tmp) || literal)
3169 xfree (tmp);
3170 rc = GPG_ERR_INV_VALUE;
3171 goto fail;
3174 if (strv_printf (&path, "%s", tmp) == 0)
3176 xfree (tmp);
3177 rc = GPG_ERR_ENOMEM;
3178 goto fail;
3181 xfree (tmp);
3182 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 1);
3183 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3185 rc = GPG_ERR_BAD_DATA;
3186 goto fail;
3189 /* Overwriting the existing tree. */
3190 if (!rc)
3192 xmlUnlinkNode (n);
3193 xmlFreeNodeList (n);
3196 rc = 0;
3197 xmlSetProp (root, (xmlChar *) "_name", (xmlChar *) path[0]);
3198 n = xmlCopyNode (root, 1);
3199 n = xmlAddChildList (xmlDocGetRootElement (client->doc), n);
3200 strv_free (path);
3203 if (n && !rc)
3204 rc = update_element_mtime (client, n->parent);
3206 for (root = root_orig->next; root; root = root->next)
3208 if (root->type == XML_ELEMENT_NODE)
3209 break;
3212 root_orig = root;
3214 while (root);
3216 fail:
3217 if (doc)
3218 xmlFreeDoc (doc);
3220 if (dst_path)
3221 strv_free (dst_path);
3223 return rc;
3226 static gpg_error_t
3227 parse_import_opt_root (void *data, void *value)
3229 struct client_s *client = data;
3231 client->import_root = str_dup (value);
3232 return client->import_root ? 0 : GPG_ERR_ENOMEM;
3235 static gpg_error_t
3236 import_command (assuan_context_t ctx, char *line)
3238 gpg_error_t rc;
3239 struct client_s *client = assuan_get_pointer (ctx);
3240 unsigned char *result;
3241 size_t len;
3242 struct argv_s *args[] = {
3243 &(struct argv_s) {"root", OPTION_TYPE_ARG, parse_import_opt_root},
3244 NULL
3247 xfree (client->import_root);
3248 client->import_root = NULL;
3249 rc = parse_options (&line, args, client);
3250 if (rc)
3251 return send_error (ctx, rc);
3253 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3254 if (rc)
3256 xfree (client->import_root);
3257 client->import_root = NULL;
3258 return send_error (ctx, rc);
3261 rc = do_import (client, client->import_root, result);
3262 xfree (client->import_root);
3263 client->import_root = NULL;
3264 return send_error (ctx, rc);
3267 static gpg_error_t
3268 do_lock (struct client_s *client, int add)
3270 gpg_error_t rc = lock_file_mutex (client, add);
3272 if (!rc)
3273 client->flags |= FLAG_LOCK_CMD;
3275 return rc;
3278 static gpg_error_t
3279 lock_command (assuan_context_t ctx, char *line)
3281 struct client_s *client = assuan_get_pointer (ctx);
3282 gpg_error_t rc = do_lock (client, 0);
3284 return send_error (ctx, rc);
3287 static gpg_error_t
3288 unlock_command (assuan_context_t ctx, char *line)
3290 struct client_s *client = assuan_get_pointer (ctx);
3291 gpg_error_t rc;
3293 rc = unlock_file_mutex (client, 0);
3294 return send_error (ctx, rc);
3297 static gpg_error_t
3298 option_command (assuan_context_t ctx, char *line)
3300 struct client_s *client = assuan_get_pointer (ctx);
3301 gpg_error_t rc = 0;
3302 struct pinentry_option_s *pin_opts = &client->pinentry_opts;
3303 #ifdef WITH_AGENT
3304 struct agent_s *agent = client->crypto->agent;
3305 #endif
3306 char namebuf[255] = { 0 };
3307 char *name = namebuf;
3308 char *value = NULL, *p, *tmp = NULL;
3310 p = strchr (line, '=');
3311 if (!p)
3313 strncpy (namebuf, line, sizeof(namebuf));
3314 namebuf[sizeof(namebuf)-1] = 0;
3316 else
3318 strncpy (namebuf, line, strlen (line)-strlen (p));
3319 namebuf[sizeof(namebuf)-1] = 0;
3320 value = p+1;
3323 log_write1 ("OPTION name='%s' value='%s'", name, value);
3325 if (strcasecmp (name, (char *) "log_level") == 0)
3327 long l = 0;
3329 if (value)
3331 l = strtol (value, NULL, 10);
3333 if (l < 0 || l > 2)
3334 return send_error (ctx, GPG_ERR_INV_VALUE);
3336 else
3337 return send_error (ctx, GPG_ERR_INV_VALUE);
3339 MUTEX_LOCK (&rcfile_mutex);
3340 config_set_int_param (&global_config, "global", "log_level", value);
3341 MUTEX_UNLOCK (&rcfile_mutex);
3342 goto done;
3344 else if (strcasecmp (name, (char *) "lock-timeout") == 0)
3346 long n = 0;
3348 if (value)
3350 n = strtol (value, &tmp, 10);
3351 if (tmp && *tmp)
3352 return send_error (ctx, GPG_ERR_INV_VALUE);
3355 client->lock_timeout = n;
3356 goto done;
3358 else if (strcasecmp (name, (char *) "NAME") == 0)
3360 if (value && strchr (value, ' '))
3361 rc = GPG_ERR_INV_VALUE;
3362 else
3364 tmp = pthread_getspecific (thread_name_key);
3365 xfree (tmp);
3366 MUTEX_LOCK (&cn_mutex);
3367 xfree (client->thd->name);
3368 client->thd->name = NULL;
3370 if (!value || !*value)
3371 pthread_setspecific (thread_name_key, str_dup (""));
3372 else
3374 client->thd->name = str_dup (value);
3375 pthread_setspecific (thread_name_key, str_dup (value));
3378 MUTEX_UNLOCK (&cn_mutex);
3380 goto done;
3382 else if (strcasecmp (name, (char *) "lc-messages") == 0)
3384 xfree (pin_opts->lc_messages);
3385 pin_opts->lc_messages = NULL;
3386 if (value && *value)
3387 pin_opts->lc_messages = str_dup (value);
3388 #ifdef WITH_AGENT
3389 if (use_agent)
3390 rc = set_agent_option (client->crypto->agent, "lc-messages", value);
3391 #endif
3393 else if (strcasecmp (name, (char *) "lc-ctype") == 0)
3395 xfree (pin_opts->lc_ctype);
3396 pin_opts->lc_ctype = NULL;
3397 if (value && *value)
3398 pin_opts->lc_ctype = str_dup (value);
3399 #ifdef WITH_AGENT
3400 if (use_agent)
3401 rc = set_agent_option (client->crypto->agent, "lc-ctype", value);
3402 #endif
3404 else if (strcasecmp (name, (char *) "ttyname") == 0)
3406 xfree (pin_opts->ttyname);
3407 pin_opts->ttyname = NULL;
3408 if (value && *value)
3409 pin_opts->ttyname = str_dup (value);
3410 #ifdef WITH_AGENT
3411 if (use_agent)
3412 rc = set_agent_option (client->crypto->agent, "ttyname", value);
3413 #endif
3415 else if (strcasecmp (name, (char *) "ttytype") == 0)
3417 xfree (pin_opts->ttytype);
3418 pin_opts->ttytype = NULL;
3419 if (value && *value)
3420 pin_opts->ttytype = str_dup (value);
3421 #ifdef WITH_AGENT
3422 if (use_agent)
3423 rc = set_agent_option (client->crypto->agent, "ttytype", value);
3424 #endif
3426 else if (strcasecmp (name, (char *) "display") == 0)
3428 xfree (pin_opts->display);
3429 pin_opts->display = NULL;
3430 if (value && *value)
3431 pin_opts->display = str_dup (value);
3432 #ifdef WITH_AGENT
3433 if (use_agent)
3434 rc = set_agent_option (client->crypto->agent, "display", value);
3435 #endif
3437 else if (strcasecmp (name, (char *) "pinentry-desc") == 0)
3439 xfree (pin_opts->desc);
3440 pin_opts->desc = NULL;
3441 if (value && *value)
3442 pin_opts->desc = str_dup (value);
3444 else if (strcasecmp (name, (char *) "pinentry-title") == 0)
3446 xfree (pin_opts->title);
3447 pin_opts->title = NULL;
3448 if (value && *value)
3449 pin_opts->title = str_dup (value);
3451 else if (strcasecmp (name, (char *) "pinentry-prompt") == 0)
3453 xfree (pin_opts->prompt);
3454 pin_opts->prompt = NULL;
3455 if (value && *value)
3456 pin_opts->prompt = str_dup (value);
3459 else if (strcasecmp (name, "pinentry-timeout") == 0)
3461 char *p = NULL;
3462 int n;
3464 if (!value)
3465 goto done;
3467 n = (int) strtol (value, &p, 10);
3469 if (*p || n < 0)
3470 return send_error (ctx, GPG_ERR_INV_VALUE);
3472 pin_opts->timeout = n;
3473 MUTEX_LOCK (&rcfile_mutex);
3474 config_set_int_param (&global_config,
3475 client->filename ? client->filename : "global",
3476 "pinentry_timeout", value);
3477 MUTEX_UNLOCK (&rcfile_mutex);
3478 goto done;
3480 else if (strcasecmp (name, "disable-pinentry") == 0)
3482 int n = 1;
3484 if (value && *value)
3486 n = (int) strtol (value, &tmp, 10);
3487 if (*tmp || n < 0 || n > 1)
3488 return send_error (ctx, GPG_ERR_INV_VALUE);
3491 if (n)
3492 client->flags |= FLAG_NO_PINENTRY;
3493 else
3494 client->flags &= ~FLAG_NO_PINENTRY;
3496 #ifdef WITH_AGENT
3497 if (use_agent)
3499 if (client->flags & FLAG_NO_PINENTRY)
3500 rc = set_agent_option (client->crypto->agent, "pinentry-mode",
3501 "loopback");
3502 else
3503 rc = set_agent_option (client->crypto->agent, "pinentry-mode",
3504 "ask");
3506 if (rc)
3507 return send_error (ctx, rc);
3509 #endif
3511 else
3512 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
3514 done:
3515 #ifdef WITH_AGENT
3516 if (!rc && use_agent && agent)
3518 rc = pinentry_merge_options (&client->crypto->agent->pinentry_opts,
3519 pin_opts);
3521 #endif
3523 return send_error (ctx, rc);
3526 static gpg_error_t
3527 do_rename (assuan_context_t ctx, char *line)
3529 struct client_s *client = assuan_get_pointer (ctx);
3530 gpg_error_t rc;
3531 char **req, **src, *dst;
3532 xmlNodePtr n, ndst;
3534 req = str_split (line, " ", 0);
3536 if (!req || !req[0] || !req[1])
3538 strv_free (req);
3539 return GPG_ERR_SYNTAX;
3542 dst = req[1];
3543 is_literal_element (&dst);
3545 if (!valid_xml_element ((xmlChar *) dst))
3547 strv_free (req);
3548 return GPG_ERR_INV_VALUE;
3551 if (strchr (req[0], '\t'))
3552 src = str_split (req[0], "\t", 0);
3553 else
3554 src = str_split (req[0], " ", 0);
3556 if (!src || !*src)
3558 rc = GPG_ERR_SYNTAX;
3559 goto fail;
3562 n = find_root_element (client, client->doc, &src, &rc, NULL, 0, 0);
3563 if (rc)
3564 goto fail;
3566 if (src[1] && n)
3567 n = find_elements (client, client->doc, n->children, src + 1, &rc, NULL, NULL,
3568 NULL, 0, 0, NULL, 0);
3570 if (!n || rc)
3571 goto fail;
3573 rc = is_element_owner (client, n);
3574 if (rc)
3575 goto fail;
3577 xmlChar *a = xmlGetProp (n, (xmlChar *) "_name");
3578 if (!a)
3580 rc = GPG_ERR_ENOMEM;
3581 goto fail;
3584 /* To prevent unwanted effects:
3586 * <root name="a"><b/></root>
3588 * RENAME a<TAB>b b
3590 if (xmlStrEqual (a, (xmlChar *) dst))
3592 xmlFree (a);
3593 rc = GPG_ERR_AMBIGUOUS_NAME;
3594 goto fail;
3597 xmlFree (a);
3598 char **tmp = NULL;
3599 if (src[1])
3601 char **p;
3603 for (p = src; *p; p++)
3605 if (!*(p + 1))
3606 break;
3607 strv_printf (&tmp, "%s", *p);
3611 strv_printf (&tmp, "!%s", dst);
3612 ndst = find_root_element (client, client->doc, &tmp, &rc, NULL, 0, 0);
3613 if (!ndst && rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3615 strv_free (tmp);
3616 goto fail;
3619 if (tmp[1] && ndst)
3620 ndst = find_elements (client, client->doc, ndst->children, tmp + 1, &rc, NULL,
3621 NULL, NULL, 0, 0, NULL, 0);
3623 strv_free (tmp);
3624 if (!ndst && rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3625 goto fail;
3627 rc = 0;
3629 /* Target may exist:
3631 * <root name="a"/>
3632 * <root name="b" target="a"/>
3634 * RENAME b a
3636 * Would need to do:
3637 * RENAME !b a
3639 if (ndst == n)
3641 rc = GPG_ERR_AMBIGUOUS_NAME;
3642 goto fail;
3645 if (ndst)
3647 rc = is_element_owner (client, ndst);
3648 if (rc)
3649 goto fail;
3651 unlink_node (client, ndst);
3652 xmlFreeNodeList (ndst);
3655 rc = add_attribute (client, n, "_name", dst);
3657 fail:
3658 strv_free (req);
3659 strv_free (src);
3660 return rc;
3663 static gpg_error_t
3664 rename_command (assuan_context_t ctx, char *line)
3666 struct client_s *client = assuan_get_pointer (ctx);
3667 gpg_error_t rc;
3668 struct argv_s *args[] = {
3669 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3670 NULL
3673 rc = parse_options (&line, args, client);
3674 if (rc)
3675 return send_error (ctx, rc);
3677 if (client->opts & OPT_INQUIRE)
3679 unsigned char *result;
3680 size_t len;
3682 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3683 if (rc)
3684 return send_error (ctx, rc);
3686 pthread_cleanup_push (xfree, result);
3687 rc = do_rename (ctx, (char *)result);
3688 pthread_cleanup_pop (1);
3690 else
3691 rc = do_rename (ctx, line);
3693 return send_error (ctx, rc);
3696 static gpg_error_t
3697 do_copy (assuan_context_t ctx, char *line)
3699 struct client_s *client = assuan_get_pointer (ctx);
3700 gpg_error_t rc;
3701 char **req, **src = NULL, **dst = NULL;
3702 xmlNodePtr nsrc, ndst, new = NULL;
3704 req = str_split (line, " ", 0);
3705 if (!req || !req[0] || !req[1])
3707 strv_free (req);
3708 return GPG_ERR_SYNTAX;
3711 if (strchr (req[0], '\t'))
3712 src = str_split (req[0], "\t", 0);
3713 else
3714 src = str_split (req[0], " ", 0);
3716 if (!src || !*src)
3718 rc = GPG_ERR_SYNTAX;
3719 goto fail;
3722 if (strchr (req[1], '\t'))
3723 dst = str_split (req[1], "\t", 0);
3724 else
3725 dst = str_split (req[1], " ", 0);
3727 if (!dst || !*dst)
3729 rc = GPG_ERR_SYNTAX;
3730 goto fail;
3733 if (!valid_element_path (dst, 0))
3735 rc = GPG_ERR_INV_VALUE;
3736 goto fail;
3739 nsrc = find_root_element (client, client->doc, &src, &rc, NULL, 0, 0);
3740 if (rc)
3741 goto fail;
3743 if (nsrc && src[1])
3744 nsrc = find_elements (client, client->doc, nsrc->children, src + 1, &rc, NULL,
3745 NULL, NULL, 0, 0, NULL, 0);
3747 if (!nsrc || rc)
3748 goto fail;
3750 new = xmlCopyNodeList (nsrc);
3751 if (!new)
3753 rc = GPG_ERR_ENOMEM;
3754 goto fail;
3757 int create = 0;
3758 ndst = find_root_element (client, client->doc, &dst, &rc, NULL, 0, 0);
3759 if (rc == GPG_ERR_EACCES)
3760 goto fail;
3762 if (ndst && dst[1])
3764 if (ndst->children)
3765 ndst = find_elements (client, client->doc, ndst->children, dst + 1, &rc, NULL,
3766 NULL, create_target_elements_cb, 0, 0, NULL, 0);
3767 else
3768 create = 1;
3770 else
3771 create = 1;
3773 if (!ndst && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3774 goto fail;
3775 else if (!ndst || create)
3777 ndst = create_element_path (client, &dst, &rc, NULL);
3778 if (!ndst || rc)
3779 goto fail;
3782 rc = is_element_owner (client, ndst);
3783 if (rc)
3784 goto fail;
3786 /* Merge any attributes from the src node to the initial dst node. */
3787 for (xmlAttrPtr attr = new->properties; attr; attr = attr->next)
3789 if (xmlStrEqual (attr->name, (xmlChar *) "_name"))
3790 continue;
3792 xmlAttrPtr a = xmlHasProp (ndst, attr->name);
3793 if (a)
3794 xmlRemoveProp (a);
3796 xmlChar *tmp = xmlNodeGetContent (attr->children);
3797 xmlNewProp (ndst, attr->name, tmp);
3798 xmlFree (tmp);
3799 rc = add_attribute (client, ndst, NULL, NULL);
3802 xmlNodePtr n = ndst->children;
3803 xmlUnlinkNode (n);
3804 xmlFreeNodeList (n);
3805 ndst->children = NULL;
3807 if (new->children)
3809 n = xmlCopyNodeList (new->children);
3810 if (!n)
3812 rc = GPG_ERR_ENOMEM;
3813 goto fail;
3816 n = xmlAddChildList (ndst, n);
3817 if (!n)
3819 rc = GPG_ERR_ENOMEM;
3820 goto fail;
3823 rc = update_element_mtime (client, xmlDocGetRootElement (client->doc) ==
3824 ndst->parent ? ndst : ndst->parent);
3827 fail:
3828 if (new)
3830 xmlUnlinkNode (new);
3831 xmlFreeNodeList (new);
3834 if (req)
3835 strv_free (req);
3837 if (src)
3838 strv_free (src);
3840 if (dst)
3841 strv_free (dst);
3843 return rc;
3846 static gpg_error_t
3847 copy_command (assuan_context_t ctx, char *line)
3849 struct client_s *client = assuan_get_pointer (ctx);
3850 gpg_error_t rc;
3851 struct argv_s *args[] = {
3852 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3853 NULL
3856 rc = parse_options (&line, args, client);
3857 if (rc)
3858 return send_error (ctx, rc);
3860 if (client->opts & OPT_INQUIRE)
3862 unsigned char *result;
3863 size_t len;
3865 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3866 if (rc)
3867 return send_error (ctx, rc);
3869 pthread_cleanup_push (xfree, result);
3870 rc = do_copy (ctx, (char *)result);
3871 pthread_cleanup_pop (1);
3873 else
3874 rc = do_copy (ctx, line);
3876 return send_error (ctx, rc);
3879 static gpg_error_t
3880 do_move (assuan_context_t ctx, char *line)
3882 struct client_s *client = assuan_get_pointer (ctx);
3883 gpg_error_t rc;
3884 char **req, **src = NULL, **dst = NULL;
3885 xmlNodePtr nsrc, ndst = NULL;
3887 req = str_split (line, " ", 0);
3889 if (!req || !req[0] || !req[1])
3891 strv_free (req);
3892 return GPG_ERR_SYNTAX;
3895 if (strchr (req[0], '\t'))
3896 src = str_split (req[0], "\t", 0);
3897 else
3898 src = str_split (req[0], " ", 0);
3900 if (!src || !*src)
3902 rc = GPG_ERR_SYNTAX;
3903 goto fail;
3906 if (strchr (req[1], '\t'))
3907 dst = str_split (req[1], "\t", 0);
3908 else
3909 dst = str_split (req[1], " ", 0);
3911 nsrc = find_root_element (client, client->doc, &src, &rc, NULL, 0, 0);
3912 if (rc)
3913 goto fail;
3915 if (nsrc && src[1])
3916 nsrc = find_elements (client, client->doc, nsrc->children, src + 1, &rc,
3917 NULL, NULL, NULL, 0, 0, NULL, 0);
3919 if (!nsrc)
3920 goto fail;
3922 rc = is_element_owner (client, nsrc);
3923 if (rc)
3924 goto fail;
3926 if (dst)
3928 if (!valid_element_path (dst, 0))
3930 rc = GPG_ERR_INV_VALUE;
3931 goto fail;
3934 ndst = find_root_element (client, client->doc, &dst, &rc, NULL, 0, 0);
3935 if (rc)
3936 goto fail;
3938 if (ndst && dst[1])
3939 ndst = find_elements (client, client->doc, ndst->children, dst + 1,
3940 &rc, NULL, NULL, NULL, 0, 0, NULL, 0);
3942 else
3943 ndst = xmlDocGetRootElement (client->doc);
3945 for (xmlNodePtr n = ndst; n; n = n->parent)
3947 if (n == nsrc)
3949 rc = GPG_ERR_CONFLICT;
3950 goto fail;
3954 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3955 goto fail;
3957 rc = 0;
3959 if (ndst)
3961 xmlChar *a = node_has_attribute (nsrc, (xmlChar *) "_name");
3963 xmlNodePtr dup = find_element (client, ndst->children, (char *) a,
3964 NULL, &rc);
3965 xmlFree (a);
3967 if (rc)
3968 goto fail;
3970 if (dup)
3972 if (dup == nsrc)
3973 goto fail;
3975 if (ndst == xmlDocGetRootElement (client->doc))
3977 xmlNodePtr n = nsrc;
3978 int match = 0;
3980 while (n->parent && n->parent != ndst)
3981 n = n->parent;
3983 xmlChar *a = node_has_attribute (n, (xmlChar *) "_name");
3984 xmlChar *b = node_has_attribute (nsrc, (xmlChar *) "_name");
3986 if (xmlStrEqual (a, b))
3988 match = 1;
3989 xmlUnlinkNode (nsrc);
3990 xmlUnlinkNode (n);
3991 xmlFreeNodeList (n);
3994 xmlFree (a);
3995 xmlFree (b);
3997 if (!match)
3999 xmlUnlinkNode (dup);
4000 xmlFreeNodeList (dup);
4003 else
4004 xmlUnlinkNode (dup);
4008 if (!ndst && dst)
4010 xmlChar *name = node_has_attribute (nsrc, (xmlChar *) "_name");
4012 if (nsrc->parent == xmlDocGetRootElement (client->doc)
4013 && !strcmp ((char *) name, *dst))
4015 xmlFree (name);
4016 rc = GPG_ERR_CONFLICT;
4017 goto fail;
4020 xmlFree (name);
4021 ndst = create_element_path (client, &dst, &rc, nsrc);
4022 if (rc)
4023 goto fail;
4026 if (!ndst)
4027 goto fail;
4029 update_element_mtime (client, nsrc->parent);
4030 xmlUnlinkNode (nsrc);
4031 ndst = xmlAddChildList (ndst, nsrc);
4033 if (!ndst)
4034 rc = GPG_ERR_ENOMEM;
4035 else
4036 update_element_mtime (client, ndst->parent);
4038 fail:
4039 if (req)
4040 strv_free (req);
4042 if (src)
4043 strv_free (src);
4045 if (dst)
4046 strv_free (dst);
4048 return rc;
4051 static gpg_error_t
4052 move_command (assuan_context_t ctx, char *line)
4054 struct client_s *client = assuan_get_pointer (ctx);
4055 gpg_error_t rc;
4056 struct argv_s *args[] = {
4057 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
4058 NULL
4061 rc = parse_options (&line, args, client);
4062 if (rc)
4063 return send_error (ctx, rc);
4065 if (client->opts & OPT_INQUIRE)
4067 unsigned char *result;
4068 size_t len;
4070 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
4071 if (rc)
4072 return send_error (ctx, rc);
4074 pthread_cleanup_push (xfree, result);
4075 rc = do_move (ctx, (char *)result);
4076 pthread_cleanup_pop (1);
4078 else
4079 rc = do_move (ctx, line);
4081 return send_error (ctx, rc);
4084 static gpg_error_t
4085 ls_command (assuan_context_t ctx, char *line)
4087 gpg_error_t rc;
4088 char *tmp = str_asprintf ("%s/data", homedir);
4089 char *dir = expand_homedir (tmp);
4090 DIR *d = opendir (dir);
4092 rc = gpg_error_from_errno (errno);
4093 xfree (tmp);
4095 if (!d)
4097 xfree (dir);
4098 return send_error (ctx, rc);
4101 size_t len =
4102 offsetof (struct dirent, d_name) +pathconf (dir, _PC_NAME_MAX) + 1;
4103 struct dirent *p = xmalloc (len), *cur = NULL;
4104 char *list = NULL;
4106 xfree (dir);
4107 pthread_cleanup_push (xfree, p);
4108 pthread_cleanup_push ((void *)(void *)closedir, d);
4109 rc = 0;
4111 while (!readdir_r (d, p, &cur) && cur)
4113 if (cur->d_name[0] == '.' && cur->d_name[1] == '\0')
4114 continue;
4115 else if (cur->d_name[0] == '.' && cur->d_name[1] == '.'
4116 && cur->d_name[2] == '\0')
4117 continue;
4119 tmp = str_asprintf ("%s%s\n", list ? list : "", cur->d_name);
4121 if (!tmp)
4123 if (list)
4124 xfree (list);
4126 rc = GPG_ERR_ENOMEM;
4127 break;
4130 xfree (list);
4131 list = tmp;
4134 pthread_cleanup_pop (1); // closedir (d)
4135 pthread_cleanup_pop (1); // xfree (p)
4137 if (rc)
4138 return send_error (ctx, rc);
4140 if (!list)
4141 return send_error (ctx, GPG_ERR_NO_DATA);
4143 list[strlen (list) - 1] = 0;
4144 pthread_cleanup_push (xfree, list);
4145 rc = xfer_data (ctx, list, strlen (list));
4146 pthread_cleanup_pop (1);
4147 return send_error (ctx, rc);
4150 static gpg_error_t
4151 bye_notify (assuan_context_t ctx, char *line)
4153 struct client_s *cl = assuan_get_pointer (ctx);
4155 cl->thd->state = CLIENT_STATE_DISCON;
4157 #ifdef WITH_GNUTLS
4158 if (cl->thd->remote)
4160 int rc;
4164 struct timeval tv = { 0, 50000 };
4166 rc = gnutls_bye (cl->thd->tls->ses, GNUTLS_SHUT_RDWR);
4167 if (rc == GNUTLS_E_AGAIN)
4168 select (0, NULL, NULL, NULL, &tv);
4170 while (rc == GNUTLS_E_AGAIN);
4172 #endif
4174 /* This will let assuan_process_next() return. */
4175 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
4177 cl->last_rc = gpg_error_from_errno (errno);
4178 return cl->last_rc;
4181 cl->last_rc = 0; // BYE command result
4182 return 0;
4185 static gpg_error_t
4186 reset_notify (assuan_context_t ctx, char *line)
4188 struct client_s *client = assuan_get_pointer (ctx);
4190 if (client)
4191 cleanup_client (client);
4193 return 0;
4197 * This is called before every Assuan command.
4199 static gpg_error_t
4200 command_startup (assuan_context_t ctx, const char *name)
4202 struct client_s *client = assuan_get_pointer (ctx);
4203 gpg_error_t rc;
4204 struct command_table_s *cmd = NULL;
4206 log_write1 ("command='%s'", name);
4207 client->last_rc = client->opts = 0;
4209 for (int i = 0; command_table[i]; i++)
4211 if (!strcasecmp (name, command_table[i]->name))
4213 if (command_table[i]->ignore_startup)
4214 return 0;
4215 cmd = command_table[i];
4216 break;
4220 if (!cmd)
4221 return GPG_ERR_UNKNOWN_COMMAND;
4223 client->last_rc = rc = gpg_error (file_modified (client, cmd));
4224 if (!rc)
4225 update_client_state (client, CLIENT_STATE_COMMAND);
4227 return rc;
4231 * This is called after every Assuan command.
4233 static void
4234 command_finalize (assuan_context_t ctx, gpg_error_t rc)
4236 struct client_s *client = assuan_get_pointer (ctx);
4238 if (!(client->flags & FLAG_LOCK_CMD))
4239 unlock_file_mutex (client, 0);
4241 log_write1 (_("command completed: rc=%u"), rc ? rc : client->last_rc);
4242 client->last_rc = gpg_error (GPG_ERR_UNKNOWN_COMMAND);
4243 #ifdef WITH_GNUTLS
4244 client->thd->buffer_timeout = client->thd->last_buffer_size = 0;
4245 #endif
4246 update_client_state (client, CLIENT_STATE_IDLE);
4249 static gpg_error_t
4250 help_command (assuan_context_t ctx, char *line)
4252 gpg_error_t rc;
4253 int i;
4255 if (!line || !*line)
4257 char *tmp;
4258 char *help = str_dup (_("Usage: HELP [<COMMAND>]\n"
4259 "For commands that take an element path as an argument, each element is "
4260 "separated with an ASCII @key{TAB} character (ASCII 0x09)."
4261 "\n" "COMMANDS:"));
4263 for (i = 0; command_table[i]; i++)
4265 if (!command_table[i]->help)
4266 continue;
4268 tmp = str_asprintf ("%s %s", help, command_table[i]->name);
4269 xfree (help);
4270 help = tmp;
4273 tmp = strip_texi_and_wrap (help);
4274 xfree (help);
4275 pthread_cleanup_push (xfree, tmp);
4276 rc = xfer_data (ctx, tmp, strlen (tmp));
4277 pthread_cleanup_pop (1);
4278 return send_error (ctx, rc);
4281 for (i = 0; command_table[i]; i++)
4283 if (!strcasecmp (line, command_table[i]->name))
4285 char *help, *tmp;
4287 if (!command_table[i]->help)
4288 break;
4290 help = strip_texi_and_wrap (command_table[i]->help);
4291 tmp = str_asprintf (_("Usage: %s"), help);
4292 xfree (help);
4293 pthread_cleanup_push (xfree, tmp);
4294 rc = xfer_data (ctx, tmp, strlen (tmp));
4295 pthread_cleanup_pop (1);
4296 return send_error (ctx, rc);
4300 return send_error (ctx, GPG_ERR_INV_NAME);
4303 static void
4304 new_command (const char *name, int ignore, int unlock,
4305 gpg_error_t (*handler) (assuan_context_t, char *),
4306 const char *help)
4308 int i = 0;
4310 if (command_table)
4311 for (i = 0; command_table[i]; i++);
4313 command_table =
4314 xrealloc (command_table, (i + 2) * sizeof (struct command_table_s *));
4315 command_table[i] = xcalloc (1, sizeof (struct command_table_s));
4316 command_table[i]->name = name;
4317 command_table[i]->handler = handler;
4318 command_table[i]->ignore_startup = ignore;
4319 command_table[i]->unlock = unlock;
4320 command_table[i++]->help = help;
4321 command_table[i] = NULL;
4324 void
4325 deinit_commands ()
4327 int i;
4329 for (i = 0; command_table[i]; i++)
4330 xfree (command_table[i]);
4332 xfree (command_table);
4335 static int
4336 sort_commands (const void *arg1, const void *arg2)
4338 struct command_table_s *const *a = arg1;
4339 struct command_table_s *const *b = arg2;
4341 if (!*a || !*b)
4342 return 0;
4343 else if (*a && !*b)
4344 return 1;
4345 else if (!*a && *b)
4346 return -1;
4348 return strcmp ((*a)->name, (*b)->name);
4351 static gpg_error_t
4352 passwd_command (assuan_context_t ctx, char *line)
4354 struct client_s *client = assuan_get_pointer (ctx);
4355 gpg_error_t rc;
4356 struct argv_s *args[] = {
4357 &(struct argv_s) {"reset", OPTION_TYPE_NOARG, parse_opt_reset},
4358 &(struct argv_s) {"s2k-count", OPTION_TYPE_ARG, parse_opt_s2k_count},
4359 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG, parse_opt_no_passphrase},
4360 NULL
4363 rc = peer_is_invoker (client);
4364 if (rc == GPG_ERR_EACCES)
4365 return send_error (ctx, rc);
4367 if (client->flags & FLAG_NEW)
4368 return send_error (ctx, GPG_ERR_INV_STATE);
4370 client->crypto->save.s2k_count =
4371 config_get_ulong (client->filename, "s2k_count");
4372 rc = parse_options (&line, args, client);
4373 if (rc)
4374 return send_error (ctx, rc);
4376 if (!rc && client->opts & OPT_RESET)
4378 rc = cache_clear (client->md5file);
4379 if (!rc)
4380 send_status_all (STATUS_CACHE, NULL);
4383 if (!rc)
4385 if (!IS_PKI (client->crypto))
4387 struct crypto_s *crypto;
4389 xfree (client->crypto->filename);
4390 client->crypto->filename = str_dup (client->filename);
4391 rc = change_passwd (ctx, client->filename,
4392 client->flags & FLAG_NO_PINENTRY, &crypto,
4393 (client->opts & OPT_NO_PASSPHRASE));
4394 if (!rc)
4396 cleanup_crypto (&client->crypto);
4397 client->crypto = crypto;
4398 update_checksum (client);
4399 cleanup_crypto_stage1 (client->crypto);
4402 #ifdef WITH_AGENT
4403 else
4405 if (client->crypto->save.s2k_count)
4406 rc = send_to_agent (client->crypto->agent, NULL, NULL,
4407 "OPTION s2k-count=%lu",
4408 client->crypto->save.s2k_count);
4410 if (!rc)
4411 rc = agent_passwd (client->crypto);
4413 (void) kill_scd (client->crypto->agent);
4415 #endif
4418 return send_error (ctx, rc);
4421 static gpg_error_t
4422 parse_keygrip_opt_sign (void *data, void *value)
4424 struct client_s *client = data;
4426 (void) value;
4427 client->opts |= OPT_SIGN;
4428 return 0;
4431 static gpg_error_t
4432 keygrip_command (assuan_context_t ctx, char *line)
4434 struct client_s *client = assuan_get_pointer (ctx);
4435 gpg_error_t rc;
4436 struct crypto_s *crypto = NULL;
4437 struct argv_s *args[] = {
4438 &(struct argv_s) {"sign", OPTION_TYPE_NOARG, parse_keygrip_opt_sign},
4439 NULL
4442 if (!line || !*line)
4443 return send_error (ctx, GPG_ERR_SYNTAX);
4445 rc = parse_options (&line, args, client);
4446 if (rc)
4447 return send_error (ctx, rc);
4449 if (!valid_filename (line))
4450 return send_error (ctx, GPG_ERR_INV_VALUE);
4452 rc = init_client_crypto (&crypto);
4453 if (rc)
4454 return send_error (ctx, rc);
4456 rc = read_data_file (line, crypto);
4457 if (!rc)
4459 char *hexgrip = NULL;
4461 if (!IS_PKI (crypto))
4463 cleanup_crypto (&crypto);
4464 return send_error (ctx, GPG_ERR_NOT_SUPPORTED);
4467 if (client->opts & OPT_SIGN)
4469 if (valid_keygrip (crypto->sign_grip, sizeof (crypto->sign_grip)))
4470 hexgrip = bin2hex (crypto->sign_grip, sizeof (crypto->sign_grip));
4473 if (!hexgrip)
4474 hexgrip = bin2hex (crypto->grip, sizeof (crypto->grip));
4476 if (!hexgrip)
4477 rc = GPG_ERR_ENOMEM;
4478 else
4479 rc = xfer_data (ctx, hexgrip, strlen (hexgrip));
4481 xfree (hexgrip);
4484 UPDATE_AGENT_CTX (client, crypto);
4485 cleanup_crypto (&crypto);
4486 return send_error (ctx, rc);
4489 static gpg_error_t
4490 parse_opt_data (void *data, void *value)
4492 struct client_s *client = data;
4494 (void) value;
4495 client->opts |= OPT_DATA;
4496 return 0;
4499 static gpg_error_t
4500 send_client_list (assuan_context_t ctx)
4502 struct client_s *client = assuan_get_pointer (ctx);
4503 gpg_error_t rc = 0;
4504 char buf[ASSUAN_LINELENGTH];
4506 if (client->opts & OPT_VERBOSE)
4508 unsigned i, t;
4509 char **list = NULL;
4510 char *line;
4512 MUTEX_LOCK (&cn_mutex);
4513 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
4514 t = slist_length (cn_thread_list);
4516 for (i = 0; i < t; i++)
4518 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
4519 char *tmp;
4521 if (thd->state == CLIENT_STATE_UNKNOWN)
4522 continue;
4524 tmp = build_client_info_line (thd, 0);
4525 if (tmp)
4527 char **l = strv_cat (list, tmp);
4528 if (!l)
4529 rc = GPG_ERR_ENOMEM;
4530 else
4531 list = l;
4533 else
4534 rc = GPG_ERR_ENOMEM;
4536 if (rc)
4538 strv_free (list);
4539 break;
4543 pthread_cleanup_pop (1);
4544 if (rc)
4545 return rc;
4547 line = strv_join ("\n", list);
4548 strv_free (list);
4549 pthread_cleanup_push (xfree, line);
4550 rc = xfer_data (ctx, line, strlen (line));
4551 pthread_cleanup_pop (1);
4552 return rc;
4555 if (client->opts & OPT_DATA)
4557 MUTEX_LOCK (&cn_mutex);
4558 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
4559 snprintf (buf, sizeof (buf), "%i", slist_length (cn_thread_list));
4560 pthread_cleanup_pop (1);
4561 rc = xfer_data (ctx, buf, strlen (buf));
4563 else
4564 rc = send_status (ctx, STATUS_CLIENTS, NULL);
4566 return rc;
4569 static gpg_error_t
4570 getinfo_command (assuan_context_t ctx, char *line)
4572 struct client_s *client = assuan_get_pointer (ctx);
4573 gpg_error_t rc;
4574 char buf[ASSUAN_LINELENGTH];
4575 struct argv_s *args[] = {
4576 &(struct argv_s) {"data", OPTION_TYPE_NOARG, parse_opt_data},
4577 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_opt_verbose},
4578 NULL
4581 rc = parse_options (&line, args, client);
4582 if (rc)
4583 return send_error (ctx, rc);
4585 if (!strcasecmp (line, "clients"))
4587 rc = send_client_list (ctx);
4589 else if (!strcasecmp (line, "cache"))
4591 if (client->opts & OPT_DATA)
4593 snprintf (buf, sizeof (buf), "%u", cache_file_count ());
4594 rc = xfer_data (ctx, buf, strlen (buf));
4596 else
4597 rc = send_status (ctx, STATUS_CACHE, NULL);
4599 else if (!strcasecmp (line, "pid"))
4601 char buf[32];
4602 pid_t pid = getpid ();
4604 snprintf (buf, sizeof (buf), "%i", pid);
4605 rc = xfer_data (ctx, buf, strlen (buf));
4607 else if (!strcasecmp (line, "version"))
4609 char *buf = str_asprintf ("0x%06x %s%s", VERSION_HEX,
4610 #ifdef WITH_GNUTLS
4611 "GNUTLS "
4612 #endif
4613 #ifdef WITH_QUALITY
4614 "QUALITY "
4615 #endif
4616 "", use_agent ? "AGENT" : "");
4617 rc = xfer_data (ctx, buf, strlen (buf));
4618 xfree (buf);
4620 else if (!strcasecmp (line, "last_error"))
4622 if (client->last_error)
4623 rc = xfer_data (ctx, client->last_error, strlen (client->last_error));
4624 else
4625 rc = GPG_ERR_NO_DATA;
4627 else if (!strcasecmp (line, "user"))
4629 char *user = NULL;
4631 #ifdef WITH_GNUTLS
4632 if (client->thd->remote)
4633 user = str_asprintf ("#%s", client->thd->tls->fp);
4634 else
4635 user = get_username (client->thd->peer->uid);
4636 #else
4637 user = get_username (client->thd->peer->uid);
4638 #endif
4639 if (user)
4641 pthread_cleanup_push (xfree, user);
4642 rc = xfer_data (ctx, user, strlen (user));
4643 pthread_cleanup_pop (1);
4645 else
4646 rc = GPG_ERR_NO_DATA;
4648 else
4649 rc = gpg_error (GPG_ERR_SYNTAX);
4651 return send_error (ctx, rc);
4654 #ifdef WITH_AGENT
4655 static gpg_error_t
4656 send_data_cb (void *user, const void *buf, size_t len)
4658 assuan_context_t ctx = user;
4660 return assuan_send_data (ctx, buf, len);
4663 static gpg_error_t
4664 send_status_cb (void *user, const char *line)
4666 assuan_context_t ctx = user;
4667 char keyword[200], *k;
4668 const char *p;
4670 for (p = line, k = keyword; *p; p++)
4672 if (isspace (*p))
4673 break;
4675 *k++ = *p;
4678 *k = 0;
4679 if (*p == '#')
4680 p++;
4682 while (isspace (*p))
4683 p++;
4685 return assuan_write_status (ctx, keyword, *p ? p : NULL);
4687 #endif
4689 static gpg_error_t
4690 kill_command (assuan_context_t ctx, char *line)
4692 #ifdef HAVE_PTHREAD_CANCEL
4693 struct client_s *client = assuan_get_pointer (ctx);
4694 gpg_error_t rc;
4695 unsigned i, t;
4697 if (!line || !*line)
4698 return send_error (ctx, GPG_ERR_SYNTAX);
4700 MUTEX_LOCK (&cn_mutex);
4701 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
4702 t = slist_length (cn_thread_list);
4703 rc = GPG_ERR_ESRCH;
4705 for (i = 0; i < t; i++)
4707 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
4708 char *tmp = str_asprintf ("%p", thd->tid);
4710 if (strcmp (line, tmp))
4712 xfree (tmp);
4713 continue;
4716 xfree (tmp);
4717 rc = peer_is_invoker (client);
4718 if (!rc)
4720 rc = pthread_cancel (thd->tid);
4721 break;
4724 rc = GPG_ERR_EACCES;
4725 if (config_get_boolean ("global", "strict_kill"))
4726 break;
4728 #ifdef WITH_GNUTLS
4729 if (client->thd->remote && thd->remote)
4731 if (!strcmp (client->thd->tls->fp, thd->tls->fp))
4733 rc = pthread_cancel (thd->tid);
4734 break;
4737 else if (!client->thd->remote && !thd->remote)
4738 #endif
4740 if (client->thd->peer->uid == thd->peer->uid)
4741 rc = pthread_cancel (thd->tid);
4743 break;
4746 pthread_cleanup_pop (1);
4747 return send_error (ctx, rc);
4748 #else
4749 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
4750 #endif
4753 static gpg_error_t
4754 agent_command (assuan_context_t ctx, char *line)
4756 gpg_error_t rc = 0;
4758 if (!use_agent)
4759 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
4761 #ifdef WITH_AGENT
4762 struct client_s *client = assuan_get_pointer (ctx);
4764 if (!line || !*line)
4765 return send_error (ctx, GPG_ERR_SYNTAX);
4767 assuan_set_flag (client->crypto->agent->ctx, ASSUAN_CONVEY_COMMENTS, 1);
4768 rc = assuan_transact (client->crypto->agent->ctx, line, send_data_cb,
4769 client->ctx, agent_loopback_cb, client->crypto,
4770 send_status_cb, client->ctx);
4771 if (gpg_err_code (rc) == GPG_ERR_ASS_CANCELED)
4773 char *line;
4774 size_t len;
4776 rc = assuan_write_line (client->crypto->agent->ctx, "CAN");
4777 if (!rc)
4779 rc = assuan_read_line (client->crypto->agent->ctx, &line, &len);
4780 if (!rc)
4781 rc = gpg_error (GPG_ERR_ASS_CANCELED);
4785 assuan_set_flag (client->crypto->agent->ctx, ASSUAN_CONVEY_COMMENTS, 0);
4786 #endif
4787 return send_error (ctx, rc);
4790 void
4791 init_commands ()
4793 /* !BEGIN-HELP-TEXT!
4795 * This comment is used as a marker to generate the offline documentation
4796 * found in doc/pwmd.info. The indentation needs to be kept for the awk
4797 * script to determine where commands begin and end.
4799 new_command("HELP", 1, 1, help_command, _(
4800 "HELP [<COMMAND>]\n"
4801 "Show available commands or command specific help text."
4804 new_command("AGENT", 1, 1, agent_command, _(
4805 "AGENT <command>\n"
4806 "Send a @command{gpg-agent} protocol @var{command} directly to the "
4807 "@command{gpg-agent}."
4810 new_command("KILL", 1, 0, kill_command, _(
4811 "KILL <thread_id>\n"
4812 "Terminates the client identified by @var{thread_id} and releases any file "
4813 "lock or other resources it has held. See @code{GETINFO} (@pxref{GETINFO}) "
4814 "for details about listing connected clients. The @code{invoking_user} "
4815 "(@pxref{Configuration}) may kill any client while others may only kill "
4816 "clients of the same @code{UID} or @abbr{TLS} fingerprint.\n"
4819 new_command("GETINFO", 1, 1, getinfo_command, _(
4820 "GETINFO [--data] [--verbose] CACHE | CLIENTS | PID | USER | LAST_ERROR | VERSION\n"
4821 "Get server and other information: @var{CACHE} returns the number of cached "
4822 "documents via a status message. @var{CLIENTS} returns the number of "
4823 "connected clients via a status message or a list of connected clients when "
4824 "the @option{--verbose} parameter is used. The list contains space delimited "
4825 "fields: the thread ID, client name, opened file (@code{/} if none opened), "
4826 "file lock status, whether the current client is self, client state, "
4827 "user ID or TLS fingerprint of the connected client and username if the "
4828 "client is a local one. "
4829 "Client state @code{0} is an unknown client state, @code{1} indicates the "
4830 "client has connected but hasn't completed initializing, @code{2} indicates "
4831 "that the client is idle, @code{3} means the "
4832 "client is in a command and @code{4} means the client is disconnecting. This "
4833 "line is always returned with a data response. @var{PID} returns the process "
4834 "ID number of the server via a data response. @var{VERSION} returns the server "
4835 "version number and compile-time features with a data response with each "
4836 "being space delimited. @var{LAST_ERROR} returns a detailed description of "
4837 "the last failed command when available. @var{USER} returns the username or "
4838 "@abbr{TLS} hash of the connected client. @xref{Status Messages}. "
4839 "\n"
4840 "When the @option{--data} option is specified then the result will be sent "
4841 "via a data response rather than a status message."
4844 new_command("PASSWD", 0, 0, passwd_command, _(
4845 "PASSWD [--reset] [--s2k-count=N] [--no-passphrase]\n"
4846 "Changes the passphrase of the secret key required to open the current "
4847 "file or the passphrase of a symmetrically encrypted data file. When the "
4848 "@option{--reset} option is passed then the cache entry for the current "
4849 "file will be reset and the passphrase, if any, will be required during the "
4850 "next @code{OPEN} (@pxref{OPEN})."
4851 "\n"
4852 "The @option{--s2k-count} option sets or changes (@pxref{SAVE}) the number "
4853 "of hash iterations for a passphrase and must be either @code{0} to use "
4854 "the calibrated count of the machine (the default), or a value greater than "
4855 "or equal to @code{65536}. This option has no effect for symmetrically "
4856 "encrypted data files."
4857 "\n"
4858 "The @option{--no-passphrase} option will prevent requiring a passphrase for "
4859 "the data file, although a passphrase may be required when changing it."
4860 "\n"
4861 "This command is not available for non-invoking clients "
4862 "(@pxref{Access Control})."
4865 new_command("KEYGRIP", 1, 1, keygrip_command, _(
4866 "KEYGRIP [--sign] <filename>\n"
4867 "Returns the hex encoded keygrip of the specified @var{filename} with a "
4868 "data response."
4869 "\n"
4870 "When the @option{--sign} option is specified then the key used for signing "
4871 "of the specified @var{filename} will be returned."
4872 "\n"
4873 "For symmetrically encrypted data files this command returns the error "
4874 "GPG_ERR_NOT_SUPPORTED."
4877 new_command("OPEN", 1, 1, open_command, _(
4878 "OPEN [--lock] <filename> [<passphrase>]\n"
4879 "Opens @var{filename} using @var{passphrase}. When the filename is not "
4880 "found on the file-system then a new document will be created. If the file "
4881 "is found, it is looked for in the file cache. If cached and no "
4882 "@var{passphrase} was specified then the cached document is opened. When not "
4883 "cached, @cite{pinentry(1)} will be used to retrieve the passphrase to use "
4884 "for decryption unless @option{disable-pinentry} (@pxref{OPTION}) was "
4885 "specified."
4886 "\n"
4887 "When the @option{--lock} option is passed then the file mutex will be "
4888 "locked as if the @code{LOCK} command (@pxref{LOCK}) had been sent after the "
4889 "file has been opened."
4892 new_command("SAVE", 0, 0, save_command, _(
4893 "SAVE [--no-passphrase] [--reset] [--ask] [--no-agent] [--s2k-count=N] [--cipher=<algo>] [--cipher-iterations=N] [--inquire-keyparam] [--keygrip=hexstring] [--sign-keygrip=hexstring]\n"
4894 "Writes the @abbr{XML} document to disk. The file written to is the file that "
4895 "was opened using the @code{OPEN} command (@pxref{OPEN}). If the file is a "
4896 "new one or the option @option{--inquire-keyparam} was passed, then a new "
4897 "keypair will be generated and a pinentry will be used to prompt for the "
4898 "passphrase to encrypt with unless the @option{--no-passphrase} option was "
4899 "passed in which case the data file will not be passphrase protected. "
4900 "\n"
4901 "The @option{--no-agent} option disables use of @command{gpg-agent} for "
4902 "passphrase retrieval and caching of new files when @command{gpg-agent} "
4903 "use is enabled. The datafile will be symmetrically encrypted and will not "
4904 "use or generate any keypair."
4905 "\n"
4906 "The @option{--reset} option will clear the cache entry for the current file "
4907 "and require a passphrase, if needed, before saving."
4908 "\n"
4909 "The @option{--ask} option will prompt for the passphrase of the current file, "
4910 "if needed, before saving. This differs from the @option{--reset} option by "
4911 "keeping the cache entry in case of an invalid passphrase or some other failure "
4912 "which may otherwise cause a denial of service for other clients."
4913 "\n"
4914 "The @option{--cipher} option can be used to encrypt the @abbr{XML} data to "
4915 "an alternate cipher. The default is @code{aes256}. See the Configuration "
4916 "(@pxref{Configuration}) for available ciphers."
4917 "\n"
4918 "The @option{--cipher-iterations} option specifies the number of times to "
4919 "hash the passphrase before encrypting the XML data. The default is "
4920 "@code{5000000}. This option is an alias for @option{--s2k-count} since "
4921 "version @var{3.0.15} of @command{pwmd}."
4922 "\n"
4923 "The @option{--inquire-keyparam} option will send a server @emph{INQUIRE} to "
4924 "the client to obtain the key paramaters to use when generating a new "
4925 "keypair. The inquired data is expected to be an S-expression. If not "
4926 "specified then an @samp{RSA} key of @samp{2048} bits will be generated "
4927 "unless otherwise set in the configuration file (@pxref{Configuration}). Note "
4928 "that when this option is specified a new keypair will be generated "
4929 "reguardless if the file is a new one and that if the data file is protected "
4930 "the passphrase to open it will be required before generating the new "
4931 "keypair. This option is not available for non-invoking clients "
4932 "(@pxref{Access Control})."
4933 "\n"
4934 "You can encrypt the data file to a public key other than the one that it "
4935 "was originally encrypted with by passing the @option{--keygrip} option with "
4936 "the hex encoded keygrip of the public key as its argument. The keygrip may "
4937 "be of any key that @command{gpg-agent} knows about. The "
4938 "@option{--sign-keygrip} option may also be used to sign with an alternate "
4939 "secret key. Use the @code{KEYGRIP} (@pxref{KEYGRIP}) command to obtain the "
4940 "keygrip of an existing data file. This option may be needed when using a "
4941 "smartcard. This option has no effect with symmetrically encrypted data "
4942 "files. These options are not available for non-invoking clients "
4943 "(@pxref{Access Control})."
4944 "\n"
4945 "The @option{--s2k-count} option sets number of hash iterations for a "
4946 "passphrase. A value less-than @code{65536} will use the machine calibrated "
4947 "value and is the default when using @command{gpg-agent}. This setting only "
4948 "affects new files when using @command{gpg-agent}. To change the setting use "
4949 "the @code{PASSWD} command (@pxref{PASSWD}). This option is an alias for "
4950 "option @option{--cipher-iterations} when not using @command{gpg-agent}."
4953 new_command("ISCACHED", 1, 0, iscached_command, _(
4954 "ISCACHED [--lock] <filename>\n"
4955 "An @emph{OK} response is returned if the specified @var{filename} is found "
4956 "in the file cache. If not found in the cache but exists on the filesystem "
4957 "then @var{GPG_ERR_NO_DATA} is returned. Otherwise a filesystem error is "
4958 "returned."
4959 "\n"
4960 "The @option{lock} option will lock the file mutex of @var{filename} when the "
4961 "file exists; it does not need to be opened nor cached. The lock will be "
4962 "released when the client exits or sends the @code{UNLOCK} (@pxref{UNLOCK}) "
4963 "command."
4966 new_command("CLEARCACHE", 1, 1, clearcache_command, _(
4967 "CLEARCACHE [<filename>]\n"
4968 "Clears a file cache entry for all or the specified @var{filename}."
4971 new_command("CACHETIMEOUT", 1, 1, cachetimeout_command, _(
4972 "CACHETIMEOUT <filename> <seconds>\n"
4973 "The time in @var{seconds} until @var{filename} will be removed from the "
4974 "cache. @code{-1} will keep the cache entry forever, @code{0} will require "
4975 "the passphrase for each @code{OPEN} or @code{SAVE} command (@pxref{OPEN}, "
4976 "@pxref{SAVE}). @xref{Configuration}, and the @code{cache_timeout} "
4977 "parameter."
4980 new_command("LIST", 0, 1, list_command, _(
4981 "LIST [--inquire] [--no-recurse] [--verbose] [--with-target] [--all] [[!]element[<TAB>[!]child[..]]]\n"
4982 "If no element path is given then a newline separated list of root elements "
4983 "is returned with a data response. If given, then all reachable elements "
4984 "of the specified element path are returned unless the @option{--no-recurse} "
4985 "option is specified. If specified, only the child elements of the element "
4986 "path are returned without recursing into grandchildren. Each resulting "
4987 "element is prefixed with the literal @code{!} character when the element "
4988 "contains no @code{target} attribute. @xref{Target Attribute}, for details."
4989 "\n"
4990 "When the @option{--verbose} option is passed then each element path "
4991 "returned will have zero or more flags appened to it. These flags are "
4992 "delimited from the element path by a single space character. A flag itself "
4993 "is a single character. Flag @code{P} indicates that access to the element "
4994 "is denied. Flag @code{+} indicates that there are child nodes of "
4995 "the current element path. Flag @code{E} indicates that an element of an "
4996 "element path contained in a @var{target} attribute could not be found. Flag "
4997 "@code{O} indicates that a @var{target} attribute recursion limit was reached "
4998 "(@pxref{Configuration}). Flag @code{T} will append the resolved element path "
4999 "of the @var{target} attribute contained in the current element (see below)."
5000 "\n"
5001 "The @option{--with-target} option implies @option{--verbose} and will append "
5002 "an additional flag @code{T} followed by a single space then an element path. "
5003 "The appended element path is the resolved path (@pxref{REALPATH}) of the "
5004 "current element when it contains a @var{target} attribute. When no "
5005 "@var{target} attribute is found then no flag will be appended."
5006 "\n"
5007 "The @option{--no-recurse} option limits the amount of data returned to only "
5008 "the listing of children of the specified element path and not any "
5009 "grandchildren."
5010 "\n"
5011 "The @option{--all} option lists the entire element tree for each root "
5012 "element. This option also implies option @option{--verbose}."
5013 "\n"
5014 "When the @option{--inquire} option is passed then all remaining non-option "
5015 "arguments are retrieved via a server @emph{INQUIRE}."
5018 new_command("REALPATH", 0, 1, realpath_command, _(
5019 "REALPATH [--inquire] [!]element[<TAB>[!]child[..]]\n"
5020 "Resolves all @code{target} attributes of the specified element path and "
5021 "returns the result with a data response. @xref{Target Attribute}, for details."
5022 "\n"
5023 "When the @option{--inquire} option is passed then all remaining non-option "
5024 "arguments are retrieved via a server @emph{INQUIRE}."
5027 new_command("STORE", 0, 1, store_command, _(
5028 "STORE [!]element[<TAB>[!]child[..]]<TAB>[content]\n"
5029 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
5030 "\n"
5031 "Creates a new element path or modifies the @var{content} of an existing "
5032 "element. If only a single element is specified then a new root element is "
5033 "created. Otherwise, elements are @key{TAB} delimited and the content will be "
5034 "set to the final @key{TAB} delimited element. If no @var{content} is "
5035 "specified after the final @key{TAB}, then the content of an existing "
5036 "element will be removed; or empty when creating a new element."
5037 "\n"
5038 "The only restriction of an element name is that it not contain whitespace "
5039 "or begin with the literal element character @code{!} unless specifying a "
5040 "literal element (@pxref{Target Attribute}). There is no whitespace between "
5041 "the @key{TAB} delimited elements. It is recommended that the content of an "
5042 "element be base64 encoded when it contains control or @key{TAB} characters "
5043 "to prevent @abbr{XML} parsing and @command{pwmd} syntax errors."
5046 new_command("RENAME", 0, 1, rename_command, _(
5047 "RENAME [--inquire] [!]element[<TAB>[!]child[..]] <value>\n"
5048 "Renames the specified @var{element} to the new @var{value}. If an element of "
5049 "the same name as the @var{value} already exists it will be overwritten."
5050 "\n"
5051 "When the @option{--inquire} option is passed then all remaining non-option "
5052 "arguments are retrieved via a server @emph{INQUIRE}."
5055 new_command("COPY", 0, 1, copy_command, _(
5056 "COPY [--inquire] [!]source[<TAB>[!]child[..]] [!]dest[<TAB>[!]child[..]]\n"
5057 "Copies the entire element tree starting from the child node of the source "
5058 "element, to the destination element path. If the destination element path "
5059 "does not exist then it will be created; otherwise it is overwritten."
5060 "\n"
5061 "Note that attributes from the source element are merged into the "
5062 "destination element when the destination element path exists. When an "
5063 "attribute of the same name exists in both the source and destination "
5064 "elements then the destination attribute will be updated to the source "
5065 "attribute value."
5066 "\n"
5067 "When the @option{--inquire} option is passed then all remaining non-option "
5068 "arguments are retrieved via a server @emph{INQUIRE}."
5071 new_command("MOVE", 0, 1, move_command, _(
5072 "MOVE [--inquire] [!]source[<TAB>[!]child[..]] [[!]dest[<TAB>[!]child[..]]]\n"
5073 "Moves the source element path to the destination element path. If the "
5074 "destination is not specified then it will be moved to the root node of the "
5075 "document. If the destination is specified and exists then it will be "
5076 "overwritten; otherwise non-existing elements of the destination element "
5077 "path will be created."
5078 "\n"
5079 "When the @option{--inquire} option is passed then all remaining non-option "
5080 "arguments are retrieved via a server @emph{INQUIRE}."
5083 new_command("DELETE", 0, 1, delete_command, _(
5084 "DELETE [--inquire] [!]element[<TAB>[!]child[..]]\n"
5085 "Removes the specified element path and all of its children. This may break "
5086 "an element with a @code{target} attribute (@pxref{Target Attribute}) that "
5087 "refers to this element or any of its children."
5088 "\n"
5089 "When the @option{--inquire} option is passed then all remaining non-option "
5090 "arguments are retrieved via a server @emph{INQUIRE}."
5093 new_command("GET", 0, 1, get_command, _(
5094 "GET [--inquire] [!]element[<TAB>[!]child[..]]\n"
5095 "Retrieves the content of the specified element. The content is returned "
5096 "with a data response."
5097 "\n"
5098 "When the @option{--inquire} option is passed then all remaining non-option "
5099 "arguments are retrieved via a server @emph{INQUIRE}."
5102 new_command("ATTR", 0, 1, attr_command, _(
5103 "ATTR [--inquire] SET|GET|DELETE|LIST [<attribute>] [!]element[<TAB>[!]child[..]] ..\n"
5104 "@table @asis\n"
5105 "@item ATTR SET attribute [!]element[<TAB>[!]child[..]] [value]\n"
5106 "\n"
5107 " Stores or updates an @var{attribute} name and optional @var{value} of an "
5108 "element. When no @var{value} is specified any existing value will be removed."
5109 "\n"
5110 "@item ATTR DELETE attribute [!]element[<TAB>[!]child[..]]\n"
5111 "\n"
5112 " Removes an @var{attribute} from an element."
5113 "\n"
5114 "@item ATTR LIST [!]element[<TAB>[!]child[..]]\n"
5115 "\n"
5116 " Retrieves a newline separated list of attributes names and values "
5117 "from the specified element. Each attribute name and value is space delimited."
5118 "\n"
5119 "@item ATTR GET attribute [!]element[<TAB>[!]child[..]]\n"
5120 "\n"
5121 " Retrieves the value of an @var{attribute} from an element."
5122 "@end table\n"
5123 "\n"
5124 "The @code{_name} attribute (case sensitive) cannot be removed nor modified. "
5125 "Use the @code{DELETE} (@pxref{DELETE}) or @code{RENAME} (@pxref{RENAME}) "
5126 "commands instead."
5127 "\n"
5128 "The @code{_mtime} attribute is updated each time an element is modified by "
5129 "either storing content, editing attributes or by deleting a child element. "
5130 "The @code{_ctime} attribute is created for each new element in an element "
5131 "path."
5132 "\n"
5133 "When the @option{--inquire} option is passed then all remaining non-option "
5134 "arguments are retrieved via a server @emph{INQUIRE}."
5135 "\n"
5136 "@xref{Target Attribute}, for details about this special attribute."
5139 new_command("XPATH", 0, 1, xpath_command, _(
5140 "XPATH [--inquire] <expression>[<TAB>[value]]\n"
5141 "Evaluates an XPath @var{expression}. If no @var{value} argument is "
5142 "specified it is assumed the expression is a request to return a result. "
5143 "Otherwise, the result is set to the @var{value} argument and the document is "
5144 "updated. If there is no @var{value} after the @key{TAB} character, the value "
5145 "is assumed to be empty and the document is updated. For example:"
5146 "@sp 1\n"
5147 "@example\n"
5148 "XPATH //element[@@_name='password']@key{TAB}\n"
5149 "@end example\n"
5150 "@sp 1"
5151 "would clear the content of all @code{password} elements in the data file "
5152 "while leaving off the trailing @key{TAB} would return all @code{password} "
5153 "elements in @abbr{XML} format."
5154 "\n"
5155 "When the @option{--inquire} option is passed then all remaining non-option "
5156 "arguments are retrieved via a server @emph{INQUIRE}."
5157 "\n"
5158 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
5159 "expression syntax."
5162 new_command("XPATHATTR", 0, 1, xpathattr_command, _(
5163 "XPATHATTR [--inquire] SET|DELETE <name> <expression>[<TAB>[<value>]]\n"
5164 "Like the @code{XPATH} command (@pxref{XPATH}) but operates on element "
5165 "attributes and does not return a result. For the @var{SET} operation the "
5166 "@var{value} is optional but the field is required. If not specified then "
5167 "the attribute value will be empty. For example:"
5168 "@sp 1"
5169 "@example\n"
5170 "XPATHATTR SET password //element[@@_name='password']@key{TAB}\n"
5171 "@end example\n"
5172 "@sp 1"
5173 "would create an @code{password} attribute for each @code{password} element "
5174 "found in the document. The attribute value will be empty but still exist."
5175 "\n"
5176 "When the @option{--inquire} option is passed then all remaining non-option "
5177 "arguments are retrieved via a server @emph{INQUIRE}."
5178 "\n"
5179 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
5180 "expression syntax."
5183 new_command("IMPORT", 0, 1, import_command, _(
5184 "IMPORT [--root=[!]element[<TAB>[!]child[..]]] <content>\n"
5185 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
5186 "\n"
5187 "Like the @code{STORE} command (@pxref{STORE}), but the @var{content} "
5188 "argument is raw @abbr{XML} data. The content is created as a child of "
5189 "the element path specified with the @option{--root} option or at the "
5190 "document root when not specified. Existing elements of the same name will "
5191 "be overwritten."
5192 "\n"
5193 "The content must begin with an @abbr{XML} element node. @xref{Introduction}, "
5194 "for details."
5197 new_command("DUMP", 0, 1, dump_command, _(
5198 "DUMP\n"
5199 "Shows the in memory @abbr{XML} document with indenting. @xref{XPATH}, for "
5200 "dumping a specific node."
5203 new_command("LOCK", 0, 0, lock_command, _(
5204 "LOCK\n"
5205 "Locks the mutex associated with the opened file. This prevents other clients "
5206 "from sending commands to the same opened file until the client "
5207 "that sent this command either disconnects or sends the @code{UNLOCK} "
5208 "command. @xref{UNLOCK}."
5211 new_command("UNLOCK", 1, 0, unlock_command, _(
5212 "UNLOCK\n"
5213 "Unlocks the file mutex which was locked with the @code{LOCK} command or "
5214 "a commands' @option{--lock} option (@pxref{LOCK}, @pxref{OPEN}, "
5215 "@pxref{ISCACHED})."
5218 new_command("GETCONFIG", 1, 1, getconfig_command, _(
5219 "GETCONFIG [filename] <parameter>\n"
5220 "Returns the value of a @command{pwmd} configuration @var{parameter} with a "
5221 "data response. If no file has been opened then the value for @var{filename} "
5222 "or the default from the @samp{global} section will be returned. If a file "
5223 "has been opened and no @var{filename} is specified, a value previously "
5224 "set with the @code{OPTION} command (@pxref{OPTION}) will be returned."
5227 new_command("OPTION", 1, 1, option_command, _(
5228 "OPTION <NAME>=<VALUE>\n"
5229 "Sets a client option @var{name} to @var{value}. The value for an option is "
5230 "kept for the duration of the connection."
5231 "\n"
5232 "@table @asis\n"
5233 "@item DISABLE-PINENTRY\n"
5234 "Disable use of @command{pinentry} for passphrase retrieval. When set, a "
5235 "server inquire is sent to the client to obtain the passphrase. This option "
5236 "may be set as needed before the @code{OPEN} (@pxref{OPEN}), @code{PASSWD} "
5237 "(@pxref{PASSWD}) and @code{SAVE} (@pxref{SAVE}) commands."
5238 "\n"
5239 "@item PINENTRY-TIMEOUT\n"
5240 "Sets the number of seconds before a pinentry prompt will return an error "
5241 "while waiting for user input."
5242 "\n"
5243 "@item TTYNAME\n"
5244 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
5245 "\n"
5246 "@item TTYTYPE\n"
5247 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
5248 "\n"
5249 "@item DISPLAY\n"
5250 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
5251 "\n"
5252 "@item PINENTRY-DESC\n"
5253 "Sets the description string of the @command{gpg-agent} and @command{pinentry} dialog."
5254 "\n"
5255 "@item PINENTRY-TITLE\n"
5256 "Sets the title string of the @command{gpg-agent} and @command{pinentry} dialog."
5257 "\n"
5258 "@item PINENTRY-PROMPT\n"
5259 "Sets the prompt string of the @command{gpg-agent} and @command{pinentry} dialog."
5260 "\n"
5261 "@item LC-CTYPE\n"
5262 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
5263 "\n"
5264 "@item LC-MESSAGES\n"
5265 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
5266 "\n"
5267 "@item NAME\n"
5268 "Associates the thread ID of the connection with the specified textual "
5269 "representation. Useful for debugging log messages. May not contain whitespace."
5270 "\n"
5271 "@item LOCK-TIMEOUT\n"
5272 "When not @code{0}, the duration in tenths of a second to wait for the file "
5273 "mutex which has been locked by another thread to be released before returning "
5274 "an error. When @code{-1}, then an error will be returned immediately."
5275 "\n"
5276 "@item LOG-LEVEL\n"
5277 "An integer specifiying the logging level."
5278 "@end table\n"
5281 new_command("LS", 1, 1, ls_command, _(
5282 "LS\n"
5283 "Lists the available data files stored in the data directory "
5284 "(@file{~/.pwmd/data}). The result is a newline separated list of filenames."
5287 new_command("RESET", 1, 1, NULL, _(
5288 "RESET\n"
5289 "Closes the currently opened file but keeps any previously set client options."
5292 new_command("NOP", 1, 1, NULL, _(
5293 "NOP\n"
5294 "Does nothing. Always returns successfully."
5297 /* !END-HELP-TEXT! */
5298 new_command ("CANCEL", 1, 1, NULL, NULL);
5299 new_command ("END", 1, 1, NULL, NULL);
5300 new_command ("BYE", 1, 1, NULL, NULL);
5302 int i;
5303 for (i = 0; command_table[i]; i++);
5304 qsort (command_table, i - 1, sizeof (struct command_table_s *),
5305 sort_commands);
5308 gpg_error_t
5309 register_commands (assuan_context_t ctx)
5311 int i = 0, rc;
5313 for (; command_table[i]; i++)
5315 if (!command_table[i]->handler)
5316 continue;
5318 rc = assuan_register_command (ctx, command_table[i]->name,
5319 command_table[i]->handler,
5320 command_table[i]->help);
5321 if (rc)
5322 return rc;
5325 rc = assuan_register_bye_notify (ctx, bye_notify);
5326 if (rc)
5327 return rc;
5329 rc = assuan_register_reset_notify (ctx, reset_notify);
5330 if (rc)
5331 return rc;
5333 rc = assuan_register_pre_cmd_notify (ctx, command_startup);
5334 if (rc)
5335 return rc;
5337 return assuan_register_post_cmd_notify (ctx, command_finalize);