ATTR LIST: fix access to unowned elements.
[libpwmd.git] / src / commands.c
blob93277d0da48043633934b49f61695ec7be39f984
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>
39 #include "pwmd-error.h"
40 #include <gcrypt.h>
42 #include "mem.h"
43 #include "xml.h"
44 #include "util-misc.h"
45 #include "common.h"
46 #include "rcfile.h"
47 #include "cache.h"
48 #include "commands.h"
49 #include "mutex.h"
50 #include "crypto.h"
52 /* These are command option flags. */
53 #define OPT_INQUIRE 0x0001
54 #define OPT_NO_PASSPHRASE 0x0002
55 #define OPT_ASK 0x0004
56 #define OPT_LIST_RECURSE 0x0008
57 #define OPT_VERBOSE 0x0010
58 #define OPT_LOCK 0x0020
59 #define OPT_LOCK_ON_OPEN 0x0040
60 #define OPT_SIGN 0x0080
61 #define OPT_LIST_ALL 0x0100
62 #define OPT_DATA 0x0200
63 #define OPT_NO_AGENT 0x0400
64 #define OPT_SECRET_ONLY 0x0800
65 #define OPT_INQUIRE_KEYID 0x1000
66 #define OPT_INQUIRE_SIGN_KEYID 0x2000
67 #define OPT_SYMMETRIC 0x4000
68 #define OPT_NO_SIGNER 0x8000
69 #define OPT_HTML 0x10000
71 #define FLOCK_TYPE_NONE 0
72 #define FLOCK_TYPE_SH 0x0001
73 #define FLOCK_TYPE_EX 0x0002
74 #define FLOCK_TYPE_KEEP 0x0004
76 struct command_table_s
78 const char *name;
79 gpg_error_t (*handler) (assuan_context_t, char *line);
80 const char *help;
81 int ignore_startup;
82 int unlock; // unlock the file mutex after validating the checksum
83 uint32_t flock_type;
86 static struct command_table_s **command_table;
88 static gpg_error_t do_lock (struct client_s *client, int add);
89 static gpg_error_t validate_checksum (struct client_s *,
90 struct cache_data_s *, unsigned char **,
91 size_t *);
92 static gpg_error_t update_checksum (struct client_s *client);
94 /* When 'status' is true the 'self' field of the status line will be false
95 * because we never send the STATE status message to the same client that
96 * initiated it. */
97 static char *
98 build_client_info_line (struct client_thread_s *thd, int status)
100 MUTEX_LOCK (&cn_mutex);
101 int with_state = config_get_boolean ("global", "send_state");
102 char *uid, *username = NULL;
103 char *line;
105 #ifdef WITH_GNUTLS
106 if (thd->remote)
107 uid = str_asprintf("#%s", thd->tls->fp);
108 else
110 uid = str_asprintf("%u", thd->peer->uid);
111 username = get_username (thd->peer->uid);
113 #else
114 uid = str_asprintf("%u", thd->peer->uid);
115 username = get_username (thd->peer->uid);
116 #endif
117 line = str_asprintf ("%p %s %s %s %u %u %u %s %s %u",
118 thd->tid,
119 thd->name ? thd->name : "-",
120 thd->cl && thd->cl->filename
121 && (thd->cl->flags & FLAG_OPEN)
122 ? thd->cl->filename : "/",
123 #ifdef WITH_GNUTLS
124 thd->remote ? thd->peeraddr : "-",
125 #else
126 "-",
127 #endif
128 thd->cl && thd->cl->flags & FLAG_HAS_LOCK ? 1 : 0,
129 !status && pthread_equal (pthread_self (), thd->tid) ? 1 : 0,
130 with_state ? thd->state : CLIENT_STATE_UNKNOWN, uid,
131 #ifdef WITH_GNUTLS
132 thd->remote ? "-" : username,
133 #else
134 username,
135 #endif
136 thd->conntime
139 xfree (username);
140 xfree (uid);
141 MUTEX_UNLOCK (&cn_mutex);
142 return line;
145 void
146 update_client_state (struct client_s *client, unsigned s)
148 client->thd->state = s;
149 int n = config_get_boolean ("global", "send_state");
151 if (n && client->thd->state != CLIENT_STATE_UNKNOWN)
153 char *line = build_client_info_line (client->thd, 1);
155 if (line)
156 send_status_all_not_self (n == 2, STATUS_STATE, "%s", line);
158 xfree (line);
162 static gpg_error_t
163 unlock_file_mutex (struct client_s *client, int remove)
165 gpg_error_t rc = 0;
167 // OPEN: keep the lock for the same file being reopened.
168 if (client->flags & FLAG_KEEP_LOCK && client->flags & FLAG_HAS_LOCK)
169 return 0;
171 if (!(client->flags & FLAG_HAS_LOCK))
172 return GPG_ERR_NOT_LOCKED;
174 rc = cache_unlock_mutex (client->md5file, remove);
175 if (rc)
176 rc = GPG_ERR_INV_STATE;
177 else
178 client->flags &= ~(FLAG_HAS_LOCK | FLAG_LOCK_CMD);
180 return rc;
183 static gpg_error_t
184 lock_file_mutex (struct client_s *client, int add)
186 gpg_error_t rc = 0;
187 int timeout = config_get_integer (client->filename, "cache_timeout");
189 if (client->flags & FLAG_HAS_LOCK)
190 return 0;
192 rc = cache_lock_mutex (client->ctx, client->md5file,
193 client->lock_timeout, add, timeout);
194 if (!rc)
195 client->flags |= FLAG_HAS_LOCK;
197 return rc;
200 static gpg_error_t
201 file_modified (struct client_s *client, struct command_table_s *cmd)
203 gpg_error_t rc = 0;
204 int type = !cmd->flock_type || (cmd->flock_type & FLOCK_TYPE_SH)
205 ? LOCK_SH : LOCK_EX;
207 if (!(client->flags & FLAG_OPEN))
208 return GPG_ERR_INV_STATE;
210 rc = lock_file_mutex (client, 0);
211 if (rc && rc != GPG_ERR_NO_DATA)
212 return rc;
214 rc = lock_flock (client->ctx, client->filename, type, &client->flock_fd);
215 if (!rc)
217 rc = validate_checksum (client, NULL, NULL, NULL);
218 if (gpg_err_code (rc) == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
219 rc = 0;
220 else if (rc)
221 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
223 else if (gpg_err_code (rc) == GPG_ERR_ENOENT)
224 rc = 0;
226 /* FLAG_HAS_LOCK may have been set by the LOCK command or OPEN --lock. */
227 if ((cmd->unlock && !(client->flags & FLAG_HAS_LOCK)) || rc)
228 unlock_file_mutex (client, 0);
230 if (rc || !(cmd->flock_type & FLOCK_TYPE_KEEP))
231 unlock_flock (&client->flock_fd);
233 return rc;
236 static gpg_error_t
237 parse_xml (assuan_context_t ctx, int new)
239 struct client_s *client = assuan_get_pointer (ctx);
240 int cached = client->doc != NULL;
241 gpg_error_t rc = 0;
243 if (new)
245 client->doc = xml_new_document ();
246 if (client->doc)
248 xmlChar *result;
249 int len;
251 xmlDocDumpFormatMemory (client->doc, &result, &len, 0);
252 client->crypto->plaintext = result;
253 client->crypto->plaintext_size = len;
254 if (!client->crypto->plaintext)
256 xmlFreeDoc (client->doc);
257 client->doc = NULL;
258 rc = GPG_ERR_ENOMEM;
261 else
262 rc = GPG_ERR_ENOMEM;
264 else if (!cached)
265 rc = xml_parse_doc ((char *) client->crypto->plaintext,
266 client->crypto->plaintext_size,
267 (xmlDocPtr *)&client->doc);
269 return rc;
272 static void
273 free_client (struct client_s *client)
275 if (client->doc)
276 xmlFreeDoc (client->doc);
278 xfree (client->crc);
279 xfree (client->filename);
280 xfree (client->last_error);
281 crypto_cleanup (client->crypto);
282 client->crypto = NULL;
285 void
286 cleanup_client (struct client_s *client)
288 assuan_context_t ctx = client->ctx;
289 struct client_thread_s *thd = client->thd;
290 long lock_timeout = client->lock_timeout;
291 xmlErrorPtr xml_error = client->xml_error;
292 int no_pinentry = (client->flags & FLAG_NO_PINENTRY);
293 int flock_fd = client->flock_fd;
295 unlock_file_mutex (client, client->flags & FLAG_NEW);
296 free_client (client);
297 memset (client, 0, sizeof (struct client_s));
298 client->flock_fd = flock_fd;
299 client->xml_error = xml_error;
300 client->ctx = ctx;
301 client->thd = thd;
302 client->lock_timeout = lock_timeout;
303 client->flags |= no_pinentry ? FLAG_NO_PINENTRY : 0;
306 static void
307 req_cleanup (void *arg)
309 if (!arg)
310 return;
312 strv_free ((char **) arg);
315 static gpg_error_t
316 parse_open_opt_lock (void *data, void *value)
318 struct client_s *client = data;
320 client->opts |= OPT_LOCK_ON_OPEN;
321 return 0;
324 static gpg_error_t
325 parse_opt_inquire (void *data, void *value)
327 struct client_s *client = data;
329 (void) value;
330 client->opts |= OPT_INQUIRE;
331 return 0;
334 static gpg_error_t
335 update_checksum (struct client_s *client)
337 unsigned char *crc;
338 size_t len;
339 struct cache_data_s *cdata;
340 gpg_error_t rc = get_checksum (client->filename, &crc, &len);
342 if (rc)
343 return rc;
345 xfree (client->crc);
346 client->crc = crc;
347 cdata = cache_get_data (client->md5file);
348 if (cdata)
350 xfree (cdata->crc);
351 cdata->crc = xmalloc (len);
352 memcpy (cdata->crc, crc, len);
355 return 0;
358 static gpg_error_t
359 validate_checksum (struct client_s *client, struct cache_data_s *cdata,
360 unsigned char **r_crc, size_t *r_crclen)
362 unsigned char *crc;
363 size_t len;
364 gpg_error_t rc;
365 int n = 0;
367 if (cdata && !cdata->crc)
368 return GPG_ERR_CHECKSUM;
370 rc = get_checksum (client->filename, &crc, &len);
371 if (rc)
372 return rc;
374 if (cdata)
375 n = memcmp (cdata->crc, crc, len);
376 else if (client->crc)
377 n = memcmp (client->crc, crc, len);
379 if (!n && r_crc)
381 *r_crc = crc;
382 *r_crclen = len;
384 else
385 xfree (crc);
387 return n ? GPG_ERR_CHECKSUM : 0;
390 static gpg_error_t
391 open_command (assuan_context_t ctx, char *line)
393 gpg_error_t rc;
394 struct client_s *client = assuan_get_pointer (ctx);
395 char **req, *filename;
396 unsigned char md5file[16];
397 int same_file = 0;
398 assuan_peercred_t peer;
399 struct cache_data_s *cdata = NULL;
400 int cached = 0;
401 unsigned char *crc = NULL;
402 size_t crclen = 0;
403 struct argv_s *args[] = {
404 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_open_opt_lock},
405 NULL
408 rc = parse_options (&line, args, client, 1);
409 if (rc)
410 return send_error (ctx, rc);
412 req = str_split (line, " ", 2);
413 if (!req)
414 return send_error (ctx, GPG_ERR_SYNTAX);
416 rc = do_validate_peer (ctx, req[0], &peer);
417 if (rc)
419 strv_free (req);
420 return send_error (ctx, rc);
423 filename = req[0];
424 if (!valid_filename (filename))
426 strv_free (req);
427 return send_error (ctx, GPG_ERR_INV_VALUE);
430 pthread_cleanup_push ((void *)req_cleanup, req);
431 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, filename, strlen (filename));
432 /* This client may have locked a different file with ISCACHED --lock than
433 * the current filename. This will remove that lock. */
434 same_file = !memcmp (md5file, client->md5file, 16) ? 1 : 0;
435 if (client->flags & FLAG_OPEN ||
436 (client->flags & FLAG_HAS_LOCK && !same_file))
438 uint32_t opts = client->opts;
439 uint32_t flags = client->flags;
441 if (same_file)
442 client->flags |= FLAG_KEEP_LOCK;
443 else if (client->flags & FLAG_NEW)
444 cache_clear (client->md5file);
446 cleanup_client (client);
447 client->opts = opts;
448 client->flags |= flags;
449 client->flags &= ~(FLAG_LOCK_CMD);
450 if (!same_file)
451 client->flags &= ~(FLAG_HAS_LOCK | FLAG_NEW);
454 memcpy (client->md5file, md5file, 16);
455 client->filename = str_dup (filename);
456 if (!client->filename)
458 strv_free (req);
459 return send_error(ctx, GPG_ERR_ENOMEM);
462 /* Need to lock the mutex here because file_modified() cannot without
463 * knowing the filename. */
464 rc = lock_file_mutex (client, 1);
465 if (rc)
466 client->flags &= ~FLAG_OPEN;
468 if (!rc)
470 rc = lock_flock (ctx, filename, LOCK_SH, &client->flock_fd);
471 if (gpg_err_code (rc) == GPG_ERR_ENOENT)
472 rc = 0;
475 if (!rc)
477 struct stat st;
479 rc = crypto_init (&client->crypto, client->ctx, client->filename,
480 client->flags & FLAG_NO_PINENTRY);
481 if (!rc && stat (client->filename, &st) == -1)
482 rc = gpg_error_from_errno (errno);
483 else if (!rc && !S_ISREG (st.st_mode)) // to match LS output
484 rc = gpg_error_from_errno (ENOANO);
487 if (!rc || gpg_err_code (rc) == GPG_ERR_ENOENT)
489 cdata = cache_get_data (client->md5file);
491 if (rc) // new file
493 rc = 0;
494 client->flags |= FLAG_NEW;
495 // data file disappeared. clear the cache entry.
496 cache_clear (client->md5file);
497 cdata = NULL;
499 else if (cdata && cdata->doc) // cached document
501 int reload = 0;
502 int defer = 0;
504 if (!rc && !(client->flags & FLAG_NEW))
506 rc = validate_checksum (client, cdata, &crc, &crclen);
507 if (rc == GPG_ERR_CHECKSUM)
509 rc = 0;
510 reload = 1;
514 if (!rc)
516 rc = cache_iscached (client->filename, &defer);
517 if ((!rc || rc == GPG_ERR_ENOENT) && defer)
519 rc = 0;
520 reload = 2;
524 if (!rc && reload)
526 if (reload == 1)
527 log_write ("%s: %s", client->filename,
528 pwmd_strerror (GPG_ERR_CHECKSUM));
529 cache_clear (client->md5file);
530 cdata = NULL;
531 rc = crypto_decrypt (client, client->crypto);
533 #ifdef WITH_GNUTLS
534 else if (!rc)
536 if (client->thd->remote
537 && config_get_boolean (client->filename, "tcp_require_key")
538 && !(client->flags & FLAG_NEW))
539 rc = crypto_try_decrypt (client,
540 (client->flags & FLAG_NO_PINENTRY));
542 #endif
544 if (!rc && cdata)
546 client->crypto->plaintext = cdata->doc;
547 client->crypto->plaintext_size = cdata->size;
548 rc = cache_decrypt (client->crypto);
549 if (!rc)
551 cdata->doc = NULL;
552 cdata->size = 0;
553 strv_free (client->crypto->pubkey);
554 strv_free (client->crypto->sigkey);
555 client->crypto->pubkey = strv_dup (cdata->pubkey);
556 client->crypto->sigkey = strv_dup (cdata->sigkey);
557 cached = 1;
559 else
561 client->crypto->plaintext = NULL;
562 client->crypto->plaintext_size = 0;
566 else // existing file
568 cached = cdata != NULL;
569 rc = crypto_decrypt (client, client->crypto);
573 if (!rc)
575 rc = parse_xml (ctx, client->flags & FLAG_NEW);
576 if (!rc)
578 rc = cache_encrypt (client->crypto);
579 if (rc)
580 cache_clear (client->md5file);
581 else
583 int timeout = config_get_integer (client->filename,
584 "cache_timeout");
586 free_cache_data_once (cdata);
587 cdata = xcalloc (1, sizeof (struct cache_data_s));
588 cdata->doc = client->crypto->plaintext;
589 cdata->size = client->crypto->plaintext_size;
590 cdata->pubkey = strv_dup(client->crypto->pubkey);
591 cdata->sigkey = strv_dup(client->crypto->sigkey);
592 client->crypto->plaintext = NULL;
593 client->crypto->plaintext_size = 0;
595 if (cached) // wont increment the refcount
597 /* Prevent using another FD to update the checksum for a
598 * cached data file. The validity has already been
599 * verified. */
600 xfree (client->crc);
601 client->crc = xmalloc (crclen);
602 memcpy (client->crc, crc, crclen);
603 xfree (cdata->crc);
604 cdata->crc = xmalloc (crclen);
605 memcpy (cdata->crc, crc, crclen);
607 rc = cache_set_data (client->md5file, cdata);
608 /* The cache entry may have been removed and cache_set_data()
609 * already sent STATUS_CACHE. */
610 if (!cache_iscached (client->filename, NULL))
611 rc = send_status (ctx, STATUS_CACHE, NULL);
613 else
614 rc = cache_add_file (client->md5file, cdata, timeout);
619 pthread_cleanup_pop (1);
620 xfree (crc);
622 if (!rc && !(client->flags & FLAG_NEW) && !cached)
623 rc = update_checksum (client);
625 if (!rc)
627 client->flags |= FLAG_OPEN;
629 if (client->flags & FLAG_NEW)
630 rc = send_status (ctx, STATUS_NEWFILE, NULL);
632 if (!rc && (client->opts & OPT_LOCK_ON_OPEN))
633 rc = do_lock (client, 0);
636 if (rc)
638 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
640 if (client->flags & FLAG_NEW)
641 cache_clear (client->md5file);
643 crypto_cleanup (client->crypto);
644 client->crypto = NULL;
645 client->flags &= ~FLAG_OPEN;
648 crypto_cleanup_non_keys (client->crypto);
649 return send_error (ctx, rc);
652 /* If not the invoking_user or is an existing file, check that the list of user
653 * supplied key ID's are in the list of current key ID's obtained when
654 * decrypting the data file. Both short and long form keyid fingerprints are
655 * valid:
657 * 8 byte with optional "0x" prefix
658 * 16 byte
659 * 40 byte
661 * Although, the key ID's are converted to the 8 byte form before calling this
662 * function in parse_save_opt_keyid_common() to keep consistancy with KEYINFO
663 * output.
665 static gpg_error_t
666 permitted_to_save (struct client_s *client, const char **keys,
667 const char **value)
669 gpg_error_t rc = 0;
670 const char **v;
672 if ((client->flags & FLAG_NEW) || (client->opts & OPT_SYMMETRIC))
673 return 0;
675 rc = peer_is_invoker (client);
676 if (!rc)
677 return 0;
679 /* Empty match. */
680 if ((!value && !keys) || ((value && !*value) && (keys && !*keys)))
681 return 0;
683 for (v = value; v && *v; v++)
685 const char **k, *pv = *v;
686 int match = 0;
688 if (*pv == '0' && *(pv+1) == 'x')
689 pv += 2;
691 for (k = keys; k && *k; k++)
693 const char *pk = *k;
695 if (*pk == '0' && *(pk+1) == 'x')
696 pk += 2;
698 rc = !strcmp (pv, pk) ? 0 : GPG_ERR_FORBIDDEN;
699 if (rc)
700 rc = !strcmp (pv, *k) ? 0 : GPG_ERR_FORBIDDEN;
702 if (!rc)
704 match = 1;
705 break;
709 if (!match)
710 return GPG_ERR_FORBIDDEN;
713 return rc;
716 static gpg_error_t
717 parse_save_opt_keyid_common (struct client_s *client, const char **list,
718 const char *value, char ***dst)
720 gpg_error_t rc;
721 char **p = NULL;
723 if (value && *value)
725 p = str_split (value, ",", 0);
726 if (!p)
727 return GPG_ERR_ENOMEM;
730 crypto_keyid_to_8b (p);
731 rc = permitted_to_save (client, list, (const char **)p);
732 if (!rc)
733 *dst = p;
734 else
735 strv_free (*dst);
737 return rc;
740 static gpg_error_t
741 parse_save_opt_keyid (void *data, void *value)
743 struct client_s *client = data;
744 const char *str = value;
745 char **dst = NULL;
746 gpg_error_t rc;
748 rc = parse_save_opt_keyid_common (client,
749 (const char **)client->crypto->pubkey,
750 str, &dst);
751 if (rc)
752 return rc;
754 client->crypto->save.pubkey = dst;
755 return 0;
758 static gpg_error_t
759 parse_save_opt_sign_keyid (void *data, void *value)
761 struct client_s *client = data;
762 const char *str = value;
763 char **dst = NULL;
764 gpg_error_t rc;
766 rc = parse_save_opt_keyid_common (client,
767 (const char **)client->crypto->sigkey,
768 str, &dst);
769 if (rc)
770 return rc;
772 if (!dst)
773 client->opts |= OPT_NO_SIGNER;
775 client->crypto->save.sigkey = dst;
776 return 0;
779 static gpg_error_t
780 parse_save_opt_inquire (struct client_s *client, uint32_t opt)
782 if (opt == OPT_INQUIRE && !(client->flags & FLAG_NEW))
784 gpg_error_t rc = peer_is_invoker (client);
786 if (rc)
787 return rc;
790 client->opts |= opt;
791 return 0;
794 static gpg_error_t
795 parse_save_opt_inquire_keyparam (void *data, void *value)
797 return parse_save_opt_inquire (data, OPT_INQUIRE);
800 static gpg_error_t
801 parse_save_opt_inquire_keyid (void *data, void *value)
803 return parse_save_opt_inquire (data, OPT_INQUIRE_KEYID);
806 static gpg_error_t
807 parse_save_opt_inquire_sign_keyid (void *data, void *value)
809 return parse_save_opt_inquire (data, OPT_INQUIRE_SIGN_KEYID);
812 static gpg_error_t
813 parse_save_opt_symmetric (void *data, void *value)
815 struct client_s *client = data;
817 client->opts |= OPT_SYMMETRIC;
818 return 0;
821 /* Tests that the keys in new_keys are also in old_keys. */
822 static gpg_error_t
823 compare_keys (char **new_keys, char **old_keys)
825 char **o;
827 if (!old_keys || !*old_keys)
828 return 0;
830 crypto_keyid_to_8b (new_keys);
832 for (o = old_keys; *o; o++)
834 char **n;
836 for (n = new_keys; *n; n++)
838 if (!strcmp (*n, *o))
839 break;
842 if (!*n)
843 return GPG_ERR_NOT_FOUND;
846 return 0;
849 static gpg_error_t
850 inquire_keyid (struct client_s *client, uint32_t opt)
852 gpg_error_t rc;
853 unsigned char *result = NULL;
854 size_t len;
855 char *s;
856 char ***orig;
857 char ***save;
859 if (opt == OPT_INQUIRE_KEYID)
861 s = "INQUIRE_KEYID";
862 orig = &client->crypto->pubkey;
863 save = &client->crypto->save.pubkey;
865 else
867 s = "INQUIRE_SIGN_KEYID";
868 orig = &client->crypto->sigkey;
869 save = &client->crypto->save.sigkey;
872 rc = assuan_inquire (client->ctx, s, &result, &len, 0);
873 if (!rc)
875 char **dst = NULL;
877 rc = parse_save_opt_keyid_common (client, (const char **)*orig,
878 (char *)result, &dst);
879 if (!rc)
881 if (!dst && opt == OPT_INQUIRE_SIGN_KEYID
882 && client->opts & OPT_SYMMETRIC)
883 client->opts |= OPT_NO_SIGNER;
885 *save = dst;
889 xfree (result);
890 return rc;
893 static gpg_error_t
894 save_command (assuan_context_t ctx, char *line)
896 struct client_s *client = assuan_get_pointer (ctx);
897 struct cache_data_s *cdata = NULL;
898 gpg_error_t rc = 0, cached = 0;
899 int defer = 0;
900 struct stat st;
901 struct argv_s *args[] = {
902 &(struct argv_s) {"keyid", OPTION_TYPE_ARG, parse_save_opt_keyid},
903 &(struct argv_s) {"sign-keyid", OPTION_TYPE_OPTARG,
904 parse_save_opt_sign_keyid},
905 &(struct argv_s) {"inquire-keyparam", OPTION_TYPE_NOARG,
906 parse_save_opt_inquire_keyparam },
907 &(struct argv_s) {"inquire-keyid", OPTION_TYPE_NOARG,
908 parse_save_opt_inquire_keyid },
909 &(struct argv_s) {"inquire-sign-keyid", OPTION_TYPE_NOARG,
910 parse_save_opt_inquire_sign_keyid },
911 &(struct argv_s) {"symmetric", OPTION_TYPE_NOARG,
912 parse_save_opt_symmetric },
913 NULL
916 crypto_cleanup_save (&client->crypto->save);
918 if (!(client->flags & FLAG_NEW))
920 rc = crypto_is_symmetric (client->filename);
921 if (!rc || rc == GPG_ERR_BAD_DATA)
923 if (!rc)
924 client->opts |= OPT_SYMMETRIC;
926 rc = 0; // PKI
930 if (rc)
931 return send_error (ctx, rc);
933 rc = parse_options (&line, args, client, 0);
934 if (rc)
935 return send_error (ctx, rc);
937 if (config_get_boolean (client->filename, "require_save_key"))
938 client->opts |= OPT_ASK;
940 if (lstat (client->filename, &st) == -1 && errno != ENOENT)
941 return send_error (ctx, gpg_error_from_errno (errno));
943 if (errno != ENOENT && !S_ISREG (st.st_mode))
945 log_write ("%s: %s", client->filename, pwmd_strerror (GPG_ERR_ENOANO));
946 return send_error (ctx, GPG_ERR_ENOANO);
949 if (!rc)
950 cached = rc = cache_iscached (client->filename, &defer);
952 if (gpg_err_code (rc) == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
953 rc = 0;
954 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
955 rc = 0;
957 if (rc)
958 return send_error (ctx, rc);
960 /* Specifying both a recipient and symmetric encryption is an error. */
961 if (client->opts & OPT_INQUIRE_KEYID && client->opts & OPT_SYMMETRIC)
963 return send_error (ctx, GPG_ERR_CONFLICT);
965 else if (client->opts & OPT_INQUIRE && client->opts & OPT_SYMMETRIC)
967 return send_error (ctx, GPG_ERR_CONFLICT);
969 /* Existing file with a recipient and wanting symmetric is an error. */
970 else if (client->opts & OPT_SYMMETRIC && client->crypto->save.pubkey)
972 return send_error (ctx, GPG_ERR_CONFLICT);
974 else if (((client->opts & OPT_INQUIRE_KEYID)
975 || (client->opts & OPT_INQUIRE_SIGN_KEYID)))
977 if (client->opts & OPT_INQUIRE)
978 return send_error (ctx, GPG_ERR_CONFLICT);
980 if (client->opts & OPT_INQUIRE_KEYID)
981 rc = inquire_keyid (client, OPT_INQUIRE_KEYID);
983 if (!rc && (client->opts & OPT_INQUIRE_SIGN_KEYID))
984 rc = inquire_keyid (client, OPT_INQUIRE_SIGN_KEYID);
986 else if ((client->crypto->save.pubkey || client->crypto->save.sigkey)
987 && client->opts & OPT_INQUIRE)
988 return send_error (ctx, GPG_ERR_CONFLICT);
990 if (!rc)
991 rc = crypto_init_ctx (client->crypto, client->flags & FLAG_NO_PINENTRY);
993 if (!rc && (client->opts & OPT_INQUIRE))
995 /* Require a passphrase when generating a new key pair for an existing
996 * file.
998 if (!(client->flags & FLAG_NEW))
1000 rc = crypto_try_decrypt (client, client->flags & FLAG_NO_PINENTRY);
1001 client->opts &= ~OPT_ASK;
1004 if (!rc)
1006 unsigned char *params = NULL;
1007 size_t len;
1009 rc = assuan_inquire (client->ctx, "KEYPARAM", &params, &len, 0);
1010 if (!rc)
1012 client->crypto->flags |= CRYPTO_FLAG_NEWFILE;
1013 pthread_cleanup_push ((void *)xfree, params);
1014 rc = crypto_genkey (client, client->crypto, params);
1015 pthread_cleanup_pop (1);
1019 else if (!rc && (client->flags & FLAG_NEW))
1021 if (!client->crypto->save.pubkey && !client->crypto->save.sigkey
1022 && !(client->opts & OPT_SYMMETRIC))
1024 char *params = crypto_default_key_params ();
1026 if (!params)
1027 rc = GPG_ERR_ENOMEM;
1029 if (!rc)
1031 client->crypto->flags |= CRYPTO_FLAG_NEWFILE;
1032 pthread_cleanup_push ((void *)xfree, params);
1033 rc = crypto_genkey (client, client->crypto,
1034 (unsigned char *)params);
1035 pthread_cleanup_pop (1);
1038 else
1040 if (!client->crypto->save.pubkey && client->crypto->save.sigkey
1041 && !(client->opts & OPT_SYMMETRIC))
1042 client->crypto->save.pubkey = strv_dup (client->crypto->save.sigkey);
1044 if (client->crypto->save.pubkey && !client->crypto->save.sigkey)
1045 client->crypto->save.sigkey = strv_dup (client->crypto->save.pubkey);
1048 else if (!rc)
1050 cdata = cache_get_data (client->md5file);
1051 if (cdata)
1053 if (client->crypto->save.pubkey)
1054 rc = compare_keys (client->crypto->save.pubkey, cdata->pubkey);
1056 /* Always allow a signer for symmetric data files. */
1057 if (!rc && client->crypto->save.sigkey
1058 && !(client->opts & OPT_SYMMETRIC))
1059 rc = compare_keys (client->crypto->save.sigkey, cdata->sigkey);
1061 /* Prevent saving to a recipient who is not in the original recipient
1062 * list without a passphrase. */
1063 if (rc || (client->crypto->sigkey && client->opts & OPT_NO_SIGNER))
1064 client->opts |= OPT_ASK;
1066 if (rc == GPG_ERR_NOT_FOUND)
1068 rc = peer_is_invoker (client);
1069 if (rc == GPG_ERR_EACCES)
1070 rc = GPG_ERR_FORBIDDEN;
1073 if (!client->crypto->save.pubkey
1074 && !(client->opts & OPT_SYMMETRIC))
1075 client->crypto->save.pubkey = strv_dup (cdata->pubkey);
1077 if (!client->crypto->save.sigkey && cdata->sigkey
1078 && !(client->opts & OPT_NO_SIGNER))
1079 client->crypto->save.sigkey = strv_dup (cdata->sigkey);
1080 else if (!client->crypto->save.sigkey
1081 && (client->opts & OPT_NO_SIGNER)
1082 && !(client->opts & OPT_SYMMETRIC))
1083 rc = GPG_ERR_NO_SIGNATURE_SCHEME;
1085 else
1087 client->crypto->save.pubkey = strv_dup (client->crypto->pubkey);
1088 client->crypto->save.sigkey = strv_dup (client->crypto->sigkey);
1092 if (!rc && !(client->flags & FLAG_NEW))
1094 /* Fixes {NEW_,SIGN_}PASSPHRASE inquire keywords. See passphrase_cb(). */
1095 if (client->opts & OPT_SYMMETRIC)
1096 client->crypto->flags |= CRYPTO_FLAG_PASSWD;
1098 if (client->opts & OPT_ASK)
1099 rc = crypto_try_decrypt (client, client->flags & FLAG_NO_PINENTRY);
1102 if (!rc && client->opts & OPT_SYMMETRIC)
1103 client->crypto->flags |= CRYPTO_FLAG_PASSWD_NEW;
1105 if (!rc)
1106 rc = xml_update_element_mtime (client, xmlDocGetRootElement (client->doc));
1108 if (!rc)
1110 int size;
1112 xmlDocDumpFormatMemory (client->doc, &client->crypto->plaintext, &size,
1114 if (size > 0)
1115 client->crypto->plaintext_size = (size_t) size;
1116 else
1117 rc = GPG_ERR_ENOMEM;
1119 if (!rc)
1121 client->crypto->flags |= (client->opts & OPT_SYMMETRIC) ? CRYPTO_FLAG_SYMMETRIC : 0;
1122 client->crypto->flags |= (client->flags & FLAG_NEW) ? CRYPTO_FLAG_NEWFILE : 0;
1123 rc = crypto_encrypt (client, client->crypto);
1124 client->crypto->flags &= ~CRYPTO_FLAG_SYMMETRIC;
1127 if (!rc)
1129 rc = crypto_write_file (client->crypto);
1130 if (!rc)
1132 if (!cached) // no error
1133 cdata = cache_get_data (client->md5file);
1136 if (!rc)
1138 rc = cache_encrypt (client->crypto);
1139 if (rc)
1141 cache_clear (client->md5file);
1142 strv_free (client->crypto->pubkey);
1143 client->crypto->pubkey = strv_dup (client->crypto->save.pubkey);
1144 strv_free (client->crypto->sigkey);
1145 client->crypto->sigkey = strv_dup (client->crypto->save.sigkey);
1146 client->flags &= ~(FLAG_NEW);
1150 if (!rc)
1152 int timeout = config_get_integer (client->filename,
1153 "cache_timeout");
1155 free_cache_data_once (cdata);
1156 cdata = xcalloc (1, sizeof (struct cache_data_s));
1157 cdata->doc = client->crypto->plaintext;
1158 client->crypto->plaintext = NULL;
1159 cdata->size = client->crypto->plaintext_size;
1160 client->crypto->plaintext_size = 0;
1161 cdata->pubkey = client->crypto->save.pubkey;
1162 client->crypto->save.pubkey = NULL;
1163 cdata->sigkey = client->crypto->save.sigkey;
1164 client->crypto->save.sigkey = NULL;
1166 /* Update in case the cache entry expires the next SAVE may not
1167 * have any known keys. */
1168 strv_free (client->crypto->pubkey);
1169 client->crypto->pubkey = strv_dup (cdata->pubkey);
1170 strv_free (client->crypto->sigkey);
1171 client->crypto->sigkey = strv_dup (cdata->sigkey);
1173 if (!cached) // no error and wont increment refcount
1174 rc = cache_set_data (client->md5file, cdata);
1175 else
1176 rc = cache_add_file (client->md5file, cdata, timeout);
1178 if (!rc && (cached || (client->flags & FLAG_NEW)))
1179 send_status_all (STATUS_CACHE, NULL);
1181 if (!rc)
1183 rc = update_checksum (client);
1184 client->flags &= ~(FLAG_NEW);
1190 crypto_cleanup_non_keys (client->crypto);
1191 return send_error (ctx, rc);
1194 static gpg_error_t
1195 do_delete (assuan_context_t ctx, char *line)
1197 struct client_s *client = assuan_get_pointer (ctx);
1198 struct xml_request_s *req;
1199 xmlNodePtr n;
1200 gpg_error_t rc;
1202 rc = xml_new_request (client, line, XML_CMD_DELETE, &req);
1203 if (rc)
1204 return rc;
1206 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1207 xml_free_request (req);
1208 if (rc)
1209 return rc;
1211 rc = xml_is_element_owner (client, n);
1212 if (!rc)
1213 rc = xml_unlink_node (client, n);
1215 return rc;
1218 static gpg_error_t
1219 delete_command (assuan_context_t ctx, char *line)
1221 struct client_s *client = assuan_get_pointer (ctx);
1222 gpg_error_t rc;
1223 struct argv_s *args[] = {
1224 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1225 NULL
1228 rc = parse_options (&line, args, client, 1);
1229 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1230 rc = GPG_ERR_SYNTAX;
1231 if (rc)
1232 return send_error (ctx, rc);
1234 if (client->opts & OPT_INQUIRE)
1236 unsigned char *result;
1237 size_t len;
1239 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1240 if (rc)
1241 return send_error (ctx, rc);
1243 pthread_cleanup_push ((void *)xfree, result);
1244 rc = do_delete (ctx, (char *)result);
1245 pthread_cleanup_pop (1);
1247 else
1248 rc = do_delete (ctx, line);
1250 return send_error (ctx, rc);
1253 static gpg_error_t
1254 store_command (assuan_context_t ctx, char *line)
1256 struct client_s *client = assuan_get_pointer (ctx);
1257 gpg_error_t rc;
1258 size_t len;
1259 unsigned char *result;
1260 xmlNodePtr n, parent;
1261 int has_content;
1262 char *content = NULL;
1263 struct xml_request_s *req;
1265 if (line && *line)
1266 return send_error (ctx, GPG_ERR_SYNTAX);
1268 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1269 if (rc)
1270 return send_error (ctx, rc);
1272 rc = xml_new_request (client, (char *)result, XML_CMD_STORE, &req);
1273 xfree (result);
1274 if (rc)
1275 return send_error (ctx, rc);
1277 /* Prevent passing the element content around to save some memory. */
1278 len = strv_length (req->args);
1279 has_content = line[strlen (line) - 1] != '\t' && len > 1;
1280 if (*(req->args+1) && !xml_valid_element_path (req->args, has_content))
1282 xml_free_request (req);
1283 return send_error (ctx, GPG_ERR_INV_VALUE);
1286 if (has_content || !*req->args[len-1])
1288 has_content = 1;
1289 content = req->args[len-1];
1290 req->args[len-1] = NULL;
1293 parent = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1295 if (!rc && len > 1)
1297 rc = xml_is_element_owner (client, parent);
1298 if (!rc)
1300 n = xml_find_text_node (parent->children);
1301 if (n)
1302 xmlNodeSetContent (n, (xmlChar *) content);
1303 else
1304 xmlNodeAddContent (parent, (xmlChar *) content);
1306 xml_update_element_mtime (client, parent);
1310 xfree (content);
1311 xml_free_request (req);
1312 return send_error (ctx, rc);
1315 static gpg_error_t
1316 xfer_data (assuan_context_t ctx, const char *line, int total)
1318 struct client_s *client = assuan_get_pointer (ctx);
1319 int to_send;
1320 int sent = 0;
1321 gpg_error_t rc = 0;
1322 int progress = config_get_integer ("global", "xfer_progress");
1323 int flush = 0;
1325 if (!(client->flags & FLAG_LOCK_CMD))
1326 rc = unlock_file_mutex (client, 0);
1327 if (rc && rc != GPG_ERR_NOT_LOCKED)
1328 return rc;
1330 progress =
1331 progress > 0 ? (progress / ASSUAN_LINELENGTH) * ASSUAN_LINELENGTH : 0;
1332 to_send = total < ASSUAN_LINELENGTH ? total : ASSUAN_LINELENGTH;
1333 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1335 if (rc)
1336 return rc;
1338 again:
1341 if (sent + to_send > total)
1342 to_send = total - sent;
1344 rc = assuan_send_data (ctx, flush ? NULL : (char *) line + sent,
1345 flush ? 0 : to_send);
1346 if (!rc)
1348 sent += flush ? 0 : to_send;
1350 if ((progress && !(sent % progress) && sent != total) ||
1351 (sent == total && flush))
1352 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1354 if (!flush && !rc && sent == total)
1356 flush = 1;
1357 goto again;
1361 while (!rc && sent < total);
1363 return rc;
1366 static gpg_error_t
1367 do_get (assuan_context_t ctx, char *line)
1369 struct client_s *client = assuan_get_pointer (ctx);
1370 gpg_error_t rc;
1371 struct xml_request_s *req;
1372 xmlNodePtr n;
1374 rc = xml_new_request (client, line, XML_CMD_NONE, &req);
1375 if (rc)
1376 return rc;
1378 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1379 if (!rc)
1381 if (n && n->children)
1383 n = xml_find_text_node (n->children);
1384 if (!n || !n->content || !*n->content)
1385 rc = GPG_ERR_NO_DATA;
1386 else
1387 rc = xfer_data (ctx, (char *) n->content, xmlStrlen (n->content));
1389 else
1390 rc = GPG_ERR_NO_DATA;
1393 xml_free_request (req);
1394 return rc;
1397 static gpg_error_t
1398 get_command (assuan_context_t ctx, char *line)
1400 struct client_s *client = assuan_get_pointer (ctx);
1401 gpg_error_t rc;
1402 struct argv_s *args[] = {
1403 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1404 NULL
1407 rc = parse_options (&line, args, client, 1);
1408 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1409 rc = GPG_ERR_SYNTAX;
1410 if (rc)
1411 return send_error (ctx, rc);
1413 if (client->opts & OPT_INQUIRE)
1415 unsigned char *result;
1416 size_t len;
1418 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1419 if (rc)
1420 return send_error (ctx, rc);
1422 pthread_cleanup_push ((void *)xfree, result);
1423 rc = do_get (ctx, (char *)result);
1424 pthread_cleanup_pop (1);
1426 else
1427 rc = do_get (ctx, line);
1429 return send_error (ctx, rc);
1432 static void list_command_cleanup1 (void *arg);
1433 static gpg_error_t
1434 realpath_command (assuan_context_t ctx, char *line)
1436 gpg_error_t rc;
1437 char **realpath = NULL;
1438 struct client_s *client = assuan_get_pointer (ctx);
1439 struct argv_s *args[] = {
1440 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1441 NULL
1444 rc = parse_options (&line, args, client, 1);
1445 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1446 rc = GPG_ERR_SYNTAX;
1447 if (rc)
1448 return send_error (ctx, rc);
1450 if (client->opts & OPT_INQUIRE)
1452 unsigned char *result;
1453 size_t len;
1455 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1456 if (rc)
1457 return send_error (ctx, rc);
1459 pthread_cleanup_push ((void *)xfree, result);
1460 (void)xml_resolve_path (client, client->doc, result, &realpath, &rc);
1461 pthread_cleanup_pop (1);
1463 else
1464 (void)xml_resolve_path (client, client->doc, (unsigned char *)line,
1465 &realpath, &rc);
1467 if (!rc)
1469 char *tmp = strv_join ("\t", realpath);
1471 strv_free (realpath);
1472 if (!tmp)
1473 return send_error (ctx, GPG_ERR_ENOMEM);
1475 pthread_cleanup_push ((void *)xfree, tmp);
1476 rc = xfer_data (ctx, tmp, strlen (tmp));
1477 pthread_cleanup_pop (1);
1480 return send_error (ctx, rc);
1483 static void
1484 list_command_cleanup1 (void *arg)
1486 if (arg)
1487 string_free ((struct string_s *) arg, 1);
1490 static void
1491 list_command_cleanup2 (void *arg)
1493 struct element_list_s *elements = arg;
1495 if (elements)
1497 if (elements->list)
1499 int total = slist_length (elements->list);
1500 int i;
1502 for (i = 0; i < total; i++)
1504 char *tmp = slist_nth_data (elements->list, i);
1505 xfree (tmp);
1508 slist_free (elements->list);
1511 string_free (elements->prefix, 1);
1512 xfree (elements->target);
1513 xfree (elements);
1517 static gpg_error_t
1518 parse_list_opt_recurse (void *data, void *value)
1520 struct client_s *client = data;
1522 client->opts |= OPT_LIST_RECURSE;
1523 return 0;
1526 static gpg_error_t
1527 parse_opt_verbose (void *data, void *value)
1529 struct client_s *client = data;
1531 client->opts |= OPT_VERBOSE;
1532 return 0;
1535 static gpg_error_t
1536 list_path_once (struct client_s *client, char *line,
1537 struct element_list_s *elements, struct string_s *result)
1539 gpg_error_t rc;
1541 rc = xml_create_path_list (client, client->doc, NULL, elements, line);
1542 if (rc == GPG_ERR_ELOOP || rc == GPG_ERR_EACCES)
1543 rc = 0;
1545 if (!rc)
1547 int total = slist_length (elements->list);
1549 if (total)
1551 int i;
1553 for (i = 0; i < total; i++)
1555 char *tmp = slist_nth_data (elements->list, i);
1557 string_append_printf (result, "%s%s", tmp,
1558 i + 1 == total ? "" : "\n");
1561 else
1562 rc = GPG_ERR_NO_DATA;
1565 return rc;
1568 static gpg_error_t
1569 do_list (assuan_context_t ctx, char *line)
1571 struct client_s *client = assuan_get_pointer (ctx);
1572 gpg_error_t rc = GPG_ERR_NO_DATA;
1573 struct element_list_s *elements = NULL;
1575 if (!line || !*line)
1577 struct string_s *str = string_new (NULL);
1578 xmlNodePtr n;
1580 if (!str)
1581 return GPG_ERR_ENOMEM;
1583 pthread_cleanup_push ((void *)list_command_cleanup1, str);
1584 n = xmlDocGetRootElement (client->doc);
1585 for (n = n->children; n; n = n->next)
1587 xmlChar *name;
1589 if (n->type != XML_ELEMENT_NODE)
1590 continue;
1592 name = xmlGetProp (n, (xmlChar *)"_name");
1593 if (!name)
1595 rc = GPG_ERR_ENOMEM;
1596 break;
1599 elements = xcalloc (1, sizeof (struct element_list_s));
1600 if (!elements)
1602 xmlFree (name);
1603 rc = GPG_ERR_ENOMEM;
1604 break;
1607 elements->prefix = string_new (NULL);
1608 if (!elements->prefix)
1610 xmlFree (name);
1611 list_command_cleanup2 (elements);
1612 rc = GPG_ERR_ENOMEM;
1613 break;
1616 elements->recurse = client->opts & OPT_LIST_RECURSE;
1617 elements->root_only = !elements->recurse;
1618 pthread_cleanup_push ((void *)list_command_cleanup2, elements);
1619 rc = list_path_once (client, (char *)name, elements, str);
1620 xmlFree (name);
1621 pthread_cleanup_pop (1);
1622 if (rc)
1623 break;
1625 if (n->next)
1626 string_append (str, "\n");
1629 if (!rc)
1630 rc = xfer_data (ctx, str->str, str->len);
1632 pthread_cleanup_pop (1);
1633 return rc;
1636 elements = xcalloc (1, sizeof (struct element_list_s));
1637 if (!elements)
1638 return GPG_ERR_ENOMEM;
1640 elements->prefix = string_new (NULL);
1641 if (!elements->prefix)
1643 list_command_cleanup2 (elements);
1644 return GPG_ERR_ENOMEM;
1647 elements->recurse = client->opts & OPT_LIST_RECURSE;
1648 pthread_cleanup_push ((void *)list_command_cleanup2, elements);
1649 struct string_s *str = string_new (NULL);
1650 pthread_cleanup_push ((void *)list_command_cleanup1, str);
1651 rc = list_path_once (client, line, elements, str);
1652 if (!rc)
1653 rc = xfer_data (ctx, str->str, str->len);
1655 pthread_cleanup_pop (1);
1656 pthread_cleanup_pop (1);
1657 return rc;
1660 static gpg_error_t
1661 list_command (assuan_context_t ctx, char *line)
1663 struct client_s *client = assuan_get_pointer (ctx);
1664 gpg_error_t rc;
1665 struct argv_s *args[] = {
1666 &(struct argv_s) {"recurse", OPTION_TYPE_NOARG, parse_list_opt_recurse},
1667 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1668 /* These are deprecated but kept for backward compatibility with older
1669 * clients. */
1670 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, NULL},
1671 &(struct argv_s) {"with-target", OPTION_TYPE_NOARG, NULL},
1672 &(struct argv_s) {"all", OPTION_TYPE_NOARG, parse_list_opt_recurse},
1673 &(struct argv_s) {"no-recurse", OPTION_TYPE_NOARG, NULL},
1674 NULL
1677 if (disable_list_and_dump == 1)
1678 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
1680 rc = parse_options (&line, args, client, 1);
1681 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1682 rc = GPG_ERR_SYNTAX;
1683 if (rc)
1684 return send_error (ctx, rc);
1686 if (client->opts & OPT_INQUIRE)
1688 unsigned char *result;
1689 size_t len;
1691 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1692 if (rc)
1693 return send_error (ctx, rc);
1695 pthread_cleanup_push ((void *)xfree, result);
1696 rc = do_list (ctx, (char *)result);
1697 pthread_cleanup_pop (1);
1699 else
1700 rc = do_list (ctx, line);
1702 return send_error (ctx, rc);
1706 * args[0] - element path
1708 static gpg_error_t
1709 attribute_list (assuan_context_t ctx, char **args)
1711 struct client_s *client = assuan_get_pointer (ctx);
1712 char **attrlist = NULL;
1713 int i = 0;
1714 xmlAttrPtr a;
1715 xmlNodePtr n, an;
1716 char *line;
1717 gpg_error_t rc;
1718 struct xml_request_s *req;
1720 if (!args || !args[0] || !*args[0])
1721 return GPG_ERR_SYNTAX;
1723 rc = xml_new_request (client, args[0], XML_CMD_ATTR_LIST, &req);
1724 if (rc)
1725 return rc;
1727 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1728 xml_free_request (req);
1729 if (rc)
1730 return rc;
1732 for (a = n->properties; a; a = a->next)
1734 char **pa;
1736 pa = xrealloc (attrlist, (i + 2) * sizeof (char *));
1737 if (!pa)
1739 if (attrlist)
1740 strv_free (attrlist);
1742 log_write ("%s(%i): %s", __FILE__, __LINE__,
1743 pwmd_strerror (GPG_ERR_ENOMEM));
1744 return GPG_ERR_ENOMEM;
1747 attrlist = pa;
1748 an = a->children;
1749 attrlist[i] = str_asprintf ("%s %s", (char *) a->name, an && an->content
1750 ? (char *)an->content : "");
1752 if (!attrlist[i])
1754 strv_free (attrlist);
1755 log_write ("%s(%i): %s", __FILE__, __LINE__,
1756 pwmd_strerror (GPG_ERR_ENOMEM));
1757 return GPG_ERR_ENOMEM;
1760 attrlist[++i] = NULL;
1763 if (!attrlist)
1764 return GPG_ERR_NO_DATA;
1766 line = strv_join ("\n", attrlist);
1767 if (!line)
1769 log_write ("%s(%i): %s", __FILE__, __LINE__,
1770 pwmd_strerror (GPG_ERR_ENOMEM));
1771 strv_free (attrlist);
1772 return GPG_ERR_ENOMEM;
1775 pthread_cleanup_push ((void *)xfree, line);
1776 pthread_cleanup_push ((void *)req_cleanup, attrlist);
1777 rc = xfer_data (ctx, line, strlen (line));
1778 pthread_cleanup_pop (1);
1779 pthread_cleanup_pop (1);
1780 return rc;
1784 * args[0] - attribute
1785 * args[1] - element path
1787 static gpg_error_t
1788 attribute_delete (struct client_s *client, char **args)
1790 gpg_error_t rc;
1791 xmlNodePtr n;
1792 struct xml_request_s *req;
1794 if (!args || !args[0] || !*args[0] || !args[1] || !*args[1])
1795 return GPG_ERR_SYNTAX;
1797 if (!strcmp (args[0], "_name") || !strcmp (args[0], "target"))
1798 return GPG_ERR_INV_ATTR;
1800 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
1801 if (rc)
1802 return rc;
1804 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1805 if (!rc && !strcmp (args[0], (char *) "_acl"))
1806 rc = xml_is_element_owner (client, n);
1808 if (!rc)
1809 rc = xml_delete_attribute (client, n, (xmlChar *) args[0]);
1811 xml_free_request (req);
1812 return rc;
1816 * Creates the "target" attribute. When other commands encounter an element
1817 * with this attribute they follow the "target" after appending remaining
1818 * elements from the original element path to the target. The exception is the
1819 * ATTR command that operates on the element itself and not the target.
1821 * If the source element path doesn't exist when using 'ATTR SET target', it is
1822 * created, but the destination element path must exist. This is simliar to the
1823 * ls(1) command: ln -s src dst.
1825 * args[0] - source element path
1826 * args[1] - destination element path
1828 static gpg_error_t
1829 target_attribute (struct client_s *client, char **args)
1831 struct xml_request_s *req = NULL;
1832 char **src, **dst;
1833 gpg_error_t rc;
1834 xmlNodePtr n;
1836 if (!args || !args[0] || !args[1])
1837 return GPG_ERR_SYNTAX;
1839 src = str_split (args[0], "\t", 0);
1840 if (!src)
1841 return GPG_ERR_SYNTAX;
1843 if (!xml_valid_element_path (src, 0))
1845 strv_free (src);
1846 return GPG_ERR_INV_VALUE;
1849 dst = str_split (args[1], "\t", 0);
1850 if (!dst)
1852 strv_free (src);
1853 return GPG_ERR_SYNTAX;
1856 // Be sure the destination element path exists. */
1857 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
1858 if (rc)
1859 goto fail;
1861 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1862 if (rc && rc != GPG_ERR_EACCES)
1863 goto fail;
1865 rc = xml_validate_target (client, req->doc, args[0], n);
1866 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
1867 goto fail;
1869 xml_free_request (req);
1870 req = NULL;
1872 if (!strcmp (args[0], args[1]))
1874 rc = GPG_ERR_EEXIST;
1875 goto fail;
1878 rc = xml_new_request (client, args[0], XML_CMD_ATTR_TARGET, &req);
1879 if (rc)
1880 goto fail;
1882 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1883 if (rc && rc != GPG_ERR_EACCES)
1884 goto fail;
1886 if (!rc)
1888 rc = xml_add_attribute (client, n, "target", args[1]);
1889 if (!rc)
1890 rc = xml_unlink_node (client, n->children);
1894 fail:
1895 strv_free (src);
1896 strv_free (dst);
1897 xml_free_request (req);
1898 return rc;
1902 * args[0] - attribute
1903 * args[1] - element path
1905 static gpg_error_t
1906 attribute_get (assuan_context_t ctx, char **args)
1908 struct client_s *client = assuan_get_pointer (ctx);
1909 xmlNodePtr n;
1910 xmlChar *a;
1911 gpg_error_t rc;
1912 struct xml_request_s *req;
1914 if (!args || !args[0] || !*args[0] || !args[1] || !*args[1])
1915 return GPG_ERR_SYNTAX;
1917 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
1918 if (rc)
1919 return rc;
1921 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1922 xml_free_request (req);
1923 if (rc)
1924 return rc;
1926 a = xmlGetProp (n, (xmlChar *) args[0]);
1927 if (!a)
1928 return GPG_ERR_NOT_FOUND;
1930 pthread_cleanup_push ((void *)xmlFree, a);
1932 if (*a)
1933 rc = xfer_data (ctx, (char *) a, xmlStrlen (a));
1934 else
1935 rc = GPG_ERR_NO_DATA;
1937 pthread_cleanup_pop (1);
1938 return rc;
1942 * args[0] - attribute
1943 * args[1] - element path
1944 * args[2] - value
1946 static gpg_error_t
1947 attribute_set (struct client_s *client, char **args)
1949 struct xml_request_s *req;
1950 gpg_error_t rc;
1951 xmlNodePtr n;
1953 if (!args || !args[0] || !args[1])
1954 return GPG_ERR_SYNTAX;
1957 * Reserved attribute names.
1959 if (!strcmp (args[0], "_name")) // Use the RENAME command instead
1960 return GPG_ERR_INV_ATTR;
1961 else if (!strcmp (args[0], "target"))
1962 return target_attribute (client, args + 1);
1963 else if (!xml_valid_attribute (args[0]))
1964 return GPG_ERR_INV_VALUE;
1966 if (!xml_valid_attribute_value (args[2]))
1967 return GPG_ERR_INV_VALUE;
1969 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
1970 if (rc)
1971 return rc;
1973 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1974 if (!rc)
1976 if (!strcmp (args[0], (char *) "_acl"))
1977 rc = xml_is_element_owner (client, n);
1979 if (!rc)
1980 rc = xml_add_attribute (client, n, args[0], args[2]);
1983 xml_free_request (req);
1984 return rc;
1988 * req[0] - command
1989 * req[1] - attribute name or element path if command is LIST
1990 * req[2] - element path
1991 * req[2] - element path or value
1994 static gpg_error_t
1995 do_attr (assuan_context_t ctx, char *line)
1997 struct client_s *client = assuan_get_pointer (ctx);
1998 gpg_error_t rc = 0;
1999 char **req;
2001 req = str_split (line, " ", 4);
2002 if (!req || !req[0] || !req[1])
2004 strv_free (req);
2005 return GPG_ERR_SYNTAX;
2008 pthread_cleanup_push ((void *)req_cleanup, req);
2010 if (strcasecmp (req[0], "SET") == 0)
2011 rc = attribute_set (client, req + 1);
2012 else if (strcasecmp (req[0], "GET") == 0)
2013 rc = attribute_get (ctx, req + 1);
2014 else if (strcasecmp (req[0], "DELETE") == 0)
2015 rc = attribute_delete (client, req + 1);
2016 else if (strcasecmp (req[0], "LIST") == 0)
2017 rc = attribute_list (ctx, req + 1);
2018 else
2019 rc = GPG_ERR_SYNTAX;
2021 client->flags &= ~(FLAG_ACL_IGNORE|FLAG_ACL_ERROR);
2022 pthread_cleanup_pop (1);
2023 return rc;
2026 static gpg_error_t
2027 attr_command (assuan_context_t ctx, char *line)
2029 struct client_s *client = assuan_get_pointer (ctx);
2030 gpg_error_t rc;
2031 struct argv_s *args[] = {
2032 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2033 NULL
2036 rc = parse_options (&line, args, client, 1);
2037 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2038 rc = GPG_ERR_SYNTAX;
2039 if (rc)
2040 return send_error (ctx, rc);
2042 if (client->opts & OPT_INQUIRE)
2044 unsigned char *result;
2045 size_t len;
2047 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2048 if (rc)
2049 return send_error (ctx, rc);
2051 pthread_cleanup_push ((void *)xfree, result);
2052 rc = do_attr (ctx, (char *)result);
2053 pthread_cleanup_pop (1);
2055 else
2056 rc = do_attr (ctx, line);
2058 return send_error (ctx, rc);
2061 static gpg_error_t
2062 parse_iscached_opt_lock (void *data, void *value)
2064 struct client_s *client = data;
2066 (void) value;
2067 client->opts |= OPT_LOCK;
2068 return 0;
2071 static gpg_error_t
2072 iscached_command (assuan_context_t ctx, char *line)
2074 struct client_s *client = assuan_get_pointer (ctx);
2075 gpg_error_t rc;
2076 struct argv_s *args[] = {
2077 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_iscached_opt_lock},
2078 NULL
2081 if (!line || !*line)
2082 return send_error (ctx, GPG_ERR_SYNTAX);
2084 rc = parse_options (&line, args, client, 1);
2085 if (rc)
2086 return send_error (ctx, rc);
2087 else if (!valid_filename (line))
2088 return send_error (ctx, GPG_ERR_INV_VALUE);
2090 rc = cache_iscached (line, NULL);
2091 if (client->opts & OPT_LOCK
2092 && (!rc || gpg_err_code (rc) == GPG_ERR_NO_DATA))
2094 unsigned char md5file[16];
2095 gpg_error_t trc = rc;
2097 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2098 if (memcmp (md5file, client->md5file, 16))
2099 cleanup_client (client);
2101 memcpy (client->md5file, md5file, 16);
2102 rc = do_lock (client, 1);
2103 if (!rc)
2104 rc = trc;
2107 return send_error (ctx, rc);
2110 static gpg_error_t
2111 clearcache_command (assuan_context_t ctx, char *line)
2113 gpg_error_t rc = 0, all_rc = 0;
2114 unsigned char md5file[16];
2115 int i;
2116 int t;
2117 int all = 0;
2118 struct client_thread_s *once = NULL;
2120 cache_lock ();
2121 MUTEX_LOCK (&cn_mutex);
2122 pthread_cleanup_push ((void *)cleanup_mutex_cb, &cn_mutex);
2124 if (!line || !*line)
2125 all = 1;
2127 t = slist_length (cn_thread_list);
2129 for (i = 0; i < t; i++)
2131 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2132 assuan_peercred_t peer;
2134 if (!thd->cl)
2135 continue;
2137 /* Lock each connected clients' file mutex to prevent any other client
2138 * from accessing the cache entry (the file mutex is locked upon
2139 * command startup). The cache for the entry is not cleared if the
2140 * file mutex is locked by another client to prevent this function
2141 * from blocking.
2143 if (all)
2145 if (thd->cl->filename)
2147 rc = do_validate_peer (ctx, thd->cl->filename, &peer);
2148 all_rc = !all_rc ? rc : all_rc;
2149 if (rc)
2151 rc = 0;
2152 continue;
2156 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0, -1);
2157 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2159 if (pthread_equal (pthread_self (), thd->tid))
2160 rc = 0;
2161 else
2163 if (!thd->cl->filename ||
2164 cache_iscached (thd->cl->filename,
2165 NULL) == GPG_ERR_NO_DATA)
2167 rc = 0;
2168 continue;
2171 cache_defer_clear (thd->cl->md5file);
2174 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
2176 rc = 0;
2177 continue;
2180 if (!rc)
2182 rc = cache_clear (thd->cl->md5file);
2183 cache_unlock_mutex (thd->cl->md5file, 0);
2186 if (rc)
2187 all_rc = rc;
2189 rc = 0;
2191 /* A single data filename was specified. Lock only this data file
2192 * mutex and free the cache entry. */
2193 else
2195 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2196 rc = do_validate_peer (ctx, line, &peer);
2198 if (!rc && !memcmp (thd->cl->md5file, md5file, sizeof (md5file)))
2200 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->md5file, -1, 0,
2201 -1);
2202 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2204 if (pthread_equal (pthread_self (), thd->tid))
2205 rc = 0;
2208 if (!rc)
2210 once = thd;
2211 rc = cache_clear (thd->cl->md5file);
2212 cache_unlock_mutex (thd->cl->md5file, 0);
2214 else
2216 cache_defer_clear (thd->cl->md5file);
2219 break;
2224 /* Only connected clients' cache entries have been cleared. Now clear any
2225 * remaining cache entries without clients but only if there wasn't an
2226 * error from above since this would defeat the locking check of the
2227 * remaining entries. */
2228 if (!all_rc && all)
2230 cache_clear (NULL);
2233 /* No clients are using the specified file. */
2234 else if (!all_rc && !rc && !once)
2236 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, line, strlen (line));
2237 rc = cache_clear (md5file);
2240 /* Release the connection mutex. */
2241 pthread_cleanup_pop (1);
2242 cache_unlock ();
2244 if (!rc)
2245 send_status_all (STATUS_CACHE, NULL);
2247 /* One or more files were locked while clearing all cache entries. */
2248 if (all_rc)
2249 rc = all_rc;
2251 return send_error (ctx, rc);
2254 static gpg_error_t
2255 cachetimeout_command (assuan_context_t ctx, char *line)
2257 int timeout;
2258 char **req = str_split (line, " ", 0);
2259 char *p;
2260 gpg_error_t rc = 0;
2261 assuan_peercred_t peer;
2263 if (!req || !*req || !req[1])
2265 strv_free (req);
2266 return send_error (ctx, GPG_ERR_SYNTAX);
2269 errno = 0;
2270 timeout = (int) strtol (req[1], &p, 10);
2271 if (errno != 0 || *p || timeout < -1)
2273 strv_free (req);
2274 return send_error (ctx, GPG_ERR_SYNTAX);
2277 rc = do_validate_peer (ctx, req[0], &peer);
2278 if (!rc)
2280 unsigned char md5file[16];
2282 gcry_md_hash_buffer (GCRY_MD_MD5, md5file, req[0], strlen (req[0]));
2283 rc = cache_set_timeout (md5file, timeout);
2284 if (!rc || gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
2286 rc = 0;
2287 MUTEX_LOCK (&rcfile_mutex);
2288 config_set_int_param (&global_config, req[0], "cache_timeout",
2289 req[1]);
2290 MUTEX_UNLOCK (&rcfile_mutex);
2294 strv_free (req);
2295 return send_error (ctx, rc);
2298 static gpg_error_t
2299 dump_command (assuan_context_t ctx, char *line)
2301 xmlChar *xml;
2302 int len;
2303 struct client_s *client = assuan_get_pointer (ctx);
2304 gpg_error_t rc;
2306 if (disable_list_and_dump == 1)
2307 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2309 if (line && *line)
2310 return send_error (ctx, GPG_ERR_SYNTAX);
2312 rc = peer_is_invoker(client);
2313 if (rc)
2314 return send_error (ctx, rc);
2316 xmlDocDumpFormatMemory (client->doc, &xml, &len, 1);
2318 if (!xml)
2320 log_write ("%s(%i): %s", __FILE__, __LINE__,
2321 pwmd_strerror (GPG_ERR_ENOMEM));
2322 return send_error (ctx, GPG_ERR_ENOMEM);
2325 pthread_cleanup_push ((void *)xmlFree, xml);
2326 rc = xfer_data (ctx, (char *) xml, len);
2327 pthread_cleanup_pop (1);
2328 return send_error (ctx, rc);
2331 static gpg_error_t
2332 getconfig_command (assuan_context_t ctx, char *line)
2334 struct client_s *client = assuan_get_pointer (ctx);
2335 gpg_error_t rc = 0;
2336 char filename[255] = { 0 }, param[747] = { 0 };
2337 char *p, *tmp = NULL, *fp = client->filename, *paramp = line;
2339 if (!line || !*line)
2340 return send_error (ctx, GPG_ERR_SYNTAX);
2342 if (strchr (line, ' '))
2344 sscanf (line, " %254[^ ] %746c", filename, param);
2345 paramp = param;
2346 fp = filename;
2349 if (fp && !valid_filename (fp))
2350 return send_error (ctx, GPG_ERR_INV_VALUE);
2352 paramp = str_down (paramp);
2353 if (!strcmp (paramp, "passphrase"))
2354 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2356 p = config_get_value (fp ? fp : "global", paramp);
2357 if (!p)
2358 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2360 tmp = expand_homedir (p);
2361 xfree (p);
2362 if (!tmp)
2364 log_write ("%s(%i): %s", __FILE__, __LINE__,
2365 pwmd_strerror (GPG_ERR_ENOMEM));
2366 return send_error (ctx, GPG_ERR_ENOMEM);
2369 p = tmp;
2370 pthread_cleanup_push ((void *)xfree, p);
2371 rc = xfer_data (ctx, p, strlen (p));
2372 pthread_cleanup_pop (1);
2373 return send_error (ctx, rc);
2376 struct xpath_s
2378 xmlXPathContextPtr xp;
2379 xmlXPathObjectPtr result;
2380 xmlBufferPtr buf;
2381 char **req;
2384 static void
2385 xpath_command_cleanup (void *arg)
2387 struct xpath_s *xpath = arg;
2389 if (!xpath)
2390 return;
2392 req_cleanup (xpath->req);
2394 if (xpath->buf)
2395 xmlBufferFree (xpath->buf);
2397 if (xpath->result)
2398 xmlXPathFreeObject (xpath->result);
2400 if (xpath->xp)
2401 xmlXPathFreeContext (xpath->xp);
2404 static gpg_error_t
2405 do_xpath (assuan_context_t ctx, char *line)
2407 gpg_error_t rc;
2408 struct client_s *client = assuan_get_pointer (ctx);
2409 struct xpath_s _x = { 0 };
2410 struct xpath_s *xpath = &_x;
2412 if (!line || !*line)
2413 return GPG_ERR_SYNTAX;
2415 if ((xpath->req = str_split (line, "\t", 2)) == NULL)
2417 if (strv_printf (&xpath->req, "%s", line) == 0)
2418 return GPG_ERR_ENOMEM;
2421 xpath->xp = xmlXPathNewContext (client->doc);
2422 if (!xpath->xp)
2424 rc = GPG_ERR_BAD_DATA;
2425 goto fail;
2428 xpath->result =
2429 xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2430 if (!xpath->result)
2432 rc = GPG_ERR_BAD_DATA;
2433 goto fail;
2436 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2438 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2439 goto fail;
2442 rc = xml_recurse_xpath_nodeset (client, client->doc,
2443 xpath->result->nodesetval,
2444 (xmlChar *) xpath->req[1], &xpath->buf, 0,
2445 NULL);
2446 if (rc)
2447 goto fail;
2448 else if (!xpath->req[1] && !xmlBufferLength (xpath->buf))
2450 rc = GPG_ERR_NO_DATA;
2451 goto fail;
2453 else if (xpath->req[1])
2455 rc = 0;
2456 goto fail;
2459 pthread_cleanup_push ((void *)xpath_command_cleanup, &xpath);
2460 rc = xfer_data (ctx, (char *) xmlBufferContent (xpath->buf),
2461 xmlBufferLength (xpath->buf));
2462 pthread_cleanup_pop (0);
2463 fail:
2464 xpath_command_cleanup (xpath);
2465 return rc;
2468 static gpg_error_t
2469 xpath_command (assuan_context_t ctx, char *line)
2471 struct client_s *client = assuan_get_pointer (ctx);
2472 gpg_error_t rc;
2473 struct argv_s *args[] = {
2474 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2475 NULL
2478 if (disable_list_and_dump == 1)
2479 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2481 rc = peer_is_invoker(client);
2482 if (rc)
2483 return send_error (ctx, rc);
2485 rc = parse_options (&line, args, client, 1);
2486 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2487 rc = GPG_ERR_SYNTAX;
2488 if (rc)
2489 return send_error (ctx, rc);
2491 if (client->opts & OPT_INQUIRE)
2493 unsigned char *result;
2494 size_t len;
2496 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2497 if (rc)
2498 return send_error (ctx, rc);
2500 pthread_cleanup_push ((void *)xfree, result);
2501 rc = do_xpath (ctx, (char *)result);
2502 pthread_cleanup_pop (1);
2504 else
2505 rc = do_xpath (ctx, line);
2507 return send_error (ctx, rc);
2510 static gpg_error_t
2511 do_xpathattr (assuan_context_t ctx, char *line)
2513 struct client_s *client = assuan_get_pointer (ctx);
2514 gpg_error_t rc;
2515 char **req = NULL;
2516 int cmd = 0; //SET
2517 struct xpath_s _x = { 0 };
2518 struct xpath_s *xpath = &_x;
2520 if (!line || !*line)
2521 return GPG_ERR_SYNTAX;
2523 if ((req = str_split (line, " ", 3)) == NULL)
2524 return GPG_ERR_ENOMEM;
2526 if (!req[0])
2528 rc = GPG_ERR_SYNTAX;
2529 goto fail;
2532 if (!strcasecmp (req[0], "SET"))
2533 cmd = 0;
2534 else if (!strcasecmp (req[0], "DELETE"))
2535 cmd = 1;
2536 else
2538 rc = GPG_ERR_SYNTAX;
2539 goto fail;
2542 if (!req[1] || !req[2])
2544 rc = GPG_ERR_SYNTAX;
2545 goto fail;
2548 if ((xpath->req = str_split (req[2], "\t", 3)) == NULL)
2550 rc = GPG_ERR_ENOMEM;
2551 goto fail;
2554 if (!xpath->req[0] || (!xpath->req[1] && !cmd) || (xpath->req[1] && cmd))
2556 rc = GPG_ERR_SYNTAX;
2557 goto fail;
2560 xpath->xp = xmlXPathNewContext (client->doc);
2561 if (!xpath->xp)
2563 rc = GPG_ERR_BAD_DATA;
2564 goto fail;
2567 xpath->result = xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2568 if (!xpath->result)
2570 rc = GPG_ERR_BAD_DATA;
2571 goto fail;
2574 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2576 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2577 goto fail;
2580 rc = xml_recurse_xpath_nodeset (client, client->doc,
2581 xpath->result->nodesetval,
2582 (xmlChar *) xpath->req[1], &xpath->buf, cmd,
2583 (xmlChar *) req[1]);
2585 fail:
2586 xpath_command_cleanup (xpath);
2587 strv_free (req);
2588 return rc;
2591 /* XPATHATTR SET|DELETE <name> <expression>[<TAB>[value]] */
2592 static gpg_error_t
2593 xpathattr_command (assuan_context_t ctx, char *line)
2595 struct client_s *client = assuan_get_pointer (ctx);
2596 gpg_error_t rc;
2597 struct argv_s *args[] = {
2598 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2599 NULL
2602 if (disable_list_and_dump == 1)
2603 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2605 rc = peer_is_invoker(client);
2606 if (rc)
2607 return send_error (ctx, rc);
2609 rc = parse_options (&line, args, client, 1);
2610 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2611 rc = GPG_ERR_SYNTAX;
2612 if (rc)
2613 return send_error (ctx, rc);
2615 if (client->opts & OPT_INQUIRE)
2617 unsigned char *result;
2618 size_t len;
2620 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2621 if (rc)
2622 return send_error (ctx, rc);
2624 pthread_cleanup_push ((void *)xfree, result);
2625 rc = do_xpathattr (ctx, (char *)result);
2626 pthread_cleanup_pop (1);
2628 else
2629 rc = do_xpathattr (ctx, line);
2631 return send_error (ctx, rc);
2634 static gpg_error_t
2635 do_import (struct client_s *client, const char *root_element,
2636 unsigned char *content)
2638 xmlDocPtr doc = NULL;
2639 xmlNodePtr n = NULL, root;
2640 gpg_error_t rc;
2641 struct string_s *str = NULL;
2642 struct xml_request_s *req = NULL;
2644 if (!content || !*content)
2645 return GPG_ERR_SYNTAX;
2647 if (root_element)
2649 rc = xml_new_request (client, root_element, XML_CMD_STORE, &req);
2650 if (rc)
2652 xfree (content);
2653 return rc;
2656 if (!xml_valid_element_path (req->args, 0))
2658 xml_free_request (req);
2659 xfree (content);
2660 return GPG_ERR_INV_VALUE;
2664 str = string_new_content ((char *)content);
2665 str = string_prepend (str, "<pwmd>");
2666 str = string_append (str, "</pwmd>");
2667 doc = xmlReadDoc ((xmlChar *) str->str, NULL, "UTF-8", XML_PARSE_NOBLANKS);
2668 string_free (str, 1);
2669 if (!doc)
2671 rc = GPG_ERR_BAD_DATA;
2672 goto fail;
2675 root = xmlDocGetRootElement (doc);
2676 root = root->children;
2677 if (root->type != XML_ELEMENT_NODE)
2679 rc = GPG_ERR_BAD_DATA;
2680 goto fail;
2683 rc = xml_validate_import (client, root);
2684 if (rc)
2685 goto fail;
2687 if (req)
2689 /* Create the new specified root element path, if needed. */
2690 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc),
2691 &rc);
2692 if (rc)
2693 goto fail;
2695 /* Overwrite the children of the specified root element path. */
2696 xmlUnlinkNode (n->children);
2697 xmlFreeNodeList (n->children);
2698 n->children = NULL;
2700 else
2701 n = xmlDocGetRootElement (client->doc);
2703 if (n)
2705 xmlNodePtr copy;
2706 xmlChar *name = xml_attribute_value (root, (xmlChar *)"_name");
2708 if (!name)
2709 rc = GPG_ERR_BAD_DATA;
2710 else if (!req)
2712 /* No --root argument passed. Overwrite the current documents' root
2713 * element matching the root element of the imported data. */
2714 xml_free_request (req);
2715 req = NULL;
2716 rc = xml_new_request (client, (char *)name, XML_CMD_DELETE, &req);
2717 xmlFree (name);
2718 if (!rc)
2720 xmlNodePtr tmp;
2722 tmp = xml_find_elements (client, req,
2723 xmlDocGetRootElement (req->doc), &rc);
2724 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
2725 goto fail;
2727 if (!rc)
2729 xmlUnlinkNode (tmp);
2730 xmlFreeNodeList (tmp);
2733 rc = 0;
2737 if (!rc)
2739 copy = xmlCopyNodeList (root);
2740 if (!copy)
2741 rc = GPG_ERR_ENOMEM;
2742 else
2744 n = xmlAddChildList (n, copy);
2745 if (!n)
2746 rc = GPG_ERR_ENOMEM;
2751 if (!rc && n && n->parent)
2752 rc = xml_update_element_mtime (client, n->parent);
2754 fail:
2755 xml_free_request (req);
2757 if (doc)
2758 xmlFreeDoc (doc);
2760 return rc;
2763 static gpg_error_t
2764 parse_import_opt_root (void *data, void *value)
2766 struct client_s *client = data;
2768 client->import_root = str_dup (value);
2769 return client->import_root ? 0 : GPG_ERR_ENOMEM;
2772 static gpg_error_t
2773 import_command (assuan_context_t ctx, char *line)
2775 gpg_error_t rc;
2776 struct client_s *client = assuan_get_pointer (ctx);
2777 unsigned char *result;
2778 size_t len;
2779 struct argv_s *args[] = {
2780 &(struct argv_s) {"root", OPTION_TYPE_ARG, parse_import_opt_root},
2781 NULL
2784 xfree (client->import_root);
2785 client->import_root = NULL;
2786 rc = parse_options (&line, args, client, 0);
2787 if (rc)
2788 return send_error (ctx, rc);
2790 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2791 if (rc)
2793 xfree (client->import_root);
2794 client->import_root = NULL;
2795 return send_error (ctx, rc);
2798 rc = do_import (client, client->import_root, result);
2799 xfree (client->import_root);
2800 client->import_root = NULL;
2801 return send_error (ctx, rc);
2804 static gpg_error_t
2805 do_lock (struct client_s *client, int add)
2807 gpg_error_t rc = lock_file_mutex (client, add);
2809 if (!rc)
2810 client->flags |= FLAG_LOCK_CMD;
2812 return rc;
2815 static gpg_error_t
2816 lock_command (assuan_context_t ctx, char *line)
2818 struct client_s *client = assuan_get_pointer (ctx);
2819 gpg_error_t rc;
2821 if (line && *line)
2822 return send_error (ctx, GPG_ERR_SYNTAX);
2824 rc = do_lock (client, 0);
2825 return send_error (ctx, rc);
2828 static gpg_error_t
2829 unlock_command (assuan_context_t ctx, char *line)
2831 struct client_s *client = assuan_get_pointer (ctx);
2832 gpg_error_t rc;
2834 if (line && *line)
2835 return send_error (ctx, GPG_ERR_SYNTAX);
2837 rc = unlock_file_mutex (client, 0);
2838 return send_error (ctx, rc);
2841 static void
2842 get_set_env (const char *name, const char *value)
2844 if (value && *value)
2845 setenv (name, value, 1);
2846 else
2847 unsetenv (name);
2850 static gpg_error_t
2851 option_command (assuan_context_t ctx, char *line)
2853 struct client_s *client = assuan_get_pointer (ctx);
2854 gpg_error_t rc = 0;
2855 char namebuf[255] = { 0 };
2856 char *name = namebuf;
2857 char *value = NULL, *p, *tmp = NULL;
2859 p = strchr (line, '=');
2860 if (!p)
2862 strncpy (namebuf, line, sizeof(namebuf));
2863 namebuf[sizeof(namebuf)-1] = 0;
2865 else
2867 strncpy (namebuf, line, strlen (line)-strlen (p));
2868 namebuf[sizeof(namebuf)-1] = 0;
2869 value = p+1;
2872 log_write2 ("OPTION name='%s' value='%s'", name, value);
2874 if (strcasecmp (name, (char *) "lock-timeout") == 0)
2876 long n = 0;
2878 if (value)
2880 n = strtol (value, &tmp, 10);
2881 if (tmp && *tmp)
2882 return send_error (ctx, GPG_ERR_INV_VALUE);
2885 client->lock_timeout = n;
2887 else if (strcasecmp (name, (char *) "NAME") == 0)
2889 if (value && strchr (value, ' '))
2890 rc = GPG_ERR_INV_VALUE;
2891 else
2893 tmp = pthread_getspecific (thread_name_key);
2894 xfree (tmp);
2895 MUTEX_LOCK (&cn_mutex);
2896 xfree (client->thd->name);
2897 client->thd->name = NULL;
2899 if (!value || !*value)
2900 pthread_setspecific (thread_name_key, str_dup (""));
2901 else
2903 client->thd->name = str_dup (value);
2904 pthread_setspecific (thread_name_key, str_dup (value));
2907 MUTEX_UNLOCK (&cn_mutex);
2910 else if (strcasecmp (name, "disable-pinentry") == 0)
2912 int n = 1;
2914 if (value && *value)
2916 n = (int) strtol (value, &tmp, 10);
2917 if (*tmp || n < 0 || n > 1)
2918 return send_error (ctx, GPG_ERR_INV_VALUE);
2921 if (n)
2922 client->flags |= FLAG_NO_PINENTRY;
2923 else
2924 client->flags &= ~FLAG_NO_PINENTRY;
2926 else if (strcasecmp (name, "ttyname") == 0)
2928 get_set_env ("GPG_TTY", value);
2930 else if (strcasecmp (name, "ttytype") == 0)
2932 get_set_env ("TERM", value);
2934 else if (strcasecmp (name, "display") == 0)
2936 get_set_env ("DISPLAY", value);
2938 else if (strcasecmp (name, "lc_messages") == 0)
2941 else if (strcasecmp (name, "lc_ctype") == 0)
2944 else if (strcasecmp (name, "desc") == 0)
2947 else if (strcasecmp (name, "pinentry-timeout") == 0)
2950 else
2951 rc = GPG_ERR_UNKNOWN_OPTION;
2953 return send_error (ctx, rc);
2956 static gpg_error_t
2957 do_rename (assuan_context_t ctx, char *line)
2959 struct client_s *client = assuan_get_pointer (ctx);
2960 char **args, *p;
2961 xmlNodePtr src, dst;
2962 struct string_s *str = NULL, *tstr;
2963 struct xml_request_s *req;
2964 gpg_error_t rc;
2966 args = str_split (line, " ", 0);
2967 if (!args || strv_length (args) != 2)
2969 strv_free (args);
2970 return GPG_ERR_SYNTAX;
2973 if (!xml_valid_element ((xmlChar *) args[1]))
2975 strv_free (args);
2976 return GPG_ERR_INV_VALUE;
2979 rc = xml_new_request (client, args[0], XML_CMD_RENAME, &req);
2980 if (rc)
2982 strv_free (args);
2983 return rc;
2986 src = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2987 if (rc)
2988 goto fail;
2990 rc = xml_is_element_owner (client, src);
2991 if (rc)
2992 goto fail;
2994 xmlChar *a = xmlGetProp (src, (xmlChar *) "_name");
2995 if (!a)
2997 rc = GPG_ERR_ENOMEM;
2998 goto fail;
3001 /* To prevent unwanted effects:
3003 * <element _name="a"><element _name="b"/></element>
3005 * RENAME a<TAB>b b
3007 if (xmlStrEqual (a, (xmlChar *) args[1]))
3009 xmlFree (a);
3010 rc = GPG_ERR_AMBIGUOUS_NAME;
3011 goto fail;
3014 xmlFree (a);
3015 str = string_new (args[0]);
3016 if (!str)
3018 rc = GPG_ERR_ENOMEM;
3019 goto fail;
3022 p = strrchr (str->str, '\t');
3023 if (p)
3024 tstr = string_truncate (str, strlen (str->str)-strlen (p));
3025 else
3026 tstr = string_truncate (str, 0);
3028 if (!tstr)
3030 string_free (str, 1);
3031 rc = GPG_ERR_ENOMEM;
3032 goto fail;
3035 str = tstr;
3036 tstr = string_append_printf (str, "%s%s", str->len ? "\t" : "", args[1]);
3037 if (!tstr)
3039 string_free (str, 1);
3040 rc = GPG_ERR_ENOMEM;
3041 goto fail;
3044 str = tstr;
3045 xml_free_request (req);
3046 rc = xml_new_request (client, str->str, XML_CMD_RENAME, &req);
3047 string_free (str, 1);
3048 if (rc)
3050 req = NULL;
3051 goto fail;
3054 dst = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3055 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3056 goto fail;
3058 rc = 0;
3060 /* Target may exist:
3062 * <element _name="a"/>
3063 * <element _name="b" target="a"/>
3065 * RENAME b a
3067 if (src == dst)
3069 rc = GPG_ERR_AMBIGUOUS_NAME;
3070 goto fail;
3073 if (dst)
3075 rc = xml_is_element_owner (client, dst);
3076 if (rc)
3077 goto fail;
3079 rc = xml_add_attribute (client, src, "_name", args[1]);
3080 if (!rc)
3081 xml_unlink_node (client, dst);
3083 else
3084 rc = xml_add_attribute (client, src, "_name", args[1]);
3086 fail:
3087 xml_free_request (req);
3088 strv_free (args);
3089 return rc;
3092 static gpg_error_t
3093 rename_command (assuan_context_t ctx, char *line)
3095 struct client_s *client = assuan_get_pointer (ctx);
3096 gpg_error_t rc;
3097 struct argv_s *args[] = {
3098 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3099 NULL
3102 rc = parse_options (&line, args, client, 1);
3103 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3104 rc = GPG_ERR_SYNTAX;
3105 if (rc)
3106 return send_error (ctx, rc);
3108 if (client->opts & OPT_INQUIRE)
3110 unsigned char *result;
3111 size_t len;
3113 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3114 if (rc)
3115 return send_error (ctx, rc);
3117 pthread_cleanup_push ((void *)xfree, result);
3118 rc = do_rename (ctx, (char *)result);
3119 pthread_cleanup_pop (1);
3121 else
3122 rc = do_rename (ctx, line);
3124 return send_error (ctx, rc);
3127 static gpg_error_t
3128 do_copy (assuan_context_t ctx, char *line)
3130 struct client_s *client = assuan_get_pointer (ctx);
3131 char **args, **targs;
3132 xmlNodePtr src, dst, tree = NULL;
3133 struct xml_request_s *req;
3134 gpg_error_t rc;
3136 args = str_split (line, " ", 0);
3137 if (!args || strv_length (args) != 2)
3139 strv_free (args);
3140 return GPG_ERR_SYNTAX;
3143 targs = str_split (args[1], "\t", 0);
3144 if (!targs)
3146 strv_free (args);
3147 return GPG_ERR_ENOMEM;
3150 if (!xml_valid_element_path (targs, 0))
3152 strv_free (args);
3153 strv_free (targs);
3154 return GPG_ERR_INV_VALUE;
3156 strv_free (targs);
3158 rc = xml_new_request (client, args[0], XML_CMD_NONE, &req);
3159 if (rc)
3161 strv_free (args);
3162 return rc;
3165 src = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3166 if (rc)
3167 goto fail;
3169 tree = xmlCopyNodeList (src);
3170 if (!tree)
3172 rc = GPG_ERR_ENOMEM;
3173 goto fail;
3176 xml_free_request (req);
3177 /* Create the destination element path if it does not exist. */
3178 rc = xml_new_request (client, args[1], XML_CMD_STORE, &req);
3179 if (rc)
3181 req = NULL;
3182 goto fail;
3185 dst = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3186 if (rc)
3187 goto fail;
3189 rc = xml_is_element_owner (client, dst);
3190 if (rc)
3191 goto fail;
3193 /* Merge any attributes from the src node to the initial dst node. */
3194 for (xmlAttrPtr attr = tree->properties; attr; attr = attr->next)
3196 if (xmlStrEqual (attr->name, (xmlChar *) "_name"))
3197 continue;
3199 xmlAttrPtr a = xmlHasProp (dst, attr->name);
3200 if (a)
3201 xmlRemoveProp (a);
3203 xmlChar *tmp = xmlNodeGetContent (attr->children);
3204 xmlNewProp (dst, attr->name, tmp);
3205 xmlFree (tmp);
3206 /* Create the default attributes. */
3207 rc = xml_add_attribute (client, dst, NULL, NULL);
3210 xmlNodePtr n = dst->children;
3211 xmlUnlinkNode (n);
3212 xmlFreeNodeList (n);
3213 dst->children = NULL;
3215 if (tree->children)
3217 n = xmlCopyNodeList (tree->children);
3218 if (!n)
3220 rc = GPG_ERR_ENOMEM;
3221 goto fail;
3224 n = xmlAddChildList (dst, n);
3225 if (!n)
3227 rc = GPG_ERR_ENOMEM;
3228 goto fail;
3231 rc = xml_update_element_mtime (client, xmlDocGetRootElement (client->doc)
3232 == dst->parent ? dst : dst->parent);
3235 fail:
3236 if (tree)
3238 xmlUnlinkNode (tree);
3239 xmlFreeNodeList (tree);
3242 xml_free_request (req);
3243 strv_free (args);
3244 return rc;
3247 static gpg_error_t
3248 copy_command (assuan_context_t ctx, char *line)
3250 struct client_s *client = assuan_get_pointer (ctx);
3251 gpg_error_t rc;
3252 struct argv_s *args[] = {
3253 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3254 NULL
3257 rc = parse_options (&line, args, client, 1);
3258 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3259 rc = GPG_ERR_SYNTAX;
3260 if (rc)
3261 return send_error (ctx, rc);
3263 if (client->opts & OPT_INQUIRE)
3265 unsigned char *result;
3266 size_t len;
3268 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3269 if (rc)
3270 return send_error (ctx, rc);
3272 pthread_cleanup_push ((void *)xfree, result);
3273 rc = do_copy (ctx, (char *)result);
3274 pthread_cleanup_pop (1);
3276 else
3277 rc = do_copy (ctx, line);
3279 return send_error (ctx, rc);
3282 static gpg_error_t
3283 do_move (assuan_context_t ctx, char *line)
3285 struct client_s *client = assuan_get_pointer (ctx);
3286 char **args;
3287 xmlNodePtr src, dst;
3288 struct xml_request_s *req;
3289 gpg_error_t rc;
3291 args = str_split (line, " ", 0);
3292 if (!args || strv_length (args) != 2)
3294 strv_free (args);
3295 return GPG_ERR_SYNTAX;
3298 if (*args[1])
3300 char **targs = str_split (args[1], "\t", 0);
3301 if (!targs)
3303 strv_free (args);
3304 return GPG_ERR_ENOMEM;
3307 if (!xml_valid_element_path (targs, 0))
3309 strv_free (targs);
3310 strv_free (args);
3311 return GPG_ERR_INV_VALUE;
3314 strv_free (targs);
3317 rc = xml_new_request (client, args[0], XML_CMD_MOVE, &req);
3318 if (rc)
3320 strv_free (args);
3321 return rc;
3324 src = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3325 if (rc)
3326 goto fail;
3328 rc = xml_is_element_owner (client, src);
3329 if (rc)
3330 goto fail;
3332 xml_free_request (req);
3333 req = NULL;
3334 if (*args[1])
3336 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
3337 if (rc)
3338 goto fail;
3340 dst = xml_find_elements (client, req, xmlDocGetRootElement (req->doc),
3341 &rc);
3343 else
3344 dst = xmlDocGetRootElement (client->doc);
3346 if (rc)
3347 goto fail;
3349 rc = 0;
3351 for (xmlNodePtr n = dst; n; n = n->parent)
3353 if (n == src)
3355 rc = GPG_ERR_CONFLICT;
3356 goto fail;
3360 if (dst)
3362 xmlChar *a = xml_attribute_value (src, (xmlChar *) "_name");
3363 xmlNodePtr dup = xml_find_element (client, dst->children, (char *) a,
3364 NULL, &rc);
3366 xmlFree (a);
3367 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3368 goto fail;
3370 rc = 0;
3372 if (dup)
3374 if (dup == src)
3376 rc = GPG_ERR_CONFLICT;
3377 goto fail;
3380 if (dst == xmlDocGetRootElement (client->doc))
3382 xmlNodePtr n = src;
3383 int match = 0;
3385 while (n->parent && n->parent != dst)
3386 n = n->parent;
3388 xmlChar *a = xml_attribute_value (n, (xmlChar *) "_name");
3389 xmlChar *b = xml_attribute_value (src, (xmlChar *) "_name");
3391 if (xmlStrEqual (a, b))
3393 match = 1;
3394 xmlUnlinkNode (src);
3395 xmlUnlinkNode (n);
3396 xmlFreeNodeList (n);
3399 xmlFree (a);
3400 xmlFree (b);
3402 if (!match)
3404 xmlUnlinkNode (dup);
3405 xmlFreeNodeList (dup);
3408 else
3409 xmlUnlinkNode (dup);
3413 if (!dst && *req->args)
3415 struct xml_request_s *nreq = NULL;
3416 xmlChar *name = xml_attribute_value (src, (xmlChar *) "_name");
3418 if (src->parent == xmlDocGetRootElement (client->doc)
3419 && !strcmp ((char *) name, *req->args))
3421 xmlFree (name);
3422 rc = GPG_ERR_CONFLICT;
3423 goto fail;
3426 xmlFree (name);
3427 rc = xml_new_request (client, args[1], XML_CMD_STORE, &nreq);
3428 if (!rc)
3430 dst = xml_find_elements (client, nreq,
3431 xmlDocGetRootElement (nreq->doc), &rc);
3432 xml_free_request (nreq);
3435 if (rc)
3436 goto fail;
3439 xml_update_element_mtime (client, src->parent);
3440 xmlUnlinkNode (src);
3442 dst = xmlAddChildList (dst, src);
3443 if (!dst)
3444 rc = GPG_ERR_ENOMEM;
3445 else
3446 xml_update_element_mtime (client, dst->parent);
3448 fail:
3449 xml_free_request (req);
3450 strv_free (args);
3451 return rc;
3454 static gpg_error_t
3455 move_command (assuan_context_t ctx, char *line)
3457 struct client_s *client = assuan_get_pointer (ctx);
3458 gpg_error_t rc;
3459 struct argv_s *args[] = {
3460 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3461 NULL
3464 rc = parse_options (&line, args, client, 1);
3465 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3466 rc = GPG_ERR_SYNTAX;
3467 if (rc)
3468 return send_error (ctx, rc);
3470 if (client->opts & OPT_INQUIRE)
3472 unsigned char *result;
3473 size_t len;
3475 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3476 if (rc)
3477 return send_error (ctx, rc);
3479 pthread_cleanup_push ((void *)xfree, result);
3480 rc = do_move (ctx, (char *)result);
3481 pthread_cleanup_pop (1);
3483 else
3484 rc = do_move (ctx, line);
3486 return send_error (ctx, rc);
3489 static gpg_error_t
3490 ls_command (assuan_context_t ctx, char *line)
3492 gpg_error_t rc;
3493 char *tmp;
3494 char *dir;
3495 DIR *d;
3497 if (line && *line)
3498 return send_error (ctx, GPG_ERR_SYNTAX);
3500 tmp = str_asprintf ("%s/data", homedir);
3501 dir = expand_homedir (tmp);
3502 xfree (tmp);
3503 d = opendir (dir);
3504 rc = gpg_error_from_errno (errno);
3506 if (!d)
3508 xfree (dir);
3509 return send_error (ctx, rc);
3512 size_t len =
3513 offsetof (struct dirent, d_name) +pathconf (dir, _PC_NAME_MAX) + 1;
3514 struct dirent *p = xmalloc (len), *cur = NULL;
3515 char *list = NULL;
3517 xfree (dir);
3518 pthread_cleanup_push ((void *)xfree, p);
3519 pthread_cleanup_push ((void *)(void *)(void *)closedir, d);
3520 rc = 0;
3522 while (!readdir_r (d, p, &cur) && cur)
3524 struct stat st;
3526 if (stat (cur->d_name, &st) == -1 || !S_ISREG (st.st_mode))
3527 continue;
3529 tmp = str_asprintf ("%s%s\n", list ? list : "", cur->d_name);
3531 if (!tmp)
3533 if (list)
3534 xfree (list);
3536 rc = GPG_ERR_ENOMEM;
3537 break;
3540 xfree (list);
3541 list = tmp;
3544 pthread_cleanup_pop (1); // closedir (d)
3545 pthread_cleanup_pop (1); // xfree (p)
3547 if (rc)
3548 return send_error (ctx, rc);
3550 if (!list)
3551 return send_error (ctx, GPG_ERR_NO_DATA);
3553 list[strlen (list) - 1] = 0;
3554 pthread_cleanup_push ((void *)xfree, list);
3555 rc = xfer_data (ctx, list, strlen (list));
3556 pthread_cleanup_pop (1);
3557 return send_error (ctx, rc);
3560 static gpg_error_t
3561 bye_notify (assuan_context_t ctx, char *line)
3563 struct client_s *cl = assuan_get_pointer (ctx);
3565 cl->thd->state = CLIENT_STATE_DISCON;
3567 #ifdef WITH_GNUTLS
3568 if (cl->thd->remote)
3570 int rc;
3574 struct timeval tv = { 0, 50000 };
3576 rc = gnutls_bye (cl->thd->tls->ses, GNUTLS_SHUT_RDWR);
3577 if (rc == GNUTLS_E_AGAIN)
3578 select (0, NULL, NULL, NULL, &tv);
3580 while (rc == GNUTLS_E_AGAIN);
3582 #endif
3584 /* This will let assuan_process_next() return. */
3585 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
3587 cl->last_rc = gpg_error_from_errno (errno);
3588 return cl->last_rc;
3591 cl->last_rc = 0; // BYE command result
3592 return 0;
3595 static gpg_error_t
3596 reset_notify (assuan_context_t ctx, char *line)
3598 struct client_s *client = assuan_get_pointer (ctx);
3600 if (client)
3601 cleanup_client (client);
3603 return 0;
3607 * This is called before every Assuan command.
3609 static gpg_error_t
3610 command_startup (assuan_context_t ctx, const char *name)
3612 struct client_s *client = assuan_get_pointer (ctx);
3613 gpg_error_t rc;
3614 struct command_table_s *cmd = NULL;
3616 log_write2 ("command='%s'", name);
3617 client->last_rc = client->opts = 0;
3619 for (int i = 0; command_table[i]; i++)
3621 if (!strcasecmp (name, command_table[i]->name))
3623 if (command_table[i]->ignore_startup)
3624 return 0;
3625 cmd = command_table[i];
3626 break;
3630 if (!cmd)
3631 return GPG_ERR_UNKNOWN_COMMAND;
3633 client->last_rc = rc = gpg_error (file_modified (client, cmd));
3634 if (!rc)
3635 update_client_state (client, CLIENT_STATE_COMMAND);
3637 return rc;
3641 * This is called after every Assuan command.
3643 static void
3644 command_finalize (assuan_context_t ctx, gpg_error_t rc)
3646 struct client_s *client = assuan_get_pointer (ctx);
3648 if (!(client->flags & FLAG_LOCK_CMD))
3649 unlock_file_mutex (client, 0);
3651 unlock_flock (&client->flock_fd);
3652 log_write2 (_("command completed: rc=%u"), rc ? rc : client->last_rc);
3653 client->last_rc = gpg_error (GPG_ERR_UNKNOWN_COMMAND);
3654 #ifdef WITH_GNUTLS
3655 client->thd->buffer_timeout = client->thd->last_buffer_size = 0;
3656 #endif
3657 update_client_state (client, CLIENT_STATE_IDLE);
3660 static gpg_error_t
3661 parse_help_opt_html (void *data, void *value)
3663 struct client_s *client = data;
3665 (void) value;
3666 client->opts |= OPT_HTML;
3667 return 0;
3670 static gpg_error_t
3671 help_command (assuan_context_t ctx, char *line)
3673 gpg_error_t rc;
3674 int i;
3675 struct client_s *client = assuan_get_pointer (ctx);
3676 struct argv_s *args[] = {
3677 &(struct argv_s) {"html", OPTION_TYPE_NOARG, parse_help_opt_html},
3678 NULL
3681 rc = parse_options (&line, args, client, 1);
3682 if (rc)
3683 return send_error (ctx, rc);
3685 if (!line || !*line)
3687 char *tmp;
3688 char *help = str_dup (_("Usage: HELP [--html] [<COMMAND>]\n"
3689 "For commands that take an element path as an argument, each element is "
3690 "separated with an ASCII @key{TAB} character (ASCII 0x09)."
3691 "@*@*COMMANDS:"));
3693 for (i = 0; command_table[i]; i++)
3695 if (!command_table[i]->help)
3696 continue;
3698 /* @npxref{} won't put a "See " or "see " in front of the command.
3699 * It's not a texinfo command but needed for --html. */
3700 tmp = str_asprintf ("%s %s%s%s", help,
3701 client->opts & OPT_HTML ? "@npxref{" : "",
3702 command_table[i]->name,
3703 client->opts & OPT_HTML ? "}" : "");
3704 xfree (help);
3705 help = tmp;
3708 tmp = strip_texi_and_wrap (help, client->opts & OPT_HTML);
3709 xfree (help);
3710 pthread_cleanup_push ((void *)xfree, tmp);
3711 rc = xfer_data (ctx, tmp, strlen (tmp));
3712 pthread_cleanup_pop (1);
3713 return send_error (ctx, rc);
3716 for (i = 0; command_table[i]; i++)
3718 if (!strcasecmp (line, command_table[i]->name))
3720 char *help, *tmp;
3722 if (!command_table[i]->help)
3723 break;
3725 help = strip_texi_and_wrap (command_table[i]->help,
3726 client->opts & OPT_HTML);
3727 tmp = str_asprintf ("%s%s",
3728 (client->opts & OPT_HTML) ? "" : _("Usage: "),
3729 help);
3730 xfree (help);
3731 pthread_cleanup_push ((void *)xfree, tmp);
3732 rc = xfer_data (ctx, tmp, strlen (tmp));
3733 pthread_cleanup_pop (1);
3734 return send_error (ctx, rc);
3738 return send_error (ctx, GPG_ERR_INV_NAME);
3741 static void
3742 new_command (const char *name, int ignore, int unlock, int flock_type,
3743 gpg_error_t (*handler) (assuan_context_t, char *),
3744 const char *help)
3746 int i = 0;
3747 struct command_table_s **tmp;
3749 if (command_table)
3750 for (i = 0; command_table[i]; i++);
3752 tmp = xrealloc (command_table, (i + 2) * sizeof (struct command_table_s *));
3753 assert (tmp);
3754 command_table = tmp;
3755 command_table[i] = xcalloc (1, sizeof (struct command_table_s));
3756 command_table[i]->name = name;
3757 command_table[i]->handler = handler;
3758 command_table[i]->ignore_startup = ignore;
3759 command_table[i]->unlock = unlock;
3760 command_table[i]->flock_type = flock_type;
3761 command_table[i++]->help = help;
3762 command_table[i] = NULL;
3765 void
3766 deinit_commands ()
3768 int i;
3770 for (i = 0; command_table[i]; i++)
3771 xfree (command_table[i]);
3773 xfree (command_table);
3776 static int
3777 sort_commands (const void *arg1, const void *arg2)
3779 struct command_table_s *const *a = arg1;
3780 struct command_table_s *const *b = arg2;
3782 if (!*a || !*b)
3783 return 0;
3784 else if (*a && !*b)
3785 return 1;
3786 else if (!*a && *b)
3787 return -1;
3789 return strcmp ((*a)->name, (*b)->name);
3792 static gpg_error_t
3793 passwd_command (assuan_context_t ctx, char *line)
3795 struct client_s *client = assuan_get_pointer (ctx);
3796 gpg_error_t rc;
3798 rc = peer_is_invoker (client);
3799 if (rc == GPG_ERR_EACCES)
3800 return send_error (ctx, GPG_ERR_FORBIDDEN);
3801 else if (rc)
3802 return send_error (ctx, rc);
3804 if (client->flags & FLAG_NEW)
3805 return send_error (ctx, GPG_ERR_INV_STATE);
3807 rc = crypto_init_ctx (client->crypto, client->flags & FLAG_NO_PINENTRY);
3808 if (rc)
3809 return send_error (ctx, rc);
3811 if (!rc)
3812 rc = crypto_passwd (client, client->crypto);
3814 crypto_cleanup_non_keys (client->crypto);
3815 return send_error (ctx, rc);
3818 static gpg_error_t
3819 parse_opt_data (void *data, void *value)
3821 struct client_s *client = data;
3823 (void) value;
3824 client->opts |= OPT_DATA;
3825 return 0;
3828 static gpg_error_t
3829 send_client_list (assuan_context_t ctx)
3831 struct client_s *client = assuan_get_pointer (ctx);
3832 gpg_error_t rc = 0;
3834 if (client->opts & OPT_VERBOSE)
3836 unsigned i, t;
3837 char **list = NULL;
3838 char *line;
3840 MUTEX_LOCK (&cn_mutex);
3841 pthread_cleanup_push ((void *)cleanup_mutex_cb, &cn_mutex);
3842 t = slist_length (cn_thread_list);
3844 for (i = 0; i < t; i++)
3846 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
3847 char *tmp;
3849 if (thd->state == CLIENT_STATE_UNKNOWN)
3850 continue;
3852 tmp = build_client_info_line (thd, 0);
3853 if (tmp)
3855 char **l = strv_cat (list, tmp);
3856 if (!l)
3857 rc = GPG_ERR_ENOMEM;
3858 else
3859 list = l;
3861 else
3862 rc = GPG_ERR_ENOMEM;
3864 if (rc)
3866 strv_free (list);
3867 break;
3871 pthread_cleanup_pop (1);
3872 if (rc)
3873 return rc;
3875 line = strv_join ("\n", list);
3876 strv_free (list);
3877 pthread_cleanup_push ((void *)xfree, line);
3878 rc = xfer_data (ctx, line, strlen (line));
3879 pthread_cleanup_pop (1);
3880 return rc;
3883 if (client->opts & OPT_DATA)
3885 char buf[ASSUAN_LINELENGTH];
3887 MUTEX_LOCK (&cn_mutex);
3888 pthread_cleanup_push ((void *)cleanup_mutex_cb, &cn_mutex);
3889 snprintf (buf, sizeof (buf), "%u", slist_length (cn_thread_list));
3890 pthread_cleanup_pop (1);
3891 rc = xfer_data (ctx, buf, strlen (buf));
3893 else
3894 rc = send_status (ctx, STATUS_CLIENTS, NULL);
3896 return rc;
3899 static gpg_error_t
3900 getinfo_command (assuan_context_t ctx, char *line)
3902 struct client_s *client = assuan_get_pointer (ctx);
3903 gpg_error_t rc;
3904 char buf[ASSUAN_LINELENGTH];
3905 struct argv_s *args[] = {
3906 &(struct argv_s) {"data", OPTION_TYPE_NOARG, parse_opt_data},
3907 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_opt_verbose},
3908 NULL
3911 rc = parse_options (&line, args, client, 1);
3912 if (rc)
3913 return send_error (ctx, rc);
3915 if (!strcasecmp (line, "clients"))
3917 rc = send_client_list (ctx);
3919 else if (!strcasecmp (line, "cache"))
3921 if (client->opts & OPT_DATA)
3923 snprintf (buf, sizeof (buf), "%u", cache_file_count ());
3924 rc = xfer_data (ctx, buf, strlen (buf));
3926 else
3927 rc = send_status (ctx, STATUS_CACHE, NULL);
3929 else if (!strcasecmp (line, "pid"))
3931 char buf[32];
3932 pid_t pid = getpid ();
3934 snprintf (buf, sizeof (buf), "%i", pid);
3935 rc = xfer_data (ctx, buf, strlen (buf));
3937 else if (!strcasecmp (line, "version"))
3939 char *buf = str_asprintf ("0x%06x %s", VERSION_HEX,
3940 #ifdef WITH_GNUTLS
3941 "GNUTLS "
3942 #endif
3943 #ifdef WITH_LIBACL
3944 "ACL "
3945 #endif
3946 "");
3947 rc = xfer_data (ctx, buf, strlen (buf));
3948 xfree (buf);
3950 else if (!strcasecmp (line, "last_error"))
3952 if (client->last_error)
3953 rc = xfer_data (ctx, client->last_error, strlen (client->last_error));
3954 else
3955 rc = GPG_ERR_NO_DATA;
3957 else if (!strcasecmp (line, "user"))
3959 char *user = NULL;
3961 #ifdef WITH_GNUTLS
3962 if (client->thd->remote)
3963 user = str_asprintf ("#%s", client->thd->tls->fp);
3964 else
3965 user = get_username (client->thd->peer->uid);
3966 #else
3967 user = get_username (client->thd->peer->uid);
3968 #endif
3969 if (user)
3971 pthread_cleanup_push ((void *)xfree, user);
3972 rc = xfer_data (ctx, user, strlen (user));
3973 pthread_cleanup_pop (1);
3975 else
3976 rc = GPG_ERR_NO_DATA;
3978 else
3979 rc = gpg_error (GPG_ERR_SYNTAX);
3981 return send_error (ctx, rc);
3984 static gpg_error_t
3985 parse_listkeys_opt_secret_only (void *data, void *value)
3987 struct client_s *client = data;
3989 (void) value;
3990 client->opts |= OPT_SECRET_ONLY;
3991 return 0;
3994 static gpg_error_t
3995 keyinfo_command (assuan_context_t ctx, char *line)
3997 struct client_s *client = assuan_get_pointer (ctx);
3998 gpg_error_t rc = 0;
3999 char **keys = NULL, **p = NULL;
4000 int sym = 0;
4002 if (line && *line)
4003 return send_error (ctx, GPG_ERR_SYNTAX);
4005 if (!(client->flags & FLAG_OPEN))
4006 return send_error (ctx, GPG_ERR_INV_STATE);
4008 if (client->flags & FLAG_NEW)
4009 return send_error (ctx, GPG_ERR_NO_DATA);
4011 rc = lock_flock (ctx, client->filename, FLOCK_TYPE_SH, &client->flock_fd);
4012 if (rc)
4013 return send_error (ctx, rc);
4015 rc = crypto_is_symmetric (client->filename);
4016 unlock_flock (&client->flock_fd);
4017 if (!rc)
4018 sym = 1;
4019 else if (rc != GPG_ERR_BAD_DATA)
4020 return send_error (ctx, rc);
4022 rc = 0;
4023 if (!sym)
4025 p = strv_catv(keys, client->crypto->pubkey);
4026 if (!p)
4027 rc = GPG_ERR_ENOMEM;
4030 if (!rc)
4032 keys = p;
4033 for (p = client->crypto->sigkey; p && *p; p++)
4035 if (!strv_printf(&keys, "S%s", *p))
4037 strv_free (keys);
4038 return send_error (ctx, GPG_ERR_ENOMEM);
4042 else
4043 rc = GPG_ERR_ENOMEM;
4045 if (!rc && keys)
4047 line = strv_join ("\n", keys);
4048 strv_free (keys);
4049 pthread_cleanup_push ((void *)xfree, line);
4050 if (line)
4051 rc = xfer_data (ctx, line, strlen (line));
4052 else
4053 rc = GPG_ERR_ENOMEM;
4055 pthread_cleanup_pop (1);
4057 else if (!keys)
4058 rc = GPG_ERR_NO_DATA;
4059 else
4060 strv_free (keys);
4062 return send_error (ctx, rc);
4065 static gpg_error_t
4066 kill_command (assuan_context_t ctx, char *line)
4068 struct client_s *client = assuan_get_pointer (ctx);
4069 gpg_error_t rc;
4070 unsigned i, t;
4072 if (!line || !*line)
4073 return send_error (ctx, GPG_ERR_SYNTAX);
4075 MUTEX_LOCK (&cn_mutex);
4076 pthread_cleanup_push ((void *)cleanup_mutex_cb, &cn_mutex);
4077 t = slist_length (cn_thread_list);
4078 rc = GPG_ERR_ESRCH;
4080 for (i = 0; i < t; i++)
4082 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
4083 char *tmp = str_asprintf ("%p", thd->tid);
4085 if (strcmp (line, tmp))
4087 xfree (tmp);
4088 continue;
4091 xfree (tmp);
4092 rc = peer_is_invoker (client);
4093 if (!rc)
4095 #ifdef HAVE_PTHREAD_CANCEL
4096 rc = pthread_cancel (thd->tid);
4097 #else
4098 close (thd->fd);
4099 thd->fd = -1;
4100 #endif
4101 break;
4104 rc = GPG_ERR_FORBIDDEN;
4105 if (config_get_boolean ("global", "strict_kill"))
4106 break;
4108 #ifdef WITH_GNUTLS
4109 if (client->thd->remote && thd->remote)
4111 if (!strcmp (client->thd->tls->fp, thd->tls->fp))
4113 #ifdef HAVE_PTHREAD_CANCEL
4114 rc = pthread_cancel (thd->tid);
4115 #else
4116 close (thd->fd);
4117 thd->fd = -1;
4118 #endif
4119 break;
4122 else if (!client->thd->remote && !thd->remote)
4123 #endif
4125 if (client->thd->peer->uid == thd->peer->uid)
4127 #ifdef HAVE_PTHREAD_CANCEL
4128 rc = pthread_cancel (thd->tid);
4129 #else
4130 close (thd->fd);
4131 thd->fd = -1;
4132 #endif
4135 break;
4138 pthread_cleanup_pop (1);
4139 return send_error (ctx, rc);
4142 static gpg_error_t
4143 listkeys_command (assuan_context_t ctx, char *line)
4145 struct client_s *client = assuan_get_pointer (ctx);
4146 struct crypto_s *crypto = NULL;
4147 char **pattern = NULL;
4148 gpgme_key_t *keys = NULL;
4149 char **result = NULL;
4150 gpg_error_t rc;
4151 struct argv_s *args[] = {
4152 &(struct argv_s) {"secret-only", OPTION_TYPE_NOARG,
4153 parse_listkeys_opt_secret_only },
4154 NULL
4157 rc = parse_options (&line, args, client, 1);
4158 if (rc)
4159 return send_error (ctx, rc);
4161 rc = crypto_init (&crypto, client->ctx, client->filename,
4162 client->flags & FLAG_NO_PINENTRY);
4163 if (rc)
4164 return send_error (ctx, rc);
4166 pthread_cleanup_push ((void *)(void *)crypto_cleanup, crypto);
4167 pattern = str_split (line, ",", 0);
4168 pthread_cleanup_push ((void *)(void *)strv_free, pattern);
4169 rc = crypto_list_keys (crypto, pattern, client->opts & OPT_SECRET_ONLY,
4170 &keys);
4171 pthread_cleanup_pop (1);
4172 pthread_cleanup_pop (1);
4173 if (!rc)
4175 int i;
4177 for (i = 0; keys[i]; i++)
4179 char *p = crypto_key_info (keys[i]);
4180 char **r;
4182 if (!p)
4184 rc = GPG_ERR_ENOMEM;
4185 break;
4188 r = strv_cat (result, p);
4189 if (!r)
4191 rc = GPG_ERR_ENOMEM;
4192 break;
4195 result = r;
4198 if (!i)
4199 rc = GPG_ERR_NO_DATA;
4201 crypto_free_key_list (keys);
4204 if (!rc)
4206 line = strv_join ("\n", result);
4207 strv_free (result);
4208 pthread_cleanup_push ((void *)xfree, line);
4209 if (!line)
4210 rc = GPG_ERR_ENOMEM;
4211 else
4212 rc = xfer_data (ctx, line, strlen (line));
4214 pthread_cleanup_pop (1);
4216 else
4217 strv_free (result);
4219 return send_error (ctx, rc);
4222 void
4223 init_commands ()
4225 /* !BEGIN-HELP-TEXT!
4227 * This comment is used as a marker to generate the offline documentation
4228 * found in doc/pwmd.info. The indentation needs to be kept for the awk
4229 * script to determine where commands begin and end.
4231 new_command("HELP", 1, 1, 0, help_command, _(
4232 "HELP [--html] [<COMMAND>]\n"
4233 "Show available commands or command specific help text."
4234 "@*@*"
4235 "The @option{--html} option will output the help text in HTML format."
4238 new_command("KILL", 1, 0, 0, kill_command, _(
4239 "KILL <thread_id>\n"
4240 "Terminates the client identified by @var{thread_id} and releases any file "
4241 "lock or other resources it has held. See @code{GETINFO} (@pxref{GETINFO}) "
4242 "for details about listing connected clients. An @code{invoking_user} "
4243 "(@pxref{Configuration}) may kill any client while others may only kill "
4244 "clients of the same @code{UID} or @abbr{TLS} fingerprint.\n"
4247 new_command("LISTKEYS", 0, 0, 0, listkeys_command, _(
4248 "LISTKEYS [--secret-only] [pattern[,<pattern>]]\n"
4249 "Returns a new line separated list of key information matching a comma "
4250 "separated list of @var{pattern}'s. When option @option{--secret-only} is "
4251 "specified, only keys matching @var{pattern} that also have a secret key "
4252 "available will be returned."
4255 new_command("KEYINFO", 1, 0, 0, keyinfo_command, _(
4256 "KEYINFO\n"
4257 "Returns a new line separated list of key ID's that the currently opened "
4258 "data file has recipients and signers for. If the key is a signing key it "
4259 "will be prefixed with an @code{S}. If the file is a new one, or has no "
4260 "signers in the case of being symmetrically encrypted, the error code "
4261 "@code{GPG_ERR_NO_DATA} is returned."
4264 new_command("GETINFO", 1, 1, 0, getinfo_command, _(
4265 "GETINFO [--data] [--verbose] CACHE | CLIENTS | PID | USER | LAST_ERROR | VERSION\n"
4266 "Get server and other information. The information is returned via a status "
4267 "message (@pxref{Status Messages}) unless otherwise noted or @option{--data} "
4268 "is specified."
4269 "@*@*"
4270 "@var{CACHE} returns the number of cached documents."
4271 "@*@*"
4272 "@var{CLIENTS} returns the number of "
4273 "connected clients via a status message or a list of connected clients when "
4274 "the @option{--verbose} parameter is used (implies @option{--data}). A "
4275 "verbose line of a client list contains "
4276 "space delimited "
4277 "fields: the thread ID, client name, opened file (@code{/} if none opened), "
4278 "IP address if remote, file lock status, whether the current client is self "
4279 "or not, client state (see below), "
4280 "user ID or TLS fingerprint of the connected client, username if the "
4281 "client is a local one else @code{-}, and finally the time stamp of when the "
4282 "client connected."
4283 "@*@*"
4284 "Client state @code{0} is an unknown client state, state @code{1} indicates "
4285 "the client has connected but hasn't completed initializing, state @code{2} "
4286 "indicates that the client is idle, state @code{3} means the "
4287 "client is in a command and state @code{4} means the client is disconnecting. "
4288 "@*@*"
4289 "@var{PID} returns the process ID number of the server via a data response."
4290 "@*@*"
4291 "@var{VERSION} returns the server version number and compile-time features "
4292 "via a data response with each being space delimited."
4293 "@*@*"
4294 "@var{LAST_ERROR} returns a detailed description of the last failed command "
4295 "via a data response, when available."
4296 "@*@*"
4297 "@var{USER} returns the username or @abbr{TLS} hash of the connected client "
4298 "via a data response."
4301 new_command("PASSWD", 0, 0, FLOCK_TYPE_EX|FLOCK_TYPE_KEEP, passwd_command, _(
4302 "PASSWD\n"
4303 "Changes the passphrase of the secret key required to open the current "
4304 "data file. If the data file is symmetrically encrypted, the error "
4305 "@code{GPG_ERR_NOT_SUPPORTED} is returned. When symmetrically encrypted, "
4306 "the @code{SAVE} command (@pxref{SAVE}) should be used instead to prevent "
4307 "this command saving any unwanted changes to the @abbr{XML} document."
4308 "@*@*"
4309 "This command is not available to non-invoking clients "
4310 "(@pxref{Access Control})."
4313 new_command("OPEN", 1, 1, FLOCK_TYPE_SH|FLOCK_TYPE_KEEP, open_command, _(
4314 "OPEN [--lock] <filename>\n"
4315 "Opens @var{filename}. When the @var{filename} is not found on the "
4316 "file-system then a new in-memory document will be created. If the file is "
4317 "found, it is looked for in the file cache and when found no passphrase will "
4318 "be required to open it. When not cached, @cite{pinentry(1)} will be used to "
4319 "retrieve the passphrase for decryption unless @option{disable-pinentry} "
4320 "(@pxref{OPTION}) was specified in which case @command{pwmd} will "
4321 "@emph{INQUIRE} the client for the passphrase."
4322 "@*@*"
4323 "When the @option{--lock} option is passed then the file mutex will be "
4324 "locked as if the @code{LOCK} command (@pxref{LOCK}) had been sent after the "
4325 "file had been opened."
4328 new_command("SAVE", 0, 0, FLOCK_TYPE_EX|FLOCK_TYPE_KEEP, save_command, _(
4329 "SAVE [--symmetric] [--inquire-keyparam] [--keyid=<keyid>[,..] | [--inquire-keyid]] [--sign-keyid=<fingerprint>[,..] | [--inquire-sign-keyid]]\n"
4330 "Writes the in-memory @abbr{XML} document to disk. The file written to is the "
4331 "file that was opened using the @code{OPEN} command (@pxref{OPEN}). If the "
4332 "file is a new one or the option @option{--inquire-keyparam} was passed, a "
4333 "new keypair will be generated and @cite{pinentry(1)} will be used to prompt "
4334 "for the passphrase of the secret key used for signing."
4335 "@*@*"
4336 "The @option{--inquire-keyparam} option will send an "
4337 "@emph{INQUIRE} to the client to obtain the key parameters to use for "
4338 "generating the new keypair. The inquired data is expected to be in "
4339 "@cite{gnupg} @abbr{XML} format. See the @cite{gnupg} documentation for "
4340 "details. Note that when this option is specified a new keypair will be "
4341 "generated reguardless if the file is a new one and that the passphrase for "
4342 "the current file will be required before generating the new keypair. This "
4343 "option is available to non-invoking clients (@pxref{Access Control}) only "
4344 "when the file is a new one."
4345 "@*@*"
4346 "You can encrypt the data file to a recipient other than the one that it "
4347 "was encrypted with by passing the @option{--keyid} or "
4348 "@option{--inquire-keyid} option with "
4349 "the key ID of a public encryption key as its argument. Use the "
4350 "@command{LISTKEYS} command (@pxref{LISTKEYS}) to show key information by "
4351 "pattern. The @option{--sign-keyid} or @option{--inquire-sign-keyid} option "
4352 "may also be used to sign the data "
4353 "file with an alternate key by specifying the key ID of a secret key. "
4354 "A passphrase to decrypt the data file "
4355 "will be required if one or more of the original encryption or signing keys "
4356 "are not found in either of these two options' arguments. The original "
4357 "encryption or signing keys will be used when either of these options are "
4358 "not specified."
4359 "@*@*"
4360 "The @option{--keyid} and @option{--sign-keyid} options are not available "
4361 "for non-invoking clients "
4362 "(@pxref{Access Control}) when the recipients or signers do not match those "
4363 "that were used when the file was @code{OPEN}'ed."
4364 "@*@*"
4365 "The @option{--symmetric} option specifies that a new data file be "
4366 "conventionally encrypted. These types of data files do not use a recipient "
4367 "public key but may be signed by using the @option{--sign-keyid} or "
4368 "@option{--inquire-sign-keyid} options. To remove all signers from a "
4369 "symmtrically encrypted data file, leave the option value empty. Note that "
4370 "you cannot change encryption schemes once a data file has been saved."
4373 new_command("ISCACHED", 1, 0, 0, iscached_command, _(
4374 "ISCACHED [--lock] <filename>\n"
4375 "An @emph{OK} response is returned if the specified @var{filename} is found "
4376 "in the file cache. If not found in the cache but exists on the filesystem "
4377 "then @code{GPG_ERR_NO_DATA} is returned. Otherwise a filesystem error is "
4378 "returned."
4379 "@*@*"
4380 "The @option{--lock} option will lock the file mutex of @var{filename} when "
4381 "the file exists; it does not need to be opened nor cached. The lock will be "
4382 "released when the client exits or sends the @code{UNLOCK} command "
4383 "(@pxref{UNLOCK})."
4386 new_command("CLEARCACHE", 1, 1, 0, clearcache_command, _(
4387 "CLEARCACHE [<filename>]\n"
4388 "Clears a file cache entry for all or the specified @var{filename}."
4391 new_command("CACHETIMEOUT", 1, 1, 0, cachetimeout_command, _(
4392 "CACHETIMEOUT <filename> <seconds>\n"
4393 "The time in @var{seconds} until @var{filename} will be removed from the "
4394 "cache. @code{-1} will keep the cache entry forever, @code{0} will require "
4395 "the passphrase for each @code{OPEN} command (@pxref{OPEN}) or @code{SAVE} "
4396 "(@pxref{SAVE}) command. @xref{Configuration}, and the @code{cache_timeout} "
4397 "parameter."
4400 new_command("LIST", 0, 1, 0, list_command, _(
4401 "LIST [--inquire] [--recurse] [element[<TAB>child[..]]]\n"
4402 "If no element path is given then a newline separated list of root elements "
4403 "is returned with a data response. If given, then children of the specified "
4404 "element path are returned."
4405 "@*@*"
4406 "Each element path "
4407 "returned will have zero or more flags appened to it. These flags are "
4408 "delimited from the element path by a single space character. A flag itself "
4409 "is a single character. Flag @code{P} indicates that access to the element "
4410 "is denied. Flag @code{+} indicates that there are child nodes of "
4411 "the current element path. Flag @code{E} indicates that an element of the "
4412 "element path contained in a @var{target} attribute could not be found. Flag "
4413 "@code{O} indicates that a @var{target} attribute recursion limit was reached "
4414 "(@pxref{Configuration}). Flag @code{T}, followed by a single space character, "
4415 "then an element path, is the element path of the @var{target} attribute "
4416 "contained in the current element."
4417 "@*@*"
4418 "When a specified element path contains an error, beit from the final "
4419 "element in the path or any previous element, the path is still shown but "
4420 "will contain the error flag for the element with the error. Determining "
4421 "the actual element which contains the error is up to the client. This can be "
4422 "done by traversing the final element up to parent elements that contain the "
4423 "same error flag."
4424 "@*@*"
4425 "The option @option{--recurse} may be used to list the entire element tree "
4426 "for a specified element path or the entire tree for all root elements."
4427 "@*@*"
4428 "When the @option{--inquire} option is passed then all remaining non-option "
4429 "arguments are retrieved via a server @emph{INQUIRE}."
4432 new_command("REALPATH", 0, 1, 0, realpath_command, _(
4433 "REALPATH [--inquire] element[<TAB>child[..]]\n"
4434 "Resolves all @code{target} attributes of the specified element path and "
4435 "returns the result with a data response. @xref{Target Attribute}, for details."
4436 "@*@*"
4437 "When the @option{--inquire} option is passed then all remaining non-option "
4438 "arguments are retrieved via a server @emph{INQUIRE}."
4441 new_command("STORE", 0, 1, 0, store_command, _(
4442 "STORE element[<TAB>child[..]]<TAB>[content]\n"
4443 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
4444 "@*@*"
4445 "Creates a new element path or modifies the @var{content} of an existing "
4446 "element. If only a single element is specified then a new root element is "
4447 "created. Otherwise, elements are @key{TAB} delimited and the content will be "
4448 "set to the final @key{TAB} delimited element. If no @var{content} is "
4449 "specified after the final @key{TAB}, then the content of the existing "
4450 "element will be removed; or will be empty if creating a new element."
4451 "@*@*"
4452 "The only restriction of an element name is that it not contain whitespace "
4453 "characters. There is no other whitespace between the @key{TAB} delimited "
4454 "elements. It is recommended that the content of an element be base64 encoded "
4455 "when it contains control or @key{TAB} characters to prevent @abbr{XML} "
4456 "parsing and @command{pwmd} syntax errors."
4459 new_command("RENAME", 0, 1, 0, rename_command, _(
4460 "RENAME [--inquire] element[<TAB>child[..]] <value>\n"
4461 "Renames the specified @var{element} to the new @var{value}. If an element of "
4462 "the same name as the @var{value} already exists it will be overwritten."
4463 "@*@*"
4464 "When the @option{--inquire} option is passed then all remaining non-option "
4465 "arguments are retrieved via a server @emph{INQUIRE}."
4468 new_command("COPY", 0, 1, 0, copy_command, _(
4469 "COPY [--inquire] source[<TAB>child[..]] dest[<TAB>child[..]]\n"
4470 "Copies the entire element tree starting from the child node of the source "
4471 "element, to the destination element path. If the destination element path "
4472 "does not exist then it will be created; otherwise it is overwritten."
4473 "@*@*"
4474 "Note that attributes from the source element are merged into the "
4475 "destination element when the destination element path exists. When an "
4476 "attribute of the same name exists in both the source and destination "
4477 "elements then the destination attribute will be updated to the source "
4478 "attribute value."
4479 "@*@*"
4480 "When the @option{--inquire} option is passed then all remaining non-option "
4481 "arguments are retrieved via a server @emph{INQUIRE}."
4484 new_command("MOVE", 0, 1, 0, move_command, _(
4485 "MOVE [--inquire] source[<TAB>child[..]] [dest[<TAB>child[..]]]\n"
4486 "Moves the source element path to the destination element path. If the "
4487 "destination is not specified then it will be moved to the root node of the "
4488 "document. If the destination is specified and exists then it will be "
4489 "overwritten; otherwise non-existing elements of the destination element "
4490 "path will be created."
4491 "@*@*"
4492 "When the @option{--inquire} option is passed then all remaining non-option "
4493 "arguments are retrieved via a server @emph{INQUIRE}."
4496 new_command("DELETE", 0, 1, 0, delete_command, _(
4497 "DELETE [--inquire] element[<TAB>child[..]]\n"
4498 "Removes the specified element path and all of its children. This may break "
4499 "an element with a @code{target} attribute (@pxref{Target Attribute}) that "
4500 "refers to this element or any of its children."
4501 "@*@*"
4502 "When the @option{--inquire} option is passed then all remaining non-option "
4503 "arguments are retrieved via a server @emph{INQUIRE}."
4506 new_command("GET", 0, 1, 0, get_command, _(
4507 "GET [--inquire] element[<TAB>child[..]]\n"
4508 "Retrieves the content of the specified element. The content is returned "
4509 "with a data response."
4510 "@*@*"
4511 "When the @option{--inquire} option is passed then all remaining non-option "
4512 "arguments are retrieved via a server @emph{INQUIRE}."
4515 new_command("ATTR", 0, 1, 0, attr_command, _(
4516 "ATTR [--inquire] SET|GET|DELETE|LIST [<attribute>] element[<TAB>child[..]] ..\n"
4517 "@table @asis\n"
4518 "@item ATTR SET attribute element[<TAB>child[..]] [value]\n"
4519 " Stores or updates an @var{attribute} name and optional @var{value} of an "
4520 "element. When no @var{value} is specified any existing value will be removed."
4521 "@*@*"
4522 "@item ATTR DELETE attribute element[<TAB>child[..]]\n"
4523 " Removes an attribute from an element. If @var{attribute} is @code{_name} "
4524 "or @code{target} an error is returned. Use the @command{DELETE} command "
4525 "(@pxref{DELETE}) instead."
4526 "@*@*"
4527 "@item ATTR LIST element[<TAB>child[..]]\n"
4528 " Retrieves a newline separated list of attributes names and values "
4529 "from the specified element. Each attribute name and value is space delimited."
4530 "@*@*"
4531 "@item ATTR GET attribute element[<TAB>child[..]]\n"
4532 " Retrieves the value of an @var{attribute} from an element."
4533 "@end table\n"
4534 "@*@*"
4535 "The @var{_name} attribute (case sensitive) cannot be removed nor modified. "
4536 "Use the @code{DELETE} (@pxref{DELETE}) or @code{RENAME} (@pxref{RENAME}) "
4537 "commands instead."
4538 "@*@*"
4539 "The @var{_mtime} attribute is updated each time an element is modified by "
4540 "either storing content, editing attributes or by deleting a child element. "
4541 "The @var{_ctime} attribute is created for each new element in an element "
4542 "path."
4543 "@*@*"
4544 "When the @option{--inquire} option is passed then all remaining non-option "
4545 "arguments are retrieved via a server @emph{INQUIRE}."
4546 "@*@*"
4547 "@xref{Target Attribute}, for details about this special attribute."
4550 new_command("XPATH", 0, 1, 0, xpath_command, _(
4551 "XPATH [--inquire] <expression>[<TAB>[value]]\n"
4552 "Evaluates an XPath @var{expression}. If no @var{value} argument is "
4553 "specified it is assumed the expression is a request to return a result. "
4554 "Otherwise, the result is set to the @var{value} argument and the document is "
4555 "updated. If there is no @var{value} after the @key{TAB} character, the value "
4556 "is assumed to be empty and the document is updated. For example:"
4557 "@sp 1\n"
4558 "@example\n"
4559 "XPATH //element[@@_name='password']@key{TAB}\n"
4560 "@end example\n"
4561 "@sp 1\n"
4562 "would clear the content of all @var{password} elements in the data file "
4563 "while leaving off the trailing @key{TAB} would return all @var{password} "
4564 "elements in @abbr{XML} format."
4565 "@*@*"
4566 "When the @option{--inquire} option is passed then all remaining non-option "
4567 "arguments are retrieved via a server @emph{INQUIRE}."
4568 "@*@*"
4569 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
4570 "expression syntax."
4573 new_command("XPATHATTR", 0, 1, 0, xpathattr_command, _(
4574 "XPATHATTR [--inquire] SET|DELETE <name> <expression>[<TAB>[<value>]]\n"
4575 "Like the @code{XPATH} command (@pxref{XPATH}) but operates on element "
4576 "attributes and does not return a result. For the @var{SET} operation the "
4577 "@var{value} is optional but the field is required. If not specified then "
4578 "the attribute value will be empty. For example:"
4579 "@sp 1\n"
4580 "@example\n"
4581 "XPATHATTR SET password //element[@@_name='password']@key{TAB}\n"
4582 "@end example\n"
4583 "@sp 1\n"
4584 "would create a @var{password} attribute for each @var{password} element "
4585 "found in the document. The attribute value will be empty but still exist."
4586 "@*@*"
4587 "When the @option{--inquire} option is passed then all remaining non-option "
4588 "arguments are retrieved via a server @emph{INQUIRE}."
4589 "@*@*"
4590 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
4591 "expression syntax."
4594 new_command("IMPORT", 0, 1, 0, import_command, _(
4595 "IMPORT [--root=element[<TAB>child[..]]]\n"
4596 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
4597 "@*@*"
4598 "Like the @code{STORE} command (@pxref{STORE}), but the @var{content} "
4599 "argument is raw @abbr{XML} data. The content is created as a child of "
4600 "the element path specified with the @option{--root} option or at the "
4601 "document root when not specified. Existing elements of the same name will "
4602 "be overwritten."
4603 "@*@*"
4604 "The content must begin with an @abbr{XML} element node. @xref{Introduction}, "
4605 "for details."
4608 new_command("DUMP", 0, 1, 0, dump_command, _(
4609 "DUMP\n"
4610 "Shows the in memory @abbr{XML} document with indenting. @xref{XPATH}, for "
4611 "dumping a specific node."
4614 new_command("LOCK", 0, 0, 0, lock_command, _(
4615 "LOCK\n"
4616 "Locks the mutex associated with the opened file. This prevents other clients "
4617 "from sending commands to the same opened file until the client "
4618 "that sent this command either disconnects or sends the @code{UNLOCK} "
4619 "command. @xref{UNLOCK}."
4622 new_command("UNLOCK", 1, 0, 0, unlock_command, _(
4623 "UNLOCK\n"
4624 "Unlocks the file mutex which was locked with the @code{LOCK} command or "
4625 "a commands' @option{--lock} option (@pxref{LOCK}, @pxref{OPEN}, "
4626 "@pxref{ISCACHED})."
4629 new_command("GETCONFIG", 1, 1, 0, getconfig_command, _(
4630 "GETCONFIG [filename] <parameter>\n"
4631 "Returns the value of a @command{pwmd} configuration @var{parameter} with a "
4632 "data response. If no file has been opened then the value for @var{filename} "
4633 "or the default from the @var{global} section will be returned. If a file "
4634 "has been opened and no @var{filename} is specified, the value previously "
4635 "set with the @code{OPTION} command (@pxref{OPTION}) will be returned."
4638 new_command("OPTION", 1, 1, 0, option_command, _(
4639 "OPTION <NAME>=[<VALUE>]\n"
4640 "Sets a client option @var{name} to @var{value}. The value for an option is "
4641 "kept for the duration of the connection with the exception of the "
4642 "@command{pinentry} options which are defaults for all future connections "
4643 "(@pxref{Pinentry}). When @var{value} is empty the option is unset."
4644 "@*@*"
4645 "@table @asis\n"
4646 "@item DISABLE-PINENTRY\n"
4647 "Disable use of @command{pinentry} for passphrase retrieval. When @code{1}, a "
4648 "server inquire is sent to the client to obtain the passphrase. This option "
4649 "may be set as needed before the @code{OPEN} (@pxref{OPEN}), @code{PASSWD} "
4650 "(@pxref{PASSWD}) and @code{SAVE} (@pxref{SAVE}) commands. Set to @code{0} "
4651 "to use a @command{pinentry}."
4652 "@*@*"
4653 "@item DISPLAY\n"
4654 "Set or unset the X11 display to use when prompting for a passphrase."
4655 "@*@*"
4656 "@item TTYNAME\n"
4657 "Set the terminal device path to use when prompting for a passphrase."
4658 "@*@*"
4659 "@item TTYTYPE\n"
4660 "Set the terminal type for use with @option{TTYNAME}."
4661 "@*@*"
4662 "@item NAME\n"
4663 "Associates the thread ID of the connection with the specified textual "
4664 "representation. Useful for debugging log messages. May not contain whitespace."
4665 "@*@*"
4666 "@item LOCK-TIMEOUT\n"
4667 "When not @code{0}, the duration in tenths of a second to wait for the file "
4668 "mutex which has been locked by another thread to be released before returning "
4669 "an error. When @code{-1} the error will be returned immediately."
4670 "@end table\n"
4673 new_command("LS", 1, 1, 0, ls_command, _(
4674 "LS\n"
4675 "Returns a newline separated list of data files stored in the data directory "
4676 "@file{HOMEDIR/data} (@pxref{Invoking}) with a data response."
4679 new_command("RESET", 1, 1, 0, NULL, _(
4680 "RESET\n"
4681 "Closes the currently opened file but keeps any previously set client options "
4682 "(@pxref{OPTION})."
4685 new_command("NOP", 1, 1, 0, NULL, _(
4686 "NOP\n"
4687 "Does nothing. Always returns successfully."
4690 /* !END-HELP-TEXT! */
4691 new_command ("CANCEL", 1, 1, 0, NULL, NULL);
4692 new_command ("END", 1, 1, 0, NULL, NULL);
4693 new_command ("BYE", 1, 1, 0, NULL, NULL);
4695 int i;
4696 for (i = 0; command_table[i]; i++);
4697 qsort (command_table, i - 1, sizeof (struct command_table_s *),
4698 sort_commands);
4701 gpg_error_t
4702 register_commands (assuan_context_t ctx)
4704 int i = 0, rc;
4706 for (; command_table[i]; i++)
4708 if (!command_table[i]->handler)
4709 continue;
4711 rc = assuan_register_command (ctx, command_table[i]->name,
4712 command_table[i]->handler,
4713 command_table[i]->help);
4714 if (rc)
4715 return rc;
4718 rc = assuan_register_bye_notify (ctx, bye_notify);
4719 if (rc)
4720 return rc;
4722 rc = assuan_register_reset_notify (ctx, reset_notify);
4723 if (rc)
4724 return rc;
4726 rc = assuan_register_pre_cmd_notify (ctx, command_startup);
4727 if (rc)
4728 return rc;
4730 return assuan_register_post_cmd_notify (ctx, command_finalize);