Fix race condition in GETINFO.
[pwmd.git] / src / commands.c
blob09b0958804d9371c5b63b133d2ead0d1b84f84c0
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 /* Flags needed to be retained for a client across commands. */
52 #define FLAG_NEW 0x0001
53 #define FLAG_HAS_LOCK 0x0002
54 #define FLAG_LOCK_CMD 0x0004
55 #define FLAG_NO_PINENTRY 0x0008
56 #define FLAG_OPEN 0x0010
57 #define FLAG_KEEP_LOCK 0x0020
59 /* These are command option flags. */
60 #define OPT_INQUIRE 0x0001
61 #define OPT_NO_PASSPHRASE 0x0002
62 #define OPT_RESET 0x0004
63 #define OPT_LIST_RECURSE 0x0008
64 #define OPT_VERBOSE 0x0010
65 #define OPT_LOCK 0x0020
66 #define OPT_LOCK_ON_OPEN 0x0040
67 #define OPT_SIGN 0x0080
68 #define OPT_LIST_ALL 0x0100
69 #define OPT_LIST_WITH_TARGET 0x0200
70 #define OPT_DATA 0x0400
71 #define OPT_NO_AGENT 0x0800
73 #ifdef WITH_AGENT
74 /* The GETCONFIG command, for example, may fail because pwmd lost the
75 * gpg-agent connection. Update the recovered agent ctx. */
76 #define UPDATE_AGENT_CTX(client, crypto) do { \
77 if (crypto && crypto->agent && crypto->agent->did_restart \
78 && client->crypto && client->crypto->agent \
79 && client->crypto->agent->ctx && \
80 crypto->agent->ctx != client->crypto->agent->ctx) \
81 { \
82 client->crypto->agent->ctx = crypto->agent->ctx; \
83 crypto->agent->ctx = NULL; \
84 } \
85 } while (0)
86 #else
87 #define UPDATE_AGENT_CTX(client, crypto)
88 #endif
90 struct command_table_s
92 const char *name;
93 gpg_error_t (*handler) (assuan_context_t, char *line);
94 const char *help;
95 int ignore_startup;
96 int unlock; // unlock the file mutex after validating the checksum
99 static struct command_table_s **command_table;
101 static gpg_error_t do_lock (struct client_s *client, int add);
102 static gpg_error_t validate_checksum (struct client_s *,
103 struct cache_data_s *);
104 static gpg_error_t update_checksum (struct client_s *client);
106 /* When 'status' is true the 'self' field of the status line will be false
107 * because we never send the STATE status message to the same client that
108 * initiated it. */
109 static char *
110 build_client_info_line (struct client_thread_s *thd, int status)
112 MUTEX_LOCK (&cn_mutex);
113 int with_state = config_get_boolean ("global", "send_state");
114 char *uid = str_asprintf("%u", thd->peer->uid);
115 char *line = str_asprintf ("%p %s %s %s %u %u %u %s%s",
116 thd->tid,
117 thd->name ? thd->name : "-",
118 thd->cl && thd->cl->filename
119 ? thd->cl->filename : "/",
120 #ifdef WITH_GNUTLS
121 thd->remote ? thd->peeraddr : "-",
122 #else
123 "-",
124 #endif
125 thd->cl && thd->cl->flags & FLAG_HAS_LOCK ? 1 : 0,
126 !status && pthread_equal (pthread_self (), thd->tid) ? 1 : 0,
127 with_state ? thd->state : CLIENT_STATE_UNKNOWN,
128 #ifdef WITH_GNUTLS
129 thd->remote ? "#" : "",
130 thd->remote ? thd->tls->fp : uid
131 #else
132 "", uid
133 #endif
136 xfree (uid);
137 MUTEX_UNLOCK (&cn_mutex);
138 return line;
141 void
142 update_client_state (struct client_s *client, unsigned s)
144 client->thd->state = s;
145 int n = config_get_boolean ("global", "send_state");
147 if (n && client->thd->state != CLIENT_STATE_UNKNOWN)
149 char *line = build_client_info_line (client->thd, 1);
151 if (line)
152 send_status_all_not_self (n == 2, STATUS_STATE, "%s", line);
156 static gpg_error_t
157 unlock_file_mutex (struct client_s *client, int remove)
159 gpg_error_t rc = 0;
161 // OPEN: keep the lock for the same file being reopened.
162 if (client->flags & FLAG_KEEP_LOCK && client->flags & FLAG_HAS_LOCK)
163 return 0;
165 if (!(client->flags & FLAG_HAS_LOCK))
166 return GPG_ERR_NOT_LOCKED;
168 rc = cache_unlock_mutex (client->md5file, remove);
169 if (rc)
170 rc = GPG_ERR_INV_STATE;
171 else
172 client->flags &= ~(FLAG_HAS_LOCK | FLAG_LOCK_CMD);
174 return rc;
177 static gpg_error_t
178 lock_file_mutex (struct client_s *client, int add)
180 gpg_error_t rc = 0;
181 int timeout = config_get_integer (client->filename, "cache_timeout");
183 if (client->flags & FLAG_HAS_LOCK)
184 return 0;
186 rc = cache_lock_mutex (client->ctx, client->md5file,
187 client->lock_timeout, add, timeout);
188 if (!rc)
189 client->flags |= FLAG_HAS_LOCK;
191 return rc;
194 static gpg_error_t
195 file_modified (struct client_s *client, struct command_table_s *cmd)
197 gpg_error_t rc = 0;
199 if (!(client->flags & FLAG_OPEN))
200 return GPG_ERR_INV_STATE;
202 rc = lock_file_mutex (client, 0);
203 if (!rc || rc == GPG_ERR_NO_DATA)
205 rc = validate_checksum (client, NULL);
206 if (gpg_err_code (rc) == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
207 rc = 0;
208 else if (rc)
209 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
212 if ((cmd->unlock && !(client->flags & FLAG_HAS_LOCK)) || rc)
213 unlock_file_mutex (client, 0);
215 return rc;
218 static gpg_error_t
219 parse_xml (assuan_context_t ctx, int new)
221 struct client_s *client = assuan_get_pointer (ctx);
222 int cached = client->doc != NULL;
223 gpg_error_t rc = 0;
225 if (new)
227 client->doc = new_document ();
228 if (client->doc)
230 xmlChar *result;
231 int len;
233 xmlDocDumpFormatMemory (client->doc, &result, &len, 0);
234 client->crypto->plaintext = result;
235 client->crypto->plaintext_len = len;
236 if (!client->crypto->plaintext)
238 xmlFreeDoc (client->doc);
239 client->doc = NULL;
243 else if (!cached)
244 rc = parse_doc ((char *) client->crypto->plaintext,
245 client->crypto->plaintext_len, (xmlDocPtr *)&client->doc);
247 return rc;
250 static void
251 free_client (struct client_s *client)
253 if (client->doc)
254 xmlFreeDoc (client->doc);
256 xfree (client->crc);
257 xfree (client->filename);
258 xfree (client->last_error);
260 if (client->crypto)
262 cleanup_crypto_stage2 (client->crypto);
263 if (client->crypto->pkey_sexp)
264 gcry_sexp_release (client->crypto->pkey_sexp);
266 if (client->crypto->sigpkey_sexp)
267 gcry_sexp_release (client->crypto->sigpkey_sexp);
269 client->crypto->pkey_sexp = NULL;
270 client->crypto->sigpkey_sexp = NULL;
271 memset (client->crypto->sign_grip, 0,
272 sizeof (client->crypto->sign_grip));
273 memset (client->crypto->grip, 0, sizeof(client->crypto->grip));
277 void
278 cleanup_client (struct client_s *client)
280 assuan_context_t ctx = client->ctx;
281 struct client_thread_s *thd = client->thd;
282 struct crypto_s *crypto = client->crypto;
283 long lock_timeout = client->lock_timeout;
284 int no_pinentry = (client->flags & FLAG_NO_PINENTRY);
285 struct pinentry_option_s pin_opts;
286 xmlErrorPtr xml_error = client->xml_error;
287 #ifdef WITH_AGENT
288 struct pinentry_option_s agent_pin_opts;
290 if (crypto && crypto->agent)
291 memcpy (&agent_pin_opts, &crypto->agent->pinentry_opts,
292 sizeof(struct pinentry_option_s));
293 #endif
295 memcpy (&pin_opts, &client->pinentry_opts, sizeof(struct pinentry_option_s));
296 unlock_file_mutex (client, client->flags & FLAG_NEW);
297 free_client (client);
298 memset (client, 0, sizeof (struct client_s));
299 client->xml_error = xml_error;
300 client->crypto = crypto;
301 client->ctx = ctx;
302 client->thd = thd;
303 client->lock_timeout = lock_timeout;
304 memcpy (&client->pinentry_opts, &pin_opts, sizeof(struct pinentry_option_s));
305 client->flags |= no_pinentry ? FLAG_NO_PINENTRY : 0;
306 #ifdef WITH_AGENT
307 if (crypto && crypto->agent)
308 memcpy (&crypto->agent->pinentry_opts, &agent_pin_opts,
309 sizeof(struct pinentry_option_s));
310 #endif
313 static gpg_error_t
314 open_finalize (assuan_context_t ctx, char *key, size_t keylen)
316 struct client_s *client = assuan_get_pointer (ctx);
317 gpg_error_t rc = 0;
318 struct cache_data_s *cdata = cache_get_data (client->md5file);
319 int cached = 0, keyarg = key ? 1 : 0;
320 size_t keysize;
321 unsigned char *salted_key = NULL;
322 int algo;
323 int pin_try = 1;
324 int pin_tries = 3;
325 char *pin_title = client->pinentry_opts.title;
327 client->crypto->filename = str_dup (client->filename);
328 if (cdata || client->flags & FLAG_NEW)
330 if (cdata && !(client->flags & FLAG_NEW))
332 rc = decrypt_cache (client->crypto, cdata->doc, cdata->doclen);
333 if (rc)
334 return rc;
337 cached = cdata != NULL;
338 goto done;
341 if (!key && !IS_PKI (client->crypto)
342 && !(client->crypto->hdr.flags & PWMD_FLAG_NO_PASSPHRASE))
344 if (client->flags & FLAG_NO_PINENTRY)
346 rc = inquire_passphrase (ctx, "PASSPHRASE", (unsigned char **)&key,
347 &keylen);
348 if (rc)
349 return rc;
351 else
353 client->pinentry_opts.timeout = config_get_integer (client->filename,
354 "pinentry_timeout");
355 pin_again:
356 rc = getpin_common (client->ctx, client->filename, PINENTRY_OPEN,
357 &key, &keylen);
358 if (rc)
359 return rc;
363 if (!IS_PKI (client->crypto))
365 if (client->crypto->hdr.flags & PWMD_FLAG_NO_PASSPHRASE)
367 keylen = 1;
368 key = gcry_malloc (keylen);
369 memset (key, 0, keylen);
372 algo = cipher_to_gcrypt (client->crypto->hdr.flags);
373 rc = hash_key (algo, client->crypto->hdr.salt,
374 sizeof(client->crypto->hdr.salt), key, keylen,
375 (void **)&salted_key, &keysize);
376 if (!keyarg)
377 gcry_free (key);
379 if (!rc)
381 rc = decrypt_data (client->ctx, client->crypto, salted_key, keysize);
382 if (gpg_err_code (rc) == GPG_ERR_BAD_PASSPHRASE
383 && ++pin_try <= pin_tries && !(client->flags & FLAG_NO_PINENTRY))
385 gcry_free (salted_key);
386 salted_key = NULL;
387 key = NULL;
388 keylen = 0;
389 client->pinentry_opts.title = str_asprintf (_ ("Bad passphrase (try %i of %i)"), pin_try, pin_tries);
390 goto pin_again;
394 if (client->pinentry_opts.title != pin_title)
395 xfree (client->pinentry_opts.title);
397 client->pinentry_opts.title = pin_title;
398 if (rc)
400 gcry_free (salted_key);
401 return rc;
404 cdata = xcalloc (1, sizeof (struct cache_data_s));
405 if (!cdata)
407 gcry_free (salted_key);
408 return GPG_ERR_ENOMEM;
411 cdata->key = salted_key;
412 cdata->keylen = keysize;
414 else
415 rc = decrypt_data (client->ctx, client->crypto, NULL, 0);
417 done:
418 if (!rc)
420 rc = parse_xml (ctx, client->flags & FLAG_NEW);
421 if (rc && !cached)
422 free_cache_data_once (cdata);
424 if (!rc)
426 int timeout = config_get_integer (client->filename,
427 "cache_timeout");
429 if (!cached)
431 if (!cdata)
432 cdata = xcalloc (1, sizeof (struct cache_data_s));
434 rc = encrypt_xml (NULL, cache_key, cache_keysize,
435 GCRY_CIPHER_AES, client->crypto->plaintext,
436 client->crypto->plaintext_len, &cdata->doc,
437 &cdata->doclen, &cache_iv, &cache_blocksize,
439 if (!rc && !(client->flags & FLAG_NEW) && IS_PKI (client->crypto))
441 rc = gcry_sexp_build ((gcry_sexp_t *) & cdata->pubkey, NULL,
442 "%S", client->crypto->pkey_sexp);
446 if (cdata->sigkey)
447 gcry_sexp_release (cdata->sigkey);
449 cdata->sigkey = NULL;
450 if (!rc && IS_PKI (client->crypto))
451 rc = gcry_sexp_build ((gcry_sexp_t *) &cdata->sigkey, NULL,
452 "%S", client->crypto->sigpkey_sexp);
454 if (!rc)
456 rc = cache_add_file (client->md5file,
457 (client->flags & FLAG_NEW) ? NULL
458 : client->crypto->grip, cdata, timeout);
459 if (rc)
461 if (!cached)
463 free_cache_data_once (cdata);
464 xmlFreeDoc (client->doc);
465 client->doc = NULL;
470 if (!rc)
471 client->flags |= FLAG_OPEN;
475 if (!rc)
476 update_checksum (client);
478 if (!rc && (client->opts & OPT_LOCK_ON_OPEN))
479 rc = do_lock (client, 0);
481 return rc;
484 static void
485 req_cleanup (void *arg)
487 if (!arg)
488 return;
490 strv_free ((char **) arg);
493 static gpg_error_t
494 parse_open_opt_lock (void *data, void *value)
496 struct client_s *client = data;
498 client->opts |= OPT_LOCK_ON_OPEN;
499 return 0;
502 static gpg_error_t
503 parse_save_opt_inquire (void *data, void *value)
505 struct client_s *client = data;
506 gpg_error_t rc;
508 if (!(client->flags & FLAG_NEW))
510 rc = peer_is_invoker (client);
511 if (rc == GPG_ERR_EACCES)
512 return rc;
515 (void) value;
516 client->opts |= OPT_INQUIRE;
517 return 0;
520 static gpg_error_t
521 parse_opt_inquire (void *data, void *value)
523 struct client_s *client = data;
525 (void) value;
526 client->opts |= OPT_INQUIRE;
527 return 0;
530 static gpg_error_t
531 update_checksum (struct client_s *client)
533 unsigned char *crc;
534 size_t len;
535 struct cache_data_s *cdata;
536 gpg_error_t rc = get_checksum (client->filename, &crc, &len);
538 if (rc)
539 return rc;
541 xfree (client->crc);
542 client->crc = crc;
543 cdata = cache_get_data (client->md5file);
544 if (cdata)
546 xfree (cdata->crc);
547 cdata->crc = xmalloc (len);
548 memcpy (cdata->crc, crc, len);
551 return 0;
554 static gpg_error_t
555 validate_checksum (struct client_s *client, struct cache_data_s *cdata)
557 unsigned char *crc;
558 size_t len;
559 gpg_error_t rc;
560 int n = 0;
562 if (cdata && !cdata->crc)
563 return GPG_ERR_CHECKSUM;
565 rc = get_checksum (client->filename, &crc, &len);
566 if (rc)
567 return rc;
569 if (cdata)
570 n = memcmp (cdata->crc, crc, len);
571 else if (client->crc)
572 n = memcmp (client->crc, crc, len);
574 xfree (crc);
575 return n ? GPG_ERR_CHECKSUM : 0;
578 static gpg_error_t
579 do_open (assuan_context_t ctx, const char *password)
581 struct client_s *client = assuan_get_pointer (ctx);
582 struct cache_data_s *cdata;
583 gpg_error_t rc = 0;
584 int done = 0;
586 // Cached document?
587 cdata = cache_get_data (client->md5file);
588 if (cdata && cdata->doc)
590 int defer = 0;
592 /* This will check that the key is cached in the agent which needs to
593 * be determined for files that share a keygrip. */
594 if (!rc)
596 rc = cache_iscached (client->filename, &defer);
597 if ((!rc || rc == GPG_ERR_ENOENT) && defer)
598 rc = GPG_ERR_KEY_EXPIRED;
601 if (!rc && !(client->flags & FLAG_NEW))
602 rc = validate_checksum (client, cdata);
604 #ifdef WITH_GNUTLS
605 if (!rc && client->thd->remote
606 && config_get_boolean (client->filename, "tcp_require_key"))
607 rc = GPG_ERR_KEY_EXPIRED;
608 #endif
610 if (!rc && !password)
612 rc = read_data_header (client->filename, &client->crypto->hdr,
613 NULL, NULL);
614 if (!rc)
616 if (IS_PKI (client->crypto))
618 gcry_sexp_build (&client->crypto->pkey_sexp, NULL, "%S",
619 cdata->pubkey);
620 gcry_pk_get_keygrip (client->crypto->pkey_sexp,
621 client->crypto->grip);
622 gcry_sexp_build (&client->crypto->sigpkey_sexp, NULL, "%S",
623 cdata->sigkey);
624 gcry_pk_get_keygrip (client->crypto->sigpkey_sexp,
625 client->crypto->sign_grip);
628 if (!rc)
630 rc = open_finalize (ctx, NULL, 0);
631 done = 1;
636 /* There was an error accessing the file so clear the cache entry. The
637 * real error will be returned from read_data_file() since the file
638 * may have only disappeared. */
639 if (!done)
641 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
642 rc = cache_clear (client->md5file);
643 send_status_all (STATUS_CACHE, NULL);
647 if (done || rc)
648 return rc;
650 rc = read_data_file (client->filename, client->crypto);
651 if (rc)
653 if (gpg_err_source (rc) != GPG_ERR_SOURCE_DEFAULT ||
654 gpg_err_code (rc) != GPG_ERR_ENOENT)
656 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
657 return rc;
660 client->flags |= FLAG_NEW;
661 memset (client->crypto->grip, 0, sizeof (client->crypto->grip));
662 memset (client->crypto->sign_grip, 0,
663 sizeof (client->crypto->sign_grip));
664 rc = open_finalize (ctx, NULL, 0);
665 return rc;
668 if (password && IS_PKI (client->crypto))
670 #ifdef WITH_AGENT
671 rc = set_agent_passphrase (client->crypto, password, strlen (password));
672 if (rc)
673 return rc;
674 #endif
677 rc = open_finalize (ctx, (char *)password, password ? strlen (password) : 0);
678 return rc;
681 static gpg_error_t
682 open_command (assuan_context_t ctx, char *line)
684 gpg_error_t rc;
685 struct client_s *client = assuan_get_pointer (ctx);
686 char **req, *filename;
687 unsigned char md5file[16];
688 int same_file = 0;
689 assuan_peercred_t peer;
690 struct argv_s *args[] = {
691 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_open_opt_lock},
692 NULL
695 rc = parse_options (&line, args, client);
696 if (rc)
697 return send_error (ctx, rc);
699 req = str_split (line, " ", 2);
700 if (!req)
701 return send_error (ctx, GPG_ERR_SYNTAX);
703 rc = do_validate_peer (ctx, req[0], &peer);
704 if (rc)
706 strv_free (req);
707 return send_error (ctx, rc);
710 filename = req[0];
711 if (!valid_filename (filename))
713 strv_free (req);
714 return send_error (ctx, GPG_ERR_INV_VALUE);
717 pthread_cleanup_push (req_cleanup, req);
718 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
719 /* This client may have locked a different file with ISCACHED --lock than
720 * the current filename. This will remove that lock. */
721 same_file = !memcmp (md5file, client->md5file, 16) ? 1 : 0;
722 if (client->flags & FLAG_OPEN ||
723 (client->flags & FLAG_HAS_LOCK && !same_file))
725 uint32_t opts = client->opts;
726 uint32_t flags = client->flags;
728 if (same_file)
729 client->flags |= FLAG_KEEP_LOCK;
730 else if (client->flags & FLAG_NEW)
731 cache_clear (client->md5file);
733 cleanup_client (client);
734 client->opts = opts;
735 client->flags |= flags;
736 client->flags &= ~(FLAG_LOCK_CMD);
737 if (!same_file)
738 client->flags &= ~(FLAG_HAS_LOCK | FLAG_NEW);
741 memcpy (client->md5file, md5file, 16);
742 client->filename = str_dup (filename);
743 if (!client->filename)
745 strv_free (req);
746 return send_error(ctx, GPG_ERR_ENOMEM);
749 /* Need to lock the mutex here because file_modified() cannot without
750 * knowing the filename. */
751 rc = lock_file_mutex (client, 1);
752 if (rc)
753 client->flags &= ~FLAG_OPEN;
755 if (!rc)
757 char *password = req[1] && *req[1] ? req[1] : NULL;
759 #ifdef WITH_AGENT
760 if (IS_PKI (client->crypto))
761 rc = set_pinentry_mode (client->crypto->agent,
762 (client->flags & FLAG_NO_PINENTRY) ? "loopback"
763 : "ask");
764 #endif
765 if (!rc)
767 rc = do_open (ctx, password);
768 if (rc)
769 cleanup_client (client);
771 cleanup_crypto_stage1 (client->crypto);
775 pthread_cleanup_pop (1);
777 if (!rc && client->flags & FLAG_NEW)
778 rc = send_status (ctx, STATUS_NEWFILE, NULL);
780 #ifdef WITH_AGENT
781 (void) kill_scd (client->crypto->agent);
782 #endif
784 return send_error (ctx, rc);
787 static gpg_error_t
788 parse_opt_no_passphrase (void *data, void *value)
790 struct client_s *client = data;
792 (void) value;
793 client->opts |= OPT_NO_PASSPHRASE;
794 return 0;
797 static gpg_error_t
798 parse_save_opt_no_agent (void *data, void *value)
800 struct client_s *client = data;
802 client->opts |= OPT_NO_AGENT;
803 return 0;
806 static gpg_error_t
807 parse_save_opt_cipher (void *data, void *value)
809 struct client_s *client = data;
810 int algo = cipher_string_to_gcrypt ((char *) value);
811 file_header_t *hdr = &client->crypto->save.hdr;
812 gpg_error_t rc = 0;
814 if (algo == -1)
815 return GPG_ERR_INV_VALUE;
817 if (!(client->flags & FLAG_NEW))
819 rc = peer_is_invoker (client);
820 if (rc == GPG_ERR_EACCES)
822 uint64_t flags = 0;
824 flags &= ((uint16_t) ((uint32_t) (flags & 0xFFFFFFFF)));
825 if (!(client->crypto->hdr.flags & gcrypt_to_cipher (algo)))
826 return rc;
828 rc = 0;
830 else if (rc)
831 return rc;
834 if (!rc)
835 hdr->flags = set_cipher_flag (hdr->flags, algo);
837 return rc;
840 #ifdef WITH_AGENT
841 static gpg_error_t
842 permitted_to_save (struct client_s *client, const unsigned char *grip,
843 size_t size, const char *value)
845 char *hexgrip;
846 gpg_error_t rc = 0;
848 if (!(client->flags & FLAG_NEW))
850 hexgrip = bin2hex (grip, size);
851 rc = !strcmp (hexgrip, (char *)value) ? 0 : GPG_ERR_EACCES;
852 xfree (hexgrip);
853 if (rc)
854 rc = peer_is_invoker (client);
857 return rc;
859 #endif
861 static gpg_error_t
862 parse_save_opt_keygrip (void *data, void *value)
864 #ifdef WITH_AGENT
865 struct client_s *client = data;
866 gpg_error_t rc = permitted_to_save (client, client->crypto->grip,
867 sizeof (client->crypto->grip),
868 value);
870 if (!IS_PKI (client->crypto))
871 return GPG_ERR_INV_ARG;
873 if (rc)
874 return rc;
876 if (client->crypto->save.pkey)
877 gcry_sexp_release (client->crypto->save.pkey);
879 client->crypto->save.pkey = NULL;
880 return get_pubkey (client->crypto, value, &client->crypto->save.pkey);
881 #else
882 return GPG_ERR_INV_ARG;
883 #endif
886 static gpg_error_t
887 parse_save_opt_sign_keygrip (void *data, void *value)
889 #ifdef WITH_AGENT
890 struct client_s *client = data;
891 gpg_error_t rc = permitted_to_save (client, client->crypto->sign_grip,
892 sizeof (client->crypto->sign_grip),
893 value);
895 if (!IS_PKI (client->crypto))
896 return GPG_ERR_INV_ARG;
898 if (rc)
899 return rc;
901 if (client->crypto->save.sigpkey)
902 gcry_sexp_release (client->crypto->save.sigpkey);
904 client->crypto->save.sigpkey = NULL;
905 return get_pubkey (client->crypto, value, &client->crypto->save.sigpkey);
906 #else
907 return GPG_ERR_INV_ARG;
908 #endif
911 static gpg_error_t
912 parse_opt_s2k_count (void *data, void *value)
914 struct client_s *client = data;
915 char *v = value;
917 if (!v || !*v)
918 return GPG_ERR_INV_VALUE;
920 client->crypto->save.s2k_count = strtoul (v, NULL, 10);
921 return 0;
924 static gpg_error_t
925 parse_save_opt_iterations (void *data, void *value)
927 struct client_s *client = data;
928 char *v = value, *p;
929 uint64_t n;
931 if (!v || !*v)
932 return GPG_ERR_INV_VALUE;
934 errno = 0;
935 n = strtoull (v, &p, 10);
936 if (n == UINT64_MAX && errno)
937 return gpg_error_from_errno (errno);
938 else if (p && *p)
939 return GPG_ERR_INV_VALUE;
941 if (!(client->flags & FLAG_NEW))
943 gpg_error_t rc = peer_is_invoker (client);
945 if (rc == GPG_ERR_EACCES)
947 if (client->crypto->hdr.iterations != n)
948 return rc;
950 rc = 0;
952 else if (rc)
953 return rc;
956 client->crypto->save.hdr.iterations = n;
957 return 0;
960 static gpg_error_t
961 save_finalize (assuan_context_t ctx)
963 struct client_s *client = assuan_get_pointer (ctx);
964 gpg_error_t rc = 0;
965 xmlChar *xmlbuf = NULL;
966 int xmlbuflen;
967 void *key = NULL;
968 size_t keylen = 0;
970 xmlDocDumpFormatMemory (client->doc, &xmlbuf, &xmlbuflen, 0);
971 if (!xmlbuf)
972 return GPG_ERR_ENOMEM;
974 pthread_cleanup_push (xmlFree, xmlbuf);
976 if (!use_agent || ((client->flags & FLAG_NEW)
977 && (client->opts & OPT_NO_AGENT))
978 || !(client->crypto->hdr.flags & PWMD_FLAG_PKI))
980 rc = export_common (ctx, client->flags & FLAG_NO_PINENTRY,
981 client->crypto, xmlbuf, xmlbuflen, client->filename,
982 NULL, &key, &keylen, 1, 1,
983 (client->opts & OPT_NO_PASSPHRASE));
985 #ifdef WITH_AGENT
986 else
988 gcry_sexp_t pubkey = client->crypto->save.pkey;
989 gcry_sexp_t sigkey = client->crypto->save.sigpkey;
991 if (!pubkey)
992 pubkey = client->crypto->pkey_sexp;
994 if (!sigkey)
996 sigkey = client->crypto->sigpkey_sexp;
997 if (!sigkey)
999 gcry_sexp_build (&client->crypto->save.sigpkey, 0, "%S", pubkey);
1000 sigkey = client->crypto->save.sigpkey;
1004 rc = encrypt_data_file (client->ctx, client->crypto, pubkey, sigkey,
1005 client->filename, xmlbuf, xmlbuflen);
1006 if (pubkey == client->crypto->save.pkey)
1008 if (!rc)
1010 gcry_sexp_release (client->crypto->pkey_sexp);
1011 client->crypto->pkey_sexp = client->crypto->save.pkey;
1012 gcry_pk_get_keygrip (client->crypto->pkey_sexp,
1013 client->crypto->grip);
1015 else
1016 gcry_sexp_release (pubkey);
1018 client->crypto->save.pkey = NULL;
1021 if (!rc)
1022 gcry_pk_get_keygrip (sigkey, client->crypto->sign_grip);
1024 if (sigkey == client->crypto->save.sigpkey)
1026 if (!rc)
1028 if (client->crypto->sigpkey_sexp)
1029 gcry_sexp_release (client->crypto->sigpkey_sexp);
1031 client->crypto->sigpkey_sexp = client->crypto->save.sigpkey;
1032 gcry_pk_get_keygrip (client->crypto->sigpkey_sexp,
1033 client->crypto->sign_grip);
1035 else
1036 gcry_sexp_release (sigkey);
1038 client->crypto->save.sigpkey = NULL;
1041 #endif
1043 if (!rc)
1045 int cached;
1047 rc = save_common (client->filename, client->crypto, xmlbuf, xmlbuflen,
1048 key, keylen, &cached, client->opts & OPT_NO_AGENT);
1049 if (rc)
1050 gcry_free (key);
1052 if (!rc && (!cached || (client->flags & FLAG_NEW)))
1053 send_status_all (STATUS_CACHE, NULL);
1055 if (!rc)
1057 rc = update_checksum (client);
1058 client->flags &= ~(FLAG_NEW);
1062 pthread_cleanup_pop (1); // xmlFree
1063 return rc;
1066 static gpg_error_t
1067 parse_opt_reset (void *data, void *value)
1069 struct client_s *client = data;
1071 (void) value;
1072 client->opts |= OPT_RESET;
1073 return 0;
1076 static gpg_error_t
1077 save_command (assuan_context_t ctx, char *line)
1079 struct client_s *client = assuan_get_pointer (ctx);
1080 gpg_error_t rc;
1081 struct stat st;
1082 struct argv_s *args[] = {
1083 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG,
1084 parse_opt_no_passphrase},
1085 &(struct argv_s) {"cipher", OPTION_TYPE_ARG, parse_save_opt_cipher},
1086 &(struct argv_s) {"inquire-keyparam", OPTION_TYPE_NOARG,
1087 parse_save_opt_inquire},
1088 &(struct argv_s) {"keygrip", OPTION_TYPE_ARG, parse_save_opt_keygrip},
1089 &(struct argv_s) {"sign-keygrip", OPTION_TYPE_ARG,
1090 parse_save_opt_sign_keygrip},
1091 &(struct argv_s) {"s2k-count", OPTION_TYPE_ARG, parse_opt_s2k_count},
1092 &(struct argv_s) {"reset", OPTION_TYPE_NOARG, parse_opt_reset},
1093 &(struct argv_s) {"cipher-iterations", OPTION_TYPE_ARG,
1094 parse_save_opt_iterations},
1095 &(struct argv_s) {"no-agent", OPTION_TYPE_NOARG,
1096 parse_save_opt_no_agent},
1097 NULL
1100 cleanup_save (&client->crypto->save);
1101 memcpy (&client->crypto->save.hdr, &client->crypto->hdr,
1102 sizeof (file_header_t));
1103 client->crypto->save.s2k_count =
1104 config_get_ulong (client->filename, "s2k_count");
1106 if (client->flags & FLAG_NEW)
1107 client->crypto->save.hdr.iterations =
1108 config_get_ulonglong (client->filename, "cipher_iterations");
1110 rc = parse_options (&line, args, client);
1111 if (rc)
1112 return send_error (ctx, rc);
1114 if (!(client->flags & FLAG_NEW))
1115 client->opts &= ~OPT_NO_AGENT;
1116 else if (client->opts & OPT_NO_AGENT)
1118 client->crypto->save.hdr.flags &= ~PWMD_FLAG_PKI;
1119 client->crypto->hdr.flags &= ~PWMD_FLAG_PKI;
1122 if ((client->opts & OPT_NO_PASSPHRASE) && !(client->flags & FLAG_NEW)
1123 && !(client->opts & OPT_INQUIRE))
1124 return send_error (ctx, GPG_ERR_WRONG_KEY_USAGE);
1126 if (lstat (client->filename, &st) == -1 && errno != ENOENT)
1127 return send_error (ctx, gpg_error_from_errno (errno));
1129 if (errno != ENOENT && !S_ISREG (st.st_mode))
1131 log_write ("%s: %s", client->filename, pwmd_strerror (GPG_ERR_ENOANO));
1132 return send_error (ctx, GPG_ERR_ENOANO);
1135 int defer = 0;
1136 rc = cache_iscached (client->filename, &defer);
1137 if (gpg_err_code (rc) == GPG_ERR_ENOENT && client->flags & FLAG_NEW)
1138 rc = 0;
1139 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
1140 rc = 0;
1142 if ((!rc && defer) || config_get_boolean ("global", "require_save_key"))
1143 client->opts |= OPT_RESET;
1145 if (!rc && (client->opts & OPT_RESET))
1147 rc = cache_clear (client->md5file);
1148 if (rc)
1149 return send_error (ctx, rc);
1151 log_write ("%s: %s", client->filename,
1152 pwmd_strerror (GPG_ERR_KEY_EXPIRED));
1153 send_status_all (STATUS_CACHE, NULL);
1156 if (!rc)
1157 rc = update_element_mtime (client, xmlDocGetRootElement (client->doc));
1159 if (rc)
1160 return send_error (ctx, rc);
1162 #ifdef WITH_AGENT
1163 if (!rc && use_agent && !client->crypto->save.pkey &&
1164 (client->flags & FLAG_NEW || client->opts & OPT_INQUIRE)
1165 && !(client->opts & OPT_NO_AGENT))
1167 rc = set_pinentry_mode (client->crypto->agent,
1168 (client->flags & FLAG_NO_PINENTRY) ? "loopback"
1169 : "ask");
1171 if (!(client->flags & FLAG_NEW))
1173 struct crypto_s *crypto;
1174 char *key = NULL;
1175 size_t keylen = 0;
1177 /* Wanting to generate a new key. Require the key to open the
1178 current file before proceeding reguardless of the
1179 require_save_key configuration parameter. */
1180 rc = cache_clear (client->md5file);
1181 if (!rc)
1183 rc = init_client_crypto (&crypto);
1184 if (!rc)
1185 crypto->client_ctx = client->ctx;
1188 if (!rc)
1189 rc = decrypt_common (client->ctx, client->opts&OPT_INQUIRE, crypto,
1190 client->filename, &key, &keylen);
1192 xfree (key);
1193 cleanup_crypto (&crypto);
1196 if (!rc)
1197 rc = send_status (client->ctx, STATUS_GENKEY, NULL);
1199 if (!rc)
1201 struct inquire_data_s idata = { 0 };
1202 char *params = client->opts & OPT_INQUIRE
1203 ? NULL : default_key_params (client->crypto);
1205 pthread_cleanup_push (xfree, params);
1206 idata.crypto = client->crypto;
1208 if (params)
1210 idata.line = params;
1211 idata.len = strlen (params);
1213 else
1214 idata.preset = 1;
1216 client->crypto->agent->inquire_data = &idata;
1217 client->crypto->agent->inquire_cb = NULL;
1218 rc = generate_key (client->crypto, params,
1219 (client->opts & OPT_NO_PASSPHRASE), 1);
1220 pthread_cleanup_pop (1);
1223 #endif
1225 if (!rc)
1226 rc = save_finalize (ctx);
1228 cleanup_crypto_stage1 (client->crypto);
1229 #ifdef WITH_AGENT
1230 (void) kill_scd (client->crypto->agent);
1231 #endif
1232 return send_error (ctx, rc);
1235 static gpg_error_t
1236 do_delete (assuan_context_t ctx, char *line)
1238 struct client_s *client = assuan_get_pointer (ctx);
1239 gpg_error_t rc;
1240 char **req;
1241 xmlNodePtr n;
1243 if (strchr (line, '\t'))
1244 req = str_split (line, "\t", 0);
1245 else
1246 req = str_split (line, " ", 0);
1248 if (!req || !*req)
1249 return GPG_ERR_SYNTAX;
1251 n = find_root_element (client, client->doc, &req, &rc, NULL, 0, 0);
1252 if (!n)
1254 strv_free (req);
1255 return rc;
1259 * No sub-node defined. Remove the entire node (root element).
1261 if (!req[1])
1263 if (n)
1265 rc = is_element_owner (client, n);
1266 if (!rc)
1268 rc = unlink_node (client, n);
1269 xmlFreeNode (n);
1273 strv_free (req);
1274 return rc;
1277 n = find_elements (client, client->doc, n->children, req + 1, &rc, NULL,
1278 NULL, NULL, 0, 0, NULL, 0);
1279 strv_free (req);
1280 if (!n)
1281 return rc;
1283 rc = is_element_owner (client, n);
1284 if (!rc)
1286 rc = unlink_node (client, n);
1287 xmlFreeNode (n);
1290 return rc;
1293 static gpg_error_t
1294 delete_command (assuan_context_t ctx, char *line)
1296 struct client_s *client = assuan_get_pointer (ctx);
1297 gpg_error_t rc;
1298 struct argv_s *args[] = {
1299 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1300 NULL
1303 rc = parse_options (&line, args, client);
1304 if (rc)
1305 return send_error (ctx, rc);
1307 if (client->opts & OPT_INQUIRE)
1309 unsigned char *result;
1310 size_t len;
1312 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1313 if (rc)
1314 return send_error (ctx, rc);
1316 pthread_cleanup_push (xfree, result);
1317 rc = do_delete (ctx, (char *)result);
1318 pthread_cleanup_pop (1);
1320 else
1321 rc = do_delete (ctx, line);
1323 return send_error (ctx, rc);
1326 static gpg_error_t
1327 store_command (assuan_context_t ctx, char *line)
1329 struct client_s *client = assuan_get_pointer (ctx);
1330 gpg_error_t rc;
1331 size_t len;
1332 unsigned char *result;
1333 char **req;
1334 xmlNodePtr n, parent;
1335 int has_content;
1336 char *content = NULL;
1338 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1339 if (rc)
1340 return send_error (ctx, rc);
1342 req = str_split ((char *) result, "\t", 0);
1343 xfree (result);
1345 if (!req || !*req)
1346 return send_error (ctx, GPG_ERR_SYNTAX);
1348 len = strv_length (req);
1349 has_content = line[strlen (line) - 1] != '\t' && len > 1;
1350 if (*(req + 1) && !valid_element_path (req, has_content))
1352 strv_free (req);
1353 return send_error (ctx, GPG_ERR_INV_VALUE);
1356 if (has_content || !*req[len - 1])
1358 has_content = 1;
1359 content = req[len - 1];
1360 req[len - 1] = NULL;
1363 again:
1364 n = find_root_element (client, client->doc, &req, &rc, NULL, 0, 0);
1365 if (rc && rc == GPG_ERR_ELEMENT_NOT_FOUND)
1367 rc = new_root_element (client, client->doc, *req);
1368 if (rc)
1370 strv_free (req);
1371 return send_error (ctx, rc);
1374 goto again;
1377 if (!n)
1379 strv_free (req);
1380 return send_error (ctx, rc);
1383 parent = n;
1385 if (req[1] && *req[1])
1387 if (!n->children)
1388 parent = create_elements_cb (client, 1, n, req + 1, &rc, NULL);
1389 else
1390 parent = find_elements (client, client->doc, n->children, req + 1, &rc,
1391 NULL, NULL, create_elements_cb, 0, 0, NULL,
1395 if (!rc && len > 1)
1397 rc = is_element_owner (client, parent);
1398 if (!rc)
1400 n = find_text_node (parent->children);
1401 if (n)
1402 xmlNodeSetContent (n, (xmlChar *) content);
1403 else
1404 xmlNodeAddContent (parent, (xmlChar *) content);
1406 update_element_mtime (client, parent);
1410 xfree (content);
1411 strv_free (req);
1412 return send_error (ctx, rc);
1415 static gpg_error_t
1416 xfer_data (assuan_context_t ctx, const char *line, int total)
1418 int to_send;
1419 int sent = 0;
1420 gpg_error_t rc;
1421 int progress = config_get_integer ("global", "xfer_progress");
1422 int flush = 0;
1424 progress =
1425 progress > 0 ? (progress / ASSUAN_LINELENGTH) * ASSUAN_LINELENGTH : 0;
1426 to_send = total < ASSUAN_LINELENGTH ? total : ASSUAN_LINELENGTH;
1427 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1429 if (rc)
1430 return rc;
1432 again:
1435 if (sent + to_send > total)
1436 to_send = total - sent;
1438 rc = assuan_send_data (ctx, flush ? NULL : (char *) line + sent,
1439 flush ? 0 : to_send);
1440 if (!rc)
1442 sent += flush ? 0 : to_send;
1444 if ((progress && !(sent % progress) && sent != total) ||
1445 (sent == total && flush))
1446 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1448 if (!flush && !rc && sent == total)
1450 flush = 1;
1451 goto again;
1455 while (!rc && sent < total);
1457 return rc;
1460 static gpg_error_t
1461 do_get (assuan_context_t ctx, char *line)
1463 struct client_s *client = assuan_get_pointer (ctx);
1464 gpg_error_t rc;
1465 char **req;
1466 xmlNodePtr n;
1468 req = str_split (line, "\t", 0);
1470 if (!req || !*req)
1472 strv_free (req);
1473 return GPG_ERR_SYNTAX;
1476 n = find_root_element (client, client->doc, &req, &rc, NULL, 0, 0);
1477 if (!n)
1479 strv_free (req);
1480 return rc;
1483 if (req[1])
1485 find_elements (client, client->doc, n->children, req + 1, &rc, NULL, NULL, NULL,
1486 0, 0, NULL, 0);
1488 strv_free (req);
1489 if (rc)
1490 return rc;
1492 if (!n || !n->children)
1493 return GPG_ERR_NO_DATA;
1495 n = find_text_node (n->children);
1496 if (!n || !n->content || !*n->content)
1497 return GPG_ERR_NO_DATA;
1499 rc = xfer_data (ctx, (char *) n->content, xmlStrlen (n->content));
1500 return rc;
1503 static gpg_error_t
1504 get_command (assuan_context_t ctx, char *line)
1506 struct client_s *client = assuan_get_pointer (ctx);
1507 gpg_error_t rc;
1508 struct argv_s *args[] = {
1509 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1510 NULL
1513 rc = parse_options (&line, args, client);
1514 if (rc)
1515 return send_error (ctx, rc);
1517 if (client->opts & OPT_INQUIRE)
1519 unsigned char *result;
1520 size_t len;
1522 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1523 if (rc)
1524 return send_error (ctx, rc);
1526 pthread_cleanup_push (xfree, result);
1527 rc = do_get (ctx, (char *)result);
1528 pthread_cleanup_pop (1);
1530 else
1531 rc = do_get (ctx, line);
1533 return send_error (ctx, rc);
1536 static void list_command_cleanup1 (void *arg);
1537 static gpg_error_t
1538 realpath_command (assuan_context_t ctx, char *line)
1540 struct string_s *string = NULL;
1541 gpg_error_t rc;
1542 struct client_s *client = assuan_get_pointer (ctx);
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 = build_realpath (client, client->doc, (char *)result, &string);
1563 pthread_cleanup_pop (1);
1565 else
1566 rc = build_realpath (client, client->doc, line, &string);
1568 if (!rc)
1570 pthread_cleanup_push (list_command_cleanup1, string);
1571 rc = xfer_data (ctx, string->str, string->len);
1572 pthread_cleanup_pop (1);
1575 return send_error (ctx, rc);
1578 static void
1579 list_command_cleanup1 (void *arg)
1581 if (arg)
1582 string_free ((struct string_s *) arg, 1);
1585 static void
1586 list_command_cleanup2 (void *arg)
1588 struct element_list_s *elements = arg;
1590 if (elements)
1592 if (elements->list)
1594 int total = slist_length (elements->list);
1595 int i;
1597 for (i = 0; i < total; i++)
1599 char *tmp = slist_nth_data (elements->list, i);
1600 xfree (tmp);
1603 slist_free (elements->list);
1606 if (elements->prefix)
1607 xfree (elements->prefix);
1609 if (elements->req)
1610 strv_free (elements->req);
1612 xfree (elements);
1616 static gpg_error_t
1617 parse_list_opt_norecurse (void *data, void *value)
1619 struct client_s *client = data;
1621 client->opts &= ~(OPT_LIST_RECURSE);
1622 return 0;
1625 static gpg_error_t
1626 parse_opt_verbose (void *data, void *value)
1628 struct client_s *client = data;
1630 client->opts |= OPT_VERBOSE;
1631 return 0;
1634 static gpg_error_t
1635 parse_list_opt_target (void *data, void *value)
1637 struct client_s *client = data;
1639 client->opts |= OPT_LIST_WITH_TARGET;
1640 return 0;
1643 static gpg_error_t
1644 parse_list_opt_all (void *data, void *value)
1646 struct client_s *client = data;
1648 client->opts |= OPT_LIST_ALL;
1649 return 0;
1652 static gpg_error_t
1653 list_path_once (struct client_s *client, char *line,
1654 struct element_list_s *elements, struct string_s *result)
1656 gpg_error_t rc;
1658 elements->req = str_split (line, " ", 0);
1659 if (!elements->req)
1660 strv_printf (&elements->req, "%s", line);
1662 rc = create_path_list (client, client->doc, elements, *elements->req);
1663 if ((rc == GPG_ERR_ELOOP || rc == GPG_ERR_EACCES) && elements->verbose)
1664 rc = 0;
1666 if (!rc)
1668 int total = slist_length (elements->list);
1670 if (!total)
1671 rc = GPG_ERR_NO_DATA;
1673 if (!rc)
1675 if (!rc)
1677 int i;
1679 for (i = 0; i < total; i++)
1681 char *tmp = slist_nth_data (elements->list, i);
1683 string_append_printf (result, "%s%s", tmp,
1684 i + 1 == total ? "" : "\n");
1688 else
1689 rc = GPG_ERR_NO_DATA;
1692 return rc;
1695 static int
1696 has_list_flag (char *path, char *flags)
1698 char *p = path;
1700 while (*p && *++p != ' ');
1702 if (!*p)
1703 return 0;
1705 for (; *p; p++)
1707 char *f;
1709 for (f = flags; *f && *f != ' '; f++)
1711 if (*p == *f)
1712 return 1;
1716 return 0;
1719 static gpg_error_t
1720 do_list (assuan_context_t ctx, char *line)
1722 struct client_s *client = assuan_get_pointer (ctx);
1723 gpg_error_t rc;
1724 struct element_list_s *elements = NULL;
1726 elements = xcalloc (1, sizeof (struct element_list_s));
1727 if (!elements)
1728 return GPG_ERR_ENOMEM;
1730 elements->recurse = client->opts & OPT_LIST_RECURSE;
1731 elements->verbose =
1732 (client->opts & OPT_VERBOSE) | (client->opts & OPT_LIST_WITH_TARGET);
1733 elements->with_target = client->opts & OPT_LIST_WITH_TARGET;
1735 if (!line || !*line)
1737 struct string_s *str = NULL;
1739 pthread_cleanup_push (list_command_cleanup2, elements);
1740 rc = list_root_elements (client, client->doc, &str, elements->verbose,
1741 elements->with_target);
1742 pthread_cleanup_pop (1);
1743 pthread_cleanup_push (list_command_cleanup1, str);
1745 if (!rc)
1747 if (client->opts & OPT_LIST_ALL)
1749 char **roots = str_split (str->str, "\n", 0);
1750 char **p;
1752 pthread_cleanup_push (req_cleanup, roots);
1753 string_truncate (str, 0);
1755 for (p = roots; *p; p++)
1757 if (strchr (*p, ' '))
1759 if (has_list_flag (*p, "EOP"))
1761 string_append_printf (str, "%s%s", *p,
1762 *(p + 1) ? "\n" : "");
1763 continue;
1767 elements = xcalloc (1, sizeof (struct element_list_s));
1768 if (!elements)
1770 rc = GPG_ERR_ENOMEM;
1771 break;
1774 elements->recurse = client->opts & OPT_LIST_RECURSE;
1775 elements->verbose =
1776 (client->opts & OPT_VERBOSE) | (client->opts &
1777 OPT_LIST_WITH_TARGET);
1778 elements->with_target = client->opts & OPT_LIST_WITH_TARGET;
1779 pthread_cleanup_push (list_command_cleanup2, elements);
1780 rc = list_path_once (client, *p, elements, str);
1781 pthread_cleanup_pop (1);
1782 if (rc)
1783 break;
1785 if (*(p + 1))
1786 string_append (str, "\n");
1789 pthread_cleanup_pop (1);
1792 if (!rc)
1793 rc = xfer_data (ctx, str->str, str->len);
1796 pthread_cleanup_pop (1);
1797 return rc;
1800 pthread_cleanup_push (list_command_cleanup2, elements);
1801 struct string_s *str = string_new (NULL);
1802 pthread_cleanup_push (list_command_cleanup1, str);
1803 rc = list_path_once (client, line, elements, str);
1804 if (!rc)
1805 rc = xfer_data (ctx, str->str, str->len);
1807 pthread_cleanup_pop (1);
1808 pthread_cleanup_pop (1);
1809 return rc;
1812 static gpg_error_t
1813 list_command (assuan_context_t ctx, char *line)
1815 struct client_s *client = assuan_get_pointer (ctx);
1816 gpg_error_t rc;
1817 struct argv_s *args[] = {
1818 &(struct argv_s) {"no-recurse", OPTION_TYPE_NOARG,
1819 parse_list_opt_norecurse},
1820 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_opt_verbose},
1821 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1822 &(struct argv_s) {"with-target", OPTION_TYPE_NOARG,
1823 parse_list_opt_target},
1824 &(struct argv_s) {"all", OPTION_TYPE_NOARG, parse_list_opt_all},
1825 NULL
1828 if (disable_list_and_dump == 1)
1829 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
1831 client->opts |= OPT_LIST_RECURSE;
1832 rc = parse_options (&line, args, client);
1833 if (rc)
1834 return send_error (ctx, rc);
1836 if (client->opts & OPT_LIST_ALL)
1837 client->opts |= OPT_LIST_RECURSE | OPT_VERBOSE;
1839 if (client->opts & OPT_INQUIRE)
1841 unsigned char *result;
1842 size_t len;
1844 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1845 if (rc)
1846 return send_error (ctx, rc);
1848 pthread_cleanup_push (xfree, result);
1849 rc = do_list (ctx, (char *)result);
1850 pthread_cleanup_pop (1);
1852 else
1853 rc = do_list (ctx, line);
1855 return send_error (ctx, rc);
1859 * req[0] - element path
1861 static gpg_error_t
1862 attribute_list (assuan_context_t ctx, char **req)
1864 struct client_s *client = assuan_get_pointer (ctx);
1865 char **attrlist = NULL;
1866 int i = 0;
1867 char **path = NULL;
1868 xmlAttrPtr a;
1869 xmlNodePtr n, an;
1870 char *line;
1871 gpg_error_t rc;
1873 if (!req || !req[0])
1874 return GPG_ERR_SYNTAX;
1876 if ((path = str_split (req[0], "\t", 0)) == NULL)
1879 * The first argument may be only a root element.
1881 if ((path = str_split (req[0], " ", 0)) == NULL)
1882 return GPG_ERR_SYNTAX;
1885 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 0);
1887 if (!n)
1889 strv_free (path);
1890 return rc;
1893 if (path[1])
1895 n = find_elements (client, client->doc, n->children, path + 1, &rc,
1896 NULL, NULL, NULL, 0, 0, NULL, 0);
1898 if (!n)
1900 strv_free (path);
1901 return rc;
1905 strv_free (path);
1907 for (a = n->properties; a; a = a->next)
1909 char **pa;
1911 if ((pa = xrealloc (attrlist, (i + 2) * sizeof (char *))) == NULL)
1913 if (attrlist)
1914 strv_free (attrlist);
1916 log_write ("%s(%i): %s", __FILE__, __LINE__,
1917 pwmd_strerror (GPG_ERR_ENOMEM));
1918 return GPG_ERR_ENOMEM;
1921 attrlist = pa;
1922 an = a->children;
1923 attrlist[i] = str_asprintf ("%s %s", (char *) a->name,
1925 && an->content ? (char *) an->content : "");
1927 if (!attrlist[i])
1929 strv_free (attrlist);
1930 log_write ("%s(%i): %s", __FILE__, __LINE__,
1931 pwmd_strerror (GPG_ERR_ENOMEM));
1932 return GPG_ERR_ENOMEM;
1935 attrlist[++i] = NULL;
1938 if (!attrlist)
1939 return GPG_ERR_NO_DATA;
1941 line = strv_join ("\n", attrlist);
1943 if (!line)
1945 log_write ("%s(%i): %s", __FILE__, __LINE__,
1946 pwmd_strerror (GPG_ERR_ENOMEM));
1947 strv_free (attrlist);
1948 return GPG_ERR_ENOMEM;
1951 pthread_cleanup_push (xfree, line);
1952 pthread_cleanup_push (req_cleanup, attrlist);
1953 rc = xfer_data (ctx, line, strlen (line));
1954 pthread_cleanup_pop (1);
1955 pthread_cleanup_pop (1);
1956 return rc;
1960 * req[0] - attribute
1961 * req[1] - element path
1963 static gpg_error_t
1964 attribute_delete (struct client_s *client, char **req)
1966 xmlNodePtr n;
1967 char **path = NULL;
1968 gpg_error_t rc;
1970 if (!req || !req[0] || !req[1])
1971 return GPG_ERR_SYNTAX;
1973 if (!strcmp (req[0], "_name"))
1974 return GPG_ERR_INV_ATTR;
1976 if ((path = str_split (req[1], "\t", 0)) == NULL)
1979 * The first argument may be only a root element.
1981 if ((path = str_split (req[1], " ", 0)) == NULL)
1982 return GPG_ERR_SYNTAX;
1985 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 0);
1986 if (!n)
1987 goto fail;
1989 if (path[1])
1991 n = find_elements (client, client->doc, n->children, path + 1, &rc,
1992 NULL, NULL, NULL, 0, 0, NULL, 0);
1993 if (!n)
1994 goto fail;
1997 if (!strcmp (req[0], (char *) "_acl"))
1999 rc = is_element_owner (client, n);
2000 if (rc)
2001 goto fail;
2004 rc = delete_attribute (client, n, (xmlChar *) req[0]);
2006 fail:
2007 strv_free (path);
2008 return rc;
2011 static xmlNodePtr
2012 create_element_path (struct client_s *client,
2013 char ***elements, gpg_error_t * rc, xmlNodePtr parent)
2015 char **req = *elements;
2016 char **req_orig = strv_dup (req);
2017 xmlNodePtr n = NULL;
2019 *rc = 0;
2021 if (!req_orig)
2023 *rc = GPG_ERR_ENOMEM;
2024 log_write ("%s(%i): %s", __FILE__, __LINE__,
2025 pwmd_strerror (GPG_ERR_ENOMEM));
2026 goto fail;
2029 again:
2030 n = find_root_element (client, client->doc, &req, rc, NULL, 0, 0);
2031 if (!n)
2033 if (*rc != GPG_ERR_ELEMENT_NOT_FOUND)
2034 goto fail;
2036 *rc = new_root_element (client, client->doc, req[0]);
2037 if (*rc)
2038 goto fail;
2040 goto again;
2042 else if (n == parent)
2044 *rc = GPG_ERR_CONFLICT;
2045 goto fail;
2048 if (req[1])
2050 if (!n->children)
2051 n = create_target_elements_cb (client, 1, n, req + 1, rc, NULL);
2052 else
2053 n = find_elements (client, client->doc, n->children, req + 1, rc,
2054 NULL, NULL, create_target_elements_cb, 0, 0,
2055 parent, 0);
2057 if (!n)
2058 goto fail;
2061 * Reset the position of the element tree now that the elements
2062 * have been created.
2064 strv_free (req);
2065 req = req_orig;
2066 req_orig = NULL;
2067 n = find_root_element (client, client->doc, &req, rc, NULL, 0, 0);
2068 if (!n)
2069 goto fail;
2071 n = find_elements (client, client->doc, n->children, req + 1, rc,
2072 NULL, NULL, NULL, 0, 0, NULL, 0);
2073 if (!n)
2074 goto fail;
2077 fail:
2078 if (req_orig)
2079 strv_free (req_orig);
2081 *elements = req;
2082 return n;
2086 * Creates a "target" attribute. When other commands encounter an element with
2087 * this attribute, the element path is modified to the target value. If the
2088 * source element path doesn't exist when using 'ATTR SET target', it is
2089 * created, but the destination element path must exist.
2091 * req[0] - source element path
2092 * req[1] - destination element path
2094 static gpg_error_t
2095 target_attribute (struct client_s *client, char **req)
2097 char **src, **dst, *line = NULL, **odst = NULL;
2098 gpg_error_t rc;
2099 xmlNodePtr n;
2101 if (!req || !req[0] || !req[1])
2102 return GPG_ERR_SYNTAX;
2104 if ((src = str_split (req[0], "\t", 0)) == NULL)
2107 * The first argument may be only a root element.
2109 if ((src = str_split (req[0], " ", 0)) == NULL)
2110 return GPG_ERR_SYNTAX;
2113 if (!valid_element_path (src, 0))
2114 return GPG_ERR_INV_VALUE;
2116 if ((dst = str_split (req[1], "\t", 0)) == NULL)
2119 * The first argument may be only a root element.
2121 if ((dst = str_split (req[1], " ", 0)) == NULL)
2123 rc = GPG_ERR_SYNTAX;
2124 goto fail;
2128 odst = strv_dup (dst);
2129 if (!odst)
2131 rc = GPG_ERR_ENOMEM;
2132 goto fail;
2135 n = find_root_element (client, client->doc, &dst, &rc, NULL, 0, 0);
2137 * Make sure the destination element path exists.
2139 if (!n)
2140 goto fail;
2142 if (dst[1])
2144 n = find_elements (client, client->doc, n->children, dst + 1, &rc,
2145 NULL, NULL, NULL, 0, 0, NULL, 0);
2146 if (!n)
2147 goto fail;
2150 rc = validate_target_attribute (client, client->doc, req[0], n);
2151 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2152 goto fail;
2154 n = create_element_path (client, &src, &rc, NULL);
2155 if (rc)
2156 goto fail;
2158 line = strv_join ("\t", odst);
2159 if (!line)
2161 rc = GPG_ERR_ENOMEM;
2162 goto fail;
2165 rc = add_attribute (client, n, "target", line);
2167 fail:
2168 xfree (line);
2169 strv_free (src);
2170 strv_free (dst);
2171 strv_free (odst);
2172 return rc;
2176 * req[0] - attribute
2177 * req[1] - element path
2179 static gpg_error_t
2180 attribute_get (assuan_context_t ctx, char **req)
2182 struct client_s *client = assuan_get_pointer (ctx);
2183 xmlNodePtr n;
2184 xmlChar *a;
2185 char **path = NULL;
2186 gpg_error_t rc;
2188 if (!req || !req[0] || !req[1])
2189 return GPG_ERR_SYNTAX;
2191 if (strchr (req[1], '\t'))
2193 if ((path = str_split (req[1], "\t", 0)) == NULL)
2194 return GPG_ERR_SYNTAX;
2196 else
2198 if ((path = str_split (req[1], " ", 0)) == NULL)
2199 return GPG_ERR_SYNTAX;
2202 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 0);
2204 if (!n)
2205 goto fail;
2207 if (path[1])
2209 n = find_elements (client, client->doc, n->children, path + 1, &rc,
2210 NULL, NULL, NULL, 0, 0, NULL, 0);
2212 if (!n)
2213 goto fail;
2216 strv_free (path);
2218 if ((a = xmlGetProp (n, (xmlChar *) req[0])) == NULL)
2219 return GPG_ERR_NOT_FOUND;
2221 pthread_cleanup_push (xmlFree, a);
2223 if (*a)
2224 rc = xfer_data (ctx, (char *) a, xmlStrlen (a));
2225 else
2226 rc = GPG_ERR_NO_DATA;
2228 pthread_cleanup_pop (1);
2229 return rc;
2231 fail:
2232 strv_free (path);
2233 return rc;
2237 * req[0] - attribute
2238 * req[1] - element path
2239 * req[2] - value
2241 static gpg_error_t
2242 attribute_set (struct client_s *client, char **req)
2244 char **path = NULL;
2245 gpg_error_t rc;
2246 xmlNodePtr n;
2248 if (!req || !req[0] || !req[1])
2249 return GPG_ERR_SYNTAX;
2252 * Reserved attribute names.
2254 if (!strcmp (req[0], "_name"))
2255 return GPG_ERR_INV_ATTR;
2256 else if (!strcmp (req[0], "target"))
2257 return target_attribute (client, req + 1);
2258 else if (!valid_xml_attribute (req[0]))
2259 return GPG_ERR_INV_VALUE;
2261 if ((path = str_split (req[1], "\t", 0)) == NULL)
2264 * The first argument may be only a root element.
2266 if ((path = str_split (req[1], " ", 0)) == NULL)
2267 return GPG_ERR_SYNTAX;
2270 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 0);
2272 if (!n)
2273 goto fail;
2275 if (path[1])
2277 n = find_elements (client, client->doc, n->children, path + 1, &rc,
2278 NULL, NULL, NULL, 0, 0, NULL, 0);
2280 if (!n)
2281 goto fail;
2284 if (!strcmp (req[0], (char *) "_acl"))
2286 rc = is_element_owner (client, n);
2287 if (rc)
2288 goto fail;
2291 rc = add_attribute (client, n, req[0], req[2]);
2293 fail:
2294 strv_free (path);
2295 return rc;
2299 * req[0] - command
2300 * req[1] - attribute name or element path if command is LIST
2301 * req[2] - element path
2302 * req[2] - element path or value
2305 static gpg_error_t
2306 do_attr (assuan_context_t ctx, char *line)
2308 struct client_s *client = assuan_get_pointer (ctx);
2309 gpg_error_t rc = 0;
2310 char **req;
2312 req = str_split (line, " ", 4);
2313 if (!req || !req[0] || !req[1])
2315 strv_free (req);
2316 return GPG_ERR_SYNTAX;
2319 pthread_cleanup_push (req_cleanup, req);
2321 if (strcasecmp (req[0], "SET") == 0)
2322 rc = attribute_set (client, req + 1);
2323 else if (strcasecmp (req[0], "GET") == 0)
2324 rc = attribute_get (ctx, req + 1);
2325 else if (strcasecmp (req[0], "DELETE") == 0)
2326 rc = attribute_delete (client, req + 1);
2327 else if (strcasecmp (req[0], "LIST") == 0)
2328 rc = attribute_list (ctx, req + 1);
2329 else
2330 rc = GPG_ERR_SYNTAX;
2332 pthread_cleanup_pop (1);
2333 return rc;
2336 static gpg_error_t
2337 attr_command (assuan_context_t ctx, char *line)
2339 struct client_s *client = assuan_get_pointer (ctx);
2340 gpg_error_t rc;
2341 struct argv_s *args[] = {
2342 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2343 NULL
2346 rc = parse_options (&line, args, client);
2347 if (rc)
2348 return send_error (ctx, rc);
2350 if (client->opts & OPT_INQUIRE)
2352 unsigned char *result;
2353 size_t len;
2355 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2356 if (rc)
2357 return send_error (ctx, rc);
2359 pthread_cleanup_push (xfree, result);
2360 rc = do_attr (ctx, (char *)result);
2361 pthread_cleanup_pop (1);
2363 else
2364 rc = do_attr (ctx, line);
2366 return send_error (ctx, rc);
2369 static gpg_error_t
2370 parse_iscached_opt_lock (void *data, void *value)
2372 struct client_s *client = data;
2374 (void) value;
2375 client->opts |= OPT_LOCK;
2376 return 0;
2379 static gpg_error_t
2380 iscached_command (assuan_context_t ctx, char *line)
2382 struct client_s *client = assuan_get_pointer (ctx);
2383 gpg_error_t rc;
2384 struct argv_s *args[] = {
2385 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_iscached_opt_lock},
2386 NULL
2389 if (!line || !*line)
2390 return send_error (ctx, GPG_ERR_SYNTAX);
2392 rc = parse_options (&line, args, client);
2393 if (rc)
2394 return send_error (ctx, rc);
2395 else if (!valid_filename (line))
2396 return send_error (ctx, GPG_ERR_INV_VALUE);
2398 rc = cache_iscached (line, NULL);
2399 if (client->opts & OPT_LOCK
2400 && (!rc || gpg_err_code (rc) == GPG_ERR_NO_DATA))
2402 unsigned char md5file[16];
2403 gpg_error_t trc = rc;
2405 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2406 if (memcmp (md5file, client->md5file, 16))
2407 cleanup_client (client);
2409 memcpy (client->md5file, md5file, 16);
2410 rc = do_lock (client, 1);
2411 if (!rc)
2412 rc = trc;
2415 return send_error (ctx, rc);
2418 static gpg_error_t
2419 clearcache_command (assuan_context_t ctx, char *line)
2421 gpg_error_t rc = 0, all_rc = 0;
2422 unsigned char md5file[16];
2423 int i;
2424 int t;
2425 int all = 0;
2426 struct client_thread_s *once = NULL;
2428 cache_lock ();
2429 MUTEX_LOCK (&cn_mutex);
2430 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
2432 if (!line || !*line)
2433 all = 1;
2435 t = slist_length (cn_thread_list);
2437 for (i = 0; i < t; i++)
2439 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2440 assuan_peercred_t peer;
2442 if (!thd->cl)
2443 continue;
2445 /* Lock each connected clients' file mutex to prevent any other client
2446 * from accessing the cache entry (the file mutex is locked upon
2447 * command startup). The cache for the entry is not cleared if the
2448 * file mutex is locked by another client to prevent this function
2449 * from blocking.
2451 if (all)
2453 if (thd->cl->filename)
2455 rc = do_validate_peer (ctx, thd->cl->filename, &peer);
2456 all_rc = !all_rc ? rc : all_rc;
2457 if (rc)
2459 rc = 0;
2460 continue;
2464 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0, -1);
2465 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2467 if (pthread_equal (pthread_self (), thd->tid))
2468 rc = 0;
2469 else
2471 if (!thd->cl->filename ||
2472 cache_iscached (thd->cl->filename,
2473 NULL) == GPG_ERR_NO_DATA)
2475 rc = 0;
2476 continue;
2479 cache_defer_clear (thd->cl->md5file);
2482 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
2484 rc = 0;
2485 continue;
2488 if (!rc)
2490 rc = cache_clear (thd->cl->md5file);
2491 cache_unlock_mutex (thd->cl->md5file, 0);
2494 if (rc)
2495 all_rc = rc;
2497 rc = 0;
2499 /* A single data filename was specified. Lock only this data file
2500 * mutex and free the cache entry. */
2501 else
2503 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2504 rc = do_validate_peer (ctx, line, &peer);
2506 if (!rc && !memcmp (thd->cl->md5file, md5file, sizeof (md5file)))
2508 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0,
2509 -1);
2510 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2512 if (pthread_equal (pthread_self (), thd->tid))
2513 rc = 0;
2516 if (!rc)
2518 once = thd;
2519 rc = cache_clear (thd->cl->md5file);
2520 cache_unlock_mutex (thd->cl->md5file, 0);
2522 else
2524 cache_defer_clear (thd->cl->md5file);
2527 break;
2532 /* Only connected clients' cache entries have been cleared. Now clear any
2533 * remaining cache entries without clients but only if there wasn't an
2534 * error from above since this would defeat the locking check of the
2535 * remaining entries. */
2536 if (!all_rc && all)
2538 cache_clear (NULL);
2541 /* No clients are using the specified file. */
2542 else if (!all_rc && !rc && !once)
2544 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2545 rc = cache_clear (md5file);
2548 /* Release the connection mutex. */
2549 pthread_cleanup_pop (1);
2550 cache_unlock ();
2552 if (!rc)
2553 send_status_all (STATUS_CACHE, NULL);
2555 /* One or more files were locked while clearing all cache entries. */
2556 if (all_rc)
2557 rc = all_rc;
2559 return send_error (ctx, rc);
2562 static gpg_error_t
2563 cachetimeout_command (assuan_context_t ctx, char *line)
2565 int timeout;
2566 char **req = str_split (line, " ", 0);
2567 char *p;
2568 gpg_error_t rc = 0;
2569 assuan_peercred_t peer;
2571 if (!req || !*req || !req[1])
2573 strv_free (req);
2574 return send_error (ctx, GPG_ERR_SYNTAX);
2577 errno = 0;
2578 timeout = (int) strtol (req[1], &p, 10);
2579 if (errno != 0 || *p || timeout < -1)
2581 strv_free (req);
2582 return send_error (ctx, GPG_ERR_SYNTAX);
2585 rc = do_validate_peer (ctx, req[0], &peer);
2586 if (!rc)
2588 unsigned char md5file[16];
2590 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, req[0], strlen (req[0]));
2591 rc = cache_set_timeout (md5file, timeout);
2592 if (!rc || gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
2594 rc = 0;
2595 MUTEX_LOCK (&rcfile_mutex);
2596 config_set_int_param (&global_config, req[0], "cache_timeout",
2597 req[1]);
2598 MUTEX_UNLOCK (&rcfile_mutex);
2602 strv_free (req);
2603 return send_error (ctx, rc);
2606 static gpg_error_t
2607 dump_command (assuan_context_t ctx, char *line)
2609 xmlChar *xml;
2610 int len;
2611 struct client_s *client = assuan_get_pointer (ctx);
2612 gpg_error_t rc;
2614 if (disable_list_and_dump == 1)
2615 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2617 rc = peer_is_invoker(client);
2618 if (rc)
2619 return send_error (ctx, rc);
2621 xmlDocDumpFormatMemory (client->doc, &xml, &len, 1);
2623 if (!xml)
2625 log_write ("%s(%i): %s", __FILE__, __LINE__,
2626 pwmd_strerror (GPG_ERR_ENOMEM));
2627 return send_error (ctx, GPG_ERR_ENOMEM);
2630 pthread_cleanup_push (xmlFree, xml);
2631 rc = xfer_data (ctx, (char *) xml, len);
2632 pthread_cleanup_pop (1);
2633 return send_error (ctx, rc);
2636 static gpg_error_t
2637 getconfig_command (assuan_context_t ctx, char *line)
2639 struct client_s *client = assuan_get_pointer (ctx);
2640 gpg_error_t rc = 0;
2641 char filename[255] = { 0 }, param[747] = { 0 };
2642 char *p, *tmp = NULL, *fp = client->filename, *paramp = line;
2644 if (!line || !*line)
2645 return send_error (ctx, GPG_ERR_SYNTAX);
2647 if (strchr (line, ' '))
2649 sscanf (line, " %254[^ ] %746c", filename, param);
2650 paramp = param;
2651 fp = filename;
2654 if (fp && !valid_filename (fp))
2655 return send_error (ctx, GPG_ERR_INV_VALUE);
2657 paramp = str_down (paramp);
2658 if (!strcmp (paramp, "cipher") && fp)
2660 struct crypto_s *crypto = NULL;
2662 rc = init_client_crypto (&crypto);
2663 if (!rc)
2665 rc = read_data_header (fp, &crypto->hdr, NULL, NULL);
2666 if (!rc)
2668 const char *t =
2669 gcry_cipher_algo_name (cipher_to_gcrypt (crypto->hdr.flags));
2670 if (t)
2672 tmp = str_dup (t);
2673 if (tmp)
2674 str_down (tmp);
2679 UPDATE_AGENT_CTX (client, crypto);
2680 cleanup_crypto (&crypto);
2681 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
2682 return send_error (ctx, rc);
2684 if (!rc && tmp)
2685 goto done;
2687 else if (!strcmp (paramp, "cipher_iterations") && fp)
2689 struct crypto_s *crypto = NULL;
2691 rc = init_client_crypto (&crypto);
2692 if (!rc)
2694 rc = read_data_header (fp, &crypto->hdr, NULL, NULL);
2695 if (!rc)
2697 tmp = str_asprintf ("%llu",
2698 (unsigned long long) crypto->hdr.
2699 iterations);
2700 if (!tmp)
2701 rc = GPG_ERR_ENOMEM;
2705 UPDATE_AGENT_CTX (client, crypto);
2706 cleanup_crypto (&crypto);
2707 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
2708 return send_error (ctx, rc);
2710 if (!rc && tmp)
2711 goto done;
2713 else if (!strcmp (paramp, "passphrase"))
2714 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2716 p = config_get_value (fp ? fp : "global", paramp);
2717 if (!p)
2718 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2720 tmp = expand_homedir (p);
2721 xfree (p);
2722 if (!tmp)
2724 log_write ("%s(%i): %s", __FILE__, __LINE__,
2725 pwmd_strerror (GPG_ERR_ENOMEM));
2726 return send_error (ctx, GPG_ERR_ENOMEM);
2729 done:
2730 p = tmp;
2731 pthread_cleanup_push (xfree, p);
2732 rc = xfer_data (ctx, p, strlen (p));
2733 pthread_cleanup_pop (1);
2734 return send_error (ctx, rc);
2737 struct xpath_s
2739 xmlXPathContextPtr xp;
2740 xmlXPathObjectPtr result;
2741 xmlBufferPtr buf;
2742 char **req;
2745 static void
2746 xpath_command_cleanup (void *arg)
2748 struct xpath_s *xpath = arg;
2750 if (!xpath)
2751 return;
2753 req_cleanup (xpath->req);
2755 if (xpath->buf)
2756 xmlBufferFree (xpath->buf);
2758 if (xpath->result)
2759 xmlXPathFreeObject (xpath->result);
2761 if (xpath->xp)
2762 xmlXPathFreeContext (xpath->xp);
2765 static gpg_error_t
2766 do_xpath (assuan_context_t ctx, char *line)
2768 gpg_error_t rc;
2769 struct client_s *client = assuan_get_pointer (ctx);
2770 struct xpath_s _x = { 0 };
2771 struct xpath_s *xpath = &_x;
2773 if (!line || !*line)
2774 return GPG_ERR_SYNTAX;
2776 if ((xpath->req = str_split (line, "\t", 2)) == NULL)
2778 if (strv_printf (&xpath->req, "%s", line) == 0)
2779 return GPG_ERR_ENOMEM;
2782 xpath->xp = xmlXPathNewContext (client->doc);
2783 if (!xpath->xp)
2785 rc = GPG_ERR_BAD_DATA;
2786 goto fail;
2789 xpath->result =
2790 xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2791 if (!xpath->result)
2793 rc = GPG_ERR_BAD_DATA;
2794 goto fail;
2797 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2799 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2800 goto fail;
2803 rc = recurse_xpath_nodeset (client, client->doc, xpath->result->nodesetval,
2804 (xmlChar *) xpath->req[1], &xpath->buf, 0,
2805 NULL);
2806 if (rc)
2807 goto fail;
2808 else if (!xpath->req[1] && !xmlBufferLength (xpath->buf))
2810 rc = GPG_ERR_NO_DATA;
2811 goto fail;
2813 else if (xpath->req[1])
2815 rc = 0;
2816 goto fail;
2819 pthread_cleanup_push (xpath_command_cleanup, &xpath);
2820 rc = xfer_data (ctx, (char *) xmlBufferContent (xpath->buf),
2821 xmlBufferLength (xpath->buf));
2822 pthread_cleanup_pop (0);
2823 fail:
2824 xpath_command_cleanup (xpath);
2825 return rc;
2828 static gpg_error_t
2829 xpath_command (assuan_context_t ctx, char *line)
2831 struct client_s *client = assuan_get_pointer (ctx);
2832 gpg_error_t rc;
2833 struct argv_s *args[] = {
2834 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2835 NULL
2838 if (disable_list_and_dump == 1)
2839 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2841 rc = peer_is_invoker(client);
2842 if (rc)
2843 return send_error (ctx, rc);
2845 rc = parse_options (&line, args, client);
2846 if (rc)
2847 return send_error (ctx, rc);
2849 if (client->opts & OPT_INQUIRE)
2851 unsigned char *result;
2852 size_t len;
2854 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2855 if (rc)
2856 return send_error (ctx, rc);
2858 pthread_cleanup_push (xfree, result);
2859 rc = do_xpath (ctx, (char *)result);
2860 pthread_cleanup_pop (1);
2862 else
2863 rc = do_xpath (ctx, line);
2865 return send_error (ctx, rc);
2868 static gpg_error_t
2869 do_xpathattr (assuan_context_t ctx, char *line)
2871 struct client_s *client = assuan_get_pointer (ctx);
2872 gpg_error_t rc;
2873 char **req = NULL;
2874 int cmd = 0; //SET
2875 struct xpath_s _x = { 0 };
2876 struct xpath_s *xpath = &_x;
2878 if (!line || !*line)
2879 return GPG_ERR_SYNTAX;
2881 if ((req = str_split (line, " ", 3)) == NULL)
2882 return GPG_ERR_ENOMEM;
2884 if (!req[0])
2886 rc = GPG_ERR_SYNTAX;
2887 goto fail;
2890 if (!strcasecmp (req[0], "SET"))
2891 cmd = 0;
2892 else if (!strcasecmp (req[0], "DELETE"))
2893 cmd = 1;
2894 else
2896 rc = GPG_ERR_SYNTAX;
2897 goto fail;
2900 if (!req[1] || !req[2])
2902 rc = GPG_ERR_SYNTAX;
2903 goto fail;
2906 if ((xpath->req = str_split (req[2], "\t", 3)) == NULL)
2908 rc = GPG_ERR_ENOMEM;
2909 goto fail;
2912 if (!xpath->req[0] || (!xpath->req[1] && !cmd) || (xpath->req[1] && cmd))
2914 rc = GPG_ERR_SYNTAX;
2915 goto fail;
2918 xpath->xp = xmlXPathNewContext (client->doc);
2919 if (!xpath->xp)
2921 rc = GPG_ERR_BAD_DATA;
2922 goto fail;
2925 xpath->result = xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2926 if (!xpath->result)
2928 rc = GPG_ERR_BAD_DATA;
2929 goto fail;
2932 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2934 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2935 goto fail;
2938 rc = recurse_xpath_nodeset (client, client->doc, xpath->result->nodesetval,
2939 (xmlChar *) xpath->req[1], &xpath->buf, cmd,
2940 (xmlChar *) req[1]);
2942 fail:
2943 xpath_command_cleanup (xpath);
2944 strv_free (req);
2945 return rc;
2948 /* XPATHATTR SET|DELETE <name> <expression>[<TAB>[value]] */
2949 static gpg_error_t
2950 xpathattr_command (assuan_context_t ctx, char *line)
2952 struct client_s *client = assuan_get_pointer (ctx);
2953 gpg_error_t rc;
2954 struct argv_s *args[] = {
2955 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2956 NULL
2959 if (disable_list_and_dump == 1)
2960 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2962 rc = peer_is_invoker(client);
2963 if (rc)
2964 return send_error (ctx, rc);
2966 rc = parse_options (&line, args, client);
2967 if (rc)
2968 return send_error (ctx, rc);
2970 if (client->opts & OPT_INQUIRE)
2972 unsigned char *result;
2973 size_t len;
2975 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2976 if (rc)
2977 return send_error (ctx, rc);
2979 pthread_cleanup_push (xfree, result);
2980 rc = do_xpathattr (ctx, (char *)result);
2981 pthread_cleanup_pop (1);
2983 else
2984 rc = do_xpathattr (ctx, line);
2986 return send_error (ctx, rc);
2989 static gpg_error_t
2990 do_import (struct client_s *client, const char *root_element,
2991 unsigned char *content)
2993 char **dst_path = NULL;
2994 xmlDocPtr doc = NULL;
2995 xmlNodePtr n, root, copy;
2996 gpg_error_t rc;
2998 if (!content || !*content)
3000 xfree (content);
3001 return GPG_ERR_SYNTAX;
3004 if (root_element)
3005 dst_path = str_split (root_element, "\t", 0);
3007 if (dst_path && !valid_element_path (dst_path, 0))
3009 if (dst_path)
3010 strv_free (dst_path);
3012 return GPG_ERR_INV_VALUE;
3015 struct string_s *str = string_new_content ((char *)content);
3016 str = string_prepend (str, "<pwmd>");
3017 str = string_append (str, "</pwmd>");
3018 doc = xmlReadDoc ((xmlChar *) str->str, NULL, "UTF-8", XML_PARSE_NOBLANKS);
3019 string_free (str, 1);
3020 if (!doc)
3022 rc = GPG_ERR_BAD_DATA;
3023 goto fail;
3026 root = xmlDocGetRootElement (doc);
3027 xmlNodePtr root_orig = root->children;
3028 root = root->children;
3029 rc = validate_import (client, root);
3030 if (rc)
3031 goto fail;
3035 again:
3036 if (dst_path)
3038 char **path = strv_dup (dst_path);
3039 if (!path)
3041 log_write ("%s(%i): %s", __FILE__, __LINE__,
3042 pwmd_strerror (GPG_ERR_ENOMEM));
3043 rc = GPG_ERR_ENOMEM;
3044 goto fail;
3047 xmlChar *a = xmlGetProp (root, (xmlChar *) "_name");
3048 if (!a)
3050 strv_free (path);
3051 rc = GPG_ERR_INV_VALUE;
3052 goto fail;
3055 if (strv_printf (&path, "%s", (char *) a) == 0)
3057 xmlFree (a);
3058 rc = GPG_ERR_ENOMEM;
3059 goto fail;
3062 xmlFree (a);
3063 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 0);
3064 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3066 strv_free (path);
3067 goto fail;
3070 if (!rc)
3072 n = find_elements (client, client->doc, n->children, path + 1, &rc,
3073 NULL, NULL, NULL, 0, 0, NULL, 1);
3074 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3076 strv_free (path);
3077 goto fail;
3079 else if (!rc)
3081 xmlUnlinkNode (n);
3082 xmlFreeNode (n);
3083 strv_free (path);
3084 path = NULL;
3085 goto again;
3089 if (rc == GPG_ERR_ELEMENT_NOT_FOUND)
3091 n = create_element_path (client, &path, &rc, NULL);
3092 if (rc)
3093 goto fail;
3096 if (root->children)
3098 copy = xmlCopyNodeList (root->children);
3099 n = xmlAddChildList (n, copy);
3100 if (!n)
3101 rc = GPG_ERR_ENOMEM;
3104 strv_free (path);
3106 else
3108 char **path = NULL;
3110 /* Check if the content root element can create a DTD root element. */
3111 if (!xmlStrEqual ((xmlChar *) "element", root->name))
3113 rc = GPG_ERR_SYNTAX;
3114 goto fail;
3117 xmlChar *a;
3119 if ((a = xmlGetProp (root, (xmlChar *) "_name")) == NULL)
3121 rc = GPG_ERR_SYNTAX;
3122 goto fail;
3125 char *tmp = str_dup ((char *) a);
3126 xmlFree (a);
3127 int literal = is_literal_element (&tmp);
3129 if (!valid_xml_element ((xmlChar *) tmp) || literal)
3131 xfree (tmp);
3132 rc = GPG_ERR_INV_VALUE;
3133 goto fail;
3136 if (strv_printf (&path, "%s", tmp) == 0)
3138 xfree (tmp);
3139 rc = GPG_ERR_ENOMEM;
3140 goto fail;
3143 xfree (tmp);
3144 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 1);
3145 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3147 rc = GPG_ERR_BAD_DATA;
3148 goto fail;
3151 /* Overwriting the existing tree. */
3152 if (!rc)
3154 xmlUnlinkNode (n);
3155 xmlFreeNodeList (n);
3158 rc = 0;
3159 xmlSetProp (root, (xmlChar *) "_name", (xmlChar *) path[0]);
3160 n = xmlCopyNode (root, 1);
3161 n = xmlAddChildList (xmlDocGetRootElement (client->doc), n);
3162 strv_free (path);
3165 if (n && !rc)
3166 rc = update_element_mtime (client, n->parent);
3168 for (root = root_orig->next; root; root = root->next)
3170 if (root->type == XML_ELEMENT_NODE)
3171 break;
3174 root_orig = root;
3176 while (root);
3178 fail:
3179 if (doc)
3180 xmlFreeDoc (doc);
3182 if (dst_path)
3183 strv_free (dst_path);
3185 return rc;
3188 static gpg_error_t
3189 parse_import_opt_root (void *data, void *value)
3191 struct client_s *client = data;
3193 client->import_root = str_dup (value);
3194 return client->import_root ? 0 : GPG_ERR_ENOMEM;
3197 static gpg_error_t
3198 import_command (assuan_context_t ctx, char *line)
3200 gpg_error_t rc;
3201 struct client_s *client = assuan_get_pointer (ctx);
3202 unsigned char *result;
3203 size_t len;
3204 struct argv_s *args[] = {
3205 &(struct argv_s) {"root", OPTION_TYPE_ARG, parse_import_opt_root},
3206 NULL
3209 xfree (client->import_root);
3210 client->import_root = NULL;
3211 rc = parse_options (&line, args, client);
3212 if (rc)
3213 return send_error (ctx, rc);
3215 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3216 if (rc)
3218 xfree (client->import_root);
3219 client->import_root = NULL;
3220 return send_error (ctx, rc);
3223 rc = do_import (client, client->import_root, result);
3224 xfree (client->import_root);
3225 client->import_root = NULL;
3226 return send_error (ctx, rc);
3229 static gpg_error_t
3230 do_lock (struct client_s *client, int add)
3232 gpg_error_t rc = lock_file_mutex (client, add);
3234 if (!rc)
3235 client->flags |= FLAG_LOCK_CMD;
3237 return rc;
3240 static gpg_error_t
3241 lock_command (assuan_context_t ctx, char *line)
3243 struct client_s *client = assuan_get_pointer (ctx);
3244 gpg_error_t rc = do_lock (client, 0);
3246 return send_error (ctx, rc);
3249 static gpg_error_t
3250 unlock_command (assuan_context_t ctx, char *line)
3252 struct client_s *client = assuan_get_pointer (ctx);
3253 gpg_error_t rc;
3255 rc = unlock_file_mutex (client, 0);
3256 return send_error (ctx, rc);
3259 static gpg_error_t
3260 option_command (assuan_context_t ctx, char *line)
3262 struct client_s *client = assuan_get_pointer (ctx);
3263 gpg_error_t rc = 0;
3264 struct pinentry_option_s *pin_opts = &client->pinentry_opts;
3265 #ifdef WITH_AGENT
3266 struct agent_s *agent = client->crypto->agent;
3267 #endif
3268 char namebuf[255] = { 0 };
3269 char *name = namebuf;
3270 char *value = NULL, *p, *tmp = NULL;
3272 p = strchr (line, '=');
3273 if (!p)
3274 strncpy (namebuf, line, sizeof(namebuf));
3275 else
3277 strncpy (namebuf, line, strlen (line)-strlen (p));
3278 value = p+1;
3281 log_write1 ("OPTION name='%s' value='%s'", name, value);
3283 if (strcasecmp (name, (char *) "log_level") == 0)
3285 long l = 0;
3287 if (value)
3289 l = strtol (value, NULL, 10);
3291 if (l < 0 || l > 2)
3292 return send_error (ctx, GPG_ERR_INV_VALUE);
3295 MUTEX_LOCK (&rcfile_mutex);
3296 config_set_int_param (&global_config, "global", "log_level", value);
3297 MUTEX_UNLOCK (&rcfile_mutex);
3298 goto done;
3300 else if (strcasecmp (name, (char *) "lock-timeout") == 0)
3302 long n = 0;
3304 if (value)
3306 n = strtol (value, &tmp, 10);
3307 if (tmp && *tmp)
3308 return send_error (ctx, GPG_ERR_INV_VALUE);
3311 client->lock_timeout = n;
3312 goto done;
3314 else if (strcasecmp (name, (char *) "NAME") == 0)
3316 if (value && strchr (value, ' '))
3317 rc = GPG_ERR_INV_VALUE;
3318 else
3320 tmp = pthread_getspecific (thread_name_key);
3321 xfree (tmp);
3322 MUTEX_LOCK (&cn_mutex);
3323 xfree (client->thd->name);
3324 client->thd->name = NULL;
3326 if (!value || !*value)
3327 pthread_setspecific (thread_name_key, str_dup (""));
3328 else
3330 client->thd->name = str_dup (value);
3331 pthread_setspecific (thread_name_key, str_dup (value));
3334 MUTEX_UNLOCK (&cn_mutex);
3336 goto done;
3338 else if (strcasecmp (name, (char *) "lc-messages") == 0)
3340 xfree (pin_opts->lc_messages);
3341 pin_opts->lc_messages = NULL;
3342 if (value && *value)
3343 pin_opts->lc_messages = str_dup (value);
3344 #ifdef WITH_AGENT
3345 if (use_agent)
3346 rc = set_agent_option (client->crypto->agent, "lc-messages", value);
3347 #endif
3349 else if (strcasecmp (name, (char *) "lc-ctype") == 0)
3351 xfree (pin_opts->lc_ctype);
3352 pin_opts->lc_ctype = NULL;
3353 if (value && *value)
3354 pin_opts->lc_ctype = str_dup (value);
3355 #ifdef WITH_AGENT
3356 if (use_agent)
3357 rc = set_agent_option (client->crypto->agent, "lc-ctype", value);
3358 #endif
3360 else if (strcasecmp (name, (char *) "ttyname") == 0)
3362 xfree (pin_opts->ttyname);
3363 pin_opts->ttyname = NULL;
3364 if (value && *value)
3365 pin_opts->ttyname = str_dup (value);
3366 #ifdef WITH_AGENT
3367 if (use_agent)
3368 rc = set_agent_option (client->crypto->agent, "ttyname", value);
3369 #endif
3371 else if (strcasecmp (name, (char *) "ttytype") == 0)
3373 xfree (pin_opts->ttytype);
3374 pin_opts->ttytype = NULL;
3375 if (value && *value)
3376 pin_opts->ttytype = str_dup (value);
3377 #ifdef WITH_AGENT
3378 if (use_agent)
3379 rc = set_agent_option (client->crypto->agent, "ttytype", value);
3380 #endif
3382 else if (strcasecmp (name, (char *) "display") == 0)
3384 xfree (pin_opts->display);
3385 pin_opts->display = NULL;
3386 if (value && *value)
3387 pin_opts->display = str_dup (value);
3388 #ifdef WITH_AGENT
3389 if (use_agent)
3390 rc = set_agent_option (client->crypto->agent, "display", value);
3391 #endif
3393 else if (strcasecmp (name, (char *) "pinentry-desc") == 0)
3395 xfree (pin_opts->desc);
3396 pin_opts->desc = NULL;
3397 if (value && *value)
3398 pin_opts->desc = str_dup (value);
3400 else if (strcasecmp (name, (char *) "pinentry-title") == 0)
3402 xfree (pin_opts->title);
3403 pin_opts->title = NULL;
3404 if (value && *value)
3405 pin_opts->title = str_dup (value);
3407 else if (strcasecmp (name, (char *) "pinentry-prompt") == 0)
3409 xfree (pin_opts->prompt);
3410 pin_opts->prompt = NULL;
3411 if (value && *value)
3412 pin_opts->prompt = str_dup (value);
3415 else if (strcasecmp (name, "pinentry-timeout") == 0)
3417 char *p = NULL;
3418 int n;
3420 if (!value)
3421 goto done;
3423 n = (int) strtol (value, &p, 10);
3425 if (*p || n < 0)
3426 return send_error (ctx, GPG_ERR_INV_VALUE);
3428 pin_opts->timeout = n;
3429 MUTEX_LOCK (&rcfile_mutex);
3430 config_set_int_param (&global_config,
3431 client->filename ? client->filename : "global",
3432 "pinentry_timeout", value);
3433 MUTEX_UNLOCK (&rcfile_mutex);
3434 goto done;
3436 else if (strcasecmp (name, "disable-pinentry") == 0)
3438 int n = 1;
3440 if (value && *value)
3442 n = (int) strtol (value, &tmp, 10);
3443 if (*tmp || n < 0 || n > 1)
3444 return send_error (ctx, GPG_ERR_INV_VALUE);
3447 if (n)
3448 client->flags |= FLAG_NO_PINENTRY;
3449 else
3450 client->flags &= ~FLAG_NO_PINENTRY;
3452 #ifdef WITH_AGENT
3453 if (use_agent)
3455 if (client->flags & FLAG_NO_PINENTRY)
3456 rc = set_agent_option (client->crypto->agent, "pinentry-mode",
3457 "loopback");
3458 else
3459 rc = set_agent_option (client->crypto->agent, "pinentry-mode",
3460 "ask");
3462 if (rc)
3463 return send_error (ctx, rc);
3465 #endif
3467 else
3468 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
3470 done:
3471 #ifdef WITH_AGENT
3472 if (!rc && use_agent && agent)
3474 rc = pinentry_merge_options (&client->crypto->agent->pinentry_opts,
3475 pin_opts);
3477 #endif
3479 return send_error (ctx, rc);
3482 static gpg_error_t
3483 do_rename (assuan_context_t ctx, char *line)
3485 struct client_s *client = assuan_get_pointer (ctx);
3486 gpg_error_t rc;
3487 char **req, **src, *dst;
3488 xmlNodePtr n, ndst;
3490 req = str_split (line, " ", 0);
3492 if (!req || !req[0] || !req[1])
3494 strv_free (req);
3495 return GPG_ERR_SYNTAX;
3498 dst = req[1];
3499 is_literal_element (&dst);
3501 if (!valid_xml_element ((xmlChar *) dst))
3503 strv_free (req);
3504 return GPG_ERR_INV_VALUE;
3507 if (strchr (req[0], '\t'))
3508 src = str_split (req[0], "\t", 0);
3509 else
3510 src = str_split (req[0], " ", 0);
3512 if (!src || !*src)
3514 rc = GPG_ERR_SYNTAX;
3515 goto fail;
3518 n = find_root_element (client, client->doc, &src, &rc, NULL, 0, 0);
3519 if (src[1] && n)
3520 n = find_elements (client, client->doc, n->children, src + 1, &rc, NULL, NULL,
3521 NULL, 0, 0, NULL, 0);
3523 if (!n)
3524 goto fail;
3526 rc = is_element_owner (client, n);
3527 if (rc)
3528 goto fail;
3530 xmlChar *a = xmlGetProp (n, (xmlChar *) "_name");
3531 if (!a)
3533 rc = GPG_ERR_ENOMEM;
3534 goto fail;
3537 /* To prevent unwanted effects:
3539 * <root name="a"><b/></root>
3541 * RENAME a<TAB>b b
3543 if (xmlStrEqual (a, (xmlChar *) dst))
3545 xmlFree (a);
3546 rc = GPG_ERR_AMBIGUOUS_NAME;
3547 goto fail;
3550 xmlFree (a);
3551 char **tmp = NULL;
3552 if (src[1])
3554 char **p;
3556 for (p = src; *p; p++)
3558 if (!*(p + 1))
3559 break;
3560 strv_printf (&tmp, "%s", *p);
3564 strv_printf (&tmp, "!%s", dst);
3565 ndst = find_root_element (client, client->doc, &tmp, &rc, NULL, 0, 0);
3566 if (!ndst && rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3568 strv_free (tmp);
3569 goto fail;
3572 if (tmp[1] && ndst)
3573 ndst = find_elements (client, client->doc, ndst->children, tmp + 1, &rc, NULL,
3574 NULL, NULL, 0, 0, NULL, 0);
3576 strv_free (tmp);
3577 if (!ndst && rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3578 goto fail;
3580 rc = 0;
3582 /* Target may exist:
3584 * <root name="a"/>
3585 * <root name="b" target="a"/>
3587 * RENAME b a
3589 * Would need to do:
3590 * RENAME !b a
3592 if (ndst == n)
3594 rc = GPG_ERR_AMBIGUOUS_NAME;
3595 goto fail;
3598 if (ndst)
3600 rc = is_element_owner (client, ndst);
3601 if (rc)
3602 goto fail;
3604 unlink_node (client, ndst);
3605 xmlFreeNodeList (ndst);
3608 rc = add_attribute (client, n, "_name", dst);
3610 fail:
3611 strv_free (req);
3612 strv_free (src);
3613 return rc;
3616 static gpg_error_t
3617 rename_command (assuan_context_t ctx, char *line)
3619 struct client_s *client = assuan_get_pointer (ctx);
3620 gpg_error_t rc;
3621 struct argv_s *args[] = {
3622 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3623 NULL
3626 rc = parse_options (&line, args, client);
3627 if (rc)
3628 return send_error (ctx, rc);
3630 if (client->opts & OPT_INQUIRE)
3632 unsigned char *result;
3633 size_t len;
3635 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3636 if (rc)
3637 return send_error (ctx, rc);
3639 pthread_cleanup_push (xfree, result);
3640 rc = do_rename (ctx, (char *)result);
3641 pthread_cleanup_pop (1);
3643 else
3644 rc = do_rename (ctx, line);
3646 return send_error (ctx, rc);
3649 static gpg_error_t
3650 do_copy (assuan_context_t ctx, char *line)
3652 struct client_s *client = assuan_get_pointer (ctx);
3653 gpg_error_t rc;
3654 char **req, **src = NULL, **dst = NULL;
3655 xmlNodePtr nsrc, ndst, new = NULL;
3657 req = str_split (line, " ", 0);
3658 if (!req || !req[0] || !req[1])
3660 strv_free (req);
3661 return GPG_ERR_SYNTAX;
3664 if (strchr (req[0], '\t'))
3665 src = str_split (req[0], "\t", 0);
3666 else
3667 src = str_split (req[0], " ", 0);
3669 if (!src || !*src)
3671 rc = GPG_ERR_SYNTAX;
3672 goto fail;
3675 if (strchr (req[1], '\t'))
3676 dst = str_split (req[1], "\t", 0);
3677 else
3678 dst = str_split (req[1], " ", 0);
3680 if (!dst || !*dst)
3682 rc = GPG_ERR_SYNTAX;
3683 goto fail;
3686 if (!valid_element_path (dst, 0))
3688 rc = GPG_ERR_INV_VALUE;
3689 goto fail;
3692 nsrc = find_root_element (client, client->doc, &src, &rc, NULL, 0, 0);
3693 if (nsrc && src[1])
3694 nsrc = find_elements (client, client->doc, nsrc->children, src + 1, &rc, NULL,
3695 NULL, NULL, 0, 0, NULL, 0);
3697 if (!nsrc)
3698 goto fail;
3700 new = xmlCopyNodeList (nsrc);
3701 if (!new)
3703 rc = GPG_ERR_ENOMEM;
3704 goto fail;
3707 int create = 0;
3708 ndst = find_root_element (client, client->doc, &dst, &rc, NULL, 0, 0);
3709 if (ndst && dst[1])
3711 if (ndst->children)
3712 ndst = find_elements (client, client->doc, ndst->children, dst + 1, &rc, NULL,
3713 NULL, create_target_elements_cb, 0, 0, NULL, 0);
3714 else
3715 create = 1;
3717 else
3718 create = 1;
3720 if (!ndst && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3721 goto fail;
3722 else if (!ndst || create)
3724 ndst = create_element_path (client, &dst, &rc, NULL);
3725 if (!ndst)
3726 goto fail;
3729 rc = is_element_owner (client, ndst);
3730 if (rc)
3731 goto fail;
3733 /* Merge any attributes from the src node to the initial dst node. */
3734 for (xmlAttrPtr attr = new->properties; attr; attr = attr->next)
3736 if (xmlStrEqual (attr->name, (xmlChar *) "_name"))
3737 continue;
3739 xmlAttrPtr a = xmlHasProp (ndst, attr->name);
3740 if (a)
3741 xmlRemoveProp (a);
3743 xmlChar *tmp = xmlNodeGetContent (attr->children);
3744 xmlNewProp (ndst, attr->name, tmp);
3745 xmlFree (tmp);
3746 rc = add_attribute (client, ndst, NULL, NULL);
3749 xmlNodePtr n = ndst->children;
3750 xmlUnlinkNode (n);
3751 xmlFreeNodeList (n);
3752 ndst->children = NULL;
3754 if (new->children)
3756 n = xmlCopyNodeList (new->children);
3757 if (!n)
3759 rc = GPG_ERR_ENOMEM;
3760 goto fail;
3763 n = xmlAddChildList (ndst, n);
3764 if (!n)
3766 rc = GPG_ERR_ENOMEM;
3767 goto fail;
3770 rc = update_element_mtime (client, xmlDocGetRootElement (client->doc) ==
3771 ndst->parent ? ndst : ndst->parent);
3774 fail:
3775 if (new)
3777 xmlUnlinkNode (new);
3778 xmlFreeNodeList (new);
3781 if (req)
3782 strv_free (req);
3784 if (src)
3785 strv_free (src);
3787 if (dst)
3788 strv_free (dst);
3790 return rc;
3793 static gpg_error_t
3794 copy_command (assuan_context_t ctx, char *line)
3796 struct client_s *client = assuan_get_pointer (ctx);
3797 gpg_error_t rc;
3798 struct argv_s *args[] = {
3799 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3800 NULL
3803 rc = parse_options (&line, args, client);
3804 if (rc)
3805 return send_error (ctx, rc);
3807 if (client->opts & OPT_INQUIRE)
3809 unsigned char *result;
3810 size_t len;
3812 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3813 if (rc)
3814 return send_error (ctx, rc);
3816 pthread_cleanup_push (xfree, result);
3817 rc = do_copy (ctx, (char *)result);
3818 pthread_cleanup_pop (1);
3820 else
3821 rc = do_copy (ctx, line);
3823 return send_error (ctx, rc);
3826 static gpg_error_t
3827 do_move (assuan_context_t ctx, char *line)
3829 struct client_s *client = assuan_get_pointer (ctx);
3830 gpg_error_t rc;
3831 char **req, **src = NULL, **dst = NULL;
3832 xmlNodePtr nsrc, ndst = NULL;
3834 req = str_split (line, " ", 0);
3836 if (!req || !req[0] || !req[1])
3838 strv_free (req);
3839 return GPG_ERR_SYNTAX;
3842 if (strchr (req[0], '\t'))
3843 src = str_split (req[0], "\t", 0);
3844 else
3845 src = str_split (req[0], " ", 0);
3847 if (!src || !*src)
3849 rc = GPG_ERR_SYNTAX;
3850 goto fail;
3853 if (strchr (req[1], '\t'))
3854 dst = str_split (req[1], "\t", 0);
3855 else
3856 dst = str_split (req[1], " ", 0);
3858 nsrc = find_root_element (client, client->doc, &src, &rc, NULL, 0, 0);
3859 if (nsrc && src[1])
3860 nsrc = find_elements (client, client->doc, nsrc->children, src + 1, &rc,
3861 NULL, NULL, NULL, 0, 0, NULL, 0);
3863 if (!nsrc)
3864 goto fail;
3866 rc = is_element_owner (client, nsrc);
3867 if (rc)
3868 goto fail;
3870 if (dst)
3872 if (!valid_element_path (dst, 0))
3874 rc = GPG_ERR_INV_VALUE;
3875 goto fail;
3878 ndst = find_root_element (client, client->doc, &dst, &rc, NULL, 0, 0);
3879 if (ndst && dst[1])
3880 ndst = find_elements (client, client->doc, ndst->children, dst + 1,
3881 &rc, NULL, NULL, NULL, 0, 0, NULL, 0);
3883 else
3884 ndst = xmlDocGetRootElement (client->doc);
3886 for (xmlNodePtr n = ndst; n; n = n->parent)
3888 if (n == nsrc)
3890 rc = GPG_ERR_CONFLICT;
3891 goto fail;
3895 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3896 goto fail;
3898 rc = 0;
3900 if (ndst)
3902 xmlChar *a = node_has_attribute (nsrc, (xmlChar *) "_name");
3904 xmlNodePtr dup = find_element (client, ndst->children, (char *) a,
3905 NULL, &rc);
3906 xmlFree (a);
3908 if (rc)
3909 goto fail;
3911 if (dup)
3913 if (dup == nsrc)
3914 goto fail;
3916 if (ndst == xmlDocGetRootElement (client->doc))
3918 xmlNodePtr n = nsrc;
3919 int match = 0;
3921 while (n->parent && n->parent != ndst)
3922 n = n->parent;
3924 xmlChar *a = node_has_attribute (n, (xmlChar *) "_name");
3925 xmlChar *b = node_has_attribute (nsrc, (xmlChar *) "_name");
3927 if (xmlStrEqual (a, b))
3929 match = 1;
3930 xmlUnlinkNode (nsrc);
3931 xmlUnlinkNode (n);
3932 xmlFreeNodeList (n);
3935 xmlFree (a);
3936 xmlFree (b);
3938 if (!match)
3940 xmlUnlinkNode (dup);
3941 xmlFreeNodeList (dup);
3944 else
3945 xmlUnlinkNode (dup);
3949 if (!ndst && dst)
3951 xmlChar *name = node_has_attribute (nsrc, (xmlChar *) "_name");
3953 if (nsrc->parent == xmlDocGetRootElement (client->doc)
3954 && !strcmp ((char *) name, *dst))
3956 xmlFree (name);
3957 rc = GPG_ERR_CONFLICT;
3958 goto fail;
3961 xmlFree (name);
3962 ndst = create_element_path (client, &dst, &rc, nsrc);
3965 if (!ndst)
3966 goto fail;
3968 update_element_mtime (client, nsrc->parent);
3969 xmlUnlinkNode (nsrc);
3970 ndst = xmlAddChildList (ndst, nsrc);
3972 if (!ndst)
3973 rc = GPG_ERR_ENOMEM;
3974 else
3975 update_element_mtime (client, ndst->parent);
3977 fail:
3978 if (req)
3979 strv_free (req);
3981 if (src)
3982 strv_free (src);
3984 if (dst)
3985 strv_free (dst);
3987 return rc;
3990 static gpg_error_t
3991 move_command (assuan_context_t ctx, char *line)
3993 struct client_s *client = assuan_get_pointer (ctx);
3994 gpg_error_t rc;
3995 struct argv_s *args[] = {
3996 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3997 NULL
4000 rc = parse_options (&line, args, client);
4001 if (rc)
4002 return send_error (ctx, rc);
4004 if (client->opts & OPT_INQUIRE)
4006 unsigned char *result;
4007 size_t len;
4009 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
4010 if (rc)
4011 return send_error (ctx, rc);
4013 pthread_cleanup_push (xfree, result);
4014 rc = do_move (ctx, (char *)result);
4015 pthread_cleanup_pop (1);
4017 else
4018 rc = do_move (ctx, line);
4020 return send_error (ctx, rc);
4023 static gpg_error_t
4024 ls_command (assuan_context_t ctx, char *line)
4026 gpg_error_t rc;
4027 char *tmp = str_asprintf ("%s/data", homedir);
4028 char *dir = expand_homedir (tmp);
4029 DIR *d = opendir (dir);
4031 rc = gpg_error_from_errno (errno);
4032 xfree (tmp);
4034 if (!d)
4036 xfree (dir);
4037 return send_error (ctx, rc);
4040 size_t len =
4041 offsetof (struct dirent, d_name) +pathconf (dir, _PC_NAME_MAX) + 1;
4042 struct dirent *p = xmalloc (len), *cur = NULL;
4043 char *list = NULL;
4045 xfree (dir);
4046 pthread_cleanup_push (xfree, p);
4047 pthread_cleanup_push ((void *)(void *)closedir, d);
4048 rc = 0;
4050 while (!readdir_r (d, p, &cur) && cur)
4052 if (cur->d_name[0] == '.' && cur->d_name[1] == '\0')
4053 continue;
4054 else if (cur->d_name[0] == '.' && cur->d_name[1] == '.'
4055 && cur->d_name[2] == '\0')
4056 continue;
4058 tmp = str_asprintf ("%s%s\n", list ? list : "", cur->d_name);
4060 if (!tmp)
4062 if (list)
4063 xfree (list);
4065 rc = GPG_ERR_ENOMEM;
4066 break;
4069 xfree (list);
4070 list = tmp;
4073 pthread_cleanup_pop (1); // closedir (d)
4074 pthread_cleanup_pop (1); // xfree (p)
4076 if (rc)
4077 return send_error (ctx, rc);
4079 if (!list)
4080 return send_error (ctx, GPG_ERR_NO_DATA);
4082 list[strlen (list) - 1] = 0;
4083 pthread_cleanup_push (xfree, list);
4084 rc = xfer_data (ctx, list, strlen (list));
4085 pthread_cleanup_pop (1);
4086 return send_error (ctx, rc);
4089 static gpg_error_t
4090 bye_notify (assuan_context_t ctx, char *line)
4092 struct client_s *cl = assuan_get_pointer (ctx);
4094 cl->thd->state = CLIENT_STATE_DISCON;
4096 #ifdef WITH_GNUTLS
4097 if (cl->thd->remote)
4099 int rc;
4103 struct timeval tv = { 0, 50000 };
4105 rc = gnutls_bye (cl->thd->tls->ses, GNUTLS_SHUT_RDWR);
4106 if (rc == GNUTLS_E_AGAIN)
4107 select (0, NULL, NULL, NULL, &tv);
4109 while (rc == GNUTLS_E_AGAIN);
4111 #endif
4113 /* This will let assuan_process_next() return. */
4114 fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK);
4115 cl->last_rc = 0; // BYE command result
4116 return 0;
4119 static gpg_error_t
4120 reset_notify (assuan_context_t ctx, char *line)
4122 struct client_s *client = assuan_get_pointer (ctx);
4124 if (client)
4125 cleanup_client (client);
4127 return 0;
4131 * This is called before every Assuan command.
4133 static gpg_error_t
4134 command_startup (assuan_context_t ctx, const char *name)
4136 struct client_s *client = assuan_get_pointer (ctx);
4137 gpg_error_t rc;
4138 struct command_table_s *cmd = NULL;
4140 log_write1 ("command='%s'", name);
4141 client->last_rc = client->opts = 0;
4143 for (int i = 0; command_table[i]; i++)
4145 if (!strcasecmp (name, command_table[i]->name))
4147 if (command_table[i]->ignore_startup)
4148 return 0;
4149 cmd = command_table[i];
4150 break;
4154 client->last_rc = rc = gpg_error (file_modified (client, cmd));
4155 if (!rc)
4156 update_client_state (client, CLIENT_STATE_COMMAND);
4158 return rc;
4162 * This is called after every Assuan command.
4164 static void
4165 command_finalize (assuan_context_t ctx, gpg_error_t rc)
4167 struct client_s *client = assuan_get_pointer (ctx);
4169 if (!(client->flags & FLAG_LOCK_CMD))
4170 unlock_file_mutex (client, 0);
4172 log_write1 (_("command completed: rc=%u"), rc ? rc : client->last_rc);
4173 client->last_rc = gpg_error (GPG_ERR_UNKNOWN_COMMAND);
4174 #ifdef WITH_GNUTLS
4175 client->thd->buffer_timeout = client->thd->last_buffer_size = 0;
4176 #endif
4177 update_client_state (client, CLIENT_STATE_IDLE);
4180 static gpg_error_t
4181 help_command (assuan_context_t ctx, char *line)
4183 gpg_error_t rc;
4184 int i;
4186 if (!line || !*line)
4188 char *tmp;
4189 char *help = str_dup (_("Usage: HELP [<COMMAND>]\n"
4190 "For commands that take an element path as an argument, each element is "
4191 "separated with an ASCII @key{TAB} character (ASCII 0x09)."
4192 "\n" "COMMANDS:"));
4194 for (i = 0; command_table[i]; i++)
4196 if (!command_table[i]->help)
4197 continue;
4199 tmp = str_asprintf ("%s %s", help, command_table[i]->name);
4200 xfree (help);
4201 help = tmp;
4204 tmp = strip_texi_and_wrap (help);
4205 xfree (help);
4206 pthread_cleanup_push (xfree, tmp);
4207 rc = xfer_data (ctx, tmp, strlen (tmp));
4208 pthread_cleanup_pop (1);
4209 return send_error (ctx, rc);
4212 for (i = 0; command_table[i]; i++)
4214 if (!strcasecmp (line, command_table[i]->name))
4216 char *help, *tmp;
4218 if (!command_table[i]->help)
4219 break;
4221 help = strip_texi_and_wrap (command_table[i]->help);
4222 tmp = str_asprintf (_("Usage: %s"), help);
4223 xfree (help);
4224 pthread_cleanup_push (xfree, tmp);
4225 rc = xfer_data (ctx, tmp, strlen (tmp));
4226 pthread_cleanup_pop (1);
4227 return send_error (ctx, rc);
4231 return send_error (ctx, GPG_ERR_INV_NAME);
4234 static void
4235 new_command (const char *name, int ignore, int unlock,
4236 gpg_error_t (*handler) (assuan_context_t, char *),
4237 const char *help)
4239 int i = 0;
4241 if (command_table)
4242 for (i = 0; command_table[i]; i++);
4244 command_table =
4245 xrealloc (command_table, (i + 2) * sizeof (struct command_table_s *));
4246 command_table[i] = xcalloc (1, sizeof (struct command_table_s));
4247 command_table[i]->name = name;
4248 command_table[i]->handler = handler;
4249 command_table[i]->ignore_startup = ignore;
4250 command_table[i]->unlock = unlock;
4251 command_table[i++]->help = help;
4252 command_table[i] = NULL;
4255 void
4256 deinit_commands ()
4258 int i;
4260 for (i = 0; command_table[i]; i++)
4261 xfree (command_table[i]);
4263 xfree (command_table);
4266 static int
4267 sort_commands (const void *arg1, const void *arg2)
4269 struct command_table_s *const *a = arg1;
4270 struct command_table_s *const *b = arg2;
4272 if (!*a || !*b)
4273 return 0;
4274 else if (*a && !*b)
4275 return 1;
4276 else if (!*a && *b)
4277 return -1;
4279 return strcmp ((*a)->name, (*b)->name);
4282 // FIXME cleanup/implement options
4283 static gpg_error_t
4284 passwd_command (assuan_context_t ctx, char *line)
4286 struct client_s *client = assuan_get_pointer (ctx);
4287 gpg_error_t rc;
4288 struct argv_s *args[] = {
4289 &(struct argv_s) {"reset", OPTION_TYPE_NOARG, parse_opt_reset},
4290 &(struct argv_s) {"s2k-count", OPTION_TYPE_ARG, parse_opt_s2k_count},
4291 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG, parse_opt_no_passphrase},
4292 NULL
4295 rc = peer_is_invoker (client);
4296 if (rc == GPG_ERR_EACCES)
4297 return send_error (ctx, rc);
4299 if (client->flags & FLAG_NEW)
4300 return send_error (ctx, GPG_ERR_INV_STATE);
4302 client->crypto->save.s2k_count =
4303 config_get_ulong (client->filename, "s2k_count");
4304 rc = parse_options (&line, args, client);
4305 if (rc)
4306 return send_error (ctx, rc);
4308 if (!rc && client->opts & OPT_RESET)
4310 rc = cache_clear (client->md5file);
4311 if (!rc)
4312 send_status_all (STATUS_CACHE, NULL);
4315 if (!rc)
4317 if (!IS_PKI (client->crypto))
4319 struct crypto_s *crypto;
4321 xfree (client->crypto->filename);
4322 client->crypto->filename = str_dup (client->filename);
4323 rc = change_passwd (ctx, client->filename,
4324 client->flags & FLAG_NO_PINENTRY, &crypto,
4325 (client->opts & OPT_NO_PASSPHRASE));
4326 if (!rc)
4328 cleanup_crypto (&client->crypto);
4329 client->crypto = crypto;
4330 update_checksum (client);
4331 cleanup_crypto_stage1 (client->crypto);
4334 #ifdef WITH_AGENT
4335 else
4337 if (client->crypto->save.s2k_count)
4338 rc = send_to_agent (client->crypto->agent, NULL, NULL,
4339 "OPTION s2k-count=%lu",
4340 client->crypto->save.s2k_count);
4342 if (!rc)
4343 rc = agent_passwd (client->crypto);
4345 #endif
4348 return send_error (ctx, rc);
4351 static gpg_error_t
4352 parse_keygrip_opt_sign (void *data, void *value)
4354 struct client_s *client = data;
4356 (void) value;
4357 client->opts |= OPT_SIGN;
4358 return 0;
4361 static gpg_error_t
4362 keygrip_command (assuan_context_t ctx, char *line)
4364 struct client_s *client = assuan_get_pointer (ctx);
4365 gpg_error_t rc;
4366 struct crypto_s *crypto = NULL;
4367 struct argv_s *args[] = {
4368 &(struct argv_s) {"sign", OPTION_TYPE_NOARG, parse_keygrip_opt_sign},
4369 NULL
4372 if (!line || !*line)
4373 return send_error (ctx, GPG_ERR_SYNTAX);
4375 rc = parse_options (&line, args, client);
4376 if (rc)
4377 return send_error (ctx, rc);
4379 if (!valid_filename (line))
4380 return send_error (ctx, GPG_ERR_INV_VALUE);
4382 rc = init_client_crypto (&crypto);
4383 if (rc)
4384 return send_error (ctx, rc);
4386 rc = read_data_file (line, crypto);
4387 if (!rc)
4389 char *hexgrip = NULL;
4391 if (!IS_PKI (crypto))
4393 cleanup_crypto (&crypto);
4394 return send_error (ctx, GPG_ERR_NOT_SUPPORTED);
4397 if (client->opts & OPT_SIGN)
4399 if (valid_keygrip (crypto->sign_grip, sizeof (crypto->sign_grip)))
4400 hexgrip = bin2hex (crypto->sign_grip, sizeof (crypto->sign_grip));
4403 if (!hexgrip)
4404 hexgrip = bin2hex (crypto->grip, sizeof (crypto->grip));
4406 if (!hexgrip)
4407 rc = GPG_ERR_ENOMEM;
4408 else
4409 rc = xfer_data (ctx, hexgrip, strlen (hexgrip));
4411 xfree (hexgrip);
4414 UPDATE_AGENT_CTX (client, crypto);
4415 cleanup_crypto (&crypto);
4416 return send_error (ctx, rc);
4419 static gpg_error_t
4420 parse_opt_data (void *data, void *value)
4422 struct client_s *client = data;
4424 (void) value;
4425 client->opts |= OPT_DATA;
4426 return 0;
4429 static gpg_error_t
4430 send_client_list (assuan_context_t ctx)
4432 struct client_s *client = assuan_get_pointer (ctx);
4433 gpg_error_t rc = 0;
4434 char buf[ASSUAN_LINELENGTH];
4436 if (client->opts & OPT_VERBOSE)
4438 unsigned i, t;
4439 char **list = NULL;
4440 char *line;
4442 MUTEX_LOCK (&cn_mutex);
4443 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
4444 t = slist_length (cn_thread_list);
4446 for (i = 0; i < t; i++)
4448 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
4449 char *tmp;
4451 if (thd->state == CLIENT_STATE_UNKNOWN)
4452 continue;
4454 tmp = build_client_info_line (thd, 0);
4455 if (tmp)
4457 char **l = strv_cat (list, tmp);
4458 if (!l)
4459 rc = GPG_ERR_ENOMEM;
4460 else
4461 list = l;
4463 else
4464 rc = GPG_ERR_ENOMEM;
4466 if (rc)
4468 strv_free (list);
4469 break;
4473 pthread_cleanup_pop (1);
4474 if (rc)
4475 return rc;
4477 line = strv_join ("\n", list);
4478 strv_free (list);
4479 pthread_cleanup_push (xfree, line);
4480 rc = xfer_data (ctx, line, strlen (line));
4481 pthread_cleanup_pop (1);
4482 return rc;
4485 if (client->opts & OPT_DATA)
4487 MUTEX_LOCK (&cn_mutex);
4488 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
4489 snprintf (buf, sizeof (buf), "%i", slist_length (cn_thread_list));
4490 pthread_cleanup_pop (1);
4491 rc = xfer_data (ctx, buf, strlen (buf));
4493 else
4494 rc = send_status (ctx, STATUS_CLIENTS, NULL);
4496 return rc;
4499 static gpg_error_t
4500 getinfo_command (assuan_context_t ctx, char *line)
4502 struct client_s *client = assuan_get_pointer (ctx);
4503 gpg_error_t rc;
4504 char buf[ASSUAN_LINELENGTH];
4505 struct argv_s *args[] = {
4506 &(struct argv_s) {"data", OPTION_TYPE_NOARG, parse_opt_data},
4507 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_opt_verbose},
4508 NULL
4511 rc = parse_options (&line, args, client);
4512 if (rc)
4513 return send_error (ctx, rc);
4515 if (!strcasecmp (line, "clients"))
4517 rc = send_client_list (ctx);
4519 else if (!strcasecmp (line, "cache"))
4521 if (client->opts & OPT_DATA)
4523 snprintf (buf, sizeof (buf), "%u", cache_file_count ());
4524 rc = xfer_data (ctx, buf, strlen (buf));
4526 else
4527 rc = send_status (ctx, STATUS_CACHE, NULL);
4529 else if (!strcasecmp (line, "pid"))
4531 char buf[32];
4532 pid_t pid = getpid ();
4534 snprintf (buf, sizeof (buf), "%i", pid);
4535 rc = xfer_data (ctx, buf, strlen (buf));
4537 else if (!strcasecmp (line, "version"))
4539 char *buf = str_asprintf ("0x%06x %s%s", VERSION_HEX,
4540 #ifdef WITH_GNUTLS
4541 "GNUTLS "
4542 #endif
4543 #ifdef WITH_QUALITY
4544 "QUALITY "
4545 #endif
4546 "", use_agent ? "AGENT" : "");
4547 rc = xfer_data (ctx, buf, strlen (buf));
4548 xfree (buf);
4550 else if (!strcasecmp (line, "last_error"))
4552 if (client->last_error)
4553 rc = xfer_data (ctx, client->last_error, strlen (client->last_error));
4554 else
4555 rc = GPG_ERR_NO_DATA;
4557 else if (!strcasecmp (line, "user"))
4559 char *user = NULL;
4561 #ifdef WITH_GNUTLS
4562 if (client->thd->remote)
4563 user = str_asprintf ("#%s", client->thd->tls->fp);
4564 else
4565 user = get_username (client->thd->peer->uid);
4566 #else
4567 user = get_username (client->thd->peer->uid);
4568 #endif
4569 if (user)
4571 pthread_cleanup_push (xfree, user);
4572 rc = xfer_data (ctx, user, strlen (user));
4573 pthread_cleanup_pop (1);
4575 else
4576 rc = GPG_ERR_NO_DATA;
4578 else
4579 rc = gpg_error (GPG_ERR_SYNTAX);
4581 return send_error (ctx, rc);
4584 #ifdef WITH_AGENT
4585 static gpg_error_t
4586 send_data_cb (void *user, const void *buf, size_t len)
4588 assuan_context_t ctx = user;
4590 return assuan_send_data (ctx, buf, len);
4593 static gpg_error_t
4594 send_status_cb (void *user, const char *line)
4596 assuan_context_t ctx = user;
4597 char keyword[200], *k;
4598 const char *p;
4600 for (p = line, k = keyword; *p; p++)
4602 if (isspace (*p))
4603 break;
4605 *k++ = *p;
4608 *k = 0;
4609 if (*p == '#')
4610 p++;
4612 while (isspace (*p))
4613 p++;
4615 return assuan_write_status (ctx, keyword, *p ? p : NULL);
4617 #endif
4619 static gpg_error_t
4620 kill_command (assuan_context_t ctx, char *line)
4622 #ifdef HAVE_PTHREAD_CANCEL
4623 struct client_s *client = assuan_get_pointer (ctx);
4624 gpg_error_t rc;
4626 if (!line || !*line)
4627 return send_error (ctx, GPG_ERR_SYNTAX);
4629 rc = peer_is_invoker (client);
4630 if (!rc)
4632 unsigned i, t;
4634 MUTEX_LOCK (&cn_mutex);
4635 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
4636 t = slist_length (cn_thread_list);
4637 rc = GPG_ERR_ESRCH;
4639 for (i = 0; i < t; i++)
4641 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
4642 char *tmp = str_asprintf ("%p", thd->tid);
4644 if (strcmp (line, tmp))
4646 xfree (tmp);
4647 continue;
4650 xfree (tmp);
4651 rc = pthread_cancel (thd->tid);
4652 break;
4655 pthread_cleanup_pop (1);
4658 return send_error (ctx, rc);
4659 #else
4660 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
4661 #endif
4664 static gpg_error_t
4665 agent_command (assuan_context_t ctx, char *line)
4667 gpg_error_t rc = 0;
4669 if (!use_agent)
4670 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
4672 #ifdef WITH_AGENT
4673 struct client_s *client = assuan_get_pointer (ctx);
4675 if (!line || !*line)
4676 return send_error (ctx, GPG_ERR_SYNTAX);
4678 assuan_set_flag (client->crypto->agent->ctx, ASSUAN_CONVEY_COMMENTS, 1);
4679 rc = assuan_transact (client->crypto->agent->ctx, line, send_data_cb,
4680 client->ctx, agent_loopback_cb, client->crypto,
4681 send_status_cb, client->ctx);
4682 if (gpg_err_code (rc) == GPG_ERR_ASS_CANCELED)
4684 char *line;
4685 size_t len;
4687 rc = assuan_write_line (client->crypto->agent->ctx, "CAN");
4688 if (!rc)
4690 rc = assuan_read_line (client->crypto->agent->ctx, &line, &len);
4691 if (!rc)
4692 rc = gpg_error (GPG_ERR_ASS_CANCELED);
4696 assuan_set_flag (client->crypto->agent->ctx, ASSUAN_CONVEY_COMMENTS, 0);
4697 #endif
4698 return send_error (ctx, rc);
4701 void
4702 init_commands ()
4704 /* !BEGIN-HELP-TEXT!
4706 * This comment is used as a marker to generate the offline documentation
4707 * found in doc/pwmd.info. The indentation needs to be kept for the awk
4708 * script to determine where commands begin and end.
4710 new_command("HELP", 1, 1, help_command, _(
4711 "HELP [<COMMAND>]\n"
4712 "Show available commands or command specific help text."
4715 new_command("AGENT", 1, 1, agent_command, _(
4716 "AGENT <command>\n"
4717 "Send a @command{gpg-agent} protocol @var{command} directly to the "
4718 "@command{gpg-agent}."
4721 new_command("KILL", 1, 0, kill_command, _(
4722 "KILL <thread_id>\n"
4723 "Terminates the client identified by @var{thread_id} and releases any file "
4724 "lock or other resources it has held. @xref{GETINFO} for details about listing "
4725 "connected clients.\n"
4728 new_command("GETINFO", 1, 1, getinfo_command, _(
4729 "GETINFO [--data] [--verbose] CACHE | CLIENTS | PID | USER | LAST_ERROR | VERSION\n"
4730 "Get server and other information: @var{CACHE} returns the number of cached "
4731 "documents via a status message. @var{CLIENTS} returns the number of "
4732 "connected clients via a status message or a list of connected clients when "
4733 "the @option{--verbose} parameter is used. The list contains space delimited "
4734 "fields: the thread ID, client name, opened file (@code{/} if none opened), "
4735 "file lock status, whether the current client is self, client state and "
4736 "user ID or TLS fingerprint of the connected client. "
4737 "Client state @code{1} indicates that the client is idle, @code{2} means the "
4738 "client is in a command and @code{3} means the client is disconnecting. This "
4739 "line is always returned with a data response. @var{PID} returns the process "
4740 "ID number of the server via a data response. @var{VERSION} returns the server "
4741 "version number and compile-time features with a data response with each "
4742 "being space delimited. @var{LAST_ERROR} returns a detailed description of "
4743 "the last failed command when available. @var{USER} returns the username or "
4744 "@abbr{TLS} hash of the connected client. @xref{Status Messages}. "
4745 "\n"
4746 "When the @option{--data} option is specified then the result will be sent "
4747 "via a data response rather than a status message."
4750 new_command("PASSWD", 0, 0, passwd_command, _(
4751 "PASSWD [--reset] [--s2k-count=N] [--no-passphrase]\n"
4752 "Changes the passphrase of the secret key required to open the current "
4753 "file or the passphrase of a symmetrically encrypted data file. When the "
4754 "@option{--reset} option is passed then the cache entry for the current "
4755 "file will be reset and the passphrase, if any, will be required during the "
4756 "next @code{OPEN} (@pxref{OPEN})."
4757 "\n"
4758 "The @option{--s2k-count} option sets or changes (@pxref{SAVE}) the number "
4759 "of hash iterations for a passphrase and must be either @code{0} to use "
4760 "the calibrated count of the machine (the default), or a value greater than "
4761 "or equal to @code{65536}. This option has no effect for symmetrically "
4762 "encrypted data files."
4763 "\n"
4764 "The @option{--no-passphrase} option will prevent requiring a passphrase for "
4765 "the data file, although a passphrase may be required when changing it."
4766 "\n"
4767 "This command is not available for non-invoking clients "
4768 "(@pxref{Access Control})."
4771 new_command("KEYGRIP", 1, 1, keygrip_command, _(
4772 "KEYGRIP [--sign] <filename>\n"
4773 "Returns the hex encoded keygrip of the specified @var{filename} with a "
4774 "data response."
4775 "\n"
4776 "When the @option{--sign} option is specified then the key used for signing "
4777 "of the specified @var{filename} will be returned."
4778 "\n"
4779 "For symmetrically encrypted data files this command returns the error "
4780 "GPG_ERR_NOT_SUPPORTED."
4783 new_command("OPEN", 1, 1, open_command, _(
4784 "OPEN [--lock] <filename> [<passphrase>]\n"
4785 "Opens @var{filename} using @var{passphrase}. When the filename is not "
4786 "found on the file-system then a new document will be created. If the file "
4787 "is found, it is looked for in the file cache. If cached and no "
4788 "@var{passphrase} was specified then the cached document is opened. When not "
4789 "cached, @cite{pinentry(1)} will be used to retrieve the passphrase to use "
4790 "for decryption unless @option{disable-pinentry} (@pxref{OPTION}) was "
4791 "specified."
4792 "\n"
4793 "When the @option{--lock} option is passed then the file mutex will be "
4794 "locked as if the @code{LOCK} command (@pxref{LOCK}) had been sent after the "
4795 "file has been opened."
4798 new_command("SAVE", 0, 0, save_command, _(
4799 "SAVE [--no-passphrase] [--reset] [--no-agent] [--s2k-count=N] [--cipher=<algo>] [--cipher-iterations=N] [--inquire-keyparam] [--keygrip=hexstring] [--sign-keygrip=hexstring]\n"
4800 "Writes the @abbr{XML} document to disk. The file written to is the file that "
4801 "was opened using the @code{OPEN} command (@pxref{OPEN}). If the file is a "
4802 "new one or the option @option{--inquire-keyparam} was passed, then a new "
4803 "keypair will be generated and a pinentry will be used to prompt for the "
4804 "passphrase to encrypt with unless the @option{--no-passphrase} option was "
4805 "passed in which case the data file will not be passphrase protected. "
4806 "\n"
4807 "The @option{--no-agent} option disables use of @command{gpg-agent} for "
4808 "passphrase retrieval and caching of new files when @command{gpg-agent} "
4809 "use is enabled. The datafile will be symmetrically encrypted and will not "
4810 "use or generate any keypair."
4811 "\n"
4812 "The @option{--reset} option will clear the cache entry for the current file "
4813 "and require a passphrase, if needed, before saving."
4814 "\n"
4815 "The @option{--cipher} option can be used to encrypt the @abbr{XML} data to "
4816 "an alternate cipher. The default is @code{aes256}. See the Configuration "
4817 "(@pxref{Configuration}) for available ciphers."
4818 "\n"
4819 "The @option{--cipher-iterations} option specifies the number of times to "
4820 "encrypt the XML data. The default is 0 although 1 iteration is still done."
4821 "\n"
4822 "The @option{--inquire-keyparam} option will send a server @emph{INQUIRE} to "
4823 "the client to obtain the key paramaters to use when generating a new "
4824 "keypair. The inquired data is expected to be an S-expression. If not "
4825 "specified then an @samp{RSA} key of @samp{2048} bits will be generated "
4826 "unless otherwise set in the configuration file (@pxref{Configuration}). Note "
4827 "that when this option is specified a new keypair will be generated "
4828 "reguardless if the file is a new one and that if the data file is protected "
4829 "the passphrase to open it will be required before generating the new "
4830 "keypair. This option is not available for non-invoking clients "
4831 "(@pxref{Access Control})."
4832 "\n"
4833 "You can encrypt the data file to a public key other than the one that it "
4834 "was originally encrypted with by passing the @option{--keygrip} option with "
4835 "the hex encoded keygrip of the public key as its argument. The keygrip may "
4836 "be of any key that @command{gpg-agent} knows about. The "
4837 "@option{--sign-keygrip} option may also be used to sign with an alternate "
4838 "secret key. Use the @code{KEYGRIP} (@pxref{KEYGRIP}) command to obtain the "
4839 "keygrip of an existing data file. This option may be needed when using a "
4840 "smartcard. This option has no effect with symmetrically encrypted data "
4841 "files. These options are not available for non-invoking clients "
4842 "(@pxref{Access Control})."
4843 "\n"
4844 "The @option{--s2k-count} option sets number of hash iterations for a "
4845 "passphrase. A value less-than @code{65536} will use the machine calibrated "
4846 "value and is the default. This setting only affects new files. To change "
4847 "the setting use the @code{PASSWD} command (@pxref{PASSWD}). This option "
4848 "has no effect with symmetrically encrypted data files."
4851 new_command("ISCACHED", 1, 0, iscached_command, _(
4852 "ISCACHED [--lock] <filename>\n"
4853 "An @emph{OK} response is returned if the specified @var{filename} is found "
4854 "in the file cache. If not found in the cache but exists on the filesystem "
4855 "then @var{GPG_ERR_NO_DATA} is returned. Otherwise a filesystem error is "
4856 "returned."
4857 "\n"
4858 "The @option{lock} option will lock the file mutex of @var{filename} when the "
4859 "file exists; it does not need to be opened nor cached. The lock will be "
4860 "released when the client exits or sends the @code{UNLOCK} (@pxref{UNLOCK}) "
4861 "command."
4864 new_command("CLEARCACHE", 1, 1, clearcache_command, _(
4865 "CLEARCACHE [<filename>]\n"
4866 "Clears a file cache entry for all or the specified @var{filename}."
4869 new_command("CACHETIMEOUT", 1, 1, cachetimeout_command, _(
4870 "CACHETIMEOUT <filename> <seconds>\n"
4871 "The time in @var{seconds} until @var{filename} will be removed from the "
4872 "cache. @code{-1} will keep the cache entry forever, @code{0} will require "
4873 "the passphrase for each @code{OPEN} or @code{SAVE} command (@pxref{OPEN}, "
4874 "@pxref{SAVE}). @xref{Configuration}, and the @code{cache_timeout} "
4875 "parameter."
4878 new_command("LIST", 0, 1, list_command, _(
4879 "LIST [--inquire] [--no-recurse] [--verbose] [--with-target] [--all] [[!]element[<TAB>[!]child[..]]]\n"
4880 "If no element path is given then a newline separated list of root elements "
4881 "is returned with a data response. If given, then all reachable elements "
4882 "of the specified element path are returned unless the @option{--no-recurse} "
4883 "option is specified. If specified, only the child elements of the element "
4884 "path are returned without recursing into grandchildren. Each resulting "
4885 "element is prefixed with the literal @code{!} character when the element "
4886 "contains no @code{target} attribute. @xref{Target Attribute}, for details."
4887 "\n"
4888 "When the @option{--verbose} option is passed then each element path "
4889 "returned will have zero or more flags appened to it. These flags are "
4890 "delimited from the element path by a single space character. A flag itself "
4891 "is a single character. Flag @code{P} indicates that access to the element "
4892 "is denied. Flag @code{+} indicates that there are child nodes of "
4893 "the current element path. Flag @code{E} indicates that an element of an "
4894 "element path contained in a @var{target} attribute could not be found. Flag "
4895 "@code{O} indicates that a @var{target} attribute recursion limit was reached "
4896 "(@pxref{Configuration}). Flag @code{T} will append the resolved element path "
4897 "of the @var{target} attribute contained in the current element (see below)."
4898 "\n"
4899 "The @option{--with-target} option implies @option{--verbose} and will append "
4900 "an additional flag @code{T} followed by a single space then an element path. "
4901 "The appended element path is the resolved path (@pxref{REALPATH}) of the "
4902 "current element when it contains a @var{target} attribute. When no "
4903 "@var{target} attribute is found then no flag will be appended."
4904 "\n"
4905 "The @option{--no-recurse} option limits the amount of data returned to only "
4906 "the listing of children of the specified element path and not any "
4907 "grandchildren."
4908 "\n"
4909 "The @option{--all} option lists the entire element tree for each root "
4910 "element. This option also implies option @option{--verbose}."
4911 "\n"
4912 "When the @option{--inquire} option is passed then all remaining non-option "
4913 "arguments are retrieved via a server @emph{INQUIRE}."
4916 new_command("REALPATH", 0, 1, realpath_command, _(
4917 "REALPATH [--inquire] [!]element[<TAB>[!]child[..]]\n"
4918 "Resolves all @code{target} attributes of the specified element path and "
4919 "returns the result with a data response. @xref{Target Attribute}, for details."
4920 "\n"
4921 "When the @option{--inquire} option is passed then all remaining non-option "
4922 "arguments are retrieved via a server @emph{INQUIRE}."
4925 new_command("STORE", 0, 1, store_command, _(
4926 "STORE [!]element[<TAB>[!]child[..]]<TAB>[content]\n"
4927 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
4928 "\n"
4929 "Creates a new element path or modifies the @var{content} of an existing "
4930 "element. If only a single element is specified then a new root element is "
4931 "created. Otherwise, elements are @key{TAB} delimited and the content will be "
4932 "set to the final @key{TAB} delimited element. If no @var{content} is "
4933 "specified after the final @key{TAB}, then the content of an existing "
4934 "element will be removed; or empty when creating a new element."
4935 "\n"
4936 "The only restriction of an element name is that it not contain whitespace "
4937 "or begin with the literal element character @code{!} unless specifying a "
4938 "literal element (@pxref{Target Attribute}). There is no whitespace between "
4939 "the @key{TAB} delimited elements. It is recommended that the content of an "
4940 "element be base64 encoded when it contains control or @key{TAB} characters "
4941 "to prevent @abbr{XML} parsing and @command{pwmd} syntax errors."
4944 new_command("RENAME", 0, 1, rename_command, _(
4945 "RENAME [--inquire] [!]element[<TAB>[!]child[..]] <value>\n"
4946 "Renames the specified @var{element} to the new @var{value}. If an element of "
4947 "the same name as the @var{value} already exists it will be overwritten."
4948 "\n"
4949 "When the @option{--inquire} option is passed then all remaining non-option "
4950 "arguments are retrieved via a server @emph{INQUIRE}."
4953 new_command("COPY", 0, 1, copy_command, _(
4954 "COPY [--inquire] [!]source[<TAB>[!]child[..]] [!]dest[<TAB>[!]child[..]]\n"
4955 "Copies the entire element tree starting from the child node of the source "
4956 "element, to the destination element path. If the destination element path "
4957 "does not exist then it will be created; otherwise it is overwritten."
4958 "\n"
4959 "Note that attributes from the source element are merged into the "
4960 "destination element when the destination element path exists. When an "
4961 "attribute of the same name exists in both the source and destination "
4962 "elements then the destination attribute will be updated to the source "
4963 "attribute value."
4964 "\n"
4965 "When the @option{--inquire} option is passed then all remaining non-option "
4966 "arguments are retrieved via a server @emph{INQUIRE}."
4969 new_command("MOVE", 0, 1, move_command, _(
4970 "MOVE [--inquire] [!]source[<TAB>[!]child[..]] [[!]dest[<TAB>[!]child[..]]]\n"
4971 "Moves the source element path to the destination element path. If the "
4972 "destination is not specified then it will be moved to the root node of the "
4973 "document. If the destination is specified and exists then it will be "
4974 "overwritten; otherwise non-existing elements of the destination element "
4975 "path will be created."
4976 "\n"
4977 "When the @option{--inquire} option is passed then all remaining non-option "
4978 "arguments are retrieved via a server @emph{INQUIRE}."
4981 new_command("DELETE", 0, 1, delete_command, _(
4982 "DELETE [--inquire] [!]element[<TAB>[!]child[..]]\n"
4983 "Removes the specified element path and all of its children. This may break "
4984 "an element with a @code{target} attribute (@pxref{Target Attribute}) that "
4985 "refers to this element or any of its children."
4986 "\n"
4987 "When the @option{--inquire} option is passed then all remaining non-option "
4988 "arguments are retrieved via a server @emph{INQUIRE}."
4991 new_command("GET", 0, 1, get_command, _(
4992 "GET [--inquire] [!]element[<TAB>[!]child[..]]\n"
4993 "Retrieves the content of the specified element. The content is returned "
4994 "with a data response."
4995 "\n"
4996 "When the @option{--inquire} option is passed then all remaining non-option "
4997 "arguments are retrieved via a server @emph{INQUIRE}."
5000 new_command("ATTR", 0, 1, attr_command, _(
5001 "ATTR [--inquire] SET|GET|DELETE|LIST [<attribute>] [!]element[<TAB>[!]child[..]] ..\n"
5002 "@table @asis\n"
5003 "@item ATTR SET attribute [!]element[<TAB>[!]child[..]] [value]\n"
5004 "\n"
5005 " Stores or updates an @var{attribute} name and optional @var{value} of an "
5006 "element. When no @var{value} is specified any existing value will be removed."
5007 "\n"
5008 "@item ATTR DELETE attribute [!]element[<TAB>[!]child[..]]\n"
5009 "\n"
5010 " Removes an @var{attribute} from an element."
5011 "\n"
5012 "@item ATTR LIST [!]element[<TAB>[!]child[..]]\n"
5013 "\n"
5014 " Retrieves a newline separated list of attributes names and values "
5015 "from the specified element. Each attribute name and value is space delimited."
5016 "\n"
5017 "@item ATTR GET attribute [!]element[<TAB>[!]child[..]]\n"
5018 "\n"
5019 " Retrieves the value of an @var{attribute} from an element."
5020 "@end table\n"
5021 "\n"
5022 "The @code{_name} attribute (case sensitive) cannot be removed nor modified. "
5023 "Use the @code{DELETE} (@pxref{DELETE}) or @code{RENAME} (@pxref{RENAME}) "
5024 "commands instead."
5025 "\n"
5026 "The @code{_mtime} attribute is updated each time an element is modified by "
5027 "either storing content, editing attributes or by deleting a child element. "
5028 "The @code{_ctime} attribute is created for each new element in an element "
5029 "path."
5030 "\n"
5031 "When the @option{--inquire} option is passed then all remaining non-option "
5032 "arguments are retrieved via a server @emph{INQUIRE}."
5033 "\n"
5034 "@xref{Target Attribute}, for details about this special attribute."
5037 new_command("XPATH", 0, 1, xpath_command, _(
5038 "XPATH [--inquire] <expression>[<TAB>[value]]\n"
5039 "Evaluates an XPath @var{expression}. If no @var{value} argument is "
5040 "specified it is assumed the expression is a request to return a result. "
5041 "Otherwise, the result is set to the @var{value} argument and the document is "
5042 "updated. If there is no @var{value} after the @key{TAB} character, the value "
5043 "is assumed to be empty and the document is updated. For example:"
5044 "@sp 1\n"
5045 "@example\n"
5046 "XPATH //element[@@_name='password']@key{TAB}\n"
5047 "@end example\n"
5048 "@sp 1"
5049 "would clear the content of all @code{password} elements in the data file "
5050 "while leaving off the trailing @key{TAB} would return all @code{password} "
5051 "elements in @abbr{XML} format."
5052 "\n"
5053 "When the @option{--inquire} option is passed then all remaining non-option "
5054 "arguments are retrieved via a server @emph{INQUIRE}."
5055 "\n"
5056 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
5057 "expression syntax."
5060 new_command("XPATHATTR", 0, 1, xpathattr_command, _(
5061 "XPATHATTR [--inquire] SET|DELETE <name> <expression>[<TAB>[<value>]]\n"
5062 "Like the @code{XPATH} command (@pxref{XPATH}) but operates on element "
5063 "attributes and does not return a result. For the @var{SET} operation the "
5064 "@var{value} is optional but the field is required. If not specified then "
5065 "the attribute value will be empty. For example:"
5066 "@sp 1"
5067 "@example\n"
5068 "XPATHATTR SET password //element[@@_name='password']@key{TAB}\n"
5069 "@end example\n"
5070 "@sp 1"
5071 "would create an @code{password} attribute for each @code{password} element "
5072 "found in the document. The attribute value will be empty but still exist."
5073 "\n"
5074 "When the @option{--inquire} option is passed then all remaining non-option "
5075 "arguments are retrieved via a server @emph{INQUIRE}."
5076 "\n"
5077 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
5078 "expression syntax."
5081 new_command("IMPORT", 0, 1, import_command, _(
5082 "IMPORT [--root [!]element[<TAB>[!]child[..]]] <content>\n"
5083 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
5084 "\n"
5085 "Like the @code{STORE} command (@pxref{STORE}), but the @var{content} "
5086 "argument is raw @abbr{XML} data. The content is created as a child of "
5087 "the element path specified with the @option{--root} option or at the "
5088 "document root when not specified. Existing elements of the same name will "
5089 "be overwritten."
5090 "\n"
5091 "The content must begin with an @abbr{XML} element node. @xref{Introduction}, "
5092 "for details."
5095 new_command("DUMP", 0, 1, dump_command, _(
5096 "DUMP\n"
5097 "Shows the in memory @abbr{XML} document with indenting. @xref{XPATH}, for "
5098 "dumping a specific node."
5101 new_command("LOCK", 0, 0, lock_command, _(
5102 "LOCK\n"
5103 "Locks the mutex associated with the opened file. This prevents other clients "
5104 "from sending commands to the same opened file until the client "
5105 "that sent this command either disconnects or sends the @code{UNLOCK} "
5106 "command. @xref{UNLOCK}."
5109 new_command("UNLOCK", 1, 0, unlock_command, _(
5110 "UNLOCK\n"
5111 "Unlocks the file mutex which was locked with the @code{LOCK} command or "
5112 "a commands' @option{--lock} option (@pxref{LOCK}, @pxref{OPEN}, "
5113 "@pxref{ISCACHED})."
5116 new_command("GETCONFIG", 1, 1, getconfig_command, _(
5117 "GETCONFIG [filename] <parameter>\n"
5118 "Returns the value of a @command{pwmd} configuration @var{parameter} with a "
5119 "data response. If no file has been opened then the value for @var{filename} "
5120 "or the default from the @samp{global} section will be returned. If a file "
5121 "has been opened and no @var{filename} is specified, a value previously "
5122 "set with the @code{OPTION} command (@pxref{OPTION}) will be returned."
5125 new_command("OPTION", 1, 1, option_command, _(
5126 "OPTION <NAME>=<VALUE>\n"
5127 "Sets a client option @var{name} to @var{value}. The value for an option is "
5128 "kept for the duration of the connection."
5129 "\n"
5130 "@table @asis\n"
5131 "@item DISABLE-PINENTRY\n"
5132 "Disable use of @command{pinentry} for passphrase retrieval. When set, a "
5133 "server inquire is sent to the client to obtain the passphrase. This option "
5134 "may be set as needed before the @code{OPEN} (@pxref{OPEN}), @code{PASSWD} "
5135 "(@pxref{PASSWD}) and @code{SAVE} (@pxref{SAVE}) commands."
5136 "\n"
5137 "@item PINENTRY-TIMEOUT\n"
5138 "Sets the number of seconds before a pinentry prompt will return an error "
5139 "while waiting for user input."
5140 "\n"
5141 "@item TTYNAME\n"
5142 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
5143 "\n"
5144 "@item TTYTYPE\n"
5145 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
5146 "\n"
5147 "@item DISPLAY\n"
5148 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
5149 "\n"
5150 "@item PINENTRY-DESC\n"
5151 "Sets the description string of the @command{gpg-agent} and @command{pinentry} dialog."
5152 "\n"
5153 "@item PINENTRY-TITLE\n"
5154 "Sets the title string of the @command{gpg-agent} and @command{pinentry} dialog."
5155 "\n"
5156 "@item PINENTRY-PROMPT\n"
5157 "Sets the prompt string of the @command{gpg-agent} and @command{pinentry} dialog."
5158 "\n"
5159 "@item LC-CTYPE\n"
5160 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
5161 "\n"
5162 "@item LC-MESSAGES\n"
5163 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
5164 "\n"
5165 "@item NAME\n"
5166 "Associates the thread ID of the connection with the specified textual "
5167 "representation. Useful for debugging log messages. May not contain whitespace."
5168 "\n"
5169 "@item LOCK-TIMEOUT\n"
5170 "When not @code{0}, the duration in tenths of a second to wait for the file "
5171 "mutex which has been locked by another thread to be released before returning "
5172 "an error. When @code{-1}, then an error will be returned immediately."
5173 "\n"
5174 "@item LOG-LEVEL\n"
5175 "An integer specifiying the logging level."
5176 "@end table\n"
5179 new_command("LS", 1, 1, ls_command, _(
5180 "LS\n"
5181 "Lists the available data files stored in the data directory "
5182 "(@file{~/.pwmd/data}). The result is a newline separated list of filenames."
5185 new_command("RESET", 1, 1, NULL, _(
5186 "RESET\n"
5187 "Closes the currently opened file but keeps any previously set client options."
5190 new_command("NOP", 1, 1, NULL, _(
5191 "NOP\n"
5192 "Does nothing. Always returns successfully."
5195 /* !END-HELP-TEXT! */
5196 new_command ("CANCEL", 1, 1, NULL, NULL);
5197 new_command ("END", 1, 1, NULL, NULL);
5198 new_command ("BYE", 1, 1, NULL, NULL);
5200 int i;
5201 for (i = 0; command_table[i]; i++);
5202 qsort (command_table, i - 1, sizeof (struct command_table_s *),
5203 sort_commands);
5206 gpg_error_t
5207 register_commands (assuan_context_t ctx)
5209 int i = 0, rc;
5211 for (; command_table[i]; i++)
5213 if (!command_table[i]->handler)
5214 continue;
5216 rc = assuan_register_command (ctx, command_table[i]->name,
5217 command_table[i]->handler,
5218 command_table[i]->help);
5219 if (rc)
5220 return rc;
5223 rc = assuan_register_bye_notify (ctx, bye_notify);
5224 if (rc)
5225 return rc;
5227 rc = assuan_register_reset_notify (ctx, reset_notify);
5228 if (rc)
5229 return rc;
5231 rc = assuan_register_pre_cmd_notify (ctx, command_startup);
5232 if (rc)
5233 return rc;
5235 return assuan_register_post_cmd_notify (ctx, command_finalize);