Use the correct free().
[pwmd.git] / src / commands.c
blobd8c3139f07df33d0f822f9dfd29123cddd786f82
1 /*
2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015,
3 2016
4 Ben Kibbey <bjk@luxsci.net>
6 This file is part of pwmd.
8 Pwmd is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 2 of the License, or
11 (at your option) any later version.
13 Pwmd is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
21 #ifdef HAVE_CONFIG_H
22 #include <config.h>
23 #endif
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <err.h>
29 #include <errno.h>
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <fcntl.h>
33 #include <ctype.h>
34 #include <dirent.h>
35 #include <pthread.h>
36 #include <stdint.h>
37 #include <assert.h>
38 #include <signal.h>
40 #include "pwmd-error.h"
41 #include <gcrypt.h>
43 #include "mem.h"
44 #include "xml.h"
45 #include "util-misc.h"
46 #include "common.h"
47 #include "rcfile.h"
48 #include "cache.h"
49 #include "commands.h"
50 #include "mutex.h"
51 #include "crypto.h"
52 #include "acl.h"
54 /* These are command option flags. */
55 #define OPT_INQUIRE 0x0001
56 #define OPT_NO_PASSPHRASE 0x0002
57 #define OPT_ASK 0x0004
58 #define OPT_LIST_RECURSE 0x0008
59 #define OPT_VERBOSE 0x0010
60 #define OPT_LOCK 0x0020
61 #define OPT_LOCK_ON_OPEN 0x0040
62 #define OPT_SIGN 0x0080
63 #define OPT_LIST_ALL 0x0100
64 #define OPT_DATA 0x0200
65 #define OPT_NO_AGENT 0x0400
66 #define OPT_SECRET_ONLY 0x0800
67 #define OPT_INQUIRE_KEYID 0x1000
68 #define OPT_INQUIRE_SIGN_KEYID 0x2000
69 #define OPT_SYMMETRIC 0x4000
70 #define OPT_NO_SIGNER 0x8000
71 #define OPT_HTML 0x10000
72 #define OPT_CACHE_AGENT 0x20000
73 #define OPT_CACHE_SIGN 0x40000
75 #define FLOCK_TYPE_NONE 0
76 #define FLOCK_TYPE_SH 0x0001
77 #define FLOCK_TYPE_EX 0x0002
78 #define FLOCK_TYPE_KEEP 0x0004
80 struct command_table_s
82 const char *name;
83 gpg_error_t (*handler) (assuan_context_t, char *line);
84 const char *help;
85 int ignore_startup;
86 int unlock; // unlock the file mutex after validating the checksum
87 uint32_t flock_type;
90 static struct command_table_s **command_table;
92 static gpg_error_t do_lock (struct client_s *client, int add);
93 static gpg_error_t validate_checksum (struct client_s *, const char *filename,
94 struct cache_data_s *, unsigned char **,
95 size_t *);
96 static gpg_error_t update_checksum (struct client_s *client);
98 /* When 'status' is true the 'self' field of the status line will be false
99 * because we never send the STATE status message to the same client that
100 * initiated it. */
101 static char *
102 build_client_info_line (struct client_thread_s *thd, int status)
104 char *uid, *username = NULL;
105 char *line;
106 char *name = pthread_getspecific (thread_name_key);
108 #ifdef WITH_GNUTLS
109 if (thd->remote)
110 uid = str_asprintf("#%s", thd->tls->fp);
111 else
113 uid = str_asprintf("%u", thd->peer->uid);
114 username = get_username (thd->peer->uid);
116 #else
117 uid = str_asprintf("%u", thd->peer->uid);
118 username = get_username (thd->peer->uid);
119 #endif
120 line = str_asprintf ("%p %s %s %s %u %u %u %s %s %u",
121 thd->tid,
122 name ? name : "-",
123 thd->cl && thd->cl->filename
124 && (thd->cl->flags & FLAG_OPEN)
125 ? thd->cl->filename : "/",
126 #ifdef WITH_GNUTLS
127 thd->remote ? thd->peeraddr : "-",
128 #else
129 "-",
130 #endif
131 thd->cl && thd->cl->flags & FLAG_HAS_LOCK ? 1 : 0,
132 !status && pthread_equal (pthread_self (), thd->tid) ? 1 : 0,
133 thd->state, uid,
134 #ifdef WITH_GNUTLS
135 thd->remote ? "-" : username,
136 #else
137 username,
138 #endif
139 thd->conntime
142 xfree (username);
143 xfree (uid);
144 return line;
147 void
148 update_client_state (struct client_s *client, unsigned s)
150 MUTEX_LOCK (&cn_mutex);
151 client->thd->state = s;
152 MUTEX_UNLOCK (&cn_mutex);
154 if (client->thd->state != CLIENT_STATE_UNKNOWN)
156 char *line = build_client_info_line (client->thd, 1);
158 pthread_cleanup_push (xfree, line);
159 if (line)
160 send_status_all_not_self (STATUS_STATE, "%s", line);
161 pthread_cleanup_pop (1);
165 static gpg_error_t
166 unlock_file_mutex (struct client_s *client, int remove)
168 gpg_error_t rc = 0;
170 // OPEN: keep the lock for the same file being reopened.
171 if (client->flags & FLAG_KEEP_LOCK && client->flags & FLAG_HAS_LOCK)
172 return 0;
174 if (!(client->flags & FLAG_HAS_LOCK))
175 return GPG_ERR_NOT_LOCKED;
177 rc = cache_unlock_mutex (client->filename, remove);
178 if (rc)
179 rc = GPG_ERR_INV_STATE;
180 else
181 client->flags &= ~(FLAG_HAS_LOCK | FLAG_LOCK_CMD);
183 return rc;
186 static gpg_error_t
187 lock_file_mutex (struct client_s *client, int add)
189 gpg_error_t rc = 0;
190 int timeout = config_get_integer (client->filename, "cache_timeout");
192 if (client->flags & FLAG_HAS_LOCK)
193 return 0;
195 rc = cache_lock_mutex (client->ctx, client->filename,
196 client->lock_timeout, add, timeout);
197 if (!rc)
198 client->flags |= FLAG_HAS_LOCK;
200 return rc;
203 static gpg_error_t
204 file_modified (struct client_s *client, struct command_table_s *cmd)
206 gpg_error_t rc = 0;
207 int type = !cmd->flock_type || (cmd->flock_type & FLOCK_TYPE_SH)
208 ? LOCK_SH : LOCK_EX;
210 if (!(client->flags & FLAG_OPEN))
211 return GPG_ERR_INV_STATE;
213 rc = lock_file_mutex (client, 0);
214 if (rc && rc != GPG_ERR_NO_DATA)
215 return rc;
217 rc = lock_flock (client->ctx, client->filename, type, &client->flock_fd);
218 if (!rc)
220 rc = validate_checksum (client, client->filename, NULL, NULL, NULL);
221 if (gpg_err_code (rc) == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
222 rc = 0;
223 else if (rc)
224 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
226 else if (gpg_err_code (rc) == GPG_ERR_ENOENT)
227 rc = 0;
229 /* FLAG_HAS_LOCK may have been set by the LOCK command or OPEN --lock. */
230 if ((cmd->unlock && !(client->flags & FLAG_HAS_LOCK)) || rc)
231 unlock_file_mutex (client, 0);
233 if (rc || !(cmd->flock_type & FLOCK_TYPE_KEEP))
234 unlock_flock (&client->flock_fd);
236 return rc;
239 static gpg_error_t
240 parse_xml (assuan_context_t ctx, int new)
242 struct client_s *client = assuan_get_pointer (ctx);
243 int cached = client->doc != NULL;
244 gpg_error_t rc = 0;
246 if (new)
248 client->doc = xml_new_document ();
249 if (client->doc)
251 xmlChar *result;
252 int len;
254 xmlDocDumpFormatMemory (client->doc, &result, &len, 0);
255 client->crypto->plaintext = result;
256 client->crypto->plaintext_size = len;
257 if (!client->crypto->plaintext)
259 xmlFreeDoc (client->doc);
260 client->doc = NULL;
261 rc = GPG_ERR_ENOMEM;
264 else
265 rc = GPG_ERR_ENOMEM;
267 else if (!cached)
268 rc = xml_parse_doc ((char *) client->crypto->plaintext,
269 client->crypto->plaintext_size,
270 (xmlDocPtr *)&client->doc);
272 return rc;
275 static void
276 free_client (struct client_s *client)
278 if (client->doc)
279 xmlFreeDoc (client->doc);
281 xfree (client->crc);
282 xfree (client->filename);
283 xfree (client->last_error);
284 crypto_free (client->crypto);
285 client->crypto = NULL;
288 void
289 reset_client (struct client_s *client)
291 assuan_context_t ctx = client->ctx;
292 struct client_thread_s *thd = client->thd;
293 long lock_timeout = client->lock_timeout;
294 xmlErrorPtr xml_error = client->xml_error;
295 int no_pinentry = (client->flags & FLAG_NO_PINENTRY);
296 int flock_fd = client->flock_fd;
298 unlock_file_mutex (client, client->flags & FLAG_NEW);
299 free_client (client);
300 memset (client, 0, sizeof (struct client_s));
301 client->flock_fd = flock_fd;
302 client->xml_error = xml_error;
303 client->ctx = ctx;
304 client->thd = thd;
305 client->lock_timeout = lock_timeout;
306 client->flags |= no_pinentry ? FLAG_NO_PINENTRY : 0;
309 static void
310 req_free (void *arg)
312 if (!arg)
313 return;
315 strv_free ((char **) arg);
318 static gpg_error_t
319 parse_open_opt_lock (void *data, void *value)
321 struct client_s *client = data;
323 (void)value;
324 client->opts |= OPT_LOCK_ON_OPEN;
325 return 0;
328 static gpg_error_t
329 parse_opt_inquire (void *data, void *value)
331 struct client_s *client = data;
333 (void) value;
334 client->opts |= OPT_INQUIRE;
335 return 0;
338 static gpg_error_t
339 update_checksum (struct client_s *client)
341 unsigned char *crc;
342 size_t len;
343 struct cache_data_s *cdata;
344 gpg_error_t rc = get_checksum (client->filename, &crc, &len);
346 if (rc)
347 return rc;
349 xfree (client->crc);
350 client->crc = crc;
351 cdata = cache_get_data (client->filename);
352 if (cdata)
354 xfree (cdata->crc);
355 cdata->crc = xmalloc (len);
356 memcpy (cdata->crc, crc, len);
359 return 0;
362 static gpg_error_t
363 validate_checksum (struct client_s *client, const char *filename,
364 struct cache_data_s *cdata, unsigned char **r_crc,
365 size_t *r_crclen)
367 unsigned char *crc;
368 size_t len;
369 gpg_error_t rc;
370 int n = 0;
372 if (cdata && !cdata->crc)
373 return GPG_ERR_CHECKSUM;
375 rc = get_checksum (filename, &crc, &len);
376 if (rc)
377 return rc;
379 if (cdata)
380 n = memcmp (cdata->crc, crc, len);
381 else if (client->crc)
382 n = memcmp (client->crc, crc, len);
384 if (!n && r_crc)
386 *r_crc = crc;
387 *r_crclen = len;
389 else
390 xfree (crc);
392 return n ? GPG_ERR_CHECKSUM : 0;
395 static gpg_error_t
396 open_command (assuan_context_t ctx, char *line)
398 gpg_error_t rc;
399 struct client_s *client = assuan_get_pointer (ctx);
400 char **req, *filename;
401 int same_file = 0;
402 assuan_peercred_t peer;
403 struct cache_data_s *cdata = NULL;
404 int cached = 0;
405 unsigned char *crc = NULL;
406 size_t crclen = 0;
407 struct argv_s *args[] = {
408 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_open_opt_lock},
409 NULL
412 rc = parse_options (&line, args, client, 1);
413 if (rc)
414 return send_error (ctx, rc);
416 req = str_split (line, " ", 2);
417 if (!req)
418 return send_error (ctx, GPG_ERR_SYNTAX);
420 rc = do_validate_peer (ctx, req[0], &peer);
421 if (rc == GPG_ERR_FORBIDDEN)
422 rc = peer_is_invoker (client);
424 if (rc)
426 strv_free (req);
427 return send_error (ctx, rc);
430 filename = req[0];
431 if (!valid_filename (filename))
433 strv_free (req);
434 return send_error (ctx, GPG_ERR_INV_VALUE);
437 pthread_cleanup_push ((void *)req_free, req);
438 /* This client may have locked a different file with ISCACHED --lock than
439 * the current filename. This will remove that lock. */
440 same_file = client->filename && !strcmp (filename, client->filename);
441 if (client->flags & FLAG_OPEN ||
442 (client->flags & FLAG_HAS_LOCK && !same_file))
444 uint32_t opts = client->opts;
445 uint32_t flags = client->flags;
447 if (same_file)
448 client->flags |= FLAG_KEEP_LOCK;
449 else if (client->flags & FLAG_NEW)
450 cache_clear (NULL, client->filename, 0);
452 reset_client (client);
453 client->opts = opts;
454 client->flags |= flags;
455 client->flags &= ~(FLAG_LOCK_CMD);
456 if (!same_file)
457 client->flags &= ~(FLAG_HAS_LOCK | FLAG_NEW);
460 client->filename = str_dup (filename);
461 if (!client->filename)
463 strv_free (req);
464 return send_error(ctx, GPG_ERR_ENOMEM);
467 /* Need to lock the mutex here because file_modified() cannot without
468 * knowing the filename. */
469 rc = lock_file_mutex (client, 1);
470 if (rc)
471 client->flags &= ~FLAG_OPEN;
473 if (!rc)
475 rc = lock_flock (ctx, filename, LOCK_SH, &client->flock_fd);
476 if (gpg_err_code (rc) == GPG_ERR_ENOENT)
477 rc = 0;
480 if (!rc)
482 char *keyfile = config_get_string (client->filename, "passphrase_file");
484 rc = crypto_init (&client->crypto, client->ctx, client->filename,
485 client->flags & FLAG_NO_PINENTRY, keyfile);
486 if (rc)
487 xfree (keyfile);
489 rc = open_check_file (client->filename, NULL, NULL, 1);
492 if (!rc || gpg_err_code (rc) == GPG_ERR_ENOENT)
494 cdata = cache_get_data (client->filename);
496 if (rc) // new file
498 rc = 0;
499 client->flags |= FLAG_NEW;
500 // data file disappeared. clear the cache entry.
501 cache_clear (NULL, client->filename, 1);
502 cdata = NULL;
504 else if (cdata && cdata->doc) // cached document
506 int reload = 0;
507 int defer = 0;
509 if (!rc && !(client->flags & FLAG_NEW))
511 rc = validate_checksum (client, client->filename, cdata, &crc,
512 &crclen);
513 if (rc == GPG_ERR_CHECKSUM)
515 rc = 0;
516 reload = 1;
520 if (!rc)
522 rc = cache_iscached (client->filename, &defer, 0, 0);
523 if ((!rc || rc == GPG_ERR_ENOENT) && defer)
525 rc = 0;
526 reload = 2;
530 if (!rc && reload)
532 if (reload == 1)
533 log_write ("%s: %s", client->filename,
534 pwmd_strerror (GPG_ERR_CHECKSUM));
535 cache_clear (NULL, client->filename, 1);
536 cdata = NULL;
537 rc = crypto_decrypt (client, client->crypto);
539 #ifdef WITH_GNUTLS
540 else if (!rc)
542 if (client->thd->remote
543 && config_get_boolean (client->filename, "tcp_require_key")
544 && !(client->flags & FLAG_NEW))
545 rc = crypto_try_decrypt (client,
546 (client->flags & FLAG_NO_PINENTRY));
548 #endif
550 if (!rc && cdata)
552 client->crypto->plaintext = cdata->doc;
553 client->crypto->plaintext_size = cdata->size;
554 rc = cache_decrypt (client->crypto);
555 if (!rc)
557 cdata->doc = NULL;
558 cdata->size = 0;
559 strv_free (client->crypto->pubkey);
560 strv_free (client->crypto->sigkey);
561 client->crypto->pubkey = strv_dup (cdata->pubkey);
562 client->crypto->sigkey = strv_dup (cdata->sigkey);
563 cached = 1;
565 else
567 client->crypto->plaintext = NULL;
568 client->crypto->plaintext_size = 0;
572 else // existing file
574 cached = cdata != NULL;
575 rc = crypto_decrypt (client, client->crypto);
579 if (!rc)
581 rc = parse_xml (ctx, client->flags & FLAG_NEW);
582 if (!rc)
584 rc = cache_encrypt (client->crypto);
585 if (rc)
586 cache_clear (NULL, client->filename, 1);
587 else
589 int timeout = config_get_integer (client->filename,
590 "cache_timeout");
592 cache_free_data_once (cdata);
593 cdata = xcalloc (1, sizeof (struct cache_data_s));
594 cdata->doc = client->crypto->plaintext;
595 cdata->size = client->crypto->plaintext_size;
596 cdata->pubkey = strv_dup(client->crypto->pubkey);
597 cdata->sigkey = strv_dup(client->crypto->sigkey);
598 client->crypto->plaintext = NULL;
599 client->crypto->plaintext_size = 0;
601 if (cached) // wont increment the refcount
603 /* Prevent using another FD to update the checksum for a
604 * cached data file. The validity has already been
605 * verified. */
606 xfree (client->crc);
607 client->crc = xmalloc (crclen);
608 memcpy (client->crc, crc, crclen);
609 xfree (cdata->crc);
610 cdata->crc = xmalloc (crclen);
611 memcpy (cdata->crc, crc, crclen);
613 rc = cache_set_data (client->filename, cdata);
614 /* The cache entry may have been removed and cache_set_data()
615 * already sent STATUS_CACHE. */
616 if (!cache_iscached (client->filename, NULL, 0, 0))
617 rc = send_status (ctx, STATUS_CACHE, NULL);
619 else
620 rc = cache_add_file (client->filename, cdata, timeout);
625 pthread_cleanup_pop (1);
626 xfree (crc);
628 if (!rc && !(client->flags & FLAG_NEW) && !cached)
629 rc = update_checksum (client);
631 if (!rc)
633 client->flags |= FLAG_OPEN;
635 if (client->flags & FLAG_NEW)
636 rc = send_status (ctx, STATUS_NEWFILE, NULL);
638 if (!rc && (client->opts & OPT_LOCK_ON_OPEN))
639 rc = do_lock (client, 0);
642 if (rc)
644 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
646 if (client->flags & FLAG_NEW)
647 cache_clear (NULL, client->filename, 1);
649 crypto_free (client->crypto);
650 client->crypto = NULL;
651 client->flags &= ~FLAG_OPEN;
653 else
654 crypto_free_non_keys (client->crypto);
656 return send_error (ctx, rc);
659 /* If not the invoking_user or is an existing file, check that the list of user
660 * supplied key ID's are in the list of current key ID's obtained when
661 * decrypting the data file.
663 static gpg_error_t
664 permitted_to_save (struct client_s *client, const char **keys,
665 const char **value)
667 gpg_error_t rc = 0;
668 const char **v;
670 if ((client->flags & FLAG_NEW) || (client->opts & OPT_SYMMETRIC))
671 return 0;
673 rc = peer_is_invoker (client);
674 if (!rc)
675 return 0;
677 /* Empty match. */
678 if ((!value && !keys) || ((value && !*value) && (keys && !*keys)))
679 return 0;
681 for (v = value; v && *v; v++)
683 const char **k, *pv = *v;
684 int match = 0;
686 if (*pv == '0' && *(pv+1) == 'x')
687 pv += 2;
689 for (k = keys; k && *k; k++)
691 const char *pk = *k;
693 if (*pk == '0' && *(pk+1) == 'x')
694 pk += 2;
696 rc = !strcmp (pv, pk) ? 0 : GPG_ERR_FORBIDDEN;
697 if (rc)
698 rc = !strcmp (pv, *k) ? 0 : GPG_ERR_FORBIDDEN;
700 if (!rc)
702 match = 1;
703 break;
707 if (!match)
708 return GPG_ERR_FORBIDDEN;
711 return rc;
714 /* Requires that the keyid be a fingerprint in 16 byte form. */
715 static gpg_error_t
716 parse_save_opt_keyid_common (struct client_s *client, const char **list,
717 const char *value, char ***dst)
719 gpg_error_t rc = 0;
720 char **keys = NULL;
722 if (value && *value)
724 keys = str_split (value, ",", 0);
725 if (!keys)
726 return GPG_ERR_ENOMEM;
729 rc = crypto_keyid_to_16b (keys);
730 if (!rc)
731 rc = permitted_to_save (client, list, (const char **)keys);
733 if (!rc)
734 *dst = keys;
735 else
736 strv_free (keys);
738 return rc;
741 static gpg_error_t
742 parse_save_opt_keyid (void *data, void *value)
744 struct client_s *client = data;
745 const char *str = value;
746 char **dst = NULL;
747 gpg_error_t rc;
749 rc = parse_save_opt_keyid_common (client,
750 (const char **)client->crypto->pubkey,
751 str, &dst);
752 if (rc)
753 return rc;
755 client->crypto->save.pubkey = dst;
756 return 0;
759 static gpg_error_t
760 parse_save_opt_sign_keyid (void *data, void *value)
762 struct client_s *client = data;
763 const char *str = value;
764 char **dst = NULL;
765 gpg_error_t rc;
767 rc = parse_save_opt_keyid_common (client,
768 (const char **)client->crypto->sigkey,
769 str, &dst);
770 if (rc)
771 return rc;
773 if (!dst)
774 client->opts |= OPT_NO_SIGNER;
776 client->crypto->save.sigkey = dst;
777 return 0;
780 static gpg_error_t
781 parse_save_opt_inquire (struct client_s *client, uint32_t opt)
783 if (opt == OPT_INQUIRE && !(client->flags & FLAG_NEW))
785 gpg_error_t rc = peer_is_invoker (client);
787 if (rc)
788 return rc;
791 client->opts |= opt;
792 return 0;
795 static gpg_error_t
796 parse_save_opt_inquire_keyparam (void *data, void *value)
798 (void)value;
799 return parse_save_opt_inquire (data, OPT_INQUIRE);
802 static gpg_error_t
803 parse_save_opt_inquire_keyid (void *data, void *value)
805 (void)value;
806 return parse_save_opt_inquire (data, OPT_INQUIRE_KEYID);
809 static gpg_error_t
810 parse_save_opt_inquire_sign_keyid (void *data, void *value)
812 (void)value;
813 return parse_save_opt_inquire (data, OPT_INQUIRE_SIGN_KEYID);
816 static gpg_error_t
817 parse_save_opt_symmetric (void *data, void *value)
819 struct client_s *client = data;
821 (void)value;
822 client->opts |= OPT_SYMMETRIC;
823 return 0;
826 /* Tests that the keys in new_keys are also in old_keys. */
827 static gpg_error_t
828 compare_keys (char **new_keys, char **old_keys)
830 char **o;
832 if (!old_keys || !*old_keys)
833 return 0;
835 crypto_keyid_to_16b (new_keys);
837 for (o = old_keys; *o; o++)
839 char **n;
841 for (n = new_keys; *n; n++)
843 if (!strcmp (*n, *o))
844 break;
847 if (!*n)
848 return GPG_ERR_NOT_FOUND;
851 return 0;
854 static gpg_error_t
855 inquire_keyid (struct client_s *client, uint32_t opt)
857 gpg_error_t rc;
858 unsigned char *result = NULL;
859 size_t len;
860 const char *s;
861 char ***orig;
862 char ***save;
864 if (opt == OPT_INQUIRE_KEYID)
866 s = "INQUIRE_KEYID";
867 orig = &client->crypto->pubkey;
868 save = &client->crypto->save.pubkey;
870 else
872 s = "INQUIRE_SIGN_KEYID";
873 orig = &client->crypto->sigkey;
874 save = &client->crypto->save.sigkey;
877 rc = assuan_inquire (client->ctx, s, &result, &len, 0);
878 if (!rc)
880 char **dst = NULL;
882 rc = parse_save_opt_keyid_common (client, (const char **)*orig,
883 (char *)result, &dst);
884 if (!rc)
886 if (!dst && opt == OPT_INQUIRE_SIGN_KEYID
887 && client->opts & OPT_SYMMETRIC)
888 client->opts |= OPT_NO_SIGNER;
890 *save = dst;
894 xfree (result);
895 return rc;
898 /* The caching test of gpg-agent is both a blessing and a curse. When a key
899 * lookup in its cache fails it tries the last successful key to be unlocked.
900 * This prevents pwmd from successfully clearing a signing key since the
901 * previous key, which more than likely belongs to the same keypair as the
902 * encryption/decryption key, will have the passphrase cached and therefore the
903 * signing key also cached. So we need to clear both the signing and encryption
904 * keys to get the effect of requiring a passphrase when generating a new
905 * keypair for an existing data file, or when the "require_save_key"
906 * configuration parameter is set. The "require_save_key" parameter is mostly a
907 * failsafe of the gpg-agent option --ignore-cache-for-signing since
908 * some/most/all users may fail to set it.
910 static gpg_error_t
911 save_command (assuan_context_t ctx, char *line)
913 struct client_s *client = assuan_get_pointer (ctx);
914 struct cache_data_s *cdata = NULL;
915 gpg_error_t rc = 0, cached = 0;
916 int defer = 0;
917 struct argv_s *args[] = {
918 &(struct argv_s) {"keyid", OPTION_TYPE_ARG, parse_save_opt_keyid},
919 &(struct argv_s) {"sign-keyid", OPTION_TYPE_OPTARG,
920 parse_save_opt_sign_keyid},
921 &(struct argv_s) {"inquire-keyparam", OPTION_TYPE_NOARG,
922 parse_save_opt_inquire_keyparam },
923 &(struct argv_s) {"inquire-keyid", OPTION_TYPE_NOARG,
924 parse_save_opt_inquire_keyid },
925 &(struct argv_s) {"inquire-sign-keyid", OPTION_TYPE_NOARG,
926 parse_save_opt_inquire_sign_keyid },
927 &(struct argv_s) {"symmetric", OPTION_TYPE_NOARG,
928 parse_save_opt_symmetric },
929 NULL
932 crypto_free_save (&client->crypto->save);
934 if (!(client->flags & FLAG_NEW))
936 rc = crypto_is_symmetric (client->filename);
937 if (!rc || rc == GPG_ERR_BAD_DATA)
939 if (!rc)
940 client->opts |= OPT_SYMMETRIC;
942 rc = 0; // PKI
946 if (rc)
947 return send_error (ctx, rc);
949 rc = parse_options (&line, args, client, 0);
950 if (rc)
951 return send_error (ctx, rc);
954 if (config_get_boolean (client->filename, "require_save_key")
955 || (client->opts & OPT_SYMMETRIC))
956 client->opts |= OPT_ASK;
958 rc = open_check_file (client->filename, NULL, NULL, 1);
959 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
961 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
962 return send_error (ctx, rc);
965 if (!rc)
966 cached = rc = cache_iscached (client->filename, &defer, 0, 1);
968 if (gpg_err_code (rc) == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
969 rc = 0;
970 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
971 rc = 0;
973 if (rc)
974 return send_error (ctx, rc);
976 /* Specifying both a recipient and symmetric encryption is an error. */
977 if (client->opts & OPT_INQUIRE_KEYID && client->opts & OPT_SYMMETRIC)
979 return send_error (ctx, GPG_ERR_CONFLICT);
981 else if (client->opts & OPT_INQUIRE && client->opts & OPT_SYMMETRIC)
983 return send_error (ctx, GPG_ERR_CONFLICT);
985 /* Existing file with a recipient and wanting symmetric is an error. */
986 else if (client->opts & OPT_SYMMETRIC && client->crypto->save.pubkey)
988 return send_error (ctx, GPG_ERR_CONFLICT);
990 else if (((client->opts & OPT_INQUIRE_KEYID)
991 || (client->opts & OPT_INQUIRE_SIGN_KEYID)))
993 if (client->opts & OPT_INQUIRE)
994 return send_error (ctx, GPG_ERR_CONFLICT);
996 if (client->opts & OPT_INQUIRE_KEYID)
997 rc = inquire_keyid (client, OPT_INQUIRE_KEYID);
999 if (!rc && (client->opts & OPT_INQUIRE_SIGN_KEYID))
1000 rc = inquire_keyid (client, OPT_INQUIRE_SIGN_KEYID);
1002 else if ((client->crypto->save.pubkey || client->crypto->save.sigkey)
1003 && client->opts & OPT_INQUIRE)
1004 return send_error (ctx, GPG_ERR_CONFLICT);
1006 if (!rc)
1008 client->crypto->keyfile = config_get_string (client->filename,
1009 "passphrase_file");
1010 rc = crypto_init_ctx (client->crypto, (client->flags & FLAG_NO_PINENTRY),
1011 client->crypto->keyfile);
1014 if (!rc && (client->opts & OPT_INQUIRE))
1016 /* Require a passphrase when generating a new key pair for an existing
1017 * file.
1019 if (!(client->flags & FLAG_NEW))
1021 rc = cache_clear_agent_keys (client->filename, 1, 1);
1022 if (!rc)
1024 rc = crypto_try_decrypt (client, client->flags & FLAG_NO_PINENTRY);
1025 client->opts &= ~OPT_ASK;
1029 if (!rc)
1031 unsigned char *params = NULL;
1032 size_t len;
1034 rc = assuan_inquire (client->ctx, "KEYPARAM", &params, &len, 0);
1035 if (!rc)
1037 client->crypto->flags |= CRYPTO_FLAG_NEWFILE;
1038 pthread_cleanup_push ((void *)xfree, params);
1039 rc = crypto_genkey (client, client->crypto, params);
1040 pthread_cleanup_pop (1);
1044 else if (!rc && (client->flags & FLAG_NEW))
1046 if (!client->crypto->save.pubkey && !client->crypto->save.sigkey
1047 && !(client->opts & OPT_SYMMETRIC))
1049 char *params = crypto_default_key_params ();
1051 if (!params)
1052 rc = GPG_ERR_ENOMEM;
1054 if (!rc)
1056 client->crypto->flags |= CRYPTO_FLAG_NEWFILE;
1057 pthread_cleanup_push ((void *)xfree, params);
1058 rc = crypto_genkey (client, client->crypto,
1059 (unsigned char *)params);
1060 pthread_cleanup_pop (1);
1063 else
1065 if (!client->crypto->save.pubkey && client->crypto->save.sigkey
1066 && !(client->opts & OPT_SYMMETRIC))
1067 client->crypto->save.pubkey = strv_dup (client->crypto->save.sigkey);
1069 if (client->crypto->save.pubkey && !client->crypto->save.sigkey)
1070 client->crypto->save.sigkey = strv_dup (client->crypto->save.pubkey);
1073 else if (!rc)
1075 cdata = cache_get_data (client->filename);
1076 if (cdata)
1078 if (client->crypto->save.pubkey)
1079 rc = compare_keys (client->crypto->save.pubkey, cdata->pubkey);
1081 /* Always allow a signer for symmetric data files. */
1082 if (!rc && client->crypto->save.sigkey
1083 && !(client->opts & OPT_SYMMETRIC))
1084 rc = compare_keys (client->crypto->save.sigkey, cdata->sigkey);
1086 /* Prevent saving to a recipient who is not in the original recipient
1087 * list without a passphrase. */
1088 if (rc || (client->crypto->sigkey && client->opts & OPT_NO_SIGNER))
1089 client->opts |= OPT_ASK;
1091 if (rc == GPG_ERR_NOT_FOUND)
1093 rc = peer_is_invoker (client);
1094 if (rc == GPG_ERR_EACCES)
1095 rc = GPG_ERR_FORBIDDEN;
1098 if (!client->crypto->save.pubkey
1099 && !(client->opts & OPT_SYMMETRIC))
1100 client->crypto->save.pubkey = strv_dup (cdata->pubkey);
1102 if (!rc && !client->crypto->save.sigkey && cdata->sigkey
1103 && !(client->opts & OPT_NO_SIGNER))
1104 client->crypto->save.sigkey = strv_dup (cdata->sigkey);
1105 else if (!rc && !client->crypto->save.sigkey
1106 && (client->opts & OPT_NO_SIGNER)
1107 && !(client->opts & OPT_SYMMETRIC))
1108 rc = GPG_ERR_NO_SIGNATURE_SCHEME;
1110 else
1112 client->crypto->save.pubkey = strv_dup (client->crypto->pubkey);
1113 client->crypto->save.sigkey = strv_dup (client->crypto->sigkey);
1117 if (!rc && !(client->flags & FLAG_NEW))
1119 /* Fixes {NEW_,SIGN_}PASSPHRASE inquire keywords. See passphrase_cb(). */
1120 if (client->opts & OPT_SYMMETRIC)
1121 client->crypto->flags |= CRYPTO_FLAG_PASSWD;
1123 if (client->opts & OPT_ASK)
1125 rc = cache_clear_agent_keys (client->filename, 1, 1);
1126 if (!rc)
1127 rc = crypto_try_decrypt (client, client->flags & FLAG_NO_PINENTRY);
1131 if (!rc && client->opts & OPT_SYMMETRIC)
1132 client->crypto->flags |= CRYPTO_FLAG_PASSWD_NEW;
1134 if (!rc)
1135 rc = xml_update_element_mtime (client, xmlDocGetRootElement (client->doc));
1137 if (!rc)
1139 int size;
1141 xmlDocDumpFormatMemory (client->doc, &client->crypto->plaintext, &size,
1143 if (size > 0)
1144 client->crypto->plaintext_size = (size_t) size;
1145 else
1146 rc = GPG_ERR_ENOMEM;
1148 if (!rc)
1150 client->crypto->flags |= (client->opts & OPT_SYMMETRIC) ? CRYPTO_FLAG_SYMMETRIC : 0;
1151 client->crypto->flags |= (client->flags & FLAG_NEW) ? CRYPTO_FLAG_NEWFILE : 0;
1152 client->crypto->flags |= !(client->opts & OPT_SYMMETRIC) ? CRYPTO_FLAG_PASSWD_SIGN : 0;
1153 rc = crypto_encrypt (client, client->crypto);
1154 client->crypto->flags &= ~CRYPTO_FLAG_SYMMETRIC;
1157 if (!rc)
1159 rc = crypto_write_file (client->crypto);
1160 if (!rc)
1162 if (!cached) // no error
1163 cdata = cache_get_data (client->filename);
1166 if (!rc)
1168 rc = cache_encrypt (client->crypto);
1169 if (rc)
1171 cache_clear (NULL, client->filename, 1);
1172 strv_free (client->crypto->pubkey);
1173 client->crypto->pubkey = strv_dup (client->crypto->save.pubkey);
1174 strv_free (client->crypto->sigkey);
1175 client->crypto->sigkey = strv_dup (client->crypto->save.sigkey);
1176 client->flags &= ~(FLAG_NEW);
1180 if (!rc)
1182 int timeout = config_get_integer (client->filename,
1183 "cache_timeout");
1185 cache_free_data_once (cdata);
1186 cdata = xcalloc (1, sizeof (struct cache_data_s));
1187 cdata->doc = client->crypto->plaintext;
1188 client->crypto->plaintext = NULL;
1189 cdata->size = client->crypto->plaintext_size;
1190 client->crypto->plaintext_size = 0;
1191 cdata->pubkey = client->crypto->save.pubkey;
1192 client->crypto->save.pubkey = NULL;
1193 cdata->sigkey = client->crypto->save.sigkey;
1194 client->crypto->save.sigkey = NULL;
1196 /* Update in case the cache entry expires the next SAVE may not
1197 * have any known keys. */
1198 strv_free (client->crypto->pubkey);
1199 client->crypto->pubkey = strv_dup (cdata->pubkey);
1200 strv_free (client->crypto->sigkey);
1201 client->crypto->sigkey = strv_dup (cdata->sigkey);
1203 if (!cached) // no error and wont increment refcount
1204 rc = cache_set_data (client->filename, cdata);
1205 else
1206 rc = cache_add_file (client->filename, cdata, timeout);
1208 if (!rc && (cached || (client->flags & FLAG_NEW)))
1209 send_status_all (STATUS_CACHE, NULL);
1211 if (!rc)
1213 rc = update_checksum (client);
1214 client->flags &= ~(FLAG_NEW);
1220 crypto_free_non_keys (client->crypto);
1221 return send_error (ctx, rc);
1224 static gpg_error_t
1225 do_delete (assuan_context_t ctx, char *line)
1227 struct client_s *client = assuan_get_pointer (ctx);
1228 struct xml_request_s *req;
1229 xmlNodePtr n;
1230 gpg_error_t rc;
1232 rc = xml_new_request (client, line, XML_CMD_DELETE, &req);
1233 if (rc)
1234 return rc;
1236 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1237 xml_free_request (req);
1238 if (rc)
1239 return rc;
1241 rc = xml_is_element_owner (client, n);
1242 if (!rc)
1243 rc = xml_unlink_node (client, n);
1245 return rc;
1248 static gpg_error_t
1249 delete_command (assuan_context_t ctx, char *line)
1251 struct client_s *client = assuan_get_pointer (ctx);
1252 gpg_error_t rc;
1253 struct argv_s *args[] = {
1254 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1255 NULL
1258 rc = parse_options (&line, args, client, 1);
1259 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1260 rc = GPG_ERR_SYNTAX;
1261 if (rc)
1262 return send_error (ctx, rc);
1264 if (client->opts & OPT_INQUIRE)
1266 unsigned char *result;
1267 size_t len;
1269 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1270 if (rc)
1271 return send_error (ctx, rc);
1273 pthread_cleanup_push ((void *)xfree, result);
1274 rc = do_delete (ctx, (char *)result);
1275 pthread_cleanup_pop (1);
1277 else
1278 rc = do_delete (ctx, line);
1280 return send_error (ctx, rc);
1283 static gpg_error_t
1284 update_element_expirey (struct client_s *client, xmlNodePtr n)
1286 gpg_error_t rc = 0;
1287 xmlChar *expire, *incr;
1288 char *p;
1289 time_t e, e_orig, i;
1290 time_t now = time (NULL);
1292 expire = xml_attribute_value (n, (xmlChar *)"expire");
1293 if (!expire)
1294 return 0;
1296 errno = 0;
1297 e = strtoul ((char *)expire, &p, 10);
1298 if (errno || *p || e == ULONG_MAX || *expire == '-')
1300 xmlFree (expire);
1301 rc = GPG_ERR_ERANGE;
1302 goto fail;
1305 xmlFree (expire);
1306 incr = xml_attribute_value (n, (xmlChar *)"expire_increment");
1307 if (!incr)
1308 return 0;
1310 i = strtoul ((char *)incr, &p, 10);
1311 if (errno || *p || i == ULONG_MAX || *incr == '-')
1313 xmlFree (incr);
1314 rc = GPG_ERR_ERANGE;
1315 goto fail;
1318 xmlFree (incr);
1319 e_orig = e;
1320 e = now + i;
1321 p = str_asprintf ("%lu", e);
1322 if (!p)
1324 rc = GPG_ERR_ENOMEM;
1325 goto fail;
1328 rc = xml_add_attribute (client, n, "expire", p);
1329 xfree (p);
1330 if (!rc)
1331 rc = send_status (client->ctx, STATUS_EXPIRE, "%lu %lu", e_orig, e);
1333 fail:
1334 return rc;
1337 static gpg_error_t
1338 store_command (assuan_context_t ctx, char *line)
1340 struct client_s *client = assuan_get_pointer (ctx);
1341 gpg_error_t rc;
1342 size_t len;
1343 unsigned char *result;
1344 xmlNodePtr n, parent;
1345 int has_content;
1346 char *content = NULL;
1347 struct xml_request_s *req;
1349 if (line && *line)
1350 return send_error (ctx, GPG_ERR_SYNTAX);
1352 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1353 if (rc)
1354 return send_error (ctx, rc);
1356 rc = xml_new_request (client, (char *)result, XML_CMD_STORE, &req);
1357 xfree (result);
1358 if (rc)
1359 return send_error (ctx, rc);
1361 /* Prevent passing the element content around to save some memory. */
1362 len = strv_length (req->args);
1363 has_content = line[strlen (line) - 1] != '\t' && len > 1;
1364 if (*(req->args+1) && !xml_valid_element_path (req->args, has_content))
1366 xml_free_request (req);
1367 return send_error (ctx, GPG_ERR_INV_VALUE);
1370 if (has_content || !*req->args[len-1])
1372 has_content = 1;
1373 content = req->args[len-1];
1374 req->args[len-1] = NULL;
1377 if (strv_length (req->args) > 1)
1379 rc = xml_check_recursion (client, req);
1380 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
1381 goto fail;
1384 parent = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1386 if (!rc && len > 1)
1388 rc = xml_is_element_owner (client, parent);
1389 if (!rc)
1391 n = xml_find_text_node (parent->children);
1392 if (n)
1393 xmlNodeSetContent (n, (xmlChar *) content);
1394 else
1395 xmlNodeAddContent (parent, (xmlChar *) content);
1397 (void)xml_update_element_mtime (client, parent);
1398 (void)update_element_expirey (client, parent);
1402 fail:
1403 xfree (content);
1404 xml_free_request (req);
1405 return send_error (ctx, rc);
1408 static gpg_error_t
1409 xfer_data (assuan_context_t ctx, const char *line, int total)
1411 struct client_s *client = assuan_get_pointer (ctx);
1412 int to_send;
1413 int sent = 0;
1414 gpg_error_t rc = 0;
1415 int progress = config_get_integer ("global", "xfer_progress");
1416 int flush = 0;
1418 if (!(client->flags & FLAG_LOCK_CMD))
1419 rc = unlock_file_mutex (client, 0);
1420 if (rc && rc != GPG_ERR_NOT_LOCKED)
1421 return rc;
1423 progress =
1424 progress > 0 ? (progress / ASSUAN_LINELENGTH) * ASSUAN_LINELENGTH : 0;
1425 to_send = total < ASSUAN_LINELENGTH ? total : ASSUAN_LINELENGTH;
1426 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1428 if (rc)
1429 return rc;
1431 again:
1434 if (sent + to_send > total)
1435 to_send = total - sent;
1437 rc = assuan_send_data (ctx, flush ? NULL : (char *) line + sent,
1438 flush ? 0 : to_send);
1439 if (!rc)
1441 sent += flush ? 0 : to_send;
1443 if ((progress && !(sent % progress) && sent != total) ||
1444 (sent == total && flush))
1445 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1447 if (!flush && !rc && sent == total)
1449 flush = 1;
1450 goto again;
1454 while (!rc && sent < total);
1456 return rc;
1459 static gpg_error_t
1460 do_get (assuan_context_t ctx, char *line)
1462 struct client_s *client = assuan_get_pointer (ctx);
1463 gpg_error_t rc;
1464 struct xml_request_s *req;
1465 xmlNodePtr n;
1467 rc = xml_new_request (client, line, XML_CMD_NONE, &req);
1468 if (rc)
1469 return rc;
1471 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1472 if (!rc)
1474 if (n && n->children)
1476 xmlNodePtr tmp = n;
1478 n = xml_find_text_node (n->children);
1479 if (!n || !n->content || !*n->content)
1480 rc = GPG_ERR_NO_DATA;
1481 else
1483 rc = xfer_data (ctx, (char *) n->content, xmlStrlen (n->content));
1484 if (!rc)
1486 xmlChar *expire = xml_attribute_value (tmp,
1487 (xmlChar *)"expire");
1488 if (expire)
1490 time_t now = time (NULL);
1491 time_t e;
1492 char *p;
1494 errno = 0;
1495 e = strtoul ((char *)expire, &p, 10);
1496 if (errno || *p || e == ULONG_MAX || *expire == '-')
1497 log_write (_("invalid expire attribute value: %s"),
1498 expire);
1499 else if (now >= e)
1500 rc = send_status (ctx, STATUS_EXPIRE, "%lu 0", e);
1502 xmlFree (expire);
1507 else
1508 rc = GPG_ERR_NO_DATA;
1511 xml_free_request (req);
1512 return rc;
1515 static gpg_error_t
1516 get_command (assuan_context_t ctx, char *line)
1518 struct client_s *client = assuan_get_pointer (ctx);
1519 gpg_error_t rc;
1520 struct argv_s *args[] = {
1521 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1522 NULL
1525 rc = parse_options (&line, args, client, 1);
1526 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1527 rc = GPG_ERR_SYNTAX;
1528 if (rc)
1529 return send_error (ctx, rc);
1531 if (client->opts & OPT_INQUIRE)
1533 unsigned char *result;
1534 size_t len;
1536 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1537 if (rc)
1538 return send_error (ctx, rc);
1540 pthread_cleanup_push ((void *)xfree, result);
1541 rc = do_get (ctx, (char *)result);
1542 pthread_cleanup_pop (1);
1544 else
1545 rc = do_get (ctx, line);
1547 return send_error (ctx, rc);
1550 static void list_command_free1 (void *arg);
1551 static gpg_error_t
1552 realpath_command (assuan_context_t ctx, char *line)
1554 gpg_error_t rc;
1555 char **realpath = NULL;
1556 struct client_s *client = assuan_get_pointer (ctx);
1557 struct argv_s *args[] = {
1558 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1559 NULL
1562 rc = parse_options (&line, args, client, 1);
1563 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1564 rc = GPG_ERR_SYNTAX;
1565 if (rc)
1566 return send_error (ctx, rc);
1568 if (client->opts & OPT_INQUIRE)
1570 unsigned char *result;
1571 size_t len;
1573 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1574 if (rc)
1575 return send_error (ctx, rc);
1577 pthread_cleanup_push ((void *)xfree, result);
1578 (void)xml_resolve_path (client, client->doc, result, &realpath, &rc);
1579 pthread_cleanup_pop (1);
1581 else
1582 (void)xml_resolve_path (client, client->doc, (unsigned char *)line,
1583 &realpath, &rc);
1585 if (!rc)
1587 char *tmp = strv_join ((char *)"\t", realpath);
1589 strv_free (realpath);
1590 if (!tmp)
1591 return send_error (ctx, GPG_ERR_ENOMEM);
1593 pthread_cleanup_push ((void *)xfree, tmp);
1594 rc = xfer_data (ctx, tmp, strlen (tmp));
1595 pthread_cleanup_pop (1);
1598 return send_error (ctx, rc);
1601 static void
1602 list_command_free1 (void *arg)
1604 if (arg)
1605 string_free ((struct string_s *) arg, 1);
1608 static gpg_error_t
1609 parse_list_opt_recurse (void *data, void *value)
1611 struct client_s *client = data;
1613 (void)value;
1614 client->opts |= OPT_LIST_RECURSE;
1615 return 0;
1618 static gpg_error_t
1619 parse_opt_verbose (void *data, void *value)
1621 struct client_s *client = data;
1623 (void)value;
1624 client->opts |= OPT_VERBOSE;
1625 return 0;
1628 static gpg_error_t
1629 list_path_once (struct client_s *client, char *line,
1630 struct element_list_s *elements, struct string_s *result)
1632 gpg_error_t rc;
1634 rc = xml_create_path_list (client, client->doc, NULL, elements, line, 0);
1635 if (rc == GPG_ERR_ELOOP || rc == GPG_ERR_EACCES)
1636 rc = 0;
1638 if (!rc)
1640 int total = slist_length (elements->list);
1642 if (total)
1644 int i;
1646 for (i = 0; i < total; i++)
1648 char *tmp = slist_nth_data (elements->list, i);
1650 string_append_printf (result, "%s%s", tmp,
1651 i + 1 == total ? "" : "\n");
1654 else
1655 rc = GPG_ERR_NO_DATA;
1658 return rc;
1661 static gpg_error_t
1662 do_list (assuan_context_t ctx, char *line)
1664 struct client_s *client = assuan_get_pointer (ctx);
1665 gpg_error_t rc = GPG_ERR_NO_DATA;
1666 struct element_list_s *elements = NULL;
1668 if (!line || !*line)
1670 struct string_s *str = string_new (NULL);
1671 xmlNodePtr n;
1673 if (!str)
1674 return GPG_ERR_ENOMEM;
1676 pthread_cleanup_push ((void *)list_command_free1, str);
1677 n = xmlDocGetRootElement (client->doc);
1678 for (n = n->children; n; n = n->next)
1680 xmlChar *name;
1682 if (n->type != XML_ELEMENT_NODE)
1683 continue;
1685 name = xmlGetProp (n, (xmlChar *)"_name");
1686 if (!name)
1688 rc = GPG_ERR_ENOMEM;
1689 break;
1692 elements = xcalloc (1, sizeof (struct element_list_s));
1693 if (!elements)
1695 xmlFree (name);
1696 rc = GPG_ERR_ENOMEM;
1697 break;
1700 elements->prefix = string_new (NULL);
1701 if (!elements->prefix)
1703 xmlFree (name);
1704 xml_free_element_list (elements);
1705 rc = GPG_ERR_ENOMEM;
1706 break;
1709 elements->recurse = client->opts & OPT_LIST_RECURSE;
1710 elements->root_only = !elements->recurse;
1711 pthread_cleanup_push ((void *)xml_free_element_list, elements);
1712 rc = list_path_once (client, (char *)name, elements, str);
1713 xmlFree (name);
1714 pthread_cleanup_pop (1);
1715 if (rc)
1716 break;
1718 if (n->next)
1719 string_append (str, "\n");
1722 if (!rc)
1723 rc = xfer_data (ctx, str->str, str->len);
1725 pthread_cleanup_pop (1);
1726 return rc;
1729 elements = xcalloc (1, sizeof (struct element_list_s));
1730 if (!elements)
1731 return GPG_ERR_ENOMEM;
1733 elements->prefix = string_new (NULL);
1734 if (!elements->prefix)
1736 xml_free_element_list (elements);
1737 return GPG_ERR_ENOMEM;
1740 elements->recurse = client->opts & OPT_LIST_RECURSE;
1741 pthread_cleanup_push ((void *)xml_free_element_list, elements);
1742 struct string_s *str = string_new (NULL);
1743 pthread_cleanup_push ((void *)list_command_free1, str);
1744 rc = list_path_once (client, line, elements, str);
1745 if (!rc)
1746 rc = xfer_data (ctx, str->str, str->len);
1748 pthread_cleanup_pop (1);
1749 pthread_cleanup_pop (1);
1750 return rc;
1753 static gpg_error_t
1754 list_command (assuan_context_t ctx, char *line)
1756 struct client_s *client = assuan_get_pointer (ctx);
1757 gpg_error_t rc;
1758 struct argv_s *args[] = {
1759 &(struct argv_s) {"recurse", OPTION_TYPE_NOARG, parse_list_opt_recurse},
1760 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1761 /* These are deprecated but kept for backward compatibility with older
1762 * clients. */
1763 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, NULL},
1764 &(struct argv_s) {"with-target", OPTION_TYPE_NOARG, NULL},
1765 &(struct argv_s) {"all", OPTION_TYPE_NOARG, parse_list_opt_recurse},
1766 &(struct argv_s) {"no-recurse", OPTION_TYPE_NOARG, NULL},
1767 NULL
1770 if (disable_list_and_dump == 1)
1771 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
1773 rc = parse_options (&line, args, client, 1);
1774 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1775 rc = GPG_ERR_SYNTAX;
1776 if (rc)
1777 return send_error (ctx, rc);
1779 if (client->opts & OPT_INQUIRE)
1781 unsigned char *result;
1782 size_t len;
1784 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1785 if (rc)
1786 return send_error (ctx, rc);
1788 pthread_cleanup_push ((void *)xfree, result);
1789 rc = do_list (ctx, (char *)result);
1790 pthread_cleanup_pop (1);
1792 else
1793 rc = do_list (ctx, line);
1795 return send_error (ctx, rc);
1798 #define RESUMABLE_ERROR(rc) (rc == GPG_ERR_ELOOP || rc == GPG_ERR_EACCES \
1799 || rc == GPG_ERR_ELEMENT_NOT_FOUND || !rc)
1801 * args[0] - element path
1803 static gpg_error_t
1804 attribute_list (assuan_context_t ctx, char **args)
1806 struct client_s *client = assuan_get_pointer (ctx);
1807 char **attrlist = NULL;
1808 int i = 0;
1809 int target = 0;
1810 xmlAttrPtr a;
1811 xmlNodePtr n, an, r;
1812 char *line;
1813 gpg_error_t rc;
1814 struct xml_request_s *req;
1816 if (!args || !args[0] || !*args[0])
1817 return GPG_ERR_SYNTAX;
1819 rc = xml_new_request (client, args[0], XML_CMD_ATTR_LIST, &req);
1820 if (rc)
1821 return rc;
1823 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1824 xml_free_request (req);
1825 if (rc)
1826 return rc;
1828 again:
1829 for (a = n->properties; a; a = a->next)
1831 char **pa;
1833 if (target && xml_reserved_attribute ((char *)a->name))
1834 continue;
1836 pa = xrealloc (attrlist, (i + 2) * sizeof (char *));
1837 if (!pa)
1839 if (attrlist)
1840 strv_free (attrlist);
1842 log_write ("%s(%i): %s", __FILE__, __LINE__,
1843 pwmd_strerror (GPG_ERR_ENOMEM));
1844 return GPG_ERR_ENOMEM;
1847 attrlist = pa;
1848 an = a->children;
1849 attrlist[i] = str_asprintf ("%s %s", (char *) a->name, an && an->content
1850 ? (char *)an->content : "");
1852 if (!attrlist[i])
1854 strv_free (attrlist);
1855 log_write ("%s(%i): %s", __FILE__, __LINE__,
1856 pwmd_strerror (GPG_ERR_ENOMEM));
1857 return GPG_ERR_ENOMEM;
1860 attrlist[++i] = NULL;
1863 if (!attrlist)
1864 return GPG_ERR_NO_DATA;
1866 if (!target)
1868 r = xml_resolve_path (client, client->doc, (xmlChar *)args[0], NULL, &rc);
1869 if (!RESUMABLE_ERROR (rc))
1871 strv_free (attrlist);
1872 return rc;
1874 else if (!rc && r != n)
1876 target = 1;
1877 n = r;
1878 goto again;
1881 rc = 0;
1884 line = strv_join ("\n", attrlist);
1885 if (!line)
1887 log_write ("%s(%i): %s", __FILE__, __LINE__,
1888 pwmd_strerror (GPG_ERR_ENOMEM));
1889 strv_free (attrlist);
1890 return GPG_ERR_ENOMEM;
1893 pthread_cleanup_push ((void *)xfree, line);
1894 pthread_cleanup_push ((void *)req_free, attrlist);
1895 rc = xfer_data (ctx, line, strlen (line));
1896 pthread_cleanup_pop (1);
1897 pthread_cleanup_pop (1);
1898 return rc;
1902 * args[0] - attribute
1903 * args[1] - element path
1905 static gpg_error_t
1906 attribute_delete (struct client_s *client, char **args)
1908 gpg_error_t rc;
1909 xmlNodePtr n;
1911 if (!args || !args[0] || !*args[0] || !args[1] || !*args[1])
1912 return GPG_ERR_SYNTAX;
1914 if (!strcmp (args[0], "_name") || !strcmp (args[0], "target"))
1915 return GPG_ERR_INV_ATTR;
1917 if (!xml_reserved_attribute (args[0]))
1918 n = xml_resolve_path (client, client->doc, (xmlChar *)args[1], NULL, &rc);
1919 else
1921 struct xml_request_s *req;
1923 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
1924 if (rc)
1925 return rc;
1927 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1928 xml_free_request (req);
1931 if (!rc)
1932 rc = xml_is_element_owner (client, n);
1934 if (!rc)
1935 rc = xml_delete_attribute (client, n, (xmlChar *) args[0]);
1937 return rc;
1941 * Creates the "target" attribute. When other commands encounter an element
1942 * with this attribute they follow the "target" after appending remaining
1943 * elements from the original element path to the target. The exception is the
1944 * ATTR command that operates on the element itself (for reserved attribute
1945 * names) and not the target.
1947 * If the source element path doesn't exist when using 'ATTR SET target', it is
1948 * created, but the destination element path must exist. This is simliar to the
1949 * ls(1) command: ln -s src dst.
1951 * args[0] - source element path
1952 * args[1] - destination element path
1954 static gpg_error_t
1955 set_target_attribute (struct client_s *client, char **args)
1957 struct xml_request_s *req = NULL;
1958 char **src, **dst;
1959 gpg_error_t rc;
1960 xmlNodePtr n;
1962 if (!args || !args[0] || !args[1])
1963 return GPG_ERR_SYNTAX;
1965 src = str_split (args[0], "\t", 0);
1966 if (!src)
1967 return GPG_ERR_SYNTAX;
1969 if (!xml_valid_element_path (src, 0))
1971 strv_free (src);
1972 return GPG_ERR_INV_VALUE;
1975 dst = str_split (args[1], "\t", 0);
1976 if (!dst)
1978 strv_free (src);
1979 return GPG_ERR_SYNTAX;
1982 // Be sure the destination element path exists. */
1983 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
1984 if (rc)
1985 goto fail;
1987 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1988 if (rc && rc != GPG_ERR_EACCES)
1989 goto fail;
1991 xml_free_request (req);
1992 req = NULL;
1994 if (!strcmp (args[0], args[1]))
1996 rc = GPG_ERR_EEXIST;
1997 goto fail;
2000 rc = xml_new_request (client, args[0], XML_CMD_ATTR_TARGET, &req);
2001 if (rc)
2002 goto fail;
2004 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2005 if (rc && rc != GPG_ERR_EACCES)
2006 goto fail;
2008 if (!rc)
2010 rc = xml_add_attribute (client, n, "target", args[1]);
2011 if (!rc)
2012 rc = xml_unlink_node (client, n->children);
2015 fail:
2016 strv_free (src);
2017 strv_free (dst);
2018 xml_free_request (req);
2019 return rc;
2023 * args[0] - attribute
2024 * args[1] - element path
2026 static gpg_error_t
2027 attribute_get (assuan_context_t ctx, char **args)
2029 struct client_s *client = assuan_get_pointer (ctx);
2030 xmlNodePtr n;
2031 xmlChar *a;
2032 gpg_error_t rc;
2033 struct xml_request_s *req;
2035 if (!args || !args[0] || !*args[0] || !args[1] || !*args[1])
2036 return GPG_ERR_SYNTAX;
2038 if (!xml_reserved_attribute (args[0]))
2039 n = xml_resolve_path (client, client->doc, (xmlChar *)args[1], NULL, &rc);
2040 else
2042 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
2043 if (rc)
2044 return rc;
2046 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2047 xml_free_request (req);
2050 if (rc)
2051 return rc;
2053 a = xmlGetProp (n, (xmlChar *) args[0]);
2054 if (!a)
2055 return GPG_ERR_NOT_FOUND;
2057 pthread_cleanup_push ((void *)xmlFree, a);
2059 if (*a)
2060 rc = xfer_data (ctx, (char *) a, xmlStrlen (a));
2061 else
2062 rc = GPG_ERR_NO_DATA;
2064 pthread_cleanup_pop (1);
2065 return rc;
2069 * args[0] - attribute
2070 * args[1] - element path
2071 * args[2] - value
2073 static gpg_error_t
2074 attribute_set (struct client_s *client, char **args)
2076 struct xml_request_s *req;
2077 gpg_error_t rc;
2078 xmlNodePtr n;
2080 if (!args || !args[0] || !args[1])
2081 return GPG_ERR_SYNTAX;
2084 * Reserved attribute names.
2086 if (!strcmp (args[0], "_name")) // Use the RENAME command instead
2087 return GPG_ERR_INV_ATTR;
2088 else if (!strcmp (args[0], "target"))
2089 return set_target_attribute (client, args + 1);
2090 else if (!xml_valid_attribute (args[0]))
2091 return GPG_ERR_INV_VALUE;
2093 if (!xml_valid_attribute_value (args[2]))
2094 return GPG_ERR_INV_VALUE;
2096 if (!xml_reserved_attribute (args[0]))
2098 n = xml_resolve_path (client, client->doc, (xmlChar *)args[1], NULL, &rc);
2099 if (!rc)
2101 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
2102 if (!rc)
2104 rc = xml_check_recursion (client, req);
2105 xml_free_request (req);
2109 else
2111 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
2112 if (rc)
2113 return rc;
2115 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2116 xml_free_request (req);
2119 if (!rc)
2120 rc = xml_is_element_owner (client, n);
2122 if (!rc)
2123 rc = xml_add_attribute (client, n, args[0], args[2]);
2125 return rc;
2129 * req[0] - command
2130 * req[1] - attribute name or element path if command is LIST
2131 * req[2] - element path
2132 * req[2] - element path or value
2135 static gpg_error_t
2136 do_attr (assuan_context_t ctx, char *line)
2138 struct client_s *client = assuan_get_pointer (ctx);
2139 gpg_error_t rc = 0;
2140 char **req;
2142 req = str_split (line, " ", 4);
2143 if (!req || !req[0] || !req[1])
2145 strv_free (req);
2146 return GPG_ERR_SYNTAX;
2149 pthread_cleanup_push ((void *)req_free, req);
2151 if (strcasecmp (req[0], "SET") == 0)
2152 rc = attribute_set (client, req + 1);
2153 else if (strcasecmp (req[0], "GET") == 0)
2154 rc = attribute_get (ctx, req + 1);
2155 else if (strcasecmp (req[0], "DELETE") == 0)
2156 rc = attribute_delete (client, req + 1);
2157 else if (strcasecmp (req[0], "LIST") == 0)
2158 rc = attribute_list (ctx, req + 1);
2159 else
2160 rc = GPG_ERR_SYNTAX;
2162 client->flags &= ~(FLAG_ACL_IGNORE|FLAG_ACL_ERROR);
2163 pthread_cleanup_pop (1);
2164 return rc;
2167 static gpg_error_t
2168 attr_command (assuan_context_t ctx, char *line)
2170 struct client_s *client = assuan_get_pointer (ctx);
2171 gpg_error_t rc;
2172 struct argv_s *args[] = {
2173 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2174 NULL
2177 rc = parse_options (&line, args, client, 1);
2178 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2179 rc = GPG_ERR_SYNTAX;
2180 if (rc)
2181 return send_error (ctx, rc);
2183 if (client->opts & OPT_INQUIRE)
2185 unsigned char *result;
2186 size_t len;
2188 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2189 if (rc)
2190 return send_error (ctx, rc);
2192 pthread_cleanup_push ((void *)xfree, result);
2193 rc = do_attr (ctx, (char *)result);
2194 pthread_cleanup_pop (1);
2196 else
2197 rc = do_attr (ctx, line);
2199 return send_error (ctx, rc);
2202 static gpg_error_t
2203 parse_iscached_opt_lock (void *data, void *value)
2205 struct client_s *client = data;
2207 (void) value;
2208 client->opts |= OPT_LOCK;
2209 return 0;
2212 static gpg_error_t
2213 parse_iscached_opt_agent (void *data, void *value)
2215 struct client_s *client = data;
2217 (void) value;
2218 client->opts |= OPT_CACHE_AGENT;
2219 return 0;
2222 static gpg_error_t
2223 parse_iscached_opt_sign (void *data, void *value)
2225 struct client_s *client = data;
2227 (void) value;
2228 client->opts |= OPT_CACHE_SIGN;
2229 return 0;
2232 static gpg_error_t
2233 iscached_command (assuan_context_t ctx, char *line)
2235 struct client_s *client = assuan_get_pointer (ctx);
2236 gpg_error_t rc;
2237 int defer = 0;
2238 struct argv_s *args[] = {
2239 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_iscached_opt_lock},
2240 &(struct argv_s) {"agent", OPTION_TYPE_NOARG, parse_iscached_opt_agent},
2241 &(struct argv_s) {"sign", OPTION_TYPE_NOARG, parse_iscached_opt_sign},
2242 NULL
2245 if (!line || !*line)
2246 return send_error (ctx, GPG_ERR_SYNTAX);
2248 rc = parse_options (&line, args, client, 1);
2249 if (rc)
2250 return send_error (ctx, rc);
2251 else if (!valid_filename (line))
2252 return send_error (ctx, GPG_ERR_INV_VALUE);
2254 if (!(client->flags & FLAG_OPEN)
2255 && ((client->opts & OPT_CACHE_AGENT) || (client->opts & OPT_CACHE_SIGN)))
2256 return send_error (ctx, GPG_ERR_INV_STATE);
2258 rc = cache_iscached (line, &defer, (client->opts & OPT_CACHE_AGENT),
2259 (client->opts & OPT_CACHE_SIGN));
2260 if (!rc && defer)
2261 rc = GPG_ERR_NO_DATA;
2263 if (!rc)
2265 struct cache_data_s *cdata = cache_get_data (line);
2267 if (cdata)
2269 rc = validate_checksum (client, line, cdata, NULL, NULL);
2270 if (rc == GPG_ERR_CHECKSUM)
2271 rc = GPG_ERR_NO_DATA;
2275 if (client->opts & OPT_LOCK
2276 && (!rc || gpg_err_code (rc) == GPG_ERR_NO_DATA))
2278 gpg_error_t trc = rc;
2280 if (strcmp (line, client->filename))
2281 reset_client (client);
2283 xfree (client->filename);
2284 client->filename = str_dup (line);
2285 rc = do_lock (client, 1);
2286 if (!rc)
2287 rc = trc;
2290 return send_error (ctx, rc);
2293 static gpg_error_t
2294 clearcache_command (assuan_context_t ctx, char *line)
2296 struct client_s *client = assuan_get_pointer (ctx);
2297 gpg_error_t rc = 0, all_rc = 0;
2298 int i;
2299 int t;
2300 int all = 0;
2301 struct client_thread_s *once = NULL;
2302 unsigned count;
2304 cache_lock ();
2305 pthread_cleanup_push (cache_release_mutex, NULL);
2306 count = cache_file_count ();
2307 MUTEX_LOCK (&cn_mutex);
2308 pthread_cleanup_push ((void *)release_mutex_cb, &cn_mutex);
2310 if (!line || !*line)
2311 all = 1;
2313 t = slist_length (cn_thread_list);
2315 for (i = 0; i < t; i++)
2317 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2318 assuan_peercred_t peer;
2320 if (!thd->cl)
2321 continue;
2323 /* Lock each connected clients' file mutex to prevent any other client
2324 * from accessing the cache entry (the file mutex is locked upon
2325 * command startup). The cache for the entry is not cleared if the
2326 * file mutex is locked by another client to prevent this function
2327 * from blocking. Rather, it returns an error.
2329 if (all)
2331 if (thd->cl->filename)
2333 rc = do_validate_peer (ctx, thd->cl->filename, &peer);
2334 /* The current client doesn't have permission to open the other
2335 * filename do to "access" configuration parameter in a filename
2336 * section. Since we are clearning all cache entries the error
2337 * will be returned later during cache_clear(). */
2338 if (rc)
2340 rc = 0;
2341 continue;
2344 else // Idle client without opened file?
2345 continue;
2347 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->filename, -1, 0, -1);
2348 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2350 /* The current client owns the lock. */
2351 if (pthread_equal (pthread_self (), thd->tid))
2352 rc = 0;
2353 else
2355 if (cache_iscached (thd->cl->filename, NULL, 0, 0)
2356 == GPG_ERR_NO_DATA)
2358 rc = 0;
2359 continue;
2362 /* The cache entry will be cleared when the other client
2363 * disconnects and cache_timer_thread() does its thing. */
2364 cache_defer_clear (thd->cl->filename);
2367 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
2369 rc = 0;
2370 continue;
2373 if (!rc)
2375 rc = cache_clear (NULL, thd->cl->filename, 1);
2376 cache_unlock_mutex (thd->cl->filename, 0);
2379 if (rc)
2380 all_rc = rc;
2382 rc = 0;
2384 else
2386 /* A single data filename was specified. Lock only this data file
2387 * mutex and free the cache entry. */
2388 rc = do_validate_peer (ctx, line, &peer);
2389 if (rc == GPG_ERR_FORBIDDEN)
2390 rc = peer_is_invoker (client);
2392 if (rc == GPG_ERR_EACCES)
2393 rc = GPG_ERR_FORBIDDEN;
2395 if (!rc && thd->cl->filename && !strcmp (thd->cl->filename , line))
2397 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->filename, -1, 0, -1);
2398 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2400 /* The current client owns the lock. */
2401 if (pthread_equal (pthread_self (), thd->tid))
2402 rc = 0;
2405 if (!rc)
2407 once = thd;
2408 rc = cache_clear (NULL, thd->cl->filename, 1);
2409 cache_unlock_mutex (thd->cl->filename, 0);
2411 else
2412 cache_defer_clear (thd->cl->filename);
2414 /* Found a client with the opened file. The cache entry has been
2415 * either cleared (self) or defered to be cleared. */
2416 break;
2421 /* Only connected clients' cache entries have been cleared. Now clear any
2422 * remaining cache entries without clients but only if there wasn't an
2423 * error from above since this would defeat the locking check of the
2424 * remaining entries. */
2425 if (all && !all_rc && cache_file_count ())
2427 rc = cache_clear (client, NULL, 1);
2428 if (rc == GPG_ERR_EACCES)
2429 rc = GPG_ERR_FORBIDDEN;
2432 /* No clients are using the specified file. */
2433 else if (!all_rc && !rc && !once)
2434 rc = cache_clear (NULL, line, 1);
2436 /* Release the connection mutex. */
2437 pthread_cleanup_pop (1);
2439 if (!rc || (cache_file_count () && count != cache_file_count ()))
2440 send_status_all (STATUS_CACHE, NULL);
2442 /* Release the cache mutex. */
2443 pthread_cleanup_pop (1);
2445 /* One or more files were locked while clearing all cache entries. */
2446 if (all_rc)
2447 rc = all_rc;
2449 return send_error (ctx, rc);
2452 static gpg_error_t
2453 cachetimeout_command (assuan_context_t ctx, char *line)
2455 struct client_s *client = assuan_get_pointer (ctx);
2456 int timeout;
2457 char **req = str_split (line, " ", 0);
2458 char *p;
2459 gpg_error_t rc = 0;
2460 assuan_peercred_t peer;
2462 if (!req || !*req || !req[1])
2464 strv_free (req);
2465 return send_error (ctx, GPG_ERR_SYNTAX);
2468 errno = 0;
2469 timeout = (int) strtol (req[1], &p, 10);
2470 if (errno != 0 || *p || timeout < -1)
2472 strv_free (req);
2473 return send_error (ctx, GPG_ERR_SYNTAX);
2476 rc = do_validate_peer (ctx, req[0], &peer);
2477 if (rc == GPG_ERR_FORBIDDEN)
2479 rc = peer_is_invoker (client);
2480 if (rc == GPG_ERR_EACCES)
2481 rc = GPG_ERR_FORBIDDEN;
2484 if (!rc)
2486 rc = cache_set_timeout (req[0], timeout);
2487 if (!rc || gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
2489 rc = 0;
2490 MUTEX_LOCK (&rcfile_mutex);
2491 config_set_int_param (&global_config, req[0], "cache_timeout",
2492 req[1]);
2493 MUTEX_UNLOCK (&rcfile_mutex);
2497 strv_free (req);
2498 return send_error (ctx, rc);
2501 static gpg_error_t
2502 dump_command (assuan_context_t ctx, char *line)
2504 xmlChar *xml;
2505 int len;
2506 struct client_s *client = assuan_get_pointer (ctx);
2507 gpg_error_t rc;
2509 if (disable_list_and_dump == 1)
2510 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2512 if (line && *line)
2513 return send_error (ctx, GPG_ERR_SYNTAX);
2515 rc = peer_is_invoker(client);
2516 if (rc)
2517 return send_error (ctx, rc);
2519 xmlDocDumpFormatMemory (client->doc, &xml, &len, 1);
2521 if (!xml)
2523 log_write ("%s(%i): %s", __FILE__, __LINE__,
2524 pwmd_strerror (GPG_ERR_ENOMEM));
2525 return send_error (ctx, GPG_ERR_ENOMEM);
2528 pthread_cleanup_push ((void *)xmlFree, xml);
2529 rc = xfer_data (ctx, (char *) xml, len);
2530 pthread_cleanup_pop (1);
2531 return send_error (ctx, rc);
2534 static gpg_error_t
2535 getconfig_command (assuan_context_t ctx, char *line)
2537 struct client_s *client = assuan_get_pointer (ctx);
2538 gpg_error_t rc = 0;
2539 char filename[255] = { 0 }, param[747] = { 0 };
2540 char *p, *tmp = NULL, *fp = client->filename, *paramp = line;
2542 if (!line || !*line)
2543 return send_error (ctx, GPG_ERR_SYNTAX);
2545 if (strchr (line, ' '))
2547 int ret = sscanf (line, " %254[^ ] %746c", filename, param);
2549 if (ret <= 0)
2550 return send_error (ctx, gpg_error_from_syserror());
2551 paramp = param;
2552 fp = filename;
2555 if (fp && !valid_filename (fp))
2556 return send_error (ctx, GPG_ERR_INV_VALUE);
2558 paramp = str_down (paramp);
2559 p = config_get_value (fp ? fp : "global", paramp);
2560 if (!p)
2561 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2563 tmp = expand_homedir (p);
2564 xfree (p);
2565 if (!tmp)
2567 log_write ("%s(%i): %s", __FILE__, __LINE__,
2568 pwmd_strerror (GPG_ERR_ENOMEM));
2569 return send_error (ctx, GPG_ERR_ENOMEM);
2572 p = tmp;
2573 pthread_cleanup_push ((void *)xfree, p);
2574 rc = xfer_data (ctx, p, strlen (p));
2575 pthread_cleanup_pop (1);
2576 return send_error (ctx, rc);
2579 struct xpath_s
2581 xmlXPathContextPtr xp;
2582 xmlXPathObjectPtr result;
2583 xmlBufferPtr buf;
2584 char **req;
2587 static void
2588 xpath_command_free (void *arg)
2590 struct xpath_s *xpath = arg;
2592 if (!xpath)
2593 return;
2595 req_free (xpath->req);
2597 if (xpath->buf)
2598 xmlBufferFree (xpath->buf);
2600 if (xpath->result)
2601 xmlXPathFreeObject (xpath->result);
2603 if (xpath->xp)
2604 xmlXPathFreeContext (xpath->xp);
2607 static gpg_error_t
2608 do_xpath (assuan_context_t ctx, char *line)
2610 gpg_error_t rc;
2611 struct client_s *client = assuan_get_pointer (ctx);
2612 struct xpath_s _x = { 0 };
2613 struct xpath_s *xpath = &_x;
2615 if (!line || !*line)
2616 return GPG_ERR_SYNTAX;
2618 if ((xpath->req = str_split (line, "\t", 2)) == NULL)
2620 if (strv_printf (&xpath->req, "%s", line) == 0)
2621 return GPG_ERR_ENOMEM;
2624 xpath->xp = xmlXPathNewContext (client->doc);
2625 if (!xpath->xp)
2627 rc = GPG_ERR_BAD_DATA;
2628 goto fail;
2631 xpath->result =
2632 xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2633 if (!xpath->result)
2635 rc = GPG_ERR_BAD_DATA;
2636 goto fail;
2639 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2641 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2642 goto fail;
2645 rc = xml_recurse_xpath_nodeset (client, client->doc,
2646 xpath->result->nodesetval,
2647 (xmlChar *) xpath->req[1], &xpath->buf, 0,
2648 NULL);
2649 if (rc)
2650 goto fail;
2651 else if (!xpath->req[1] && !xmlBufferLength (xpath->buf))
2653 rc = GPG_ERR_NO_DATA;
2654 goto fail;
2656 else if (xpath->req[1])
2658 rc = 0;
2659 goto fail;
2662 pthread_cleanup_push ((void *)xpath_command_free, &xpath);
2663 rc = xfer_data (ctx, (char *) xmlBufferContent (xpath->buf),
2664 xmlBufferLength (xpath->buf));
2665 pthread_cleanup_pop (0);
2666 fail:
2667 xpath_command_free (xpath);
2668 return rc;
2671 static gpg_error_t
2672 xpath_command (assuan_context_t ctx, char *line)
2674 struct client_s *client = assuan_get_pointer (ctx);
2675 gpg_error_t rc;
2676 struct argv_s *args[] = {
2677 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2678 NULL
2681 if (disable_list_and_dump == 1)
2682 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2684 rc = peer_is_invoker(client);
2685 if (rc)
2686 return send_error (ctx, rc);
2688 rc = parse_options (&line, args, client, 1);
2689 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2690 rc = GPG_ERR_SYNTAX;
2691 if (rc)
2692 return send_error (ctx, rc);
2694 if (client->opts & OPT_INQUIRE)
2696 unsigned char *result;
2697 size_t len;
2699 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2700 if (rc)
2701 return send_error (ctx, rc);
2703 pthread_cleanup_push ((void *)xfree, result);
2704 rc = do_xpath (ctx, (char *)result);
2705 pthread_cleanup_pop (1);
2707 else
2708 rc = do_xpath (ctx, line);
2710 return send_error (ctx, rc);
2713 static gpg_error_t
2714 do_xpathattr (assuan_context_t ctx, char *line)
2716 struct client_s *client = assuan_get_pointer (ctx);
2717 gpg_error_t rc;
2718 char **req = NULL;
2719 int cmd = 0; //SET
2720 struct xpath_s _x = { 0 };
2721 struct xpath_s *xpath = &_x;
2723 if (!line || !*line)
2724 return GPG_ERR_SYNTAX;
2726 if ((req = str_split (line, " ", 3)) == NULL)
2727 return GPG_ERR_ENOMEM;
2729 if (!req[0])
2731 rc = GPG_ERR_SYNTAX;
2732 goto fail;
2735 if (!strcasecmp (req[0], "SET"))
2736 cmd = 0;
2737 else if (!strcasecmp (req[0], "DELETE"))
2738 cmd = 1;
2739 else
2741 rc = GPG_ERR_SYNTAX;
2742 goto fail;
2745 if (!req[1] || !req[2])
2747 rc = GPG_ERR_SYNTAX;
2748 goto fail;
2751 if ((xpath->req = str_split (req[2], "\t", 3)) == NULL)
2753 rc = GPG_ERR_ENOMEM;
2754 goto fail;
2757 if (!xpath->req[0] || (!xpath->req[1] && !cmd) || (xpath->req[1] && cmd))
2759 rc = GPG_ERR_SYNTAX;
2760 goto fail;
2763 xpath->xp = xmlXPathNewContext (client->doc);
2764 if (!xpath->xp)
2766 rc = GPG_ERR_BAD_DATA;
2767 goto fail;
2770 xpath->result = xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2771 if (!xpath->result)
2773 rc = GPG_ERR_BAD_DATA;
2774 goto fail;
2777 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2779 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2780 goto fail;
2783 rc = xml_recurse_xpath_nodeset (client, client->doc,
2784 xpath->result->nodesetval,
2785 (xmlChar *) xpath->req[1], &xpath->buf, cmd,
2786 (xmlChar *) req[1]);
2788 fail:
2789 xpath_command_free (xpath);
2790 strv_free (req);
2791 return rc;
2794 /* XPATHATTR SET|DELETE <name> <expression>[<TAB>[value]] */
2795 static gpg_error_t
2796 xpathattr_command (assuan_context_t ctx, char *line)
2798 struct client_s *client = assuan_get_pointer (ctx);
2799 gpg_error_t rc;
2800 struct argv_s *args[] = {
2801 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2802 NULL
2805 if (disable_list_and_dump == 1)
2806 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2808 rc = peer_is_invoker(client);
2809 if (rc)
2810 return send_error (ctx, rc);
2812 rc = parse_options (&line, args, client, 1);
2813 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2814 rc = GPG_ERR_SYNTAX;
2815 if (rc)
2816 return send_error (ctx, rc);
2818 if (client->opts & OPT_INQUIRE)
2820 unsigned char *result;
2821 size_t len;
2823 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2824 if (rc)
2825 return send_error (ctx, rc);
2827 pthread_cleanup_push ((void *)xfree, result);
2828 rc = do_xpathattr (ctx, (char *)result);
2829 pthread_cleanup_pop (1);
2831 else
2832 rc = do_xpathattr (ctx, line);
2834 return send_error (ctx, rc);
2837 static gpg_error_t
2838 do_import (struct client_s *client, const char *root_element,
2839 unsigned char *content)
2841 xmlDocPtr doc = NULL;
2842 xmlNodePtr n = NULL, root;
2843 gpg_error_t rc;
2844 struct string_s *str = NULL, *tstr = NULL;
2845 struct xml_request_s *req = NULL;
2847 if (!content || !*content)
2848 return GPG_ERR_SYNTAX;
2850 if (root_element)
2852 rc = xml_new_request (client, root_element, XML_CMD_STORE, &req);
2853 if (rc)
2855 xfree (content);
2856 return rc;
2859 if (!xml_valid_element_path (req->args, 0))
2861 xml_free_request (req);
2862 xfree (content);
2863 return GPG_ERR_INV_VALUE;
2867 str = string_new_content ((char *)content);
2868 tstr = string_prepend (str, "<pwmd>");
2869 if (tstr)
2871 str = tstr;
2872 tstr = string_append (str, "</pwmd>");
2873 if (!tstr)
2874 rc = GPG_ERR_ENOMEM;
2876 else
2877 rc = GPG_ERR_ENOMEM;
2879 if (rc)
2880 goto fail;
2882 doc = xmlReadDoc ((xmlChar *) str->str, NULL, "UTF-8", XML_PARSE_NOBLANKS);
2883 string_free (str, 1);
2884 if (!doc)
2886 rc = GPG_ERR_BAD_DATA;
2887 goto fail;
2890 root = xmlDocGetRootElement (doc);
2891 root = root->children;
2892 if (root->type != XML_ELEMENT_NODE)
2894 rc = GPG_ERR_BAD_DATA;
2895 goto fail;
2898 rc = xml_validate_import (client, root);
2899 if (rc)
2900 goto fail;
2902 if (req)
2904 /* Create the new specified root element path, if needed. */
2905 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc),
2906 &rc);
2907 if (rc)
2908 goto fail;
2910 /* Overwrite the children of the specified root element path. */
2911 (void)xml_unlink_node (client, n->children);
2912 n->children = NULL;
2914 else
2915 n = xmlDocGetRootElement (client->doc);
2917 if (n)
2919 xmlNodePtr copy;
2920 xmlChar *name = xml_attribute_value (root, (xmlChar *)"_name");
2922 if (!name)
2923 rc = GPG_ERR_BAD_DATA;
2924 else if (!req)
2926 /* No --root argument passed. Overwrite the current documents' root
2927 * element matching the root element of the imported data. */
2928 xml_free_request (req);
2929 req = NULL;
2930 rc = xml_new_request (client, (char *)name, XML_CMD_DELETE, &req);
2931 xmlFree (name);
2932 if (!rc)
2934 xmlNodePtr tmp;
2936 tmp = xml_find_elements (client, req,
2937 xmlDocGetRootElement (req->doc), &rc);
2938 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2939 goto fail;
2941 if (!rc)
2942 (void)xml_unlink_node (client, tmp);
2944 rc = 0;
2948 if (!rc)
2950 copy = xmlCopyNodeList (root);
2951 if (!copy)
2952 rc = GPG_ERR_ENOMEM;
2953 else
2955 n = xmlAddChildList (n, copy);
2956 if (!n)
2957 rc = GPG_ERR_ENOMEM;
2962 if (!rc && n && n->parent)
2963 rc = xml_update_element_mtime (client, n->parent);
2965 fail:
2966 xml_free_request (req);
2968 if (doc)
2969 xmlFreeDoc (doc);
2971 return rc;
2974 static gpg_error_t
2975 parse_import_opt_root (void *data, void *value)
2977 struct client_s *client = data;
2979 client->import_root = str_dup (value);
2980 return client->import_root ? 0 : GPG_ERR_ENOMEM;
2983 static gpg_error_t
2984 import_command (assuan_context_t ctx, char *line)
2986 gpg_error_t rc;
2987 struct client_s *client = assuan_get_pointer (ctx);
2988 unsigned char *result;
2989 size_t len;
2990 struct argv_s *args[] = {
2991 &(struct argv_s) {"root", OPTION_TYPE_ARG, parse_import_opt_root},
2992 NULL
2995 xfree (client->import_root);
2996 client->import_root = NULL;
2997 rc = parse_options (&line, args, client, 0);
2998 if (rc)
2999 return send_error (ctx, rc);
3001 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3002 if (rc)
3004 xfree (client->import_root);
3005 client->import_root = NULL;
3006 return send_error (ctx, rc);
3009 rc = do_import (client, client->import_root, result);
3010 xfree (client->import_root);
3011 client->import_root = NULL;
3012 return send_error (ctx, rc);
3015 static gpg_error_t
3016 do_lock (struct client_s *client, int add)
3018 gpg_error_t rc = lock_file_mutex (client, add);
3020 if (!rc)
3021 client->flags |= FLAG_LOCK_CMD;
3023 return rc;
3026 static gpg_error_t
3027 lock_command (assuan_context_t ctx, char *line)
3029 struct client_s *client = assuan_get_pointer (ctx);
3030 gpg_error_t rc;
3032 if (line && *line)
3033 return send_error (ctx, GPG_ERR_SYNTAX);
3035 rc = do_lock (client, 0);
3036 return send_error (ctx, rc);
3039 static gpg_error_t
3040 unlock_command (assuan_context_t ctx, char *line)
3042 struct client_s *client = assuan_get_pointer (ctx);
3043 gpg_error_t rc;
3045 if (line && *line)
3046 return send_error (ctx, GPG_ERR_SYNTAX);
3048 rc = unlock_file_mutex (client, 0);
3049 return send_error (ctx, rc);
3052 static void
3053 get_set_env (const char *name, const char *value)
3055 if (value && *value)
3056 setenv (name, value, 1);
3057 else
3058 unsetenv (name);
3061 static gpg_error_t
3062 option_command (assuan_context_t ctx, char *line)
3064 struct client_s *client = assuan_get_pointer (ctx);
3065 gpg_error_t rc = 0;
3066 char namebuf[255] = { 0 };
3067 char *name = namebuf;
3068 char *value = NULL, *p, *tmp = NULL;
3070 p = strchr (line, '=');
3071 if (!p)
3073 strncpy (namebuf, line, sizeof(namebuf));
3074 namebuf[sizeof(namebuf)-1] = 0;
3076 else
3078 strncpy (namebuf, line, strlen (line)-strlen (p));
3079 namebuf[sizeof(namebuf)-1] = 0;
3080 value = p+1;
3083 log_write2 ("OPTION name='%s' value='%s'", name, value);
3085 if (strcasecmp (name, (char *) "lock-timeout") == 0)
3087 long n = 0;
3089 if (value)
3091 n = strtol (value, &tmp, 10);
3092 if (tmp && *tmp)
3093 return send_error (ctx, GPG_ERR_INV_VALUE);
3096 client->lock_timeout = n;
3098 else if (strcasecmp (name, (char *) "client-state") == 0)
3100 long n = 0;
3102 if (value)
3104 n = strtol (value, &tmp, 10);
3105 if ((tmp && *tmp) || (n < 0 || n > 1))
3106 return send_error (ctx, GPG_ERR_INV_VALUE);
3107 client->client_state = n;
3109 else
3110 client->client_state = 0;
3112 else if (strcasecmp (name, (char *) "NAME") == 0)
3114 if (value && strchr (value, ' '))
3115 rc = GPG_ERR_INV_VALUE;
3116 else
3118 tmp = pthread_getspecific (thread_name_key);
3119 pthread_setspecific (thread_name_key, NULL);
3120 xfree (tmp);
3121 MUTEX_LOCK (&cn_mutex);
3123 if (value && *value)
3124 pthread_setspecific (thread_name_key, str_dup (value));
3126 MUTEX_UNLOCK (&cn_mutex);
3129 else if (strcasecmp (name, "disable-pinentry") == 0)
3131 int n = 1;
3133 if (value && *value)
3135 n = (int) strtol (value, &tmp, 10);
3136 if (*tmp || n < 0 || n > 1)
3137 return send_error (ctx, GPG_ERR_INV_VALUE);
3140 if (n)
3141 client->flags |= FLAG_NO_PINENTRY;
3142 else
3143 client->flags &= ~FLAG_NO_PINENTRY;
3145 else if (strcasecmp (name, "ttyname") == 0)
3147 get_set_env ("GPG_TTY", value);
3149 else if (strcasecmp (name, "ttytype") == 0)
3151 get_set_env ("TERM", value);
3153 else if (strcasecmp (name, "display") == 0)
3155 get_set_env ("DISPLAY", value);
3157 else if (strcasecmp (name, "lc_messages") == 0)
3160 else if (strcasecmp (name, "lc_ctype") == 0)
3163 else if (strcasecmp (name, "desc") == 0)
3166 else if (strcasecmp (name, "pinentry-timeout") == 0)
3169 else
3170 rc = GPG_ERR_UNKNOWN_OPTION;
3172 return send_error (ctx, rc);
3175 static gpg_error_t
3176 do_rename (assuan_context_t ctx, char *line)
3178 struct client_s *client = assuan_get_pointer (ctx);
3179 char **args, *p;
3180 xmlNodePtr src, dst;
3181 struct string_s *str = NULL, *tstr;
3182 struct xml_request_s *req;
3183 gpg_error_t rc;
3185 args = str_split (line, " ", 0);
3186 if (!args || strv_length (args) != 2)
3188 strv_free (args);
3189 return GPG_ERR_SYNTAX;
3192 if (!xml_valid_element ((xmlChar *) args[1]))
3194 strv_free (args);
3195 return GPG_ERR_INV_VALUE;
3198 rc = xml_new_request (client, args[0], XML_CMD_RENAME, &req);
3199 if (rc)
3201 strv_free (args);
3202 return rc;
3205 src = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3206 if (rc)
3207 goto fail;
3209 rc = xml_is_element_owner (client, src);
3210 if (rc)
3211 goto fail;
3213 xmlChar *a = xmlGetProp (src, (xmlChar *) "_name");
3214 if (!a)
3216 rc = GPG_ERR_ENOMEM;
3217 goto fail;
3220 /* To prevent unwanted effects:
3222 * <element _name="a"><element _name="b"/></element>
3224 * RENAME a<TAB>b b
3226 if (xmlStrEqual (a, (xmlChar *) args[1]))
3228 xmlFree (a);
3229 rc = GPG_ERR_EEXIST;
3230 goto fail;
3233 xmlFree (a);
3234 str = string_new (args[0]);
3235 if (!str)
3237 rc = GPG_ERR_ENOMEM;
3238 goto fail;
3241 p = strrchr (str->str, '\t');
3242 if (p)
3243 tstr = string_truncate (str, strlen (str->str)-strlen (p));
3244 else
3245 tstr = string_truncate (str, 0);
3247 if (!tstr)
3249 string_free (str, 1);
3250 rc = GPG_ERR_ENOMEM;
3251 goto fail;
3254 str = tstr;
3255 tstr = string_append_printf (str, "%s%s", str->len ? "\t" : "", args[1]);
3256 if (!tstr)
3258 string_free (str, 1);
3259 rc = GPG_ERR_ENOMEM;
3260 goto fail;
3263 str = tstr;
3264 xml_free_request (req);
3265 rc = xml_new_request (client, str->str, XML_CMD_RENAME, &req);
3266 string_free (str, 1);
3267 if (rc)
3269 req = NULL;
3270 goto fail;
3273 dst = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3274 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3275 goto fail;
3277 rc = 0;
3279 /* Target may exist:
3281 * <element _name="a"/>
3282 * <element _name="b" target="a"/>
3284 * RENAME b a
3286 if (src == dst)
3288 rc = GPG_ERR_EEXIST;
3289 goto fail;
3292 if (dst)
3294 rc = xml_is_element_owner (client, dst);
3295 if (rc)
3296 goto fail;
3298 rc = xml_add_attribute (client, src, "_name", args[1]);
3299 if (!rc)
3300 xml_unlink_node (client, dst);
3302 else
3303 rc = xml_add_attribute (client, src, "_name", args[1]);
3305 fail:
3306 xml_free_request (req);
3307 strv_free (args);
3308 return rc;
3311 static gpg_error_t
3312 rename_command (assuan_context_t ctx, char *line)
3314 struct client_s *client = assuan_get_pointer (ctx);
3315 gpg_error_t rc;
3316 struct argv_s *args[] = {
3317 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3318 NULL
3321 rc = parse_options (&line, args, client, 1);
3322 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3323 rc = GPG_ERR_SYNTAX;
3324 if (rc)
3325 return send_error (ctx, rc);
3327 if (client->opts & OPT_INQUIRE)
3329 unsigned char *result;
3330 size_t len;
3332 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3333 if (rc)
3334 return send_error (ctx, rc);
3336 pthread_cleanup_push ((void *)xfree, result);
3337 rc = do_rename (ctx, (char *)result);
3338 pthread_cleanup_pop (1);
3340 else
3341 rc = do_rename (ctx, line);
3343 return send_error (ctx, rc);
3346 static gpg_error_t
3347 do_copy (assuan_context_t ctx, char *line)
3349 struct client_s *client = assuan_get_pointer (ctx);
3350 char **args, **targs;
3351 xmlNodePtr src, dst, tree = NULL;
3352 struct xml_request_s *req;
3353 gpg_error_t rc;
3355 args = str_split (line, " ", 0);
3356 if (!args || strv_length (args) != 2)
3358 strv_free (args);
3359 return GPG_ERR_SYNTAX;
3362 targs = str_split (args[1], "\t", 0);
3363 if (!targs)
3365 strv_free (args);
3366 return GPG_ERR_SYNTAX;
3369 if (!xml_valid_element_path (targs, 0))
3371 strv_free (args);
3372 strv_free (targs);
3373 return GPG_ERR_INV_VALUE;
3375 strv_free (targs);
3377 rc = xml_new_request (client, args[0], XML_CMD_NONE, &req);
3378 if (rc)
3380 strv_free (args);
3381 return rc;
3384 src = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3385 if (rc)
3386 goto fail;
3388 tree = xmlCopyNodeList (src);
3389 if (!tree)
3391 rc = GPG_ERR_ENOMEM;
3392 goto fail;
3395 xml_free_request (req);
3396 /* Create the destination element path if it does not exist. */
3397 rc = xml_new_request (client, args[1], XML_CMD_STORE, &req);
3398 if (rc)
3400 req = NULL;
3401 goto fail;
3404 dst = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3405 if (rc)
3406 goto fail;
3408 rc = xml_is_element_owner (client, dst);
3409 if (rc)
3410 goto fail;
3412 rc = xml_validate_target (client, req->doc, args[1], src);
3413 if (rc || src == dst)
3415 rc = rc ? rc : GPG_ERR_EEXIST;
3416 goto fail;
3419 /* Merge any attributes from the src node to the initial dst node. */
3420 for (xmlAttrPtr attr = tree->properties; attr; attr = attr->next)
3422 if (xmlStrEqual (attr->name, (xmlChar *) "_name"))
3423 continue;
3425 xmlAttrPtr a = xmlHasProp (dst, attr->name);
3426 if (a)
3427 xmlRemoveProp (a);
3429 xmlChar *tmp = xmlNodeGetContent (attr->children);
3430 xmlNewProp (dst, attr->name, tmp);
3431 xmlFree (tmp);
3432 /* Create the default attributes. */
3433 rc = xml_add_attribute (client, dst, NULL, NULL);
3436 xmlNodePtr n = dst->children;
3437 (void)xml_unlink_node (client, n);
3438 dst->children = NULL;
3440 if (tree->children)
3442 n = xmlCopyNodeList (tree->children);
3443 if (!n)
3445 rc = GPG_ERR_ENOMEM;
3446 goto fail;
3449 n = xmlAddChildList (dst, n);
3450 if (!n)
3452 rc = GPG_ERR_ENOMEM;
3453 goto fail;
3456 rc = xml_update_element_mtime (client, xmlDocGetRootElement (client->doc)
3457 == dst->parent ? dst : dst->parent);
3460 fail:
3461 if (tree)
3462 (void)xml_unlink_node (client, tree);
3464 xml_free_request (req);
3465 strv_free (args);
3466 return rc;
3469 static gpg_error_t
3470 copy_command (assuan_context_t ctx, char *line)
3472 struct client_s *client = assuan_get_pointer (ctx);
3473 gpg_error_t rc;
3474 struct argv_s *args[] = {
3475 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3476 NULL
3479 rc = parse_options (&line, args, client, 1);
3480 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3481 rc = GPG_ERR_SYNTAX;
3482 if (rc)
3483 return send_error (ctx, rc);
3485 if (client->opts & OPT_INQUIRE)
3487 unsigned char *result;
3488 size_t len;
3490 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3491 if (rc)
3492 return send_error (ctx, rc);
3494 pthread_cleanup_push ((void *)xfree, result);
3495 rc = do_copy (ctx, (char *)result);
3496 pthread_cleanup_pop (1);
3498 else
3499 rc = do_copy (ctx, line);
3501 return send_error (ctx, rc);
3504 static gpg_error_t
3505 do_move (assuan_context_t ctx, char *line)
3507 struct client_s *client = assuan_get_pointer (ctx);
3508 char **args;
3509 xmlNodePtr src, dst;
3510 struct xml_request_s *req;
3511 gpg_error_t rc;
3513 args = str_split (line, " ", 0);
3514 if (!args || strv_length (args) != 2)
3516 strv_free (args);
3517 return GPG_ERR_SYNTAX;
3520 if (*args[1])
3522 char **targs = str_split (args[1], "\t", 0);
3523 if (!targs)
3525 strv_free (args);
3526 return GPG_ERR_ENOMEM;
3529 if (!xml_valid_element_path (targs, 0))
3531 strv_free (targs);
3532 strv_free (args);
3533 return GPG_ERR_INV_VALUE;
3536 strv_free (targs);
3539 rc = xml_new_request (client, args[0], XML_CMD_MOVE, &req);
3540 if (rc)
3542 strv_free (args);
3543 return rc;
3546 src = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3547 if (rc)
3548 goto fail;
3550 rc = xml_is_element_owner (client, src);
3551 if (rc)
3552 goto fail;
3554 xml_free_request (req);
3555 req = NULL;
3556 if (*args[1])
3558 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
3559 if (rc)
3560 goto fail;
3562 dst = xml_find_elements (client, req, xmlDocGetRootElement (req->doc),
3563 &rc);
3565 else
3566 dst = xmlDocGetRootElement (client->doc);
3568 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3569 goto fail;
3571 rc = 0;
3573 for (xmlNodePtr n = dst; n; n = n->parent)
3575 if (n == src)
3577 rc = GPG_ERR_EEXIST;
3578 goto fail;
3582 if (dst)
3584 xmlChar *a = xml_attribute_value (src, (xmlChar *) "_name");
3585 xmlNodePtr dup = xml_find_element (client, dst->children, (char *) a, &rc);
3587 xmlFree (a);
3588 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3589 goto fail;
3591 rc = 0;
3593 if (dup)
3595 if (dup == src)
3597 rc = GPG_ERR_EEXIST;
3598 goto fail;
3601 if (dst == xmlDocGetRootElement (client->doc))
3603 xmlNodePtr n = src;
3604 int match = 0;
3606 while (n->parent && n->parent != dst)
3607 n = n->parent;
3609 a = xml_attribute_value (n, (xmlChar *) "_name");
3610 xmlChar *b = xml_attribute_value (src, (xmlChar *) "_name");
3612 if (xmlStrEqual (a, b))
3614 match = 1;
3615 xmlUnlinkNode (src);
3616 (void)xml_unlink_node (client, n);
3619 xmlFree (a);
3620 xmlFree (b);
3622 if (!match)
3623 (void)xml_unlink_node (client, dup);
3625 else
3626 xmlUnlinkNode (dup);
3630 if (!dst && *req->args)
3632 struct xml_request_s *nreq = NULL;
3633 xmlChar *name = xml_attribute_value (src, (xmlChar *) "_name");
3635 if (src->parent == xmlDocGetRootElement (client->doc)
3636 && !strcmp ((char *) name, *req->args))
3638 xmlFree (name);
3639 rc = GPG_ERR_EEXIST;
3640 goto fail;
3643 xmlFree (name);
3644 rc = xml_new_request (client, args[1], XML_CMD_STORE, &nreq);
3645 if (!rc)
3647 dst = xml_find_elements (client, nreq,
3648 xmlDocGetRootElement (nreq->doc), &rc);
3649 xml_free_request (nreq);
3652 if (rc)
3653 goto fail;
3656 xml_update_element_mtime (client, src->parent);
3657 xmlUnlinkNode (src);
3659 dst = xmlAddChildList (dst, src);
3660 if (!dst)
3661 rc = GPG_ERR_ENOMEM;
3662 else
3663 xml_update_element_mtime (client, dst->parent);
3665 fail:
3666 xml_free_request (req);
3667 strv_free (args);
3668 return rc;
3671 static gpg_error_t
3672 move_command (assuan_context_t ctx, char *line)
3674 struct client_s *client = assuan_get_pointer (ctx);
3675 gpg_error_t rc;
3676 struct argv_s *args[] = {
3677 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3678 NULL
3681 rc = parse_options (&line, args, client, 1);
3682 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3683 rc = GPG_ERR_SYNTAX;
3684 if (rc)
3685 return send_error (ctx, rc);
3687 if (client->opts & OPT_INQUIRE)
3689 unsigned char *result;
3690 size_t len;
3692 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3693 if (rc)
3694 return send_error (ctx, rc);
3696 pthread_cleanup_push ((void *)xfree, result);
3697 rc = do_move (ctx, (char *)result);
3698 pthread_cleanup_pop (1);
3700 else
3701 rc = do_move (ctx, line);
3703 return send_error (ctx, rc);
3706 static gpg_error_t
3707 ls_command (assuan_context_t ctx, char *line)
3709 gpg_error_t rc;
3710 char *tmp;
3711 char *dir;
3712 DIR *d;
3714 if (line && *line)
3715 return send_error (ctx, GPG_ERR_SYNTAX);
3717 tmp = str_asprintf ("%s/data", homedir);
3718 dir = expand_homedir (tmp);
3719 xfree (tmp);
3720 d = opendir (dir);
3721 rc = gpg_error_from_errno (errno);
3723 if (!d)
3725 xfree (dir);
3726 return send_error (ctx, rc);
3729 size_t len =
3730 offsetof (struct dirent, d_name) +pathconf (dir, _PC_NAME_MAX) + 1;
3731 struct dirent *p = xmalloc (len), *cur = NULL;
3732 char *list = NULL;
3734 xfree (dir);
3735 pthread_cleanup_push ((void *)xfree, p);
3736 pthread_cleanup_push ((void *)(void *)(void *)closedir, d);
3737 rc = 0;
3739 while (!readdir_r (d, p, &cur) && cur)
3741 rc = open_check_file (cur->d_name, NULL, NULL, 1);
3742 if (rc)
3743 continue;
3745 tmp = str_asprintf ("%s%s\n", list ? list : "", cur->d_name);
3747 if (!tmp)
3749 if (list)
3750 xfree (list);
3752 rc = GPG_ERR_ENOMEM;
3753 break;
3756 xfree (list);
3757 list = tmp;
3760 pthread_cleanup_pop (1); // closedir (d)
3761 pthread_cleanup_pop (1); // xfree (p)
3763 if (rc)
3764 return send_error (ctx, rc);
3766 if (!list)
3767 return send_error (ctx, GPG_ERR_NO_DATA);
3769 list[strlen (list) - 1] = 0;
3770 pthread_cleanup_push ((void *)xfree, list);
3771 rc = xfer_data (ctx, list, strlen (list));
3772 pthread_cleanup_pop (1);
3773 return send_error (ctx, rc);
3776 static gpg_error_t
3777 bye_notify (assuan_context_t ctx, char *line)
3779 struct client_s *cl = assuan_get_pointer (ctx);
3780 gpg_error_t ret = 0;
3782 (void)line;
3783 update_client_state (cl, CLIENT_STATE_DISCON);
3785 #ifdef WITH_GNUTLS
3786 cl->disco = 1;
3787 if (cl->thd->remote)
3789 int rc;
3793 struct timeval tv = { 0, 50000 };
3795 rc = gnutls_bye (cl->thd->tls->ses, GNUTLS_SHUT_RDWR);
3796 if (rc == GNUTLS_E_AGAIN)
3797 select (0, NULL, NULL, NULL, &tv);
3799 while (rc == GNUTLS_E_AGAIN);
3801 #endif
3803 /* This will let assuan_process_next() return. */
3804 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
3806 cl->last_rc = gpg_error_from_errno (errno);
3807 ret = cl->last_rc;
3810 cl->last_rc = 0; // BYE command result
3811 return ret;
3814 static gpg_error_t
3815 reset_notify (assuan_context_t ctx, char *line)
3817 struct client_s *client = assuan_get_pointer (ctx);
3819 (void)line;
3820 if (client)
3821 reset_client (client);
3823 return 0;
3827 * This is called before every Assuan command.
3829 static gpg_error_t
3830 command_startup (assuan_context_t ctx, const char *name)
3832 struct client_s *client = assuan_get_pointer (ctx);
3833 gpg_error_t rc;
3834 struct command_table_s *cmd = NULL;
3836 log_write2 ("command='%s'", name);
3837 client->last_rc = client->opts = 0;
3839 for (int i = 0; command_table[i]; i++)
3841 if (!strcasecmp (name, command_table[i]->name))
3843 if (command_table[i]->ignore_startup)
3844 return 0;
3845 cmd = command_table[i];
3846 break;
3850 if (!cmd)
3851 return GPG_ERR_UNKNOWN_COMMAND;
3853 client->last_rc = rc = gpg_error (file_modified (client, cmd));
3854 if (!rc)
3855 update_client_state (client, CLIENT_STATE_COMMAND);
3857 return rc;
3861 * This is called after every Assuan command.
3863 static void
3864 command_finalize (assuan_context_t ctx, gpg_error_t rc)
3866 struct client_s *client = assuan_get_pointer (ctx);
3868 if (!(client->flags & FLAG_LOCK_CMD))
3869 unlock_file_mutex (client, 0);
3871 unlock_flock (&client->flock_fd);
3872 log_write2 (_("command completed: rc=%u"), rc ? rc : client->last_rc);
3873 client->last_rc = gpg_error (GPG_ERR_UNKNOWN_COMMAND);
3874 #ifdef WITH_GNUTLS
3875 client->thd->buffer_timeout = client->thd->last_buffer_size = 0;
3876 #endif
3877 if (client->thd->state != CLIENT_STATE_DISCON)
3878 update_client_state (client, CLIENT_STATE_IDLE);
3881 static gpg_error_t
3882 parse_help_opt_html (void *data, void *value)
3884 struct client_s *client = data;
3886 (void) value;
3887 client->opts |= OPT_HTML;
3888 return 0;
3891 static gpg_error_t
3892 help_command (assuan_context_t ctx, char *line)
3894 gpg_error_t rc;
3895 int i;
3896 struct client_s *client = assuan_get_pointer (ctx);
3897 struct argv_s *args[] = {
3898 &(struct argv_s) {"html", OPTION_TYPE_NOARG, parse_help_opt_html},
3899 NULL
3902 rc = parse_options (&line, args, client, 1);
3903 if (rc)
3904 return send_error (ctx, rc);
3906 if (!line || !*line)
3908 char *tmp;
3909 char *help = str_dup (_("Usage: HELP [--html] [<COMMAND>]\n"
3910 "For commands that take an element path as an argument, each element is "
3911 "separated with an ASCII @key{TAB} character (ASCII 0x09)."
3912 "@*@*COMMANDS:"));
3914 for (i = 0; command_table[i]; i++)
3916 if (!command_table[i]->help)
3917 continue;
3919 /* @npxref{} won't put a "See " or "see " in front of the command.
3920 * It's not a texinfo command but needed for --html. */
3921 tmp = str_asprintf ("%s %s%s%s", help,
3922 client->opts & OPT_HTML ? "@npxref{" : "",
3923 command_table[i]->name,
3924 client->opts & OPT_HTML ? "}" : "");
3925 xfree (help);
3926 help = tmp;
3929 tmp = strip_texi_and_wrap (help, client->opts & OPT_HTML);
3930 xfree (help);
3931 pthread_cleanup_push ((void *)xfree, tmp);
3932 rc = xfer_data (ctx, tmp, strlen (tmp));
3933 pthread_cleanup_pop (1);
3934 return send_error (ctx, rc);
3937 for (i = 0; command_table[i]; i++)
3939 if (!strcasecmp (line, command_table[i]->name))
3941 char *help, *tmp;
3943 if (!command_table[i]->help)
3944 break;
3946 help = strip_texi_and_wrap (command_table[i]->help,
3947 client->opts & OPT_HTML);
3948 tmp = str_asprintf ("%s%s",
3949 (client->opts & OPT_HTML) ? "" : _("Usage: "),
3950 help);
3951 xfree (help);
3952 pthread_cleanup_push ((void *)xfree, tmp);
3953 rc = xfer_data (ctx, tmp, strlen (tmp));
3954 pthread_cleanup_pop (1);
3955 return send_error (ctx, rc);
3959 return send_error (ctx, GPG_ERR_INV_NAME);
3962 static void
3963 new_command (const char *name, int ignore, int unlock, int flock_type,
3964 gpg_error_t (*handler) (assuan_context_t, char *),
3965 const char *help)
3967 int i = 0;
3968 struct command_table_s **tmp;
3970 if (command_table)
3971 for (i = 0; command_table[i]; i++);
3973 tmp = xrealloc (command_table, (i + 2) * sizeof (struct command_table_s *));
3974 assert (tmp);
3975 command_table = tmp;
3976 command_table[i] = xcalloc (1, sizeof (struct command_table_s));
3977 command_table[i]->name = name;
3978 command_table[i]->handler = handler;
3979 command_table[i]->ignore_startup = ignore;
3980 command_table[i]->unlock = unlock;
3981 command_table[i]->flock_type = flock_type;
3982 command_table[i++]->help = help;
3983 command_table[i] = NULL;
3986 void
3987 deinit_commands ()
3989 int i;
3991 for (i = 0; command_table[i]; i++)
3992 xfree (command_table[i]);
3994 xfree (command_table);
3997 static int
3998 sort_commands (const void *arg1, const void *arg2)
4000 struct command_table_s *const *a = arg1;
4001 struct command_table_s *const *b = arg2;
4003 if (!*a || !*b)
4004 return 0;
4005 else if (*a && !*b)
4006 return 1;
4007 else if (!*a && *b)
4008 return -1;
4010 return strcmp ((*a)->name, (*b)->name);
4013 static gpg_error_t
4014 passwd_command (assuan_context_t ctx, char *line)
4016 struct client_s *client = assuan_get_pointer (ctx);
4017 gpg_error_t rc;
4019 (void)line;
4020 rc = peer_is_invoker (client);
4021 if (rc == GPG_ERR_EACCES)
4022 return send_error (ctx, GPG_ERR_FORBIDDEN);
4023 else if (rc)
4024 return send_error (ctx, rc);
4026 if (client->flags & FLAG_NEW)
4027 return send_error (ctx, GPG_ERR_INV_STATE);
4029 client->crypto->keyfile = config_get_string (client->filename,
4030 "passphrase_file");
4031 rc = crypto_init_ctx (client->crypto, client->flags & FLAG_NO_PINENTRY,
4032 client->crypto->keyfile);
4033 if (rc)
4034 return send_error (ctx, rc);
4036 if (!rc)
4037 rc = crypto_passwd (client, client->crypto);
4039 crypto_free_non_keys (client->crypto);
4040 return send_error (ctx, rc);
4043 static gpg_error_t
4044 parse_opt_data (void *data, void *value)
4046 struct client_s *client = data;
4048 (void) value;
4049 client->opts |= OPT_DATA;
4050 return 0;
4053 static gpg_error_t
4054 send_client_list (assuan_context_t ctx)
4056 struct client_s *client = assuan_get_pointer (ctx);
4057 gpg_error_t rc = 0;
4059 if (client->opts & OPT_VERBOSE)
4061 unsigned i, t;
4062 char **list = NULL;
4063 char *line;
4065 MUTEX_LOCK (&cn_mutex);
4066 pthread_cleanup_push ((void *)release_mutex_cb, &cn_mutex);
4067 t = slist_length (cn_thread_list);
4069 for (i = 0; i < t; i++)
4071 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
4072 char *tmp;
4074 if (thd->state == CLIENT_STATE_UNKNOWN)
4075 continue;
4077 tmp = build_client_info_line (thd, 0);
4078 if (tmp)
4080 char **l = strv_cat (list, tmp);
4081 if (!l)
4082 rc = GPG_ERR_ENOMEM;
4083 else
4084 list = l;
4086 else
4087 rc = GPG_ERR_ENOMEM;
4089 if (rc)
4091 strv_free (list);
4092 break;
4096 pthread_cleanup_pop (1);
4097 if (rc)
4098 return rc;
4100 line = strv_join ("\n", list);
4101 strv_free (list);
4102 pthread_cleanup_push ((void *)xfree, line);
4103 rc = xfer_data (ctx, line, strlen (line));
4104 pthread_cleanup_pop (1);
4105 return rc;
4108 if (client->opts & OPT_DATA)
4110 char buf[ASSUAN_LINELENGTH];
4112 MUTEX_LOCK (&cn_mutex);
4113 snprintf (buf, sizeof (buf), "%u", slist_length (cn_thread_list));
4114 MUTEX_UNLOCK (&cn_mutex);
4115 rc = xfer_data (ctx, buf, strlen (buf));
4117 else
4118 rc = send_status (ctx, STATUS_CLIENTS, NULL);
4120 return rc;
4123 static gpg_error_t
4124 getinfo_command (assuan_context_t ctx, char *line)
4126 struct client_s *client = assuan_get_pointer (ctx);
4127 gpg_error_t rc;
4128 char buf[ASSUAN_LINELENGTH];
4129 struct argv_s *args[] = {
4130 &(struct argv_s) {"data", OPTION_TYPE_NOARG, parse_opt_data},
4131 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_opt_verbose},
4132 NULL
4135 rc = parse_options (&line, args, client, 1);
4136 if (rc)
4137 return send_error (ctx, rc);
4139 if (!strcasecmp (line, "clients"))
4141 rc = send_client_list (ctx);
4143 else if (!strcasecmp (line, "cache"))
4145 if (client->opts & OPT_DATA)
4147 snprintf (buf, sizeof (buf), "%u", cache_file_count ());
4148 rc = xfer_data (ctx, buf, strlen (buf));
4150 else
4151 rc = send_status (ctx, STATUS_CACHE, NULL);
4153 else if (!strcasecmp (line, "pid"))
4155 pid_t pid = getpid ();
4157 snprintf (buf, sizeof (buf), "%u", pid);
4158 rc = xfer_data (ctx, buf, strlen (buf));
4160 else if (!strcasecmp (line, "version"))
4162 char *tmp = str_asprintf ("0x%06x %s", VERSION_HEX,
4163 #ifdef WITH_GNUTLS
4164 "GNUTLS "
4165 #endif
4166 #ifdef WITH_LIBACL
4167 "ACL "
4168 #endif
4169 "");
4170 pthread_cleanup_push (xfree, tmp);
4171 rc = xfer_data (ctx, tmp, strlen (tmp));
4172 pthread_cleanup_pop (1);
4174 else if (!strcasecmp (line, "last_error"))
4176 if (client->last_error)
4177 rc = xfer_data (ctx, client->last_error, strlen (client->last_error));
4178 else
4179 rc = GPG_ERR_NO_DATA;
4181 else if (!strcasecmp (line, "user"))
4183 char *user = NULL;
4185 #ifdef WITH_GNUTLS
4186 if (client->thd->remote)
4187 user = str_asprintf ("#%s", client->thd->tls->fp);
4188 else
4189 user = get_username (client->thd->peer->uid);
4190 #else
4191 user = get_username (client->thd->peer->uid);
4192 #endif
4193 if (user)
4195 pthread_cleanup_push ((void *)xfree, user);
4196 rc = xfer_data (ctx, user, strlen (user));
4197 pthread_cleanup_pop (1);
4199 else
4200 rc = GPG_ERR_NO_DATA;
4202 else
4203 rc = gpg_error (GPG_ERR_SYNTAX);
4205 return send_error (ctx, rc);
4208 static gpg_error_t
4209 parse_listkeys_opt_secret_only (void *data, void *value)
4211 struct client_s *client = data;
4213 (void) value;
4214 client->opts |= OPT_SECRET_ONLY;
4215 return 0;
4218 static gpg_error_t
4219 keyinfo_command (assuan_context_t ctx, char *line)
4221 struct client_s *client = assuan_get_pointer (ctx);
4222 gpg_error_t rc = 0;
4223 char **keys = NULL, **p = NULL;
4224 int sym = 0;
4226 if (line && *line)
4227 return send_error (ctx, GPG_ERR_SYNTAX);
4229 if (!(client->flags & FLAG_OPEN))
4230 return send_error (ctx, GPG_ERR_INV_STATE);
4232 if (client->flags & FLAG_NEW)
4233 return send_error (ctx, GPG_ERR_NO_DATA);
4235 rc = lock_flock (ctx, client->filename, FLOCK_TYPE_SH, &client->flock_fd);
4236 if (rc)
4237 return send_error (ctx, rc);
4239 rc = crypto_is_symmetric (client->filename);
4240 unlock_flock (&client->flock_fd);
4241 if (!rc)
4242 sym = 1;
4243 else if (rc != GPG_ERR_BAD_DATA)
4244 return send_error (ctx, rc);
4246 rc = 0;
4247 if (!sym)
4249 p = strv_catv(keys, client->crypto->pubkey);
4250 if (!p)
4251 rc = GPG_ERR_ENOMEM;
4254 if (!rc)
4256 keys = p;
4257 for (p = client->crypto->sigkey; p && *p; p++)
4259 if (!strv_printf(&keys, "S%s", *p))
4261 strv_free (keys);
4262 return send_error (ctx, GPG_ERR_ENOMEM);
4266 else
4267 rc = GPG_ERR_ENOMEM;
4269 if (!rc)
4271 if (keys)
4273 line = strv_join ("\n", keys);
4274 strv_free (keys);
4275 pthread_cleanup_push ((void *)xfree, line);
4276 if (line)
4277 rc = xfer_data (ctx, line, strlen (line));
4278 else
4279 rc = GPG_ERR_ENOMEM;
4281 pthread_cleanup_pop (1);
4283 else
4284 rc = GPG_ERR_NO_DATA;
4286 else
4287 strv_free (keys);
4289 return send_error (ctx, rc);
4292 static gpg_error_t
4293 kill_command (assuan_context_t ctx, char *line)
4295 struct client_s *client = assuan_get_pointer (ctx);
4296 gpg_error_t rc;
4297 unsigned i, t;
4299 if (!line || !*line)
4300 return send_error (ctx, GPG_ERR_SYNTAX);
4302 MUTEX_LOCK (&cn_mutex);
4303 pthread_cleanup_push ((void *)release_mutex_cb, &cn_mutex);
4304 t = slist_length (cn_thread_list);
4305 rc = GPG_ERR_ESRCH;
4307 for (i = 0; i < t; i++)
4309 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
4310 char *tmp = str_asprintf ("%p", thd->tid);
4312 if (strcmp (line, tmp))
4314 xfree (tmp);
4315 continue;
4318 xfree (tmp);
4319 rc = peer_is_invoker (client);
4320 if (!rc)
4322 #ifdef HAVE_PTHREAD_CANCEL
4323 pthread_cancel (thd->tid);
4324 #else
4325 pthread_kill (thd->tid, SIGUSR2);
4326 #endif
4327 break;
4329 else if (rc == GPG_ERR_EACCES)
4330 rc = GPG_ERR_FORBIDDEN;
4331 else if (rc)
4332 break;
4334 if (config_get_boolean ("global", "strict_kill"))
4335 break;
4337 #ifdef WITH_GNUTLS
4338 if (client->thd->remote && thd->remote)
4340 if (!thd->tls || !thd->tls->fp)
4342 rc = GPG_ERR_INV_STATE;
4343 break;
4345 if (!strcmp (client->thd->tls->fp, thd->tls->fp))
4347 #ifdef HAVE_PTHREAD_CANCEL
4348 pthread_cancel (thd->tid);
4349 #else
4350 pthread_kill (thd->tid, SIGUSR2);
4351 #endif
4352 break;
4355 else if (!client->thd->remote && !thd->remote)
4356 #endif
4358 if (client->thd->peer->uid == thd->peer->uid)
4360 #ifdef HAVE_PTHREAD_CANCEL
4361 pthread_cancel (thd->tid);
4362 #else
4363 pthread_kill (thd->tid, SIGUSR2);
4364 #endif
4367 break;
4370 pthread_cleanup_pop (1);
4371 return send_error (ctx, rc);
4374 static gpg_error_t
4375 listkeys_command (assuan_context_t ctx, char *line)
4377 struct client_s *client = assuan_get_pointer (ctx);
4378 struct crypto_s *crypto = NULL;
4379 char **pattern = NULL;
4380 gpgme_key_t *keys = NULL;
4381 char **result = NULL;
4382 gpg_error_t rc;
4383 struct argv_s *args[] = {
4384 &(struct argv_s) {"secret-only", OPTION_TYPE_NOARG,
4385 parse_listkeys_opt_secret_only },
4386 NULL
4389 rc = parse_options (&line, args, client, 1);
4390 if (rc)
4391 return send_error (ctx, rc);
4393 rc = crypto_init (&crypto, client->ctx, client->filename,
4394 client->flags & FLAG_NO_PINENTRY, NULL);
4395 if (rc)
4396 return send_error (ctx, rc);
4398 pthread_cleanup_push ((void *)crypto_free, crypto);
4399 pattern = str_split (line, ",", 0);
4400 pthread_cleanup_push ((void *)(void *)strv_free, pattern);
4401 rc = crypto_list_keys (crypto, pattern, client->opts & OPT_SECRET_ONLY,
4402 &keys);
4403 pthread_cleanup_pop (1);
4404 pthread_cleanup_pop (1);
4405 if (!rc)
4407 int i;
4409 for (i = 0; keys[i]; i++)
4411 char *p = crypto_key_info (keys[i]);
4412 char **r;
4414 if (!p)
4416 rc = GPG_ERR_ENOMEM;
4417 break;
4420 r = strv_cat (result, p);
4421 if (!r)
4423 rc = GPG_ERR_ENOMEM;
4424 break;
4427 result = r;
4430 if (!i)
4431 rc = GPG_ERR_NO_DATA;
4433 crypto_free_key_list (keys);
4436 if (!rc)
4438 line = strv_join ("\n", result);
4439 strv_free (result);
4440 pthread_cleanup_push ((void *)xfree, line);
4441 if (!line)
4442 rc = GPG_ERR_ENOMEM;
4443 else
4444 rc = xfer_data (ctx, line, strlen (line));
4446 pthread_cleanup_pop (1);
4448 else
4449 strv_free (result);
4451 if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
4452 || gpg_err_code (rc) == GPG_ERR_NO_SECKEY)
4453 rc = GPG_ERR_NO_DATA;
4455 return send_error (ctx, rc);
4458 void
4459 init_commands ()
4461 /* !BEGIN-HELP-TEXT!
4463 * This comment is used as a marker to generate the offline documentation
4464 * found in doc/pwmd.info. The indentation needs to be kept for the awk
4465 * script to determine where commands begin and end.
4467 new_command("HELP", 1, 1, 0, help_command, _(
4468 "HELP [--html] [<COMMAND>]\n"
4469 "Show available commands or command specific help text."
4470 "@*@*"
4471 "The @option{--html} option will output the help text in HTML format."
4474 new_command("KILL", 1, 0, 0, kill_command, _(
4475 "KILL <thread_id>\n"
4476 "Terminates the client identified by @var{thread_id} and releases any file "
4477 "lock or other resources it has held. See @code{GETINFO} (@pxref{GETINFO}) "
4478 "for details about listing connected clients. An @code{invoking_user} "
4479 "(@pxref{Configuration}) may kill any client while others may only kill "
4480 "clients of the same @code{UID} or @abbr{TLS} fingerprint."
4483 new_command("LISTKEYS", 0, 0, 0, listkeys_command, _(
4484 "LISTKEYS [--secret-only] [pattern[,<pattern>]]\n"
4485 "Returns a new line separated list of key information matching a comma "
4486 "separated list of @var{pattern}'s. When option @option{--secret-only} is "
4487 "specified, only keys matching @var{pattern} that also have a secret key "
4488 "available will be returned."
4491 new_command("KEYINFO", 1, 0, 0, keyinfo_command, _(
4492 "KEYINFO\n"
4493 "Returns a new line separated list of key ID's that the currently opened "
4494 "data file has recipients and signers for. If the key is a signing key it "
4495 "will be prefixed with an @code{S}. If the file is a new one, or has no "
4496 "signers in the case of being symmetrically encrypted, the error code "
4497 "@code{GPG_ERR_NO_DATA} is returned."
4500 new_command("GETINFO", 1, 1, 0, getinfo_command, _(
4501 "GETINFO [--data] [--verbose] CACHE | CLIENTS | PID | USER | LAST_ERROR | VERSION\n"
4502 "Get server and other information. The information is returned via a status "
4503 "message (@pxref{Status Messages}) unless otherwise noted or @option{--data} "
4504 "is specified."
4505 "@*@*"
4506 "@var{CACHE} returns the number of cached documents."
4507 "@*@*"
4508 "@var{CLIENTS} returns the number of "
4509 "connected clients via a status message or a list of connected clients when "
4510 "the @option{--verbose} parameter is used (implies @option{--data}). A "
4511 "verbose line of a client list contains "
4512 "space delimited "
4513 "fields: the thread ID, client name, opened file (@code{/} if none opened), "
4514 "IP address if remote, file lock status, whether the current client is self "
4515 "or not, client state (see below), "
4516 "user ID or TLS fingerprint of the connected client, username if the "
4517 "client is a local one else @code{-}, and finally the time stamp of when the "
4518 "client connected."
4519 "@*@*"
4520 "Client state @code{0} is an unknown client state, state @code{1} indicates "
4521 "the client has connected but hasn't completed initializing, state @code{2} "
4522 "indicates that the client is idle, state @code{3} means the "
4523 "client is in a command and state @code{4} means the client is disconnecting. "
4524 "@*@*"
4525 "@var{PID} returns the process ID number of the server via a data response."
4526 "@*@*"
4527 "@var{VERSION} returns the server version number and compile-time features "
4528 "via a data response with each being space delimited."
4529 "@*@*"
4530 "@var{LAST_ERROR} returns a detailed description of the last failed command "
4531 "via a data response, when available."
4532 "@*@*"
4533 "@var{USER} returns the username or @abbr{TLS} hash of the connected client "
4534 "via a data response."
4537 new_command("PASSWD", 0, 0, FLOCK_TYPE_EX|FLOCK_TYPE_KEEP, passwd_command, _(
4538 "PASSWD\n"
4539 "Changes the passphrase of the secret key required to open the current "
4540 "data file. If the data file is symmetrically encrypted, the error "
4541 "@code{GPG_ERR_NOT_SUPPORTED} is returned. When symmetrically encrypted, "
4542 "the @code{SAVE} command (@pxref{SAVE}) should be used instead to prevent "
4543 "this command saving any unwanted changes to the @abbr{XML} document."
4544 "@*@*"
4545 "This command is not available to non-invoking clients "
4546 "(@pxref{Access Control})."
4549 new_command("OPEN", 1, 1, FLOCK_TYPE_SH|FLOCK_TYPE_KEEP, open_command, _(
4550 "OPEN [--lock] <filename>\n"
4551 "Opens @var{filename}. When the @var{filename} is not found on the "
4552 "file-system then a new in-memory document will be created. If the file is "
4553 "found, it is looked for in the file cache and when found no passphrase will "
4554 "be required to open it. When not cached, @cite{pinentry(1)} will be used to "
4555 "retrieve the passphrase for decryption unless @option{disable-pinentry} "
4556 "(@pxref{OPTION}) was specified in which case @command{pwmd} will "
4557 "@emph{INQUIRE} the client for the passphrase."
4558 "@*@*"
4559 "When the @option{--lock} option is passed then the file mutex will be "
4560 "locked as if the @code{LOCK} command (@pxref{LOCK}) had been sent after the "
4561 "file had been opened."
4564 new_command("SAVE", 0, 0, FLOCK_TYPE_EX|FLOCK_TYPE_KEEP, save_command, _(
4565 "SAVE [--symmetric] [--inquire-keyparam] [--keyid=<fpr>[,..] | [--inquire-keyid]] [--sign-keyid=<fpr>[,..] | [--inquire-sign-keyid]]\n"
4566 "Writes the in-memory @abbr{XML} document to disk. The file written to is the "
4567 "file that was opened using the @code{OPEN} command (@pxref{OPEN}). If the "
4568 "file is a new one or the option @option{--inquire-keyparam} was passed, a "
4569 "new keypair will be generated and @cite{pinentry(1)} will be used to prompt "
4570 "for the passphrase of the secret key used for signing."
4571 "@*@*"
4572 "The @option{--inquire-keyparam} option will send an "
4573 "@emph{INQUIRE} to the client to obtain the key parameters to use for "
4574 "generating the new keypair. The inquired data is expected to be in "
4575 "@cite{gnupg} @abbr{XML} format. See the @cite{gnupg} documentation for "
4576 "details. Note that when this option is specified a new keypair will be "
4577 "generated reguardless if the file is a new one and that the passphrase for "
4578 "the current file will be required before generating the new keypair. This "
4579 "option is available to non-invoking clients (@pxref{Access Control}) only "
4580 "when the file is a new one."
4581 "@*@*"
4582 "You can encrypt the data file to a recipient other than the one that it "
4583 "was encrypted with by passing the @option{--keyid} or "
4584 "@option{--inquire-keyid} option with "
4585 "the fingerprint of a public encryption key as its argument. Use the "
4586 "@command{LISTKEYS} command (@pxref{LISTKEYS}) to show key information by "
4587 "pattern. The @option{--sign-keyid} or @option{--inquire-sign-keyid} option "
4588 "may also be used to sign the data "
4589 "file with an alternate key by specifying the fingerprint of a secret key. "
4590 "A passphrase to decrypt the data file "
4591 "will be required when one or more of the original encryption or signing keys "
4592 "are not found in either of these two options' arguments or when the data "
4593 "file is symmetrically encrypted, reguardless of the @code{require_save_key} "
4594 "configuration parameter. The original encryption or signing keys will be "
4595 "used when either of these options are not specified."
4596 "@*@*"
4597 "The @option{--keyid} and @option{--sign-keyid} options are not available "
4598 "for non-invoking clients "
4599 "(@pxref{Access Control}) when the recipients or signers do not match those "
4600 "that were used when the file was @code{OPEN}'ed."
4601 "@*@*"
4602 "The @option{--symmetric} option specifies that a new data file be "
4603 "conventionally encrypted. These types of data files do not use a recipient "
4604 "public key but may be signed by using the @option{--sign-keyid} or "
4605 "@option{--inquire-sign-keyid} options. To remove all signers from a "
4606 "symmtrically encrypted data file, leave the option value empty. Note that "
4607 "you cannot change encryption schemes once a data file has been saved."
4610 new_command("ISCACHED", 1, 0, 0, iscached_command, _(
4611 "ISCACHED [--lock] [--agent [--sign]] <filename>\n"
4612 "Determines the file cache status of the specified @var{filename}. "
4613 "The default is to test whether the filename is cached in memory. Passing "
4614 "option @option{--agent} will test the @command{gpg-agent} cache for at most "
4615 "one cached key used for opening the data file (@pxref{OPEN}). To test if "
4616 "a signing key is cached, pass @option{--sign} along with @option{--agent}. "
4617 "Both the @option{--agent} and @option{--sign} options require an opened data "
4618 "file."
4619 "@*@*"
4620 "An @emph{OK} response is returned if the specified @var{filename} is found "
4621 "in the cache. If not found in the cache but exists on the filesystem "
4622 "then @code{GPG_ERR_NO_DATA} is returned. Otherwise a filesystem error is "
4623 "returned."
4624 "@*@*"
4625 "The @option{--lock} option will lock the file mutex of @var{filename} when "
4626 "the file exists; it does not need to be opened nor cached. The lock will be "
4627 "released when the client exits or sends the @code{UNLOCK} command "
4628 "(@pxref{UNLOCK}). When this option is passed the current data file is closed."
4631 new_command("CLEARCACHE", 1, 1, 0, clearcache_command, _(
4632 "CLEARCACHE [<filename>]\n"
4633 "Clears a file cache entry for all or the specified @var{filename}. Note that "
4634 "this will also clear any @command{gpg-agent} cached keys which may cause "
4635 "problems if another data file shares the same keys as @var{filename}."
4636 "@*@*"
4637 "When clearing all cache entries a permissions test is done against the "
4638 "current client based on the @var{access} configuration parameter in a "
4639 "@var{filename} section. Both a cache entry may be cleared and an error "
4640 "returned depending on cached data files and client permissions."
4643 new_command("CACHETIMEOUT", 1, 1, 0, cachetimeout_command, _(
4644 "CACHETIMEOUT <filename> <seconds>\n"
4645 "The time in @var{seconds} until @var{filename} will be removed from the "
4646 "cache. @code{-1} will keep the cache entry forever, @code{0} will require "
4647 "the passphrase for each @code{OPEN} command (@pxref{OPEN}) or @code{SAVE} "
4648 "(@pxref{SAVE}) command. @xref{Configuration}, and the @code{cache_timeout} "
4649 "parameter."
4652 new_command("LIST", 0, 1, 0, list_command, _(
4653 "LIST [--inquire] [--recurse] [element[<TAB>child[..]]]\n"
4654 "If no element path is given then a newline separated list of root elements "
4655 "is returned with a data response. If given, then children of the specified "
4656 "element path are returned."
4657 "@*@*"
4658 "Each element path "
4659 "returned will have zero or more flags appened to it. These flags are "
4660 "delimited from the element path by a single space character. A flag itself "
4661 "is a single character. Flag @code{P} indicates that access to the element "
4662 "is denied. Flag @code{+} indicates that there are child nodes of "
4663 "the current element path. Flag @code{E} indicates that an element of the "
4664 "element path contained in a @var{target} attribute could not be found. Flag "
4665 "@code{O} indicates that a @var{target} attribute recursion limit was reached "
4666 "(@pxref{Configuration}). Flag @code{T}, followed by a single space character, "
4667 "then an element path, is the element path of the @var{target} attribute "
4668 "contained in the current element."
4669 "@*@*"
4670 "When a specified element path contains an error, beit from the final "
4671 "element in the path or any previous element, the path is still shown but "
4672 "will contain the error flag for the element with the error. Determining "
4673 "the actual element which contains the error is up to the client. This can be "
4674 "done by traversing the final element up to parent elements that contain the "
4675 "same error flag."
4676 "@*@*"
4677 "The option @option{--recurse} may be used to list the entire element tree "
4678 "for a specified element path or the entire tree for all root elements."
4679 "@*@*"
4680 "When the @option{--inquire} option is passed then all remaining non-option "
4681 "arguments are retrieved via a server @emph{INQUIRE}."
4684 new_command("REALPATH", 0, 1, 0, realpath_command, _(
4685 "REALPATH [--inquire] element[<TAB>child[..]]\n"
4686 "Resolves all @code{target} attributes of the specified element path and "
4687 "returns the result with a data response. @xref{Target Attribute}, for details."
4688 "@*@*"
4689 "When the @option{--inquire} option is passed then all remaining non-option "
4690 "arguments are retrieved via a server @emph{INQUIRE}."
4693 new_command("STORE", 0, 1, 0, store_command, _(
4694 "STORE element[<TAB>child[..]]<TAB>[content]\n"
4695 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
4696 "@*@*"
4697 "Creates a new element path or modifies the @var{content} of an existing "
4698 "element. If only a single element is specified then a new root element is "
4699 "created. Otherwise, elements are @key{TAB} delimited and the content will be "
4700 "set to the final @key{TAB} delimited element. If no @var{content} is "
4701 "specified after the final @key{TAB}, then the content of the existing "
4702 "element will be removed; or will be empty if creating a new element."
4703 "@*@*"
4704 "The only restriction of an element name is that it not contain whitespace "
4705 "characters. There is no other whitespace between the @key{TAB} delimited "
4706 "elements. It is recommended that the content of an element be base64 encoded "
4707 "when it contains control or @key{TAB} characters to prevent @abbr{XML} "
4708 "parsing and @command{pwmd} syntax errors."
4711 new_command("RENAME", 0, 1, 0, rename_command, _(
4712 "RENAME [--inquire] element[<TAB>child[..]] <value>\n"
4713 "Renames the specified @var{element} to the new @var{value}. If an element of "
4714 "the same name as the @var{value} already exists it will be overwritten."
4715 "@*@*"
4716 "When the @option{--inquire} option is passed then all remaining non-option "
4717 "arguments are retrieved via a server @emph{INQUIRE}."
4720 new_command("COPY", 0, 1, 0, copy_command, _(
4721 "COPY [--inquire] source[<TAB>child[..]] dest[<TAB>child[..]]\n"
4722 "Copies the entire element tree starting from the child node of the source "
4723 "element, to the destination element path. If the destination element path "
4724 "does not exist then it will be created; otherwise it is overwritten."
4725 "@*@*"
4726 "Note that attributes from the source element are merged into the "
4727 "destination element when the destination element path exists. When an "
4728 "attribute of the same name exists in both the source and destination "
4729 "elements then the destination attribute will be updated to the source "
4730 "attribute value."
4731 "@*@*"
4732 "When the @option{--inquire} option is passed then all remaining non-option "
4733 "arguments are retrieved via a server @emph{INQUIRE}."
4736 new_command("MOVE", 0, 1, 0, move_command, _(
4737 "MOVE [--inquire] source[<TAB>child[..]] [dest[<TAB>child[..]]]\n"
4738 "Moves the source element path to the destination element path. If the "
4739 "destination is not specified then it will be moved to the root node of the "
4740 "document. If the destination is specified and exists then it will be "
4741 "overwritten; otherwise non-existing elements of the destination element "
4742 "path will be created."
4743 "@*@*"
4744 "When the @option{--inquire} option is passed then all remaining non-option "
4745 "arguments are retrieved via a server @emph{INQUIRE}."
4748 new_command("DELETE", 0, 1, 0, delete_command, _(
4749 "DELETE [--inquire] element[<TAB>child[..]]\n"
4750 "Removes the specified element path and all of its children. This may break "
4751 "an element with a @code{target} attribute (@pxref{Target Attribute}) that "
4752 "refers to this element or any of its children."
4753 "@*@*"
4754 "When the @option{--inquire} option is passed then all remaining non-option "
4755 "arguments are retrieved via a server @emph{INQUIRE}."
4758 new_command("GET", 0, 1, 0, get_command, _(
4759 "GET [--inquire] element[<TAB>child[..]]\n"
4760 "Retrieves the content of the specified element. The content is returned "
4761 "with a data response."
4762 "@*@*"
4763 "When the @option{--inquire} option is passed then all remaining non-option "
4764 "arguments are retrieved via a server @emph{INQUIRE}."
4767 new_command("ATTR", 0, 1, 0, attr_command, _(
4768 "ATTR [--inquire] SET|GET|DELETE|LIST [<attribute>] element[<TAB>child[..]] ..\n"
4769 "@table @asis\n"
4770 "@item ATTR SET attribute element[<TAB>child[..]] [value]\n"
4771 " Stores or updates an @var{attribute} name and optional @var{value} of an "
4772 "element. When no @var{value} is specified any existing value will be removed."
4773 "@*@*"
4774 "@item ATTR DELETE attribute element[<TAB>child[..]]\n"
4775 " Removes an attribute from an element. If @var{attribute} is @code{_name} "
4776 "or @code{target} an error is returned. Use the @command{DELETE} command "
4777 "(@pxref{DELETE}) instead."
4778 "@*@*"
4779 "@item ATTR LIST element[<TAB>child[..]]\n"
4780 " Retrieves a newline separated list of attributes names and values "
4781 "from the specified element. Each attribute name and value is space delimited."
4782 "@*@*"
4783 "@item ATTR GET attribute element[<TAB>child[..]]\n"
4784 " Retrieves the value of an @var{attribute} from an element."
4785 "@end table\n"
4786 "@*@*"
4787 "When the @option{--inquire} option is passed then all remaining non-option "
4788 "arguments are retrieved via a server @emph{INQUIRE}."
4789 "@*@*"
4790 "@xref{Target Attribute}, for details about this special attribute and also "
4791 "@pxref{Other Attributes} for other attributes that are handled specially "
4792 "by @command{pwmd}."
4795 new_command("XPATH", 0, 1, 0, xpath_command, _(
4796 "XPATH [--inquire] <expression>[<TAB>[value]]\n"
4797 "Evaluates an XPath @var{expression}. If no @var{value} argument is "
4798 "specified it is assumed the expression is a request to return a result. "
4799 "Otherwise, the result is set to the @var{value} argument and the document is "
4800 "updated. If there is no @var{value} after the @key{TAB} character, the value "
4801 "is assumed to be empty and the document is updated. For example:"
4802 "@sp 1\n"
4803 "@example\n"
4804 "XPATH //element[@@_name='password']@key{TAB}\n"
4805 "@end example\n"
4806 "@sp 1\n"
4807 "would clear the content of all @var{password} elements in the data file "
4808 "while leaving off the trailing @key{TAB} would return all @var{password} "
4809 "elements in @abbr{XML} format."
4810 "@*@*"
4811 "When the @option{--inquire} option is passed then all remaining non-option "
4812 "arguments are retrieved via a server @emph{INQUIRE}."
4813 "@*@*"
4814 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
4815 "expression syntax."
4818 new_command("XPATHATTR", 0, 1, 0, xpathattr_command, _(
4819 "XPATHATTR [--inquire] SET|DELETE <name> <expression>[<TAB>[<value>]]\n"
4820 "Like the @code{XPATH} command (@pxref{XPATH}) but operates on element "
4821 "attributes and does not return a result. For the @var{SET} operation the "
4822 "@var{value} is optional but the field is required. If not specified then "
4823 "the attribute value will be empty. For example:"
4824 "@sp 1\n"
4825 "@example\n"
4826 "XPATHATTR SET password //element[@@_name='password']@key{TAB}\n"
4827 "@end example\n"
4828 "@sp 1\n"
4829 "would create a @var{password} attribute for each @var{password} element "
4830 "found in the document. The attribute value will be empty but still exist."
4831 "@*@*"
4832 "When the @option{--inquire} option is passed then all remaining non-option "
4833 "arguments are retrieved via a server @emph{INQUIRE}."
4834 "@*@*"
4835 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
4836 "expression syntax."
4839 new_command("IMPORT", 0, 1, 0, import_command, _(
4840 "IMPORT [--root=element[<TAB>child[..]]]\n"
4841 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
4842 "@*@*"
4843 "Like the @code{STORE} command (@pxref{STORE}), but the @var{content} "
4844 "argument is raw @abbr{XML} data. The content is created as a child of "
4845 "the element path specified with the @option{--root} option or at the "
4846 "document root when not specified. Existing elements of the same name will "
4847 "be overwritten."
4848 "@*@*"
4849 "The content must begin with an @abbr{XML} element node. @xref{Introduction}, "
4850 "for details."
4853 new_command("DUMP", 0, 1, 0, dump_command, _(
4854 "DUMP\n"
4855 "Shows the in memory @abbr{XML} document with indenting. @xref{XPATH}, for "
4856 "dumping a specific node."
4859 new_command("LOCK", 0, 0, 0, lock_command, _(
4860 "LOCK\n"
4861 "Locks the mutex associated with the opened file. This prevents other clients "
4862 "from sending commands to the same opened file until the client "
4863 "that sent this command either disconnects or sends the @code{UNLOCK} "
4864 "command. @xref{UNLOCK}."
4867 new_command("UNLOCK", 1, 0, 0, unlock_command, _(
4868 "UNLOCK\n"
4869 "Unlocks the file mutex which was locked with the @code{LOCK} command or "
4870 "a commands' @option{--lock} option (@pxref{LOCK}, @pxref{OPEN}, "
4871 "@pxref{ISCACHED})."
4874 new_command("GETCONFIG", 1, 1, 0, getconfig_command, _(
4875 "GETCONFIG [filename] <parameter>\n"
4876 "Returns the value of a @command{pwmd} configuration @var{parameter} with a "
4877 "data response. If no file has been opened then the value for @var{filename} "
4878 "or the default from the @var{global} section will be returned. If a file "
4879 "has been opened and no @var{filename} is specified, the value previously "
4880 "set with the @code{OPTION} command (@pxref{OPTION}) will be returned."
4883 new_command("OPTION", 1, 1, 0, option_command, _(
4884 "OPTION <NAME>=[<VALUE>]\n"
4885 "Sets a client option @var{name} to @var{value}. The value for an option is "
4886 "kept for the duration of the connection with the exception of the "
4887 "@command{pinentry} options which are defaults for all future connections "
4888 "(@pxref{Pinentry}). When @var{value} is empty the option is unset."
4889 "@*@*"
4890 "@table @asis\n"
4891 "@item DISABLE-PINENTRY\n"
4892 "Disable use of @command{pinentry} for passphrase retrieval. When @code{1}, a "
4893 "server inquire is sent to the client to obtain the passphrase. This option "
4894 "may be set as needed before the @code{OPEN} (@pxref{OPEN}), @code{PASSWD} "
4895 "(@pxref{PASSWD}) and @code{SAVE} (@pxref{SAVE}) commands. Set to @code{0} "
4896 "to use a @command{pinentry}."
4897 "@*@*"
4898 "@item DISPLAY\n"
4899 "Set or unset the X11 display to use when prompting for a passphrase."
4900 "@*@*"
4901 "@item TTYNAME\n"
4902 "Set the terminal device path to use when prompting for a passphrase."
4903 "@*@*"
4904 "@item TTYTYPE\n"
4905 "Set the terminal type for use with @option{TTYNAME}."
4906 "@*@*"
4907 "@item NAME\n"
4908 "Associates the thread ID of the connection with the specified textual "
4909 "representation. Useful for debugging log messages. May not contain whitespace."
4910 "@*@*"
4911 "@item LOCK-TIMEOUT\n"
4912 "When not @code{0}, the duration in tenths of a second to wait for the file "
4913 "mutex which has been locked by another thread to be released before returning "
4914 "an error. When @code{-1} the error will be returned immediately."
4915 "@*@*"
4916 "@item CLIENT-STATE\n"
4917 "When set to @code{1} then client state status messages for other clients are "
4918 "sent to the current client. The default is @code{0}."
4919 "@end table\n"
4922 new_command("LS", 1, 1, 0, ls_command, _(
4923 "LS\n"
4924 "Returns a newline separated list of data files stored in the data directory "
4925 "@file{HOMEDIR/data} (@pxref{Invoking}) with a data response."
4928 new_command("RESET", 1, 1, 0, NULL, _(
4929 "RESET\n"
4930 "Closes the currently opened file but keeps any previously set client options "
4931 "(@pxref{OPTION})."
4934 new_command("NOP", 1, 1, 0, NULL, _(
4935 "NOP\n"
4936 "Does nothing. Always returns successfully."
4939 /* !END-HELP-TEXT! */
4940 new_command ("CANCEL", 1, 1, 0, NULL, NULL);
4941 new_command ("END", 1, 1, 0, NULL, NULL);
4942 new_command ("BYE", 1, 1, 0, NULL, NULL);
4944 int i;
4945 for (i = 0; command_table[i]; i++);
4946 qsort (command_table, i - 1, sizeof (struct command_table_s *),
4947 sort_commands);
4950 gpg_error_t
4951 register_commands (assuan_context_t ctx)
4953 int i = 0, rc;
4955 for (; command_table[i]; i++)
4957 if (!command_table[i]->handler)
4958 continue;
4960 rc = assuan_register_command (ctx, command_table[i]->name,
4961 command_table[i]->handler,
4962 command_table[i]->help);
4963 if (rc)
4964 return rc;
4967 rc = assuan_register_bye_notify (ctx, bye_notify);
4968 if (rc)
4969 return rc;
4971 rc = assuan_register_reset_notify (ctx, reset_notify);
4972 if (rc)
4973 return rc;
4975 rc = assuan_register_pre_cmd_notify (ctx, command_startup);
4976 if (rc)
4977 return rc;
4979 return assuan_register_post_cmd_notify (ctx, command_finalize);