Return an rc from the passwd and group functions.
[pwmd.git] / src / commands.c
blob3eed90df6766a703135474b670fb96730c3ab940
1 /*
2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015
3 Ben Kibbey <bjk@luxsci.net>
5 This file is part of pwmd.
7 Pwmd is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 2 of the License, or
10 (at your option) any later version.
12 Pwmd is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
20 #ifdef HAVE_CONFIG_H
21 #include <config.h>
22 #endif
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <unistd.h>
27 #include <err.h>
28 #include <errno.h>
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <fcntl.h>
32 #include <ctype.h>
33 #include <dirent.h>
34 #include <pthread.h>
35 #include <stdint.h>
37 #include "pwmd-error.h"
38 #include <gcrypt.h>
40 #include "mem.h"
41 #include "xml.h"
42 #include "util-misc.h"
43 #include "common.h"
44 #include "rcfile.h"
45 #include "cache.h"
46 #include "commands.h"
47 #include "mutex.h"
48 #include "crypto.h"
49 #include "pinentry.h"
51 /* These are command option flags. */
52 #define OPT_INQUIRE 0x0001
53 #define OPT_NO_PASSPHRASE 0x0002
54 #define OPT_RESET 0x0004
55 #define OPT_LIST_RECURSE 0x0008
56 #define OPT_VERBOSE 0x0010
57 #define OPT_LOCK 0x0020
58 #define OPT_LOCK_ON_OPEN 0x0040
59 #define OPT_SIGN 0x0080
60 #define OPT_LIST_ALL 0x0100
61 #define OPT_LIST_WITH_TARGET 0x0200
62 #define OPT_DATA 0x0400
63 #define OPT_NO_AGENT 0x0800
64 #define OPT_ASK 0x1000
66 #ifdef WITH_AGENT
67 /* The GETCONFIG command, for example, may fail because pwmd lost the
68 * gpg-agent connection. Update the recovered agent ctx. */
69 #define UPDATE_AGENT_CTX(client, crypto) do { \
70 if (crypto && crypto->agent && crypto->agent->did_restart \
71 && client->crypto && client->crypto->agent \
72 && client->crypto->agent->ctx && \
73 crypto->agent->ctx != client->crypto->agent->ctx) \
74 { \
75 client->crypto->agent->ctx = crypto->agent->ctx; \
76 crypto->agent->ctx = NULL; \
77 } \
78 } while (0)
79 #else
80 #define UPDATE_AGENT_CTX(client, crypto)
81 #endif
83 #define FLOCK_TYPE_NONE 0
84 #define FLOCK_TYPE_SH 0x0001
85 #define FLOCK_TYPE_EX 0x0002
86 #define FLOCK_TYPE_KEEP 0x0004
88 struct command_table_s
90 const char *name;
91 gpg_error_t (*handler) (assuan_context_t, char *line);
92 const char *help;
93 int ignore_startup;
94 int unlock; // unlock the file mutex after validating the checksum
95 uint32_t flock_type;
98 static struct command_table_s **command_table;
100 static gpg_error_t do_lock (struct client_s *client, int add);
101 static gpg_error_t validate_checksum (struct client_s *,
102 struct cache_data_s *);
103 static gpg_error_t update_checksum (struct client_s *client);
105 /* When 'status' is true the 'self' field of the status line will be false
106 * because we never send the STATE status message to the same client that
107 * initiated it. */
108 static char *
109 build_client_info_line (struct client_thread_s *thd, int status)
111 MUTEX_LOCK (&cn_mutex);
112 int with_state = config_get_boolean ("global", "send_state");
113 char *uid, *username = NULL;
114 char *line;
116 #ifdef WITH_GNUTLS
117 if (thd->remote)
118 uid = str_asprintf("#%s", thd->tls->fp);
119 else
121 uid = str_asprintf("%u", thd->peer->uid);
122 username = get_username (thd->peer->uid);
124 #else
125 uid = str_asprintf("%u", thd->peer->uid);
126 username = get_username (thd->peer->uid);
127 #endif
128 line = str_asprintf ("%p %s %s %s %u %u %u %s %s",
129 thd->tid,
130 thd->name ? thd->name : "-",
131 thd->cl && thd->cl->filename
132 && (thd->cl->flags & FLAG_OPEN)
133 ? thd->cl->filename : "/",
134 #ifdef WITH_GNUTLS
135 thd->remote ? thd->peeraddr : "-",
136 #else
137 "-",
138 #endif
139 thd->cl && thd->cl->flags & FLAG_HAS_LOCK ? 1 : 0,
140 !status && pthread_equal (pthread_self (), thd->tid) ? 1 : 0,
141 with_state ? thd->state : CLIENT_STATE_UNKNOWN, uid,
142 #ifdef WITH_GNUTLS
143 thd->remote ? "" : username
144 #else
145 username
146 #endif
149 xfree (username);
150 xfree (uid);
151 MUTEX_UNLOCK (&cn_mutex);
152 return line;
155 void
156 update_client_state (struct client_s *client, unsigned s)
158 client->thd->state = s;
159 int n = config_get_boolean ("global", "send_state");
161 if (n && client->thd->state != CLIENT_STATE_UNKNOWN)
163 char *line = build_client_info_line (client->thd, 1);
165 if (line)
166 send_status_all_not_self (n == 2, STATUS_STATE, "%s", line);
170 static gpg_error_t
171 unlock_file_mutex (struct client_s *client, int remove)
173 gpg_error_t rc = 0;
175 // OPEN: keep the lock for the same file being reopened.
176 if (client->flags & FLAG_KEEP_LOCK && client->flags & FLAG_HAS_LOCK)
177 return 0;
179 if (!(client->flags & FLAG_HAS_LOCK))
180 return GPG_ERR_NOT_LOCKED;
182 rc = cache_unlock_mutex (client->md5file, remove);
183 if (rc)
184 rc = GPG_ERR_INV_STATE;
185 else
186 client->flags &= ~(FLAG_HAS_LOCK | FLAG_LOCK_CMD);
188 return rc;
191 static gpg_error_t
192 lock_file_mutex (struct client_s *client, int add)
194 gpg_error_t rc = 0;
195 int timeout = config_get_integer (client->filename, "cache_timeout");
197 if (client->flags & FLAG_HAS_LOCK)
198 return 0;
200 rc = cache_lock_mutex (client->ctx, client->md5file,
201 client->lock_timeout, add, timeout);
202 if (!rc)
203 client->flags |= FLAG_HAS_LOCK;
205 return rc;
208 static gpg_error_t
209 file_modified (struct client_s *client, struct command_table_s *cmd)
211 gpg_error_t rc = 0;
212 int type = !cmd->flock_type || (cmd->flock_type & FLOCK_TYPE_SH)
213 ? LOCK_SH : LOCK_EX;
215 if (!(client->flags & FLAG_OPEN))
216 return GPG_ERR_INV_STATE;
218 rc = lock_flock (client->ctx, client->filename, type, &client->flock_fd);
219 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
220 return rc;
222 rc = lock_file_mutex (client, 0);
223 if (!rc || rc == GPG_ERR_NO_DATA)
225 rc = validate_checksum (client, NULL);
226 if (gpg_err_code (rc) == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
227 rc = 0;
228 else if (rc)
229 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
232 if ((cmd->unlock && !(client->flags & FLAG_HAS_LOCK)) || rc)
233 unlock_file_mutex (client, 0);
235 if (rc || !(cmd->flock_type & FLOCK_TYPE_KEEP))
236 unlock_flock (&client->flock_fd);
238 return rc;
241 static gpg_error_t
242 parse_xml (assuan_context_t ctx, int new)
244 struct client_s *client = assuan_get_pointer (ctx);
245 int cached = client->doc != NULL;
246 gpg_error_t rc = 0;
248 if (new)
250 client->doc = new_document ();
251 if (client->doc)
253 xmlChar *result;
254 int len;
256 xmlDocDumpFormatMemory (client->doc, &result, &len, 0);
257 client->crypto->plaintext = result;
258 client->crypto->plaintext_len = len;
259 if (!client->crypto->plaintext)
261 xmlFreeDoc (client->doc);
262 client->doc = NULL;
263 rc = GPG_ERR_ENOMEM;
266 else
267 rc = GPG_ERR_ENOMEM;
269 else if (!cached)
270 rc = parse_doc ((char *) client->crypto->plaintext,
271 client->crypto->plaintext_len, (xmlDocPtr *)&client->doc);
273 return rc;
276 static void
277 free_client (struct client_s *client)
279 if (client->doc)
280 xmlFreeDoc (client->doc);
282 xfree (client->crc);
283 xfree (client->filename);
284 xfree (client->last_error);
286 if (client->crypto)
288 cleanup_crypto_stage2 (client->crypto);
289 if (client->crypto->pkey_sexp)
290 gcry_sexp_release (client->crypto->pkey_sexp);
292 if (client->crypto->sigpkey_sexp)
293 gcry_sexp_release (client->crypto->sigpkey_sexp);
295 client->crypto->pkey_sexp = NULL;
296 client->crypto->sigpkey_sexp = NULL;
297 memset (client->crypto->sign_grip, 0,
298 sizeof (client->crypto->sign_grip));
299 memset (client->crypto->grip, 0, sizeof(client->crypto->grip));
303 void
304 cleanup_client (struct client_s *client)
306 assuan_context_t ctx = client->ctx;
307 struct client_thread_s *thd = client->thd;
308 struct crypto_s *crypto = client->crypto;
309 long lock_timeout = client->lock_timeout;
310 int no_pinentry = (client->flags & FLAG_NO_PINENTRY);
311 struct pinentry_option_s pin_opts;
312 xmlErrorPtr xml_error = client->xml_error;
313 int flock_fd = client->flock_fd;
314 #ifdef WITH_AGENT
315 struct pinentry_option_s agent_pin_opts;
317 if (crypto && crypto->agent)
318 memcpy (&agent_pin_opts, &crypto->agent->pinentry_opts,
319 sizeof(struct pinentry_option_s));
320 #endif
322 memcpy (&pin_opts, &client->pinentry_opts, sizeof(struct pinentry_option_s));
323 unlock_file_mutex (client, client->flags & FLAG_NEW);
324 free_client (client);
325 memset (client, 0, sizeof (struct client_s));
326 client->flock_fd = flock_fd;
327 client->xml_error = xml_error;
328 client->crypto = crypto;
329 client->ctx = ctx;
330 client->thd = thd;
331 client->lock_timeout = lock_timeout;
332 memcpy (&client->pinentry_opts, &pin_opts, sizeof(struct pinentry_option_s));
333 client->flags |= no_pinentry ? FLAG_NO_PINENTRY : 0;
334 #ifdef WITH_AGENT
335 if (crypto && crypto->agent)
336 memcpy (&crypto->agent->pinentry_opts, &agent_pin_opts,
337 sizeof(struct pinentry_option_s));
338 #endif
341 static gpg_error_t
342 open_finalize (assuan_context_t ctx, char *key, size_t keylen)
344 struct client_s *client = assuan_get_pointer (ctx);
345 gpg_error_t rc = 0;
346 struct cache_data_s *cdata = cache_get_data (client->md5file);
347 int cached = 0, keyarg = key ? 1 : 0;
348 size_t keysize;
349 unsigned char *salted_key = NULL;
350 int algo;
351 int pin_try = 1;
352 int pin_tries = 3;
353 char *pin_title = client->pinentry_opts.title;
355 client->crypto->filename = str_dup (client->filename);
356 if (cdata || client->flags & FLAG_NEW)
358 if (cdata && !(client->flags & FLAG_NEW))
360 rc = decrypt_cache (client->crypto, cdata->doc, cdata->doclen);
361 if (rc)
362 return rc;
365 cached = cdata != NULL;
366 goto done;
369 if (!key && !IS_PKI (client->crypto)
370 && !(client->crypto->hdr.flags & PWMD_FLAG_NO_PASSPHRASE))
372 if (client->flags & FLAG_NO_PINENTRY)
374 rc = inquire_passphrase (ctx, "PASSPHRASE", (unsigned char **)&key,
375 &keylen);
376 if (rc)
377 return rc;
379 else
381 client->pinentry_opts.timeout = config_get_integer (client->filename,
382 "pinentry_timeout");
383 pin_again:
384 rc = getpin_common (client->ctx, client->filename, PINENTRY_OPEN,
385 &key, &keylen);
386 if (rc)
387 return rc;
391 if (!IS_PKI (client->crypto))
393 if (client->crypto->hdr.flags & PWMD_FLAG_NO_PASSPHRASE)
395 keylen = 1;
396 key = gcry_malloc (keylen);
397 memset (key, 0, keylen);
400 algo = cipher_to_gcrypt (client->crypto->hdr.flags);
401 rc = hash_key (algo, client->crypto->hdr.salt,
402 sizeof(client->crypto->hdr.salt), key, keylen,
403 (void **)&salted_key, &keysize,
404 client->crypto->hdr.version <= 0x03000e ? COMPAT_KDFS2K_ITERATIONS : client->crypto->hdr.s2k_count);
405 if (!keyarg)
406 gcry_free (key);
408 if (!rc)
410 rc = decrypt_data (client->ctx, client->crypto, salted_key, keysize);
411 if (gpg_err_code (rc) == GPG_ERR_BAD_PASSPHRASE
412 && ++pin_try <= pin_tries && !(client->flags & FLAG_NO_PINENTRY))
414 gcry_free (salted_key);
415 salted_key = NULL;
416 key = NULL;
417 keylen = 0;
418 client->pinentry_opts.title = str_asprintf (_ ("Bad passphrase (try %i of %i)"), pin_try, pin_tries);
419 goto pin_again;
423 if (client->pinentry_opts.title != pin_title)
424 xfree (client->pinentry_opts.title);
426 client->pinentry_opts.title = pin_title;
427 if (rc)
429 gcry_free (salted_key);
430 return rc;
433 cdata = xcalloc (1, sizeof (struct cache_data_s));
434 if (!cdata)
436 gcry_free (salted_key);
437 return GPG_ERR_ENOMEM;
440 cdata->key = salted_key;
441 cdata->keylen = keysize;
443 else
444 #ifdef WITH_AGENT
445 rc = decrypt_data (client->ctx, client->crypto, NULL, 0);
446 #else
447 rc = GPG_ERR_NOT_IMPLEMENTED;
448 #endif
450 done:
451 if (!rc)
453 rc = parse_xml (ctx, client->flags & FLAG_NEW);
454 if (rc && !cached)
455 free_cache_data_once (cdata);
457 if (!rc)
459 int timeout = config_get_integer (client->filename,
460 "cache_timeout");
462 if (!cached)
464 if (!cdata)
465 cdata = xcalloc (1, sizeof (struct cache_data_s));
467 rc = encrypt_xml (NULL, cache_key, cache_keysize,
468 GCRY_CIPHER_AES, client->crypto->plaintext,
469 client->crypto->plaintext_len, &cdata->doc,
470 &cdata->doclen, &cache_iv, &cache_blocksize);
471 if (!rc && !(client->flags & FLAG_NEW) && IS_PKI (client->crypto))
473 rc = gcry_sexp_build ((gcry_sexp_t *) & cdata->pubkey, NULL,
474 "%S", client->crypto->pkey_sexp);
478 if (cdata->sigkey)
479 gcry_sexp_release (cdata->sigkey);
481 cdata->sigkey = NULL;
482 if (!rc && IS_PKI (client->crypto))
483 rc = gcry_sexp_build ((gcry_sexp_t *) &cdata->sigkey, NULL,
484 "%S", client->crypto->sigpkey_sexp);
486 if (!rc)
488 rc = cache_add_file (client->md5file,
489 (client->flags & FLAG_NEW) ? NULL
490 : client->crypto->grip, cdata, timeout);
491 if (rc)
493 if (!cached)
495 free_cache_data_once (cdata);
496 xmlFreeDoc (client->doc);
497 client->doc = NULL;
502 if (!rc)
503 client->flags |= FLAG_OPEN;
507 if (!rc)
508 rc = update_checksum (client);
510 if (!rc && (client->opts & OPT_LOCK_ON_OPEN))
511 rc = do_lock (client, 0);
513 return rc;
516 static void
517 req_cleanup (void *arg)
519 if (!arg)
520 return;
522 strv_free ((char **) arg);
525 static gpg_error_t
526 parse_open_opt_lock (void *data, void *value)
528 struct client_s *client = data;
530 client->opts |= OPT_LOCK_ON_OPEN;
531 return 0;
534 static gpg_error_t
535 parse_save_opt_inquire (void *data, void *value)
537 struct client_s *client = data;
538 gpg_error_t rc;
540 if (!(client->flags & FLAG_NEW))
542 rc = peer_is_invoker (client);
543 if (rc == GPG_ERR_EACCES)
544 return rc;
547 (void) value;
548 client->opts |= OPT_INQUIRE;
549 return 0;
552 static gpg_error_t
553 parse_opt_inquire (void *data, void *value)
555 struct client_s *client = data;
557 (void) value;
558 client->opts |= OPT_INQUIRE;
559 return 0;
562 static gpg_error_t
563 update_checksum (struct client_s *client)
565 unsigned char *crc;
566 size_t len;
567 struct cache_data_s *cdata;
568 gpg_error_t rc = get_checksum (client->filename, &crc, &len);
570 if (rc)
571 return rc;
573 xfree (client->crc);
574 client->crc = crc;
575 cdata = cache_get_data (client->md5file);
576 if (cdata)
578 xfree (cdata->crc);
579 cdata->crc = xmalloc (len);
580 memcpy (cdata->crc, crc, len);
583 return 0;
586 static gpg_error_t
587 validate_checksum (struct client_s *client, struct cache_data_s *cdata)
589 unsigned char *crc;
590 size_t len;
591 gpg_error_t rc;
592 int n = 0;
594 if (cdata && !cdata->crc)
595 return GPG_ERR_CHECKSUM;
597 rc = get_checksum (client->filename, &crc, &len);
598 if (rc)
599 return rc;
601 if (cdata)
602 n = memcmp (cdata->crc, crc, len);
603 else if (client->crc)
604 n = memcmp (client->crc, crc, len);
606 xfree (crc);
607 return n ? GPG_ERR_CHECKSUM : 0;
610 static gpg_error_t
611 do_open (assuan_context_t ctx, const char *password)
613 struct client_s *client = assuan_get_pointer (ctx);
614 struct cache_data_s *cdata;
615 gpg_error_t rc = 0;
616 int done = 0;
618 // Cached document?
619 cdata = cache_get_data (client->md5file);
620 if (cdata && cdata->doc)
622 int defer = 0;
624 /* This will check that the key is cached in the agent which needs to
625 * be determined for files that share a keygrip. */
626 if (!rc)
628 rc = cache_iscached (client->filename, &defer);
629 if ((!rc || rc == GPG_ERR_ENOENT) && defer)
630 rc = GPG_ERR_KEY_EXPIRED;
633 if (!rc && !(client->flags & FLAG_NEW))
634 rc = validate_checksum (client, cdata);
636 #ifdef WITH_GNUTLS
637 if (!rc && client->thd->remote
638 && config_get_boolean (client->filename, "tcp_require_key"))
639 rc = GPG_ERR_KEY_EXPIRED;
640 #endif
642 if (!rc && !password)
644 rc = read_data_header (client->filename, &client->crypto->hdr,
645 NULL, NULL);
646 if (!rc)
648 if (IS_PKI (client->crypto))
650 gcry_sexp_build (&client->crypto->pkey_sexp, NULL, "%S",
651 cdata->pubkey);
652 gcry_pk_get_keygrip (client->crypto->pkey_sexp,
653 client->crypto->grip);
654 gcry_sexp_build (&client->crypto->sigpkey_sexp, NULL, "%S",
655 cdata->sigkey);
656 gcry_pk_get_keygrip (client->crypto->sigpkey_sexp,
657 client->crypto->sign_grip);
660 if (!rc)
662 rc = open_finalize (ctx, NULL, 0);
663 done = 1;
668 /* There was an error accessing the file so clear the cache entry. The
669 * real error will be returned from read_data_file() since the file
670 * may have only disappeared. */
671 if (!done)
673 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
674 rc = cache_clear (client->md5file);
675 send_status_all (STATUS_CACHE, NULL);
679 if (done || rc)
680 return rc;
682 rc = read_data_file (client->filename, client->crypto);
683 if (rc)
685 if (gpg_err_source (rc) != GPG_ERR_SOURCE_DEFAULT ||
686 gpg_err_code (rc) != GPG_ERR_ENOENT)
688 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
689 return rc;
692 client->flags |= FLAG_NEW;
693 memset (client->crypto->grip, 0, sizeof (client->crypto->grip));
694 memset (client->crypto->sign_grip, 0,
695 sizeof (client->crypto->sign_grip));
696 rc = open_finalize (ctx, NULL, 0);
697 return rc;
700 if (password && IS_PKI (client->crypto))
702 #ifdef WITH_AGENT
703 rc = set_agent_passphrase (client->crypto, password, strlen (password));
704 if (rc)
705 return rc;
706 #endif
709 rc = open_finalize (ctx, (char *)password, password ? strlen (password) : 0);
710 return rc;
713 static gpg_error_t
714 open_command (assuan_context_t ctx, char *line)
716 gpg_error_t rc;
717 struct client_s *client = assuan_get_pointer (ctx);
718 char **req, *filename;
719 unsigned char md5file[16];
720 int same_file = 0;
721 assuan_peercred_t peer;
722 struct argv_s *args[] = {
723 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_open_opt_lock},
724 NULL
727 rc = parse_options (&line, args, client, 1);
728 if (rc)
729 return send_error (ctx, rc);
731 req = str_split (line, " ", 2);
732 if (!req)
733 return send_error (ctx, GPG_ERR_SYNTAX);
735 rc = do_validate_peer (ctx, req[0], &peer);
736 if (rc)
738 strv_free (req);
739 return send_error (ctx, rc);
742 filename = req[0];
743 if (!valid_filename (filename))
745 strv_free (req);
746 return send_error (ctx, GPG_ERR_INV_VALUE);
749 pthread_cleanup_push (req_cleanup, req);
750 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
751 /* This client may have locked a different file with ISCACHED --lock than
752 * the current filename. This will remove that lock. */
753 same_file = !memcmp (md5file, client->md5file, 16) ? 1 : 0;
754 if (client->flags & FLAG_OPEN ||
755 (client->flags & FLAG_HAS_LOCK && !same_file))
757 uint32_t opts = client->opts;
758 uint32_t flags = client->flags;
760 if (same_file)
761 client->flags |= FLAG_KEEP_LOCK;
762 else if (client->flags & FLAG_NEW)
763 cache_clear (client->md5file);
765 cleanup_client (client);
766 client->opts = opts;
767 client->flags |= flags;
768 client->flags &= ~(FLAG_LOCK_CMD);
769 if (!same_file)
770 client->flags &= ~(FLAG_HAS_LOCK | FLAG_NEW);
773 rc = lock_flock (ctx, filename, LOCK_SH, &client->flock_fd);
774 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
776 strv_free (req);
777 return send_error(ctx, rc);
780 memcpy (client->md5file, md5file, 16);
781 client->filename = str_dup (filename);
782 if (!client->filename)
784 strv_free (req);
785 return send_error(ctx, GPG_ERR_ENOMEM);
788 /* Need to lock the mutex here because file_modified() cannot without
789 * knowing the filename. */
790 rc = lock_file_mutex (client, 1);
791 if (rc)
792 client->flags &= ~FLAG_OPEN;
794 if (!rc)
796 char *password = req[1] && *req[1] ? req[1] : NULL;
798 #ifdef WITH_AGENT
799 if (IS_PKI (client->crypto))
800 rc = set_pinentry_mode (client->crypto->agent,
801 (client->flags & FLAG_NO_PINENTRY) ? "loopback"
802 : "ask");
803 #endif
804 if (!rc)
806 rc = do_open (ctx, password);
807 if (rc)
808 cleanup_client (client);
810 cleanup_crypto_stage1 (client->crypto);
814 pthread_cleanup_pop (1);
816 if (!rc && client->flags & FLAG_NEW)
817 rc = send_status (ctx, STATUS_NEWFILE, NULL);
819 #ifdef WITH_AGENT
820 (void) kill_scd (client->crypto->agent);
821 #endif
823 return send_error (ctx, rc);
826 static gpg_error_t
827 parse_opt_no_passphrase (void *data, void *value)
829 struct client_s *client = data;
831 (void) value;
832 client->opts |= OPT_NO_PASSPHRASE;
833 return 0;
836 static gpg_error_t
837 parse_save_opt_no_agent (void *data, void *value)
839 struct client_s *client = data;
841 client->opts |= OPT_NO_AGENT;
842 return 0;
845 static gpg_error_t
846 parse_save_opt_cipher (void *data, void *value)
848 struct client_s *client = data;
849 int algo = cipher_string_to_gcrypt ((char *) value);
850 file_header_t *hdr = &client->crypto->save.hdr;
851 gpg_error_t rc = 0;
853 if (algo == -1)
854 return GPG_ERR_INV_VALUE;
856 if (!(client->flags & FLAG_NEW))
858 rc = peer_is_invoker (client);
859 if (rc == GPG_ERR_EACCES)
861 uint64_t flags = 0;
863 flags &= ((uint16_t) ((uint32_t) (flags & 0xFFFFFFFF)));
864 if (!(client->crypto->hdr.flags & gcrypt_to_cipher (algo)))
865 return rc;
867 rc = 0;
869 else if (rc)
870 return rc;
873 if (!rc)
874 hdr->flags = set_cipher_flag (hdr->flags, algo);
876 return rc;
879 #ifdef WITH_AGENT
880 static gpg_error_t
881 permitted_to_save (struct client_s *client, const unsigned char *grip,
882 size_t size, const char *value)
884 char *hexgrip;
885 gpg_error_t rc = 0;
887 if (!(client->flags & FLAG_NEW))
889 hexgrip = bin2hex (grip, size);
890 rc = !strcmp (hexgrip, (char *)value) ? 0 : GPG_ERR_EACCES;
891 xfree (hexgrip);
892 if (rc)
893 rc = peer_is_invoker (client);
896 return rc;
898 #endif
900 static gpg_error_t
901 parse_save_opt_keygrip (void *data, void *value)
903 #ifdef WITH_AGENT
904 struct client_s *client = data;
905 gpg_error_t rc = permitted_to_save (client, client->crypto->grip,
906 sizeof (client->crypto->grip),
907 value);
909 if (!IS_PKI (client->crypto))
910 return GPG_ERR_INV_ARG;
912 if (rc)
913 return rc;
915 if (client->crypto->save.pkey)
916 gcry_sexp_release (client->crypto->save.pkey);
918 client->crypto->save.pkey = NULL;
919 return get_pubkey (client->crypto, value, &client->crypto->save.pkey);
920 #else
921 return GPG_ERR_INV_ARG;
922 #endif
925 static gpg_error_t
926 parse_save_opt_sign_keygrip (void *data, void *value)
928 #ifdef WITH_AGENT
929 struct client_s *client = data;
930 gpg_error_t rc = permitted_to_save (client, client->crypto->sign_grip,
931 sizeof (client->crypto->sign_grip),
932 value);
934 if (!IS_PKI (client->crypto))
935 return GPG_ERR_INV_ARG;
937 if (rc)
938 return rc;
940 if (client->crypto->save.sigpkey)
941 gcry_sexp_release (client->crypto->save.sigpkey);
943 client->crypto->save.sigpkey = NULL;
944 return get_pubkey (client->crypto, value, &client->crypto->save.sigpkey);
945 #else
946 return GPG_ERR_INV_ARG;
947 #endif
950 static gpg_error_t
951 parse_opt_s2k_count (void *data, void *value)
953 struct client_s *client = data;
954 char *v = value, *p;
955 uint64_t n;
957 if (!v || !*v)
958 return GPG_ERR_INV_VALUE;
960 errno = 0;
961 n = strtoull (v, &p, 10);
962 if (n == UINT64_MAX && errno)
963 return gpg_error_from_errno (errno);
964 else if (p && *p)
965 return GPG_ERR_INV_VALUE;
967 if (!(client->flags & FLAG_NEW))
969 gpg_error_t rc = peer_is_invoker (client);
971 if (rc == GPG_ERR_EACCES)
973 if (n && client->crypto->hdr.s2k_count != n)
974 return rc;
976 rc = 0;
978 else if (rc)
979 return rc;
982 // Keep compatibility with libpwmd passing --s2k-count=0. If somehow
983 // s2k_count == 0 it will be set to DEFAULT_KDFS2K_ITERATIONS in
984 // save_command().
985 if (n)
986 client->crypto->save.hdr.s2k_count = n;
988 return 0;
991 static gpg_error_t
992 save_finalize (assuan_context_t ctx)
994 struct client_s *client = assuan_get_pointer (ctx);
995 gpg_error_t rc = 0;
996 xmlChar *xmlbuf = NULL;
997 int xmlbuflen;
998 void *key = NULL;
999 size_t keylen = 0;
1001 xmlDocDumpFormatMemory (client->doc, &xmlbuf, &xmlbuflen, 0);
1002 if (!xmlbuf)
1003 return GPG_ERR_ENOMEM;
1005 pthread_cleanup_push (xmlFree, xmlbuf);
1007 if (!use_agent || ((client->flags & FLAG_NEW)
1008 && (client->opts & OPT_NO_AGENT))
1009 || !(client->crypto->hdr.flags & PWMD_FLAG_PKI))
1011 rc = export_common (ctx, client->flags & FLAG_NO_PINENTRY,
1012 client->crypto, xmlbuf, xmlbuflen, client->filename,
1013 NULL, &key, &keylen, 1, 1,
1014 (client->opts & OPT_NO_PASSPHRASE));
1016 #ifdef WITH_AGENT
1017 else
1019 gcry_sexp_t pubkey = client->crypto->save.pkey;
1020 gcry_sexp_t sigkey = client->crypto->save.sigpkey;
1022 if (!pubkey)
1023 pubkey = client->crypto->pkey_sexp;
1025 if (!sigkey)
1027 sigkey = client->crypto->sigpkey_sexp;
1028 if (!sigkey)
1030 gcry_sexp_build (&client->crypto->save.sigpkey, 0, "%S", pubkey);
1031 sigkey = client->crypto->save.sigpkey;
1035 rc = encrypt_data_file (client->ctx, client->crypto, pubkey, sigkey,
1036 client->filename, xmlbuf, xmlbuflen);
1037 if (pubkey == client->crypto->save.pkey)
1039 if (!rc)
1041 gcry_sexp_release (client->crypto->pkey_sexp);
1042 client->crypto->pkey_sexp = client->crypto->save.pkey;
1043 gcry_pk_get_keygrip (client->crypto->pkey_sexp,
1044 client->crypto->grip);
1046 else
1047 gcry_sexp_release (pubkey);
1049 client->crypto->save.pkey = NULL;
1052 if (!rc)
1053 gcry_pk_get_keygrip (sigkey, client->crypto->sign_grip);
1055 if (sigkey == client->crypto->save.sigpkey)
1057 if (!rc)
1059 if (client->crypto->sigpkey_sexp)
1060 gcry_sexp_release (client->crypto->sigpkey_sexp);
1062 client->crypto->sigpkey_sexp = client->crypto->save.sigpkey;
1063 gcry_pk_get_keygrip (client->crypto->sigpkey_sexp,
1064 client->crypto->sign_grip);
1066 else
1067 gcry_sexp_release (sigkey);
1069 client->crypto->save.sigpkey = NULL;
1072 #endif
1074 if (!rc)
1076 int cached;
1078 rc = save_common (client->filename, client->crypto, xmlbuf, xmlbuflen,
1079 key, keylen, &cached, client->opts & OPT_NO_AGENT);
1080 gcry_free (key);
1082 if (!rc && (!cached || (client->flags & FLAG_NEW)))
1083 send_status_all (STATUS_CACHE, NULL);
1085 if (!rc)
1087 rc = update_checksum (client);
1088 client->flags &= ~(FLAG_NEW);
1092 pthread_cleanup_pop (1); // xmlFree
1093 return rc;
1096 static gpg_error_t
1097 parse_opt_reset (void *data, void *value)
1099 struct client_s *client = data;
1101 (void) value;
1102 client->opts |= OPT_RESET;
1103 return 0;
1106 static gpg_error_t
1107 parse_opt_ask (void *data, void *value)
1109 struct client_s *client = data;
1111 (void) value;
1112 client->opts |= OPT_ASK;
1113 return 0;
1116 static gpg_error_t
1117 save_command (assuan_context_t ctx, char *line)
1119 struct client_s *client = assuan_get_pointer (ctx);
1120 gpg_error_t rc;
1121 struct stat st;
1122 struct argv_s *args[] = {
1123 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG,
1124 parse_opt_no_passphrase},
1125 &(struct argv_s) {"cipher", OPTION_TYPE_ARG, parse_save_opt_cipher},
1126 &(struct argv_s) {"inquire-keyparam", OPTION_TYPE_NOARG,
1127 parse_save_opt_inquire},
1128 &(struct argv_s) {"keygrip", OPTION_TYPE_ARG, parse_save_opt_keygrip},
1129 &(struct argv_s) {"sign-keygrip", OPTION_TYPE_ARG,
1130 parse_save_opt_sign_keygrip},
1131 &(struct argv_s) {"s2k-count", OPTION_TYPE_ARG, parse_opt_s2k_count},
1132 &(struct argv_s) {"reset", OPTION_TYPE_NOARG, parse_opt_reset},
1133 &(struct argv_s) {"cipher-iterations", OPTION_TYPE_ARG,
1134 parse_opt_s2k_count},
1135 &(struct argv_s) {"no-agent", OPTION_TYPE_NOARG,
1136 parse_save_opt_no_agent},
1137 &(struct argv_s) {"ask", OPTION_TYPE_NOARG,
1138 parse_opt_ask},
1139 NULL
1142 cleanup_save (&client->crypto->save);
1143 memcpy (&client->crypto->save.hdr, &client->crypto->hdr,
1144 sizeof (file_header_t));
1146 rc = parse_options (&line, args, client, 0);
1147 if (rc)
1148 return send_error (ctx, rc);
1150 if (!(client->flags & FLAG_NEW))
1151 client->opts &= ~OPT_NO_AGENT;
1152 else if (client->opts & OPT_NO_AGENT)
1154 client->crypto->save.hdr.flags &= ~PWMD_FLAG_PKI;
1155 client->crypto->hdr.flags &= ~PWMD_FLAG_PKI;
1158 /* Update to the default hash iteration count for data file
1159 * versions <= 3.0.14. */
1160 #ifdef WITH_AGENT
1161 if ((!IS_PKI (client->crypto) && client->crypto->hdr.version <= 0x03000e
1162 && client->crypto->save.hdr.s2k_count < DEFAULT_KDFS2K_ITERATIONS)
1163 || (!IS_PKI (client->crypto) && !client->crypto->save.hdr.s2k_count))
1164 #else
1165 if ((client->crypto->hdr.version <= 0x03000e
1166 && client->crypto->save.hdr.s2k_count < DEFAULT_KDFS2K_ITERATIONS)
1167 || !client->crypto->save.hdr.s2k_count)
1168 #endif
1170 client->crypto->save.hdr.s2k_count =
1171 config_get_ulonglong (client->filename, "s2k_count");
1172 if (!client->crypto->save.hdr.s2k_count)
1173 client->crypto->save.hdr.s2k_count = DEFAULT_KDFS2K_ITERATIONS;
1176 /* Deal with the hashed vs non-hashed cached key mess by clearing the cached
1177 * key entry. */
1178 if (client->crypto->hdr.version <= 0x03000e && !IS_PKI (client->crypto))
1179 client->opts |= OPT_RESET;
1180 else if (!IS_PKI (client->crypto) && !(client->flags & FLAG_NEW)
1181 && client->crypto->hdr.s2k_count !=
1182 client->crypto->save.hdr.s2k_count)
1183 client->opts |= OPT_RESET;
1185 if ((client->opts & OPT_NO_PASSPHRASE) && !(client->flags & FLAG_NEW)
1186 && !(client->opts & OPT_INQUIRE))
1187 return send_error (ctx, GPG_ERR_WRONG_KEY_USAGE);
1189 if (lstat (client->filename, &st) == -1 && errno != ENOENT)
1190 return send_error (ctx, gpg_error_from_errno (errno));
1192 if (errno != ENOENT && !S_ISREG (st.st_mode))
1194 log_write ("%s: %s", client->filename, pwmd_strerror (GPG_ERR_ENOANO));
1195 return send_error (ctx, GPG_ERR_ENOANO);
1198 int defer = 0;
1199 rc = cache_iscached (client->filename, &defer);
1200 if (gpg_err_code (rc) == GPG_ERR_ENOENT && client->flags & FLAG_NEW)
1201 rc = 0;
1202 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
1203 rc = 0;
1205 if ((!rc && defer))
1206 client->opts |= OPT_RESET;
1207 else if (config_get_boolean ("global", "require_save_key"))
1208 client->opts |= OPT_ASK;
1210 if (!rc && (client->opts & OPT_RESET))
1212 rc = cache_clear (client->md5file);
1213 if (rc)
1214 return send_error (ctx, rc);
1216 log_write ("%s: %s", client->filename,
1217 pwmd_strerror (GPG_ERR_KEY_EXPIRED));
1218 send_status_all (STATUS_CACHE, NULL);
1221 if (!rc && client->opts & OPT_ASK)
1222 rc = crypto_try_decrypt (ctx, client->flags & FLAG_NO_PINENTRY,
1223 client->filename, NULL, NULL, NULL);
1225 if (!rc)
1226 rc = update_element_mtime (client, xmlDocGetRootElement (client->doc));
1228 if (rc)
1229 return send_error (ctx, rc);
1231 #ifdef WITH_AGENT
1232 if (!rc && use_agent && !client->crypto->save.pkey &&
1233 (client->flags & FLAG_NEW || client->opts & OPT_INQUIRE)
1234 && !(client->opts & OPT_NO_AGENT))
1236 rc = set_pinentry_mode (client->crypto->agent,
1237 (client->flags & FLAG_NO_PINENTRY) ? "loopback"
1238 : "ask");
1240 if (!(client->flags & FLAG_NEW))
1242 struct crypto_s *crypto;
1243 void *key = NULL;
1244 size_t keylen = 0;
1246 /* Wanting to generate a new key. Require the key to open the
1247 current file before proceeding reguardless of the
1248 require_save_key configuration parameter. */
1249 rc = cache_clear (client->md5file);
1250 if (!rc)
1252 rc = init_client_crypto (&crypto);
1253 if (!rc)
1254 crypto->client_ctx = client->ctx;
1257 if (!rc)
1258 rc = decrypt_common (client->ctx, client->opts&OPT_INQUIRE, crypto,
1259 client->filename, &key, &keylen, NULL, NULL);
1261 xfree (key);
1262 cleanup_crypto (&crypto);
1265 if (!rc)
1266 rc = send_status (client->ctx, STATUS_GENKEY, NULL);
1268 if (!rc)
1270 struct inquire_data_s idata = { 0 };
1271 char *params = client->opts & OPT_INQUIRE
1272 ? NULL : default_key_params (client->crypto);
1274 pthread_cleanup_push (xfree, params);
1275 idata.crypto = client->crypto;
1277 if (params)
1279 idata.line = params;
1280 idata.len = strlen (params);
1282 else
1283 idata.preset = 1;
1285 client->crypto->agent->inquire_data = &idata;
1286 client->crypto->agent->inquire_cb = NULL;
1287 rc = generate_key (client->crypto, params,
1288 (client->opts & OPT_NO_PASSPHRASE), 1);
1289 pthread_cleanup_pop (1);
1292 #endif
1294 if (!rc)
1295 rc = save_finalize (ctx);
1297 cleanup_crypto_stage1 (client->crypto);
1298 #ifdef WITH_AGENT
1299 (void) kill_scd (client->crypto->agent);
1300 #endif
1301 return send_error (ctx, rc);
1304 static gpg_error_t
1305 do_delete (assuan_context_t ctx, char *line)
1307 struct client_s *client = assuan_get_pointer (ctx);
1308 gpg_error_t rc;
1309 char **req;
1310 xmlNodePtr n;
1312 if (strchr (line, '\t'))
1313 req = str_split (line, "\t", 0);
1314 else
1315 req = str_split (line, " ", 0);
1317 if (!req || !*req)
1318 return GPG_ERR_SYNTAX;
1320 n = find_root_element (client, client->doc, &req, &rc, NULL, 0, 0);
1321 if (!n || rc)
1323 strv_free (req);
1324 return rc;
1328 * No sub-node defined. Remove the entire node (root element).
1330 if (!req[1])
1332 if (n)
1334 rc = is_element_owner (client, n);
1335 if (!rc)
1337 rc = unlink_node (client, n);
1338 xmlFreeNode (n);
1342 strv_free (req);
1343 return rc;
1346 n = find_elements (client, client->doc, n->children, req + 1, &rc, NULL,
1347 NULL, NULL, 0, 0, NULL, 0);
1348 strv_free (req);
1349 if (!n || rc)
1350 return rc;
1352 rc = is_element_owner (client, n);
1353 if (!rc)
1355 rc = unlink_node (client, n);
1356 xmlFreeNode (n);
1359 return rc;
1362 static gpg_error_t
1363 delete_command (assuan_context_t ctx, char *line)
1365 struct client_s *client = assuan_get_pointer (ctx);
1366 gpg_error_t rc;
1367 struct argv_s *args[] = {
1368 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1369 NULL
1372 rc = parse_options (&line, args, client, 1);
1373 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1374 rc = GPG_ERR_SYNTAX;
1375 if (rc)
1376 return send_error (ctx, rc);
1378 if (client->opts & OPT_INQUIRE)
1380 unsigned char *result;
1381 size_t len;
1383 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1384 if (rc)
1385 return send_error (ctx, rc);
1387 pthread_cleanup_push (xfree, result);
1388 rc = do_delete (ctx, (char *)result);
1389 pthread_cleanup_pop (1);
1391 else
1392 rc = do_delete (ctx, line);
1394 return send_error (ctx, rc);
1397 static gpg_error_t
1398 store_command (assuan_context_t ctx, char *line)
1400 struct client_s *client = assuan_get_pointer (ctx);
1401 gpg_error_t rc;
1402 size_t len;
1403 unsigned char *result;
1404 char **req;
1405 xmlNodePtr n, parent;
1406 int has_content;
1407 char *content = NULL;
1409 if (line && *line)
1410 return send_error (ctx, GPG_ERR_SYNTAX);
1412 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1413 if (rc)
1414 return send_error (ctx, rc);
1416 req = str_split ((char *) result, "\t", 0);
1417 xfree (result);
1419 if (!req || !*req)
1420 return send_error (ctx, GPG_ERR_SYNTAX);
1422 len = strv_length (req);
1423 has_content = line[strlen (line) - 1] != '\t' && len > 1;
1424 if (*(req + 1) && !valid_element_path (req, has_content))
1426 strv_free (req);
1427 return send_error (ctx, GPG_ERR_INV_VALUE);
1430 if (has_content || !*req[len - 1])
1432 has_content = 1;
1433 content = req[len - 1];
1434 req[len - 1] = NULL;
1437 again:
1438 n = find_root_element (client, client->doc, &req, &rc, NULL, 0, 0);
1439 if (rc && rc == GPG_ERR_ELEMENT_NOT_FOUND)
1441 rc = new_root_element (client, client->doc, *req);
1442 if (rc)
1444 strv_free (req);
1445 return send_error (ctx, rc);
1448 goto again;
1451 if (!n || rc)
1453 strv_free (req);
1454 return send_error (ctx, rc);
1457 parent = n;
1459 if (req[1] && *req[1])
1461 if (!n->children)
1462 parent = create_elements_cb (client, 1, n, req + 1, &rc, NULL);
1463 else
1464 parent = find_elements (client, client->doc, n->children, req + 1, &rc,
1465 NULL, NULL, create_elements_cb, 0, 0, NULL,
1469 if (!rc && len > 1)
1471 rc = is_element_owner (client, parent);
1472 if (!rc)
1474 n = find_text_node (parent->children);
1475 if (n)
1476 xmlNodeSetContent (n, (xmlChar *) content);
1477 else
1478 xmlNodeAddContent (parent, (xmlChar *) content);
1480 update_element_mtime (client, parent);
1484 xfree (content);
1485 strv_free (req);
1486 return send_error (ctx, rc);
1489 static gpg_error_t
1490 xfer_data (assuan_context_t ctx, const char *line, int total)
1492 int to_send;
1493 int sent = 0;
1494 gpg_error_t rc;
1495 int progress = config_get_integer ("global", "xfer_progress");
1496 int flush = 0;
1498 progress =
1499 progress > 0 ? (progress / ASSUAN_LINELENGTH) * ASSUAN_LINELENGTH : 0;
1500 to_send = total < ASSUAN_LINELENGTH ? total : ASSUAN_LINELENGTH;
1501 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1503 if (rc)
1504 return rc;
1506 again:
1509 if (sent + to_send > total)
1510 to_send = total - sent;
1512 rc = assuan_send_data (ctx, flush ? NULL : (char *) line + sent,
1513 flush ? 0 : to_send);
1514 if (!rc)
1516 sent += flush ? 0 : to_send;
1518 if ((progress && !(sent % progress) && sent != total) ||
1519 (sent == total && flush))
1520 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1522 if (!flush && !rc && sent == total)
1524 flush = 1;
1525 goto again;
1529 while (!rc && sent < total);
1531 return rc;
1534 static gpg_error_t
1535 do_get (assuan_context_t ctx, char *line)
1537 struct client_s *client = assuan_get_pointer (ctx);
1538 gpg_error_t rc;
1539 char **req;
1540 xmlNodePtr n;
1542 req = str_split (line, "\t", 0);
1544 if (!req || !*req)
1546 strv_free (req);
1547 return GPG_ERR_SYNTAX;
1550 n = find_root_element (client, client->doc, &req, &rc, NULL, 0, 0);
1551 if (!n || rc)
1553 strv_free (req);
1554 return rc;
1557 if (req[1])
1558 n = find_elements (client, client->doc, n->children, req + 1, &rc,
1559 NULL, NULL, NULL, 0, 0, NULL, 0);
1561 strv_free (req);
1562 if (rc)
1563 return rc;
1565 if (!n || !n->children)
1566 return GPG_ERR_NO_DATA;
1568 n = find_text_node (n->children);
1569 if (!n || !n->content || !*n->content)
1570 return GPG_ERR_NO_DATA;
1572 rc = xfer_data (ctx, (char *) n->content, xmlStrlen (n->content));
1573 return rc;
1576 static gpg_error_t
1577 get_command (assuan_context_t ctx, char *line)
1579 struct client_s *client = assuan_get_pointer (ctx);
1580 gpg_error_t rc;
1581 struct argv_s *args[] = {
1582 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1583 NULL
1586 rc = parse_options (&line, args, client, 1);
1587 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1588 rc = GPG_ERR_SYNTAX;
1589 if (rc)
1590 return send_error (ctx, rc);
1592 if (client->opts & OPT_INQUIRE)
1594 unsigned char *result;
1595 size_t len;
1597 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1598 if (rc)
1599 return send_error (ctx, rc);
1601 pthread_cleanup_push (xfree, result);
1602 rc = do_get (ctx, (char *)result);
1603 pthread_cleanup_pop (1);
1605 else
1606 rc = do_get (ctx, line);
1608 return send_error (ctx, rc);
1611 static void list_command_cleanup1 (void *arg);
1612 static gpg_error_t
1613 realpath_command (assuan_context_t ctx, char *line)
1615 struct string_s *string = NULL;
1616 gpg_error_t rc;
1617 struct client_s *client = assuan_get_pointer (ctx);
1618 struct argv_s *args[] = {
1619 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1620 NULL
1623 rc = parse_options (&line, args, client, 1);
1624 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1625 rc = GPG_ERR_SYNTAX;
1626 if (rc)
1627 return send_error (ctx, rc);
1629 if (client->opts & OPT_INQUIRE)
1631 unsigned char *result;
1632 size_t len;
1634 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1635 if (rc)
1636 return send_error (ctx, rc);
1638 pthread_cleanup_push (xfree, result);
1639 rc = build_realpath (client, client->doc, (char *)result, &string);
1640 pthread_cleanup_pop (1);
1642 else
1643 rc = build_realpath (client, client->doc, line, &string);
1645 if (!rc)
1647 pthread_cleanup_push (list_command_cleanup1, string);
1648 rc = xfer_data (ctx, string->str, string->len);
1649 pthread_cleanup_pop (1);
1652 return send_error (ctx, rc);
1655 static void
1656 list_command_cleanup1 (void *arg)
1658 if (arg)
1659 string_free ((struct string_s *) arg, 1);
1662 static void
1663 list_command_cleanup2 (void *arg)
1665 struct element_list_s *elements = arg;
1667 if (elements)
1669 if (elements->list)
1671 int total = slist_length (elements->list);
1672 int i;
1674 for (i = 0; i < total; i++)
1676 char *tmp = slist_nth_data (elements->list, i);
1677 xfree (tmp);
1680 slist_free (elements->list);
1683 if (elements->prefix)
1684 xfree (elements->prefix);
1686 if (elements->req)
1687 strv_free (elements->req);
1689 xfree (elements);
1693 static gpg_error_t
1694 parse_list_opt_norecurse (void *data, void *value)
1696 struct client_s *client = data;
1698 client->opts &= ~(OPT_LIST_RECURSE);
1699 return 0;
1702 static gpg_error_t
1703 parse_opt_verbose (void *data, void *value)
1705 struct client_s *client = data;
1707 client->opts |= OPT_VERBOSE;
1708 return 0;
1711 static gpg_error_t
1712 parse_list_opt_target (void *data, void *value)
1714 struct client_s *client = data;
1716 client->opts |= OPT_LIST_WITH_TARGET;
1717 return 0;
1720 static gpg_error_t
1721 parse_list_opt_all (void *data, void *value)
1723 struct client_s *client = data;
1725 client->opts |= OPT_LIST_ALL;
1726 return 0;
1729 static gpg_error_t
1730 list_path_once (struct client_s *client, char *line,
1731 struct element_list_s *elements, struct string_s *result)
1733 gpg_error_t rc;
1735 elements->req = str_split (line, " ", 0);
1736 if (!elements->req)
1737 strv_printf (&elements->req, "%s", line);
1739 rc = create_path_list (client, client->doc, elements, *elements->req);
1740 if ((rc == GPG_ERR_ELOOP || rc == GPG_ERR_EACCES) && elements->verbose)
1741 rc = 0;
1743 if (!rc)
1745 int total = slist_length (elements->list);
1747 if (total)
1749 int i;
1751 for (i = 0; i < total; i++)
1753 char *tmp = slist_nth_data (elements->list, i);
1755 string_append_printf (result, "%s%s", tmp,
1756 i + 1 == total ? "" : "\n");
1759 else
1760 rc = GPG_ERR_NO_DATA;
1763 return rc;
1766 static int
1767 has_list_flag (char *path, char *flags)
1769 char *p = path;
1771 while (*p && *++p != ' ');
1773 if (!*p)
1774 return 0;
1776 for (; *p; p++)
1778 char *f;
1780 for (f = flags; *f && *f != ' '; f++)
1782 if (*p == *f)
1783 return 1;
1787 return 0;
1790 static gpg_error_t
1791 do_list (assuan_context_t ctx, char *line)
1793 struct client_s *client = assuan_get_pointer (ctx);
1794 gpg_error_t rc;
1795 struct element_list_s *elements = NULL;
1797 elements = xcalloc (1, sizeof (struct element_list_s));
1798 if (!elements)
1799 return GPG_ERR_ENOMEM;
1801 elements->recurse = client->opts & OPT_LIST_RECURSE;
1802 elements->verbose =
1803 (client->opts & OPT_VERBOSE) | (client->opts & OPT_LIST_WITH_TARGET);
1804 elements->with_target = client->opts & OPT_LIST_WITH_TARGET;
1806 if (!line || !*line)
1808 struct string_s *str = NULL;
1810 pthread_cleanup_push (list_command_cleanup2, elements);
1811 rc = list_root_elements (client, client->doc, &str, elements->verbose,
1812 elements->with_target);
1813 pthread_cleanup_pop (1);
1814 pthread_cleanup_push (list_command_cleanup1, str);
1816 if (!rc)
1818 if (client->opts & OPT_LIST_ALL)
1820 char **roots = str_split (str->str, "\n", 0);
1821 char **p;
1823 pthread_cleanup_push (req_cleanup, roots);
1824 string_truncate (str, 0);
1826 for (p = roots; *p; p++)
1828 if (strchr (*p, ' '))
1830 if (has_list_flag (*p, "EOP"))
1832 string_append_printf (str, "%s%s", *p,
1833 *(p + 1) ? "\n" : "");
1834 continue;
1838 elements = xcalloc (1, sizeof (struct element_list_s));
1839 if (!elements)
1841 rc = GPG_ERR_ENOMEM;
1842 break;
1845 elements->recurse = client->opts & OPT_LIST_RECURSE;
1846 elements->verbose =
1847 (client->opts & OPT_VERBOSE) | (client->opts &
1848 OPT_LIST_WITH_TARGET);
1849 elements->with_target = client->opts & OPT_LIST_WITH_TARGET;
1850 pthread_cleanup_push (list_command_cleanup2, elements);
1851 rc = list_path_once (client, *p, elements, str);
1852 pthread_cleanup_pop (1);
1853 if (rc)
1854 break;
1856 if (*(p + 1))
1857 string_append (str, "\n");
1860 pthread_cleanup_pop (1);
1863 if (!rc)
1864 rc = xfer_data (ctx, str->str, str->len);
1867 pthread_cleanup_pop (1);
1868 return rc;
1871 pthread_cleanup_push (list_command_cleanup2, elements);
1872 struct string_s *str = string_new (NULL);
1873 pthread_cleanup_push (list_command_cleanup1, str);
1874 rc = list_path_once (client, line, elements, str);
1875 if (!rc)
1876 rc = xfer_data (ctx, str->str, str->len);
1878 pthread_cleanup_pop (1);
1879 pthread_cleanup_pop (1);
1880 return rc;
1883 static gpg_error_t
1884 list_command (assuan_context_t ctx, char *line)
1886 struct client_s *client = assuan_get_pointer (ctx);
1887 gpg_error_t rc;
1888 struct argv_s *args[] = {
1889 &(struct argv_s) {"no-recurse", OPTION_TYPE_NOARG,
1890 parse_list_opt_norecurse},
1891 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_opt_verbose},
1892 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1893 &(struct argv_s) {"with-target", OPTION_TYPE_NOARG,
1894 parse_list_opt_target},
1895 &(struct argv_s) {"all", OPTION_TYPE_NOARG, parse_list_opt_all},
1896 NULL
1899 if (disable_list_and_dump == 1)
1900 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
1902 client->opts |= OPT_LIST_RECURSE;
1903 rc = parse_options (&line, args, client, 1);
1904 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1905 rc = GPG_ERR_SYNTAX;
1906 if (rc)
1907 return send_error (ctx, rc);
1909 if (client->opts & OPT_LIST_ALL)
1910 client->opts |= OPT_LIST_RECURSE | OPT_VERBOSE;
1912 if (client->opts & OPT_INQUIRE)
1914 unsigned char *result;
1915 size_t len;
1917 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1918 if (rc)
1919 return send_error (ctx, rc);
1921 pthread_cleanup_push (xfree, result);
1922 rc = do_list (ctx, (char *)result);
1923 pthread_cleanup_pop (1);
1925 else
1926 rc = do_list (ctx, line);
1928 return send_error (ctx, rc);
1932 * req[0] - element path
1934 static gpg_error_t
1935 attribute_list (assuan_context_t ctx, char **req)
1937 struct client_s *client = assuan_get_pointer (ctx);
1938 char **attrlist = NULL;
1939 int i = 0;
1940 char **path = NULL;
1941 xmlAttrPtr a;
1942 xmlNodePtr n, an;
1943 char *line;
1944 gpg_error_t rc;
1946 if (!req || !req[0])
1947 return GPG_ERR_SYNTAX;
1949 client->flags |= FLAG_ACL_IGNORE;
1951 if ((path = str_split (req[0], "\t", 0)) == NULL)
1954 * The first argument may be only a root element.
1956 if ((path = str_split (req[0], " ", 0)) == NULL)
1957 return GPG_ERR_SYNTAX;
1960 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 0);
1961 if (!n || rc)
1963 strv_free (path);
1964 return rc;
1967 if (client->flags & FLAG_ACL_ERROR)
1969 client->flags &= ~FLAG_ACL_IGNORE;
1970 if (path[1])
1972 strv_free (path);
1973 return GPG_ERR_EACCES;
1976 client->flags &= ~FLAG_ACL_ERROR;
1979 if (path[1])
1981 n = find_elements (client, client->doc, n->children, path + 1, &rc,
1982 NULL, NULL, NULL, 0, 0, NULL, 0);
1983 if (!n || rc)
1985 strv_free (path);
1986 return rc;
1990 strv_free (path);
1992 for (a = n->properties; a; a = a->next)
1994 char **pa;
1996 if ((pa = xrealloc (attrlist, (i + 2) * sizeof (char *))) == NULL)
1998 if (attrlist)
1999 strv_free (attrlist);
2001 log_write ("%s(%i): %s", __FILE__, __LINE__,
2002 pwmd_strerror (GPG_ERR_ENOMEM));
2003 return GPG_ERR_ENOMEM;
2006 attrlist = pa;
2007 an = a->children;
2008 attrlist[i] = str_asprintf ("%s %s", (char *) a->name,
2010 && an->content ? (char *) an->content : "");
2012 if (!attrlist[i])
2014 strv_free (attrlist);
2015 log_write ("%s(%i): %s", __FILE__, __LINE__,
2016 pwmd_strerror (GPG_ERR_ENOMEM));
2017 return GPG_ERR_ENOMEM;
2020 attrlist[++i] = NULL;
2023 if (!attrlist)
2024 return GPG_ERR_NO_DATA;
2026 line = strv_join ("\n", attrlist);
2028 if (!line)
2030 log_write ("%s(%i): %s", __FILE__, __LINE__,
2031 pwmd_strerror (GPG_ERR_ENOMEM));
2032 strv_free (attrlist);
2033 return GPG_ERR_ENOMEM;
2036 pthread_cleanup_push (xfree, line);
2037 pthread_cleanup_push (req_cleanup, attrlist);
2038 rc = xfer_data (ctx, line, strlen (line));
2039 pthread_cleanup_pop (1);
2040 pthread_cleanup_pop (1);
2041 return rc;
2045 * req[0] - attribute
2046 * req[1] - element path
2048 static gpg_error_t
2049 attribute_delete (struct client_s *client, char **req)
2051 xmlNodePtr n;
2052 char **path = NULL;
2053 gpg_error_t rc;
2055 if (!req || !req[0] || !req[1])
2056 return GPG_ERR_SYNTAX;
2058 if (!strcmp (req[0], "_name"))
2059 return GPG_ERR_INV_ATTR;
2061 if ((path = str_split (req[1], "\t", 0)) == NULL)
2064 * The first argument may be only a root element.
2066 if ((path = str_split (req[1], " ", 0)) == NULL)
2067 return GPG_ERR_SYNTAX;
2070 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 0);
2071 if (!n || rc)
2072 goto fail;
2074 if (path[1])
2076 n = find_elements (client, client->doc, n->children, path + 1, &rc,
2077 NULL, NULL, NULL, 0, 0, NULL, 0);
2078 if (!n || rc)
2079 goto fail;
2082 if (!strcmp (req[0], (char *) "_acl"))
2084 rc = is_element_owner (client, n);
2085 if (rc)
2086 goto fail;
2089 rc = delete_attribute (client, n, (xmlChar *) req[0]);
2091 fail:
2092 strv_free (path);
2093 return rc;
2096 static xmlNodePtr
2097 create_element_path (struct client_s *client,
2098 char ***elements, gpg_error_t * rc, xmlNodePtr parent)
2100 char **req = *elements;
2101 char **req_orig = strv_dup (req);
2102 xmlNodePtr n = NULL;
2104 *rc = 0;
2106 if (!req_orig)
2108 *rc = GPG_ERR_ENOMEM;
2109 log_write ("%s(%i): %s", __FILE__, __LINE__,
2110 pwmd_strerror (GPG_ERR_ENOMEM));
2111 goto fail;
2114 again:
2115 n = find_root_element (client, client->doc, &req, rc, NULL, 0, 0);
2116 if (!n)
2118 if (*rc != GPG_ERR_ELEMENT_NOT_FOUND)
2119 goto fail;
2121 *rc = new_root_element (client, client->doc, req[0]);
2122 if (*rc)
2123 goto fail;
2125 goto again;
2127 else if (n == parent)
2129 *rc = GPG_ERR_CONFLICT;
2130 goto fail;
2133 if (req[1])
2135 if (!n->children)
2136 n = create_target_elements_cb (client, 1, n, req + 1, rc, NULL);
2137 else
2138 n = find_elements (client, client->doc, n->children, req + 1, rc,
2139 NULL, NULL, create_target_elements_cb, 0, 0,
2140 parent, 0);
2142 if (!n)
2143 goto fail;
2146 * Reset the position of the element tree now that the elements
2147 * have been created.
2149 strv_free (req);
2150 req = req_orig;
2151 req_orig = NULL;
2152 n = find_root_element (client, client->doc, &req, rc, NULL, 0, 0);
2153 if (!n)
2154 goto fail;
2156 n = find_elements (client, client->doc, n->children, req + 1, rc,
2157 NULL, NULL, NULL, 0, 0, NULL, 0);
2158 if (!n)
2159 goto fail;
2162 fail:
2163 if (req_orig)
2164 strv_free (req_orig);
2166 *elements = req;
2167 return n;
2171 * Creates a "target" attribute. When other commands encounter an element with
2172 * this attribute, the element path is modified to the target value. If the
2173 * source element path doesn't exist when using 'ATTR SET target', it is
2174 * created, but the destination element path must exist.
2176 * req[0] - source element path
2177 * req[1] - destination element path
2179 static gpg_error_t
2180 target_attribute (struct client_s *client, char **req)
2182 char **src, **dst, *line = NULL, **odst = NULL;
2183 gpg_error_t rc;
2184 xmlNodePtr n;
2186 if (!req || !req[0] || !req[1])
2187 return GPG_ERR_SYNTAX;
2189 if ((src = str_split (req[0], "\t", 0)) == NULL)
2192 * The first argument may be only a root element.
2194 if ((src = str_split (req[0], " ", 0)) == NULL)
2195 return GPG_ERR_SYNTAX;
2198 if (!valid_element_path (src, 0))
2199 return GPG_ERR_INV_VALUE;
2201 if ((dst = str_split (req[1], "\t", 0)) == NULL)
2204 * The first argument may be only a root element.
2206 if ((dst = str_split (req[1], " ", 0)) == NULL)
2208 rc = GPG_ERR_SYNTAX;
2209 goto fail;
2213 odst = strv_dup (dst);
2214 if (!odst)
2216 rc = GPG_ERR_ENOMEM;
2217 goto fail;
2220 n = find_root_element (client, client->doc, &dst, &rc, NULL, 0, 0);
2222 * Make sure the destination element path exists.
2224 if (rc && rc != GPG_ERR_EACCES)
2225 goto fail;
2227 rc = 0;
2228 if (dst[1])
2230 n = find_elements (client, client->doc, n->children, dst + 1, &rc,
2231 NULL, NULL, NULL, 0, 0, NULL, 0);
2232 if (rc && rc != GPG_ERR_EACCES)
2233 goto fail;
2236 rc = validate_target_attribute (client, client->doc, req[0], n);
2237 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2238 goto fail;
2240 n = create_element_path (client, &src, &rc, NULL);
2241 if (rc)
2242 goto fail;
2244 line = strv_join ("\t", odst);
2245 if (!line)
2247 rc = GPG_ERR_ENOMEM;
2248 goto fail;
2251 rc = add_attribute (client, n, "target", line);
2253 fail:
2254 xfree (line);
2255 strv_free (src);
2256 strv_free (dst);
2257 strv_free (odst);
2258 return rc;
2262 * req[0] - attribute
2263 * req[1] - element path
2265 static gpg_error_t
2266 attribute_get (assuan_context_t ctx, char **req)
2268 struct client_s *client = assuan_get_pointer (ctx);
2269 xmlNodePtr n;
2270 xmlChar *a;
2271 char **path = NULL;
2272 gpg_error_t rc;
2274 if (!req || !req[0] || !req[1])
2275 return GPG_ERR_SYNTAX;
2277 if (strchr (req[1], '\t'))
2279 if ((path = str_split (req[1], "\t", 0)) == NULL)
2280 return GPG_ERR_SYNTAX;
2282 else
2284 if ((path = str_split (req[1], " ", 0)) == NULL)
2285 return GPG_ERR_SYNTAX;
2288 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 0);
2289 if (!n || rc)
2290 goto fail;
2292 if (path[1])
2294 n = find_elements (client, client->doc, n->children, path + 1, &rc,
2295 NULL, NULL, NULL, 0, 0, NULL, 0);
2296 if (!n || rc)
2297 goto fail;
2300 strv_free (path);
2302 if ((a = xmlGetProp (n, (xmlChar *) req[0])) == NULL)
2303 return GPG_ERR_NOT_FOUND;
2305 pthread_cleanup_push (xmlFree, a);
2307 if (*a)
2308 rc = xfer_data (ctx, (char *) a, xmlStrlen (a));
2309 else
2310 rc = GPG_ERR_NO_DATA;
2312 pthread_cleanup_pop (1);
2313 return rc;
2315 fail:
2316 strv_free (path);
2317 return rc;
2321 * req[0] - attribute
2322 * req[1] - element path
2323 * req[2] - value
2325 static gpg_error_t
2326 attribute_set (struct client_s *client, char **req)
2328 char **path = NULL;
2329 gpg_error_t rc;
2330 xmlNodePtr n;
2332 if (!req || !req[0] || !req[1])
2333 return GPG_ERR_SYNTAX;
2336 * Reserved attribute names.
2338 if (!strcmp (req[0], "_name"))
2339 return GPG_ERR_INV_ATTR;
2340 else if (!strcmp (req[0], "target"))
2341 return target_attribute (client, req + 1);
2342 else if (!valid_xml_attribute (req[0]))
2343 return GPG_ERR_INV_VALUE;
2345 if ((path = str_split (req[1], "\t", 0)) == NULL)
2348 * The first argument may be only a root element.
2350 if ((path = str_split (req[1], " ", 0)) == NULL)
2351 return GPG_ERR_SYNTAX;
2354 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 0);
2355 if (!n || rc)
2356 goto fail;
2358 if (path[1])
2360 n = find_elements (client, client->doc, n->children, path + 1, &rc,
2361 NULL, NULL, NULL, 0, 0, NULL, 0);
2362 if (!n || rc)
2363 goto fail;
2366 if (!strcmp (req[0], (char *) "_acl"))
2368 rc = is_element_owner (client, n);
2369 if (rc)
2370 goto fail;
2373 rc = add_attribute (client, n, req[0], req[2]);
2375 fail:
2376 strv_free (path);
2377 return rc;
2381 * req[0] - command
2382 * req[1] - attribute name or element path if command is LIST
2383 * req[2] - element path
2384 * req[2] - element path or value
2387 static gpg_error_t
2388 do_attr (assuan_context_t ctx, char *line)
2390 struct client_s *client = assuan_get_pointer (ctx);
2391 gpg_error_t rc = 0;
2392 char **req;
2394 req = str_split (line, " ", 4);
2395 if (!req || !req[0] || !req[1])
2397 strv_free (req);
2398 return GPG_ERR_SYNTAX;
2401 pthread_cleanup_push (req_cleanup, req);
2403 if (strcasecmp (req[0], "SET") == 0)
2404 rc = attribute_set (client, req + 1);
2405 else if (strcasecmp (req[0], "GET") == 0)
2406 rc = attribute_get (ctx, req + 1);
2407 else if (strcasecmp (req[0], "DELETE") == 0)
2408 rc = attribute_delete (client, req + 1);
2409 else if (strcasecmp (req[0], "LIST") == 0)
2410 rc = attribute_list (ctx, req + 1);
2411 else
2412 rc = GPG_ERR_SYNTAX;
2414 client->flags &= ~(FLAG_ACL_IGNORE|FLAG_ACL_ERROR);
2415 pthread_cleanup_pop (1);
2416 return rc;
2419 static gpg_error_t
2420 attr_command (assuan_context_t ctx, char *line)
2422 struct client_s *client = assuan_get_pointer (ctx);
2423 gpg_error_t rc;
2424 struct argv_s *args[] = {
2425 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2426 NULL
2429 rc = parse_options (&line, args, client, 1);
2430 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2431 rc = GPG_ERR_SYNTAX;
2432 if (rc)
2433 return send_error (ctx, rc);
2435 if (client->opts & OPT_INQUIRE)
2437 unsigned char *result;
2438 size_t len;
2440 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2441 if (rc)
2442 return send_error (ctx, rc);
2444 pthread_cleanup_push (xfree, result);
2445 rc = do_attr (ctx, (char *)result);
2446 pthread_cleanup_pop (1);
2448 else
2449 rc = do_attr (ctx, line);
2451 return send_error (ctx, rc);
2454 static gpg_error_t
2455 parse_iscached_opt_lock (void *data, void *value)
2457 struct client_s *client = data;
2459 (void) value;
2460 client->opts |= OPT_LOCK;
2461 return 0;
2464 static gpg_error_t
2465 iscached_command (assuan_context_t ctx, char *line)
2467 struct client_s *client = assuan_get_pointer (ctx);
2468 gpg_error_t rc;
2469 struct argv_s *args[] = {
2470 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_iscached_opt_lock},
2471 NULL
2474 if (!line || !*line)
2475 return send_error (ctx, GPG_ERR_SYNTAX);
2477 rc = parse_options (&line, args, client, 1);
2478 if (rc)
2479 return send_error (ctx, rc);
2480 else if (!valid_filename (line))
2481 return send_error (ctx, GPG_ERR_INV_VALUE);
2483 rc = cache_iscached (line, NULL);
2484 if (client->opts & OPT_LOCK
2485 && (!rc || gpg_err_code (rc) == GPG_ERR_NO_DATA))
2487 unsigned char md5file[16];
2488 gpg_error_t trc = rc;
2490 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2491 if (memcmp (md5file, client->md5file, 16))
2492 cleanup_client (client);
2494 memcpy (client->md5file, md5file, 16);
2495 rc = do_lock (client, 1);
2496 if (!rc)
2497 rc = trc;
2500 return send_error (ctx, rc);
2503 static gpg_error_t
2504 clearcache_command (assuan_context_t ctx, char *line)
2506 gpg_error_t rc = 0, all_rc = 0;
2507 unsigned char md5file[16];
2508 int i;
2509 int t;
2510 int all = 0;
2511 struct client_thread_s *once = NULL;
2513 cache_lock ();
2514 MUTEX_LOCK (&cn_mutex);
2515 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
2517 if (!line || !*line)
2518 all = 1;
2520 t = slist_length (cn_thread_list);
2522 for (i = 0; i < t; i++)
2524 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2525 assuan_peercred_t peer;
2527 if (!thd->cl)
2528 continue;
2530 /* Lock each connected clients' file mutex to prevent any other client
2531 * from accessing the cache entry (the file mutex is locked upon
2532 * command startup). The cache for the entry is not cleared if the
2533 * file mutex is locked by another client to prevent this function
2534 * from blocking.
2536 if (all)
2538 if (thd->cl->filename)
2540 rc = do_validate_peer (ctx, thd->cl->filename, &peer);
2541 all_rc = !all_rc ? rc : all_rc;
2542 if (rc)
2544 rc = 0;
2545 continue;
2549 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0, -1);
2550 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2552 if (pthread_equal (pthread_self (), thd->tid))
2553 rc = 0;
2554 else
2556 if (!thd->cl->filename ||
2557 cache_iscached (thd->cl->filename,
2558 NULL) == GPG_ERR_NO_DATA)
2560 rc = 0;
2561 continue;
2564 cache_defer_clear (thd->cl->md5file);
2567 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
2569 rc = 0;
2570 continue;
2573 if (!rc)
2575 rc = cache_clear (thd->cl->md5file);
2576 cache_unlock_mutex (thd->cl->md5file, 0);
2579 if (rc)
2580 all_rc = rc;
2582 rc = 0;
2584 /* A single data filename was specified. Lock only this data file
2585 * mutex and free the cache entry. */
2586 else
2588 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2589 rc = do_validate_peer (ctx, line, &peer);
2591 if (!rc && !memcmp (thd->cl->md5file, md5file, sizeof (md5file)))
2593 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0,
2594 -1);
2595 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2597 if (pthread_equal (pthread_self (), thd->tid))
2598 rc = 0;
2601 if (!rc)
2603 once = thd;
2604 rc = cache_clear (thd->cl->md5file);
2605 cache_unlock_mutex (thd->cl->md5file, 0);
2607 else
2609 cache_defer_clear (thd->cl->md5file);
2612 break;
2617 /* Only connected clients' cache entries have been cleared. Now clear any
2618 * remaining cache entries without clients but only if there wasn't an
2619 * error from above since this would defeat the locking check of the
2620 * remaining entries. */
2621 if (!all_rc && all)
2623 cache_clear (NULL);
2626 /* No clients are using the specified file. */
2627 else if (!all_rc && !rc && !once)
2629 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2630 rc = cache_clear (md5file);
2633 /* Release the connection mutex. */
2634 pthread_cleanup_pop (1);
2635 cache_unlock ();
2637 if (!rc)
2638 send_status_all (STATUS_CACHE, NULL);
2640 /* One or more files were locked while clearing all cache entries. */
2641 if (all_rc)
2642 rc = all_rc;
2644 return send_error (ctx, rc);
2647 static gpg_error_t
2648 cachetimeout_command (assuan_context_t ctx, char *line)
2650 int timeout;
2651 char **req = str_split (line, " ", 0);
2652 char *p;
2653 gpg_error_t rc = 0;
2654 assuan_peercred_t peer;
2656 if (!req || !*req || !req[1])
2658 strv_free (req);
2659 return send_error (ctx, GPG_ERR_SYNTAX);
2662 errno = 0;
2663 timeout = (int) strtol (req[1], &p, 10);
2664 if (errno != 0 || *p || timeout < -1)
2666 strv_free (req);
2667 return send_error (ctx, GPG_ERR_SYNTAX);
2670 rc = do_validate_peer (ctx, req[0], &peer);
2671 if (!rc)
2673 unsigned char md5file[16];
2675 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, req[0], strlen (req[0]));
2676 rc = cache_set_timeout (md5file, timeout);
2677 if (!rc || gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
2679 rc = 0;
2680 MUTEX_LOCK (&rcfile_mutex);
2681 config_set_int_param (&global_config, req[0], "cache_timeout",
2682 req[1]);
2683 MUTEX_UNLOCK (&rcfile_mutex);
2687 strv_free (req);
2688 return send_error (ctx, rc);
2691 static gpg_error_t
2692 dump_command (assuan_context_t ctx, char *line)
2694 xmlChar *xml;
2695 int len;
2696 struct client_s *client = assuan_get_pointer (ctx);
2697 gpg_error_t rc;
2699 if (disable_list_and_dump == 1)
2700 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2702 if (line && *line)
2703 return send_error (ctx, GPG_ERR_SYNTAX);
2705 rc = peer_is_invoker(client);
2706 if (rc)
2707 return send_error (ctx, rc);
2709 xmlDocDumpFormatMemory (client->doc, &xml, &len, 1);
2711 if (!xml)
2713 log_write ("%s(%i): %s", __FILE__, __LINE__,
2714 pwmd_strerror (GPG_ERR_ENOMEM));
2715 return send_error (ctx, GPG_ERR_ENOMEM);
2718 pthread_cleanup_push (xmlFree, xml);
2719 rc = xfer_data (ctx, (char *) xml, len);
2720 pthread_cleanup_pop (1);
2721 return send_error (ctx, rc);
2724 static gpg_error_t
2725 getconfig_command (assuan_context_t ctx, char *line)
2727 struct client_s *client = assuan_get_pointer (ctx);
2728 gpg_error_t rc = 0;
2729 char filename[255] = { 0 }, param[747] = { 0 };
2730 char *p, *tmp = NULL, *fp = client->filename, *paramp = line;
2732 if (!line || !*line)
2733 return send_error (ctx, GPG_ERR_SYNTAX);
2735 if (strchr (line, ' '))
2737 sscanf (line, " %254[^ ] %746c", filename, param);
2738 paramp = param;
2739 fp = filename;
2742 if (fp && !valid_filename (fp))
2743 return send_error (ctx, GPG_ERR_INV_VALUE);
2745 paramp = str_down (paramp);
2746 if (!strcmp (paramp, "cipher") && fp)
2748 struct crypto_s *crypto = NULL;
2750 rc = init_client_crypto (&crypto);
2751 if (!rc)
2753 rc = read_data_header (fp, &crypto->hdr, NULL, NULL);
2754 if (!rc)
2756 const char *t =
2757 gcry_cipher_algo_name (cipher_to_gcrypt (crypto->hdr.flags));
2758 if (t)
2760 tmp = str_dup (t);
2761 if (tmp)
2762 str_down (tmp);
2767 UPDATE_AGENT_CTX (client, crypto);
2768 cleanup_crypto (&crypto);
2769 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
2770 return send_error (ctx, rc);
2772 if (!rc && tmp)
2773 goto done;
2775 else if (!strcmp (paramp, "cipher_iterations") && fp)
2777 struct crypto_s *crypto = NULL;
2779 rc = init_client_crypto (&crypto);
2780 if (!rc)
2782 rc = read_data_header (fp, &crypto->hdr, NULL, NULL);
2783 if (!rc)
2785 tmp = str_asprintf ("%llu",
2786 (unsigned long long) crypto->hdr.s2k_count);
2787 if (!tmp)
2788 rc = GPG_ERR_ENOMEM;
2792 UPDATE_AGENT_CTX (client, crypto);
2793 cleanup_crypto (&crypto);
2794 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
2795 return send_error (ctx, rc);
2797 if (!rc && tmp)
2798 goto done;
2800 else if (!strcmp (paramp, "passphrase"))
2801 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2803 p = config_get_value (fp ? fp : "global", paramp);
2804 if (!p)
2805 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2807 tmp = expand_homedir (p);
2808 xfree (p);
2809 if (!tmp)
2811 log_write ("%s(%i): %s", __FILE__, __LINE__,
2812 pwmd_strerror (GPG_ERR_ENOMEM));
2813 return send_error (ctx, GPG_ERR_ENOMEM);
2816 done:
2817 p = tmp;
2818 pthread_cleanup_push (xfree, p);
2819 rc = xfer_data (ctx, p, strlen (p));
2820 pthread_cleanup_pop (1);
2821 return send_error (ctx, rc);
2824 struct xpath_s
2826 xmlXPathContextPtr xp;
2827 xmlXPathObjectPtr result;
2828 xmlBufferPtr buf;
2829 char **req;
2832 static void
2833 xpath_command_cleanup (void *arg)
2835 struct xpath_s *xpath = arg;
2837 if (!xpath)
2838 return;
2840 req_cleanup (xpath->req);
2842 if (xpath->buf)
2843 xmlBufferFree (xpath->buf);
2845 if (xpath->result)
2846 xmlXPathFreeObject (xpath->result);
2848 if (xpath->xp)
2849 xmlXPathFreeContext (xpath->xp);
2852 static gpg_error_t
2853 do_xpath (assuan_context_t ctx, char *line)
2855 gpg_error_t rc;
2856 struct client_s *client = assuan_get_pointer (ctx);
2857 struct xpath_s _x = { 0 };
2858 struct xpath_s *xpath = &_x;
2860 if (!line || !*line)
2861 return GPG_ERR_SYNTAX;
2863 if ((xpath->req = str_split (line, "\t", 2)) == NULL)
2865 if (strv_printf (&xpath->req, "%s", line) == 0)
2866 return GPG_ERR_ENOMEM;
2869 xpath->xp = xmlXPathNewContext (client->doc);
2870 if (!xpath->xp)
2872 rc = GPG_ERR_BAD_DATA;
2873 goto fail;
2876 xpath->result =
2877 xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2878 if (!xpath->result)
2880 rc = GPG_ERR_BAD_DATA;
2881 goto fail;
2884 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2886 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2887 goto fail;
2890 rc = recurse_xpath_nodeset (client, client->doc, xpath->result->nodesetval,
2891 (xmlChar *) xpath->req[1], &xpath->buf, 0,
2892 NULL);
2893 if (rc)
2894 goto fail;
2895 else if (!xpath->req[1] && !xmlBufferLength (xpath->buf))
2897 rc = GPG_ERR_NO_DATA;
2898 goto fail;
2900 else if (xpath->req[1])
2902 rc = 0;
2903 goto fail;
2906 pthread_cleanup_push (xpath_command_cleanup, &xpath);
2907 rc = xfer_data (ctx, (char *) xmlBufferContent (xpath->buf),
2908 xmlBufferLength (xpath->buf));
2909 pthread_cleanup_pop (0);
2910 fail:
2911 xpath_command_cleanup (xpath);
2912 return rc;
2915 static gpg_error_t
2916 xpath_command (assuan_context_t ctx, char *line)
2918 struct client_s *client = assuan_get_pointer (ctx);
2919 gpg_error_t rc;
2920 struct argv_s *args[] = {
2921 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2922 NULL
2925 if (disable_list_and_dump == 1)
2926 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2928 rc = peer_is_invoker(client);
2929 if (rc)
2930 return send_error (ctx, rc);
2932 rc = parse_options (&line, args, client, 1);
2933 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2934 rc = GPG_ERR_SYNTAX;
2935 if (rc)
2936 return send_error (ctx, rc);
2938 if (client->opts & OPT_INQUIRE)
2940 unsigned char *result;
2941 size_t len;
2943 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2944 if (rc)
2945 return send_error (ctx, rc);
2947 pthread_cleanup_push (xfree, result);
2948 rc = do_xpath (ctx, (char *)result);
2949 pthread_cleanup_pop (1);
2951 else
2952 rc = do_xpath (ctx, line);
2954 return send_error (ctx, rc);
2957 static gpg_error_t
2958 do_xpathattr (assuan_context_t ctx, char *line)
2960 struct client_s *client = assuan_get_pointer (ctx);
2961 gpg_error_t rc;
2962 char **req = NULL;
2963 int cmd = 0; //SET
2964 struct xpath_s _x = { 0 };
2965 struct xpath_s *xpath = &_x;
2967 if (!line || !*line)
2968 return GPG_ERR_SYNTAX;
2970 if ((req = str_split (line, " ", 3)) == NULL)
2971 return GPG_ERR_ENOMEM;
2973 if (!req[0])
2975 rc = GPG_ERR_SYNTAX;
2976 goto fail;
2979 if (!strcasecmp (req[0], "SET"))
2980 cmd = 0;
2981 else if (!strcasecmp (req[0], "DELETE"))
2982 cmd = 1;
2983 else
2985 rc = GPG_ERR_SYNTAX;
2986 goto fail;
2989 if (!req[1] || !req[2])
2991 rc = GPG_ERR_SYNTAX;
2992 goto fail;
2995 if ((xpath->req = str_split (req[2], "\t", 3)) == NULL)
2997 rc = GPG_ERR_ENOMEM;
2998 goto fail;
3001 if (!xpath->req[0] || (!xpath->req[1] && !cmd) || (xpath->req[1] && cmd))
3003 rc = GPG_ERR_SYNTAX;
3004 goto fail;
3007 xpath->xp = xmlXPathNewContext (client->doc);
3008 if (!xpath->xp)
3010 rc = GPG_ERR_BAD_DATA;
3011 goto fail;
3014 xpath->result = xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
3015 if (!xpath->result)
3017 rc = GPG_ERR_BAD_DATA;
3018 goto fail;
3021 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
3023 rc = GPG_ERR_ELEMENT_NOT_FOUND;
3024 goto fail;
3027 rc = recurse_xpath_nodeset (client, client->doc, xpath->result->nodesetval,
3028 (xmlChar *) xpath->req[1], &xpath->buf, cmd,
3029 (xmlChar *) req[1]);
3031 fail:
3032 xpath_command_cleanup (xpath);
3033 strv_free (req);
3034 return rc;
3037 /* XPATHATTR SET|DELETE <name> <expression>[<TAB>[value]] */
3038 static gpg_error_t
3039 xpathattr_command (assuan_context_t ctx, char *line)
3041 struct client_s *client = assuan_get_pointer (ctx);
3042 gpg_error_t rc;
3043 struct argv_s *args[] = {
3044 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3045 NULL
3048 if (disable_list_and_dump == 1)
3049 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
3051 rc = peer_is_invoker(client);
3052 if (rc)
3053 return send_error (ctx, rc);
3055 rc = parse_options (&line, args, client, 1);
3056 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3057 rc = GPG_ERR_SYNTAX;
3058 if (rc)
3059 return send_error (ctx, rc);
3061 if (client->opts & OPT_INQUIRE)
3063 unsigned char *result;
3064 size_t len;
3066 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3067 if (rc)
3068 return send_error (ctx, rc);
3070 pthread_cleanup_push (xfree, result);
3071 rc = do_xpathattr (ctx, (char *)result);
3072 pthread_cleanup_pop (1);
3074 else
3075 rc = do_xpathattr (ctx, line);
3077 return send_error (ctx, rc);
3080 static gpg_error_t
3081 do_import (struct client_s *client, const char *root_element,
3082 unsigned char *content)
3084 char **dst_path = NULL;
3085 xmlDocPtr doc = NULL;
3086 xmlNodePtr n, root, copy;
3087 gpg_error_t rc;
3089 if (!content || !*content)
3091 xfree (content);
3092 return GPG_ERR_SYNTAX;
3095 if (root_element)
3096 dst_path = str_split (root_element, "\t", 0);
3098 if (dst_path && !valid_element_path (dst_path, 0))
3100 if (dst_path)
3101 strv_free (dst_path);
3103 return GPG_ERR_INV_VALUE;
3106 struct string_s *str = string_new_content ((char *)content);
3107 str = string_prepend (str, "<pwmd>");
3108 str = string_append (str, "</pwmd>");
3109 doc = xmlReadDoc ((xmlChar *) str->str, NULL, "UTF-8", XML_PARSE_NOBLANKS);
3110 string_free (str, 1);
3111 if (!doc)
3113 rc = GPG_ERR_BAD_DATA;
3114 goto fail;
3117 root = xmlDocGetRootElement (doc);
3118 xmlNodePtr root_orig = root->children;
3119 root = root->children;
3120 rc = validate_import (client, root);
3121 if (rc)
3122 goto fail;
3126 again:
3127 if (dst_path)
3129 char **path = strv_dup (dst_path);
3130 if (!path)
3132 log_write ("%s(%i): %s", __FILE__, __LINE__,
3133 pwmd_strerror (GPG_ERR_ENOMEM));
3134 rc = GPG_ERR_ENOMEM;
3135 goto fail;
3138 xmlChar *a = xmlGetProp (root, (xmlChar *) "_name");
3139 if (!a)
3141 strv_free (path);
3142 rc = GPG_ERR_INV_VALUE;
3143 goto fail;
3146 if (strv_printf (&path, "%s", (char *) a) == 0)
3148 xmlFree (a);
3149 rc = GPG_ERR_ENOMEM;
3150 goto fail;
3153 xmlFree (a);
3154 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 0);
3155 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3157 strv_free (path);
3158 goto fail;
3161 if (!rc)
3163 n = find_elements (client, client->doc, n->children, path + 1, &rc,
3164 NULL, NULL, NULL, 0, 0, NULL, 1);
3165 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3167 strv_free (path);
3168 goto fail;
3170 else if (!rc)
3172 xmlUnlinkNode (n);
3173 xmlFreeNode (n);
3174 strv_free (path);
3175 path = NULL;
3176 goto again;
3180 if (rc == GPG_ERR_ELEMENT_NOT_FOUND)
3182 n = create_element_path (client, &path, &rc, NULL);
3183 if (rc)
3184 goto fail;
3187 if (root->children)
3189 copy = xmlCopyNodeList (root->children);
3190 n = xmlAddChildList (n, copy);
3191 if (!n)
3192 rc = GPG_ERR_ENOMEM;
3195 strv_free (path);
3197 else
3199 char **path = NULL;
3201 /* Check if the content root element can create a DTD root element. */
3202 if (!xmlStrEqual ((xmlChar *) "element", root->name))
3204 rc = GPG_ERR_SYNTAX;
3205 goto fail;
3208 xmlChar *a;
3210 if ((a = xmlGetProp (root, (xmlChar *) "_name")) == NULL)
3212 rc = GPG_ERR_SYNTAX;
3213 goto fail;
3216 char *tmp = str_dup ((char *) a);
3217 xmlFree (a);
3218 int literal = is_literal_element (&tmp);
3220 if (!valid_xml_element ((xmlChar *) tmp) || literal)
3222 xfree (tmp);
3223 rc = GPG_ERR_INV_VALUE;
3224 goto fail;
3227 if (strv_printf (&path, "%s", tmp) == 0)
3229 xfree (tmp);
3230 rc = GPG_ERR_ENOMEM;
3231 goto fail;
3234 xfree (tmp);
3235 n = find_root_element (client, client->doc, &path, &rc, NULL, 0, 1);
3236 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3238 rc = GPG_ERR_BAD_DATA;
3239 goto fail;
3242 /* Overwriting the existing tree. */
3243 if (!rc)
3245 xmlUnlinkNode (n);
3246 xmlFreeNodeList (n);
3249 rc = 0;
3250 xmlSetProp (root, (xmlChar *) "_name", (xmlChar *) path[0]);
3251 n = xmlCopyNode (root, 1);
3252 n = xmlAddChildList (xmlDocGetRootElement (client->doc), n);
3253 strv_free (path);
3256 if (n && !rc)
3257 rc = update_element_mtime (client, n->parent);
3259 for (root = root_orig->next; root; root = root->next)
3261 if (root->type == XML_ELEMENT_NODE)
3262 break;
3265 root_orig = root;
3267 while (root);
3269 fail:
3270 if (doc)
3271 xmlFreeDoc (doc);
3273 if (dst_path)
3274 strv_free (dst_path);
3276 return rc;
3279 static gpg_error_t
3280 parse_import_opt_root (void *data, void *value)
3282 struct client_s *client = data;
3284 client->import_root = str_dup (value);
3285 return client->import_root ? 0 : GPG_ERR_ENOMEM;
3288 static gpg_error_t
3289 import_command (assuan_context_t ctx, char *line)
3291 gpg_error_t rc;
3292 struct client_s *client = assuan_get_pointer (ctx);
3293 unsigned char *result;
3294 size_t len;
3295 struct argv_s *args[] = {
3296 &(struct argv_s) {"root", OPTION_TYPE_ARG, parse_import_opt_root},
3297 NULL
3300 xfree (client->import_root);
3301 client->import_root = NULL;
3302 rc = parse_options (&line, args, client, 0);
3303 if (rc)
3304 return send_error (ctx, rc);
3306 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3307 if (rc)
3309 xfree (client->import_root);
3310 client->import_root = NULL;
3311 return send_error (ctx, rc);
3314 rc = do_import (client, client->import_root, result);
3315 xfree (client->import_root);
3316 client->import_root = NULL;
3317 return send_error (ctx, rc);
3320 static gpg_error_t
3321 do_lock (struct client_s *client, int add)
3323 gpg_error_t rc = lock_file_mutex (client, add);
3325 if (!rc)
3326 client->flags |= FLAG_LOCK_CMD;
3328 return rc;
3331 static gpg_error_t
3332 lock_command (assuan_context_t ctx, char *line)
3334 struct client_s *client = assuan_get_pointer (ctx);
3335 gpg_error_t rc;
3337 if (line && *line)
3338 return send_error (ctx, GPG_ERR_SYNTAX);
3340 rc = do_lock (client, 0);
3341 return send_error (ctx, rc);
3344 static gpg_error_t
3345 unlock_command (assuan_context_t ctx, char *line)
3347 struct client_s *client = assuan_get_pointer (ctx);
3348 gpg_error_t rc;
3350 if (line && *line)
3351 return send_error (ctx, GPG_ERR_SYNTAX);
3353 rc = unlock_file_mutex (client, 0);
3354 return send_error (ctx, rc);
3357 static gpg_error_t
3358 option_command (assuan_context_t ctx, char *line)
3360 struct client_s *client = assuan_get_pointer (ctx);
3361 gpg_error_t rc = 0;
3362 struct pinentry_option_s *pin_opts = &client->pinentry_opts;
3363 #ifdef WITH_AGENT
3364 struct agent_s *agent = client->crypto->agent;
3365 #endif
3366 char namebuf[255] = { 0 };
3367 char *name = namebuf;
3368 char *value = NULL, *p, *tmp = NULL;
3370 p = strchr (line, '=');
3371 if (!p)
3373 strncpy (namebuf, line, sizeof(namebuf));
3374 namebuf[sizeof(namebuf)-1] = 0;
3376 else
3378 strncpy (namebuf, line, strlen (line)-strlen (p));
3379 namebuf[sizeof(namebuf)-1] = 0;
3380 value = p+1;
3383 log_write1 ("OPTION name='%s' value='%s'", name, value);
3385 if (strcasecmp (name, (char *) "lock-timeout") == 0)
3387 long n = 0;
3389 if (value)
3391 n = strtol (value, &tmp, 10);
3392 if (tmp && *tmp)
3393 return send_error (ctx, GPG_ERR_INV_VALUE);
3396 client->lock_timeout = n;
3397 goto done;
3399 else if (strcasecmp (name, (char *) "NAME") == 0)
3401 if (value && strchr (value, ' '))
3402 rc = GPG_ERR_INV_VALUE;
3403 else
3405 tmp = pthread_getspecific (thread_name_key);
3406 xfree (tmp);
3407 MUTEX_LOCK (&cn_mutex);
3408 xfree (client->thd->name);
3409 client->thd->name = NULL;
3411 if (!value || !*value)
3412 pthread_setspecific (thread_name_key, str_dup (""));
3413 else
3415 client->thd->name = str_dup (value);
3416 pthread_setspecific (thread_name_key, str_dup (value));
3419 MUTEX_UNLOCK (&cn_mutex);
3421 goto done;
3423 else if (strcasecmp (name, (char *) "lc-messages") == 0)
3425 xfree (pin_opts->lc_messages);
3426 pin_opts->lc_messages = NULL;
3427 if (value && *value)
3428 pin_opts->lc_messages = str_dup (value);
3429 #ifdef WITH_AGENT
3430 if (use_agent)
3431 rc = set_agent_option (client->crypto->agent, "lc-messages", value);
3432 #endif
3434 else if (strcasecmp (name, (char *) "lc-ctype") == 0)
3436 xfree (pin_opts->lc_ctype);
3437 pin_opts->lc_ctype = NULL;
3438 if (value && *value)
3439 pin_opts->lc_ctype = str_dup (value);
3440 #ifdef WITH_AGENT
3441 if (use_agent)
3442 rc = set_agent_option (client->crypto->agent, "lc-ctype", value);
3443 #endif
3445 else if (strcasecmp (name, (char *) "ttyname") == 0)
3447 xfree (pin_opts->ttyname);
3448 pin_opts->ttyname = NULL;
3449 if (value && *value)
3450 pin_opts->ttyname = str_dup (value);
3451 #ifdef WITH_AGENT
3452 if (use_agent)
3453 rc = set_agent_option (client->crypto->agent, "ttyname", value);
3454 #endif
3456 else if (strcasecmp (name, (char *) "ttytype") == 0)
3458 xfree (pin_opts->ttytype);
3459 pin_opts->ttytype = NULL;
3460 if (value && *value)
3461 pin_opts->ttytype = str_dup (value);
3462 #ifdef WITH_AGENT
3463 if (use_agent)
3464 rc = set_agent_option (client->crypto->agent, "ttytype", value);
3465 #endif
3467 else if (strcasecmp (name, (char *) "display") == 0)
3469 xfree (pin_opts->display);
3470 pin_opts->display = NULL;
3471 if (value && *value)
3472 pin_opts->display = str_dup (value);
3473 #ifdef WITH_AGENT
3474 if (use_agent)
3475 rc = set_agent_option (client->crypto->agent, "display", value);
3476 #endif
3478 else if (strcasecmp (name, (char *) "pinentry-desc") == 0)
3480 xfree (pin_opts->desc);
3481 pin_opts->desc = NULL;
3482 if (value && *value)
3483 pin_opts->desc = str_dup (value);
3485 else if (strcasecmp (name, (char *) "pinentry-title") == 0)
3487 xfree (pin_opts->title);
3488 pin_opts->title = NULL;
3489 if (value && *value)
3490 pin_opts->title = str_dup (value);
3492 else if (strcasecmp (name, (char *) "pinentry-prompt") == 0)
3494 xfree (pin_opts->prompt);
3495 pin_opts->prompt = NULL;
3496 if (value && *value)
3497 pin_opts->prompt = str_dup (value);
3500 else if (strcasecmp (name, "pinentry-timeout") == 0)
3502 char *p = NULL;
3503 int n;
3505 if (!value)
3506 goto done;
3508 n = (int) strtol (value, &p, 10);
3510 if (*p || n < 0)
3511 return send_error (ctx, GPG_ERR_INV_VALUE);
3513 pin_opts->timeout = n;
3514 MUTEX_LOCK (&rcfile_mutex);
3515 config_set_int_param (&global_config,
3516 client->filename ? client->filename : "global",
3517 "pinentry_timeout", value);
3518 MUTEX_UNLOCK (&rcfile_mutex);
3519 goto done;
3521 else if (strcasecmp (name, "disable-pinentry") == 0)
3523 int n = 1;
3525 if (value && *value)
3527 n = (int) strtol (value, &tmp, 10);
3528 if (*tmp || n < 0 || n > 1)
3529 return send_error (ctx, GPG_ERR_INV_VALUE);
3532 if (n)
3533 client->flags |= FLAG_NO_PINENTRY;
3534 else
3535 client->flags &= ~FLAG_NO_PINENTRY;
3537 #ifdef WITH_AGENT
3538 if (use_agent)
3540 if (client->flags & FLAG_NO_PINENTRY)
3541 rc = set_agent_option (client->crypto->agent, "pinentry-mode",
3542 "loopback");
3543 else
3544 rc = set_agent_option (client->crypto->agent, "pinentry-mode",
3545 "ask");
3547 if (rc)
3548 return send_error (ctx, rc);
3550 #endif
3552 else
3553 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
3555 done:
3556 #ifdef WITH_AGENT
3557 if (!rc && use_agent && agent)
3559 rc = pinentry_merge_options (&client->crypto->agent->pinentry_opts,
3560 pin_opts);
3562 #endif
3564 return send_error (ctx, rc);
3567 static gpg_error_t
3568 do_rename (assuan_context_t ctx, char *line)
3570 struct client_s *client = assuan_get_pointer (ctx);
3571 gpg_error_t rc;
3572 char **req, **src, *dst;
3573 xmlNodePtr n, ndst;
3575 req = str_split (line, " ", 0);
3577 if (!req || !req[0] || !req[1])
3579 strv_free (req);
3580 return GPG_ERR_SYNTAX;
3583 dst = req[1];
3584 is_literal_element (&dst);
3586 if (!valid_xml_element ((xmlChar *) dst))
3588 strv_free (req);
3589 return GPG_ERR_INV_VALUE;
3592 if (strchr (req[0], '\t'))
3593 src = str_split (req[0], "\t", 0);
3594 else
3595 src = str_split (req[0], " ", 0);
3597 if (!src || !*src)
3599 rc = GPG_ERR_SYNTAX;
3600 goto fail;
3603 n = find_root_element (client, client->doc, &src, &rc, NULL, 0, 0);
3604 if (rc)
3605 goto fail;
3607 if (src[1] && n)
3608 n = find_elements (client, client->doc, n->children, src + 1, &rc, NULL, NULL,
3609 NULL, 0, 0, NULL, 0);
3611 if (!n || rc)
3612 goto fail;
3614 rc = is_element_owner (client, n);
3615 if (rc)
3616 goto fail;
3618 xmlChar *a = xmlGetProp (n, (xmlChar *) "_name");
3619 if (!a)
3621 rc = GPG_ERR_ENOMEM;
3622 goto fail;
3625 /* To prevent unwanted effects:
3627 * <root name="a"><b/></root>
3629 * RENAME a<TAB>b b
3631 if (xmlStrEqual (a, (xmlChar *) dst))
3633 xmlFree (a);
3634 rc = GPG_ERR_AMBIGUOUS_NAME;
3635 goto fail;
3638 xmlFree (a);
3639 char **tmp = NULL;
3640 if (src[1])
3642 char **p;
3644 for (p = src; *p; p++)
3646 if (!*(p + 1))
3647 break;
3648 strv_printf (&tmp, "%s", *p);
3652 strv_printf (&tmp, "!%s", dst);
3653 ndst = find_root_element (client, client->doc, &tmp, &rc, NULL, 0, 0);
3654 if (!ndst && rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3656 strv_free (tmp);
3657 goto fail;
3660 if (tmp[1] && ndst)
3661 ndst = find_elements (client, client->doc, ndst->children, tmp + 1, &rc, NULL,
3662 NULL, NULL, 0, 0, NULL, 0);
3664 strv_free (tmp);
3665 if (!ndst && rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3666 goto fail;
3668 rc = 0;
3670 /* Target may exist:
3672 * <root name="a"/>
3673 * <root name="b" target="a"/>
3675 * RENAME b a
3677 * Would need to do:
3678 * RENAME !b a
3680 if (ndst == n)
3682 rc = GPG_ERR_AMBIGUOUS_NAME;
3683 goto fail;
3686 if (ndst)
3688 rc = is_element_owner (client, ndst);
3689 if (rc)
3690 goto fail;
3692 unlink_node (client, ndst);
3693 xmlFreeNodeList (ndst);
3696 rc = add_attribute (client, n, "_name", dst);
3698 fail:
3699 strv_free (req);
3700 strv_free (src);
3701 return rc;
3704 static gpg_error_t
3705 rename_command (assuan_context_t ctx, char *line)
3707 struct client_s *client = assuan_get_pointer (ctx);
3708 gpg_error_t rc;
3709 struct argv_s *args[] = {
3710 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3711 NULL
3714 rc = parse_options (&line, args, client, 1);
3715 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3716 rc = GPG_ERR_SYNTAX;
3717 if (rc)
3718 return send_error (ctx, rc);
3720 if (client->opts & OPT_INQUIRE)
3722 unsigned char *result;
3723 size_t len;
3725 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3726 if (rc)
3727 return send_error (ctx, rc);
3729 pthread_cleanup_push (xfree, result);
3730 rc = do_rename (ctx, (char *)result);
3731 pthread_cleanup_pop (1);
3733 else
3734 rc = do_rename (ctx, line);
3736 return send_error (ctx, rc);
3739 static gpg_error_t
3740 do_copy (assuan_context_t ctx, char *line)
3742 struct client_s *client = assuan_get_pointer (ctx);
3743 gpg_error_t rc;
3744 char **req, **src = NULL, **dst = NULL;
3745 xmlNodePtr nsrc, ndst, new = NULL;
3747 req = str_split (line, " ", 0);
3748 if (!req || !req[0] || !req[1])
3750 strv_free (req);
3751 return GPG_ERR_SYNTAX;
3754 if (strchr (req[0], '\t'))
3755 src = str_split (req[0], "\t", 0);
3756 else
3757 src = str_split (req[0], " ", 0);
3759 if (!src || !*src)
3761 rc = GPG_ERR_SYNTAX;
3762 goto fail;
3765 if (strchr (req[1], '\t'))
3766 dst = str_split (req[1], "\t", 0);
3767 else
3768 dst = str_split (req[1], " ", 0);
3770 if (!dst || !*dst)
3772 rc = GPG_ERR_SYNTAX;
3773 goto fail;
3776 if (!valid_element_path (dst, 0))
3778 rc = GPG_ERR_INV_VALUE;
3779 goto fail;
3782 nsrc = find_root_element (client, client->doc, &src, &rc, NULL, 0, 0);
3783 if (rc)
3784 goto fail;
3786 if (nsrc && src[1])
3787 nsrc = find_elements (client, client->doc, nsrc->children, src + 1, &rc, NULL,
3788 NULL, NULL, 0, 0, NULL, 0);
3790 if (!nsrc || rc)
3791 goto fail;
3793 new = xmlCopyNodeList (nsrc);
3794 if (!new)
3796 rc = GPG_ERR_ENOMEM;
3797 goto fail;
3800 int create = 0;
3801 ndst = find_root_element (client, client->doc, &dst, &rc, NULL, 0, 0);
3802 if (rc == GPG_ERR_EACCES)
3803 goto fail;
3805 if (ndst && dst[1])
3807 if (ndst->children)
3808 ndst = find_elements (client, client->doc, ndst->children, dst + 1, &rc, NULL,
3809 NULL, create_target_elements_cb, 0, 0, NULL, 0);
3810 else
3811 create = 1;
3813 else
3814 create = 1;
3816 if (!ndst && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3817 goto fail;
3818 else if (!ndst || create)
3820 ndst = create_element_path (client, &dst, &rc, NULL);
3821 if (!ndst || rc)
3822 goto fail;
3825 rc = is_element_owner (client, ndst);
3826 if (rc)
3827 goto fail;
3829 /* Merge any attributes from the src node to the initial dst node. */
3830 for (xmlAttrPtr attr = new->properties; attr; attr = attr->next)
3832 if (xmlStrEqual (attr->name, (xmlChar *) "_name"))
3833 continue;
3835 xmlAttrPtr a = xmlHasProp (ndst, attr->name);
3836 if (a)
3837 xmlRemoveProp (a);
3839 xmlChar *tmp = xmlNodeGetContent (attr->children);
3840 xmlNewProp (ndst, attr->name, tmp);
3841 xmlFree (tmp);
3842 rc = add_attribute (client, ndst, NULL, NULL);
3845 xmlNodePtr n = ndst->children;
3846 xmlUnlinkNode (n);
3847 xmlFreeNodeList (n);
3848 ndst->children = NULL;
3850 if (new->children)
3852 n = xmlCopyNodeList (new->children);
3853 if (!n)
3855 rc = GPG_ERR_ENOMEM;
3856 goto fail;
3859 n = xmlAddChildList (ndst, n);
3860 if (!n)
3862 rc = GPG_ERR_ENOMEM;
3863 goto fail;
3866 rc = update_element_mtime (client, xmlDocGetRootElement (client->doc) ==
3867 ndst->parent ? ndst : ndst->parent);
3870 fail:
3871 if (new)
3873 xmlUnlinkNode (new);
3874 xmlFreeNodeList (new);
3877 if (req)
3878 strv_free (req);
3880 if (src)
3881 strv_free (src);
3883 if (dst)
3884 strv_free (dst);
3886 return rc;
3889 static gpg_error_t
3890 copy_command (assuan_context_t ctx, char *line)
3892 struct client_s *client = assuan_get_pointer (ctx);
3893 gpg_error_t rc;
3894 struct argv_s *args[] = {
3895 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3896 NULL
3899 rc = parse_options (&line, args, client, 1);
3900 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3901 rc = GPG_ERR_SYNTAX;
3902 if (rc)
3903 return send_error (ctx, rc);
3905 if (client->opts & OPT_INQUIRE)
3907 unsigned char *result;
3908 size_t len;
3910 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3911 if (rc)
3912 return send_error (ctx, rc);
3914 pthread_cleanup_push (xfree, result);
3915 rc = do_copy (ctx, (char *)result);
3916 pthread_cleanup_pop (1);
3918 else
3919 rc = do_copy (ctx, line);
3921 return send_error (ctx, rc);
3924 static gpg_error_t
3925 do_move (assuan_context_t ctx, char *line)
3927 struct client_s *client = assuan_get_pointer (ctx);
3928 gpg_error_t rc;
3929 char **req, **src = NULL, **dst = NULL;
3930 xmlNodePtr nsrc, ndst = NULL;
3932 req = str_split (line, " ", 0);
3934 if (!req || !req[0] || !req[1])
3936 strv_free (req);
3937 return GPG_ERR_SYNTAX;
3940 if (strchr (req[0], '\t'))
3941 src = str_split (req[0], "\t", 0);
3942 else
3943 src = str_split (req[0], " ", 0);
3945 if (!src || !*src)
3947 rc = GPG_ERR_SYNTAX;
3948 goto fail;
3951 if (strchr (req[1], '\t'))
3952 dst = str_split (req[1], "\t", 0);
3953 else
3954 dst = str_split (req[1], " ", 0);
3956 nsrc = find_root_element (client, client->doc, &src, &rc, NULL, 0, 0);
3957 if (rc)
3958 goto fail;
3960 if (nsrc && src[1])
3961 nsrc = find_elements (client, client->doc, nsrc->children, src + 1, &rc,
3962 NULL, NULL, NULL, 0, 0, NULL, 0);
3964 if (!nsrc)
3965 goto fail;
3967 rc = is_element_owner (client, nsrc);
3968 if (rc)
3969 goto fail;
3971 if (dst)
3973 if (!valid_element_path (dst, 0))
3975 rc = GPG_ERR_INV_VALUE;
3976 goto fail;
3979 ndst = find_root_element (client, client->doc, &dst, &rc, NULL, 0, 0);
3980 if (rc)
3981 goto fail;
3983 if (ndst && dst[1])
3984 ndst = find_elements (client, client->doc, ndst->children, dst + 1,
3985 &rc, NULL, NULL, NULL, 0, 0, NULL, 0);
3987 else
3988 ndst = xmlDocGetRootElement (client->doc);
3990 for (xmlNodePtr n = ndst; n; n = n->parent)
3992 if (n == nsrc)
3994 rc = GPG_ERR_CONFLICT;
3995 goto fail;
3999 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
4000 goto fail;
4002 rc = 0;
4004 if (ndst)
4006 xmlChar *a = node_has_attribute (nsrc, (xmlChar *) "_name");
4008 xmlNodePtr dup = find_element (client, ndst->children, (char *) a,
4009 NULL, &rc);
4010 xmlFree (a);
4012 if (rc)
4013 goto fail;
4015 if (dup)
4017 if (dup == nsrc)
4018 goto fail;
4020 if (ndst == xmlDocGetRootElement (client->doc))
4022 xmlNodePtr n = nsrc;
4023 int match = 0;
4025 while (n->parent && n->parent != ndst)
4026 n = n->parent;
4028 xmlChar *a = node_has_attribute (n, (xmlChar *) "_name");
4029 xmlChar *b = node_has_attribute (nsrc, (xmlChar *) "_name");
4031 if (xmlStrEqual (a, b))
4033 match = 1;
4034 xmlUnlinkNode (nsrc);
4035 xmlUnlinkNode (n);
4036 xmlFreeNodeList (n);
4039 xmlFree (a);
4040 xmlFree (b);
4042 if (!match)
4044 xmlUnlinkNode (dup);
4045 xmlFreeNodeList (dup);
4048 else
4049 xmlUnlinkNode (dup);
4053 if (!ndst && dst)
4055 xmlChar *name = node_has_attribute (nsrc, (xmlChar *) "_name");
4057 if (nsrc->parent == xmlDocGetRootElement (client->doc)
4058 && !strcmp ((char *) name, *dst))
4060 xmlFree (name);
4061 rc = GPG_ERR_CONFLICT;
4062 goto fail;
4065 xmlFree (name);
4066 ndst = create_element_path (client, &dst, &rc, nsrc);
4067 if (rc)
4068 goto fail;
4071 if (!ndst)
4072 goto fail;
4074 update_element_mtime (client, nsrc->parent);
4075 xmlUnlinkNode (nsrc);
4076 ndst = xmlAddChildList (ndst, nsrc);
4078 if (!ndst)
4079 rc = GPG_ERR_ENOMEM;
4080 else
4081 update_element_mtime (client, ndst->parent);
4083 fail:
4084 if (req)
4085 strv_free (req);
4087 if (src)
4088 strv_free (src);
4090 if (dst)
4091 strv_free (dst);
4093 return rc;
4096 static gpg_error_t
4097 move_command (assuan_context_t ctx, char *line)
4099 struct client_s *client = assuan_get_pointer (ctx);
4100 gpg_error_t rc;
4101 struct argv_s *args[] = {
4102 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
4103 NULL
4106 rc = parse_options (&line, args, client, 1);
4107 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
4108 rc = GPG_ERR_SYNTAX;
4109 if (rc)
4110 return send_error (ctx, rc);
4112 if (client->opts & OPT_INQUIRE)
4114 unsigned char *result;
4115 size_t len;
4117 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
4118 if (rc)
4119 return send_error (ctx, rc);
4121 pthread_cleanup_push (xfree, result);
4122 rc = do_move (ctx, (char *)result);
4123 pthread_cleanup_pop (1);
4125 else
4126 rc = do_move (ctx, line);
4128 return send_error (ctx, rc);
4131 static gpg_error_t
4132 ls_command (assuan_context_t ctx, char *line)
4134 gpg_error_t rc;
4135 char *tmp;
4136 char *dir;
4137 DIR *d;
4139 if (line && *line)
4140 return send_error (ctx, GPG_ERR_SYNTAX);
4142 tmp = str_asprintf ("%s/data", homedir);
4143 dir = expand_homedir (tmp);
4144 xfree (tmp);
4145 d = opendir (dir);
4146 rc = gpg_error_from_errno (errno);
4148 if (!d)
4150 xfree (dir);
4151 return send_error (ctx, rc);
4154 size_t len =
4155 offsetof (struct dirent, d_name) +pathconf (dir, _PC_NAME_MAX) + 1;
4156 struct dirent *p = xmalloc (len), *cur = NULL;
4157 char *list = NULL;
4159 xfree (dir);
4160 pthread_cleanup_push (xfree, p);
4161 pthread_cleanup_push ((void *)(void *)closedir, d);
4162 rc = 0;
4164 while (!readdir_r (d, p, &cur) && cur)
4166 if (cur->d_name[0] == '.' && cur->d_name[1] == '\0')
4167 continue;
4168 else if (cur->d_name[0] == '.' && cur->d_name[1] == '.'
4169 && cur->d_name[2] == '\0')
4170 continue;
4172 tmp = str_asprintf ("%s%s\n", list ? list : "", cur->d_name);
4174 if (!tmp)
4176 if (list)
4177 xfree (list);
4179 rc = GPG_ERR_ENOMEM;
4180 break;
4183 xfree (list);
4184 list = tmp;
4187 pthread_cleanup_pop (1); // closedir (d)
4188 pthread_cleanup_pop (1); // xfree (p)
4190 if (rc)
4191 return send_error (ctx, rc);
4193 if (!list)
4194 return send_error (ctx, GPG_ERR_NO_DATA);
4196 list[strlen (list) - 1] = 0;
4197 pthread_cleanup_push (xfree, list);
4198 rc = xfer_data (ctx, list, strlen (list));
4199 pthread_cleanup_pop (1);
4200 return send_error (ctx, rc);
4203 static gpg_error_t
4204 bye_notify (assuan_context_t ctx, char *line)
4206 struct client_s *cl = assuan_get_pointer (ctx);
4208 cl->thd->state = CLIENT_STATE_DISCON;
4210 #ifdef WITH_GNUTLS
4211 if (cl->thd->remote)
4213 int rc;
4217 struct timeval tv = { 0, 50000 };
4219 rc = gnutls_bye (cl->thd->tls->ses, GNUTLS_SHUT_RDWR);
4220 if (rc == GNUTLS_E_AGAIN)
4221 select (0, NULL, NULL, NULL, &tv);
4223 while (rc == GNUTLS_E_AGAIN);
4225 #endif
4227 /* This will let assuan_process_next() return. */
4228 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
4230 cl->last_rc = gpg_error_from_errno (errno);
4231 return cl->last_rc;
4234 cl->last_rc = 0; // BYE command result
4235 return 0;
4238 static gpg_error_t
4239 reset_notify (assuan_context_t ctx, char *line)
4241 struct client_s *client = assuan_get_pointer (ctx);
4243 if (client)
4244 cleanup_client (client);
4246 return 0;
4250 * This is called before every Assuan command.
4252 static gpg_error_t
4253 command_startup (assuan_context_t ctx, const char *name)
4255 struct client_s *client = assuan_get_pointer (ctx);
4256 gpg_error_t rc;
4257 struct command_table_s *cmd = NULL;
4259 log_write1 ("command='%s'", name);
4260 client->last_rc = client->opts = 0;
4262 for (int i = 0; command_table[i]; i++)
4264 if (!strcasecmp (name, command_table[i]->name))
4266 if (command_table[i]->ignore_startup)
4267 return 0;
4268 cmd = command_table[i];
4269 break;
4273 if (!cmd)
4274 return GPG_ERR_UNKNOWN_COMMAND;
4276 client->last_rc = rc = gpg_error (file_modified (client, cmd));
4277 if (!rc)
4278 update_client_state (client, CLIENT_STATE_COMMAND);
4280 return rc;
4284 * This is called after every Assuan command.
4286 static void
4287 command_finalize (assuan_context_t ctx, gpg_error_t rc)
4289 struct client_s *client = assuan_get_pointer (ctx);
4291 if (!(client->flags & FLAG_LOCK_CMD))
4292 unlock_file_mutex (client, 0);
4294 unlock_flock (&client->flock_fd);
4295 log_write1 (_("command completed: rc=%u"), rc ? rc : client->last_rc);
4296 client->last_rc = gpg_error (GPG_ERR_UNKNOWN_COMMAND);
4297 #ifdef WITH_GNUTLS
4298 client->thd->buffer_timeout = client->thd->last_buffer_size = 0;
4299 #endif
4300 update_client_state (client, CLIENT_STATE_IDLE);
4303 static gpg_error_t
4304 help_command (assuan_context_t ctx, char *line)
4306 gpg_error_t rc;
4307 int i;
4309 if (!line || !*line)
4311 char *tmp;
4312 char *help = str_dup (_("Usage: HELP [<COMMAND>]\n"
4313 "For commands that take an element path as an argument, each element is "
4314 "separated with an ASCII @key{TAB} character (ASCII 0x09)."
4315 "\n" "COMMANDS:"));
4317 for (i = 0; command_table[i]; i++)
4319 if (!command_table[i]->help)
4320 continue;
4322 tmp = str_asprintf ("%s %s", help, command_table[i]->name);
4323 xfree (help);
4324 help = tmp;
4327 tmp = strip_texi_and_wrap (help);
4328 xfree (help);
4329 pthread_cleanup_push (xfree, tmp);
4330 rc = xfer_data (ctx, tmp, strlen (tmp));
4331 pthread_cleanup_pop (1);
4332 return send_error (ctx, rc);
4335 for (i = 0; command_table[i]; i++)
4337 if (!strcasecmp (line, command_table[i]->name))
4339 char *help, *tmp;
4341 if (!command_table[i]->help)
4342 break;
4344 help = strip_texi_and_wrap (command_table[i]->help);
4345 tmp = str_asprintf (_("Usage: %s"), help);
4346 xfree (help);
4347 pthread_cleanup_push (xfree, tmp);
4348 rc = xfer_data (ctx, tmp, strlen (tmp));
4349 pthread_cleanup_pop (1);
4350 return send_error (ctx, rc);
4354 return send_error (ctx, GPG_ERR_INV_NAME);
4357 static void
4358 new_command (const char *name, int ignore, int unlock, int flock_type,
4359 gpg_error_t (*handler) (assuan_context_t, char *),
4360 const char *help)
4362 int i = 0;
4364 if (command_table)
4365 for (i = 0; command_table[i]; i++);
4367 command_table =
4368 xrealloc (command_table, (i + 2) * sizeof (struct command_table_s *));
4369 command_table[i] = xcalloc (1, sizeof (struct command_table_s));
4370 command_table[i]->name = name;
4371 command_table[i]->handler = handler;
4372 command_table[i]->ignore_startup = ignore;
4373 command_table[i]->unlock = unlock;
4374 command_table[i]->flock_type = flock_type;
4375 command_table[i++]->help = help;
4376 command_table[i] = NULL;
4379 void
4380 deinit_commands ()
4382 int i;
4384 for (i = 0; command_table[i]; i++)
4385 xfree (command_table[i]);
4387 xfree (command_table);
4390 static int
4391 sort_commands (const void *arg1, const void *arg2)
4393 struct command_table_s *const *a = arg1;
4394 struct command_table_s *const *b = arg2;
4396 if (!*a || !*b)
4397 return 0;
4398 else if (*a && !*b)
4399 return 1;
4400 else if (!*a && *b)
4401 return -1;
4403 return strcmp ((*a)->name, (*b)->name);
4406 static gpg_error_t
4407 passwd_command (assuan_context_t ctx, char *line)
4409 struct client_s *client = assuan_get_pointer (ctx);
4410 gpg_error_t rc;
4411 struct argv_s *args[] = {
4412 &(struct argv_s) {"reset", OPTION_TYPE_NOARG, parse_opt_reset},
4413 &(struct argv_s) {"s2k-count", OPTION_TYPE_ARG, parse_opt_s2k_count},
4414 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG, parse_opt_no_passphrase},
4415 NULL
4418 rc = peer_is_invoker (client);
4419 if (rc == GPG_ERR_EACCES)
4420 return send_error (ctx, rc);
4422 if (client->flags & FLAG_NEW)
4423 return send_error (ctx, GPG_ERR_INV_STATE);
4425 client->crypto->save.hdr.s2k_count =
4426 config_get_ulonglong (client->filename, "s2k_count");
4427 rc = parse_options (&line, args, client, 0);
4428 if (rc)
4429 return send_error (ctx, rc);
4431 if (!rc && client->opts & OPT_RESET)
4433 rc = cache_clear (client->md5file);
4434 if (!rc)
4435 send_status_all (STATUS_CACHE, NULL);
4438 if (!rc)
4440 if (!IS_PKI (client->crypto))
4442 struct crypto_s *crypto;
4444 xfree (client->crypto->filename);
4445 client->crypto->filename = str_dup (client->filename);
4446 rc = change_passwd (ctx, client->filename,
4447 client->flags & FLAG_NO_PINENTRY, &crypto,
4448 (client->opts & OPT_NO_PASSPHRASE));
4449 if (!rc)
4451 cleanup_crypto (&client->crypto);
4452 client->crypto = crypto;
4453 update_checksum (client);
4454 cleanup_crypto_stage1 (client->crypto);
4457 #ifdef WITH_AGENT
4458 else
4460 if (client->crypto->save.hdr.s2k_count)
4461 rc = send_to_agent (client->crypto->agent, NULL, NULL,
4462 "OPTION s2k-count=%lu",
4463 client->crypto->save.hdr.s2k_count);
4465 if (!rc)
4466 rc = agent_passwd (client->crypto);
4468 (void) kill_scd (client->crypto->agent);
4470 #endif
4473 return send_error (ctx, rc);
4476 static gpg_error_t
4477 parse_keygrip_opt_sign (void *data, void *value)
4479 struct client_s *client = data;
4481 (void) value;
4482 client->opts |= OPT_SIGN;
4483 return 0;
4486 static gpg_error_t
4487 keygrip_command (assuan_context_t ctx, char *line)
4489 struct client_s *client = assuan_get_pointer (ctx);
4490 gpg_error_t rc;
4491 struct crypto_s *crypto = NULL;
4492 struct argv_s *args[] = {
4493 &(struct argv_s) {"sign", OPTION_TYPE_NOARG, parse_keygrip_opt_sign},
4494 NULL
4497 if (!line || !*line)
4498 return send_error (ctx, GPG_ERR_SYNTAX);
4500 rc = parse_options (&line, args, client, 1);
4501 if (rc)
4502 return send_error (ctx, rc);
4504 if (!valid_filename (line))
4505 return send_error (ctx, GPG_ERR_INV_VALUE);
4507 rc = init_client_crypto (&crypto);
4508 if (rc)
4509 return send_error (ctx, rc);
4511 rc = read_data_file (line, crypto);
4512 if (!rc)
4514 char *hexgrip = NULL;
4516 if (!IS_PKI (crypto))
4518 cleanup_crypto (&crypto);
4519 return send_error (ctx, GPG_ERR_NOT_SUPPORTED);
4522 if (client->opts & OPT_SIGN)
4524 if (valid_keygrip (crypto->sign_grip, sizeof (crypto->sign_grip)))
4525 hexgrip = bin2hex (crypto->sign_grip, sizeof (crypto->sign_grip));
4528 if (!hexgrip)
4529 hexgrip = bin2hex (crypto->grip, sizeof (crypto->grip));
4531 if (!hexgrip)
4532 rc = GPG_ERR_ENOMEM;
4533 else
4534 rc = xfer_data (ctx, hexgrip, strlen (hexgrip));
4536 xfree (hexgrip);
4539 UPDATE_AGENT_CTX (client, crypto);
4540 cleanup_crypto (&crypto);
4541 return send_error (ctx, rc);
4544 static gpg_error_t
4545 parse_opt_data (void *data, void *value)
4547 struct client_s *client = data;
4549 (void) value;
4550 client->opts |= OPT_DATA;
4551 return 0;
4554 static gpg_error_t
4555 send_client_list (assuan_context_t ctx)
4557 struct client_s *client = assuan_get_pointer (ctx);
4558 gpg_error_t rc = 0;
4559 char buf[ASSUAN_LINELENGTH];
4561 if (client->opts & OPT_VERBOSE)
4563 unsigned i, t;
4564 char **list = NULL;
4565 char *line;
4567 MUTEX_LOCK (&cn_mutex);
4568 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
4569 t = slist_length (cn_thread_list);
4571 for (i = 0; i < t; i++)
4573 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
4574 char *tmp;
4576 if (thd->state == CLIENT_STATE_UNKNOWN)
4577 continue;
4579 tmp = build_client_info_line (thd, 0);
4580 if (tmp)
4582 char **l = strv_cat (list, tmp);
4583 if (!l)
4584 rc = GPG_ERR_ENOMEM;
4585 else
4586 list = l;
4588 else
4589 rc = GPG_ERR_ENOMEM;
4591 if (rc)
4593 strv_free (list);
4594 break;
4598 pthread_cleanup_pop (1);
4599 if (rc)
4600 return rc;
4602 line = strv_join ("\n", list);
4603 strv_free (list);
4604 pthread_cleanup_push (xfree, line);
4605 rc = xfer_data (ctx, line, strlen (line));
4606 pthread_cleanup_pop (1);
4607 return rc;
4610 if (client->opts & OPT_DATA)
4612 MUTEX_LOCK (&cn_mutex);
4613 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
4614 snprintf (buf, sizeof (buf), "%i", slist_length (cn_thread_list));
4615 pthread_cleanup_pop (1);
4616 rc = xfer_data (ctx, buf, strlen (buf));
4618 else
4619 rc = send_status (ctx, STATUS_CLIENTS, NULL);
4621 return rc;
4624 static gpg_error_t
4625 getinfo_command (assuan_context_t ctx, char *line)
4627 struct client_s *client = assuan_get_pointer (ctx);
4628 gpg_error_t rc;
4629 char buf[ASSUAN_LINELENGTH];
4630 struct argv_s *args[] = {
4631 &(struct argv_s) {"data", OPTION_TYPE_NOARG, parse_opt_data},
4632 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_opt_verbose},
4633 NULL
4636 rc = parse_options (&line, args, client, 1);
4637 if (rc)
4638 return send_error (ctx, rc);
4640 if (!strcasecmp (line, "clients"))
4642 rc = send_client_list (ctx);
4644 else if (!strcasecmp (line, "cache"))
4646 if (client->opts & OPT_DATA)
4648 snprintf (buf, sizeof (buf), "%u", cache_file_count ());
4649 rc = xfer_data (ctx, buf, strlen (buf));
4651 else
4652 rc = send_status (ctx, STATUS_CACHE, NULL);
4654 else if (!strcasecmp (line, "pid"))
4656 char buf[32];
4657 pid_t pid = getpid ();
4659 snprintf (buf, sizeof (buf), "%i", pid);
4660 rc = xfer_data (ctx, buf, strlen (buf));
4662 else if (!strcasecmp (line, "version"))
4664 char *buf = str_asprintf ("0x%06x %s%s", VERSION_HEX,
4665 #ifdef WITH_GNUTLS
4666 "GNUTLS "
4667 #endif
4668 #ifdef WITH_QUALITY
4669 "QUALITY "
4670 #endif
4671 "", use_agent ? "AGENT" : "");
4672 rc = xfer_data (ctx, buf, strlen (buf));
4673 xfree (buf);
4675 else if (!strcasecmp (line, "last_error"))
4677 if (client->last_error)
4678 rc = xfer_data (ctx, client->last_error, strlen (client->last_error));
4679 else
4680 rc = GPG_ERR_NO_DATA;
4682 else if (!strcasecmp (line, "user"))
4684 char *user = NULL;
4686 #ifdef WITH_GNUTLS
4687 if (client->thd->remote)
4688 user = str_asprintf ("#%s", client->thd->tls->fp);
4689 else
4690 user = get_username (client->thd->peer->uid);
4691 #else
4692 user = get_username (client->thd->peer->uid);
4693 #endif
4694 if (user)
4696 pthread_cleanup_push (xfree, user);
4697 rc = xfer_data (ctx, user, strlen (user));
4698 pthread_cleanup_pop (1);
4700 else
4701 rc = GPG_ERR_NO_DATA;
4703 else
4704 rc = gpg_error (GPG_ERR_SYNTAX);
4706 return send_error (ctx, rc);
4709 #ifdef WITH_AGENT
4710 static gpg_error_t
4711 send_data_cb (void *user, const void *buf, size_t len)
4713 assuan_context_t ctx = user;
4715 return assuan_send_data (ctx, buf, len);
4718 static gpg_error_t
4719 send_status_cb (void *user, const char *line)
4721 assuan_context_t ctx = user;
4722 char keyword[200], *k;
4723 const char *p;
4725 for (p = line, k = keyword; *p; p++)
4727 if (isspace (*p))
4728 break;
4730 *k++ = *p;
4733 *k = 0;
4734 if (*p == '#')
4735 p++;
4737 while (isspace (*p))
4738 p++;
4740 return assuan_write_status (ctx, keyword, *p ? p : NULL);
4742 #endif
4744 static gpg_error_t
4745 kill_command (assuan_context_t ctx, char *line)
4747 struct client_s *client = assuan_get_pointer (ctx);
4748 gpg_error_t rc;
4749 unsigned i, t;
4751 if (!line || !*line)
4752 return send_error (ctx, GPG_ERR_SYNTAX);
4754 MUTEX_LOCK (&cn_mutex);
4755 pthread_cleanup_push (cleanup_mutex_cb, &cn_mutex);
4756 t = slist_length (cn_thread_list);
4757 rc = GPG_ERR_ESRCH;
4759 for (i = 0; i < t; i++)
4761 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
4762 char *tmp = str_asprintf ("%p", thd->tid);
4764 if (strcmp (line, tmp))
4766 xfree (tmp);
4767 continue;
4770 xfree (tmp);
4771 rc = peer_is_invoker (client);
4772 if (!rc)
4774 #ifdef HAVE_PTHREAD_CANCEL
4775 rc = pthread_cancel (thd->tid);
4776 #else
4777 close (thd->fd);
4778 thd->fd = -1;
4779 #endif
4780 break;
4783 rc = GPG_ERR_EACCES;
4784 if (config_get_boolean ("global", "strict_kill"))
4785 break;
4787 #ifdef WITH_GNUTLS
4788 if (client->thd->remote && thd->remote)
4790 if (!strcmp (client->thd->tls->fp, thd->tls->fp))
4792 #ifdef HAVE_PTHREAD_CANCEL
4793 rc = pthread_cancel (thd->tid);
4794 #else
4795 close (thd->fd);
4796 thd->fd = -1;
4797 #endif
4798 break;
4801 else if (!client->thd->remote && !thd->remote)
4802 #endif
4804 if (client->thd->peer->uid == thd->peer->uid)
4806 #ifdef HAVE_PTHREAD_CANCEL
4807 rc = pthread_cancel (thd->tid);
4808 #else
4809 close (thd->fd);
4810 thd->fd = -1;
4811 #endif
4814 break;
4817 pthread_cleanup_pop (1);
4818 return send_error (ctx, rc);
4821 static gpg_error_t
4822 agent_command (assuan_context_t ctx, char *line)
4824 gpg_error_t rc = 0;
4826 if (!use_agent)
4827 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
4829 #ifdef WITH_AGENT
4830 struct client_s *client = assuan_get_pointer (ctx);
4832 if (!line || !*line)
4833 return send_error (ctx, GPG_ERR_SYNTAX);
4835 assuan_set_flag (client->crypto->agent->ctx, ASSUAN_CONVEY_COMMENTS, 1);
4836 rc = assuan_transact (client->crypto->agent->ctx, line, send_data_cb,
4837 client->ctx, agent_loopback_cb, client->crypto,
4838 send_status_cb, client->ctx);
4839 if (gpg_err_code (rc) == GPG_ERR_ASS_CANCELED)
4841 char *line;
4842 size_t len;
4844 rc = assuan_write_line (client->crypto->agent->ctx, "CAN");
4845 if (!rc)
4847 rc = assuan_read_line (client->crypto->agent->ctx, &line, &len);
4848 if (!rc)
4849 rc = gpg_error (GPG_ERR_ASS_CANCELED);
4853 assuan_set_flag (client->crypto->agent->ctx, ASSUAN_CONVEY_COMMENTS, 0);
4854 #endif
4855 return send_error (ctx, rc);
4858 void
4859 init_commands ()
4861 /* !BEGIN-HELP-TEXT!
4863 * This comment is used as a marker to generate the offline documentation
4864 * found in doc/pwmd.info. The indentation needs to be kept for the awk
4865 * script to determine where commands begin and end.
4867 new_command("HELP", 1, 1, 0, help_command, _(
4868 "HELP [<COMMAND>]\n"
4869 "Show available commands or command specific help text."
4872 new_command("AGENT", 1, 1, 0, agent_command, _(
4873 "AGENT <command>\n"
4874 "Send a @command{gpg-agent} protocol @var{command} directly to the "
4875 "@command{gpg-agent}."
4878 new_command("KILL", 1, 0, 0, kill_command, _(
4879 "KILL <thread_id>\n"
4880 "Terminates the client identified by @var{thread_id} and releases any file "
4881 "lock or other resources it has held. See @code{GETINFO} (@pxref{GETINFO}) "
4882 "for details about listing connected clients. The @code{invoking_user} "
4883 "(@pxref{Configuration}) may kill any client while others may only kill "
4884 "clients of the same @code{UID} or @abbr{TLS} fingerprint.\n"
4887 new_command("GETINFO", 1, 1, 0, getinfo_command, _(
4888 "GETINFO [--data] [--verbose] CACHE | CLIENTS | PID | USER | LAST_ERROR | VERSION\n"
4889 "Get server and other information: @var{CACHE} returns the number of cached "
4890 "documents via a status message. @var{CLIENTS} returns the number of "
4891 "connected clients via a status message or a list of connected clients when "
4892 "the @option{--verbose} parameter is used. The list contains space delimited "
4893 "fields: the thread ID, client name, opened file (@code{/} if none opened), "
4894 "file lock status, whether the current client is self, client state, "
4895 "user ID or TLS fingerprint of the connected client and username if the "
4896 "client is a local one. "
4897 "Client state @code{0} is an unknown client state, @code{1} indicates the "
4898 "client has connected but hasn't completed initializing, @code{2} indicates "
4899 "that the client is idle, @code{3} means the "
4900 "client is in a command and @code{4} means the client is disconnecting. This "
4901 "line is always returned with a data response. @var{PID} returns the process "
4902 "ID number of the server via a data response. @var{VERSION} returns the server "
4903 "version number and compile-time features with a data response with each "
4904 "being space delimited. @var{LAST_ERROR} returns a detailed description of "
4905 "the last failed command when available. @var{USER} returns the username or "
4906 "@abbr{TLS} hash of the connected client. @xref{Status Messages}. "
4907 "\n"
4908 "When the @option{--data} option is specified then the result will be sent "
4909 "via a data response rather than a status message."
4912 new_command("PASSWD", 0, 0, FLOCK_TYPE_EX|FLOCK_TYPE_KEEP, passwd_command, _(
4913 "PASSWD [--reset] [--s2k-count=N] [--no-passphrase]\n"
4914 "Changes the passphrase of the secret key required to open the current "
4915 "file or the passphrase of a symmetrically encrypted data file. When the "
4916 "@option{--reset} option is passed then the cache entry for the current "
4917 "file will be reset and the passphrase, if any, will be required during the "
4918 "next @code{OPEN} (@pxref{OPEN})."
4919 "\n"
4920 "The @option{--s2k-count} option sets or changes (@pxref{SAVE}) the number "
4921 "of hash iterations for a passphrase and must be either @code{0} to use "
4922 "the calibrated count of the machine (the default), or a value greater than "
4923 "or equal to @code{65536}. This option has no effect for symmetrically "
4924 "encrypted data files."
4925 "\n"
4926 "The @option{--no-passphrase} option will prevent requiring a passphrase for "
4927 "the data file, although a passphrase may be required when changing it."
4928 "\n"
4929 "This command is not available for non-invoking clients "
4930 "(@pxref{Access Control})."
4933 new_command("KEYGRIP", 1, 1, FLOCK_TYPE_SH|FLOCK_TYPE_KEEP, keygrip_command, _(
4934 "KEYGRIP [--sign] <filename>\n"
4935 "Returns the hex encoded keygrip of the specified @var{filename} with a "
4936 "data response."
4937 "\n"
4938 "When the @option{--sign} option is specified then the key used for signing "
4939 "of the specified @var{filename} will be returned."
4940 "\n"
4941 "For symmetrically encrypted data files this command returns the error "
4942 "GPG_ERR_NOT_SUPPORTED."
4945 new_command("OPEN", 1, 1, FLOCK_TYPE_SH|FLOCK_TYPE_KEEP, open_command, _(
4946 "OPEN [--lock] <filename> [<passphrase>]\n"
4947 "Opens @var{filename} using @var{passphrase}. When the filename is not "
4948 "found on the file-system then a new document will be created. If the file "
4949 "is found, it is looked for in the file cache. If cached and no "
4950 "@var{passphrase} was specified then the cached document is opened. When not "
4951 "cached, @cite{pinentry(1)} will be used to retrieve the passphrase to use "
4952 "for decryption unless @option{disable-pinentry} (@pxref{OPTION}) was "
4953 "specified."
4954 "\n"
4955 "When the @option{--lock} option is passed then the file mutex will be "
4956 "locked as if the @code{LOCK} command (@pxref{LOCK}) had been sent after the "
4957 "file has been opened."
4960 new_command("SAVE", 0, 0, FLOCK_TYPE_EX|FLOCK_TYPE_KEEP, save_command, _(
4961 "SAVE [--no-passphrase] [--reset] [--ask] [--no-agent] [--s2k-count=N] [--cipher=<algo>] [--cipher-iterations=N] [--inquire-keyparam] [--keygrip=hexstring] [--sign-keygrip=hexstring]\n"
4962 "Writes the @abbr{XML} document to disk. The file written to is the file that "
4963 "was opened using the @code{OPEN} command (@pxref{OPEN}). If the file is a "
4964 "new one or the option @option{--inquire-keyparam} was passed, then a new "
4965 "keypair will be generated and a pinentry will be used to prompt for the "
4966 "passphrase to encrypt with unless the @option{--no-passphrase} option was "
4967 "passed in which case the data file will not be passphrase protected. "
4968 "\n"
4969 "The @option{--no-agent} option disables use of @command{gpg-agent} for "
4970 "passphrase retrieval and caching of new files when @command{gpg-agent} "
4971 "use is enabled. The datafile will be symmetrically encrypted and will not "
4972 "use or generate any keypair."
4973 "\n"
4974 "The @option{--reset} option will clear the cache entry for the current file "
4975 "and require a passphrase, if needed, before saving."
4976 "\n"
4977 "The @option{--ask} option will prompt for the passphrase of the current file, "
4978 "if needed, before saving. This differs from the @option{--reset} option by "
4979 "keeping the cache entry in case of an invalid passphrase or some other failure "
4980 "which may otherwise cause a denial of service for other clients."
4981 "\n"
4982 "The @option{--cipher} option can be used to encrypt the @abbr{XML} data to "
4983 "an alternate cipher. The default is @code{aes256}. See the Configuration "
4984 "(@pxref{Configuration}) for available ciphers."
4985 "\n"
4986 "The @option{--cipher-iterations} option specifies the number of times to "
4987 "hash the passphrase before encrypting the XML data. The default is "
4988 "@code{5000000}. This option is an alias for @option{--s2k-count} since "
4989 "version @var{3.0.15} of @command{pwmd}."
4990 "\n"
4991 "The @option{--inquire-keyparam} option will send a server @emph{INQUIRE} to "
4992 "the client to obtain the key paramaters to use when generating a new "
4993 "keypair. The inquired data is expected to be an S-expression. If not "
4994 "specified then an @samp{RSA} key of @samp{2048} bits will be generated "
4995 "unless otherwise set in the configuration file (@pxref{Configuration}). Note "
4996 "that when this option is specified a new keypair will be generated "
4997 "reguardless if the file is a new one and that if the data file is protected "
4998 "the passphrase to open it will be required before generating the new "
4999 "keypair. This option is not available for non-invoking clients "
5000 "(@pxref{Access Control})."
5001 "\n"
5002 "You can encrypt the data file to a public key other than the one that it "
5003 "was originally encrypted with by passing the @option{--keygrip} option with "
5004 "the hex encoded keygrip of the public key as its argument. The keygrip may "
5005 "be of any key that @command{gpg-agent} knows about. The "
5006 "@option{--sign-keygrip} option may also be used to sign with an alternate "
5007 "secret key. Use the @code{KEYGRIP} (@pxref{KEYGRIP}) command to obtain the "
5008 "keygrip of an existing data file. This option may be needed when using a "
5009 "smartcard. This option has no effect with symmetrically encrypted data "
5010 "files. These options are not available for non-invoking clients "
5011 "(@pxref{Access Control})."
5012 "\n"
5013 "The @option{--s2k-count} option sets number of hash iterations for a "
5014 "passphrase. A value less-than @code{65536} will use the machine calibrated "
5015 "value and is the default when using @command{gpg-agent}. This setting only "
5016 "affects new files when using @command{gpg-agent}. To change the setting use "
5017 "the @code{PASSWD} command (@pxref{PASSWD}). This option is an alias for "
5018 "option @option{--cipher-iterations} when not using @command{gpg-agent}."
5021 new_command("ISCACHED", 1, 0, 0, iscached_command, _(
5022 "ISCACHED [--lock] <filename>\n"
5023 "An @emph{OK} response is returned if the specified @var{filename} is found "
5024 "in the file cache. If not found in the cache but exists on the filesystem "
5025 "then @var{GPG_ERR_NO_DATA} is returned. Otherwise a filesystem error is "
5026 "returned."
5027 "\n"
5028 "The @option{lock} option will lock the file mutex of @var{filename} when the "
5029 "file exists; it does not need to be opened nor cached. The lock will be "
5030 "released when the client exits or sends the @code{UNLOCK} (@pxref{UNLOCK}) "
5031 "command."
5034 new_command("CLEARCACHE", 1, 1, 0, clearcache_command, _(
5035 "CLEARCACHE [<filename>]\n"
5036 "Clears a file cache entry for all or the specified @var{filename}."
5039 new_command("CACHETIMEOUT", 1, 1, 0, cachetimeout_command, _(
5040 "CACHETIMEOUT <filename> <seconds>\n"
5041 "The time in @var{seconds} until @var{filename} will be removed from the "
5042 "cache. @code{-1} will keep the cache entry forever, @code{0} will require "
5043 "the passphrase for each @code{OPEN} or @code{SAVE} command (@pxref{OPEN}, "
5044 "@pxref{SAVE}). @xref{Configuration}, and the @code{cache_timeout} "
5045 "parameter."
5048 new_command("LIST", 0, 1, 0, list_command, _(
5049 "LIST [--inquire] [--no-recurse] [--verbose] [--with-target] [--all] [[!]element[<TAB>[!]child[..]]]\n"
5050 "If no element path is given then a newline separated list of root elements "
5051 "is returned with a data response. If given, then all reachable elements "
5052 "of the specified element path are returned unless the @option{--no-recurse} "
5053 "option is specified. If specified, only the child elements of the element "
5054 "path are returned without recursing into grandchildren. Each resulting "
5055 "element is prefixed with the literal @code{!} character when the element "
5056 "contains no @code{target} attribute. @xref{Target Attribute}, for details."
5057 "\n"
5058 "When the @option{--verbose} option is passed then each element path "
5059 "returned will have zero or more flags appened to it. These flags are "
5060 "delimited from the element path by a single space character. A flag itself "
5061 "is a single character. Flag @code{P} indicates that access to the element "
5062 "is denied. Flag @code{+} indicates that there are child nodes of "
5063 "the current element path. Flag @code{E} indicates that an element of an "
5064 "element path contained in a @var{target} attribute could not be found. Flag "
5065 "@code{O} indicates that a @var{target} attribute recursion limit was reached "
5066 "(@pxref{Configuration}). Flag @code{T} will append the resolved element path "
5067 "of the @var{target} attribute contained in the current element (see below)."
5068 "\n"
5069 "The @option{--with-target} option implies @option{--verbose} and will append "
5070 "an additional flag @code{T} followed by a single space then an element path. "
5071 "The appended element path is the resolved path (@pxref{REALPATH}) of the "
5072 "current element when it contains a @var{target} attribute. When no "
5073 "@var{target} attribute is found then no flag will be appended."
5074 "\n"
5075 "The @option{--no-recurse} option limits the amount of data returned to only "
5076 "the listing of children of the specified element path and not any "
5077 "grandchildren."
5078 "\n"
5079 "The @option{--all} option lists the entire element tree for each root "
5080 "element. This option also implies option @option{--verbose}."
5081 "\n"
5082 "When the @option{--inquire} option is passed then all remaining non-option "
5083 "arguments are retrieved via a server @emph{INQUIRE}."
5086 new_command("REALPATH", 0, 1, 0, realpath_command, _(
5087 "REALPATH [--inquire] [!]element[<TAB>[!]child[..]]\n"
5088 "Resolves all @code{target} attributes of the specified element path and "
5089 "returns the result with a data response. @xref{Target Attribute}, for details."
5090 "\n"
5091 "When the @option{--inquire} option is passed then all remaining non-option "
5092 "arguments are retrieved via a server @emph{INQUIRE}."
5095 new_command("STORE", 0, 1, 0, store_command, _(
5096 "STORE [!]element[<TAB>[!]child[..]]<TAB>[content]\n"
5097 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
5098 "\n"
5099 "Creates a new element path or modifies the @var{content} of an existing "
5100 "element. If only a single element is specified then a new root element is "
5101 "created. Otherwise, elements are @key{TAB} delimited and the content will be "
5102 "set to the final @key{TAB} delimited element. If no @var{content} is "
5103 "specified after the final @key{TAB}, then the content of an existing "
5104 "element will be removed; or empty when creating a new element."
5105 "\n"
5106 "The only restriction of an element name is that it not contain whitespace "
5107 "or begin with the literal element character @code{!} unless specifying a "
5108 "literal element (@pxref{Target Attribute}). There is no whitespace between "
5109 "the @key{TAB} delimited elements. It is recommended that the content of an "
5110 "element be base64 encoded when it contains control or @key{TAB} characters "
5111 "to prevent @abbr{XML} parsing and @command{pwmd} syntax errors."
5114 new_command("RENAME", 0, 1, 0, rename_command, _(
5115 "RENAME [--inquire] [!]element[<TAB>[!]child[..]] <value>\n"
5116 "Renames the specified @var{element} to the new @var{value}. If an element of "
5117 "the same name as the @var{value} already exists it will be overwritten."
5118 "\n"
5119 "When the @option{--inquire} option is passed then all remaining non-option "
5120 "arguments are retrieved via a server @emph{INQUIRE}."
5123 new_command("COPY", 0, 1, 0, copy_command, _(
5124 "COPY [--inquire] [!]source[<TAB>[!]child[..]] [!]dest[<TAB>[!]child[..]]\n"
5125 "Copies the entire element tree starting from the child node of the source "
5126 "element, to the destination element path. If the destination element path "
5127 "does not exist then it will be created; otherwise it is overwritten."
5128 "\n"
5129 "Note that attributes from the source element are merged into the "
5130 "destination element when the destination element path exists. When an "
5131 "attribute of the same name exists in both the source and destination "
5132 "elements then the destination attribute will be updated to the source "
5133 "attribute value."
5134 "\n"
5135 "When the @option{--inquire} option is passed then all remaining non-option "
5136 "arguments are retrieved via a server @emph{INQUIRE}."
5139 new_command("MOVE", 0, 1, 0, move_command, _(
5140 "MOVE [--inquire] [!]source[<TAB>[!]child[..]] [[!]dest[<TAB>[!]child[..]]]\n"
5141 "Moves the source element path to the destination element path. If the "
5142 "destination is not specified then it will be moved to the root node of the "
5143 "document. If the destination is specified and exists then it will be "
5144 "overwritten; otherwise non-existing elements of the destination element "
5145 "path will be created."
5146 "\n"
5147 "When the @option{--inquire} option is passed then all remaining non-option "
5148 "arguments are retrieved via a server @emph{INQUIRE}."
5151 new_command("DELETE", 0, 1, 0, delete_command, _(
5152 "DELETE [--inquire] [!]element[<TAB>[!]child[..]]\n"
5153 "Removes the specified element path and all of its children. This may break "
5154 "an element with a @code{target} attribute (@pxref{Target Attribute}) that "
5155 "refers to this element or any of its children."
5156 "\n"
5157 "When the @option{--inquire} option is passed then all remaining non-option "
5158 "arguments are retrieved via a server @emph{INQUIRE}."
5161 new_command("GET", 0, 1, 0, get_command, _(
5162 "GET [--inquire] [!]element[<TAB>[!]child[..]]\n"
5163 "Retrieves the content of the specified element. The content is returned "
5164 "with a data response."
5165 "\n"
5166 "When the @option{--inquire} option is passed then all remaining non-option "
5167 "arguments are retrieved via a server @emph{INQUIRE}."
5170 new_command("ATTR", 0, 1, 0, attr_command, _(
5171 "ATTR [--inquire] SET|GET|DELETE|LIST [<attribute>] [!]element[<TAB>[!]child[..]] ..\n"
5172 "@table @asis\n"
5173 "@item ATTR SET attribute [!]element[<TAB>[!]child[..]] [value]\n"
5174 "\n"
5175 " Stores or updates an @var{attribute} name and optional @var{value} of an "
5176 "element. When no @var{value} is specified any existing value will be removed."
5177 "\n"
5178 "@item ATTR DELETE attribute [!]element[<TAB>[!]child[..]]\n"
5179 "\n"
5180 " Removes an @var{attribute} from an element."
5181 "\n"
5182 "@item ATTR LIST [!]element[<TAB>[!]child[..]]\n"
5183 "\n"
5184 " Retrieves a newline separated list of attributes names and values "
5185 "from the specified element. Each attribute name and value is space delimited."
5186 "\n"
5187 "@item ATTR GET attribute [!]element[<TAB>[!]child[..]]\n"
5188 "\n"
5189 " Retrieves the value of an @var{attribute} from an element."
5190 "@end table\n"
5191 "\n"
5192 "The @code{_name} attribute (case sensitive) cannot be removed nor modified. "
5193 "Use the @code{DELETE} (@pxref{DELETE}) or @code{RENAME} (@pxref{RENAME}) "
5194 "commands instead."
5195 "\n"
5196 "The @code{_mtime} attribute is updated each time an element is modified by "
5197 "either storing content, editing attributes or by deleting a child element. "
5198 "The @code{_ctime} attribute is created for each new element in an element "
5199 "path."
5200 "\n"
5201 "When the @option{--inquire} option is passed then all remaining non-option "
5202 "arguments are retrieved via a server @emph{INQUIRE}."
5203 "\n"
5204 "@xref{Target Attribute}, for details about this special attribute."
5207 new_command("XPATH", 0, 1, 0, xpath_command, _(
5208 "XPATH [--inquire] <expression>[<TAB>[value]]\n"
5209 "Evaluates an XPath @var{expression}. If no @var{value} argument is "
5210 "specified it is assumed the expression is a request to return a result. "
5211 "Otherwise, the result is set to the @var{value} argument and the document is "
5212 "updated. If there is no @var{value} after the @key{TAB} character, the value "
5213 "is assumed to be empty and the document is updated. For example:"
5214 "@sp 1\n"
5215 "@example\n"
5216 "XPATH //element[@@_name='password']@key{TAB}\n"
5217 "@end example\n"
5218 "@sp 1"
5219 "would clear the content of all @code{password} elements in the data file "
5220 "while leaving off the trailing @key{TAB} would return all @code{password} "
5221 "elements in @abbr{XML} format."
5222 "\n"
5223 "When the @option{--inquire} option is passed then all remaining non-option "
5224 "arguments are retrieved via a server @emph{INQUIRE}."
5225 "\n"
5226 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
5227 "expression syntax."
5230 new_command("XPATHATTR", 0, 1, 0, xpathattr_command, _(
5231 "XPATHATTR [--inquire] SET|DELETE <name> <expression>[<TAB>[<value>]]\n"
5232 "Like the @code{XPATH} command (@pxref{XPATH}) but operates on element "
5233 "attributes and does not return a result. For the @var{SET} operation the "
5234 "@var{value} is optional but the field is required. If not specified then "
5235 "the attribute value will be empty. For example:"
5236 "@sp 1"
5237 "@example\n"
5238 "XPATHATTR SET password //element[@@_name='password']@key{TAB}\n"
5239 "@end example\n"
5240 "@sp 1"
5241 "would create an @code{password} attribute for each @code{password} element "
5242 "found in the document. The attribute value will be empty but still exist."
5243 "\n"
5244 "When the @option{--inquire} option is passed then all remaining non-option "
5245 "arguments are retrieved via a server @emph{INQUIRE}."
5246 "\n"
5247 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
5248 "expression syntax."
5251 new_command("IMPORT", 0, 1, 0, import_command, _(
5252 "IMPORT [--root=[!]element[<TAB>[!]child[..]]] <content>\n"
5253 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
5254 "\n"
5255 "Like the @code{STORE} command (@pxref{STORE}), but the @var{content} "
5256 "argument is raw @abbr{XML} data. The content is created as a child of "
5257 "the element path specified with the @option{--root} option or at the "
5258 "document root when not specified. Existing elements of the same name will "
5259 "be overwritten."
5260 "\n"
5261 "The content must begin with an @abbr{XML} element node. @xref{Introduction}, "
5262 "for details."
5265 new_command("DUMP", 0, 1, 0, dump_command, _(
5266 "DUMP\n"
5267 "Shows the in memory @abbr{XML} document with indenting. @xref{XPATH}, for "
5268 "dumping a specific node."
5271 new_command("LOCK", 0, 0, 0, lock_command, _(
5272 "LOCK\n"
5273 "Locks the mutex associated with the opened file. This prevents other clients "
5274 "from sending commands to the same opened file until the client "
5275 "that sent this command either disconnects or sends the @code{UNLOCK} "
5276 "command. @xref{UNLOCK}."
5279 new_command("UNLOCK", 1, 0, 0, unlock_command, _(
5280 "UNLOCK\n"
5281 "Unlocks the file mutex which was locked with the @code{LOCK} command or "
5282 "a commands' @option{--lock} option (@pxref{LOCK}, @pxref{OPEN}, "
5283 "@pxref{ISCACHED})."
5286 new_command("GETCONFIG", 1, 1, FLOCK_TYPE_SH|FLOCK_TYPE_KEEP, getconfig_command, _(
5287 "GETCONFIG [filename] <parameter>\n"
5288 "Returns the value of a @command{pwmd} configuration @var{parameter} with a "
5289 "data response. If no file has been opened then the value for @var{filename} "
5290 "or the default from the @samp{global} section will be returned. If a file "
5291 "has been opened and no @var{filename} is specified, a value previously "
5292 "set with the @code{OPTION} command (@pxref{OPTION}) will be returned."
5295 new_command("OPTION", 1, 1, 0, option_command, _(
5296 "OPTION <NAME>=<VALUE>\n"
5297 "Sets a client option @var{name} to @var{value}. The value for an option is "
5298 "kept for the duration of the connection."
5299 "\n"
5300 "@table @asis\n"
5301 "@item DISABLE-PINENTRY\n"
5302 "Disable use of @command{pinentry} for passphrase retrieval. When set, a "
5303 "server inquire is sent to the client to obtain the passphrase. This option "
5304 "may be set as needed before the @code{OPEN} (@pxref{OPEN}), @code{PASSWD} "
5305 "(@pxref{PASSWD}) and @code{SAVE} (@pxref{SAVE}) commands."
5306 "\n"
5307 "@item PINENTRY-TIMEOUT\n"
5308 "Sets the number of seconds before a pinentry prompt will return an error "
5309 "while waiting for user input."
5310 "\n"
5311 "@item TTYNAME\n"
5312 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
5313 "\n"
5314 "@item TTYTYPE\n"
5315 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
5316 "\n"
5317 "@item DISPLAY\n"
5318 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
5319 "\n"
5320 "@item PINENTRY-DESC\n"
5321 "Sets the description string of the @command{gpg-agent} and @command{pinentry} dialog."
5322 "\n"
5323 "@item PINENTRY-TITLE\n"
5324 "Sets the title string of the @command{gpg-agent} and @command{pinentry} dialog."
5325 "\n"
5326 "@item PINENTRY-PROMPT\n"
5327 "Sets the prompt string of the @command{gpg-agent} and @command{pinentry} dialog."
5328 "\n"
5329 "@item LC-CTYPE\n"
5330 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
5331 "\n"
5332 "@item LC-MESSAGES\n"
5333 "Passed to the @command{gpg-agent} and used for the @command{pinentry} dialog."
5334 "\n"
5335 "@item NAME\n"
5336 "Associates the thread ID of the connection with the specified textual "
5337 "representation. Useful for debugging log messages. May not contain whitespace."
5338 "\n"
5339 "@item LOCK-TIMEOUT\n"
5340 "When not @code{0}, the duration in tenths of a second to wait for the file "
5341 "mutex which has been locked by another thread to be released before returning "
5342 "an error. When @code{-1}, then an error will be returned immediately."
5343 "@end table\n"
5346 new_command("LS", 1, 1, 0, ls_command, _(
5347 "LS\n"
5348 "Lists the available data files stored in the data directory "
5349 "(@file{~/.pwmd/data}). The result is a newline separated list of filenames."
5352 new_command("RESET", 1, 1, 0, NULL, _(
5353 "RESET\n"
5354 "Closes the currently opened file but keeps any previously set client options."
5357 new_command("NOP", 1, 1, 0, NULL, _(
5358 "NOP\n"
5359 "Does nothing. Always returns successfully."
5362 /* !END-HELP-TEXT! */
5363 new_command ("CANCEL", 1, 1, 0, NULL, NULL);
5364 new_command ("END", 1, 1, 0, NULL, NULL);
5365 new_command ("BYE", 1, 1, 0, NULL, NULL);
5367 int i;
5368 for (i = 0; command_table[i]; i++);
5369 qsort (command_table, i - 1, sizeof (struct command_table_s *),
5370 sort_commands);
5373 gpg_error_t
5374 register_commands (assuan_context_t ctx)
5376 int i = 0, rc;
5378 for (; command_table[i]; i++)
5380 if (!command_table[i]->handler)
5381 continue;
5383 rc = assuan_register_command (ctx, command_table[i]->name,
5384 command_table[i]->handler,
5385 command_table[i]->help);
5386 if (rc)
5387 return rc;
5390 rc = assuan_register_bye_notify (ctx, bye_notify);
5391 if (rc)
5392 return rc;
5394 rc = assuan_register_reset_notify (ctx, reset_notify);
5395 if (rc)
5396 return rc;
5398 rc = assuan_register_pre_cmd_notify (ctx, command_startup);
5399 if (rc)
5400 return rc;
5402 return assuan_register_post_cmd_notify (ctx, command_finalize);