Add STATUS_MODIFIED.
[pwmd.git] / src / commands.c
blobd5671cb8bd056d0fb90805af1351b856d01a6a3d
1 /*
2 Copyright (C) 2006-2022 Ben Kibbey <bjk@luxsci.net>
4 This file is part of pwmd.
6 Pwmd is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License version 2 as
8 published by the Free Software Foundation.
10 Pwmd is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
18 #ifdef HAVE_CONFIG_H
19 #include <config.h>
20 #endif
22 #include <stdio.h>
23 #include <stdlib.h>
24 #ifdef HAVE_UNISTD_H
25 #include <unistd.h>
26 #endif
27 #include <err.h>
28 #include <errno.h>
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #ifdef HAVE_FCNTL_H
32 #include <fcntl.h>
33 #endif
34 #include <ctype.h>
35 #include <dirent.h>
36 #include <pthread.h>
37 #ifdef HAVE_STDINT_H
38 #include <stdint.h>
39 #endif
40 #include <assert.h>
41 #include <signal.h>
43 #include "pwmd-error.h"
44 #include <gcrypt.h>
46 #include "mem.h"
47 #include "xml.h"
48 #include "util-misc.h"
49 #include "common.h"
50 #include "rcfile.h"
51 #include "cache.h"
52 #include "commands.h"
53 #include "mutex.h"
54 #include "crypto.h"
55 #include "acl.h"
57 /* These are command option flags. */
58 #define OPT_INQUIRE 0x0001
59 #define OPT_NO_PASSPHRASE 0x0002
60 #define OPT_ASK 0x0004
61 #define OPT_LIST_RECURSE 0x0008
62 #define OPT_VERBOSE 0x0010
63 #define OPT_LOCK 0x0020
64 #define OPT_LOCK_ON_OPEN 0x0040
65 #define OPT_SIGN 0x0080
66 #define OPT_LIST_ALL 0x0100
67 #define OPT_DATA 0x0200
68 #define OPT_NO_AGENT 0x0400
69 #define OPT_SECRET 0x0800
70 #define OPT_INQUIRE_KEYID 0x1000
71 #define OPT_SYMMETRIC 0x4000
72 #define OPT_NO_SIGNER 0x8000
73 #define OPT_HTML 0x10000
74 #define OPT_CACHE_AGENT 0x20000
75 #define OPT_CACHE_SIGN 0x40000
76 #define OPT_KEYINFO_LEARN 0x80000
77 #define OPT_SEXP 0x100000
79 #define FLOCK_TYPE_NONE 0
80 #define FLOCK_TYPE_SH 0x0001
81 #define FLOCK_TYPE_EX 0x0002
82 #define FLOCK_TYPE_KEEP 0x0004
84 static char env_display[256];
85 static char env_gpg_tty[256];
86 static char env_term[256];
87 static struct command_table_s **command_table;
89 static gpg_error_t do_lock (struct client_s *client, int add);
90 static gpg_error_t validate_checksum (struct client_s *, const char *filename,
91 struct cache_data_s *, unsigned char **,
92 size_t *, int);
93 static gpg_error_t update_checksum (struct client_s *client,
94 unsigned char *from_crc, size_t crclen);
95 static gpg_error_t command_startup (assuan_context_t ctx, const char *name);
96 static void command_finalize (assuan_context_t ctx, gpg_error_t rc);
98 /* When 'status' is true the 'self' field of the status line will be false
99 * because we never send the STATE status message to the same client that
100 * initiated it. */
101 static char *
102 build_client_info_line (struct client_thread_s *thd, int status)
104 char *uid, *username = NULL;
105 char *line;
107 #ifdef WITH_GNUTLS
108 if (thd->remote)
109 uid = str_asprintf("#%s", thd->tls->fp);
110 else
112 uid = str_asprintf("%u", thd->peer->uid);
113 username = get_username (thd->peer->uid);
115 #else
116 uid = str_asprintf("%u", thd->peer->uid);
117 username = get_username (thd->peer->uid);
118 #endif
119 line = str_asprintf ("%p %s %s %s %u %u %u %s %s %u",
120 thd->tid,
121 thd->name ? thd->name : "-",
122 thd->cl && thd->cl->filename
123 && (thd->cl->flags & FLAG_OPEN)
124 ? thd->cl->filename : "/",
125 #ifdef WITH_GNUTLS
126 thd->remote ? thd->peeraddr : "-",
127 #else
128 "-",
129 #endif
130 thd->cl && thd->cl->flags & FLAG_HAS_LOCK ? 1 : 0,
131 !status && pthread_equal (pthread_self (), thd->tid) ? 1 : 0,
132 thd->state, uid,
133 #ifdef WITH_GNUTLS
134 thd->remote ? "-" : username,
135 #else
136 username,
137 #endif
138 thd->conntime
141 xfree (username);
142 xfree (uid);
143 return line;
146 void
147 update_client_state (struct client_s *client, unsigned s)
149 MUTEX_LOCK (&cn_mutex);
150 if (client->thd->state == s)
152 MUTEX_UNLOCK (&cn_mutex);
153 return;
155 client->thd->state = s;
156 MUTEX_UNLOCK (&cn_mutex);
158 if (client->thd->state != CLIENT_STATE_UNKNOWN)
160 char *line = build_client_info_line (client->thd, 1);
162 pthread_cleanup_push (xfree, line);
163 if (line)
164 send_status_all_not_self (STATUS_STATE, "%s", line);
165 pthread_cleanup_pop (1);
169 static gpg_error_t
170 unlock_file_mutex (struct client_s *client, int remove)
172 gpg_error_t rc = 0;
174 // OPEN: keep the lock for the same file being reopened.
175 if (client->flags & FLAG_KEEP_LOCK && client->flags & FLAG_HAS_LOCK)
176 return 0;
178 if (!(client->flags & FLAG_HAS_LOCK))
179 return GPG_ERR_NOT_LOCKED;
181 rc = cache_unlock_mutex (client->filename, remove);
182 if (rc)
183 rc = GPG_ERR_INV_STATE;
184 else
185 client->flags &= ~(FLAG_HAS_LOCK | FLAG_LOCK_CMD);
187 return rc;
190 static gpg_error_t
191 lock_file_mutex (struct client_s *client, int add)
193 gpg_error_t rc = 0;
194 long timeout = config_get_long (client->filename, "cache_timeout");
196 if (client->flags & FLAG_HAS_LOCK)
197 return 0;
199 rc = cache_lock_mutex (client->ctx, client->filename,
200 client->lock_timeout, add, timeout);
201 if (!rc)
202 client->flags |= FLAG_HAS_LOCK;
204 return rc;
207 static gpg_error_t
208 file_modified (struct client_s *client, struct command_table_s *cmd)
210 gpg_error_t rc = 0;
211 int type = !cmd->flock_type || (cmd->flock_type & FLOCK_TYPE_SH)
212 ? LOCK_SH : LOCK_EX;
214 if (!(client->flags & FLAG_OPEN))
215 return GPG_ERR_INV_STATE;
217 rc = lock_file_mutex (client, 0);
218 if (rc && rc != GPG_ERR_NO_DATA)
219 return rc;
221 rc = lock_flock (client->ctx, client->filename, type, &client->flock_fd);
222 if (!rc)
224 rc = validate_checksum (client, client->filename, NULL, NULL, NULL, 0);
225 if (gpg_err_code (rc) == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
226 rc = 0;
227 else if (rc)
228 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
230 else if (gpg_err_code (rc) == GPG_ERR_ENOENT)
231 rc = 0;
233 /* FLAG_HAS_LOCK may have been set by the LOCK command or OPEN --lock. */
234 if ((cmd->unlock && !(client->flags & FLAG_HAS_LOCK)) || rc)
235 unlock_file_mutex (client, 0);
237 if (rc || !(cmd->flock_type & FLOCK_TYPE_KEEP))
238 unlock_flock (&client->flock_fd);
240 return rc;
243 static gpg_error_t
244 parse_xml (assuan_context_t ctx, int new)
246 struct client_s *client = assuan_get_pointer (ctx);
247 int cached = client->doc != NULL;
248 gpg_error_t rc = 0;
250 if (new)
252 client->doc = xml_new_document ();
253 if (client->doc)
255 xmlChar *result;
256 int len;
258 xmlDocDumpFormatMemory (client->doc, &result, &len, 0);
259 client->crypto->plaintext = result;
260 client->crypto->plaintext_size = len;
261 if (!client->crypto->plaintext)
263 xmlFreeDoc (client->doc);
264 client->doc = NULL;
265 rc = GPG_ERR_ENOMEM;
268 else
269 rc = GPG_ERR_ENOMEM;
271 else if (!cached)
272 rc = xml_parse_doc ((char *) client->crypto->plaintext,
273 client->crypto->plaintext_size,
274 (xmlDocPtr *)&client->doc);
276 return rc;
279 static void
280 free_client (struct client_s *client)
282 cache_plaintext_release (&client->doc);
283 xfree (client->crc);
284 xfree (client->filename);
285 xfree (client->last_error);
286 crypto_free (client->crypto);
287 client->crypto = NULL;
290 void
291 reset_client (struct client_s *client)
293 assuan_context_t ctx = client->ctx;
294 struct client_thread_s *thd = client->thd;
295 long lock_timeout = client->lock_timeout;
296 xmlErrorPtr xml_error = client->xml_error;
297 int no_pinentry = (client->flags & FLAG_NO_PINENTRY);
298 int flock_fd = client->flock_fd;
299 struct bulk_cmd_s *bulk_p = client->bulk_p;
301 unlock_file_mutex (client, client->flags & FLAG_NEW);
302 cache_lock ();
303 free_client (client);
304 memset (client, 0, sizeof (struct client_s));
305 client->flock_fd = flock_fd;
306 client->xml_error = xml_error;
307 client->ctx = ctx;
308 client->thd = thd;
309 client->lock_timeout = lock_timeout;
310 client->flags |= no_pinentry ? FLAG_NO_PINENTRY : 0;
311 client->bulk_p = bulk_p;
312 cache_unlock ();
315 static void
316 req_free (void *arg)
318 if (!arg)
319 return;
321 strv_free ((char **) arg);
324 static gpg_error_t
325 parse_open_opt_lock (void *data, void *value)
327 struct client_s *client = data;
329 (void)value;
330 client->opts |= OPT_LOCK_ON_OPEN;
331 return 0;
334 static gpg_error_t
335 parse_opt_inquire (void *data, void *value)
337 struct client_s *client = data;
339 (void) value;
340 client->opts |= OPT_INQUIRE;
341 return 0;
344 static gpg_error_t
345 update_checksum (struct client_s *client, unsigned char *from_crc,
346 size_t crclen)
348 unsigned char *crc;
349 size_t len;
350 struct cache_data_s *cdata;
351 gpg_error_t rc;
353 if (!from_crc)
355 rc = get_checksum (client->filename, &crc, &len);
356 if (rc)
357 return rc;
359 else
361 crc = from_crc;
362 len = crclen;
365 xfree (client->crc);
366 client->crc = xmalloc (len);
367 memcpy (client->crc, crc, len);
368 pthread_cleanup_push (xfree, crc);
369 cdata = cache_get_data (client->filename, NULL);
370 pthread_cleanup_pop (0);
371 if (cdata)
373 xfree (cdata->crc);
374 cdata->crc = xmalloc (len);
375 memcpy (cdata->crc, crc, len);
378 if (!from_crc)
379 xfree (crc);
380 return 0;
383 static gpg_error_t
384 validate_checksum (struct client_s *client, const char *filename,
385 struct cache_data_s *cdata, unsigned char **r_crc,
386 size_t *r_crclen, int from_cdata)
388 unsigned char *crc;
389 size_t len;
390 gpg_error_t rc;
391 int n = 0;
393 if (cdata && !cdata->crc)
394 return GPG_ERR_CHECKSUM;
396 rc = get_checksum (filename, &crc, &len);
397 if (rc)
398 return rc;
400 if (client->crc)
401 n = memcmp (client->crc, crc, len);
402 else if ((client->flags & FLAG_NEW) && cache_get_data (filename, NULL))
403 n = 1;
405 if ((!n && cdata) || (from_cdata && cdata && crc))
406 n = memcmp (cdata->crc, crc, len);
408 if (!n && r_crc)
410 *r_crc = crc;
411 *r_crclen = len;
413 else
414 xfree (crc);
416 return n ? GPG_ERR_CHECKSUM : 0;
419 static gpg_error_t
420 open_command (assuan_context_t ctx, char *line)
422 gpg_error_t rc;
423 struct client_s *client = assuan_get_pointer (ctx);
424 int same_file = 0;
425 assuan_peercred_t peer;
426 struct cache_data_s *cdata = NULL;
427 int cached = 0;
428 unsigned char *crc = NULL;
429 size_t crclen = 0;
430 int plaintext = 0;
431 struct argv_s *args[] = {
432 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_open_opt_lock},
433 NULL
436 rc = parse_options (&line, args, client, 1);
437 if (rc)
438 return send_error (ctx, rc);
440 rc = do_validate_peer (ctx, line, &peer, NULL);
441 if (rc == GPG_ERR_FORBIDDEN)
443 rc = peer_is_invoker (client);
444 if (rc == GPG_ERR_EACCES)
445 rc = GPG_ERR_FORBIDDEN;
448 if (rc)
449 return send_error (ctx, rc);
451 if (!valid_filename (line))
452 return send_error (ctx, GPG_ERR_INV_VALUE);
454 /* This client may have locked a different file with ISCACHED --lock than
455 * the current filename. This will remove that lock. */
456 same_file = client->filename && !strcmp (line, client->filename);
457 if (client->flags & FLAG_OPEN ||
458 (client->flags & FLAG_HAS_LOCK && !same_file))
460 unsigned opts = client->opts;
461 unsigned flags = client->flags;
463 if (same_file)
464 client->flags |= FLAG_KEEP_LOCK;
466 /* Another client wrote to the same data file as currently opened. */
467 cdata = cache_get_data (client->filename, NULL);
468 if (cdata && cdata->crc)
469 flags &= ~FLAG_NEW;
470 /* Remove cache entry for the new file that hadn't been written. */
471 else if (client->flags & FLAG_NEW)
472 cache_clear (NULL, client->filename, 0, 0);
474 cdata = NULL;
475 reset_client (client);
476 client->opts = opts;
477 client->flags |= flags;
478 client->flags &= ~(FLAG_LOCK_CMD);
479 if (!same_file)
480 client->flags &= ~(FLAG_HAS_LOCK | FLAG_NEW);
483 xfree (client->filename);
484 client->filename = str_dup (line);
485 if (!client->filename)
486 return send_error(ctx, GPG_ERR_ENOMEM);
488 /* Need to lock the mutex here because file_modified() cannot without
489 * knowing the filename. */
490 rc = lock_file_mutex (client, 1);
491 if (rc)
492 client->flags &= ~FLAG_OPEN;
494 if (!rc)
496 rc = lock_flock (ctx, client->filename, LOCK_SH, &client->flock_fd);
497 if (gpg_err_code (rc) == GPG_ERR_ENOENT)
498 rc = 0;
501 if (!rc)
503 char *keyfile = config_get_string (client->filename, "passphrase_file");
505 rc = crypto_init (&client->crypto, client->ctx, client->filename,
506 client->flags & FLAG_NO_PINENTRY, keyfile);
507 if (rc)
508 xfree (keyfile);
509 else
510 rc = open_check_file (client->filename, NULL, NULL, 1);
513 if (!rc || gpg_err_code (rc) == GPG_ERR_ENOENT)
515 int reload = 0;
516 int defer = 0;
518 if (rc) // new file
520 rc = 0;
522 if (config_get_boolean ("global", "strict_open"))
524 rc = peer_is_invoker (client);
525 if (rc == GPG_ERR_EACCES)
526 rc = GPG_ERR_FORBIDDEN;
529 if (!rc)
531 client->flags |= FLAG_NEW;
532 // data file disappeared. clear the cache entry.
533 cache_clear (NULL, client->filename, 1, 1);
534 cdata = NULL;
537 goto done;
540 cdata = cache_get_data (client->filename, &defer);
541 if (cdata && !defer
542 && !cache_plaintext_get (client->filename, &client->doc))
544 rc = validate_checksum (client, client->filename, cdata, &crc,
545 &crclen, 0);
546 if (rc)
548 log_write ("%s: %s", client->filename,
549 pwmd_strerror (rc));
550 cache_plaintext_release (&client->doc);
551 if (rc == GPG_ERR_CHECKSUM)
553 cache_clear (NULL, client->filename, 1, 1);
554 cdata = NULL;
555 goto decrypt;
559 #ifdef WITH_GNUTLS
560 if (!rc && client->thd->remote
561 && config_get_boolean (client->filename, "tcp_require_key")
562 && !(client->flags & FLAG_NEW))
564 rc = crypto_try_decrypt (client,
565 (client->flags & FLAG_NO_PINENTRY));
567 #endif
568 if (!rc)
570 strv_free (client->crypto->pubkey);
571 client->crypto->pubkey = NULL;
572 if (cdata->pubkey)
573 client->crypto->pubkey = strv_dup (cdata->pubkey);
575 xfree (client->crypto->sigkey);
576 client->crypto->sigkey = NULL;
577 if (cdata->sigkey)
578 client->crypto->sigkey = str_dup (cdata->sigkey);
580 cached = 1;
581 plaintext = 1;
584 else if (cdata && cdata->doc) // cached document
586 if (!rc && !(client->flags & FLAG_NEW))
588 rc = validate_checksum (client, client->filename, cdata, &crc,
589 &crclen, 0);
590 if (rc == GPG_ERR_CHECKSUM)
592 rc = 0;
593 reload = 1;
597 if (!rc)
599 rc = cache_iscached (client->filename, &defer, 0, 0);
600 if ((!rc || rc == GPG_ERR_ENOENT) && defer)
602 rc = 0;
603 reload = 2;
607 if (!rc && reload)
609 if (reload == 1)
610 log_write ("%s: %s", client->filename,
611 pwmd_strerror (GPG_ERR_CHECKSUM));
612 cache_clear (NULL, client->filename, 1, 1);
613 cdata = NULL;
614 rc = crypto_decrypt (client, client->crypto);
616 #ifdef WITH_GNUTLS
617 else if (!rc)
619 if (client->thd->remote
620 && config_get_boolean (client->filename, "tcp_require_key")
621 && !(client->flags & FLAG_NEW))
622 rc = crypto_try_decrypt (client,
623 (client->flags & FLAG_NO_PINENTRY));
625 #endif
627 if (!rc && cdata)
629 client->crypto->plaintext = cdata->doc;
630 client->crypto->plaintext_size = cdata->size;
631 rc = cache_decrypt (client->crypto);
632 if (!rc)
634 cdata->doc = NULL;
635 cdata->size = 0;
637 strv_free (client->crypto->pubkey);
638 client->crypto->pubkey = NULL;
639 if (cdata->pubkey)
640 client->crypto->pubkey = strv_dup (cdata->pubkey);
642 xfree (client->crypto->sigkey);
643 client->crypto->sigkey = NULL;
644 if (cdata->sigkey)
645 client->crypto->sigkey = str_dup (cdata->sigkey);
647 cached = 1;
649 else
651 client->crypto->plaintext = NULL;
652 client->crypto->plaintext_size = 0;
656 else // existing file
658 decrypt:
659 cached = cdata != NULL;
660 rc = crypto_decrypt (client, client->crypto);
664 done:
665 if (!rc && !plaintext)
667 rc = parse_xml (ctx, client->flags & FLAG_NEW);
668 if (!rc)
670 rc = cache_encrypt (client->crypto);
671 if (rc)
672 cache_clear (NULL, client->filename, 1, 1);
673 else
675 long timeout = config_get_long (client->filename,
676 "cache_timeout");
678 cache_free_data_once (cdata);
679 cdata = xcalloc (1, sizeof (struct cache_data_s));
680 cdata->doc = client->crypto->plaintext;
681 cdata->size = client->crypto->plaintext_size;
682 cdata->pubkey = strv_dup(client->crypto->pubkey);
683 cdata->sigkey = client->crypto->sigkey ? str_dup(client->crypto->sigkey) : NULL;
684 client->crypto->plaintext = NULL;
685 client->crypto->plaintext_size = 0;
687 if (cached) // wont increment the refcount
689 if (crclen)
691 xfree (client->crc);
692 client->crc = NULL;
693 xfree (cdata->crc);
694 cdata->crc = xmalloc (crclen);
695 memcpy (cdata->crc, crc, crclen);
698 rc = cache_set_data (client->filename, cdata);
699 /* The cache entry may have been removed and cache_set_data()
700 * already sent STATUS_CACHE. */
701 if (!cache_iscached (client->filename, NULL, 0, 0))
702 rc = send_status (ctx, STATUS_CACHE, NULL);
704 else
705 rc = cache_add_file (client->filename, cdata, timeout);
707 if (!rc)
708 cache_plaintext_set (client->filename, client->doc, 0);
713 if (!rc)
715 xfree (client->crc);
716 client->crc = NULL;
717 if (crc)
719 client->crc = xmalloc (crclen);
720 memcpy (client->crc, crc, crclen);
724 xfree (crc);
726 if (!rc && !(client->flags & FLAG_NEW) && !cached)
727 rc = update_checksum (client, NULL, 0);
729 if (!rc)
731 client->flags |= FLAG_OPEN;
733 if (client->flags & FLAG_NEW)
734 rc = send_status (ctx, STATUS_NEWFILE, NULL);
736 if (!rc && (client->opts & OPT_LOCK_ON_OPEN))
737 rc = do_lock (client, 0);
739 crypto_free_non_keys (client->crypto);
741 else
743 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
745 if (client->flags & FLAG_NEW)
746 cache_clear (NULL, client->filename, 1, 1);
748 crypto_free (client->crypto);
749 client->crypto = NULL;
750 client->flags &= ~FLAG_OPEN;
751 cache_plaintext_release (&client->doc);
754 return send_error (ctx, rc);
757 /* If not an invoking_user or is an existing file, check that the list of user
758 * supplied key ID's are in the list of current key ID's obtained when
759 * decrypting the data file.
761 static gpg_error_t
762 permitted_to_save (struct client_s *client, const char **keys,
763 const char **value)
765 gpg_error_t rc = 0;
766 const char **v;
768 if ((client->flags & FLAG_NEW) || (client->opts & OPT_SYMMETRIC))
769 return 0;
771 rc = peer_is_invoker (client);
772 if (!rc)
773 return 0;
774 else if (rc == GPG_ERR_EACCES)
775 rc = GPG_ERR_FORBIDDEN;
776 else if (rc)
777 return rc;
779 /* Empty match. */
780 if ((!value && !keys) || ((value && !*value) && (keys && !*keys)))
781 return 0;
783 for (v = value; v && *v; v++)
785 const char **k, *pv = *v;
786 int match = 0;
788 if (*pv == '0' && *(pv+1) == 'x')
789 pv += 2;
791 for (k = keys; k && *k; k++)
793 const char *pk = *k;
795 if (*pk == '0' && *(pk+1) == 'x')
796 pk += 2;
798 rc = !strcmp (pv, pk) ? 0 : GPG_ERR_FORBIDDEN;
799 if (rc)
800 rc = !strcmp (pv, *k) ? 0 : GPG_ERR_FORBIDDEN;
802 if (!rc)
804 match = 1;
805 break;
809 if (!match)
810 return GPG_ERR_FORBIDDEN;
813 return rc;
816 /* Requires that the keyid be a fingerprint in 16 byte form. */
817 static gpg_error_t
818 parse_save_opt_keyid_common (struct client_s *client, const char **list,
819 const char *value, char ***dst)
821 gpg_error_t rc = 0;
822 char **keys = NULL;
824 if (value && *value)
826 keys = str_split (value, ",", 0);
827 if (!keys)
828 return GPG_ERR_ENOMEM;
831 rc = crypto_keyid_to_16b (keys);
832 if (!rc)
833 rc = permitted_to_save (client, list, (const char **)keys);
835 if (!rc)
836 *dst = keys;
837 else
838 strv_free (keys);
840 return rc;
843 static gpg_error_t
844 parse_save_opt_keyid (void *data, void *value)
846 struct client_s *client = data;
847 const char *str = value;
848 char **dst = NULL;
849 gpg_error_t rc;
851 rc = parse_save_opt_keyid_common (client,
852 (const char **)client->crypto->pubkey,
853 str, &dst);
854 if (rc)
855 return rc;
857 client->crypto->save.pubkey = dst;
858 return 0;
861 static gpg_error_t
862 parse_save_opt_sign_keyid (void *data, void *value)
864 struct client_s *client = data;
865 const char *str = value;
866 char **dst = NULL;
867 gpg_error_t rc;
868 char **tmp = NULL;
870 if (client->crypto->sigkey)
872 if (!strv_printf (&tmp, "%s", client->crypto->sigkey))
873 return GPG_ERR_ENOMEM;
876 rc = parse_save_opt_keyid_common (client, (const char **)tmp, str, &dst);
877 strv_free (tmp);
878 if (rc)
879 return rc;
881 if (!dst)
882 client->opts |= OPT_NO_SIGNER;
883 else
884 client->crypto->save.sigkey = str_dup (*dst);
886 strv_free (dst);
887 return 0;
890 static gpg_error_t
891 parse_save_opt_inquire_keyid (void *data, void *value)
893 struct client_s *client = data;
895 (void)value;
897 if (!(client->flags & FLAG_NEW))
899 gpg_error_t rc = peer_is_invoker (client);
901 if (rc)
902 return rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc;
905 client->opts |= OPT_INQUIRE_KEYID;
906 return 0;
909 static gpg_error_t
910 parse_save_opt_symmetric (void *data, void *value)
912 struct client_s *client = data;
914 (void)value;
915 client->opts |= OPT_SYMMETRIC;
916 return 0;
919 static gpg_error_t
920 parse_genkey_opt_userid (void *data, void *value)
922 struct client_s *client = data;
924 if (!(client->flags & FLAG_NEW))
926 gpg_error_t rc = peer_is_invoker (client);
928 if (rc)
929 return rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc;
932 client->crypto->save.userid = str_dup (value);
933 return client->crypto->save.userid ? 0 : GPG_ERR_ENOMEM;
936 static gpg_error_t
937 parse_genkey_opt_algo (void *data, void *value)
939 struct client_s *client = data;
941 client->crypto->save.algo = str_dup (value);
942 return client->crypto->save.algo ? 0 : GPG_ERR_ENOMEM;
945 static gpg_error_t
946 parse_genkey_opt_no_expire (void *data, void *value)
948 struct client_s *client = data;
950 client->crypto->save.flags |= GPGME_CREATE_NOEXPIRE;
951 return 0;
954 static gpg_error_t
955 parse_genkey_opt_expire (void *data, void *value)
957 struct client_s *client = data;
958 gpg_error_t rc = 0;
959 char *p = NULL;
960 unsigned long t;
962 errno = 0;
963 t = strtoul (value, &p, 10);
965 if (!errno && p && *p)
966 rc = GPG_ERR_INV_VALUE;
967 else if (t == ULONG_MAX)
968 rc = GPG_ERR_INV_VALUE;
969 else if (errno)
970 rc = gpg_error_from_syserror ();
971 else
972 client->crypto->save.expire = t;
974 return rc;
977 static gpg_error_t
978 parse_genkey_opt_no_passphrase (void *data, void *value)
980 struct client_s *client = data;
982 (void)value;
983 client->crypto->save.flags |= GPGME_CREATE_NOPASSWD;
984 return 0;
987 /* Tests that the keys in new_keys are also in old_keys. */
988 static gpg_error_t
989 compare_keys (char **new_keys, char **old_keys)
991 char **o;
993 if (!old_keys || !*old_keys)
994 return 0;
996 crypto_keyid_to_16b (new_keys);
998 for (o = old_keys; *o; o++)
1000 char **n;
1002 for (n = new_keys; *n; n++)
1004 if (!strcmp (*n, *o))
1005 break;
1008 if (!*n)
1009 return GPG_ERR_NOT_FOUND;
1012 return 0;
1015 static gpg_error_t
1016 inquire_keyid (struct client_s *client)
1018 gpg_error_t rc;
1019 unsigned char *result = NULL;
1020 size_t len;
1021 const char *s = "KEYID";
1022 char ***orig;
1023 char ***save;
1025 orig = &client->crypto->pubkey;
1026 save = &client->crypto->save.pubkey;
1027 rc = assuan_inquire (client->ctx, s, &result, &len, 0);
1028 if (!rc)
1030 char **dst = NULL;
1032 rc = parse_save_opt_keyid_common (client, (const char **)*orig,
1033 (char *)result, &dst);
1034 if (!rc)
1035 *save = dst;
1038 xfree (result);
1039 return rc;
1043 /* When a key lookup in gpg-agent's cache fails, the agent tries the last
1044 * successful key to be unlocked. This prevents pwmd from successfully
1045 * clearing a signing key since the previous key, which more than likely
1046 * belongs to the same keypair as the encryption/decryption key, will have the
1047 * passphrase cached and therefore the signing key also cached. So we need to
1048 * clear both the signing and encryption keys to get the effect of requiring a
1049 * passphrase when generating a new keypair for an existing data file, or when
1050 * the "require_save_key" configuration parameter is set. This parameter is
1051 * mostly a failsafe of the gpg-agent option --ignore-cache-for-signing since
1052 * some/most/all users may fail to set it.
1054 static gpg_error_t
1055 save_command (assuan_context_t ctx, char *line)
1057 struct client_s *client = assuan_get_pointer (ctx);
1058 struct cache_data_s *cdata = NULL;
1059 int sym = 0;
1060 gpg_error_t rc = 0, cache_rc = 0;
1061 int defer = 0;
1062 struct argv_s *args[] = {
1063 &(struct argv_s) {"keyid", OPTION_TYPE_ARG, parse_save_opt_keyid},
1064 &(struct argv_s) {"inquire-keyid", OPTION_TYPE_NOARG,
1065 parse_save_opt_inquire_keyid },
1066 &(struct argv_s) {"sign-keyid", OPTION_TYPE_OPTARG,
1067 parse_save_opt_sign_keyid},
1068 &(struct argv_s) {"symmetric", OPTION_TYPE_NOARG,
1069 parse_save_opt_symmetric },
1070 NULL
1073 crypto_free_save (&client->crypto->save);
1074 client->crypto->save.expire = DEFAULT_EXPIRE;
1076 rc = crypto_is_symmetric (client->filename);
1077 if (!rc || rc == GPG_ERR_BAD_DATA || rc == GPG_ERR_ENOENT)
1079 if (!rc)
1081 client->opts |= OPT_SYMMETRIC;
1082 sym = 1;
1084 else if (rc == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
1085 rc = 0; // New file
1086 else
1087 rc = 0; // PKI
1090 if (rc)
1091 return send_error (ctx, rc);
1093 rc = parse_options (&line, args, client, 0);
1094 if (rc)
1095 return send_error (ctx, rc);
1097 if (config_get_boolean (client->filename, "require_save_key")
1098 || (client->opts & OPT_SYMMETRIC))
1099 client->opts |= OPT_ASK;
1101 rc = open_check_file (client->filename, NULL, NULL, 1);
1102 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
1104 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
1105 return send_error (ctx, rc);
1108 if (!rc)
1109 cache_rc = rc = cache_iscached (client->filename, &defer, 0, 1);
1111 if (gpg_err_code (rc) == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
1112 rc = 0;
1113 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
1114 rc = 0;
1116 if (rc)
1117 return send_error (ctx, rc);
1119 /* Specifying both a recipient and symmetric encryption is an error. */
1120 if ((client->opts & OPT_INQUIRE_KEYID) && (client->opts & OPT_SYMMETRIC))
1121 return send_error (ctx, GPG_ERR_CONFLICT);
1122 /* Existing file with a recipient and wanting symmetric is an error. */
1123 else if ((client->opts & OPT_SYMMETRIC) && client->crypto->save.pubkey)
1124 return send_error (ctx, GPG_ERR_CONFLICT);
1125 else if (client->crypto->save.pubkey && (client->opts & OPT_INQUIRE_KEYID))
1126 return send_error (ctx, GPG_ERR_CONFLICT);
1127 else if (!sym && (client->opts & OPT_SYMMETRIC) && !(client->flags & FLAG_NEW))
1128 return send_error (ctx, GPG_ERR_CONFLICT);
1129 /* New file that is not symmetric without either a recipient or signer. */
1130 else if ((client->flags & FLAG_NEW) && !(client->opts & OPT_SYMMETRIC)
1131 && (!client->crypto->save.pubkey || !client->crypto->save.sigkey))
1132 return send_error (ctx, GPG_ERR_SYNTAX);
1133 else if (client->opts & OPT_INQUIRE_KEYID)
1134 rc = inquire_keyid (client);
1136 if (!rc)
1138 client->crypto->keyfile = config_get_string (client->filename,
1139 "passphrase_file");
1140 rc = crypto_init_ctx (client->crypto, (client->flags & FLAG_NO_PINENTRY),
1141 client->crypto->keyfile);
1144 if (!rc && (client->flags & FLAG_NEW))
1146 /* Require --keyid when --sign-keyid exists to keep KEYINFO
1147 * synchronized. */
1148 if (!client->crypto->save.pubkey && client->crypto->save.sigkey
1149 && !(client->opts & OPT_SYMMETRIC))
1150 rc = GPG_ERR_NO_PUBKEY;
1152 else if (!rc)
1154 cdata = cache_get_data (client->filename, NULL);
1155 if (cdata)
1157 if (client->crypto->save.pubkey)
1158 rc = compare_keys (client->crypto->save.pubkey, cdata->pubkey);
1160 /* Always allow a signer for symmetric data files. */
1161 if (!rc && client->crypto->save.sigkey
1162 && !(client->opts & OPT_SYMMETRIC))
1163 rc = !strcmp (client->crypto->save.sigkey, cdata->sigkey)
1164 ? 0 : GPG_ERR_NOT_FOUND;
1166 /* Prevent saving to a recipient who is not in the original recipient
1167 * list without a passphrase. */
1168 if (rc || (client->crypto->sigkey && (client->opts & OPT_NO_SIGNER)))
1169 client->opts |= OPT_ASK;
1171 if (rc == GPG_ERR_NOT_FOUND)
1173 rc = peer_is_invoker (client);
1174 if (rc == GPG_ERR_EACCES)
1175 rc = GPG_ERR_FORBIDDEN;
1178 if (!client->crypto->save.pubkey
1179 && !(client->opts & OPT_SYMMETRIC))
1180 client->crypto->save.pubkey = strv_dup (cdata->pubkey);
1182 if (!rc && !client->crypto->save.sigkey && cdata->sigkey
1183 && !(client->opts & OPT_NO_SIGNER))
1184 client->crypto->save.sigkey = str_dup (cdata->sigkey);
1185 else if (!rc && !client->crypto->save.sigkey
1186 && (client->opts & OPT_NO_SIGNER)
1187 && !(client->opts & OPT_SYMMETRIC))
1188 rc = GPG_ERR_NO_SIGNATURE_SCHEME;
1190 else
1192 client->crypto->save.pubkey = strv_dup (client->crypto->pubkey);
1193 client->crypto->save.sigkey = str_dup (client->crypto->sigkey);
1197 if (!rc && !(client->flags & FLAG_NEW))
1199 /* Fixes {NEW_,SIGN_}PASSPHRASE inquire keywords. See passphrase_cb(). */
1200 if (client->opts & OPT_SYMMETRIC)
1201 client->crypto->flags |= CRYPTO_FLAG_PASSWD;
1203 if (client->opts & OPT_ASK)
1205 rc = cache_clear_agent_keys (client->filename, 1, 1);
1206 if (!rc)
1207 rc = crypto_try_decrypt (client, client->flags & FLAG_NO_PINENTRY);
1211 if (!rc && client->opts & OPT_SYMMETRIC)
1212 client->crypto->flags |= CRYPTO_FLAG_PASSWD_NEW;
1214 if (!rc)
1215 rc = xml_update_element_mtime (client, xmlDocGetRootElement (client->doc));
1217 if (!rc)
1219 xmlNodePtr root = xmlDocGetRootElement (client->doc);
1221 rc = xml_add_attribute (client, root, "_version", PACKAGE_VERSION);
1224 if (!rc)
1226 int size;
1228 xmlDocDumpFormatMemory (client->doc, &client->crypto->plaintext, &size,
1230 if (size > 0)
1231 client->crypto->plaintext_size = (size_t) size;
1232 else
1233 rc = GPG_ERR_ENOMEM;
1235 if (!rc)
1237 client->crypto->flags |= (client->opts & OPT_SYMMETRIC) ? CRYPTO_FLAG_SYMMETRIC : 0;
1238 client->crypto->flags |= (client->flags & FLAG_NEW) ? CRYPTO_FLAG_NEWFILE : 0;
1239 client->crypto->flags |= !(client->opts & OPT_SYMMETRIC) ? CRYPTO_FLAG_PASSWD_SIGN : 0;
1240 rc = crypto_encrypt (client, client->crypto);
1241 client->crypto->flags &= ~CRYPTO_FLAG_SYMMETRIC;
1244 if (!rc)
1246 unsigned char *crc = NULL;
1247 size_t crclen = 0;
1249 rc = crypto_write_file (client->crypto, &crc, &crclen);
1250 pthread_cleanup_push ((void *)xfree, crc);
1251 if (!rc)
1253 if (!cache_rc)
1254 cdata = cache_get_data (client->filename, NULL);
1255 else
1256 cdata = xcalloc (1, sizeof (struct cache_data_s));
1259 if (!rc)
1261 rc = cache_encrypt (client->crypto);
1262 if (rc)
1264 cache_clear (NULL, client->filename, 1, 1);
1265 client->flags &= ~(FLAG_NEW);
1267 strv_free (client->crypto->pubkey);
1268 client->crypto->pubkey = NULL;
1269 if (client->crypto->save.pubkey)
1270 client->crypto->pubkey = strv_dup (client->crypto->save.pubkey);
1272 xfree (client->crypto->sigkey);
1273 client->crypto->sigkey = NULL;
1274 if (client->crypto->save.sigkey)
1275 client->crypto->sigkey = str_dup (client->crypto->save.sigkey);
1279 if (!rc)
1281 long timeout = config_get_long (client->filename, "cache_timeout");
1282 xmlDocPtr doc = xmlCopyDoc (client->doc, 1);
1284 if (!doc)
1285 rc = GPG_ERR_ENOMEM;
1287 if (!rc)
1289 cache_plaintext_release (&client->doc);
1290 strv_free (cdata->pubkey);
1291 cdata->pubkey = client->crypto->save.pubkey;
1292 client->crypto->save.pubkey = NULL;
1294 xfree (cdata->sigkey);
1295 cdata->sigkey = client->crypto->save.sigkey;
1296 client->crypto->save.sigkey = NULL;
1298 xfree (cdata->crc);
1299 cdata->crc = NULL;
1301 /* cache_encrypt() does in-place encryption */
1302 xfree (cdata->doc);
1303 cdata->doc = client->crypto->plaintext;
1304 client->crypto->plaintext = NULL;
1305 cdata->size = client->crypto->plaintext_size;
1306 client->crypto->plaintext_size = 0;
1308 client->doc = doc;
1309 cache_plaintext_set (client->filename, client->doc, 0);
1311 /* Update in case the cache entry expires the next SAVE may
1312 * not have any known keys. */
1313 strv_free (client->crypto->pubkey);
1314 client->crypto->pubkey = NULL;
1315 if (cdata->pubkey)
1316 client->crypto->pubkey = strv_dup (cdata->pubkey);
1318 xfree (client->crypto->sigkey);
1319 client->crypto->sigkey = NULL;
1320 if (cdata->sigkey)
1321 client->crypto->sigkey = str_dup (cdata->sigkey);
1323 if (!cache_rc) // wont increment refcount
1324 rc = cache_set_data (client->filename, cdata);
1325 else
1326 rc = cache_add_file (client->filename, cdata, timeout);
1329 if (!rc && (cache_rc || (client->flags & FLAG_NEW)))
1330 send_status_all (STATUS_CACHE, NULL);
1332 if (!rc)
1334 rc = update_checksum (client, crc, crclen);
1335 client->flags &= ~(FLAG_NEW);
1339 pthread_cleanup_pop (1);
1340 if (!rc)
1342 client->did_cow = 0;
1343 send_status_modified (client->ctx);
1348 crypto_free_non_keys (client->crypto);
1349 return send_error (ctx, rc);
1352 static gpg_error_t
1353 parse_genkey_opt_usage (void *data, void *v)
1355 struct client_s *client = data;
1356 char *value = v;
1358 if (!value || !*value)
1359 return GPG_ERR_INV_VALUE;
1360 else if (!strcmp (value, "sign"))
1361 client->crypto->save.flags |= GPGME_CREATE_SIGN;
1362 else if (!strcmp (value, "encrypt"))
1363 client->crypto->save.flags |= GPGME_CREATE_ENCR;
1364 else if (!strcmp (value, "default"))
1365 client->crypto->save.flags &= ~(GPGME_CREATE_ENCR|GPGME_CREATE_SIGN);
1366 else
1367 return GPG_ERR_INV_VALUE;
1369 return 0;
1372 gpg_error_t
1373 parse_genkey_opt_subkey_of (void *data, void *v)
1375 gpg_error_t rc;
1376 struct client_s *client = data;
1377 char *value = v;
1378 char *tmp[] = { value, NULL };
1379 gpgme_key_t *keys = NULL;
1381 rc = peer_is_invoker (client);
1382 if (rc)
1383 return rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc;
1385 if (!value || !*value)
1386 return GPG_ERR_INV_VALUE;
1388 rc = crypto_list_keys (client->crypto, tmp, 1, &keys);
1389 if (rc)
1390 return rc;
1392 if (!keys || !*keys)
1394 crypto_free_key_list (keys);
1395 return GPG_ERR_NO_SECKEY;
1398 client->crypto->save.mainkey = keys;
1399 return 0;
1402 static gpg_error_t
1403 genkey_command (assuan_context_t ctx, char *line)
1405 struct client_s *client = assuan_get_pointer (ctx);
1406 struct crypto_s *crypto, *orig;
1407 gpg_error_t rc = 0;
1408 struct argv_s *args[] = {
1409 &(struct argv_s) {"userid", OPTION_TYPE_ARG,
1410 parse_genkey_opt_userid},
1411 &(struct argv_s) {"expire", OPTION_TYPE_ARG,
1412 parse_genkey_opt_expire},
1413 &(struct argv_s) {"no-expire", OPTION_TYPE_NOARG,
1414 parse_genkey_opt_no_expire},
1415 &(struct argv_s) {"algo", OPTION_TYPE_ARG,
1416 parse_genkey_opt_algo},
1417 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG,
1418 parse_genkey_opt_no_passphrase},
1419 &(struct argv_s) {"usage", OPTION_TYPE_ARG,
1420 parse_genkey_opt_usage},
1421 &(struct argv_s) {"subkey-of", OPTION_TYPE_ARG,
1422 parse_genkey_opt_subkey_of},
1423 NULL
1426 if (!(client->flags & FLAG_OPEN))
1427 return send_error (ctx, GPG_ERR_INV_STATE);
1429 rc = crypto_init (&crypto, ctx, client->filename,
1430 client->flags & FLAG_NO_PINENTRY, NULL);
1431 if (rc)
1432 return send_error (ctx, rc);
1434 pthread_cleanup_push ((void *)crypto_free, client->crypto);
1435 orig = client->crypto;
1436 client->crypto = crypto;
1437 rc = parse_options (&line, args, client, 0);
1438 if (!rc)
1440 if (!client->crypto->save.userid && !client->crypto->save.mainkey)
1441 rc = GPG_ERR_SYNTAX;
1442 else
1444 client->crypto->flags |= CRYPTO_FLAG_NEWFILE;
1445 rc = crypto_genkey (client, client->crypto);
1449 pthread_cleanup_pop (0);
1450 crypto_free (crypto);
1451 client->crypto = orig;
1452 return send_error (ctx, rc);
1455 static gpg_error_t
1456 do_delete (assuan_context_t ctx, char *line)
1458 struct client_s *client = assuan_get_pointer (ctx);
1459 struct xml_request_s *req;
1460 xmlNodePtr n;
1461 gpg_error_t rc;
1463 if (!line || !*line)
1464 return GPG_ERR_SYNTAX;
1466 rc = xml_new_request (client, line, XML_CMD_DELETE, &req);
1467 if (rc)
1468 return rc;
1470 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1471 xml_free_request (req);
1472 if (rc)
1473 return rc;
1475 rc = xml_is_element_owner (client, n, 0);
1476 if (!rc)
1477 rc = xml_unlink_node (client, n);
1479 return rc;
1482 /* Won't update cdata->plaintext. Other clients are working on the original or
1483 * copy of the same document. The first client to SAVE wins and requires others
1484 * to reopen the data file due to a checksum error. */
1485 static gpg_error_t
1486 copy_on_write (struct client_s *client)
1488 struct cache_data_s *cdata;
1490 if (client->did_cow)
1491 return 0;
1493 cdata = cache_get_data (client->filename, NULL);
1494 if (cdata)
1496 gpg_error_t rc;
1497 xmlDocPtr doc = xmlCopyDoc (client->doc, 1);
1499 if (!doc)
1500 return GPG_ERR_ENOMEM;
1502 rc = cache_plaintext_set (client->filename, doc, 1);
1503 if (rc)
1505 xmlFree (doc);
1506 return rc;
1509 (void)cache_plaintext_release (&client->doc);
1510 client->doc = doc;
1511 client->did_cow = 1;
1512 return 0;
1515 return GPG_ERR_NO_DATA;
1518 static gpg_error_t
1519 delete_command (assuan_context_t ctx, char *line)
1521 struct client_s *client = assuan_get_pointer (ctx);
1522 gpg_error_t rc;
1523 struct argv_s *args[] = {
1524 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1525 NULL
1528 rc = parse_options (&line, args, client, 1);
1529 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1530 rc = GPG_ERR_SYNTAX;
1531 if (rc)
1532 return send_error (ctx, rc);
1534 rc = copy_on_write (client);
1535 if (rc)
1536 return send_error (ctx, rc);
1538 if (client->opts & OPT_INQUIRE)
1540 unsigned char *result;
1541 size_t len;
1543 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1544 if (rc)
1545 return send_error (ctx, rc);
1547 pthread_cleanup_push ((void *)xfree, result);
1548 rc = do_delete (ctx, (char *)result);
1549 pthread_cleanup_pop (1);
1551 else
1552 rc = do_delete (ctx, line);
1554 return send_error (ctx, rc);
1557 static gpg_error_t
1558 update_element_expirey (struct client_s *client, xmlNodePtr n)
1560 gpg_error_t rc = 0;
1561 xmlChar *expire, *incr;
1562 char *p;
1563 time_t e, e_orig, i;
1564 time_t now = time (NULL);
1566 expire = xml_attribute_value (n, (xmlChar *)"_expire");
1567 if (!expire)
1568 return 0;
1570 errno = 0;
1571 e = strtoul ((char *)expire, &p, 10);
1572 if (errno || *p || e == ULONG_MAX || *expire == '-')
1574 xmlFree (expire);
1575 rc = GPG_ERR_ERANGE;
1576 goto fail;
1579 xmlFree (expire);
1580 incr = xml_attribute_value (n, (xmlChar *)"_age");
1581 if (!incr)
1582 return 0;
1584 i = strtoul ((char *)incr, &p, 10);
1585 if (errno || *p || i == ULONG_MAX || *incr == '-')
1587 xmlFree (incr);
1588 rc = GPG_ERR_ERANGE;
1589 goto fail;
1592 xmlFree (incr);
1593 e_orig = e;
1594 e = now + i;
1595 p = str_asprintf ("%lu", e);
1596 if (!p)
1598 rc = GPG_ERR_ENOMEM;
1599 goto fail;
1602 rc = xml_add_attribute (client, n, "_expire", p);
1603 xfree (p);
1604 if (!rc)
1605 rc = send_status (client->ctx, STATUS_EXPIRE, "%lu %lu", e_orig, e);
1607 fail:
1608 return rc;
1611 static gpg_error_t
1612 parse_opt_store_no_acl_inherit (void *data, void *value)
1614 struct client_s *client = data;
1616 (void)value;
1617 client->flags |= FLAG_NO_INHERIT_ACL;
1618 return 0;
1621 static gpg_error_t
1622 store_command (assuan_context_t ctx, char *line)
1624 struct client_s *client = assuan_get_pointer (ctx);
1625 gpg_error_t rc;
1626 size_t len;
1627 unsigned char *result;
1628 xmlNodePtr n, parent;
1629 int has_content;
1630 char *content = NULL;
1631 struct xml_request_s *req;
1632 struct argv_s *args[] = {
1633 &(struct argv_s) {"no-inherit-acl", OPTION_TYPE_NOARG,
1634 parse_opt_store_no_acl_inherit},
1635 NULL
1638 rc = parse_options (&line, args, client, 1);
1639 if (rc)
1640 return send_error (ctx, rc);
1642 if (!client->bulk_p && line && *line)
1643 return send_error (ctx, GPG_ERR_SYNTAX);
1645 rc = copy_on_write (client);
1646 if (rc)
1647 return send_error (ctx, rc);
1649 if (!client->bulk_p)
1651 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1652 if (rc)
1653 return send_error (ctx, rc);
1654 rc = xml_new_request (client, (char *)result, XML_CMD_STORE, &req);
1655 if (!result || !*result)
1657 xfree (result);
1658 return send_error (ctx, GPG_ERR_SYNTAX);
1661 len = strv_length (req->args);
1662 has_content = result[strlen ((char *)result) - 1] != '\t' && len > 1;
1663 xfree (result);
1665 else
1667 rc = xml_new_request (client, line, XML_CMD_STORE, &req);
1668 len = strv_length (req->args);
1669 has_content = line && line[strlen (line) - 1] != '\t' && len > 1;
1672 if (rc)
1673 return send_error (ctx, rc);
1675 /* Prevent passing the element content around to save some memory
1676 * (has_content). */
1677 if (*(req->args+1) && !xml_valid_element_path (req->args, has_content))
1679 xml_free_request (req);
1680 return send_error (ctx, GPG_ERR_INV_VALUE);
1683 if (has_content || !*req->args[len-1])
1685 content = req->args[len-1];
1686 req->args[len-1] = NULL;
1689 if (strv_length (req->args) > 1)
1691 rc = xml_check_recursion (client, req);
1692 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
1693 goto fail;
1696 parent = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1698 if (!rc && len > 1)
1700 rc = xml_is_element_owner (client, parent, 0);
1701 if (!rc)
1703 n = xml_find_text_node (parent->children);
1704 if (n)
1705 xmlNodeSetContent (n, (xmlChar *) content);
1706 else
1707 xmlNodeAddContent (parent, (xmlChar *) content);
1709 (void)xml_update_element_mtime (client, parent);
1710 (void)update_element_expirey (client, parent);
1714 fail:
1715 xfree (content);
1716 xml_free_request (req);
1717 return send_error (ctx, rc);
1720 static gpg_error_t
1721 xfer_data (assuan_context_t ctx, const char *line, int total)
1723 struct client_s *client = assuan_get_pointer (ctx);
1724 int to_send = total < ASSUAN_LINELENGTH ? total : ASSUAN_LINELENGTH;
1725 int sent = 0;
1726 gpg_error_t rc = 0;
1728 if (!(client->flags & FLAG_LOCK_CMD))
1729 rc = unlock_file_mutex (client, 0);
1730 if (rc && rc != GPG_ERR_NOT_LOCKED)
1731 return rc;
1733 if (client->bulk_p)
1735 client->bulk_p->result = xmalloc (total+1);
1736 if (!client->bulk_p->result)
1737 return GPG_ERR_ENOMEM;
1738 memcpy (client->bulk_p->result, line, total);
1739 client->bulk_p->result[total] = 0;
1740 client->bulk_p->result_len = total;
1741 return 0;
1744 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1745 if (rc)
1746 return rc;
1750 if (sent + to_send > total)
1751 to_send = total - sent;
1753 rc = assuan_send_data (ctx, (char *) line + sent, to_send);
1754 if (!rc)
1755 sent += to_send;
1757 while (!rc && sent < total);
1759 return rc;
1762 static gpg_error_t
1763 do_get (assuan_context_t ctx, char *line)
1765 struct client_s *client = assuan_get_pointer (ctx);
1766 gpg_error_t rc;
1767 struct xml_request_s *req;
1768 xmlNodePtr n;
1770 if (!line || !*line)
1771 return GPG_ERR_SYNTAX;
1773 rc = xml_new_request (client, line, XML_CMD_NONE, &req);
1774 if (rc)
1775 return rc;
1777 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1778 if (!rc)
1780 if (n && n->children)
1782 xmlNodePtr tmp = n;
1784 n = xml_find_text_node (n->children);
1785 if (!n || !n->content || !*n->content)
1786 rc = GPG_ERR_NO_DATA;
1787 else
1789 rc = xfer_data (ctx, (char *) n->content, xmlStrlen (n->content));
1790 if (!rc)
1792 xmlChar *expire = xml_attribute_value (tmp,
1793 (xmlChar *)"_expire");
1794 if (expire)
1796 time_t now = time (NULL);
1797 time_t e;
1798 char *p;
1800 errno = 0;
1801 e = strtoul ((char *)expire, &p, 10);
1802 if (errno || *p || e == ULONG_MAX || *expire == '-')
1803 log_write (_("invalid expire attribute value: %s"),
1804 expire);
1805 else if (now >= e)
1807 pthread_cleanup_push (xmlFree, expire);
1808 rc = send_status (ctx, STATUS_EXPIRE, "%lu 0", e);
1809 pthread_cleanup_pop (0);
1812 xmlFree (expire);
1817 else
1818 rc = GPG_ERR_NO_DATA;
1821 xml_free_request (req);
1822 return rc;
1825 static gpg_error_t
1826 get_command (assuan_context_t ctx, char *line)
1828 struct client_s *client = assuan_get_pointer (ctx);
1829 gpg_error_t rc;
1830 struct argv_s *args[] = {
1831 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1832 NULL
1835 rc = parse_options (&line, args, client, 1);
1836 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1837 rc = GPG_ERR_SYNTAX;
1838 if (rc)
1839 return send_error (ctx, rc);
1841 if (client->opts & OPT_INQUIRE)
1843 unsigned char *result;
1844 size_t len;
1846 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1847 if (rc)
1848 return send_error (ctx, rc);
1850 pthread_cleanup_push ((void *)xfree, result);
1851 rc = do_get (ctx, (char *)result);
1852 pthread_cleanup_pop (1);
1854 else
1855 rc = do_get (ctx, line);
1857 return send_error (ctx, rc);
1860 static void list_command_free1 (void *arg);
1861 static gpg_error_t
1862 realpath_command (assuan_context_t ctx, char *line)
1864 gpg_error_t rc;
1865 char **realpath = NULL;
1866 struct client_s *client = assuan_get_pointer (ctx);
1867 struct argv_s *args[] = {
1868 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1869 NULL
1872 rc = parse_options (&line, args, client, 1);
1873 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1874 rc = GPG_ERR_SYNTAX;
1875 if (rc)
1876 return send_error (ctx, rc);
1878 if (client->opts & OPT_INQUIRE)
1880 unsigned char *result;
1881 size_t len;
1883 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1884 if (rc)
1885 return send_error (ctx, rc);
1887 pthread_cleanup_push ((void *)xfree, result);
1888 (void)xml_resolve_path (client, client->doc, result, &realpath, &rc);
1889 pthread_cleanup_pop (1);
1891 else
1892 (void)xml_resolve_path (client, client->doc, (unsigned char *)line,
1893 &realpath, &rc);
1895 if (!rc)
1897 char *tmp = strv_join ((char *)"\t", realpath);
1899 strv_free (realpath);
1900 if (!tmp)
1901 return send_error (ctx, GPG_ERR_ENOMEM);
1903 pthread_cleanup_push ((void *)xfree, tmp);
1904 rc = xfer_data (ctx, tmp, strlen (tmp));
1905 pthread_cleanup_pop (1);
1908 return send_error (ctx, rc);
1911 static void
1912 list_command_free1 (void *arg)
1914 if (arg)
1915 string_free ((struct string_s *) arg, 1);
1918 static gpg_error_t
1919 parse_list_opt_recurse (void *data, void *value)
1921 struct client_s *client = data;
1923 (void)value;
1924 client->opts |= OPT_LIST_RECURSE;
1925 return 0;
1928 static gpg_error_t
1929 parse_opt_verbose (void *data, void *value)
1931 struct client_s *client = data;
1933 (void)value;
1934 client->opts |= OPT_VERBOSE;
1935 return 0;
1938 static gpg_error_t
1939 parse_opt_sexp (void *data, void *value)
1941 struct client_s *client = data;
1943 (void)value;
1944 client->opts |= OPT_SEXP;
1945 return 0;
1948 static gpg_error_t
1949 list_path_once (struct client_s *client, char *line,
1950 struct element_list_s *elements, struct string_s *result)
1952 gpg_error_t rc;
1954 rc = xml_create_path_list (client, client->doc, NULL, elements, line, 0);
1955 if (rc == GPG_ERR_ELOOP || rc == GPG_ERR_EACCES)
1956 rc = 0;
1958 if (!rc)
1960 int total = slist_length (elements->list);
1962 if (total)
1964 int i;
1966 for (i = 0; i < total; i++)
1968 char *tmp = slist_nth_data (elements->list, i);
1970 string_append_printf (result, "%s%s", tmp,
1971 i + 1 == total ? "" : "\n");
1974 else
1975 rc = GPG_ERR_NO_DATA;
1978 return rc;
1981 #define RESUMABLE_ERROR(rc) (rc == GPG_ERR_ELOOP || rc == GPG_ERR_EACCES \
1982 || rc == GPG_ERR_ELEMENT_NOT_FOUND || !rc)
1983 static gpg_error_t
1984 attribute_list_common (struct client_s *client, const char *path,
1985 char ***result)
1987 char **attrlist = NULL;
1988 int i = 0;
1989 int target = 0;
1990 xmlAttrPtr a;
1991 xmlNodePtr n, an, r;
1992 gpg_error_t rc;
1993 struct xml_request_s *req;
1995 rc = xml_new_request (client, path, XML_CMD_ATTR_LIST, &req);
1996 if (rc)
1997 return rc;
1999 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2000 xml_free_request (req);
2001 if (rc)
2002 return rc;
2004 gpg_error_t acl_rc = 0;
2005 again:
2006 acl_rc = xml_acl_check (client, n);
2007 for (a = n->properties; a; a = a->next)
2009 char **pa;
2010 int reserved = xml_reserved_attribute ((char *)a->name);
2012 if (acl_rc == GPG_ERR_EACCES && !reserved)
2013 continue;
2014 else if (acl_rc && acl_rc != GPG_ERR_EACCES)
2016 rc = acl_rc;
2017 break;
2020 if (reserved && target)
2021 continue;
2023 pa = xrealloc (attrlist, (i + 2) * sizeof (char *));
2024 if (!pa)
2026 log_write ("%s(%i): %s", __FILE__, __LINE__,
2027 pwmd_strerror (GPG_ERR_ENOMEM));
2028 rc = GPG_ERR_ENOMEM;
2029 break;
2032 attrlist = pa;
2033 an = a->children;
2034 attrlist[i] = str_asprintf ("%s %s", (char *) a->name, an && an->content
2035 ? (char *)an->content : "");
2037 if (!attrlist[i])
2039 log_write ("%s(%i): %s", __FILE__, __LINE__,
2040 pwmd_strerror (GPG_ERR_ENOMEM));
2041 rc = GPG_ERR_ENOMEM;
2042 break;
2045 attrlist[++i] = NULL;
2048 if (!rc && !attrlist)
2049 return GPG_ERR_NO_DATA;
2051 if (!rc && !target)
2053 r = xml_resolve_path (client, client->doc, (xmlChar *)path, NULL, &rc);
2054 if (RESUMABLE_ERROR (rc))
2056 rc = 0;
2057 if (r && r != n)
2059 target = 1;
2060 n = r;
2061 goto again;
2066 if (!rc)
2067 *result = attrlist;
2068 else
2069 strv_free (attrlist);
2071 return rc;
2074 static gpg_error_t
2075 create_list_sexp (struct client_s *client, struct string_s *string,
2076 struct string_s **r_string)
2078 struct string_s *str = string;
2079 gpg_error_t rc = 0;
2080 struct string_s *result = string_new ("(11:list-result");
2081 char **strv = str_split (str->str, "\n", 0);
2082 int t = strv_length (strv);
2083 int i;
2085 string_large (result);
2087 for (i = 0; i < t; i++)
2089 char **tmpv = str_split (strv[i], " ", 0);
2090 char **attrlist = NULL;
2092 result = string_append_printf (result, "(4:path%i:%s", strlen (tmpv[0]),
2093 tmpv[0]);
2094 if (tmpv[1])
2095 result = string_append_printf (result, "5:flags%i:%s", strlen (tmpv[1]),
2096 tmpv[1]);
2097 else
2098 result = string_append (result, "5:flags0:");
2100 rc = attribute_list_common (client, tmpv[0], &attrlist);
2101 if (!rc)
2103 int ai;
2104 int at = strv_length (attrlist);
2106 result = string_append (result, "(5:attrs");
2108 for (ai = 0; ai < at; ai++)
2110 char **attrv = str_split (attrlist[ai], " ", 0);
2111 char *value = strv_join (" ", attrv+1);
2113 result = string_append_printf (result, "%i:%s%i:%s",
2114 strlen (attrv[0]), attrv[0],
2115 strlen (value), value);
2116 strv_free (attrv);
2117 xfree (value);
2120 result = string_append (result, ")");
2123 result = string_append (result, ")");
2124 strv_free (attrlist);
2125 strv_free (tmpv);
2128 strv_free (strv);
2129 result = string_append (result, ")");
2130 if (!rc)
2131 *r_string = result;
2133 return rc;
2136 static gpg_error_t
2137 do_list (assuan_context_t ctx, char *line)
2139 struct client_s *client = assuan_get_pointer (ctx);
2140 gpg_error_t rc = GPG_ERR_NO_DATA;
2141 struct element_list_s *elements = NULL;
2142 struct string_s *result = NULL;
2144 if (!line || !*line)
2146 struct string_s *str = string_new (NULL);
2147 xmlNodePtr n;
2149 if (!str)
2150 return GPG_ERR_ENOMEM;
2152 string_large (str);
2153 pthread_cleanup_push ((void *)list_command_free1, str);
2154 n = xmlDocGetRootElement (client->doc);
2155 for (n = n->children; n; n = n->next)
2157 xmlChar *name;
2159 if (n->type != XML_ELEMENT_NODE)
2160 continue;
2162 name = xmlGetProp (n, (xmlChar *)"_name");
2163 if (!name)
2165 rc = GPG_ERR_ENOMEM;
2166 break;
2169 elements = xcalloc (1, sizeof (struct element_list_s));
2170 if (!elements)
2172 xmlFree (name);
2173 rc = GPG_ERR_ENOMEM;
2174 break;
2177 elements->prefix = string_new (NULL);
2178 if (!elements->prefix)
2180 xmlFree (name);
2181 xml_free_element_list (elements);
2182 rc = GPG_ERR_ENOMEM;
2183 break;
2186 elements->recurse = client->opts & OPT_LIST_RECURSE;
2187 elements->root_only = !elements->recurse;
2188 pthread_cleanup_push ((void *)xml_free_element_list, elements);
2189 rc = list_path_once (client, (char *)name, elements, str);
2190 xmlFree (name);
2191 pthread_cleanup_pop (1);
2192 if (rc)
2193 break;
2195 if (n->next)
2196 string_append (str, "\n");
2199 if (!rc)
2201 if (client->opts & OPT_SEXP)
2203 rc = create_list_sexp (client, str, &result);
2204 if (!rc)
2206 pthread_cleanup_push ((void *)list_command_free1, result);
2207 rc = xfer_data (ctx, result->str, result->len);
2208 pthread_cleanup_pop (1);
2211 else
2212 rc = xfer_data (ctx, str->str, str->len);
2215 pthread_cleanup_pop (1);
2216 return rc;
2219 elements = xcalloc (1, sizeof (struct element_list_s));
2220 if (!elements)
2221 return GPG_ERR_ENOMEM;
2223 elements->prefix = string_new (NULL);
2224 if (!elements->prefix)
2226 xml_free_element_list (elements);
2227 return GPG_ERR_ENOMEM;
2230 elements->recurse = client->opts & OPT_LIST_RECURSE;
2231 pthread_cleanup_push ((void *)xml_free_element_list, elements);
2232 struct string_s *str = string_new (NULL);
2233 string_large (str);
2234 pthread_cleanup_push ((void *)list_command_free1, str);
2235 rc = list_path_once (client, line, elements, str);
2236 if (!rc)
2238 if (client->opts & OPT_SEXP)
2240 rc = create_list_sexp (client, str, &result);
2241 if (!rc)
2243 pthread_cleanup_push ((void *)list_command_free1, result);
2244 rc = xfer_data (ctx, result->str, result->len);
2245 pthread_cleanup_pop (1);
2248 else
2249 rc = xfer_data (ctx, str->str, str->len);
2252 pthread_cleanup_pop (1);
2253 pthread_cleanup_pop (1);
2254 return rc;
2257 static gpg_error_t
2258 list_command (assuan_context_t ctx, char *line)
2260 struct client_s *client = assuan_get_pointer (ctx);
2261 gpg_error_t rc;
2262 struct argv_s *args[] = {
2263 &(struct argv_s) {"recurse", OPTION_TYPE_NOARG, parse_list_opt_recurse},
2264 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2265 /* These are deprecated but kept for backward compatibility with older
2266 * clients. */
2267 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, NULL},
2268 &(struct argv_s) {"with-target", OPTION_TYPE_NOARG, NULL},
2269 &(struct argv_s) {"all", OPTION_TYPE_NOARG, parse_list_opt_recurse},
2270 &(struct argv_s) {"no-recurse", OPTION_TYPE_NOARG, NULL},
2271 &(struct argv_s) {"sexp", OPTION_TYPE_NOARG, parse_opt_sexp},
2272 NULL
2275 if (disable_list_and_dump == 1)
2276 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2278 rc = parse_options (&line, args, client, 1);
2279 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2280 rc = GPG_ERR_SYNTAX;
2281 if (rc)
2282 return send_error (ctx, rc);
2284 if (client->opts & OPT_INQUIRE)
2286 unsigned char *result;
2287 size_t len;
2289 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2290 if (rc)
2291 return send_error (ctx, rc);
2293 pthread_cleanup_push ((void *)xfree, result);
2294 rc = do_list (ctx, (char *)result);
2295 pthread_cleanup_pop (1);
2297 else
2298 rc = do_list (ctx, line);
2300 return send_error (ctx, rc);
2304 * args[0] - element path
2306 static gpg_error_t
2307 attribute_list (assuan_context_t ctx, char **args)
2309 struct client_s *client = assuan_get_pointer (ctx);
2310 char **attrlist = NULL;
2311 gpg_error_t rc;
2312 char *line;
2314 if (!args || !args[0] || !*args[0])
2315 return GPG_ERR_SYNTAX;
2317 rc = attribute_list_common (client, args[0], &attrlist);
2318 pthread_cleanup_push ((void *)req_free, attrlist);
2320 if (!rc)
2322 line = strv_join ("\n", attrlist);
2323 if (line)
2325 pthread_cleanup_push ((void *)xfree, line);
2326 rc = xfer_data (ctx, line, strlen (line));
2327 pthread_cleanup_pop (1);
2329 else
2331 log_write ("%s(%i): %s", __FILE__, __LINE__,
2332 pwmd_strerror (GPG_ERR_ENOMEM));
2333 rc = GPG_ERR_ENOMEM;
2337 pthread_cleanup_pop (1);
2338 return rc;
2342 * args[0] - attribute
2343 * args[1] - element path
2345 static gpg_error_t
2346 attribute_delete (struct client_s *client, char **args)
2348 gpg_error_t rc;
2349 xmlNodePtr n;
2351 if (!args || !args[0] || !*args[0] || !args[1] || !*args[1])
2352 return GPG_ERR_SYNTAX;
2354 rc = xml_protected_attr (args[0]);
2355 if (rc || !strcmp (args[0], "_target"))
2356 return rc ? rc : GPG_ERR_EPERM;
2358 rc = copy_on_write (client);
2359 if (rc)
2360 return rc;
2362 if (!xml_reserved_attribute (args[0]))
2363 n = xml_resolve_path (client, client->doc, (xmlChar *)args[1], NULL, &rc);
2364 else
2366 struct xml_request_s *req;
2368 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
2369 if (rc)
2370 return rc;
2372 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2373 xml_free_request (req);
2376 if (!rc)
2377 rc = xml_is_element_owner (client, n, 0);
2379 if (!rc)
2380 rc = xml_delete_attribute (client, n, (xmlChar *) args[0]);
2382 return rc;
2386 * Creates the "_target" attribute. When other commands encounter an element
2387 * with this attribute they follow the "_target" after appending remaining
2388 * elements from the original element path to the target. The exception is the
2389 * ATTR command that operates on the element itself (for reserved attribute
2390 * names) and not the target.
2392 * If the source element path doesn't exist when using 'ATTR SET target', it is
2393 * created, but the destination element path must exist. This is similar to the
2394 * ls(1) command: ln -s src dst.
2396 * args[0] - source element path
2397 * args[1] - destination element path
2399 static gpg_error_t
2400 set_target_attribute (struct client_s *client, char **args)
2402 struct xml_request_s *req = NULL;
2403 char **src, **dst;
2404 gpg_error_t rc;
2405 xmlNodePtr n;
2407 if (!args || !args[0] || !args[1])
2408 return GPG_ERR_SYNTAX;
2410 src = str_split (args[0], "\t", 0);
2411 if (!src)
2412 return GPG_ERR_SYNTAX;
2414 if (!xml_valid_element_path (src, 0))
2416 strv_free (src);
2417 return GPG_ERR_INV_VALUE;
2420 dst = str_split (args[1], "\t", 0);
2421 if (!dst)
2423 strv_free (src);
2424 return GPG_ERR_SYNTAX;
2427 rc = copy_on_write (client);
2428 if (rc)
2429 goto fail;
2431 // Be sure the destination element path exists. */
2432 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
2433 if (rc)
2434 goto fail;
2436 (void)xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2437 if (rc && rc != GPG_ERR_EACCES)
2438 goto fail;
2440 xml_free_request (req);
2441 req = NULL;
2443 if (!strcmp (args[0], args[1]))
2445 rc = GPG_ERR_EEXIST;
2446 goto fail;
2449 rc = xml_new_request (client, args[0], XML_CMD_ATTR_TARGET, &req);
2450 if (rc)
2451 goto fail;
2453 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2454 if (rc && rc != GPG_ERR_EACCES)
2455 goto fail;
2457 if (!rc)
2459 rc = xml_add_attribute (client, n, "_target", args[1]);
2460 if (!rc)
2462 rc = xml_remove_user_attributes (client, n);
2463 if (!rc)
2464 rc = xml_unlink_node (client, n->children);
2468 fail:
2469 strv_free (src);
2470 strv_free (dst);
2471 xml_free_request (req);
2472 return rc;
2476 * args[0] - attribute
2477 * args[1] - element path
2479 static gpg_error_t
2480 attribute_get (assuan_context_t ctx, char **args)
2482 struct client_s *client = assuan_get_pointer (ctx);
2483 xmlNodePtr n;
2484 xmlChar *a;
2485 gpg_error_t rc;
2486 struct xml_request_s *req;
2488 if (!args || !args[0] || !*args[0] || !args[1] || !*args[1])
2489 return GPG_ERR_SYNTAX;
2491 if (!xml_reserved_attribute (args[0]))
2492 n = xml_resolve_path (client, client->doc, (xmlChar *)args[1], NULL, &rc);
2493 else
2495 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
2496 if (rc)
2497 return rc;
2499 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2500 xml_free_request (req);
2503 if (rc)
2504 return rc;
2506 a = xmlGetProp (n, (xmlChar *) args[0]);
2507 if (!a)
2508 return GPG_ERR_NOT_FOUND;
2510 pthread_cleanup_push ((void *)xmlFree, a);
2512 if (*a)
2513 rc = xfer_data (ctx, (char *) a, xmlStrlen (a));
2514 else
2515 rc = GPG_ERR_NO_DATA;
2517 pthread_cleanup_pop (1);
2518 return rc;
2522 * args[0] - attribute
2523 * args[1] - element path
2524 * args[2] - value
2526 static gpg_error_t
2527 attribute_set (struct client_s *client, char **args)
2529 struct xml_request_s *req;
2530 gpg_error_t rc;
2531 xmlNodePtr n;
2533 if (!args || !args[0] || !args[1])
2534 return GPG_ERR_SYNTAX;
2537 * Reserved attribute names.
2539 if ((rc = xml_protected_attr (args[0])))
2540 return rc;
2541 else if (!strcmp (args[0], "_target"))
2542 return set_target_attribute (client, args + 1);
2543 else if (!strcmp (args[0], "_acl"))
2544 rc = xml_valid_username (args[2]);
2545 else if (!xml_valid_attribute (args[0]))
2546 return GPG_ERR_INV_VALUE;
2548 if (rc)
2549 return rc;
2551 if (!xml_valid_attribute_value (args[2]))
2552 return GPG_ERR_INV_VALUE;
2554 rc = copy_on_write (client);
2555 if (rc)
2556 return rc;
2558 if (!xml_reserved_attribute (args[0]))
2560 n = xml_resolve_path (client, client->doc, (xmlChar *)args[1], NULL, &rc);
2561 if (!rc)
2563 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
2564 if (!rc)
2566 rc = xml_check_recursion (client, req);
2567 xml_free_request (req);
2571 else
2573 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
2574 if (rc)
2575 return rc;
2577 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2578 xml_free_request (req);
2581 if (!rc)
2582 rc = xml_is_element_owner (client, n, 0);
2584 if (!rc)
2585 rc = xml_add_attribute (client, n, args[0], args[2]);
2587 return rc;
2591 * req[0] - command
2592 * req[1] - attribute name or element path if command is LIST
2593 * req[2] - element path
2594 * req[2] - element path or value
2597 static gpg_error_t
2598 do_attr (assuan_context_t ctx, char *line)
2600 struct client_s *client = assuan_get_pointer (ctx);
2601 gpg_error_t rc = 0;
2602 char **req;
2604 if (!line || !*line)
2605 return GPG_ERR_SYNTAX;
2607 req = str_split (line, " ", 4);
2608 if (!req || !req[0] || !req[1])
2610 strv_free (req);
2611 return GPG_ERR_SYNTAX;
2614 pthread_cleanup_push ((void *)req_free, req);
2616 if (strcasecmp (req[0], "SET") == 0)
2617 rc = attribute_set (client, req + 1);
2618 else if (strcasecmp (req[0], "GET") == 0)
2619 rc = attribute_get (ctx, req + 1);
2620 else if (strcasecmp (req[0], "DELETE") == 0)
2621 rc = attribute_delete (client, req + 1);
2622 else if (strcasecmp (req[0], "LIST") == 0)
2623 rc = attribute_list (ctx, req + 1);
2624 else
2625 rc = GPG_ERR_SYNTAX;
2627 client->flags &= ~(FLAG_ACL_IGNORE|FLAG_ACL_ERROR);
2628 pthread_cleanup_pop (1);
2629 return rc;
2632 static gpg_error_t
2633 attr_command (assuan_context_t ctx, char *line)
2635 struct client_s *client = assuan_get_pointer (ctx);
2636 gpg_error_t rc;
2637 struct argv_s *args[] = {
2638 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2639 NULL
2642 rc = parse_options (&line, args, client, 1);
2643 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2644 rc = GPG_ERR_SYNTAX;
2645 if (rc)
2646 return send_error (ctx, rc);
2648 if (client->opts & OPT_INQUIRE)
2650 unsigned char *result;
2651 size_t len;
2653 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2654 if (rc)
2655 return send_error (ctx, rc);
2657 pthread_cleanup_push ((void *)xfree, result);
2658 rc = do_attr (ctx, (char *)result);
2659 pthread_cleanup_pop (1);
2661 else
2662 rc = do_attr (ctx, line);
2664 return send_error (ctx, rc);
2667 static gpg_error_t
2668 parse_iscached_opt_lock (void *data, void *value)
2670 struct client_s *client = data;
2672 (void) value;
2673 client->opts |= OPT_LOCK;
2674 return 0;
2677 static gpg_error_t
2678 parse_iscached_opt_agent (void *data, void *value)
2680 struct client_s *client = data;
2682 (void) value;
2683 client->opts |= OPT_CACHE_AGENT;
2684 return 0;
2687 static gpg_error_t
2688 parse_iscached_opt_sign (void *data, void *value)
2690 struct client_s *client = data;
2692 (void) value;
2693 client->opts |= OPT_CACHE_SIGN;
2694 return 0;
2697 static gpg_error_t
2698 iscached_command (assuan_context_t ctx, char *line)
2700 struct client_s *client = assuan_get_pointer (ctx);
2701 gpg_error_t rc;
2702 int defer = 0;
2703 struct argv_s *args[] = {
2704 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_iscached_opt_lock},
2705 &(struct argv_s) {"agent", OPTION_TYPE_NOARG, parse_iscached_opt_agent},
2706 &(struct argv_s) {"sign", OPTION_TYPE_NOARG, parse_iscached_opt_sign},
2707 NULL
2710 if (!line || !*line)
2711 return send_error (ctx, GPG_ERR_SYNTAX);
2713 rc = parse_options (&line, args, client, 1);
2714 if (rc)
2715 return send_error (ctx, rc);
2716 else if (!valid_filename (line))
2717 return send_error (ctx, GPG_ERR_INV_VALUE);
2719 if (!(client->flags & FLAG_OPEN)
2720 && ((client->opts & OPT_CACHE_AGENT) || (client->opts & OPT_CACHE_SIGN)))
2721 return send_error (ctx, GPG_ERR_INV_STATE);
2723 rc = cache_iscached (line, &defer, (client->opts & OPT_CACHE_AGENT),
2724 (client->opts & OPT_CACHE_SIGN));
2725 if (!rc && defer)
2726 rc = GPG_ERR_NO_DATA;
2728 if (!rc)
2730 struct cache_data_s *cdata = cache_get_data (line, NULL);
2732 if (cdata)
2734 rc = validate_checksum (client, line, cdata, NULL, NULL, 1);
2735 if (rc == GPG_ERR_CHECKSUM)
2736 rc = GPG_ERR_NO_DATA;
2740 if (client->opts & OPT_LOCK
2741 && (!rc || gpg_err_code (rc) == GPG_ERR_NO_DATA
2742 || gpg_err_code (rc) == GPG_ERR_ENOENT))
2744 gpg_error_t trc = rc;
2746 if (client->filename && strcmp (line, client->filename))
2747 reset_client (client);
2749 xfree (client->filename);
2750 client->filename = str_dup (line);
2751 rc = do_lock (client, 1);
2752 if (!rc)
2753 rc = trc;
2756 return send_error (ctx, rc);
2759 static gpg_error_t
2760 clearcache_command (assuan_context_t ctx, char *line)
2762 struct client_s *client = assuan_get_pointer (ctx);
2763 gpg_error_t rc = 0, all_rc = 0;
2764 int i;
2765 int t;
2766 int all = 0;
2767 struct client_thread_s *once = NULL;
2768 unsigned count;
2770 cache_lock ();
2771 pthread_cleanup_push (cache_unlock, NULL);
2772 count = cache_file_count ();
2773 MUTEX_LOCK (&cn_mutex);
2774 pthread_cleanup_push ((void *)release_mutex_cb, &cn_mutex);
2776 if (!line || !*line)
2777 all = 1;
2779 t = slist_length (cn_thread_list);
2781 for (i = 0; i < t; i++)
2783 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2784 assuan_peercred_t peer;
2786 if (!thd->cl)
2787 continue;
2789 /* Lock each connected clients' file mutex to prevent any other client
2790 * from accessing the cache entry (the file mutex is locked upon
2791 * command startup). The cache for the entry is not cleared if the
2792 * file mutex is locked by another client to prevent this function
2793 * from blocking. Rather, it returns an error.
2795 if (all)
2797 if (thd->cl->filename)
2799 rc = do_validate_peer (ctx, thd->cl->filename, &peer, NULL);
2800 /* The current client doesn't have permission to open the other
2801 * filename do to "access" configuration parameter in a filename
2802 * section. Since we are clearning all cache entries the error
2803 * will be returned later during cache_clear(). */
2804 if (rc)
2806 rc = 0;
2807 continue;
2810 else // Idle client without opened file?
2811 continue;
2813 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->filename, -1, 0, -1);
2814 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2816 /* The current client owns the lock. */
2817 if (pthread_equal (pthread_self (), thd->tid))
2818 rc = 0;
2819 else
2821 if (cache_iscached (thd->cl->filename, NULL, 0, 0)
2822 == GPG_ERR_NO_DATA)
2824 rc = 0;
2825 continue;
2828 /* The cache entry will be cleared when the other client
2829 * disconnects and cache_timer_thread() does its thing. */
2830 cache_defer_clear (thd->cl->filename);
2833 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
2835 rc = 0;
2836 continue;
2839 if (!rc)
2841 rc = cache_clear (NULL, thd->cl->filename, 1, 0);
2842 cache_unlock_mutex (thd->cl->filename, 0);
2845 if (rc)
2846 all_rc = rc;
2848 rc = 0;
2850 else
2852 /* A single data filename was specified. Lock only this data file
2853 * mutex and free the cache entry. */
2854 rc = do_validate_peer (ctx, line, &peer, NULL);
2855 if (rc == GPG_ERR_FORBIDDEN)
2856 rc = peer_is_invoker (client);
2858 if (rc == GPG_ERR_EACCES)
2859 rc = GPG_ERR_FORBIDDEN;
2861 if (!rc && thd->cl->filename && !strcmp (thd->cl->filename , line))
2863 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->filename, -1, 0, -1);
2864 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2866 /* The current client owns the lock. */
2867 if (pthread_equal (pthread_self (), thd->tid))
2868 rc = 0;
2871 if (!rc)
2873 once = thd;
2874 rc = cache_clear (NULL, thd->cl->filename, 1, 0);
2875 cache_unlock_mutex (thd->cl->filename, 0);
2877 else
2878 cache_defer_clear (thd->cl->filename);
2880 /* Found a client with the opened file. The cache entry has been
2881 * either cleared (self) or deferred to be cleared. */
2882 break;
2887 /* Only connected clients' cache entries have been cleared. Now clear any
2888 * remaining cache entries without clients but only if there wasn't an
2889 * error from above since this would defeat the locking check of the
2890 * remaining entries. */
2891 if (all && !all_rc && cache_file_count ())
2893 rc = cache_clear (client, NULL, 1, 0);
2894 if (rc == GPG_ERR_EACCES)
2895 rc = GPG_ERR_FORBIDDEN;
2898 /* No clients are using the specified file. */
2899 else if (!all_rc && !rc && !once)
2900 rc = cache_clear (NULL, line, 1, 0);
2902 /* Release the connection mutex. */
2903 pthread_cleanup_pop (1);
2905 if (!rc || (cache_file_count () && count != cache_file_count ()))
2906 send_status_all (STATUS_CACHE, NULL);
2908 /* Release the cache mutex. */
2909 pthread_cleanup_pop (1);
2911 /* One or more files were locked while clearing all cache entries. */
2912 if (all_rc)
2913 rc = all_rc;
2915 return send_error (ctx, rc);
2918 static gpg_error_t
2919 cachetimeout_command (assuan_context_t ctx, char *line)
2921 struct client_s *client = assuan_get_pointer (ctx);
2922 long timeout;
2923 char **req = str_split (line, " ", 0);
2924 char *p;
2925 gpg_error_t rc = 0;
2927 if (!(client->flags & FLAG_OPEN))
2928 return send_error (ctx, GPG_ERR_INV_STATE);
2930 if (!req || !*req || strv_length (req) > 1)
2932 strv_free (req);
2933 return send_error (ctx, GPG_ERR_SYNTAX);
2936 errno = 0;
2937 timeout = strtol (req[0], &p, 10);
2938 if (errno != 0 || *p || timeout < (long)-1)
2939 rc = GPG_ERR_SYNTAX;
2941 if (!rc)
2943 rc = cache_set_timeout (client->filename, timeout);
2944 if (!rc || gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
2946 rc = 0;
2947 MUTEX_LOCK (&rcfile_mutex);
2948 config_set_long_param (&global_config, client->filename,
2949 "cache_timeout", req[0]);
2950 MUTEX_UNLOCK (&rcfile_mutex);
2954 strv_free (req);
2955 return send_error (ctx, rc);
2958 static gpg_error_t
2959 dump_command (assuan_context_t ctx, char *line)
2961 xmlChar *xml;
2962 int len;
2963 struct client_s *client = assuan_get_pointer (ctx);
2964 gpg_error_t rc;
2966 if (disable_list_and_dump == 1)
2967 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2969 if (line && *line)
2970 return send_error (ctx, GPG_ERR_SYNTAX);
2972 rc = peer_is_invoker(client);
2973 if (rc)
2974 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
2976 xmlDocDumpFormatMemory (client->doc, &xml, &len, 1);
2978 if (!xml)
2980 log_write ("%s(%i): %s", __FILE__, __LINE__,
2981 pwmd_strerror (GPG_ERR_ENOMEM));
2982 return send_error (ctx, GPG_ERR_ENOMEM);
2985 pthread_cleanup_push ((void *)xmlFree, xml);
2986 rc = xfer_data (ctx, (char *) xml, len);
2987 pthread_cleanup_pop (1);
2988 return send_error (ctx, rc);
2991 static gpg_error_t
2992 getconfig_command (assuan_context_t ctx, char *line)
2994 struct client_s *client = assuan_get_pointer (ctx);
2995 gpg_error_t rc = 0;
2996 char filename[255] = { 0 }, param[747] = { 0 };
2997 char *p, *tmp = NULL, *fp = client->filename, *paramp = line;
2999 if (!line || !*line)
3000 return send_error (ctx, GPG_ERR_SYNTAX);
3002 if (strchr (line, ' '))
3004 int ret = sscanf (line, " %254[^ ] %746c", filename, param);
3006 if (ret <= 0)
3007 return send_error (ctx, gpg_error_from_syserror());
3008 paramp = param;
3009 fp = filename;
3012 if (fp && !valid_filename (fp))
3013 return send_error (ctx, GPG_ERR_INV_VALUE);
3015 paramp = str_down (paramp);
3016 p = config_get_value (fp ? fp : "global", paramp);
3017 if (!p)
3018 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
3020 tmp = expand_homedir (p);
3021 xfree (p);
3022 if (!tmp)
3024 log_write ("%s(%i): %s", __FILE__, __LINE__,
3025 pwmd_strerror (GPG_ERR_ENOMEM));
3026 return send_error (ctx, GPG_ERR_ENOMEM);
3029 p = tmp;
3030 pthread_cleanup_push ((void *)xfree, p);
3031 rc = xfer_data (ctx, p, strlen (p));
3032 pthread_cleanup_pop (1);
3033 return send_error (ctx, rc);
3036 struct xpath_s
3038 xmlXPathContextPtr xp;
3039 xmlXPathObjectPtr result;
3040 xmlBufferPtr buf;
3041 char **req;
3044 static void
3045 xpath_command_free (void *arg)
3047 struct xpath_s *xpath = arg;
3049 if (!xpath)
3050 return;
3052 req_free (xpath->req);
3054 if (xpath->buf)
3055 xmlBufferFree (xpath->buf);
3057 if (xpath->result)
3058 xmlXPathFreeObject (xpath->result);
3060 if (xpath->xp)
3061 xmlXPathFreeContext (xpath->xp);
3064 static gpg_error_t
3065 do_xpath (assuan_context_t ctx, char *line)
3067 gpg_error_t rc;
3068 struct client_s *client = assuan_get_pointer (ctx);
3069 struct xpath_s _x = { 0 };
3070 struct xpath_s *xpath = &_x;
3072 if (!line || !*line)
3073 return GPG_ERR_SYNTAX;
3075 if ((xpath->req = str_split (line, "\t", 2)) == NULL)
3077 if (strv_printf (&xpath->req, "%s", line) == 0)
3078 return GPG_ERR_ENOMEM;
3081 if (xpath->req[1])
3083 rc = copy_on_write (client);
3084 if (rc)
3085 goto fail;
3088 xpath->xp = xmlXPathNewContext (client->doc);
3089 if (!xpath->xp)
3091 rc = GPG_ERR_BAD_DATA;
3092 goto fail;
3095 xpath->result =
3096 xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
3097 if (!xpath->result)
3099 rc = GPG_ERR_BAD_DATA;
3100 goto fail;
3103 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
3105 rc = GPG_ERR_ELEMENT_NOT_FOUND;
3106 goto fail;
3109 rc = xml_recurse_xpath_nodeset (client, client->doc,
3110 xpath->result->nodesetval,
3111 (xmlChar *) xpath->req[1], &xpath->buf, 0,
3112 NULL);
3113 if (rc)
3114 goto fail;
3115 else if (!xpath->req[1] && !xmlBufferLength (xpath->buf))
3117 rc = GPG_ERR_NO_DATA;
3118 goto fail;
3120 else if (xpath->req[1])
3122 rc = 0;
3123 goto fail;
3126 pthread_cleanup_push ((void *)xpath_command_free, &xpath);
3127 rc = xfer_data (ctx, (char *) xmlBufferContent (xpath->buf),
3128 xmlBufferLength (xpath->buf));
3129 pthread_cleanup_pop (0);
3130 fail:
3131 xpath_command_free (xpath);
3132 return rc;
3135 static gpg_error_t
3136 xpath_command (assuan_context_t ctx, char *line)
3138 struct client_s *client = assuan_get_pointer (ctx);
3139 gpg_error_t rc;
3140 struct argv_s *args[] = {
3141 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3142 NULL
3145 if (disable_list_and_dump == 1)
3146 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
3148 rc = peer_is_invoker(client);
3149 if (rc)
3150 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
3152 rc = parse_options (&line, args, client, 1);
3153 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3154 rc = GPG_ERR_SYNTAX;
3155 if (rc)
3156 return send_error (ctx, rc);
3158 if (client->opts & OPT_INQUIRE)
3160 unsigned char *result;
3161 size_t len;
3163 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3164 if (rc)
3165 return send_error (ctx, rc);
3167 pthread_cleanup_push ((void *)xfree, result);
3168 rc = do_xpath (ctx, (char *)result);
3169 pthread_cleanup_pop (1);
3171 else
3172 rc = do_xpath (ctx, line);
3174 return send_error (ctx, rc);
3177 static gpg_error_t
3178 do_xpathattr (assuan_context_t ctx, char *line)
3180 struct client_s *client = assuan_get_pointer (ctx);
3181 gpg_error_t rc;
3182 char **req = NULL;
3183 int cmd = 0; //SET
3184 struct xpath_s _x = { 0 };
3185 struct xpath_s *xpath = &_x;
3187 if (!line || !*line)
3188 return GPG_ERR_SYNTAX;
3190 if ((req = str_split (line, " ", 3)) == NULL)
3191 return GPG_ERR_ENOMEM;
3193 if (!req[0])
3195 rc = GPG_ERR_SYNTAX;
3196 goto fail;
3199 if (!strcasecmp (req[0], "SET"))
3200 cmd = 0;
3201 else if (!strcasecmp (req[0], "DELETE"))
3202 cmd = 1;
3203 else
3205 rc = GPG_ERR_SYNTAX;
3206 goto fail;
3209 if (!req[1] || !req[2])
3211 rc = GPG_ERR_SYNTAX;
3212 goto fail;
3215 if ((xpath->req = str_split (req[2], "\t", 3)) == NULL)
3217 rc = GPG_ERR_ENOMEM;
3218 goto fail;
3221 if (!xpath->req[0] || (!xpath->req[1] && !cmd) || (xpath->req[1] && cmd))
3223 rc = GPG_ERR_SYNTAX;
3224 goto fail;
3227 rc = copy_on_write (client);
3228 if (rc)
3229 goto fail;
3231 xpath->xp = xmlXPathNewContext (client->doc);
3232 if (!xpath->xp)
3234 rc = GPG_ERR_BAD_DATA;
3235 goto fail;
3238 xpath->result = xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
3239 if (!xpath->result)
3241 rc = GPG_ERR_BAD_DATA;
3242 goto fail;
3245 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
3247 rc = GPG_ERR_ELEMENT_NOT_FOUND;
3248 goto fail;
3251 rc = xml_recurse_xpath_nodeset (client, client->doc,
3252 xpath->result->nodesetval,
3253 (xmlChar *) xpath->req[1], &xpath->buf, cmd,
3254 (xmlChar *) req[1]);
3256 fail:
3257 xpath_command_free (xpath);
3258 strv_free (req);
3259 return rc;
3262 /* XPATHATTR SET|DELETE <name> <expression>[<TAB>[value]] */
3263 static gpg_error_t
3264 xpathattr_command (assuan_context_t ctx, char *line)
3266 struct client_s *client = assuan_get_pointer (ctx);
3267 gpg_error_t rc;
3268 struct argv_s *args[] = {
3269 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3270 NULL
3273 if (disable_list_and_dump == 1)
3274 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
3276 rc = peer_is_invoker(client);
3277 if (rc)
3278 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
3280 rc = parse_options (&line, args, client, 1);
3281 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3282 rc = GPG_ERR_SYNTAX;
3283 if (rc)
3284 return send_error (ctx, rc);
3286 if (client->opts & OPT_INQUIRE)
3288 unsigned char *result;
3289 size_t len;
3291 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3292 if (rc)
3293 return send_error (ctx, rc);
3295 pthread_cleanup_push ((void *)xfree, result);
3296 rc = do_xpathattr (ctx, (char *)result);
3297 pthread_cleanup_pop (1);
3299 else
3300 rc = do_xpathattr (ctx, line);
3302 return send_error (ctx, rc);
3305 static gpg_error_t
3306 do_import (struct client_s *client, const char *root_element,
3307 unsigned char *content)
3309 xmlDocPtr doc = NULL;
3310 xmlNodePtr n = NULL, root;
3311 gpg_error_t rc = 0;
3312 struct string_s *str = NULL, *tstr = NULL;
3313 struct xml_request_s *req = NULL;
3315 if (!content || !*content)
3316 return GPG_ERR_SYNTAX;
3318 if (root_element)
3320 rc = xml_new_request (client, root_element, XML_CMD_STORE, &req);
3321 if (rc)
3323 xfree (content);
3324 return rc;
3327 if (!xml_valid_element_path (req->args, 0))
3329 xml_free_request (req);
3330 xfree (content);
3331 return GPG_ERR_INV_VALUE;
3335 str = string_new_content ((char *)content);
3336 tstr = string_prepend (str, "<pwmd>");
3337 if (tstr)
3339 str = tstr;
3340 tstr = string_append (str, "</pwmd>");
3341 if (!tstr)
3342 rc = GPG_ERR_ENOMEM;
3343 else
3344 str = tstr;
3346 else
3347 rc = GPG_ERR_ENOMEM;
3349 if (rc)
3350 goto fail;
3352 doc = xmlReadDoc ((xmlChar *) str->str, NULL, "UTF-8", XML_PARSE_NOBLANKS);
3353 string_free (str, 1);
3354 if (!doc)
3356 rc = GPG_ERR_BAD_DATA;
3357 goto fail;
3360 root = xmlDocGetRootElement (doc);
3361 root = root->children;
3362 if (!root || root->type != XML_ELEMENT_NODE)
3364 rc = GPG_ERR_BAD_DATA;
3365 goto fail;
3368 rc = xml_validate_import (client, root);
3369 if (rc)
3370 goto fail;
3372 if (req)
3374 /* Create the new specified root element path, if needed. */
3375 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc),
3376 &rc);
3377 if (rc)
3378 goto fail;
3380 /* Overwrite the children of the specified root element path. */
3381 (void)xml_unlink_node (client, n->children);
3382 n->children = NULL;
3384 else
3385 n = xmlDocGetRootElement (client->doc);
3387 if (n)
3389 xmlNodePtr copy;
3390 xmlChar *name = xml_attribute_value (root, (xmlChar *)"_name");
3392 if (!name)
3393 rc = GPG_ERR_BAD_DATA;
3394 else
3395 rc = xml_is_element_owner (client, n, 0);
3397 if (!rc && !req)
3399 /* No --root argument passed. Overwrite the current documents' root
3400 * element matching the root element of the imported data. */
3401 xml_free_request (req);
3402 req = NULL;
3403 rc = xml_new_request (client, (char *)name, XML_CMD_DELETE, &req);
3404 xmlFree (name);
3405 if (!rc)
3407 xmlNodePtr tmp;
3409 tmp = xml_find_elements (client, req,
3410 xmlDocGetRootElement (req->doc), &rc);
3411 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3412 goto fail;
3414 if (!rc)
3416 rc = xml_is_element_owner (client, tmp, 0);
3417 if (rc)
3418 goto fail;
3421 (void)xml_unlink_node (client, tmp);
3422 rc = 0;
3426 if (!rc)
3428 copy = xmlCopyNodeList (root);
3429 if (!copy)
3430 rc = GPG_ERR_ENOMEM;
3431 else
3433 n = xmlAddChildList (n, copy);
3434 if (!n)
3435 rc = GPG_ERR_ENOMEM;
3440 if (!rc && n && n->parent)
3441 rc = xml_update_element_mtime (client, n->parent);
3443 fail:
3444 xml_free_request (req);
3446 if (doc)
3447 xmlFreeDoc (doc);
3449 return rc;
3452 static gpg_error_t
3453 parse_import_opt_root (void *data, void *value)
3455 struct client_s *client = data;
3457 client->import_root = str_dup (value);
3458 return client->import_root ? 0 : GPG_ERR_ENOMEM;
3461 static gpg_error_t
3462 import_command (assuan_context_t ctx, char *line)
3464 gpg_error_t rc;
3465 struct client_s *client = assuan_get_pointer (ctx);
3466 unsigned char *result;
3467 size_t len;
3468 struct argv_s *args[] = {
3469 &(struct argv_s) {
3470 "root", OPTION_TYPE_ARG, parse_import_opt_root
3472 NULL
3475 xfree (client->import_root);
3476 client->import_root = NULL;
3477 rc = parse_options (&line, args, client, client->bulk_p ? 1 : 0);
3478 if (rc)
3479 return send_error (ctx, rc);
3481 rc = copy_on_write (client);
3482 if (rc)
3483 return send_error (ctx, rc);
3485 if (!client->bulk_p)
3487 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3488 if (rc)
3490 xfree (client->import_root);
3491 client->import_root = NULL;
3492 return send_error (ctx, rc);
3494 rc = do_import (client, client->import_root, result);
3496 else
3498 char *p = str_dup (line);
3500 if (!p)
3501 rc = GPG_ERR_ENOMEM;
3502 else
3503 rc = do_import (client, client->import_root, (unsigned char *)p);
3506 xfree (client->import_root);
3507 client->import_root = NULL;
3508 return send_error (ctx, rc);
3511 static gpg_error_t
3512 do_lock (struct client_s *client, int add)
3514 gpg_error_t rc = lock_file_mutex (client, add);
3516 if (!rc)
3517 client->flags |= FLAG_LOCK_CMD;
3519 return rc;
3522 static gpg_error_t
3523 lock_command (assuan_context_t ctx, char *line)
3525 struct client_s *client = assuan_get_pointer (ctx);
3526 gpg_error_t rc;
3528 if (line && *line)
3529 return send_error (ctx, GPG_ERR_SYNTAX);
3531 rc = do_lock (client, 0);
3532 return send_error (ctx, rc);
3535 static gpg_error_t
3536 unlock_command (assuan_context_t ctx, char *line)
3538 struct client_s *client = assuan_get_pointer (ctx);
3539 gpg_error_t rc;
3541 if (line && *line)
3542 return send_error (ctx, GPG_ERR_SYNTAX);
3544 rc = unlock_file_mutex (client, 0);
3545 return send_error (ctx, rc);
3548 static void
3549 set_env (const char *name, char *buf, size_t size, const char *value)
3551 MUTEX_LOCK (&rcfile_mutex);
3552 if (!value || !*value)
3554 unsetenv (name);
3555 buf[0] = 0;
3557 else if (!buf[0] || strcmp (buf, value))
3559 snprintf (buf, size, "%s=%s", name, value);
3560 putenv (buf);
3563 MUTEX_UNLOCK (&rcfile_mutex);
3566 static gpg_error_t
3567 option_command (assuan_context_t ctx, char *line)
3569 struct client_s *client = assuan_get_pointer (ctx);
3570 gpg_error_t rc = 0;
3571 char namebuf[255] = { 0 };
3572 char *name = namebuf;
3573 char *value = NULL, *p, *tmp = NULL;
3575 p = strchr (line, '=');
3576 if (!p)
3578 strncpy (namebuf, line, sizeof(namebuf));
3579 namebuf[sizeof(namebuf)-1] = 0;
3581 else
3583 tmp = str_dup (line);
3584 if (!tmp)
3585 return send_error (ctx, GPG_ERR_ENOMEM);
3587 tmp[strlen (line) - strlen (p)] = 0;
3588 strncpy (namebuf, tmp, sizeof (namebuf));
3589 namebuf[sizeof(namebuf)-1] = 0;
3590 xfree (tmp);
3591 tmp = NULL;
3592 value = p+1;
3595 log_write2 ("OPTION name='%s' value='%s'", name, value);
3597 if (strcasecmp (name, (char *) "lock-timeout") == 0)
3599 long n = 0;
3601 if (value)
3603 n = strtol (value, &tmp, 10);
3604 if (tmp && *tmp)
3605 return send_error (ctx, GPG_ERR_INV_VALUE);
3608 client->lock_timeout = n;
3610 else if (strcasecmp (name, (char *) "client-state") == 0)
3612 long n = 0;
3614 MUTEX_LOCK (&client->thd->status_mutex);
3615 if (value)
3617 n = strtol (value, &tmp, 10);
3618 if ((tmp && *tmp) || (n < 0 || n > 1))
3620 MUTEX_UNLOCK (&client->thd->status_mutex);
3621 return send_error (ctx, GPG_ERR_INV_VALUE);
3623 client->thd->send_state = n;
3625 else
3626 client->thd->send_state = 0;
3627 MUTEX_UNLOCK (&client->thd->status_mutex);
3629 else if (strcasecmp (name, (char *) "NAME") == 0)
3631 if (value && strchr (value, ' '))
3632 rc = GPG_ERR_INV_VALUE;
3633 else
3635 MUTEX_LOCK (&cn_mutex);
3636 tmp = pthread_getspecific (thread_name_key);
3637 pthread_setspecific (thread_name_key, NULL);
3638 xfree (tmp);
3639 xfree (client->thd->name);
3640 client->thd->name = NULL;
3641 if (value && *value)
3643 pthread_setspecific (thread_name_key, str_dup (value));
3644 client->thd->name = str_dup (value);
3646 MUTEX_UNLOCK (&cn_mutex);
3649 else if (strcasecmp (name, "disable-pinentry") == 0)
3651 int n = 1;
3653 if (value && *value)
3655 n = (int) strtol (value, &tmp, 10);
3656 if (*tmp || n < 0 || n > 1)
3657 return send_error (ctx, GPG_ERR_INV_VALUE);
3660 if (n)
3661 client->flags |= FLAG_NO_PINENTRY;
3662 else
3663 client->flags &= ~FLAG_NO_PINENTRY;
3665 else if (strcasecmp (name, "ttyname") == 0)
3666 set_env ("GPG_TTY", env_gpg_tty, sizeof (env_gpg_tty), value);
3667 else if (strcasecmp (name, "ttytype") == 0)
3668 set_env ("TERM", env_term, sizeof (env_term), value);
3669 else if (strcasecmp (name, "display") == 0)
3670 set_env ("DISPLAY", env_display, sizeof (env_display), value);
3671 else if (strcasecmp (name, "lc_messages") == 0)
3674 else if (strcasecmp (name, "lc_ctype") == 0)
3677 else if (strcasecmp (name, "desc") == 0)
3680 else if (strcasecmp (name, "pinentry-timeout") == 0)
3683 else
3684 rc = GPG_ERR_UNKNOWN_OPTION;
3686 return send_error (ctx, rc);
3689 static gpg_error_t
3690 do_rename (assuan_context_t ctx, char *line)
3692 struct client_s *client = assuan_get_pointer (ctx);
3693 char **args, *p;
3694 xmlNodePtr src, dst;
3695 struct string_s *str = NULL, *tstr;
3696 struct xml_request_s *req;
3697 gpg_error_t rc;
3699 if (!line || !*line)
3700 return GPG_ERR_SYNTAX;
3702 args = str_split (line, " ", 0);
3703 if (!args || strv_length (args) != 2)
3705 strv_free (args);
3706 return GPG_ERR_SYNTAX;
3709 if (!xml_valid_element ((xmlChar *) args[1]))
3711 strv_free (args);
3712 return GPG_ERR_INV_VALUE;
3715 rc = xml_new_request (client, args[0], XML_CMD_RENAME, &req);
3716 if (rc)
3718 strv_free (args);
3719 return rc;
3722 src = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3723 if (rc)
3724 goto fail;
3726 rc = xml_is_element_owner (client, src, 0);
3727 if (rc)
3728 goto fail;
3730 xmlChar *a = xmlGetProp (src, (xmlChar *) "_name");
3731 if (!a)
3733 rc = GPG_ERR_ENOMEM;
3734 goto fail;
3737 /* To prevent unwanted effects:
3739 * <element _name="a"><element _name="b"/></element>
3741 * RENAME a<TAB>b b
3743 if (xmlStrEqual (a, (xmlChar *) args[1]))
3745 xmlFree (a);
3746 rc = GPG_ERR_EEXIST;
3747 goto fail;
3750 xmlFree (a);
3751 str = string_new (args[0]);
3752 if (!str)
3754 rc = GPG_ERR_ENOMEM;
3755 goto fail;
3758 p = strrchr (str->str, '\t');
3759 if (p)
3760 tstr = string_truncate (str, strlen (str->str)-strlen (p));
3761 else
3762 tstr = string_truncate (str, 0);
3764 if (!tstr)
3766 string_free (str, 1);
3767 rc = GPG_ERR_ENOMEM;
3768 goto fail;
3771 str = tstr;
3772 tstr = string_append_printf (str, "%s%s", str->len ? "\t" : "", args[1]);
3773 if (!tstr)
3775 string_free (str, 1);
3776 rc = GPG_ERR_ENOMEM;
3777 goto fail;
3780 str = tstr;
3781 xml_free_request (req);
3782 rc = xml_new_request (client, str->str, XML_CMD_RENAME, &req);
3783 string_free (str, 1);
3784 if (rc)
3786 req = NULL;
3787 goto fail;
3790 dst = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3791 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3792 goto fail;
3794 rc = 0;
3796 /* Target may exist:
3798 * <element _name="a"/>
3799 * <element _name="b" target="a"/>
3801 * RENAME b a
3803 if (src == dst)
3805 rc = GPG_ERR_EEXIST;
3806 goto fail;
3809 if (dst)
3811 rc = xml_is_element_owner (client, dst, 0);
3812 if (rc)
3813 goto fail;
3815 rc = xml_add_attribute (client, src, "_name", args[1]);
3816 if (!rc)
3817 xml_unlink_node (client, dst);
3819 else
3820 rc = xml_add_attribute (client, src, "_name", args[1]);
3822 fail:
3823 xml_free_request (req);
3824 strv_free (args);
3825 return rc;
3828 static gpg_error_t
3829 rename_command (assuan_context_t ctx, char *line)
3831 struct client_s *client = assuan_get_pointer (ctx);
3832 gpg_error_t rc;
3833 struct argv_s *args[] = {
3834 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3835 NULL
3838 rc = parse_options (&line, args, client, 1);
3839 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3840 rc = GPG_ERR_SYNTAX;
3841 if (rc)
3842 return send_error (ctx, rc);
3844 rc = copy_on_write (client);
3845 if (rc)
3846 return send_error (ctx, rc);
3848 if (client->opts & OPT_INQUIRE)
3850 unsigned char *result;
3851 size_t len;
3853 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3854 if (rc)
3855 return send_error (ctx, rc);
3857 pthread_cleanup_push ((void *)xfree, result);
3858 rc = do_rename (ctx, (char *)result);
3859 pthread_cleanup_pop (1);
3861 else
3862 rc = do_rename (ctx, line);
3864 return send_error (ctx, rc);
3867 static gpg_error_t
3868 do_copy (assuan_context_t ctx, char *line)
3870 struct client_s *client = assuan_get_pointer (ctx);
3871 char **args, **targs;
3872 xmlNodePtr src, dst, tree = NULL;
3873 struct xml_request_s *req;
3874 gpg_error_t rc;
3876 if (!line || !*line)
3877 return GPG_ERR_SYNTAX;
3879 args = str_split (line, " ", 0);
3880 if (!args || strv_length (args) != 2)
3882 strv_free (args);
3883 return GPG_ERR_SYNTAX;
3886 targs = str_split (args[1], "\t", 0);
3887 if (!targs)
3889 strv_free (args);
3890 return GPG_ERR_SYNTAX;
3893 if (!xml_valid_element_path (targs, 0))
3895 strv_free (args);
3896 strv_free (targs);
3897 return GPG_ERR_INV_VALUE;
3899 strv_free (targs);
3901 rc = xml_new_request (client, args[0], XML_CMD_NONE, &req);
3902 if (rc)
3904 strv_free (args);
3905 return rc;
3908 src = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3909 if (rc)
3910 goto fail;
3912 tree = xmlCopyNodeList (src);
3913 if (!tree)
3915 rc = GPG_ERR_ENOMEM;
3916 goto fail;
3919 xml_free_request (req);
3920 /* Create the destination element path if it does not exist. */
3921 rc = xml_new_request (client, args[1], XML_CMD_STORE, &req);
3922 if (rc)
3924 req = NULL;
3925 goto fail;
3928 dst = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3929 if (rc)
3930 goto fail;
3932 rc = xml_is_element_owner (client, dst, 0);
3933 if (rc)
3934 goto fail;
3936 if (!(req->flags & XML_REQUEST_FLAG_CREATED))
3938 rc = xml_validate_target (client, req->doc, args[1], src);
3939 if (rc || src == dst)
3941 rc = rc ? rc : GPG_ERR_EEXIST;
3942 goto fail;
3946 /* Merge any attributes from the src node to the initial dst node. */
3947 for (xmlAttrPtr attr = tree->properties; attr; attr = attr->next)
3949 if (xmlStrEqual (attr->name, (xmlChar *) "_name"))
3950 continue;
3952 xmlAttrPtr a = xmlHasProp (dst, attr->name);
3953 if (a)
3954 xmlRemoveProp (a);
3956 xmlChar *tmp = xmlNodeGetContent (attr->children);
3957 xmlNewProp (dst, attr->name, tmp);
3958 xmlFree (tmp);
3959 /* Create the default attributes. */
3960 rc = xml_add_attribute (client, dst, NULL, NULL);
3963 xmlNodePtr n = dst->children;
3964 (void)xml_unlink_node (client, n);
3965 dst->children = NULL;
3967 if (tree->children)
3969 n = xmlCopyNodeList (tree->children);
3970 if (!n)
3972 rc = GPG_ERR_ENOMEM;
3973 goto fail;
3976 n = xmlAddChildList (dst, n);
3977 if (!n)
3979 rc = GPG_ERR_ENOMEM;
3980 goto fail;
3983 rc = xml_update_element_mtime (client, xmlDocGetRootElement (client->doc)
3984 == dst->parent ? dst : dst->parent);
3987 fail:
3988 if (tree)
3989 (void)xml_unlink_node (client, tree);
3991 xml_free_request (req);
3992 strv_free (args);
3993 return rc;
3996 static gpg_error_t
3997 copy_command (assuan_context_t ctx, char *line)
3999 struct client_s *client = assuan_get_pointer (ctx);
4000 gpg_error_t rc;
4001 struct argv_s *args[] = {
4002 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
4003 NULL
4006 rc = parse_options (&line, args, client, 1);
4007 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
4008 rc = GPG_ERR_SYNTAX;
4009 if (rc)
4010 return send_error (ctx, rc);
4012 rc = copy_on_write (client);
4013 if (rc)
4014 return send_error (ctx, rc);
4016 if (client->opts & OPT_INQUIRE)
4018 unsigned char *result;
4019 size_t len;
4021 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
4022 if (rc)
4023 return send_error (ctx, rc);
4025 pthread_cleanup_push ((void *)xfree, result);
4026 rc = do_copy (ctx, (char *)result);
4027 pthread_cleanup_pop (1);
4029 else
4030 rc = do_copy (ctx, line);
4032 return send_error (ctx, rc);
4035 static gpg_error_t
4036 do_move (assuan_context_t ctx, char *line)
4038 struct client_s *client = assuan_get_pointer (ctx);
4039 char **args;
4040 xmlNodePtr src, dst;
4041 struct xml_request_s *req;
4042 gpg_error_t rc;
4044 if (!line || !*line)
4045 return GPG_ERR_SYNTAX;
4047 args = str_split (line, " ", 0);
4048 if (!args || strv_length (args) != 2)
4050 strv_free (args);
4051 return GPG_ERR_SYNTAX;
4054 if (*args[1])
4056 char **targs = str_split (args[1], "\t", 0);
4057 if (!targs)
4059 strv_free (args);
4060 return GPG_ERR_ENOMEM;
4063 if (!xml_valid_element_path (targs, 0))
4065 strv_free (targs);
4066 strv_free (args);
4067 return GPG_ERR_INV_VALUE;
4070 strv_free (targs);
4073 rc = xml_new_request (client, args[0], XML_CMD_MOVE, &req);
4074 if (rc)
4076 strv_free (args);
4077 return rc;
4080 src = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
4081 if (rc)
4082 goto fail;
4084 rc = xml_is_element_owner (client, src, 0);
4085 if (rc)
4086 goto fail;
4088 xml_free_request (req);
4089 req = NULL;
4090 if (*args[1])
4092 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
4093 if (rc)
4094 goto fail;
4096 dst = xml_find_elements (client, req, xmlDocGetRootElement (req->doc),
4097 &rc);
4099 else
4100 dst = xmlDocGetRootElement (client->doc);
4102 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
4103 goto fail;
4105 rc = 0;
4107 for (xmlNodePtr n = dst; n; n = n->parent)
4109 if (n == src)
4111 rc = GPG_ERR_EEXIST;
4112 goto fail;
4116 if (dst)
4118 xmlChar *a = xml_attribute_value (src, (xmlChar *) "_name");
4119 xmlNodePtr dup = xml_find_element (client, dst->children, (char *) a, &rc);
4121 xmlFree (a);
4122 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
4123 goto fail;
4125 rc = 0;
4127 if (dup)
4129 if (dup == src)
4131 rc = GPG_ERR_EEXIST;
4132 goto fail;
4135 if (dst == xmlDocGetRootElement (client->doc))
4137 xmlNodePtr n = src;
4138 int match = 0;
4140 while (n->parent && n->parent != dst)
4141 n = n->parent;
4143 a = xml_attribute_value (n, (xmlChar *) "_name");
4144 xmlChar *b = xml_attribute_value (src, (xmlChar *) "_name");
4146 if (xmlStrEqual (a, b))
4148 match = 1;
4149 xmlUnlinkNode (src);
4150 (void)xml_unlink_node (client, n);
4153 xmlFree (a);
4154 xmlFree (b);
4156 if (!match)
4157 (void)xml_unlink_node (client, dup);
4159 else
4160 xmlUnlinkNode (dup);
4164 if (!dst && req && req->args && *req->args)
4166 struct xml_request_s *nreq = NULL;
4167 xmlChar *name = xml_attribute_value (src, (xmlChar *) "_name");
4169 if (src->parent == xmlDocGetRootElement (client->doc)
4170 && !strcmp ((char *) name, *req->args))
4172 xmlFree (name);
4173 rc = GPG_ERR_EEXIST;
4174 goto fail;
4177 xmlFree (name);
4178 rc = xml_new_request (client, args[1], XML_CMD_STORE, &nreq);
4179 if (!rc)
4181 dst = xml_find_elements (client, nreq,
4182 xmlDocGetRootElement (nreq->doc), &rc);
4183 xml_free_request (nreq);
4186 if (rc)
4187 goto fail;
4190 xml_update_element_mtime (client, src->parent);
4191 xmlUnlinkNode (src);
4193 dst = xmlAddChildList (dst, src);
4194 if (!dst)
4195 rc = GPG_ERR_ENOMEM;
4196 else
4197 xml_update_element_mtime (client, dst->parent);
4199 fail:
4200 xml_free_request (req);
4201 strv_free (args);
4202 return rc;
4205 static gpg_error_t
4206 move_command (assuan_context_t ctx, char *line)
4208 struct client_s *client = assuan_get_pointer (ctx);
4209 gpg_error_t rc;
4210 struct argv_s *args[] = {
4211 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
4212 NULL
4215 rc = parse_options (&line, args, client, 1);
4216 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
4217 rc = GPG_ERR_SYNTAX;
4218 if (rc)
4219 return send_error (ctx, rc);
4221 rc = copy_on_write (client);
4222 if (rc)
4223 return send_error (ctx, rc);
4225 if (client->opts & OPT_INQUIRE)
4227 unsigned char *result;
4228 size_t len;
4230 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
4231 if (rc)
4232 return send_error (ctx, rc);
4234 pthread_cleanup_push ((void *)xfree, result);
4235 rc = do_move (ctx, (char *)result);
4236 pthread_cleanup_pop (1);
4238 else
4239 rc = do_move (ctx, line);
4241 return send_error (ctx, rc);
4244 static int
4245 sort_files (const void *arg1, const void *arg2)
4247 char *const *a = arg1;
4248 char *const *b = arg2;
4250 return strcmp (*a, *b);
4253 static gpg_error_t
4254 ls_command (assuan_context_t ctx, char *line)
4256 struct client_s *client = assuan_get_pointer (ctx);
4257 gpg_error_t rc;
4258 char *tmp;
4259 char *dir;
4260 DIR *d;
4261 char *list = NULL;
4262 char **v = NULL;
4263 struct dirent *cur = NULL;
4264 struct argv_s *args[] = {
4265 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_opt_verbose},
4266 NULL
4269 rc = parse_options (&line, args, client, 0);
4270 if (rc)
4271 return send_error (ctx, rc);
4273 tmp = str_asprintf ("%s/data", homedir);
4274 dir = expand_homedir (tmp);
4275 xfree (tmp);
4276 if (!dir)
4277 return send_error (ctx, GPG_ERR_ENOMEM);
4279 d = opendir (dir);
4280 rc = gpg_error_from_errno (errno);
4282 if (!d)
4284 xfree (dir);
4285 return send_error (ctx, rc);
4288 pthread_cleanup_push ((void *)closedir, d);
4289 xfree (dir);
4290 rc = 0;
4292 while ((cur = readdir (d)))
4294 char **vtmp;
4295 struct stat st;
4297 rc = open_check_file (cur->d_name, NULL, &st, 1);
4298 if (rc)
4299 continue;
4301 if (client->opts & OPT_VERBOSE)
4302 tmp = str_asprintf ("%s %lu.%lu %lu.%lu %lu.%lu", cur->d_name,
4303 st.st_atim.tv_sec, st.st_atim.tv_nsec,
4304 st.st_mtim.tv_sec, st.st_mtim.tv_nsec,
4305 st.st_ctim.tv_sec, st.st_ctim.tv_nsec);
4306 else
4307 tmp = str_dup (cur->d_name);
4309 if (!tmp)
4311 rc = GPG_ERR_ENOMEM;
4312 break;
4315 vtmp = strv_cat (v, tmp);
4316 if (!vtmp)
4318 xfree (tmp);
4319 rc = GPG_ERR_ENOMEM;
4320 break;
4323 v = vtmp;
4326 pthread_cleanup_pop (1); // closedir (d)
4328 if (rc && rc != GPG_ERR_ENODEV)
4330 strv_free (v);
4331 return send_error (ctx, rc);
4334 rc = 0;
4335 if (v && *v)
4337 unsigned n, t = strv_length (v);
4339 qsort (v, t, sizeof (char **), sort_files);
4341 for (n = 0; n < t; n++)
4343 tmp = str_asprintf ("%s%s\n", list ? list : "", v[n]);
4344 if (!tmp)
4346 xfree (list);
4347 rc = GPG_ERR_ENOMEM;
4348 break;
4351 xfree (list);
4352 list = tmp;
4356 strv_free (v);
4357 if (rc || !list)
4358 return send_error (ctx, rc ? rc : GPG_ERR_NO_DATA);
4360 list[strlen (list) - 1] = 0;
4361 pthread_cleanup_push (xfree, list);
4362 rc = xfer_data (ctx, list, strlen (list));
4363 pthread_cleanup_pop (1);
4364 return send_error (ctx, rc);
4367 /* Run all commands in the command list 'head'. The return code isn't
4368 * considered at all for a command. It is stored in the list and later sent to
4369 * the client. */
4370 static gpg_error_t
4371 dispatch_bulk_commands (struct client_s *client, struct sexp_s **list)
4373 unsigned i;
4374 unsigned id = 0;
4375 gpg_error_t rc = 0;
4377 for (i = 0; list && list[i];)
4379 struct bulk_cmd_s *cur = list[i]->user;
4381 if (!strcmp (list[i]->tag, "command"))
4383 i++;
4384 continue;
4386 else if (!strcmp (list[i]->tag, "id"))
4388 id = i++;
4389 continue;
4392 if ((client->flags & FLAG_NO_PINENTRY) && cur->cmd->inquire)
4394 rc = send_status (client->ctx, STATUS_BULK, "BEGIN %s",
4395 list[id]->data);
4396 if (rc)
4397 break;
4400 if (!cur)
4401 continue;
4403 client->bulk_p = cur;
4404 cur->ran = 1;
4406 cur->rc = command_startup (client->ctx, cur->cmd->name);
4407 if (!cur->rc)
4408 cur->rc = cur->cmd->handler (client->ctx, list[i]->data);
4410 if ((client->flags & FLAG_NO_PINENTRY) && cur->cmd->inquire)
4412 (void)send_status (client->ctx, STATUS_BULK, "END %s",
4413 list[id]->data);
4415 command_finalize (client->ctx, cur->rc);
4416 cur->rc = cur->rc ? cur->rc : client->last_rc;
4418 do {
4419 if (list[i+1] && !strcmp (list[i+1]->tag, "rc"))
4421 gpg_error_t erc = 0;
4422 int match = 0;
4424 if (list[i+1]->data)
4426 char **rcs = str_split (list[i+1]->data, "|", 0);
4427 char **p;
4429 for (p = rcs; p && *p; p++)
4431 erc = strtoul (*p, NULL, 10);
4432 if (erc == cur->rc)
4434 match = 1;
4435 break;
4439 strv_free (rcs);
4442 if (!match)
4444 i++;
4445 continue;
4448 rc = dispatch_bulk_commands (client, list[++i]->next);
4450 else
4452 i++;
4453 break;
4455 } while (1);
4458 return rc;
4461 static gpg_error_t
4462 bulk_command (assuan_context_t ctx, char *line)
4464 struct client_s *client = assuan_get_pointer (ctx);
4465 gpg_error_t rc = 0;
4466 unsigned char *result, *p;
4467 size_t len;
4468 struct sexp_s **sexp = NULL;
4469 struct argv_s *args[] = {
4470 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
4471 NULL
4474 rc = parse_options (&line, args, client, 1);
4475 if (rc)
4476 return send_error (ctx, rc);
4478 if ((client->opts & OPT_INQUIRE) && line && *line)
4479 rc = GPG_ERR_SYNTAX;
4480 else if (!(client->opts & OPT_INQUIRE) && (!line || !*line))
4481 rc = GPG_ERR_SYNTAX;
4483 if (rc)
4484 return send_error (ctx, rc);
4486 if (client->opts & OPT_INQUIRE)
4488 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
4489 if (rc)
4490 return send_error (ctx, rc);
4491 p = result;
4493 else
4495 p = (unsigned char *)line;
4496 len = line && *line ? strlen (line) : 0;
4499 if (!len)
4500 return send_error (ctx, GPG_ERR_SYNTAX);
4502 rc = bulk_parse_commands (&sexp, (const char *)p, command_table);
4503 if (client->opts & OPT_INQUIRE)
4504 xfree (result);
4506 if (rc)
4507 return send_error (ctx, rc);
4509 pthread_cleanup_push ((void *)bulk_free_list, sexp);
4510 rc = dispatch_bulk_commands (client, sexp);
4511 pthread_cleanup_pop (0);
4512 if (!rc)
4513 rc = bulk_build_result (sexp, (char **)&result);
4515 bulk_free_list (sexp);
4517 if (!rc)
4519 pthread_cleanup_push ((void *)xfree, result);
4520 rc = xfer_data (ctx, (char *)result, strlen ((char *)result));
4521 pthread_cleanup_pop (1);
4524 return send_error (ctx, rc);
4527 static gpg_error_t
4528 nop_command (assuan_context_t ctx, char *line)
4530 return send_error (ctx, 0);
4533 static gpg_error_t
4534 bye_notify (assuan_context_t ctx, char *line)
4536 struct client_s *cl = assuan_get_pointer (ctx);
4537 gpg_error_t ret = 0;
4539 (void)line;
4540 update_client_state (cl, CLIENT_STATE_DISCON);
4542 #ifdef WITH_GNUTLS
4543 cl->disco = 1;
4544 if (cl->thd->remote)
4546 int rc;
4550 struct timeval tv = { 0, 50000 };
4552 rc = gnutls_bye (cl->thd->tls->ses, GNUTLS_SHUT_WR);
4553 if (rc == GNUTLS_E_AGAIN)
4554 select (0, NULL, NULL, NULL, &tv);
4556 while (rc == GNUTLS_E_AGAIN);
4558 #endif
4560 /* This will let assuan_process_next() return. */
4561 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
4563 cl->last_rc = gpg_error_from_errno (errno);
4564 ret = cl->last_rc;
4567 cl->last_rc = 0; // BYE command result
4568 return ret;
4571 static gpg_error_t
4572 reset_notify (assuan_context_t ctx, char *line)
4574 struct client_s *client = assuan_get_pointer (ctx);
4576 (void)line;
4577 if (client)
4578 reset_client (client);
4580 return 0;
4584 * This is called before every Assuan command.
4586 static gpg_error_t
4587 command_startup (assuan_context_t ctx, const char *name)
4589 struct client_s *client = assuan_get_pointer (ctx);
4590 gpg_error_t rc = 0;
4591 struct command_table_s *cmd = NULL;
4593 log_write2 ("command='%s'", name);
4594 client->last_rc = client->opts = 0;
4596 for (int i = 0; command_table[i]; i++)
4598 if (!strcasecmp (name, command_table[i]->name))
4600 if (command_table[i]->ignore_startup)
4601 goto send_state;
4603 cmd = command_table[i];
4604 break;
4608 if (!cmd)
4609 return GPG_ERR_UNKNOWN_COMMAND;
4611 client->last_rc = rc = gpg_error (file_modified (client, cmd));
4613 send_state:
4614 if (!client->bulk_p && !rc)
4615 update_client_state (client, CLIENT_STATE_COMMAND);
4617 return rc;
4621 * This is called after every Assuan command.
4623 static void
4624 command_finalize (assuan_context_t ctx, gpg_error_t rc)
4626 struct client_s *client = assuan_get_pointer (ctx);
4628 // Needed for the STORE command. Really should be an OPT_.
4629 client->flags &= ~(FLAG_NO_INHERIT_ACL);
4631 if (!(client->flags & FLAG_LOCK_CMD))
4632 unlock_file_mutex (client, 0);
4634 unlock_flock (&client->flock_fd);
4635 log_write2 (_("command completed: rc=%u"), rc ? rc : client->last_rc);
4637 #ifdef WITH_GNUTLS
4638 client->thd->buffer_timeout = client->thd->last_buffer_size = 0;
4639 #endif
4641 if (!client->bulk_p && client->thd->state != CLIENT_STATE_DISCON)
4642 update_client_state (client, CLIENT_STATE_IDLE);
4644 client->bulk_p = NULL;
4647 static gpg_error_t
4648 parse_help_opt_html (void *data, void *value)
4650 struct client_s *client = data;
4652 (void) value;
4653 client->opts |= OPT_HTML;
4654 return 0;
4657 static gpg_error_t
4658 help_command (assuan_context_t ctx, char *line)
4660 gpg_error_t rc;
4661 int i;
4662 struct client_s *client = assuan_get_pointer (ctx);
4663 struct argv_s *args[] = {
4664 &(struct argv_s) {"html", OPTION_TYPE_NOARG, parse_help_opt_html},
4665 NULL
4668 rc = parse_options (&line, args, client, 1);
4669 if (rc)
4670 return send_error (ctx, rc);
4672 if (!line || !*line)
4674 char *tmp;
4675 char *help = str_dup (_("Usage: HELP [--html] [<COMMAND>]\n"
4676 "For commands that take an element path as an argument, each element is "
4677 "separated with an ASCII @key{TAB} character (ASCII 0x09). Not all help text is available here. For complete documentation refer to the texinfo or HTML manual."
4678 "@*@*COMMANDS:"));
4680 for (i = 0; command_table[i]; i++)
4682 if (!command_table[i]->help)
4683 continue;
4685 /* @npxref{} won't put a "See " or "see " in front of the command.
4686 * It's not a texinfo command but needed for --html. */
4687 tmp = str_asprintf ("%s %s%s%s", help,
4688 client->opts & OPT_HTML ? "@npxref{" : "",
4689 command_table[i]->name,
4690 client->opts & OPT_HTML ? "}" : "");
4691 xfree (help);
4692 help = tmp;
4695 tmp = strip_texi_and_wrap (help, client->opts & OPT_HTML);
4696 xfree (help);
4697 pthread_cleanup_push ((void *)xfree, tmp);
4698 rc = xfer_data (ctx, tmp, strlen (tmp));
4699 pthread_cleanup_pop (1);
4700 return send_error (ctx, rc);
4703 for (i = 0; command_table[i]; i++)
4705 if (!strcasecmp (line, command_table[i]->name))
4707 char *help, *tmp;
4709 if (!command_table[i]->help)
4710 break;
4712 help = strip_texi_and_wrap (command_table[i]->help,
4713 client->opts & OPT_HTML);
4714 tmp = str_asprintf ("%s%s",
4715 (client->opts & OPT_HTML) ? "" : _("Usage: "),
4716 help);
4717 xfree (help);
4718 pthread_cleanup_push ((void *)xfree, tmp);
4719 rc = xfer_data (ctx, tmp, strlen (tmp));
4720 pthread_cleanup_pop (1);
4721 return send_error (ctx, rc);
4725 return send_error (ctx, GPG_ERR_INV_NAME);
4728 static void
4729 new_command (const char *name, int inquire, int ignore, int unlock,
4730 int flock_type, gpg_error_t (*handler) (assuan_context_t, char *),
4731 const char *help)
4733 int i = 0;
4734 struct command_table_s **tmp;
4736 if (command_table)
4737 for (i = 0; command_table[i]; i++);
4739 tmp = xrealloc (command_table, (i + 2) * sizeof (struct command_table_s *));
4740 assert (tmp);
4741 command_table = tmp;
4742 command_table[i] = xcalloc (1, sizeof (struct command_table_s));
4743 command_table[i]->name = name;
4744 command_table[i]->inquire = inquire;
4745 command_table[i]->handler = handler;
4746 command_table[i]->ignore_startup = ignore;
4747 command_table[i]->unlock = unlock;
4748 command_table[i]->flock_type = flock_type;
4749 command_table[i++]->help = help;
4750 command_table[i] = NULL;
4753 void
4754 deinit_commands ()
4756 int i;
4758 for (i = 0; command_table[i]; i++)
4759 xfree (command_table[i]);
4761 xfree (command_table);
4764 static int
4765 sort_commands (const void *arg1, const void *arg2)
4767 struct command_table_s *const *a = arg1;
4768 struct command_table_s *const *b = arg2;
4770 if (!*a || !*b)
4771 return 0;
4772 else if (*a && !*b)
4773 return 1;
4774 else if (!*a && *b)
4775 return -1;
4777 return strcmp ((*a)->name, (*b)->name);
4780 static gpg_error_t
4781 passwd_command (assuan_context_t ctx, char *line)
4783 struct client_s *client = assuan_get_pointer (ctx);
4784 gpg_error_t rc;
4786 (void)line;
4787 rc = peer_is_invoker (client);
4788 if (rc)
4789 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
4791 if (client->flags & FLAG_NEW)
4792 return send_error (ctx, GPG_ERR_INV_STATE);
4794 client->crypto->keyfile = config_get_string (client->filename,
4795 "passphrase_file");
4796 rc = crypto_init_ctx (client->crypto, client->flags & FLAG_NO_PINENTRY,
4797 client->crypto->keyfile);
4798 if (!rc)
4799 rc = crypto_passwd (client, client->crypto);
4801 crypto_free_non_keys (client->crypto);
4802 return send_error (ctx, rc);
4805 static gpg_error_t
4806 parse_opt_data (void *data, void *value)
4808 struct client_s *client = data;
4810 (void) value;
4811 client->opts |= OPT_DATA;
4812 return 0;
4815 static gpg_error_t
4816 send_client_list (assuan_context_t ctx)
4818 struct client_s *client = assuan_get_pointer (ctx);
4819 gpg_error_t rc = 0;
4821 if (client->opts & OPT_VERBOSE)
4823 unsigned i, t;
4824 char **list = NULL;
4825 char *line;
4827 MUTEX_LOCK (&cn_mutex);
4828 pthread_cleanup_push ((void *)release_mutex_cb, &cn_mutex);
4829 t = slist_length (cn_thread_list);
4831 for (i = 0; i < t; i++)
4833 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
4834 char *tmp;
4836 if (thd->state == CLIENT_STATE_UNKNOWN)
4837 continue;
4839 tmp = build_client_info_line (thd, 0);
4840 if (tmp)
4842 char **l = strv_cat (list, tmp);
4843 if (!l)
4844 rc = GPG_ERR_ENOMEM;
4845 else
4846 list = l;
4848 else
4849 rc = GPG_ERR_ENOMEM;
4851 if (rc)
4853 strv_free (list);
4854 break;
4858 pthread_cleanup_pop (1);
4859 if (rc)
4860 return rc;
4862 line = strv_join ("\n", list);
4863 strv_free (list);
4864 pthread_cleanup_push ((void *)xfree, line);
4865 rc = xfer_data (ctx, line, strlen (line));
4866 pthread_cleanup_pop (1);
4867 return rc;
4870 if (client->opts & OPT_DATA)
4872 char buf[ASSUAN_LINELENGTH];
4874 MUTEX_LOCK (&cn_mutex);
4875 snprintf (buf, sizeof (buf), "%u", slist_length (cn_thread_list));
4876 MUTEX_UNLOCK (&cn_mutex);
4877 rc = xfer_data (ctx, buf, strlen (buf));
4879 else
4880 rc = send_status (ctx, STATUS_CLIENTS, NULL);
4882 return rc;
4885 static gpg_error_t
4886 getinfo_command (assuan_context_t ctx, char *line)
4888 struct client_s *client = assuan_get_pointer (ctx);
4889 gpg_error_t rc;
4890 char buf[ASSUAN_LINELENGTH];
4891 struct argv_s *args[] = {
4892 &(struct argv_s) {"data", OPTION_TYPE_NOARG, parse_opt_data},
4893 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_opt_verbose},
4894 NULL
4897 rc = parse_options (&line, args, client, 1);
4898 if (rc)
4899 return send_error (ctx, rc);
4901 if (!line || !*line)
4902 return send_error (ctx, GPG_ERR_SYNTAX);
4904 if (!strcasecmp (line, "clients"))
4906 rc = send_client_list (ctx);
4908 else if (!strcasecmp (line, "cache"))
4910 if (client->opts & OPT_DATA)
4912 snprintf (buf, sizeof (buf), "%u", cache_file_count ());
4913 rc = xfer_data (ctx, buf, strlen (buf));
4915 else
4916 rc = send_status (ctx, STATUS_CACHE, NULL);
4918 else if (!strcasecmp (line, "pid"))
4920 long pid = getpid ();
4922 snprintf (buf, sizeof (buf), "%li", pid);
4923 rc = xfer_data (ctx, buf, strlen (buf));
4925 else if (!strcasecmp (line, "version"))
4927 char *tmp = str_asprintf ("0x%06x %s", VERSION_HEX,
4928 #ifdef WITH_GNUTLS
4929 "GNUTLS "
4930 #endif
4931 #ifdef WITH_LIBACL
4932 "ACL "
4933 #endif
4934 "");
4935 pthread_cleanup_push (xfree, tmp);
4936 rc = xfer_data (ctx, tmp, strlen (tmp));
4937 pthread_cleanup_pop (1);
4939 else if (!strcasecmp (line, "last_error"))
4941 if (client->last_error)
4942 rc = xfer_data (ctx, client->last_error, strlen (client->last_error));
4943 else
4944 rc = GPG_ERR_NO_DATA;
4946 else if (!strcasecmp (line, "user"))
4948 char *user = NULL;
4950 #ifdef WITH_GNUTLS
4951 if (client->thd->remote)
4952 user = str_asprintf ("#%s", client->thd->tls->fp);
4953 else
4954 user = get_username (client->thd->peer->uid);
4955 #else
4956 user = get_username (client->thd->peer->uid);
4957 #endif
4958 if (user)
4960 pthread_cleanup_push ((void *)xfree, user);
4961 rc = xfer_data (ctx, user, strlen (user));
4962 pthread_cleanup_pop (1);
4964 else
4965 rc = GPG_ERR_NO_DATA;
4967 else
4968 rc = gpg_error (GPG_ERR_SYNTAX);
4970 return send_error (ctx, rc);
4973 static gpg_error_t
4974 parse_opt_secret (void *data, void *value)
4976 struct client_s *client = data;
4978 (void) value;
4979 client->opts |= OPT_SECRET;
4980 return 0;
4983 static gpg_error_t
4984 parse_keyinfo_opt_learn (void *data, void *value)
4986 struct client_s *client = data;
4988 (void)value;
4989 client->opts |= OPT_KEYINFO_LEARN;
4990 return 0;
4993 static gpg_error_t
4994 keyinfo_command (assuan_context_t ctx, char *line)
4996 struct client_s *client = assuan_get_pointer (ctx);
4997 gpg_error_t rc = 0;
4998 char **keys = NULL, **p = NULL;
4999 int sym = 0;
5000 struct argv_s *args[] = {
5001 &(struct argv_s) {"learn", OPTION_TYPE_NOARG, parse_keyinfo_opt_learn},
5002 NULL
5005 rc = parse_options (&line, args, client, 0);
5006 if (rc)
5007 return send_error (ctx, rc);
5009 if (line && *line)
5010 return send_error (ctx, GPG_ERR_SYNTAX);
5012 if (!(client->flags & FLAG_OPEN))
5013 return send_error (ctx, GPG_ERR_INV_STATE);
5015 if (client->opts & OPT_KEYINFO_LEARN)
5017 rc = cache_agent_command ("LEARN");
5018 return send_error (ctx, rc);
5021 if (client->flags & FLAG_NEW)
5022 return send_error (ctx, GPG_ERR_NO_DATA);
5024 rc = lock_flock (ctx, client->filename, FLOCK_TYPE_SH, &client->flock_fd);
5025 if (rc)
5026 return send_error (ctx, rc);
5028 rc = crypto_is_symmetric (client->filename);
5029 unlock_flock (&client->flock_fd);
5030 if (!rc)
5031 sym = 1;
5032 else if (rc != GPG_ERR_BAD_DATA)
5033 return send_error (ctx, rc);
5035 rc = 0;
5036 if (!sym)
5038 p = strv_catv (keys, client->crypto->pubkey);
5039 if (!p)
5040 rc = GPG_ERR_ENOMEM;
5041 else
5042 keys = p;
5045 if (!rc && client->crypto->sigkey)
5047 if (!strv_printf (&keys, "S%s", client->crypto->sigkey))
5049 strv_free (keys);
5050 return send_error (ctx, GPG_ERR_ENOMEM);
5054 if (!rc)
5056 if (keys)
5058 line = strv_join ("\n", keys);
5059 strv_free (keys);
5060 pthread_cleanup_push ((void *)xfree, line);
5061 if (line)
5062 rc = xfer_data (ctx, line, strlen (line));
5063 else
5064 rc = GPG_ERR_ENOMEM;
5066 pthread_cleanup_pop (1);
5068 else
5069 rc = GPG_ERR_NO_DATA;
5071 else
5072 strv_free (keys);
5074 return send_error (ctx, rc);
5077 static gpg_error_t
5078 deletekey_command (assuan_context_t ctx, char *line)
5080 gpg_error_t rc;
5081 struct client_s *client = assuan_get_pointer (ctx);
5082 struct crypto_s *crypto = NULL;
5083 char *keys[] = { NULL, NULL };
5084 gpgme_key_t *result;
5085 char **p = NULL;
5087 if (!(client->flags & FLAG_OPEN))
5088 return send_error (ctx, GPG_ERR_INV_STATE);
5090 rc = peer_is_invoker (client);
5091 if (rc)
5092 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
5094 if (client->flags & FLAG_NO_PINENTRY)
5095 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
5097 if (!*line)
5098 return send_error (ctx, GPG_ERR_SYNTAX);
5100 rc = crypto_keyid_to_16b_once (line);
5101 if (rc)
5102 return send_error (ctx, rc);
5104 for (p = client->crypto->pubkey; p && *p; p++)
5106 if (!strcmp (*p, line))
5107 break;
5110 if (!p)
5112 if (client->crypto->sigkey && strcmp (client->crypto->sigkey, line))
5113 return send_error (ctx, GPG_ERR_FORBIDDEN);
5114 else if (!client->crypto->sigkey)
5115 return send_error (ctx, GPG_ERR_NO_SECKEY);
5118 rc = crypto_init (&crypto, client->ctx, client->filename,
5119 client->flags & FLAG_NO_PINENTRY, NULL);
5120 if (rc)
5121 return send_error (ctx, rc);
5123 pthread_cleanup_push ((void *)crypto_free, crypto);
5124 keys[0] = line;
5125 rc = crypto_list_keys (crypto, keys, 1, &result);
5126 if (!rc)
5128 pthread_cleanup_push ((void *)crypto_free_key_list, result);
5129 rc = crypto_delete_key (client, crypto, *result, 1);
5130 pthread_cleanup_pop (1);
5133 pthread_cleanup_pop (1);
5134 return send_error (ctx, rc);
5137 static gpg_error_t
5138 kill_command (assuan_context_t ctx, char *line)
5140 struct client_s *client = assuan_get_pointer (ctx);
5141 gpg_error_t rc;
5142 unsigned i, t;
5144 if (!line || !*line)
5145 return send_error (ctx, GPG_ERR_SYNTAX);
5147 MUTEX_LOCK (&cn_mutex);
5148 pthread_cleanup_push ((void *)release_mutex_cb, &cn_mutex);
5149 t = slist_length (cn_thread_list);
5150 rc = GPG_ERR_ESRCH;
5152 for (i = 0; i < t; i++)
5154 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
5155 char *tmp = str_asprintf ("%p", thd->tid);
5157 if (strcmp (line, tmp))
5159 xfree (tmp);
5160 continue;
5163 xfree (tmp);
5164 rc = peer_is_invoker (client);
5165 if (!rc)
5167 #ifdef HAVE_PTHREAD_CANCEL
5168 pthread_cancel (thd->tid);
5169 #else
5170 pthread_kill (thd->tid, SIGUSR2);
5171 #endif
5172 break;
5174 else if (rc == GPG_ERR_EACCES)
5175 rc = GPG_ERR_FORBIDDEN;
5176 else if (rc)
5177 break;
5179 if (config_get_boolean ("global", "strict_kill"))
5180 break;
5182 #ifdef WITH_GNUTLS
5183 if (client->thd->remote && thd->remote)
5185 if (!thd->tls || !thd->tls->fp)
5187 rc = GPG_ERR_INV_STATE;
5188 break;
5190 if (!strcmp (client->thd->tls->fp, thd->tls->fp))
5192 #ifdef HAVE_PTHREAD_CANCEL
5193 pthread_cancel (thd->tid);
5194 #else
5195 pthread_kill (thd->tid, SIGUSR2);
5196 #endif
5197 rc = 0;
5198 break;
5201 else if (!client->thd->remote && !thd->remote)
5202 #endif
5204 if (client->thd->peer->uid == thd->peer->uid)
5206 #ifdef HAVE_PTHREAD_CANCEL
5207 pthread_cancel (thd->tid);
5208 #else
5209 pthread_kill (thd->tid, SIGUSR2);
5210 #endif
5211 rc = 0;
5214 break;
5217 pthread_cleanup_pop (1);
5218 return send_error (ctx, rc);
5221 static gpg_error_t
5222 listkeys_command (assuan_context_t ctx, char *line)
5224 struct client_s *client = assuan_get_pointer (ctx);
5225 struct crypto_s *crypto = NULL;
5226 char **pattern = NULL;
5227 gpgme_key_t *keys = NULL;
5228 char **result = NULL;
5229 gpg_error_t rc;
5230 struct argv_s *args[] = {
5231 &(struct argv_s) {"secret-only", OPTION_TYPE_NOARG, parse_opt_secret},
5232 NULL
5235 rc = parse_options (&line, args, client, 1);
5236 if (rc)
5237 return send_error (ctx, rc);
5239 rc = crypto_init (&crypto, client->ctx, client->filename,
5240 client->flags & FLAG_NO_PINENTRY, NULL);
5241 if (rc)
5242 return send_error (ctx, rc);
5244 pthread_cleanup_push ((void *)crypto_free, crypto);
5245 if (line)
5246 pattern = str_split (line, ",", 0);
5247 pthread_cleanup_push ((void *)(void *)strv_free, pattern);
5248 rc = crypto_list_keys (crypto, pattern, client->opts & OPT_SECRET,
5249 &keys);
5250 pthread_cleanup_pop (1);
5251 pthread_cleanup_pop (1);
5252 if (!rc)
5254 int i;
5256 for (i = 0; keys[i]; i++)
5258 char *p = crypto_key_info (keys[i]);
5259 char **r;
5261 if (!p)
5263 rc = GPG_ERR_ENOMEM;
5264 break;
5267 r = strv_cat (result, p);
5268 if (!r)
5270 rc = GPG_ERR_ENOMEM;
5271 break;
5274 result = r;
5277 if (!i)
5278 rc = GPG_ERR_NO_DATA;
5280 crypto_free_key_list (keys);
5283 if (!rc)
5285 line = strv_join ("\n", result);
5286 strv_free (result);
5287 pthread_cleanup_push ((void *)xfree, line);
5288 if (!line)
5289 rc = GPG_ERR_ENOMEM;
5290 else
5291 rc = xfer_data (ctx, line, strlen (line));
5293 pthread_cleanup_pop (1);
5295 else
5296 strv_free (result);
5298 if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
5299 || gpg_err_code (rc) == GPG_ERR_NO_SECKEY)
5300 rc = GPG_ERR_NO_DATA;
5302 return send_error (ctx, rc);
5305 void
5306 init_commands ()
5308 /* !BEGIN-HELP-TEXT!
5310 * This comment is used as a marker to generate the offline documentation
5311 * found in doc/pwmd.info. The indentation needs to be kept for the awk
5312 * script to determine where commands begin and end.
5314 new_command("HELP", 0, 1, 1, 0, help_command, _(
5315 "HELP [--html] [<COMMAND>]\n" /* Showing available commands. */
5316 "Show available commands or command specific help text."
5317 "@*@*"
5318 "The @option{--html} option will output the help text in HTML format."
5321 new_command("DELETEKEY", 0, 1, 1, FLOCK_TYPE_SH|FLOCK_TYPE_KEEP, deletekey_command, _(
5322 "DELETEKEY <keyid>\n" /* Deleting a key from the key ring. */
5323 "Deletes the public and secret key associated with key @var{keyid} from the "
5324 "keyring. The @var{keyid} must be one associated with the currently opened "
5325 "data file. "
5326 "Note that no confirmation occurs. Also note that when the key is deleted, "
5327 "the current or other data files using this key will no longer be able to be "
5328 "opened."
5331 new_command("KILL", 0, 1, 0, 0, kill_command, _(
5332 "KILL <thread_id>\n" /* Terminating another client. */
5333 "Terminates the client identified by @var{thread_id} and releases any file "
5334 "lock or other resources it has held. See @code{GETINFO} (@pxref{GETINFO}) "
5335 "for details about listing connected clients. An @code{invoking_user} "
5336 "(@pxref{Configuration}) may kill any client while others may only kill "
5337 "clients of the same @code{UID} or @abbr{TLS} fingerprint."
5340 new_command("LISTKEYS", 0, 1, 0, 0, listkeys_command, _(
5341 "LISTKEYS [--secret-only] [pattern[,<pattern>]]\n" /* Listing keys in the key ring. */
5342 "Returns a new line separated list of key information matching a comma "
5343 "separated list of @var{pattern}'s. When option @option{--secret-only} is "
5344 "specified, only keys matching @var{pattern} that also have a secret key "
5345 "available will be returned."
5348 new_command("KEYINFO", 0, 1, 0, 0, keyinfo_command, _(
5349 "KEYINFO [--learn]\n" /* Showing keys used for the current data file. */
5350 "Returns a new line separated list of key ID's that the currently opened "
5351 "data file has recipients and signers for. If the key is a signing key it "
5352 "will be prefixed with an @code{S}. If the file is a new one, or has no "
5353 "signers in the case of being symmetrically encrypted, the error code "
5354 "@code{GPG_ERR_NO_DATA} is returned."
5355 "@*@*"
5356 "When the @option{--learn} option is passed, keys on a smartcard will be "
5357 "imported."
5360 new_command("GETINFO", 0, 1, 1, 0, getinfo_command, _(
5361 "GETINFO [--data] [--verbose] CACHE | CLIENTS | PID | USER | LAST_ERROR | VERSION\n" /* Obtaining server and client information. */
5362 "Get server and other information. The information is returned via a status "
5363 "message (@pxref{Status Messages}) unless otherwise noted or @option{--data} "
5364 "is specified."
5365 "@*@*"
5366 "@var{CACHE} returns the number of cached documents."
5367 "@*@*"
5368 "@var{CLIENTS} returns the number of "
5369 "connected clients via a status message or a list of connected clients when "
5370 "the @option{--verbose} parameter is used (implies @option{--data}). A "
5371 "verbose line of a client list contains "
5372 "space delimited "
5373 "fields: the thread ID, client name, opened file (@code{/} if none opened), "
5374 "IP address if remote, file lock status, whether the current client is self "
5375 "or not, client state (see below), "
5376 "user ID or TLS fingerprint of the connected client, username if the "
5377 "client is a local one else @code{-}, and finally the time stamp of when the "
5378 "client connected."
5379 "@*@*"
5380 "Client state @code{0} is an unknown client state, state @code{1} indicates "
5381 "the client has connected but hasn't completed initializing, state @code{2} "
5382 "indicates that the client is idle, state @code{3} means the "
5383 "client is in a command and state @code{4} means the client is disconnecting. "
5384 "@*@*"
5385 "@var{PID} returns the process ID number of the server via a data response."
5386 "@*@*"
5387 "@var{VERSION} returns the server version number and compile-time features "
5388 "via a data response with each being space delimited."
5389 "@*@*"
5390 "@var{LAST_ERROR} returns a detailed description of the last failed command "
5391 "via a data response, when available."
5392 "@*@*"
5393 "@var{USER} returns the username or @abbr{TLS} hash of the connected client "
5394 "via a data response."
5397 new_command("PASSWD", 1, 0, 0, FLOCK_TYPE_EX|FLOCK_TYPE_KEEP, passwd_command, _(
5398 "PASSWD\n" /* Changing the passphrase for a key. */
5399 "Changes the passphrase of the secret key required to open the current "
5400 "data file. If the data file is symmetrically encrypted the error "
5401 "@code{GPG_ERR_NOT_SUPPORTED} is returned. When symmetrically encrypted "
5402 "the @code{SAVE} command (@pxref{SAVE}) should be used instead to prevent "
5403 "this command saving any unwanted changes to the @abbr{XML} document."
5404 "@*@*"
5405 "Note that when the current data file has been either encrypted or signed "
5406 "with a key stored on a smartcard this command will return an error. In this "
5407 "case you should instead use @command{gpg --card-edit} to change the "
5408 "pin of the smartcard or @command{gpg --edit-key} to change the passphrase "
5409 "of the key used to sign or encrypt the data file."
5410 "@*@*"
5411 "This command is not available to non-invoking clients "
5412 "(@pxref{Access Control})."
5415 new_command("OPEN", 1, 1, 1, FLOCK_TYPE_SH|FLOCK_TYPE_KEEP, open_command, _(
5416 "OPEN [--lock] <filename>\n" /* Opening a data file. */
5417 "Opens @var{filename}. When the @var{filename} is not found on the "
5418 "file-system then a new in-memory document will be created. If the file is "
5419 "found, it is looked for in the file cache and when found no passphrase will "
5420 "be required to open it. When not cached, @cite{pinentry(1)} will be used to "
5421 "retrieve the passphrase for decryption unless @option{disable-pinentry} "
5422 "(@pxref{OPTION}) was specified in which case @command{pwmd} will "
5423 "@emph{INQUIRE} the client for the passphrase. Note than when configuration "
5424 "option @option{strict_open} is enabled and the client is not an "
5425 "@option{invoking_user}, an error will be returned when the data file does "
5426 "not exist."
5427 "@*@*"
5428 "When the @option{--lock} option is passed then the file mutex will be "
5429 "locked as if the @code{LOCK} command (@pxref{LOCK}) had been sent after the "
5430 "file had been opened."
5433 new_command("GENKEY", 1, 1, 1, 0, genkey_command, _(
5434 "GENKEY --subkey-of=fpr | --userid=\"str\" [--no-expire | --expire=N] [--algo=\"str\"] [--no-passphrase] [--usage=\"default|sign|encrypt\"]\n" /* Generating a new key. */
5435 "Generates a new key based on option arguments. One of "
5436 "@option{--subkey-of} or @option{--userid} is "
5437 "required. The @option{--subkey-of} option will generate a subkey for the key "
5438 "of the specified fingerprint."
5441 new_command("SAVE", 1, 0, 0, FLOCK_TYPE_EX|FLOCK_TYPE_KEEP, save_command, _(
5442 "SAVE [--sign-keyid=[<fpr>]] [--symmetric | --keyid=<fpr>[,..] | --inquire-keyid]\n" /* Saving document changes to disk. */
5443 "Writes the in-memory @abbr{XML} document to disk. The file written to is the "
5444 "file that was opened when using the @code{OPEN} command (@pxref{OPEN})."
5445 "@*@*"
5446 "If the file is a new one one of @option{--symmetric}, @option{--keyid} or"
5447 "@option{--inquire-keyid} is required. When not @option{--symmetric} the "
5448 "option @option{--sign-keyid} is also required but optional otherwise."
5449 "@*@*"
5450 "You can encrypt the data file to a recipient other than the one that it "
5451 "was originally encrypted with by passing the @option{--keyid} or "
5452 "@option{--inquire-keyid} option with a comma separated list of "
5453 "public encryption key fingerprints as its argument. Use the "
5454 "@command{LISTKEYS} command (@pxref{LISTKEYS}) to show key information by "
5455 "pattern. The @option{--sign-keyid} option may also be used to sign the data "
5456 "file with an alternate key by specifying the fingerprint of a signing key. "
5457 "Only one signing key is supported unlike the @option{--keyid} option. "
5458 "A passphrase to decrypt the data file "
5459 "will be required when one or more of the original encryption keys or signing "
5460 "key are not found in either of these two options' arguments or when the data "
5461 "file is symmetrically encrypted regardless of the @code{require_save_key} "
5462 "configuration parameter. The original encryption keys and signing key will be "
5463 "used when neither of these options are specified."
5464 "@*@*"
5465 "The @option{--keyid} and @option{--sign-keyid} options are not available "
5466 "to non-invoking clients "
5467 "(@pxref{Access Control}) when the recipients or signer do not match those "
5468 "that were used when the file was @code{OPEN}'ed."
5469 "@*@*"
5470 "The @option{--symmetric} option specifies that a new data file be "
5471 "conventionally encrypted. These types of data files do not use a recipient "
5472 "public key but may optionally be signed by using the @option{--sign-keyid} "
5473 "option. To remove the signing key from a symmtrically encrypted data file, "
5474 "leave the option value empty."
5475 "@*@*"
5476 "Note that you cannot change encryption schemes once a data file has been "
5477 "saved."
5480 new_command("ISCACHED", 0, 1, 0, 0, iscached_command, _(
5481 "ISCACHED [--lock] [--agent [--sign]] <filename>\n" /* Testing cache status. */
5482 "Determines the file cache status of the specified @var{filename}. "
5483 "The default is to test whether the filename is cached in memory. Passing "
5484 "option @option{--agent} will test the @command{gpg-agent} cache for at most "
5485 "one cached key used for opening the data file (@pxref{OPEN}). To test if "
5486 "a signing key is cached, pass @option{--sign} along with @option{--agent}. "
5487 "Both the @option{--agent} and @option{--sign} options require an opened data "
5488 "file."
5489 "@*@*"
5490 "An @emph{OK} response is returned if the specified @var{filename} is found "
5491 "in the cache. If not found in the cache but exists on the filesystem "
5492 "then @code{GPG_ERR_NO_DATA} is returned. Otherwise a filesystem error is "
5493 "returned."
5494 "@*@*"
5495 "The @option{--lock} option will lock the file mutex of @var{filename} when "
5496 "the file exists; it does not need to be opened nor cached. The lock will be "
5497 "released when the client exits or sends the @code{UNLOCK} command "
5498 "(@pxref{UNLOCK}). When this option is passed the current data file is closed."
5501 new_command("CLEARCACHE", 0, 1, 1, 0, clearcache_command, _(
5502 "CLEARCACHE [<filename>]\n" /* Removing a cache entry. */
5503 "Clears a file cache entry for all or the specified @var{filename}. Note that "
5504 "this will also clear any @command{gpg-agent} cached keys which may cause "
5505 "problems if another data file shares the same keys as @var{filename}."
5506 "@*@*"
5507 "When clearing all cache entries a permissions test is done against the "
5508 "current client based on the @var{allowed} configuration parameter in a "
5509 "@var{filename} section. Both a cache entry may be cleared and an error "
5510 "returned depending on cached data files and client permissions."
5513 new_command("CACHETIMEOUT", 0, 1, 1, 0, cachetimeout_command, _(
5514 "CACHETIMEOUT <seconds>\n" /* Setting the cache timeout. */
5515 "The time in @var{seconds} until the currently opened data file will be "
5516 "removed from the cache. @code{-1} will keep the cache entry forever, "
5517 "@code{0} will require the passphrase for each @code{OPEN} command "
5518 "(@pxref{OPEN}) or @code{SAVE} (@pxref{SAVE}) command. @xref{Configuration}, "
5519 "and the @code{cache_timeout} parameter."
5522 new_command("LIST", 0, 0, 1, 0, list_command, _(
5523 "LIST [--inquire] [--recurse] [--sexp] [element[<TAB>child[..]]]\n" /* Showing document elements. */
5524 "If no element path is given then a newline separated list of root elements "
5525 "is returned with a data response. If given, then children of the specified "
5526 "element path are returned."
5527 "@*@*"
5528 "Each element path "
5529 "returned will have zero or more flags appened to it. These flags are "
5530 "delimited from the element path by a single space character. A flag itself "
5531 "is a single character. Flag @code{P} indicates that access to the element "
5532 "is denied. Flag @code{+} indicates that there are child nodes of "
5533 "the current element path. Flag @code{E} indicates that an element of the "
5534 "element path contained in a @var{target} attribute could not be found. Flag "
5535 "@code{O} indicates that a @var{target} attribute recursion limit was reached "
5536 "(@pxref{Configuration}). Flag @code{T}, followed by a single space character, "
5537 "then an element path, is the element path of the @var{target} attribute "
5538 "contained in the current element."
5539 "@*@*"
5540 "When a specified element path contains an error either from the final "
5541 "element in the path or any previous element, the path is still shown but "
5542 "will contain the error flag for the element with the error. Determining "
5543 "the actual element which contains the error is up to the client. This can be "
5544 "done by traversing the final element up to parent elements that contain the "
5545 "same error flag."
5546 "@*@*"
5547 "The option @option{--recurse} may be used to list the entire element tree "
5548 "for a specified element path or the entire tree for all root elements."
5549 "@*@*"
5550 "The option @option{--sexp} outputs the list in an s-expression and also "
5551 "appends an elements' attributes and attribute values. The syntax is:\n"
5552 "\n"
5553 "@example\n"
5554 "(11:list-result\n"
5555 " (4:path N:<path> 5:flags N:<flags>\n"
5556 " (5:attrs N:<name> N:<value> ...)\n"
5557 " )\n"
5558 " ...\n"
5559 ")\n"
5560 "@end example\n"
5561 "\n"
5562 "When the @option{--inquire} option is passed then all remaining non-option "
5563 "arguments are retrieved via a server @emph{INQUIRE}."
5566 new_command("REALPATH", 0, 0, 1, 0, realpath_command, _(
5567 "REALPATH [--inquire] element[<TAB>child[..]]\n" /* Resolving an element. */
5568 "Resolves all @code{target} attributes of the specified element path and "
5569 "returns the result with a data response. @xref{Target Attribute}, for details."
5570 "@*@*"
5571 "When the @option{--inquire} option is passed then all remaining non-option "
5572 "arguments are retrieved via a server @emph{INQUIRE}."
5575 new_command("STORE", 0, 0, 1, 0, store_command, _(
5576 "STORE [--no-inherit-acl] element[<TAB>child[..]]<TAB>[content]\n" /* Modifying the content of an element. */
5577 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
5578 "@*@*"
5579 "Creates a new element path or modifies the @var{content} of an existing "
5580 "element. If only a single element is specified then a new root element is "
5581 "created. Otherwise, elements are @key{TAB} delimited and the content will be "
5582 "set to the final @key{TAB} delimited element. If no @var{content} is "
5583 "specified after the final @key{TAB}, then the content of the existing "
5584 "element will be removed; or will be empty if creating a new element."
5585 "@*@*"
5586 "The option @option{--no-inherit-acl} prevents a newly created element from "
5587 "inheriting the value of the parent element @code{_acl} attribute. In either "
5588 "case, the current user is made the owner of the newly created element(s)."
5589 "@*@*"
5590 "The only restriction of an element name is that it not contain whitespace "
5591 "characters. There is no other whitespace between the @key{TAB} delimited "
5592 "elements. It is recommended that the content of an element be base64 encoded "
5593 "when it contains control or @key{TAB} characters to prevent @abbr{XML} "
5594 "parsing and @command{pwmd} syntax errors."
5597 new_command("RENAME", 0, 0, 1, 0, rename_command, _(
5598 "RENAME [--inquire] element[<TAB>child[..]] <value>\n" /* Renaming an element. */
5599 "Renames the specified @var{element} to the new @var{value}. If an element of "
5600 "the same name as the @var{value} already exists it will be overwritten."
5601 "@*@*"
5602 "When the @option{--inquire} option is passed then all remaining non-option "
5603 "arguments are retrieved via a server @emph{INQUIRE}."
5606 new_command("COPY", 0, 0, 1, 0, copy_command, _(
5607 "COPY [--inquire] source[<TAB>child[..]] dest[<TAB>child[..]]\n" /* Copying an element. */
5608 "Copies the entire element tree starting from the child node of the source "
5609 "element, to the destination element path. If the destination element path "
5610 "does not exist then it will be created; otherwise it is overwritten."
5611 "@*@*"
5612 "Note that attributes from the source element are merged into the "
5613 "destination element when the destination element path exists. When an "
5614 "attribute of the same name exists in both the source and destination "
5615 "elements then the destination attribute will be updated to the source "
5616 "attribute value."
5617 "@*@*"
5618 "When the @option{--inquire} option is passed then all remaining non-option "
5619 "arguments are retrieved via a server @emph{INQUIRE}."
5622 new_command("MOVE", 0, 0, 1, 0, move_command, _(
5623 "MOVE [--inquire] source[<TAB>child[..]] [dest[<TAB>child[..]]]\n" /* Moving an element. */
5624 "Moves the source element path to the destination element path. If the "
5625 "destination is not specified then it will be moved to the root node of the "
5626 "document. If the destination is specified and exists then it will be "
5627 "overwritten; otherwise non-existing elements of the destination element "
5628 "path will be created."
5629 "@*@*"
5630 "When the @option{--inquire} option is passed then all remaining non-option "
5631 "arguments are retrieved via a server @emph{INQUIRE}."
5634 new_command("DELETE", 0, 0, 1, 0, delete_command, _(
5635 "DELETE [--inquire] element[<TAB>child[..]]\n" /* Deleting an element. */
5636 "Removes the specified element path and all of its children. This may break "
5637 "an element with a @code{target} attribute (@pxref{Target Attribute}) that "
5638 "refers to this element or any of its children."
5639 "@*@*"
5640 "When the @option{--inquire} option is passed then all remaining non-option "
5641 "arguments are retrieved via a server @emph{INQUIRE}."
5644 new_command("GET", 0, 0, 1, 0, get_command, _(
5645 "GET [--inquire] element[<TAB>child[..]]\n" /* Getting the content of an element. */
5646 "Retrieves the content of the specified element. The content is returned "
5647 "with a data response."
5648 "@*@*"
5649 "When the @option{--inquire} option is passed then all remaining non-option "
5650 "arguments are retrieved via a server @emph{INQUIRE}."
5653 new_command("ATTR", 0, 0, 1, 0, attr_command, _(
5654 "ATTR [--inquire] SET|GET|DELETE|LIST [<attribute>] element[<TAB>child[..]] ..\n" /* Modifying element attributes. */
5655 "@table @asis\n"
5656 "@item ATTR SET attribute element[<TAB>child[..]] [value]\n"
5657 " Stores or updates an @var{attribute} name and optional @var{value} of an "
5658 "element. When no @var{value} is specified any existing value will be removed."
5659 "@*@*"
5660 "@item ATTR DELETE attribute element[<TAB>child[..]]\n"
5661 " Removes an attribute from an element. If @var{attribute} is @code{_name} "
5662 "or @code{target} an error is returned. Use the @command{DELETE} command "
5663 "(@pxref{DELETE}) instead."
5664 "@*@*"
5665 "@item ATTR LIST element[<TAB>child[..]]\n"
5666 " Retrieves a newline separated list of attributes names and values "
5667 "from the specified element. Each attribute name and value is space delimited."
5668 "@*@*"
5669 "@item ATTR GET attribute element[<TAB>child[..]]\n"
5670 " Retrieves the value of an @var{attribute} from an element."
5671 "@end table\n"
5672 "@*@*"
5673 "When the @option{--inquire} option is passed then all remaining non-option "
5674 "arguments are retrieved via a server @emph{INQUIRE}."
5675 "@*@*"
5676 "@xref{Target Attribute}, for details about this special attribute and also "
5677 "@pxref{Other Attributes} for other attributes that are handled specially "
5678 "by @command{pwmd}."
5681 new_command("XPATH", 0, 0, 1, 0, xpath_command, _(
5682 "XPATH [--inquire] <expression>[<TAB>[value]]\n" /* Modifying more than one element. */
5683 "Evaluates an XPath @var{expression}. If no @var{value} argument is "
5684 "specified it is assumed the expression is a request to return a result. "
5685 "Otherwise, the result is set to the @var{value} argument and the document is "
5686 "updated. If there is no @var{value} after the @key{TAB} character, the value "
5687 "is assumed to be empty and the document is updated. For example:"
5688 "@sp 1\n"
5689 "@example\n"
5690 "XPATH //element[@@_name='password']@key{TAB}\n"
5691 "@end example\n"
5692 "@sp 1\n"
5693 "would clear the content of all @var{password} elements in the data file "
5694 "while leaving off the trailing @key{TAB} would return all @var{password} "
5695 "elements in @abbr{XML} format."
5696 "@*@*"
5697 "When the @option{--inquire} option is passed then all remaining non-option "
5698 "arguments are retrieved via a server @emph{INQUIRE}."
5699 "@*@*"
5700 "See @url{https://www.w3schools.com/xml/xpath_intro.asp} for @abbr{XPATH} "
5701 "expression syntax."
5704 new_command("XPATHATTR", 0, 0, 1, 0, xpathattr_command, _(
5705 "XPATHATTR [--inquire] SET|DELETE <name> <expression>[<TAB>[<value>]]\n" /* Modifying more than one element's attributes. */
5706 "Like the @code{XPATH} command (@pxref{XPATH}) but operates on element "
5707 "attributes and does not return a result. For the @var{SET} operation the "
5708 "@var{value} is optional but the field is required. If not specified then "
5709 "the attribute value will be empty. For example:"
5710 "@sp 1\n"
5711 "@example\n"
5712 "XPATHATTR SET password //element[@@_name='password']@key{TAB}\n"
5713 "@end example\n"
5714 "@sp 1\n"
5715 "would create a @var{password} attribute for each @var{password} element "
5716 "found in the document. The attribute value will be empty but still exist."
5717 "@*@*"
5718 "When the @option{--inquire} option is passed then all remaining non-option "
5719 "arguments are retrieved via a server @emph{INQUIRE}."
5720 "@*@*"
5721 "See @url{https://www.w3schools.com/xml/xpath_intro.asp} for @abbr{XPATH} "
5722 "expression syntax."
5725 new_command("IMPORT", 0, 0, 1, 0, import_command, _(
5726 "IMPORT [--root=element[<TAB>child[..]]]\n" /* Creating elements from XML. */
5727 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
5728 "@*@*"
5729 "Like the @code{STORE} command (@pxref{STORE}), but the @var{content} "
5730 "argument is raw @abbr{XML} data. The content is created as a child of "
5731 "the element path specified with the @option{--root} option or at the "
5732 "document root when not specified. Existing elements of the same name will "
5733 "be overwritten."
5734 "@*@*"
5735 "The content must begin with an @abbr{XML} element node. @xref{Introduction}, "
5736 "for details."
5739 new_command("DUMP", 0, 1, 1, 0, dump_command, _(
5740 "DUMP\n" /* Showing the XML document. */
5741 "Shows the in memory @abbr{XML} document with indenting. @xref{XPATH}, for "
5742 "dumping a specific node."
5745 new_command("LOCK", 0, 0, 0, 0, lock_command, _(
5746 "LOCK\n" /* Locking the current data file. */
5747 "Locks the mutex associated with the opened file. This prevents other clients "
5748 "from sending commands to the same opened file until the client "
5749 "that sent this command either disconnects or sends the @code{UNLOCK} "
5750 "command. @xref{UNLOCK}."
5753 new_command("UNLOCK", 0, 1, 0, 0, unlock_command, _(
5754 "UNLOCK\n" /* Removing a data file lock. */
5755 "Unlocks the file mutex which was locked with the @code{LOCK} command or "
5756 "a commands' @option{--lock} option (@pxref{LOCK}, @pxref{OPEN}, "
5757 "@pxref{ISCACHED})."
5760 new_command("GETCONFIG", 0, 1, 1, 0, getconfig_command, _(
5761 "GETCONFIG [filename] <parameter>\n" /* Obtaining a configuration value. */
5762 "Returns the value of a @command{pwmd} configuration @var{parameter} with a "
5763 "data response. If no file has been opened then the value for @var{filename} "
5764 "or the default from the @var{global} section will be returned. If a file "
5765 "has been opened and no @var{filename} is specified, the value previously "
5766 "set with the @code{OPTION} command (@pxref{OPTION}) will be returned."
5769 new_command("OPTION", 0, 1, 1, 0, option_command, _(
5770 "OPTION <NAME>=[<VALUE>]\n" /* Setting various client parameters. */
5771 "Sets a client option @var{name} to @var{value}. The value for an option is "
5772 "kept for the duration of the connection with the exception of the "
5773 "@command{pinentry} options which are defaults for all future connections "
5774 "(@pxref{Pinentry}). When @var{value} is empty the option is unset."
5775 "@*@*"
5776 "@table @asis\n"
5777 "@item DISABLE-PINENTRY\n"
5778 "Disable use of @command{pinentry} for passphrase retrieval. When @code{1}, a "
5779 "server inquire is sent to the client to obtain the passphrase. This option "
5780 "may be set as needed before the @code{OPEN} (@pxref{OPEN}), @code{PASSWD} "
5781 "(@pxref{PASSWD}) and @code{SAVE} (@pxref{SAVE}) commands. Set to @code{0} "
5782 "to use a @command{pinentry}."
5783 "@*@*"
5784 "@item DISPLAY\n"
5785 "Set or unset the X11 display to use when prompting for a passphrase."
5786 "@*@*"
5787 "@item TTYNAME\n"
5788 "Set the terminal device path to use when prompting for a passphrase."
5789 "@*@*"
5790 "@item TTYTYPE\n"
5791 "Set the terminal type for use with @option{TTYNAME}."
5792 "@*@*"
5793 "@item NAME\n"
5794 "Associates the thread ID of the connection with the specified textual "
5795 "representation. Useful for debugging log messages. May not contain whitespace."
5796 "@*@*"
5797 "@item LOCK-TIMEOUT\n"
5798 "When not @code{0}, the duration in tenths of a second to wait for the file "
5799 "mutex which has been locked by another thread to be released before returning "
5800 "an error. When @code{-1} the error will be returned immediately."
5801 "@*@*"
5802 "@item CLIENT-STATE\n"
5803 "When set to @code{1} then client state status messages for other clients are "
5804 "sent to the current client. The default is @code{0}."
5805 "@end table\n"
5808 new_command("LS", 0, 1, 1, 0, ls_command, _(
5809 "LS [--verbose]\n" /* Showing available data files. */
5810 "Returns a newline separated list of data files stored in the data directory "
5811 "@file{HOMEDIR/data} (@pxref{Invoking}) with a data response. When the "
5812 "@var{--verbose} option is passed, the space-separated filesystem inode "
5813 "access, modification and change times are appended to the line."
5816 new_command("BULK", 0, 1, 1, 0, bulk_command, _(
5817 "BULK [--inquire]\n" /* Run a series of commands in sequence. */
5818 "Parses a semi-canonical s-expression representing a series of protocol "
5819 "commands to be run in sequence (@pxref{Bulk Commands}). Returns a canonical "
5820 "s-expression containing each commands id, return value and result data "
5821 "(if any)."
5822 "@*@*"
5823 "When the @option{--inquire} option is passed then all remaining non-option "
5824 "arguments are retrieved via a server @emph{INQUIRE}."
5827 new_command("RESET", 0, 1, 1, 0, NULL, _(
5828 "RESET\n" /* Resetting the client state. */
5829 "Closes the currently opened file but keeps any previously set client options "
5830 "(@pxref{OPTION})."
5833 new_command("NOP", 0, 1, 1, 0, nop_command, _(
5834 "NOP\n" /* Testing the connection. */
5835 "This command does nothing. It is useful for testing the connection for a "
5836 "timeout condition."
5839 /* !END-HELP-TEXT! */
5840 new_command ("CANCEL", 0, 1, 1, 0, NULL, NULL);
5841 new_command ("END", 0, 1, 1, 0, NULL, NULL);
5842 new_command ("BYE", 0, 1, 1, 0, NULL, NULL);
5844 int i;
5845 for (i = 0; command_table[i]; i++);
5846 qsort (command_table, i - 1, sizeof (struct command_table_s *),
5847 sort_commands);
5850 gpg_error_t
5851 register_commands (assuan_context_t ctx)
5853 int i = 0, rc;
5855 for (; command_table[i]; i++)
5857 if (!command_table[i]->handler)
5858 continue;
5860 rc = assuan_register_command (ctx, command_table[i]->name,
5861 command_table[i]->handler,
5862 command_table[i]->help);
5863 if (rc)
5864 return rc;
5867 rc = assuan_register_bye_notify (ctx, bye_notify);
5868 if (rc)
5869 return rc;
5871 rc = assuan_register_reset_notify (ctx, reset_notify);
5872 if (rc)
5873 return rc;
5875 rc = assuan_register_pre_cmd_notify (ctx, command_startup);
5876 if (rc)
5877 return rc;
5879 return assuan_register_post_cmd_notify (ctx, command_finalize);