IMPORT: Fix importing to element without permission.
[pwmd.git] / src / commands.c
blob4893d80a15aa07354b2eabb265e016d080534fe0
1 /*
2 Copyright (C) 2006-2021 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 free_client (client);
303 memset (client, 0, sizeof (struct client_s));
304 client->flock_fd = flock_fd;
305 client->xml_error = xml_error;
306 client->ctx = ctx;
307 client->thd = thd;
308 client->lock_timeout = lock_timeout;
309 client->flags |= no_pinentry ? FLAG_NO_PINENTRY : 0;
310 client->bulk_p = bulk_p;
313 static void
314 req_free (void *arg)
316 if (!arg)
317 return;
319 strv_free ((char **) arg);
322 static gpg_error_t
323 parse_open_opt_lock (void *data, void *value)
325 struct client_s *client = data;
327 (void)value;
328 client->opts |= OPT_LOCK_ON_OPEN;
329 return 0;
332 static gpg_error_t
333 parse_opt_inquire (void *data, void *value)
335 struct client_s *client = data;
337 (void) value;
338 client->opts |= OPT_INQUIRE;
339 return 0;
342 static gpg_error_t
343 update_checksum (struct client_s *client, unsigned char *from_crc,
344 size_t crclen)
346 unsigned char *crc;
347 size_t len;
348 struct cache_data_s *cdata;
349 gpg_error_t rc;
351 if (!from_crc)
353 rc = get_checksum (client->filename, &crc, &len);
354 if (rc)
355 return rc;
357 else
359 crc = from_crc;
360 len = crclen;
363 xfree (client->crc);
364 client->crc = xmalloc (len);
365 memcpy (client->crc, crc, len);
366 pthread_cleanup_push (xfree, crc);
367 cdata = cache_get_data (client->filename, NULL);
368 pthread_cleanup_pop (0);
369 if (cdata)
371 xfree (cdata->crc);
372 cdata->crc = xmalloc (len);
373 memcpy (cdata->crc, crc, len);
376 if (!from_crc)
377 xfree (crc);
378 return 0;
381 static gpg_error_t
382 validate_checksum (struct client_s *client, const char *filename,
383 struct cache_data_s *cdata, unsigned char **r_crc,
384 size_t *r_crclen, int from_cdata)
386 unsigned char *crc;
387 size_t len;
388 gpg_error_t rc;
389 int n = 0;
391 if (cdata && !cdata->crc)
392 return GPG_ERR_CHECKSUM;
394 rc = get_checksum (filename, &crc, &len);
395 if (rc)
396 return rc;
398 if (client->crc)
399 n = memcmp (client->crc, crc, len);
400 else if ((client->flags & FLAG_NEW) && cache_get_data (filename, NULL))
401 n = 1;
403 if ((!n && cdata) || (from_cdata && cdata && crc))
404 n = memcmp (cdata->crc, crc, len);
406 if (!n && r_crc)
408 *r_crc = crc;
409 *r_crclen = len;
411 else
412 xfree (crc);
414 return n ? GPG_ERR_CHECKSUM : 0;
417 static gpg_error_t
418 open_command (assuan_context_t ctx, char *line)
420 gpg_error_t rc;
421 struct client_s *client = assuan_get_pointer (ctx);
422 int same_file = 0;
423 assuan_peercred_t peer;
424 struct cache_data_s *cdata = NULL;
425 int cached = 0;
426 unsigned char *crc = NULL;
427 size_t crclen = 0;
428 int plaintext = 0;
429 struct argv_s *args[] = {
430 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_open_opt_lock},
431 NULL
434 rc = parse_options (&line, args, client, 1);
435 if (rc)
436 return send_error (ctx, rc);
438 rc = do_validate_peer (ctx, line, &peer, NULL);
439 if (rc == GPG_ERR_FORBIDDEN)
441 rc = peer_is_invoker (client);
442 if (rc == GPG_ERR_EACCES)
443 rc = GPG_ERR_FORBIDDEN;
446 if (rc)
447 return send_error (ctx, rc);
449 if (!valid_filename (line))
450 return send_error (ctx, GPG_ERR_INV_VALUE);
452 /* This client may have locked a different file with ISCACHED --lock than
453 * the current filename. This will remove that lock. */
454 same_file = client->filename && !strcmp (line, client->filename);
455 if (client->flags & FLAG_OPEN ||
456 (client->flags & FLAG_HAS_LOCK && !same_file))
458 unsigned opts = client->opts;
459 unsigned flags = client->flags;
461 if (same_file)
462 client->flags |= FLAG_KEEP_LOCK;
464 /* Another client wrote to the same data file as currently opened. */
465 cdata = cache_get_data (client->filename, NULL);
466 if (cdata && cdata->crc)
467 flags &= ~FLAG_NEW;
468 /* Remove cache entry for the new file that hadn't been written. */
469 else if (client->flags & FLAG_NEW)
470 cache_clear (NULL, client->filename, 0, 0);
472 cdata = NULL;
473 reset_client (client);
474 client->opts = opts;
475 client->flags |= flags;
476 client->flags &= ~(FLAG_LOCK_CMD);
477 if (!same_file)
478 client->flags &= ~(FLAG_HAS_LOCK | FLAG_NEW);
481 xfree (client->filename);
482 client->filename = str_dup (line);
483 if (!client->filename)
484 return send_error(ctx, GPG_ERR_ENOMEM);
486 /* Need to lock the mutex here because file_modified() cannot without
487 * knowing the filename. */
488 rc = lock_file_mutex (client, 1);
489 if (rc)
490 client->flags &= ~FLAG_OPEN;
492 if (!rc)
494 rc = lock_flock (ctx, client->filename, LOCK_SH, &client->flock_fd);
495 if (gpg_err_code (rc) == GPG_ERR_ENOENT)
496 rc = 0;
499 if (!rc)
501 char *keyfile = config_get_string (client->filename, "passphrase_file");
503 rc = crypto_init (&client->crypto, client->ctx, client->filename,
504 client->flags & FLAG_NO_PINENTRY, keyfile);
505 if (rc)
506 xfree (keyfile);
507 else
508 rc = open_check_file (client->filename, NULL, NULL, 1);
511 if (!rc || gpg_err_code (rc) == GPG_ERR_ENOENT)
513 int reload = 0;
514 int defer = 0;
516 if (rc) // new file
518 rc = 0;
520 if (config_get_boolean ("global", "strict_open"))
522 rc = peer_is_invoker (client);
523 if (rc == GPG_ERR_EACCES)
524 rc = GPG_ERR_FORBIDDEN;
527 if (!rc)
529 client->flags |= FLAG_NEW;
530 // data file disappeared. clear the cache entry.
531 cache_clear (NULL, client->filename, 1, 1);
532 cdata = NULL;
535 goto done;
538 cdata = cache_get_data (client->filename, &defer);
539 if (cdata && !defer
540 && !cache_plaintext_get (client->filename, &client->doc))
542 rc = validate_checksum (client, client->filename, cdata, &crc,
543 &crclen, 0);
544 if (rc)
546 log_write ("%s: %s", client->filename,
547 pwmd_strerror (rc));
548 cache_plaintext_release (&client->doc);
549 if (rc == GPG_ERR_CHECKSUM)
551 cache_clear (NULL, client->filename, 1, 1);
552 cdata = NULL;
553 goto decrypt;
557 #ifdef WITH_GNUTLS
558 if (!rc && client->thd->remote
559 && config_get_boolean (client->filename, "tcp_require_key")
560 && !(client->flags & FLAG_NEW))
562 rc = crypto_try_decrypt (client,
563 (client->flags & FLAG_NO_PINENTRY));
565 #endif
566 if (!rc)
568 strv_free (client->crypto->pubkey);
569 client->crypto->pubkey = NULL;
570 if (cdata->pubkey)
571 client->crypto->pubkey = strv_dup (cdata->pubkey);
573 xfree (client->crypto->sigkey);
574 client->crypto->sigkey = NULL;
575 if (cdata->sigkey)
576 client->crypto->sigkey = str_dup (cdata->sigkey);
578 cached = 1;
579 plaintext = 1;
582 else if (cdata && cdata->doc) // cached document
584 if (!rc && !(client->flags & FLAG_NEW))
586 rc = validate_checksum (client, client->filename, cdata, &crc,
587 &crclen, 0);
588 if (rc == GPG_ERR_CHECKSUM)
590 rc = 0;
591 reload = 1;
595 if (!rc)
597 rc = cache_iscached (client->filename, &defer, 0, 0);
598 if ((!rc || rc == GPG_ERR_ENOENT) && defer)
600 rc = 0;
601 reload = 2;
605 if (!rc && reload)
607 if (reload == 1)
608 log_write ("%s: %s", client->filename,
609 pwmd_strerror (GPG_ERR_CHECKSUM));
610 cache_clear (NULL, client->filename, 1, 1);
611 cdata = NULL;
612 rc = crypto_decrypt (client, client->crypto);
614 #ifdef WITH_GNUTLS
615 else if (!rc)
617 if (client->thd->remote
618 && config_get_boolean (client->filename, "tcp_require_key")
619 && !(client->flags & FLAG_NEW))
620 rc = crypto_try_decrypt (client,
621 (client->flags & FLAG_NO_PINENTRY));
623 #endif
625 if (!rc && cdata)
627 client->crypto->plaintext = cdata->doc;
628 client->crypto->plaintext_size = cdata->size;
629 rc = cache_decrypt (client->crypto);
630 if (!rc)
632 cdata->doc = NULL;
633 cdata->size = 0;
635 strv_free (client->crypto->pubkey);
636 client->crypto->pubkey = NULL;
637 if (cdata->pubkey)
638 client->crypto->pubkey = strv_dup (cdata->pubkey);
640 xfree (client->crypto->sigkey);
641 client->crypto->sigkey = NULL;
642 if (cdata->sigkey)
643 client->crypto->sigkey = str_dup (cdata->sigkey);
645 cached = 1;
647 else
649 client->crypto->plaintext = NULL;
650 client->crypto->plaintext_size = 0;
654 else // existing file
656 decrypt:
657 cached = cdata != NULL;
658 rc = crypto_decrypt (client, client->crypto);
662 done:
663 if (!rc && !plaintext)
665 rc = parse_xml (ctx, client->flags & FLAG_NEW);
666 if (!rc)
668 rc = cache_encrypt (client->crypto);
669 if (rc)
670 cache_clear (NULL, client->filename, 1, 1);
671 else
673 long timeout = config_get_long (client->filename,
674 "cache_timeout");
676 cache_free_data_once (cdata);
677 cdata = xcalloc (1, sizeof (struct cache_data_s));
678 cdata->doc = client->crypto->plaintext;
679 cdata->size = client->crypto->plaintext_size;
680 cdata->pubkey = strv_dup(client->crypto->pubkey);
681 cdata->sigkey = client->crypto->sigkey ? str_dup(client->crypto->sigkey) : NULL;
682 client->crypto->plaintext = NULL;
683 client->crypto->plaintext_size = 0;
685 if (cached) // wont increment the refcount
687 if (crclen)
689 xfree (client->crc);
690 client->crc = NULL;
691 xfree (cdata->crc);
692 cdata->crc = xmalloc (crclen);
693 memcpy (cdata->crc, crc, crclen);
696 rc = cache_set_data (client->filename, cdata);
697 /* The cache entry may have been removed and cache_set_data()
698 * already sent STATUS_CACHE. */
699 if (!cache_iscached (client->filename, NULL, 0, 0))
700 rc = send_status (ctx, STATUS_CACHE, NULL);
702 else
703 rc = cache_add_file (client->filename, cdata, timeout);
705 if (!rc)
706 cache_plaintext_set (client->filename, client->doc, 0);
711 if (!rc)
713 xfree (client->crc);
714 client->crc = NULL;
715 if (crc)
717 client->crc = xmalloc (crclen);
718 memcpy (client->crc, crc, crclen);
722 xfree (crc);
724 if (!rc && !(client->flags & FLAG_NEW) && !cached)
725 rc = update_checksum (client, NULL, 0);
727 if (!rc)
729 client->flags |= FLAG_OPEN;
731 if (client->flags & FLAG_NEW)
732 rc = send_status (ctx, STATUS_NEWFILE, NULL);
734 if (!rc && (client->opts & OPT_LOCK_ON_OPEN))
735 rc = do_lock (client, 0);
737 crypto_free_non_keys (client->crypto);
739 else
741 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
743 if (client->flags & FLAG_NEW)
744 cache_clear (NULL, client->filename, 1, 1);
746 crypto_free (client->crypto);
747 client->crypto = NULL;
748 client->flags &= ~FLAG_OPEN;
749 cache_plaintext_release (&client->doc);
752 return send_error (ctx, rc);
755 /* If not an invoking_user or is an existing file, check that the list of user
756 * supplied key ID's are in the list of current key ID's obtained when
757 * decrypting the data file.
759 static gpg_error_t
760 permitted_to_save (struct client_s *client, const char **keys,
761 const char **value)
763 gpg_error_t rc = 0;
764 const char **v;
766 if ((client->flags & FLAG_NEW) || (client->opts & OPT_SYMMETRIC))
767 return 0;
769 rc = peer_is_invoker (client);
770 if (!rc)
771 return 0;
772 else if (rc == GPG_ERR_EACCES)
773 rc = GPG_ERR_FORBIDDEN;
774 else if (rc)
775 return rc;
777 /* Empty match. */
778 if ((!value && !keys) || ((value && !*value) && (keys && !*keys)))
779 return 0;
781 for (v = value; v && *v; v++)
783 const char **k, *pv = *v;
784 int match = 0;
786 if (*pv == '0' && *(pv+1) == 'x')
787 pv += 2;
789 for (k = keys; k && *k; k++)
791 const char *pk = *k;
793 if (*pk == '0' && *(pk+1) == 'x')
794 pk += 2;
796 rc = !strcmp (pv, pk) ? 0 : GPG_ERR_FORBIDDEN;
797 if (rc)
798 rc = !strcmp (pv, *k) ? 0 : GPG_ERR_FORBIDDEN;
800 if (!rc)
802 match = 1;
803 break;
807 if (!match)
808 return GPG_ERR_FORBIDDEN;
811 return rc;
814 /* Requires that the keyid be a fingerprint in 16 byte form. */
815 static gpg_error_t
816 parse_save_opt_keyid_common (struct client_s *client, const char **list,
817 const char *value, char ***dst)
819 gpg_error_t rc = 0;
820 char **keys = NULL;
822 if (value && *value)
824 keys = str_split (value, ",", 0);
825 if (!keys)
826 return GPG_ERR_ENOMEM;
829 rc = crypto_keyid_to_16b (keys);
830 if (!rc)
831 rc = permitted_to_save (client, list, (const char **)keys);
833 if (!rc)
834 *dst = keys;
835 else
836 strv_free (keys);
838 return rc;
841 static gpg_error_t
842 parse_save_opt_keyid (void *data, void *value)
844 struct client_s *client = data;
845 const char *str = value;
846 char **dst = NULL;
847 gpg_error_t rc;
849 rc = parse_save_opt_keyid_common (client,
850 (const char **)client->crypto->pubkey,
851 str, &dst);
852 if (rc)
853 return rc;
855 client->crypto->save.pubkey = dst;
856 return 0;
859 static gpg_error_t
860 parse_save_opt_sign_keyid (void *data, void *value)
862 struct client_s *client = data;
863 const char *str = value;
864 char **dst = NULL;
865 gpg_error_t rc;
866 char **tmp = NULL;
868 if (client->crypto->sigkey)
870 if (!strv_printf (&tmp, "%s", client->crypto->sigkey))
871 return GPG_ERR_ENOMEM;
874 rc = parse_save_opt_keyid_common (client, (const char **)tmp, str, &dst);
875 strv_free (tmp);
876 if (rc)
877 return rc;
879 if (!dst)
880 client->opts |= OPT_NO_SIGNER;
881 else
882 client->crypto->save.sigkey = str_dup (*dst);
884 strv_free (dst);
885 return 0;
888 static gpg_error_t
889 parse_save_opt_inquire_keyid (void *data, void *value)
891 struct client_s *client = data;
893 (void)value;
895 if (!(client->flags & FLAG_NEW))
897 gpg_error_t rc = peer_is_invoker (client);
899 if (rc)
900 return rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc;
903 client->opts |= OPT_INQUIRE_KEYID;
904 return 0;
907 static gpg_error_t
908 parse_save_opt_symmetric (void *data, void *value)
910 struct client_s *client = data;
912 (void)value;
913 client->opts |= OPT_SYMMETRIC;
914 return 0;
917 static gpg_error_t
918 parse_genkey_opt_userid (void *data, void *value)
920 struct client_s *client = data;
922 if (!(client->flags & FLAG_NEW))
924 gpg_error_t rc = peer_is_invoker (client);
926 if (rc)
927 return rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc;
930 client->crypto->save.userid = str_dup (value);
931 return client->crypto->save.userid ? 0 : GPG_ERR_ENOMEM;
934 static gpg_error_t
935 parse_genkey_opt_algo (void *data, void *value)
937 struct client_s *client = data;
939 client->crypto->save.algo = str_dup (value);
940 return client->crypto->save.algo ? 0 : GPG_ERR_ENOMEM;
943 static gpg_error_t
944 parse_genkey_opt_no_expire (void *data, void *value)
946 struct client_s *client = data;
948 client->crypto->save.flags |= GPGME_CREATE_NOEXPIRE;
949 return 0;
952 static gpg_error_t
953 parse_genkey_opt_expire (void *data, void *value)
955 struct client_s *client = data;
956 gpg_error_t rc = 0;
957 char *p = NULL;
958 unsigned long t;
960 errno = 0;
961 t = strtoul (value, &p, 10);
963 if (!errno && p && *p)
964 rc = GPG_ERR_INV_VALUE;
965 else if (t == ULONG_MAX)
966 rc = GPG_ERR_INV_VALUE;
967 else if (errno)
968 rc = gpg_error_from_syserror ();
969 else
970 client->crypto->save.expire = t;
972 return rc;
975 static gpg_error_t
976 parse_genkey_opt_no_passphrase (void *data, void *value)
978 struct client_s *client = data;
980 (void)value;
981 client->crypto->save.flags |= GPGME_CREATE_NOPASSWD;
982 return 0;
985 /* Tests that the keys in new_keys are also in old_keys. */
986 static gpg_error_t
987 compare_keys (char **new_keys, char **old_keys)
989 char **o;
991 if (!old_keys || !*old_keys)
992 return 0;
994 crypto_keyid_to_16b (new_keys);
996 for (o = old_keys; *o; o++)
998 char **n;
1000 for (n = new_keys; *n; n++)
1002 if (!strcmp (*n, *o))
1003 break;
1006 if (!*n)
1007 return GPG_ERR_NOT_FOUND;
1010 return 0;
1013 static gpg_error_t
1014 inquire_keyid (struct client_s *client)
1016 gpg_error_t rc;
1017 unsigned char *result = NULL;
1018 size_t len;
1019 const char *s = "KEYID";
1020 char ***orig;
1021 char ***save;
1023 orig = &client->crypto->pubkey;
1024 save = &client->crypto->save.pubkey;
1025 rc = assuan_inquire (client->ctx, s, &result, &len, 0);
1026 if (!rc)
1028 char **dst = NULL;
1030 rc = parse_save_opt_keyid_common (client, (const char **)*orig,
1031 (char *)result, &dst);
1032 if (!rc)
1033 *save = dst;
1036 xfree (result);
1037 return rc;
1041 /* When a key lookup in gpg-agent's cache fails, the agent tries the last
1042 * successful key to be unlocked. This prevents pwmd from successfully
1043 * clearing a signing key since the previous key, which more than likely
1044 * belongs to the same keypair as the encryption/decryption key, will have the
1045 * passphrase cached and therefore the signing key also cached. So we need to
1046 * clear both the signing and encryption keys to get the effect of requiring a
1047 * passphrase when generating a new keypair for an existing data file, or when
1048 * the "require_save_key" configuration parameter is set. This parameter is
1049 * mostly a failsafe of the gpg-agent option --ignore-cache-for-signing since
1050 * some/most/all users may fail to set it.
1052 static gpg_error_t
1053 save_command (assuan_context_t ctx, char *line)
1055 struct client_s *client = assuan_get_pointer (ctx);
1056 struct cache_data_s *cdata = NULL;
1057 int sym = 0;
1058 gpg_error_t rc = 0, cache_rc = 0;
1059 int defer = 0;
1060 struct argv_s *args[] = {
1061 &(struct argv_s) {"keyid", OPTION_TYPE_ARG, parse_save_opt_keyid},
1062 &(struct argv_s) {"inquire-keyid", OPTION_TYPE_NOARG,
1063 parse_save_opt_inquire_keyid },
1064 &(struct argv_s) {"sign-keyid", OPTION_TYPE_OPTARG,
1065 parse_save_opt_sign_keyid},
1066 &(struct argv_s) {"symmetric", OPTION_TYPE_NOARG,
1067 parse_save_opt_symmetric },
1068 NULL
1071 crypto_free_save (&client->crypto->save);
1072 client->crypto->save.expire = DEFAULT_EXPIRE;
1074 rc = crypto_is_symmetric (client->filename);
1075 if (!rc || rc == GPG_ERR_BAD_DATA || rc == GPG_ERR_ENOENT)
1077 if (!rc)
1079 client->opts |= OPT_SYMMETRIC;
1080 sym = 1;
1082 else if (rc == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
1083 rc = 0; // New file
1084 else
1085 rc = 0; // PKI
1088 if (rc)
1089 return send_error (ctx, rc);
1091 rc = parse_options (&line, args, client, 0);
1092 if (rc)
1093 return send_error (ctx, rc);
1095 if (config_get_boolean (client->filename, "require_save_key")
1096 || (client->opts & OPT_SYMMETRIC))
1097 client->opts |= OPT_ASK;
1099 rc = open_check_file (client->filename, NULL, NULL, 1);
1100 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
1102 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
1103 return send_error (ctx, rc);
1106 if (!rc)
1107 cache_rc = rc = cache_iscached (client->filename, &defer, 0, 1);
1109 if (gpg_err_code (rc) == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
1110 rc = 0;
1111 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
1112 rc = 0;
1114 if (rc)
1115 return send_error (ctx, rc);
1117 /* Specifying both a recipient and symmetric encryption is an error. */
1118 if ((client->opts & OPT_INQUIRE_KEYID) && (client->opts & OPT_SYMMETRIC))
1119 return send_error (ctx, GPG_ERR_CONFLICT);
1120 /* Existing file with a recipient and wanting symmetric is an error. */
1121 else if ((client->opts & OPT_SYMMETRIC) && client->crypto->save.pubkey)
1122 return send_error (ctx, GPG_ERR_CONFLICT);
1123 else if (client->crypto->save.pubkey && (client->opts & OPT_INQUIRE_KEYID))
1124 return send_error (ctx, GPG_ERR_CONFLICT);
1125 else if (!sym && (client->opts & OPT_SYMMETRIC) && !(client->flags & FLAG_NEW))
1126 return send_error (ctx, GPG_ERR_CONFLICT);
1127 /* New file that is not symmetric without either a recipient or signer. */
1128 else if ((client->flags & FLAG_NEW) && !(client->opts & OPT_SYMMETRIC)
1129 && (!client->crypto->save.pubkey || !client->crypto->save.sigkey))
1130 return send_error (ctx, GPG_ERR_SYNTAX);
1131 else if (client->opts & OPT_INQUIRE_KEYID)
1132 rc = inquire_keyid (client);
1134 if (!rc)
1136 client->crypto->keyfile = config_get_string (client->filename,
1137 "passphrase_file");
1138 rc = crypto_init_ctx (client->crypto, (client->flags & FLAG_NO_PINENTRY),
1139 client->crypto->keyfile);
1142 if (!rc && (client->flags & FLAG_NEW))
1144 /* Require --keyid when --sign-keyid exists to keep KEYINFO
1145 * synchronized. */
1146 if (!client->crypto->save.pubkey && client->crypto->save.sigkey
1147 && !(client->opts & OPT_SYMMETRIC))
1148 rc = GPG_ERR_NO_PUBKEY;
1150 else if (!rc)
1152 cdata = cache_get_data (client->filename, NULL);
1153 if (cdata)
1155 if (client->crypto->save.pubkey)
1156 rc = compare_keys (client->crypto->save.pubkey, cdata->pubkey);
1158 /* Always allow a signer for symmetric data files. */
1159 if (!rc && client->crypto->save.sigkey
1160 && !(client->opts & OPT_SYMMETRIC))
1161 rc = !strcmp (client->crypto->save.sigkey, cdata->sigkey)
1162 ? 0 : GPG_ERR_NOT_FOUND;
1164 /* Prevent saving to a recipient who is not in the original recipient
1165 * list without a passphrase. */
1166 if (rc || (client->crypto->sigkey && (client->opts & OPT_NO_SIGNER)))
1167 client->opts |= OPT_ASK;
1169 if (rc == GPG_ERR_NOT_FOUND)
1171 rc = peer_is_invoker (client);
1172 if (rc == GPG_ERR_EACCES)
1173 rc = GPG_ERR_FORBIDDEN;
1176 if (!client->crypto->save.pubkey
1177 && !(client->opts & OPT_SYMMETRIC))
1178 client->crypto->save.pubkey = strv_dup (cdata->pubkey);
1180 if (!rc && !client->crypto->save.sigkey && cdata->sigkey
1181 && !(client->opts & OPT_NO_SIGNER))
1182 client->crypto->save.sigkey = str_dup (cdata->sigkey);
1183 else if (!rc && !client->crypto->save.sigkey
1184 && (client->opts & OPT_NO_SIGNER)
1185 && !(client->opts & OPT_SYMMETRIC))
1186 rc = GPG_ERR_NO_SIGNATURE_SCHEME;
1188 else
1190 client->crypto->save.pubkey = strv_dup (client->crypto->pubkey);
1191 client->crypto->save.sigkey = str_dup (client->crypto->sigkey);
1195 if (!rc && !(client->flags & FLAG_NEW))
1197 /* Fixes {NEW_,SIGN_}PASSPHRASE inquire keywords. See passphrase_cb(). */
1198 if (client->opts & OPT_SYMMETRIC)
1199 client->crypto->flags |= CRYPTO_FLAG_PASSWD;
1201 if (client->opts & OPT_ASK)
1203 rc = cache_clear_agent_keys (client->filename, 1, 1);
1204 if (!rc)
1205 rc = crypto_try_decrypt (client, client->flags & FLAG_NO_PINENTRY);
1209 if (!rc && client->opts & OPT_SYMMETRIC)
1210 client->crypto->flags |= CRYPTO_FLAG_PASSWD_NEW;
1212 if (!rc)
1213 rc = xml_update_element_mtime (client, xmlDocGetRootElement (client->doc));
1215 if (!rc)
1217 xmlNodePtr root = xmlDocGetRootElement (client->doc);
1219 rc = xml_add_attribute (client, root, "_version", PACKAGE_VERSION);
1222 if (!rc)
1224 int size;
1226 xmlDocDumpFormatMemory (client->doc, &client->crypto->plaintext, &size,
1228 if (size > 0)
1229 client->crypto->plaintext_size = (size_t) size;
1230 else
1231 rc = GPG_ERR_ENOMEM;
1233 if (!rc)
1235 client->crypto->flags |= (client->opts & OPT_SYMMETRIC) ? CRYPTO_FLAG_SYMMETRIC : 0;
1236 client->crypto->flags |= (client->flags & FLAG_NEW) ? CRYPTO_FLAG_NEWFILE : 0;
1237 client->crypto->flags |= !(client->opts & OPT_SYMMETRIC) ? CRYPTO_FLAG_PASSWD_SIGN : 0;
1238 rc = crypto_encrypt (client, client->crypto);
1239 client->crypto->flags &= ~CRYPTO_FLAG_SYMMETRIC;
1242 if (!rc)
1244 unsigned char *crc = NULL;
1245 size_t crclen = 0;
1247 rc = crypto_write_file (client->crypto, &crc, &crclen);
1248 pthread_cleanup_push ((void *)xfree, crc);
1249 if (!rc)
1251 if (!cache_rc)
1252 cdata = cache_get_data (client->filename, NULL);
1253 else
1254 cdata = xcalloc (1, sizeof (struct cache_data_s));
1257 if (!rc)
1259 rc = cache_encrypt (client->crypto);
1260 if (rc)
1262 cache_clear (NULL, client->filename, 1, 1);
1263 client->flags &= ~(FLAG_NEW);
1265 strv_free (client->crypto->pubkey);
1266 client->crypto->pubkey = NULL;
1267 if (client->crypto->save.pubkey)
1268 client->crypto->pubkey = strv_dup (client->crypto->save.pubkey);
1270 xfree (client->crypto->sigkey);
1271 client->crypto->sigkey = NULL;
1272 if (client->crypto->save.sigkey)
1273 client->crypto->sigkey = str_dup (client->crypto->save.sigkey);
1277 if (!rc)
1279 long timeout = config_get_long (client->filename, "cache_timeout");
1280 xmlDocPtr doc = xmlCopyDoc (client->doc, 1);
1282 if (!doc)
1283 rc = GPG_ERR_ENOMEM;
1285 if (!rc)
1287 cache_plaintext_release (&client->doc);
1288 strv_free (cdata->pubkey);
1289 cdata->pubkey = client->crypto->save.pubkey;
1290 client->crypto->save.pubkey = NULL;
1292 xfree (cdata->sigkey);
1293 cdata->sigkey = client->crypto->save.sigkey;
1294 client->crypto->save.sigkey = NULL;
1296 xfree (cdata->crc);
1297 cdata->crc = NULL;
1299 /* cache_encrypt() does in-place encryption */
1300 xfree (cdata->doc);
1301 cdata->doc = client->crypto->plaintext;
1302 client->crypto->plaintext = NULL;
1303 cdata->size = client->crypto->plaintext_size;
1304 client->crypto->plaintext_size = 0;
1306 client->doc = doc;
1307 cache_plaintext_set (client->filename, client->doc, 0);
1309 /* Update in case the cache entry expires the next SAVE may
1310 * not have any known keys. */
1311 strv_free (client->crypto->pubkey);
1312 client->crypto->pubkey = NULL;
1313 if (cdata->pubkey)
1314 client->crypto->pubkey = strv_dup (cdata->pubkey);
1316 xfree (client->crypto->sigkey);
1317 client->crypto->sigkey = NULL;
1318 if (cdata->sigkey)
1319 client->crypto->sigkey = str_dup (cdata->sigkey);
1321 if (!cache_rc) // wont increment refcount
1322 rc = cache_set_data (client->filename, cdata);
1323 else
1324 rc = cache_add_file (client->filename, cdata, timeout);
1327 if (!rc && (cache_rc || (client->flags & FLAG_NEW)))
1328 send_status_all (STATUS_CACHE, NULL);
1330 if (!rc)
1332 rc = update_checksum (client, crc, crclen);
1333 client->flags &= ~(FLAG_NEW);
1337 pthread_cleanup_pop (1);
1338 if (!rc)
1339 client->did_cow = 0;
1343 crypto_free_non_keys (client->crypto);
1344 return send_error (ctx, rc);
1347 static gpg_error_t
1348 parse_genkey_opt_usage (void *data, void *v)
1350 struct client_s *client = data;
1351 char *value = v;
1353 if (!value || !*value)
1354 return GPG_ERR_INV_VALUE;
1355 else if (!strcmp (value, "sign"))
1356 client->crypto->save.flags |= GPGME_CREATE_SIGN;
1357 else if (!strcmp (value, "encrypt"))
1358 client->crypto->save.flags |= GPGME_CREATE_ENCR;
1359 else if (!strcmp (value, "default"))
1360 client->crypto->save.flags &= ~(GPGME_CREATE_ENCR|GPGME_CREATE_SIGN);
1361 else
1362 return GPG_ERR_INV_VALUE;
1364 return 0;
1367 gpg_error_t
1368 parse_genkey_opt_subkey_of (void *data, void *v)
1370 gpg_error_t rc;
1371 struct client_s *client = data;
1372 char *value = v;
1373 char *tmp[] = { value, NULL };
1374 gpgme_key_t *keys = NULL;
1376 rc = peer_is_invoker (client);
1377 if (rc)
1378 return rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc;
1380 if (!value || !*value)
1381 return GPG_ERR_INV_VALUE;
1383 rc = crypto_list_keys (client->crypto, tmp, 1, &keys);
1384 if (rc)
1385 return rc;
1387 if (!keys || !*keys)
1389 crypto_free_key_list (keys);
1390 return GPG_ERR_NO_SECKEY;
1393 client->crypto->save.mainkey = keys;
1394 return 0;
1397 static gpg_error_t
1398 genkey_command (assuan_context_t ctx, char *line)
1400 struct client_s *client = assuan_get_pointer (ctx);
1401 struct crypto_s *crypto, *orig;
1402 gpg_error_t rc = 0;
1403 struct argv_s *args[] = {
1404 &(struct argv_s) {"userid", OPTION_TYPE_ARG,
1405 parse_genkey_opt_userid},
1406 &(struct argv_s) {"expire", OPTION_TYPE_ARG,
1407 parse_genkey_opt_expire},
1408 &(struct argv_s) {"no-expire", OPTION_TYPE_NOARG,
1409 parse_genkey_opt_no_expire},
1410 &(struct argv_s) {"algo", OPTION_TYPE_ARG,
1411 parse_genkey_opt_algo},
1412 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG,
1413 parse_genkey_opt_no_passphrase},
1414 &(struct argv_s) {"usage", OPTION_TYPE_ARG,
1415 parse_genkey_opt_usage},
1416 &(struct argv_s) {"subkey-of", OPTION_TYPE_ARG,
1417 parse_genkey_opt_subkey_of},
1418 NULL
1421 if (!(client->flags & FLAG_OPEN))
1422 return send_error (ctx, GPG_ERR_INV_STATE);
1424 rc = crypto_init (&crypto, ctx, client->filename,
1425 client->flags & FLAG_NO_PINENTRY, NULL);
1426 if (rc)
1427 return send_error (ctx, rc);
1429 pthread_cleanup_push ((void *)crypto_free, client->crypto);
1430 orig = client->crypto;
1431 client->crypto = crypto;
1432 rc = parse_options (&line, args, client, 0);
1433 if (!rc)
1435 if (!client->crypto->save.userid && !client->crypto->save.mainkey)
1436 rc = GPG_ERR_SYNTAX;
1437 else
1439 client->crypto->flags |= CRYPTO_FLAG_NEWFILE;
1440 rc = crypto_genkey (client, client->crypto);
1444 pthread_cleanup_pop (0);
1445 crypto_free (crypto);
1446 client->crypto = orig;
1447 return send_error (ctx, rc);
1450 static gpg_error_t
1451 do_delete (assuan_context_t ctx, char *line)
1453 struct client_s *client = assuan_get_pointer (ctx);
1454 struct xml_request_s *req;
1455 xmlNodePtr n;
1456 gpg_error_t rc;
1458 if (!line || !*line)
1459 return GPG_ERR_SYNTAX;
1461 rc = xml_new_request (client, line, XML_CMD_DELETE, &req);
1462 if (rc)
1463 return rc;
1465 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1466 xml_free_request (req);
1467 if (rc)
1468 return rc;
1470 rc = xml_is_element_owner (client, n, 0);
1471 if (!rc)
1472 rc = xml_unlink_node (client, n);
1474 return rc;
1477 /* Won't update cdata->plaintext. Other clients are working on the original or
1478 * copy of the same document. The first client to SAVE wins and requires others
1479 * to reopen the data file due to a checksum error. */
1480 static gpg_error_t
1481 copy_on_write (struct client_s *client)
1483 struct cache_data_s *cdata;
1485 if (client->did_cow)
1486 return 0;
1488 cdata = cache_get_data (client->filename, NULL);
1489 if (cdata)
1491 gpg_error_t rc;
1492 xmlDocPtr doc = xmlCopyDoc (client->doc, 1);
1494 if (!doc)
1495 return GPG_ERR_ENOMEM;
1497 rc = cache_plaintext_set (client->filename, doc, 1);
1498 if (rc)
1500 xmlFree (doc);
1501 return rc;
1504 (void)cache_plaintext_release (&client->doc);
1505 client->doc = doc;
1506 client->did_cow = 1;
1507 return 0;
1510 return GPG_ERR_NO_DATA;
1513 static gpg_error_t
1514 delete_command (assuan_context_t ctx, char *line)
1516 struct client_s *client = assuan_get_pointer (ctx);
1517 gpg_error_t rc;
1518 struct argv_s *args[] = {
1519 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1520 NULL
1523 rc = parse_options (&line, args, client, 1);
1524 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1525 rc = GPG_ERR_SYNTAX;
1526 if (rc)
1527 return send_error (ctx, rc);
1529 rc = copy_on_write (client);
1530 if (rc)
1531 return send_error (ctx, rc);
1533 if (client->opts & OPT_INQUIRE)
1535 unsigned char *result;
1536 size_t len;
1538 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1539 if (rc)
1540 return send_error (ctx, rc);
1542 pthread_cleanup_push ((void *)xfree, result);
1543 rc = do_delete (ctx, (char *)result);
1544 pthread_cleanup_pop (1);
1546 else
1547 rc = do_delete (ctx, line);
1549 return send_error (ctx, rc);
1552 static gpg_error_t
1553 update_element_expirey (struct client_s *client, xmlNodePtr n)
1555 gpg_error_t rc = 0;
1556 xmlChar *expire, *incr;
1557 char *p;
1558 time_t e, e_orig, i;
1559 time_t now = time (NULL);
1561 expire = xml_attribute_value (n, (xmlChar *)"_expire");
1562 if (!expire)
1563 return 0;
1565 errno = 0;
1566 e = strtoul ((char *)expire, &p, 10);
1567 if (errno || *p || e == ULONG_MAX || *expire == '-')
1569 xmlFree (expire);
1570 rc = GPG_ERR_ERANGE;
1571 goto fail;
1574 xmlFree (expire);
1575 incr = xml_attribute_value (n, (xmlChar *)"_age");
1576 if (!incr)
1577 return 0;
1579 i = strtoul ((char *)incr, &p, 10);
1580 if (errno || *p || i == ULONG_MAX || *incr == '-')
1582 xmlFree (incr);
1583 rc = GPG_ERR_ERANGE;
1584 goto fail;
1587 xmlFree (incr);
1588 e_orig = e;
1589 e = now + i;
1590 p = str_asprintf ("%lu", e);
1591 if (!p)
1593 rc = GPG_ERR_ENOMEM;
1594 goto fail;
1597 rc = xml_add_attribute (client, n, "_expire", p);
1598 xfree (p);
1599 if (!rc)
1600 rc = send_status (client->ctx, STATUS_EXPIRE, "%lu %lu", e_orig, e);
1602 fail:
1603 return rc;
1606 static gpg_error_t
1607 parse_opt_store_no_acl_inherit (void *data, void *value)
1609 struct client_s *client = data;
1611 (void)value;
1612 client->flags |= FLAG_NO_INHERIT_ACL;
1613 return 0;
1616 static gpg_error_t
1617 store_command (assuan_context_t ctx, char *line)
1619 struct client_s *client = assuan_get_pointer (ctx);
1620 gpg_error_t rc;
1621 size_t len;
1622 unsigned char *result;
1623 xmlNodePtr n, parent;
1624 int has_content;
1625 char *content = NULL;
1626 struct xml_request_s *req;
1627 struct argv_s *args[] = {
1628 &(struct argv_s) {"no-inherit-acl", OPTION_TYPE_NOARG,
1629 parse_opt_store_no_acl_inherit},
1630 NULL
1633 rc = parse_options (&line, args, client, 1);
1634 if (rc)
1635 return send_error (ctx, rc);
1637 if (!client->bulk_p && line && *line)
1638 return send_error (ctx, GPG_ERR_SYNTAX);
1640 rc = copy_on_write (client);
1641 if (rc)
1642 return send_error (ctx, rc);
1644 if (!client->bulk_p)
1646 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1647 if (rc)
1648 return send_error (ctx, rc);
1649 rc = xml_new_request (client, (char *)result, XML_CMD_STORE, &req);
1650 if (!result || !*result)
1652 xfree (result);
1653 return send_error (ctx, GPG_ERR_SYNTAX);
1656 len = strv_length (req->args);
1657 has_content = result[strlen ((char *)result) - 1] != '\t' && len > 1;
1658 xfree (result);
1660 else
1662 rc = xml_new_request (client, line, XML_CMD_STORE, &req);
1663 len = strv_length (req->args);
1664 has_content = line && line[strlen (line) - 1] != '\t' && len > 1;
1667 if (rc)
1668 return send_error (ctx, rc);
1670 /* Prevent passing the element content around to save some memory
1671 * (has_content). */
1672 if (*(req->args+1) && !xml_valid_element_path (req->args, has_content))
1674 xml_free_request (req);
1675 return send_error (ctx, GPG_ERR_INV_VALUE);
1678 if (has_content || !*req->args[len-1])
1680 content = req->args[len-1];
1681 req->args[len-1] = NULL;
1684 if (strv_length (req->args) > 1)
1686 rc = xml_check_recursion (client, req);
1687 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
1688 goto fail;
1691 parent = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1693 if (!rc && len > 1)
1695 rc = xml_is_element_owner (client, parent, 0);
1696 if (!rc)
1698 n = xml_find_text_node (parent->children);
1699 if (n)
1700 xmlNodeSetContent (n, (xmlChar *) content);
1701 else
1702 xmlNodeAddContent (parent, (xmlChar *) content);
1704 (void)xml_update_element_mtime (client, parent);
1705 (void)update_element_expirey (client, parent);
1709 fail:
1710 xfree (content);
1711 xml_free_request (req);
1712 return send_error (ctx, rc);
1715 static gpg_error_t
1716 xfer_data (assuan_context_t ctx, const char *line, int total)
1718 struct client_s *client = assuan_get_pointer (ctx);
1719 int to_send = total < ASSUAN_LINELENGTH ? total : ASSUAN_LINELENGTH;
1720 int sent = 0;
1721 gpg_error_t rc = 0;
1723 if (!(client->flags & FLAG_LOCK_CMD))
1724 rc = unlock_file_mutex (client, 0);
1725 if (rc && rc != GPG_ERR_NOT_LOCKED)
1726 return rc;
1728 if (client->bulk_p)
1730 client->bulk_p->result = xmalloc (total+1);
1731 if (!client->bulk_p->result)
1732 return GPG_ERR_ENOMEM;
1733 memcpy (client->bulk_p->result, line, total);
1734 client->bulk_p->result[total] = 0;
1735 client->bulk_p->result_len = total;
1736 return 0;
1739 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1740 if (rc)
1741 return rc;
1745 if (sent + to_send > total)
1746 to_send = total - sent;
1748 rc = assuan_send_data (ctx, (char *) line + sent, to_send);
1749 if (!rc)
1750 sent += to_send;
1752 while (!rc && sent < total);
1754 return rc;
1757 static gpg_error_t
1758 do_get (assuan_context_t ctx, char *line)
1760 struct client_s *client = assuan_get_pointer (ctx);
1761 gpg_error_t rc;
1762 struct xml_request_s *req;
1763 xmlNodePtr n;
1765 if (!line || !*line)
1766 return GPG_ERR_SYNTAX;
1768 rc = xml_new_request (client, line, XML_CMD_NONE, &req);
1769 if (rc)
1770 return rc;
1772 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1773 if (!rc)
1775 if (n && n->children)
1777 xmlNodePtr tmp = n;
1779 n = xml_find_text_node (n->children);
1780 if (!n || !n->content || !*n->content)
1781 rc = GPG_ERR_NO_DATA;
1782 else
1784 rc = xfer_data (ctx, (char *) n->content, xmlStrlen (n->content));
1785 if (!rc)
1787 xmlChar *expire = xml_attribute_value (tmp,
1788 (xmlChar *)"_expire");
1789 if (expire)
1791 time_t now = time (NULL);
1792 time_t e;
1793 char *p;
1795 errno = 0;
1796 e = strtoul ((char *)expire, &p, 10);
1797 if (errno || *p || e == ULONG_MAX || *expire == '-')
1798 log_write (_("invalid expire attribute value: %s"),
1799 expire);
1800 else if (now >= e)
1802 pthread_cleanup_push (xmlFree, expire);
1803 rc = send_status (ctx, STATUS_EXPIRE, "%lu 0", e);
1804 pthread_cleanup_pop (0);
1807 xmlFree (expire);
1812 else
1813 rc = GPG_ERR_NO_DATA;
1816 xml_free_request (req);
1817 return rc;
1820 static gpg_error_t
1821 get_command (assuan_context_t ctx, char *line)
1823 struct client_s *client = assuan_get_pointer (ctx);
1824 gpg_error_t rc;
1825 struct argv_s *args[] = {
1826 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1827 NULL
1830 rc = parse_options (&line, args, client, 1);
1831 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1832 rc = GPG_ERR_SYNTAX;
1833 if (rc)
1834 return send_error (ctx, rc);
1836 if (client->opts & OPT_INQUIRE)
1838 unsigned char *result;
1839 size_t len;
1841 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1842 if (rc)
1843 return send_error (ctx, rc);
1845 pthread_cleanup_push ((void *)xfree, result);
1846 rc = do_get (ctx, (char *)result);
1847 pthread_cleanup_pop (1);
1849 else
1850 rc = do_get (ctx, line);
1852 return send_error (ctx, rc);
1855 static void list_command_free1 (void *arg);
1856 static gpg_error_t
1857 realpath_command (assuan_context_t ctx, char *line)
1859 gpg_error_t rc;
1860 char **realpath = NULL;
1861 struct client_s *client = assuan_get_pointer (ctx);
1862 struct argv_s *args[] = {
1863 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1864 NULL
1867 rc = parse_options (&line, args, client, 1);
1868 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1869 rc = GPG_ERR_SYNTAX;
1870 if (rc)
1871 return send_error (ctx, rc);
1873 if (client->opts & OPT_INQUIRE)
1875 unsigned char *result;
1876 size_t len;
1878 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1879 if (rc)
1880 return send_error (ctx, rc);
1882 pthread_cleanup_push ((void *)xfree, result);
1883 (void)xml_resolve_path (client, client->doc, result, &realpath, &rc);
1884 pthread_cleanup_pop (1);
1886 else
1887 (void)xml_resolve_path (client, client->doc, (unsigned char *)line,
1888 &realpath, &rc);
1890 if (!rc)
1892 char *tmp = strv_join ((char *)"\t", realpath);
1894 strv_free (realpath);
1895 if (!tmp)
1896 return send_error (ctx, GPG_ERR_ENOMEM);
1898 pthread_cleanup_push ((void *)xfree, tmp);
1899 rc = xfer_data (ctx, tmp, strlen (tmp));
1900 pthread_cleanup_pop (1);
1903 return send_error (ctx, rc);
1906 static void
1907 list_command_free1 (void *arg)
1909 if (arg)
1910 string_free ((struct string_s *) arg, 1);
1913 static gpg_error_t
1914 parse_list_opt_recurse (void *data, void *value)
1916 struct client_s *client = data;
1918 (void)value;
1919 client->opts |= OPT_LIST_RECURSE;
1920 return 0;
1923 static gpg_error_t
1924 parse_opt_verbose (void *data, void *value)
1926 struct client_s *client = data;
1928 (void)value;
1929 client->opts |= OPT_VERBOSE;
1930 return 0;
1933 static gpg_error_t
1934 parse_opt_sexp (void *data, void *value)
1936 struct client_s *client = data;
1938 (void)value;
1939 client->opts |= OPT_SEXP;
1940 return 0;
1943 static gpg_error_t
1944 list_path_once (struct client_s *client, char *line,
1945 struct element_list_s *elements, struct string_s *result)
1947 gpg_error_t rc;
1949 rc = xml_create_path_list (client, client->doc, NULL, elements, line, 0);
1950 if (rc == GPG_ERR_ELOOP || rc == GPG_ERR_EACCES)
1951 rc = 0;
1953 if (!rc)
1955 int total = slist_length (elements->list);
1957 if (total)
1959 int i;
1961 for (i = 0; i < total; i++)
1963 char *tmp = slist_nth_data (elements->list, i);
1965 string_append_printf (result, "%s%s", tmp,
1966 i + 1 == total ? "" : "\n");
1969 else
1970 rc = GPG_ERR_NO_DATA;
1973 return rc;
1976 #define RESUMABLE_ERROR(rc) (rc == GPG_ERR_ELOOP || rc == GPG_ERR_EACCES \
1977 || rc == GPG_ERR_ELEMENT_NOT_FOUND || !rc)
1978 static gpg_error_t
1979 attribute_list_common (struct client_s *client, const char *path,
1980 char ***result)
1982 char **attrlist = NULL;
1983 int i = 0;
1984 int target = 0;
1985 xmlAttrPtr a;
1986 xmlNodePtr n, an, r;
1987 gpg_error_t rc;
1988 struct xml_request_s *req;
1990 rc = xml_new_request (client, path, XML_CMD_ATTR_LIST, &req);
1991 if (rc)
1992 return rc;
1994 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1995 xml_free_request (req);
1996 if (rc)
1997 return rc;
1999 gpg_error_t acl_rc = 0;
2000 again:
2001 acl_rc = xml_acl_check (client, n);
2002 for (a = n->properties; a; a = a->next)
2004 char **pa;
2005 int reserved = xml_reserved_attribute ((char *)a->name);
2007 if (acl_rc == GPG_ERR_EACCES && !reserved)
2008 continue;
2009 else if (acl_rc && acl_rc != GPG_ERR_EACCES)
2011 rc = acl_rc;
2012 break;
2015 if (reserved && target)
2016 continue;
2018 pa = xrealloc (attrlist, (i + 2) * sizeof (char *));
2019 if (!pa)
2021 log_write ("%s(%i): %s", __FILE__, __LINE__,
2022 pwmd_strerror (GPG_ERR_ENOMEM));
2023 rc = GPG_ERR_ENOMEM;
2024 break;
2027 attrlist = pa;
2028 an = a->children;
2029 attrlist[i] = str_asprintf ("%s %s", (char *) a->name, an && an->content
2030 ? (char *)an->content : "");
2032 if (!attrlist[i])
2034 log_write ("%s(%i): %s", __FILE__, __LINE__,
2035 pwmd_strerror (GPG_ERR_ENOMEM));
2036 rc = GPG_ERR_ENOMEM;
2037 break;
2040 attrlist[++i] = NULL;
2043 if (!rc && !attrlist)
2044 return GPG_ERR_NO_DATA;
2046 if (!rc && !target)
2048 r = xml_resolve_path (client, client->doc, (xmlChar *)path, NULL, &rc);
2049 if (RESUMABLE_ERROR (rc))
2051 rc = 0;
2052 if (r && r != n)
2054 target = 1;
2055 n = r;
2056 goto again;
2061 if (!rc)
2062 *result = attrlist;
2063 else
2064 strv_free (attrlist);
2066 return rc;
2069 static gpg_error_t
2070 create_list_sexp (struct client_s *client, struct string_s *string,
2071 struct string_s **r_string)
2073 struct string_s *str = string;
2074 gpg_error_t rc = 0;
2075 struct string_s *result = string_new ("(11:list-result");
2076 char **strv = str_split (str->str, "\n", 0);
2077 int t = strv_length (strv);
2078 int i;
2080 string_large (result);
2082 for (i = 0; i < t; i++)
2084 char **tmpv = str_split (strv[i], " ", 0);
2085 char **attrlist = NULL;
2087 result = string_append_printf (result, "(4:path%i:%s", strlen (tmpv[0]),
2088 tmpv[0]);
2089 if (tmpv[1])
2090 result = string_append_printf (result, "5:flags%i:%s", strlen (tmpv[1]),
2091 tmpv[1]);
2092 else
2093 result = string_append (result, "5:flags0:");
2095 rc = attribute_list_common (client, tmpv[0], &attrlist);
2096 if (!rc)
2098 int ai;
2099 int at = strv_length (attrlist);
2101 result = string_append (result, "(5:attrs");
2103 for (ai = 0; ai < at; ai++)
2105 char **attrv = str_split (attrlist[ai], " ", 0);
2106 char *value = strv_join (" ", attrv+1);
2108 result = string_append_printf (result, "%i:%s%i:%s",
2109 strlen (attrv[0]), attrv[0],
2110 strlen (value), value);
2111 strv_free (attrv);
2112 xfree (value);
2115 result = string_append (result, ")");
2118 result = string_append (result, ")");
2119 strv_free (attrlist);
2120 strv_free (tmpv);
2123 strv_free (strv);
2124 result = string_append (result, ")");
2125 if (!rc)
2126 *r_string = result;
2128 return rc;
2131 static gpg_error_t
2132 do_list (assuan_context_t ctx, char *line)
2134 struct client_s *client = assuan_get_pointer (ctx);
2135 gpg_error_t rc = GPG_ERR_NO_DATA;
2136 struct element_list_s *elements = NULL;
2137 struct string_s *result = NULL;
2139 if (!line || !*line)
2141 struct string_s *str = string_new (NULL);
2142 xmlNodePtr n;
2144 if (!str)
2145 return GPG_ERR_ENOMEM;
2147 string_large (str);
2148 pthread_cleanup_push ((void *)list_command_free1, str);
2149 n = xmlDocGetRootElement (client->doc);
2150 for (n = n->children; n; n = n->next)
2152 xmlChar *name;
2154 if (n->type != XML_ELEMENT_NODE)
2155 continue;
2157 name = xmlGetProp (n, (xmlChar *)"_name");
2158 if (!name)
2160 rc = GPG_ERR_ENOMEM;
2161 break;
2164 elements = xcalloc (1, sizeof (struct element_list_s));
2165 if (!elements)
2167 xmlFree (name);
2168 rc = GPG_ERR_ENOMEM;
2169 break;
2172 elements->prefix = string_new (NULL);
2173 if (!elements->prefix)
2175 xmlFree (name);
2176 xml_free_element_list (elements);
2177 rc = GPG_ERR_ENOMEM;
2178 break;
2181 elements->recurse = client->opts & OPT_LIST_RECURSE;
2182 elements->root_only = !elements->recurse;
2183 pthread_cleanup_push ((void *)xml_free_element_list, elements);
2184 rc = list_path_once (client, (char *)name, elements, str);
2185 xmlFree (name);
2186 pthread_cleanup_pop (1);
2187 if (rc)
2188 break;
2190 if (n->next)
2191 string_append (str, "\n");
2194 if (!rc)
2196 if (client->opts & OPT_SEXP)
2198 rc = create_list_sexp (client, str, &result);
2199 if (!rc)
2201 pthread_cleanup_push ((void *)list_command_free1, result);
2202 rc = xfer_data (ctx, result->str, result->len);
2203 pthread_cleanup_pop (1);
2206 else
2207 rc = xfer_data (ctx, str->str, str->len);
2210 pthread_cleanup_pop (1);
2211 return rc;
2214 elements = xcalloc (1, sizeof (struct element_list_s));
2215 if (!elements)
2216 return GPG_ERR_ENOMEM;
2218 elements->prefix = string_new (NULL);
2219 if (!elements->prefix)
2221 xml_free_element_list (elements);
2222 return GPG_ERR_ENOMEM;
2225 elements->recurse = client->opts & OPT_LIST_RECURSE;
2226 pthread_cleanup_push ((void *)xml_free_element_list, elements);
2227 struct string_s *str = string_new (NULL);
2228 string_large (str);
2229 pthread_cleanup_push ((void *)list_command_free1, str);
2230 rc = list_path_once (client, line, elements, str);
2231 if (!rc)
2233 if (client->opts & OPT_SEXP)
2235 rc = create_list_sexp (client, str, &result);
2236 if (!rc)
2238 pthread_cleanup_push ((void *)list_command_free1, result);
2239 rc = xfer_data (ctx, result->str, result->len);
2240 pthread_cleanup_pop (1);
2243 else
2244 rc = xfer_data (ctx, str->str, str->len);
2247 pthread_cleanup_pop (1);
2248 pthread_cleanup_pop (1);
2249 return rc;
2252 static gpg_error_t
2253 list_command (assuan_context_t ctx, char *line)
2255 struct client_s *client = assuan_get_pointer (ctx);
2256 gpg_error_t rc;
2257 struct argv_s *args[] = {
2258 &(struct argv_s) {"recurse", OPTION_TYPE_NOARG, parse_list_opt_recurse},
2259 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2260 /* These are deprecated but kept for backward compatibility with older
2261 * clients. */
2262 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, NULL},
2263 &(struct argv_s) {"with-target", OPTION_TYPE_NOARG, NULL},
2264 &(struct argv_s) {"all", OPTION_TYPE_NOARG, parse_list_opt_recurse},
2265 &(struct argv_s) {"no-recurse", OPTION_TYPE_NOARG, NULL},
2266 &(struct argv_s) {"sexp", OPTION_TYPE_NOARG, parse_opt_sexp},
2267 NULL
2270 if (disable_list_and_dump == 1)
2271 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2273 rc = parse_options (&line, args, client, 1);
2274 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2275 rc = GPG_ERR_SYNTAX;
2276 if (rc)
2277 return send_error (ctx, rc);
2279 if (client->opts & OPT_INQUIRE)
2281 unsigned char *result;
2282 size_t len;
2284 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2285 if (rc)
2286 return send_error (ctx, rc);
2288 pthread_cleanup_push ((void *)xfree, result);
2289 rc = do_list (ctx, (char *)result);
2290 pthread_cleanup_pop (1);
2292 else
2293 rc = do_list (ctx, line);
2295 return send_error (ctx, rc);
2299 * args[0] - element path
2301 static gpg_error_t
2302 attribute_list (assuan_context_t ctx, char **args)
2304 struct client_s *client = assuan_get_pointer (ctx);
2305 char **attrlist = NULL;
2306 gpg_error_t rc;
2307 char *line;
2309 if (!args || !args[0] || !*args[0])
2310 return GPG_ERR_SYNTAX;
2312 rc = attribute_list_common (client, args[0], &attrlist);
2313 pthread_cleanup_push ((void *)req_free, attrlist);
2315 if (!rc)
2317 line = strv_join ("\n", attrlist);
2318 if (line)
2320 pthread_cleanup_push ((void *)xfree, line);
2321 rc = xfer_data (ctx, line, strlen (line));
2322 pthread_cleanup_pop (1);
2324 else
2326 log_write ("%s(%i): %s", __FILE__, __LINE__,
2327 pwmd_strerror (GPG_ERR_ENOMEM));
2328 rc = GPG_ERR_ENOMEM;
2332 pthread_cleanup_pop (1);
2333 return rc;
2337 * args[0] - attribute
2338 * args[1] - element path
2340 static gpg_error_t
2341 attribute_delete (struct client_s *client, char **args)
2343 gpg_error_t rc;
2344 xmlNodePtr n;
2346 if (!args || !args[0] || !*args[0] || !args[1] || !*args[1])
2347 return GPG_ERR_SYNTAX;
2349 rc = xml_protected_attr (args[0]);
2350 if (rc || !strcmp (args[0], "_target"))
2351 return rc ? rc : GPG_ERR_EPERM;
2353 rc = copy_on_write (client);
2354 if (rc)
2355 return rc;
2357 if (!xml_reserved_attribute (args[0]))
2358 n = xml_resolve_path (client, client->doc, (xmlChar *)args[1], NULL, &rc);
2359 else
2361 struct xml_request_s *req;
2363 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
2364 if (rc)
2365 return rc;
2367 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2368 xml_free_request (req);
2371 if (!rc)
2372 rc = xml_is_element_owner (client, n, 0);
2374 if (!rc)
2375 rc = xml_delete_attribute (client, n, (xmlChar *) args[0]);
2377 return rc;
2381 * Creates the "_target" attribute. When other commands encounter an element
2382 * with this attribute they follow the "_target" after appending remaining
2383 * elements from the original element path to the target. The exception is the
2384 * ATTR command that operates on the element itself (for reserved attribute
2385 * names) and not the target.
2387 * If the source element path doesn't exist when using 'ATTR SET target', it is
2388 * created, but the destination element path must exist. This is similar to the
2389 * ls(1) command: ln -s src dst.
2391 * args[0] - source element path
2392 * args[1] - destination element path
2394 static gpg_error_t
2395 set_target_attribute (struct client_s *client, char **args)
2397 struct xml_request_s *req = NULL;
2398 char **src, **dst;
2399 gpg_error_t rc;
2400 xmlNodePtr n;
2402 if (!args || !args[0] || !args[1])
2403 return GPG_ERR_SYNTAX;
2405 src = str_split (args[0], "\t", 0);
2406 if (!src)
2407 return GPG_ERR_SYNTAX;
2409 if (!xml_valid_element_path (src, 0))
2411 strv_free (src);
2412 return GPG_ERR_INV_VALUE;
2415 dst = str_split (args[1], "\t", 0);
2416 if (!dst)
2418 strv_free (src);
2419 return GPG_ERR_SYNTAX;
2422 rc = copy_on_write (client);
2423 if (rc)
2424 goto fail;
2426 // Be sure the destination element path exists. */
2427 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
2428 if (rc)
2429 goto fail;
2431 (void)xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2432 if (rc && rc != GPG_ERR_EACCES)
2433 goto fail;
2435 xml_free_request (req);
2436 req = NULL;
2438 if (!strcmp (args[0], args[1]))
2440 rc = GPG_ERR_EEXIST;
2441 goto fail;
2444 rc = xml_new_request (client, args[0], XML_CMD_ATTR_TARGET, &req);
2445 if (rc)
2446 goto fail;
2448 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2449 if (rc && rc != GPG_ERR_EACCES)
2450 goto fail;
2452 if (!rc)
2454 rc = xml_add_attribute (client, n, "_target", args[1]);
2455 if (!rc)
2457 rc = xml_remove_user_attributes (client, n);
2458 if (!rc)
2459 rc = xml_unlink_node (client, n->children);
2463 fail:
2464 strv_free (src);
2465 strv_free (dst);
2466 xml_free_request (req);
2467 return rc;
2471 * args[0] - attribute
2472 * args[1] - element path
2474 static gpg_error_t
2475 attribute_get (assuan_context_t ctx, char **args)
2477 struct client_s *client = assuan_get_pointer (ctx);
2478 xmlNodePtr n;
2479 xmlChar *a;
2480 gpg_error_t rc;
2481 struct xml_request_s *req;
2483 if (!args || !args[0] || !*args[0] || !args[1] || !*args[1])
2484 return GPG_ERR_SYNTAX;
2486 if (!xml_reserved_attribute (args[0]))
2487 n = xml_resolve_path (client, client->doc, (xmlChar *)args[1], NULL, &rc);
2488 else
2490 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
2491 if (rc)
2492 return rc;
2494 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2495 xml_free_request (req);
2498 if (rc)
2499 return rc;
2501 a = xmlGetProp (n, (xmlChar *) args[0]);
2502 if (!a)
2503 return GPG_ERR_NOT_FOUND;
2505 pthread_cleanup_push ((void *)xmlFree, a);
2507 if (*a)
2508 rc = xfer_data (ctx, (char *) a, xmlStrlen (a));
2509 else
2510 rc = GPG_ERR_NO_DATA;
2512 pthread_cleanup_pop (1);
2513 return rc;
2517 * args[0] - attribute
2518 * args[1] - element path
2519 * args[2] - value
2521 static gpg_error_t
2522 attribute_set (struct client_s *client, char **args)
2524 struct xml_request_s *req;
2525 gpg_error_t rc;
2526 xmlNodePtr n;
2528 if (!args || !args[0] || !args[1])
2529 return GPG_ERR_SYNTAX;
2532 * Reserved attribute names.
2534 if ((rc = xml_protected_attr (args[0])))
2535 return rc;
2536 else if (!strcmp (args[0], "_target"))
2537 return set_target_attribute (client, args + 1);
2538 else if (!strcmp (args[0], "_acl"))
2539 rc = xml_valid_username (args[2]);
2540 else if (!xml_valid_attribute (args[0]))
2541 return GPG_ERR_INV_VALUE;
2543 if (rc)
2544 return rc;
2546 if (!xml_valid_attribute_value (args[2]))
2547 return GPG_ERR_INV_VALUE;
2549 rc = copy_on_write (client);
2550 if (rc)
2551 return rc;
2553 if (!xml_reserved_attribute (args[0]))
2555 n = xml_resolve_path (client, client->doc, (xmlChar *)args[1], NULL, &rc);
2556 if (!rc)
2558 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
2559 if (!rc)
2561 rc = xml_check_recursion (client, req);
2562 xml_free_request (req);
2566 else
2568 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
2569 if (rc)
2570 return rc;
2572 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2573 xml_free_request (req);
2576 if (!rc)
2577 rc = xml_is_element_owner (client, n, 0);
2579 if (!rc)
2580 rc = xml_add_attribute (client, n, args[0], args[2]);
2582 return rc;
2586 * req[0] - command
2587 * req[1] - attribute name or element path if command is LIST
2588 * req[2] - element path
2589 * req[2] - element path or value
2592 static gpg_error_t
2593 do_attr (assuan_context_t ctx, char *line)
2595 struct client_s *client = assuan_get_pointer (ctx);
2596 gpg_error_t rc = 0;
2597 char **req;
2599 if (!line || !*line)
2600 return GPG_ERR_SYNTAX;
2602 req = str_split (line, " ", 4);
2603 if (!req || !req[0] || !req[1])
2605 strv_free (req);
2606 return GPG_ERR_SYNTAX;
2609 pthread_cleanup_push ((void *)req_free, req);
2611 if (strcasecmp (req[0], "SET") == 0)
2612 rc = attribute_set (client, req + 1);
2613 else if (strcasecmp (req[0], "GET") == 0)
2614 rc = attribute_get (ctx, req + 1);
2615 else if (strcasecmp (req[0], "DELETE") == 0)
2616 rc = attribute_delete (client, req + 1);
2617 else if (strcasecmp (req[0], "LIST") == 0)
2618 rc = attribute_list (ctx, req + 1);
2619 else
2620 rc = GPG_ERR_SYNTAX;
2622 client->flags &= ~(FLAG_ACL_IGNORE|FLAG_ACL_ERROR);
2623 pthread_cleanup_pop (1);
2624 return rc;
2627 static gpg_error_t
2628 attr_command (assuan_context_t ctx, char *line)
2630 struct client_s *client = assuan_get_pointer (ctx);
2631 gpg_error_t rc;
2632 struct argv_s *args[] = {
2633 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2634 NULL
2637 rc = parse_options (&line, args, client, 1);
2638 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2639 rc = GPG_ERR_SYNTAX;
2640 if (rc)
2641 return send_error (ctx, rc);
2643 if (client->opts & OPT_INQUIRE)
2645 unsigned char *result;
2646 size_t len;
2648 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2649 if (rc)
2650 return send_error (ctx, rc);
2652 pthread_cleanup_push ((void *)xfree, result);
2653 rc = do_attr (ctx, (char *)result);
2654 pthread_cleanup_pop (1);
2656 else
2657 rc = do_attr (ctx, line);
2659 return send_error (ctx, rc);
2662 static gpg_error_t
2663 parse_iscached_opt_lock (void *data, void *value)
2665 struct client_s *client = data;
2667 (void) value;
2668 client->opts |= OPT_LOCK;
2669 return 0;
2672 static gpg_error_t
2673 parse_iscached_opt_agent (void *data, void *value)
2675 struct client_s *client = data;
2677 (void) value;
2678 client->opts |= OPT_CACHE_AGENT;
2679 return 0;
2682 static gpg_error_t
2683 parse_iscached_opt_sign (void *data, void *value)
2685 struct client_s *client = data;
2687 (void) value;
2688 client->opts |= OPT_CACHE_SIGN;
2689 return 0;
2692 static gpg_error_t
2693 iscached_command (assuan_context_t ctx, char *line)
2695 struct client_s *client = assuan_get_pointer (ctx);
2696 gpg_error_t rc;
2697 int defer = 0;
2698 struct argv_s *args[] = {
2699 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_iscached_opt_lock},
2700 &(struct argv_s) {"agent", OPTION_TYPE_NOARG, parse_iscached_opt_agent},
2701 &(struct argv_s) {"sign", OPTION_TYPE_NOARG, parse_iscached_opt_sign},
2702 NULL
2705 if (!line || !*line)
2706 return send_error (ctx, GPG_ERR_SYNTAX);
2708 rc = parse_options (&line, args, client, 1);
2709 if (rc)
2710 return send_error (ctx, rc);
2711 else if (!valid_filename (line))
2712 return send_error (ctx, GPG_ERR_INV_VALUE);
2714 if (!(client->flags & FLAG_OPEN)
2715 && ((client->opts & OPT_CACHE_AGENT) || (client->opts & OPT_CACHE_SIGN)))
2716 return send_error (ctx, GPG_ERR_INV_STATE);
2718 rc = cache_iscached (line, &defer, (client->opts & OPT_CACHE_AGENT),
2719 (client->opts & OPT_CACHE_SIGN));
2720 if (!rc && defer)
2721 rc = GPG_ERR_NO_DATA;
2723 if (!rc)
2725 struct cache_data_s *cdata = cache_get_data (line, NULL);
2727 if (cdata)
2729 rc = validate_checksum (client, line, cdata, NULL, NULL, 1);
2730 if (rc == GPG_ERR_CHECKSUM)
2731 rc = GPG_ERR_NO_DATA;
2735 if (client->opts & OPT_LOCK
2736 && (!rc || gpg_err_code (rc) == GPG_ERR_NO_DATA
2737 || gpg_err_code (rc) == GPG_ERR_ENOENT))
2739 gpg_error_t trc = rc;
2741 if (client->filename && strcmp (line, client->filename))
2742 reset_client (client);
2744 xfree (client->filename);
2745 client->filename = str_dup (line);
2746 rc = do_lock (client, 1);
2747 if (!rc)
2748 rc = trc;
2751 return send_error (ctx, rc);
2754 static gpg_error_t
2755 clearcache_command (assuan_context_t ctx, char *line)
2757 struct client_s *client = assuan_get_pointer (ctx);
2758 gpg_error_t rc = 0, all_rc = 0;
2759 int i;
2760 int t;
2761 int all = 0;
2762 struct client_thread_s *once = NULL;
2763 unsigned count;
2765 cache_lock ();
2766 pthread_cleanup_push (cache_release_mutex, NULL);
2767 count = cache_file_count ();
2768 MUTEX_LOCK (&cn_mutex);
2769 pthread_cleanup_push ((void *)release_mutex_cb, &cn_mutex);
2771 if (!line || !*line)
2772 all = 1;
2774 t = slist_length (cn_thread_list);
2776 for (i = 0; i < t; i++)
2778 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2779 assuan_peercred_t peer;
2781 if (!thd->cl)
2782 continue;
2784 /* Lock each connected clients' file mutex to prevent any other client
2785 * from accessing the cache entry (the file mutex is locked upon
2786 * command startup). The cache for the entry is not cleared if the
2787 * file mutex is locked by another client to prevent this function
2788 * from blocking. Rather, it returns an error.
2790 if (all)
2792 if (thd->cl->filename)
2794 rc = do_validate_peer (ctx, thd->cl->filename, &peer, NULL);
2795 /* The current client doesn't have permission to open the other
2796 * filename do to "access" configuration parameter in a filename
2797 * section. Since we are clearning all cache entries the error
2798 * will be returned later during cache_clear(). */
2799 if (rc)
2801 rc = 0;
2802 continue;
2805 else // Idle client without opened file?
2806 continue;
2808 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->filename, -1, 0, -1);
2809 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2811 /* The current client owns the lock. */
2812 if (pthread_equal (pthread_self (), thd->tid))
2813 rc = 0;
2814 else
2816 if (cache_iscached (thd->cl->filename, NULL, 0, 0)
2817 == GPG_ERR_NO_DATA)
2819 rc = 0;
2820 continue;
2823 /* The cache entry will be cleared when the other client
2824 * disconnects and cache_timer_thread() does its thing. */
2825 cache_defer_clear (thd->cl->filename);
2828 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
2830 rc = 0;
2831 continue;
2834 if (!rc)
2836 rc = cache_clear (NULL, thd->cl->filename, 1, 0);
2837 cache_unlock_mutex (thd->cl->filename, 0);
2840 if (rc)
2841 all_rc = rc;
2843 rc = 0;
2845 else
2847 /* A single data filename was specified. Lock only this data file
2848 * mutex and free the cache entry. */
2849 rc = do_validate_peer (ctx, line, &peer, NULL);
2850 if (rc == GPG_ERR_FORBIDDEN)
2851 rc = peer_is_invoker (client);
2853 if (rc == GPG_ERR_EACCES)
2854 rc = GPG_ERR_FORBIDDEN;
2856 if (!rc && thd->cl->filename && !strcmp (thd->cl->filename , line))
2858 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->filename, -1, 0, -1);
2859 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2861 /* The current client owns the lock. */
2862 if (pthread_equal (pthread_self (), thd->tid))
2863 rc = 0;
2866 if (!rc)
2868 once = thd;
2869 rc = cache_clear (NULL, thd->cl->filename, 1, 0);
2870 cache_unlock_mutex (thd->cl->filename, 0);
2872 else
2873 cache_defer_clear (thd->cl->filename);
2875 /* Found a client with the opened file. The cache entry has been
2876 * either cleared (self) or deferred to be cleared. */
2877 break;
2882 /* Only connected clients' cache entries have been cleared. Now clear any
2883 * remaining cache entries without clients but only if there wasn't an
2884 * error from above since this would defeat the locking check of the
2885 * remaining entries. */
2886 if (all && !all_rc && cache_file_count ())
2888 rc = cache_clear (client, NULL, 1, 0);
2889 if (rc == GPG_ERR_EACCES)
2890 rc = GPG_ERR_FORBIDDEN;
2893 /* No clients are using the specified file. */
2894 else if (!all_rc && !rc && !once)
2895 rc = cache_clear (NULL, line, 1, 0);
2897 /* Release the connection mutex. */
2898 pthread_cleanup_pop (1);
2900 if (!rc || (cache_file_count () && count != cache_file_count ()))
2901 send_status_all (STATUS_CACHE, NULL);
2903 /* Release the cache mutex. */
2904 pthread_cleanup_pop (1);
2906 /* One or more files were locked while clearing all cache entries. */
2907 if (all_rc)
2908 rc = all_rc;
2910 return send_error (ctx, rc);
2913 static gpg_error_t
2914 cachetimeout_command (assuan_context_t ctx, char *line)
2916 struct client_s *client = assuan_get_pointer (ctx);
2917 long timeout;
2918 char **req = str_split (line, " ", 0);
2919 char *p;
2920 gpg_error_t rc = 0;
2922 if (!(client->flags & FLAG_OPEN))
2923 return send_error (ctx, GPG_ERR_INV_STATE);
2925 if (!req || !*req || strv_length (req) > 1)
2927 strv_free (req);
2928 return send_error (ctx, GPG_ERR_SYNTAX);
2931 errno = 0;
2932 timeout = strtol (req[0], &p, 10);
2933 if (errno != 0 || *p || timeout < (long)-1)
2934 rc = GPG_ERR_SYNTAX;
2936 if (!rc)
2938 rc = cache_set_timeout (client->filename, timeout);
2939 if (!rc || gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
2941 rc = 0;
2942 MUTEX_LOCK (&rcfile_mutex);
2943 config_set_long_param (&global_config, client->filename,
2944 "cache_timeout", req[0]);
2945 MUTEX_UNLOCK (&rcfile_mutex);
2949 strv_free (req);
2950 return send_error (ctx, rc);
2953 static gpg_error_t
2954 dump_command (assuan_context_t ctx, char *line)
2956 xmlChar *xml;
2957 int len;
2958 struct client_s *client = assuan_get_pointer (ctx);
2959 gpg_error_t rc;
2961 if (disable_list_and_dump == 1)
2962 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2964 if (line && *line)
2965 return send_error (ctx, GPG_ERR_SYNTAX);
2967 rc = peer_is_invoker(client);
2968 if (rc)
2969 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
2971 xmlDocDumpFormatMemory (client->doc, &xml, &len, 1);
2973 if (!xml)
2975 log_write ("%s(%i): %s", __FILE__, __LINE__,
2976 pwmd_strerror (GPG_ERR_ENOMEM));
2977 return send_error (ctx, GPG_ERR_ENOMEM);
2980 pthread_cleanup_push ((void *)xmlFree, xml);
2981 rc = xfer_data (ctx, (char *) xml, len);
2982 pthread_cleanup_pop (1);
2983 return send_error (ctx, rc);
2986 static gpg_error_t
2987 getconfig_command (assuan_context_t ctx, char *line)
2989 struct client_s *client = assuan_get_pointer (ctx);
2990 gpg_error_t rc = 0;
2991 char filename[255] = { 0 }, param[747] = { 0 };
2992 char *p, *tmp = NULL, *fp = client->filename, *paramp = line;
2994 if (!line || !*line)
2995 return send_error (ctx, GPG_ERR_SYNTAX);
2997 if (strchr (line, ' '))
2999 int ret = sscanf (line, " %254[^ ] %746c", filename, param);
3001 if (ret <= 0)
3002 return send_error (ctx, gpg_error_from_syserror());
3003 paramp = param;
3004 fp = filename;
3007 if (fp && !valid_filename (fp))
3008 return send_error (ctx, GPG_ERR_INV_VALUE);
3010 paramp = str_down (paramp);
3011 p = config_get_value (fp ? fp : "global", paramp);
3012 if (!p)
3013 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
3015 tmp = expand_homedir (p);
3016 xfree (p);
3017 if (!tmp)
3019 log_write ("%s(%i): %s", __FILE__, __LINE__,
3020 pwmd_strerror (GPG_ERR_ENOMEM));
3021 return send_error (ctx, GPG_ERR_ENOMEM);
3024 p = tmp;
3025 pthread_cleanup_push ((void *)xfree, p);
3026 rc = xfer_data (ctx, p, strlen (p));
3027 pthread_cleanup_pop (1);
3028 return send_error (ctx, rc);
3031 struct xpath_s
3033 xmlXPathContextPtr xp;
3034 xmlXPathObjectPtr result;
3035 xmlBufferPtr buf;
3036 char **req;
3039 static void
3040 xpath_command_free (void *arg)
3042 struct xpath_s *xpath = arg;
3044 if (!xpath)
3045 return;
3047 req_free (xpath->req);
3049 if (xpath->buf)
3050 xmlBufferFree (xpath->buf);
3052 if (xpath->result)
3053 xmlXPathFreeObject (xpath->result);
3055 if (xpath->xp)
3056 xmlXPathFreeContext (xpath->xp);
3059 static gpg_error_t
3060 do_xpath (assuan_context_t ctx, char *line)
3062 gpg_error_t rc;
3063 struct client_s *client = assuan_get_pointer (ctx);
3064 struct xpath_s _x = { 0 };
3065 struct xpath_s *xpath = &_x;
3067 if (!line || !*line)
3068 return GPG_ERR_SYNTAX;
3070 if ((xpath->req = str_split (line, "\t", 2)) == NULL)
3072 if (strv_printf (&xpath->req, "%s", line) == 0)
3073 return GPG_ERR_ENOMEM;
3076 if (xpath->req[1])
3078 rc = copy_on_write (client);
3079 if (rc)
3080 goto fail;
3083 xpath->xp = xmlXPathNewContext (client->doc);
3084 if (!xpath->xp)
3086 rc = GPG_ERR_BAD_DATA;
3087 goto fail;
3090 xpath->result =
3091 xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
3092 if (!xpath->result)
3094 rc = GPG_ERR_BAD_DATA;
3095 goto fail;
3098 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
3100 rc = GPG_ERR_ELEMENT_NOT_FOUND;
3101 goto fail;
3104 rc = xml_recurse_xpath_nodeset (client, client->doc,
3105 xpath->result->nodesetval,
3106 (xmlChar *) xpath->req[1], &xpath->buf, 0,
3107 NULL);
3108 if (rc)
3109 goto fail;
3110 else if (!xpath->req[1] && !xmlBufferLength (xpath->buf))
3112 rc = GPG_ERR_NO_DATA;
3113 goto fail;
3115 else if (xpath->req[1])
3117 rc = 0;
3118 goto fail;
3121 pthread_cleanup_push ((void *)xpath_command_free, &xpath);
3122 rc = xfer_data (ctx, (char *) xmlBufferContent (xpath->buf),
3123 xmlBufferLength (xpath->buf));
3124 pthread_cleanup_pop (0);
3125 fail:
3126 xpath_command_free (xpath);
3127 return rc;
3130 static gpg_error_t
3131 xpath_command (assuan_context_t ctx, char *line)
3133 struct client_s *client = assuan_get_pointer (ctx);
3134 gpg_error_t rc;
3135 struct argv_s *args[] = {
3136 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3137 NULL
3140 if (disable_list_and_dump == 1)
3141 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
3143 rc = peer_is_invoker(client);
3144 if (rc)
3145 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
3147 rc = parse_options (&line, args, client, 1);
3148 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3149 rc = GPG_ERR_SYNTAX;
3150 if (rc)
3151 return send_error (ctx, rc);
3153 if (client->opts & OPT_INQUIRE)
3155 unsigned char *result;
3156 size_t len;
3158 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3159 if (rc)
3160 return send_error (ctx, rc);
3162 pthread_cleanup_push ((void *)xfree, result);
3163 rc = do_xpath (ctx, (char *)result);
3164 pthread_cleanup_pop (1);
3166 else
3167 rc = do_xpath (ctx, line);
3169 return send_error (ctx, rc);
3172 static gpg_error_t
3173 do_xpathattr (assuan_context_t ctx, char *line)
3175 struct client_s *client = assuan_get_pointer (ctx);
3176 gpg_error_t rc;
3177 char **req = NULL;
3178 int cmd = 0; //SET
3179 struct xpath_s _x = { 0 };
3180 struct xpath_s *xpath = &_x;
3182 if (!line || !*line)
3183 return GPG_ERR_SYNTAX;
3185 if ((req = str_split (line, " ", 3)) == NULL)
3186 return GPG_ERR_ENOMEM;
3188 if (!req[0])
3190 rc = GPG_ERR_SYNTAX;
3191 goto fail;
3194 if (!strcasecmp (req[0], "SET"))
3195 cmd = 0;
3196 else if (!strcasecmp (req[0], "DELETE"))
3197 cmd = 1;
3198 else
3200 rc = GPG_ERR_SYNTAX;
3201 goto fail;
3204 if (!req[1] || !req[2])
3206 rc = GPG_ERR_SYNTAX;
3207 goto fail;
3210 if ((xpath->req = str_split (req[2], "\t", 3)) == NULL)
3212 rc = GPG_ERR_ENOMEM;
3213 goto fail;
3216 if (!xpath->req[0] || (!xpath->req[1] && !cmd) || (xpath->req[1] && cmd))
3218 rc = GPG_ERR_SYNTAX;
3219 goto fail;
3222 rc = copy_on_write (client);
3223 if (rc)
3224 goto fail;
3226 xpath->xp = xmlXPathNewContext (client->doc);
3227 if (!xpath->xp)
3229 rc = GPG_ERR_BAD_DATA;
3230 goto fail;
3233 xpath->result = xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
3234 if (!xpath->result)
3236 rc = GPG_ERR_BAD_DATA;
3237 goto fail;
3240 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
3242 rc = GPG_ERR_ELEMENT_NOT_FOUND;
3243 goto fail;
3246 rc = xml_recurse_xpath_nodeset (client, client->doc,
3247 xpath->result->nodesetval,
3248 (xmlChar *) xpath->req[1], &xpath->buf, cmd,
3249 (xmlChar *) req[1]);
3251 fail:
3252 xpath_command_free (xpath);
3253 strv_free (req);
3254 return rc;
3257 /* XPATHATTR SET|DELETE <name> <expression>[<TAB>[value]] */
3258 static gpg_error_t
3259 xpathattr_command (assuan_context_t ctx, char *line)
3261 struct client_s *client = assuan_get_pointer (ctx);
3262 gpg_error_t rc;
3263 struct argv_s *args[] = {
3264 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3265 NULL
3268 if (disable_list_and_dump == 1)
3269 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
3271 rc = peer_is_invoker(client);
3272 if (rc)
3273 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
3275 rc = parse_options (&line, args, client, 1);
3276 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3277 rc = GPG_ERR_SYNTAX;
3278 if (rc)
3279 return send_error (ctx, rc);
3281 if (client->opts & OPT_INQUIRE)
3283 unsigned char *result;
3284 size_t len;
3286 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3287 if (rc)
3288 return send_error (ctx, rc);
3290 pthread_cleanup_push ((void *)xfree, result);
3291 rc = do_xpathattr (ctx, (char *)result);
3292 pthread_cleanup_pop (1);
3294 else
3295 rc = do_xpathattr (ctx, line);
3297 return send_error (ctx, rc);
3300 static gpg_error_t
3301 do_import (struct client_s *client, const char *root_element,
3302 unsigned char *content)
3304 xmlDocPtr doc = NULL;
3305 xmlNodePtr n = NULL, root;
3306 gpg_error_t rc = 0;
3307 struct string_s *str = NULL, *tstr = NULL;
3308 struct xml_request_s *req = NULL;
3310 if (!content || !*content)
3311 return GPG_ERR_SYNTAX;
3313 if (root_element)
3315 rc = xml_new_request (client, root_element, XML_CMD_STORE, &req);
3316 if (rc)
3318 xfree (content);
3319 return rc;
3322 if (!xml_valid_element_path (req->args, 0))
3324 xml_free_request (req);
3325 xfree (content);
3326 return GPG_ERR_INV_VALUE;
3330 str = string_new_content ((char *)content);
3331 tstr = string_prepend (str, "<pwmd>");
3332 if (tstr)
3334 str = tstr;
3335 tstr = string_append (str, "</pwmd>");
3336 if (!tstr)
3337 rc = GPG_ERR_ENOMEM;
3338 else
3339 str = tstr;
3341 else
3342 rc = GPG_ERR_ENOMEM;
3344 if (rc)
3345 goto fail;
3347 doc = xmlReadDoc ((xmlChar *) str->str, NULL, "UTF-8", XML_PARSE_NOBLANKS);
3348 string_free (str, 1);
3349 if (!doc)
3351 rc = GPG_ERR_BAD_DATA;
3352 goto fail;
3355 root = xmlDocGetRootElement (doc);
3356 root = root->children;
3357 if (!root || root->type != XML_ELEMENT_NODE)
3359 rc = GPG_ERR_BAD_DATA;
3360 goto fail;
3363 rc = xml_validate_import (client, root);
3364 if (rc)
3365 goto fail;
3367 if (req)
3369 /* Create the new specified root element path, if needed. */
3370 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc),
3371 &rc);
3372 if (rc)
3373 goto fail;
3375 /* Overwrite the children of the specified root element path. */
3376 (void)xml_unlink_node (client, n->children);
3377 n->children = NULL;
3379 else
3380 n = xmlDocGetRootElement (client->doc);
3382 if (n)
3384 xmlNodePtr copy;
3385 xmlChar *name = xml_attribute_value (root, (xmlChar *)"_name");
3387 if (!name)
3388 rc = GPG_ERR_BAD_DATA;
3389 else
3390 rc = xml_is_element_owner (client, n, 0);
3392 if (!rc && !req)
3394 /* No --root argument passed. Overwrite the current documents' root
3395 * element matching the root element of the imported data. */
3396 xml_free_request (req);
3397 req = NULL;
3398 rc = xml_new_request (client, (char *)name, XML_CMD_DELETE, &req);
3399 xmlFree (name);
3400 if (!rc)
3402 xmlNodePtr tmp;
3404 tmp = xml_find_elements (client, req,
3405 xmlDocGetRootElement (req->doc), &rc);
3406 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3407 goto fail;
3409 if (!rc)
3411 rc = xml_is_element_owner (client, tmp, 0);
3412 if (rc)
3413 goto fail;
3416 (void)xml_unlink_node (client, tmp);
3417 rc = 0;
3421 if (!rc)
3423 copy = xmlCopyNodeList (root);
3424 if (!copy)
3425 rc = GPG_ERR_ENOMEM;
3426 else
3428 n = xmlAddChildList (n, copy);
3429 if (!n)
3430 rc = GPG_ERR_ENOMEM;
3435 if (!rc && n && n->parent)
3436 rc = xml_update_element_mtime (client, n->parent);
3438 fail:
3439 xml_free_request (req);
3441 if (doc)
3442 xmlFreeDoc (doc);
3444 return rc;
3447 static gpg_error_t
3448 parse_import_opt_root (void *data, void *value)
3450 struct client_s *client = data;
3452 client->import_root = str_dup (value);
3453 return client->import_root ? 0 : GPG_ERR_ENOMEM;
3456 static gpg_error_t
3457 import_command (assuan_context_t ctx, char *line)
3459 gpg_error_t rc;
3460 struct client_s *client = assuan_get_pointer (ctx);
3461 unsigned char *result;
3462 size_t len;
3463 struct argv_s *args[] = {
3464 &(struct argv_s) {"root", OPTION_TYPE_ARG, parse_import_opt_root},
3465 NULL
3468 xfree (client->import_root);
3469 client->import_root = NULL;
3470 rc = parse_options (&line, args, client, client->bulk_p ? 1 : 0);
3471 if (rc)
3472 return send_error (ctx, rc);
3474 rc = copy_on_write (client);
3475 if (rc)
3476 return send_error (ctx, rc);
3478 if (!client->bulk_p)
3480 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3481 if (rc)
3483 xfree (client->import_root);
3484 client->import_root = NULL;
3485 return send_error (ctx, rc);
3487 rc = do_import (client, client->import_root, result);
3489 else
3491 char *p = str_dup (line);
3493 if (!p)
3494 rc = GPG_ERR_ENOMEM;
3495 else
3496 rc = do_import (client, client->import_root, (unsigned char *)p);
3499 xfree (client->import_root);
3500 client->import_root = NULL;
3501 return send_error (ctx, rc);
3504 static gpg_error_t
3505 do_lock (struct client_s *client, int add)
3507 gpg_error_t rc = lock_file_mutex (client, add);
3509 if (!rc)
3510 client->flags |= FLAG_LOCK_CMD;
3512 return rc;
3515 static gpg_error_t
3516 lock_command (assuan_context_t ctx, char *line)
3518 struct client_s *client = assuan_get_pointer (ctx);
3519 gpg_error_t rc;
3521 if (line && *line)
3522 return send_error (ctx, GPG_ERR_SYNTAX);
3524 rc = do_lock (client, 0);
3525 return send_error (ctx, rc);
3528 static gpg_error_t
3529 unlock_command (assuan_context_t ctx, char *line)
3531 struct client_s *client = assuan_get_pointer (ctx);
3532 gpg_error_t rc;
3534 if (line && *line)
3535 return send_error (ctx, GPG_ERR_SYNTAX);
3537 rc = unlock_file_mutex (client, 0);
3538 return send_error (ctx, rc);
3541 static void
3542 set_env (const char *name, char *buf, size_t size, const char *value)
3544 MUTEX_LOCK (&rcfile_mutex);
3545 if (!value || !*value)
3547 unsetenv (name);
3548 buf[0] = 0;
3550 else if (!buf[0] || strcmp (buf, value))
3552 snprintf (buf, size, "%s=%s", name, value);
3553 putenv (buf);
3556 MUTEX_UNLOCK (&rcfile_mutex);
3559 static gpg_error_t
3560 option_command (assuan_context_t ctx, char *line)
3562 struct client_s *client = assuan_get_pointer (ctx);
3563 gpg_error_t rc = 0;
3564 char namebuf[255] = { 0 };
3565 char *name = namebuf;
3566 char *value = NULL, *p, *tmp = NULL;
3568 p = strchr (line, '=');
3569 if (!p)
3571 strncpy (namebuf, line, sizeof(namebuf));
3572 namebuf[sizeof(namebuf)-1] = 0;
3574 else
3576 tmp = str_dup (line);
3577 if (!tmp)
3578 return send_error (ctx, GPG_ERR_ENOMEM);
3580 tmp[strlen (line) - strlen (p)] = 0;
3581 strncpy (namebuf, tmp, sizeof (namebuf));
3582 namebuf[sizeof(namebuf)-1] = 0;
3583 xfree (tmp);
3584 tmp = NULL;
3585 value = p+1;
3588 log_write2 ("OPTION name='%s' value='%s'", name, value);
3590 if (strcasecmp (name, (char *) "lock-timeout") == 0)
3592 long n = 0;
3594 if (value)
3596 n = strtol (value, &tmp, 10);
3597 if (tmp && *tmp)
3598 return send_error (ctx, GPG_ERR_INV_VALUE);
3601 client->lock_timeout = n;
3603 else if (strcasecmp (name, (char *) "client-state") == 0)
3605 long n = 0;
3607 MUTEX_LOCK (&client->thd->status_mutex);
3608 if (value)
3610 n = strtol (value, &tmp, 10);
3611 if ((tmp && *tmp) || (n < 0 || n > 1))
3613 MUTEX_UNLOCK (&client->thd->status_mutex);
3614 return send_error (ctx, GPG_ERR_INV_VALUE);
3616 client->client_state = n;
3618 else
3619 client->client_state = 0;
3620 MUTEX_UNLOCK (&client->thd->status_mutex);
3622 else if (strcasecmp (name, (char *) "NAME") == 0)
3624 if (value && strchr (value, ' '))
3625 rc = GPG_ERR_INV_VALUE;
3626 else
3628 MUTEX_LOCK (&cn_mutex);
3629 tmp = pthread_getspecific (thread_name_key);
3630 pthread_setspecific (thread_name_key, NULL);
3631 xfree (tmp);
3632 xfree (client->thd->name);
3633 client->thd->name = NULL;
3634 if (value && *value)
3636 pthread_setspecific (thread_name_key, str_dup (value));
3637 client->thd->name = str_dup (value);
3639 MUTEX_UNLOCK (&cn_mutex);
3642 else if (strcasecmp (name, "disable-pinentry") == 0)
3644 int n = 1;
3646 if (value && *value)
3648 n = (int) strtol (value, &tmp, 10);
3649 if (*tmp || n < 0 || n > 1)
3650 return send_error (ctx, GPG_ERR_INV_VALUE);
3653 if (n)
3654 client->flags |= FLAG_NO_PINENTRY;
3655 else
3656 client->flags &= ~FLAG_NO_PINENTRY;
3658 else if (strcasecmp (name, "ttyname") == 0)
3659 set_env ("GPG_TTY", env_gpg_tty, sizeof (env_gpg_tty), value);
3660 else if (strcasecmp (name, "ttytype") == 0)
3661 set_env ("TERM", env_term, sizeof (env_term), value);
3662 else if (strcasecmp (name, "display") == 0)
3663 set_env ("DISPLAY", env_display, sizeof (env_display), value);
3664 else if (strcasecmp (name, "lc_messages") == 0)
3667 else if (strcasecmp (name, "lc_ctype") == 0)
3670 else if (strcasecmp (name, "desc") == 0)
3673 else if (strcasecmp (name, "pinentry-timeout") == 0)
3676 else
3677 rc = GPG_ERR_UNKNOWN_OPTION;
3679 return send_error (ctx, rc);
3682 static gpg_error_t
3683 do_rename (assuan_context_t ctx, char *line)
3685 struct client_s *client = assuan_get_pointer (ctx);
3686 char **args, *p;
3687 xmlNodePtr src, dst;
3688 struct string_s *str = NULL, *tstr;
3689 struct xml_request_s *req;
3690 gpg_error_t rc;
3692 if (!line || !*line)
3693 return GPG_ERR_SYNTAX;
3695 args = str_split (line, " ", 0);
3696 if (!args || strv_length (args) != 2)
3698 strv_free (args);
3699 return GPG_ERR_SYNTAX;
3702 if (!xml_valid_element ((xmlChar *) args[1]))
3704 strv_free (args);
3705 return GPG_ERR_INV_VALUE;
3708 rc = xml_new_request (client, args[0], XML_CMD_RENAME, &req);
3709 if (rc)
3711 strv_free (args);
3712 return rc;
3715 src = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3716 if (rc)
3717 goto fail;
3719 rc = xml_is_element_owner (client, src, 0);
3720 if (rc)
3721 goto fail;
3723 xmlChar *a = xmlGetProp (src, (xmlChar *) "_name");
3724 if (!a)
3726 rc = GPG_ERR_ENOMEM;
3727 goto fail;
3730 /* To prevent unwanted effects:
3732 * <element _name="a"><element _name="b"/></element>
3734 * RENAME a<TAB>b b
3736 if (xmlStrEqual (a, (xmlChar *) args[1]))
3738 xmlFree (a);
3739 rc = GPG_ERR_EEXIST;
3740 goto fail;
3743 xmlFree (a);
3744 str = string_new (args[0]);
3745 if (!str)
3747 rc = GPG_ERR_ENOMEM;
3748 goto fail;
3751 p = strrchr (str->str, '\t');
3752 if (p)
3753 tstr = string_truncate (str, strlen (str->str)-strlen (p));
3754 else
3755 tstr = string_truncate (str, 0);
3757 if (!tstr)
3759 string_free (str, 1);
3760 rc = GPG_ERR_ENOMEM;
3761 goto fail;
3764 str = tstr;
3765 tstr = string_append_printf (str, "%s%s", str->len ? "\t" : "", args[1]);
3766 if (!tstr)
3768 string_free (str, 1);
3769 rc = GPG_ERR_ENOMEM;
3770 goto fail;
3773 str = tstr;
3774 xml_free_request (req);
3775 rc = xml_new_request (client, str->str, XML_CMD_RENAME, &req);
3776 string_free (str, 1);
3777 if (rc)
3779 req = NULL;
3780 goto fail;
3783 dst = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3784 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3785 goto fail;
3787 rc = 0;
3789 /* Target may exist:
3791 * <element _name="a"/>
3792 * <element _name="b" target="a"/>
3794 * RENAME b a
3796 if (src == dst)
3798 rc = GPG_ERR_EEXIST;
3799 goto fail;
3802 if (dst)
3804 rc = xml_is_element_owner (client, dst, 0);
3805 if (rc)
3806 goto fail;
3808 rc = xml_add_attribute (client, src, "_name", args[1]);
3809 if (!rc)
3810 xml_unlink_node (client, dst);
3812 else
3813 rc = xml_add_attribute (client, src, "_name", args[1]);
3815 fail:
3816 xml_free_request (req);
3817 strv_free (args);
3818 return rc;
3821 static gpg_error_t
3822 rename_command (assuan_context_t ctx, char *line)
3824 struct client_s *client = assuan_get_pointer (ctx);
3825 gpg_error_t rc;
3826 struct argv_s *args[] = {
3827 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3828 NULL
3831 rc = parse_options (&line, args, client, 1);
3832 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3833 rc = GPG_ERR_SYNTAX;
3834 if (rc)
3835 return send_error (ctx, rc);
3837 rc = copy_on_write (client);
3838 if (rc)
3839 return send_error (ctx, rc);
3841 if (client->opts & OPT_INQUIRE)
3843 unsigned char *result;
3844 size_t len;
3846 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3847 if (rc)
3848 return send_error (ctx, rc);
3850 pthread_cleanup_push ((void *)xfree, result);
3851 rc = do_rename (ctx, (char *)result);
3852 pthread_cleanup_pop (1);
3854 else
3855 rc = do_rename (ctx, line);
3857 return send_error (ctx, rc);
3860 static gpg_error_t
3861 do_copy (assuan_context_t ctx, char *line)
3863 struct client_s *client = assuan_get_pointer (ctx);
3864 char **args, **targs;
3865 xmlNodePtr src, dst, tree = NULL;
3866 struct xml_request_s *req;
3867 gpg_error_t rc;
3869 if (!line || !*line)
3870 return GPG_ERR_SYNTAX;
3872 args = str_split (line, " ", 0);
3873 if (!args || strv_length (args) != 2)
3875 strv_free (args);
3876 return GPG_ERR_SYNTAX;
3879 targs = str_split (args[1], "\t", 0);
3880 if (!targs)
3882 strv_free (args);
3883 return GPG_ERR_SYNTAX;
3886 if (!xml_valid_element_path (targs, 0))
3888 strv_free (args);
3889 strv_free (targs);
3890 return GPG_ERR_INV_VALUE;
3892 strv_free (targs);
3894 rc = xml_new_request (client, args[0], XML_CMD_NONE, &req);
3895 if (rc)
3897 strv_free (args);
3898 return rc;
3901 src = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3902 if (rc)
3903 goto fail;
3905 tree = xmlCopyNodeList (src);
3906 if (!tree)
3908 rc = GPG_ERR_ENOMEM;
3909 goto fail;
3912 xml_free_request (req);
3913 /* Create the destination element path if it does not exist. */
3914 rc = xml_new_request (client, args[1], XML_CMD_STORE, &req);
3915 if (rc)
3917 req = NULL;
3918 goto fail;
3921 dst = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3922 if (rc)
3923 goto fail;
3925 rc = xml_is_element_owner (client, dst, 0);
3926 if (rc)
3927 goto fail;
3929 if (!(req->flags & XML_REQUEST_FLAG_CREATED))
3931 rc = xml_validate_target (client, req->doc, args[1], src);
3932 if (rc || src == dst)
3934 rc = rc ? rc : GPG_ERR_EEXIST;
3935 goto fail;
3939 /* Merge any attributes from the src node to the initial dst node. */
3940 for (xmlAttrPtr attr = tree->properties; attr; attr = attr->next)
3942 if (xmlStrEqual (attr->name, (xmlChar *) "_name"))
3943 continue;
3945 xmlAttrPtr a = xmlHasProp (dst, attr->name);
3946 if (a)
3947 xmlRemoveProp (a);
3949 xmlChar *tmp = xmlNodeGetContent (attr->children);
3950 xmlNewProp (dst, attr->name, tmp);
3951 xmlFree (tmp);
3952 /* Create the default attributes. */
3953 rc = xml_add_attribute (client, dst, NULL, NULL);
3956 xmlNodePtr n = dst->children;
3957 (void)xml_unlink_node (client, n);
3958 dst->children = NULL;
3960 if (tree->children)
3962 n = xmlCopyNodeList (tree->children);
3963 if (!n)
3965 rc = GPG_ERR_ENOMEM;
3966 goto fail;
3969 n = xmlAddChildList (dst, n);
3970 if (!n)
3972 rc = GPG_ERR_ENOMEM;
3973 goto fail;
3976 rc = xml_update_element_mtime (client, xmlDocGetRootElement (client->doc)
3977 == dst->parent ? dst : dst->parent);
3980 fail:
3981 if (tree)
3982 (void)xml_unlink_node (client, tree);
3984 xml_free_request (req);
3985 strv_free (args);
3986 return rc;
3989 static gpg_error_t
3990 copy_command (assuan_context_t ctx, char *line)
3992 struct client_s *client = assuan_get_pointer (ctx);
3993 gpg_error_t rc;
3994 struct argv_s *args[] = {
3995 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3996 NULL
3999 rc = parse_options (&line, args, client, 1);
4000 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
4001 rc = GPG_ERR_SYNTAX;
4002 if (rc)
4003 return send_error (ctx, rc);
4005 rc = copy_on_write (client);
4006 if (rc)
4007 return send_error (ctx, rc);
4009 if (client->opts & OPT_INQUIRE)
4011 unsigned char *result;
4012 size_t len;
4014 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
4015 if (rc)
4016 return send_error (ctx, rc);
4018 pthread_cleanup_push ((void *)xfree, result);
4019 rc = do_copy (ctx, (char *)result);
4020 pthread_cleanup_pop (1);
4022 else
4023 rc = do_copy (ctx, line);
4025 return send_error (ctx, rc);
4028 static gpg_error_t
4029 do_move (assuan_context_t ctx, char *line)
4031 struct client_s *client = assuan_get_pointer (ctx);
4032 char **args;
4033 xmlNodePtr src, dst;
4034 struct xml_request_s *req;
4035 gpg_error_t rc;
4037 if (!line || !*line)
4038 return GPG_ERR_SYNTAX;
4040 args = str_split (line, " ", 0);
4041 if (!args || strv_length (args) != 2)
4043 strv_free (args);
4044 return GPG_ERR_SYNTAX;
4047 if (*args[1])
4049 char **targs = str_split (args[1], "\t", 0);
4050 if (!targs)
4052 strv_free (args);
4053 return GPG_ERR_ENOMEM;
4056 if (!xml_valid_element_path (targs, 0))
4058 strv_free (targs);
4059 strv_free (args);
4060 return GPG_ERR_INV_VALUE;
4063 strv_free (targs);
4066 rc = xml_new_request (client, args[0], XML_CMD_MOVE, &req);
4067 if (rc)
4069 strv_free (args);
4070 return rc;
4073 src = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
4074 if (rc)
4075 goto fail;
4077 rc = xml_is_element_owner (client, src, 0);
4078 if (rc)
4079 goto fail;
4081 xml_free_request (req);
4082 req = NULL;
4083 if (*args[1])
4085 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
4086 if (rc)
4087 goto fail;
4089 dst = xml_find_elements (client, req, xmlDocGetRootElement (req->doc),
4090 &rc);
4092 else
4093 dst = xmlDocGetRootElement (client->doc);
4095 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
4096 goto fail;
4098 rc = 0;
4100 for (xmlNodePtr n = dst; n; n = n->parent)
4102 if (n == src)
4104 rc = GPG_ERR_EEXIST;
4105 goto fail;
4109 if (dst)
4111 xmlChar *a = xml_attribute_value (src, (xmlChar *) "_name");
4112 xmlNodePtr dup = xml_find_element (client, dst->children, (char *) a, &rc);
4114 xmlFree (a);
4115 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
4116 goto fail;
4118 rc = 0;
4120 if (dup)
4122 if (dup == src)
4124 rc = GPG_ERR_EEXIST;
4125 goto fail;
4128 if (dst == xmlDocGetRootElement (client->doc))
4130 xmlNodePtr n = src;
4131 int match = 0;
4133 while (n->parent && n->parent != dst)
4134 n = n->parent;
4136 a = xml_attribute_value (n, (xmlChar *) "_name");
4137 xmlChar *b = xml_attribute_value (src, (xmlChar *) "_name");
4139 if (xmlStrEqual (a, b))
4141 match = 1;
4142 xmlUnlinkNode (src);
4143 (void)xml_unlink_node (client, n);
4146 xmlFree (a);
4147 xmlFree (b);
4149 if (!match)
4150 (void)xml_unlink_node (client, dup);
4152 else
4153 xmlUnlinkNode (dup);
4157 if (!dst && req && req->args && *req->args)
4159 struct xml_request_s *nreq = NULL;
4160 xmlChar *name = xml_attribute_value (src, (xmlChar *) "_name");
4162 if (src->parent == xmlDocGetRootElement (client->doc)
4163 && !strcmp ((char *) name, *req->args))
4165 xmlFree (name);
4166 rc = GPG_ERR_EEXIST;
4167 goto fail;
4170 xmlFree (name);
4171 rc = xml_new_request (client, args[1], XML_CMD_STORE, &nreq);
4172 if (!rc)
4174 dst = xml_find_elements (client, nreq,
4175 xmlDocGetRootElement (nreq->doc), &rc);
4176 xml_free_request (nreq);
4179 if (rc)
4180 goto fail;
4183 xml_update_element_mtime (client, src->parent);
4184 xmlUnlinkNode (src);
4186 dst = xmlAddChildList (dst, src);
4187 if (!dst)
4188 rc = GPG_ERR_ENOMEM;
4189 else
4190 xml_update_element_mtime (client, dst->parent);
4192 fail:
4193 xml_free_request (req);
4194 strv_free (args);
4195 return rc;
4198 static gpg_error_t
4199 move_command (assuan_context_t ctx, char *line)
4201 struct client_s *client = assuan_get_pointer (ctx);
4202 gpg_error_t rc;
4203 struct argv_s *args[] = {
4204 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
4205 NULL
4208 rc = parse_options (&line, args, client, 1);
4209 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
4210 rc = GPG_ERR_SYNTAX;
4211 if (rc)
4212 return send_error (ctx, rc);
4214 rc = copy_on_write (client);
4215 if (rc)
4216 return send_error (ctx, rc);
4218 if (client->opts & OPT_INQUIRE)
4220 unsigned char *result;
4221 size_t len;
4223 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
4224 if (rc)
4225 return send_error (ctx, rc);
4227 pthread_cleanup_push ((void *)xfree, result);
4228 rc = do_move (ctx, (char *)result);
4229 pthread_cleanup_pop (1);
4231 else
4232 rc = do_move (ctx, line);
4234 return send_error (ctx, rc);
4237 static int
4238 sort_files (const void *arg1, const void *arg2)
4240 char *const *a = arg1;
4241 char *const *b = arg2;
4243 return strcmp (*a, *b);
4246 static gpg_error_t
4247 ls_command (assuan_context_t ctx, char *line)
4249 struct client_s *client = assuan_get_pointer (ctx);
4250 gpg_error_t rc;
4251 char *tmp;
4252 char *dir;
4253 DIR *d;
4254 char *list = NULL;
4255 char **v = NULL;
4256 struct dirent *cur = NULL;
4257 struct argv_s *args[] = {
4258 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_opt_verbose},
4259 NULL
4262 rc = parse_options (&line, args, client, 0);
4263 if (rc)
4264 return send_error (ctx, rc);
4266 tmp = str_asprintf ("%s/data", homedir);
4267 dir = expand_homedir (tmp);
4268 xfree (tmp);
4269 if (!dir)
4270 return send_error (ctx, GPG_ERR_ENOMEM);
4272 d = opendir (dir);
4273 rc = gpg_error_from_errno (errno);
4275 if (!d)
4277 xfree (dir);
4278 return send_error (ctx, rc);
4281 pthread_cleanup_push ((void *)closedir, d);
4282 xfree (dir);
4283 rc = 0;
4285 while ((cur = readdir (d)))
4287 char **vtmp;
4288 struct stat st;
4290 rc = open_check_file (cur->d_name, NULL, &st, 1);
4291 if (rc)
4292 continue;
4294 if (client->opts & OPT_VERBOSE)
4295 tmp = str_asprintf ("%s %lu.%lu %lu.%lu %lu.%lu", cur->d_name,
4296 st.st_atim.tv_sec, st.st_atim.tv_nsec,
4297 st.st_mtim.tv_sec, st.st_mtim.tv_nsec,
4298 st.st_ctim.tv_sec, st.st_ctim.tv_nsec);
4299 else
4300 tmp = str_dup (cur->d_name);
4302 if (!tmp)
4304 rc = GPG_ERR_ENOMEM;
4305 break;
4308 vtmp = strv_cat (v, tmp);
4309 if (!vtmp)
4311 xfree (tmp);
4312 rc = GPG_ERR_ENOMEM;
4313 break;
4316 v = vtmp;
4319 pthread_cleanup_pop (1); // closedir (d)
4321 if (rc && rc != GPG_ERR_ENODEV)
4323 strv_free (v);
4324 return send_error (ctx, rc);
4327 rc = 0;
4328 if (v && *v)
4330 unsigned n, t = strv_length (v);
4332 qsort (v, t, sizeof (char **), sort_files);
4334 for (n = 0; n < t; n++)
4336 tmp = str_asprintf ("%s%s\n", list ? list : "", v[n]);
4337 if (!tmp)
4339 xfree (list);
4340 rc = GPG_ERR_ENOMEM;
4341 break;
4344 xfree (list);
4345 list = tmp;
4349 strv_free (v);
4350 if (rc || !list)
4351 return send_error (ctx, rc ? rc : GPG_ERR_NO_DATA);
4353 list[strlen (list) - 1] = 0;
4354 pthread_cleanup_push (xfree, list);
4355 rc = xfer_data (ctx, list, strlen (list));
4356 pthread_cleanup_pop (1);
4357 return send_error (ctx, rc);
4360 /* Run all commands in the command list 'head'. The return code isn't
4361 * considered at all for a command. It is stored in the list and later sent to
4362 * the client. */
4363 static gpg_error_t
4364 dispatch_bulk_commands (struct client_s *client, struct sexp_s **list)
4366 unsigned i;
4367 unsigned id = 0;
4368 gpg_error_t rc = 0;
4370 for (i = 0; list && list[i];)
4372 struct bulk_cmd_s *cur = list[i]->user;
4374 if (!strcmp (list[i]->tag, "command"))
4376 i++;
4377 continue;
4379 else if (!strcmp (list[i]->tag, "id"))
4381 id = i++;
4382 continue;
4385 if ((client->flags & FLAG_NO_PINENTRY) && cur->cmd->inquire)
4387 rc = send_status (client->ctx, STATUS_BULK, "BEGIN %s",
4388 list[id]->data);
4389 if (rc)
4390 break;
4393 client->bulk_p = cur;
4394 cur->ran = 1;
4396 cur->rc = command_startup (client->ctx, cur->cmd->name);
4397 if (!cur->rc)
4398 cur->rc = cur->cmd->handler (client->ctx, list[i]->data);
4400 if ((client->flags & FLAG_NO_PINENTRY) && cur->cmd->inquire)
4402 (void)send_status (client->ctx, STATUS_BULK, "END %s",
4403 list[id]->data);
4405 command_finalize (client->ctx, cur->rc);
4406 cur->rc = cur->rc ? cur->rc : client->last_rc;
4408 do {
4409 if (list[i+1] && !strcmp (list[i+1]->tag, "rc"))
4411 gpg_error_t erc = 0;
4412 int match = 0;
4414 if (list[i+1]->data)
4416 char **rcs = str_split (list[i+1]->data, "|", 0);
4417 char **p;
4419 for (p = rcs; p && *p; p++)
4421 erc = strtoul (*p, NULL, 10);
4422 if (erc == cur->rc)
4424 match = 1;
4425 break;
4429 strv_free (rcs);
4432 if (!match)
4434 i++;
4435 continue;
4438 rc = dispatch_bulk_commands (client, list[++i]->next);
4440 else
4442 i++;
4443 break;
4445 } while (1);
4448 return rc;
4451 static gpg_error_t
4452 bulk_command (assuan_context_t ctx, char *line)
4454 struct client_s *client = assuan_get_pointer (ctx);
4455 gpg_error_t rc = 0;
4456 unsigned char *result, *p;
4457 size_t len;
4458 struct sexp_s **sexp = NULL;
4459 struct argv_s *args[] = {
4460 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
4461 NULL
4464 rc = parse_options (&line, args, client, 1);
4465 if (rc)
4466 return send_error (ctx, rc);
4468 if ((client->opts & OPT_INQUIRE) && line && *line)
4469 rc = GPG_ERR_SYNTAX;
4470 else if (!(client->opts & OPT_INQUIRE) && (!line || !*line))
4471 rc = GPG_ERR_SYNTAX;
4473 if (rc)
4474 return send_error (ctx, rc);
4476 if (client->opts & OPT_INQUIRE)
4478 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
4479 if (rc)
4480 return send_error (ctx, rc);
4481 p = result;
4483 else
4485 p = (unsigned char *)line;
4486 len = line && *line ? strlen (line) : 0;
4489 if (!len)
4490 return send_error (ctx, GPG_ERR_SYNTAX);
4492 rc = bulk_parse_commands (&sexp, (const char *)p, command_table);
4493 if (client->opts & OPT_INQUIRE)
4494 xfree (result);
4496 if (rc)
4497 return send_error (ctx, rc);
4499 pthread_cleanup_push ((void *)bulk_free_list, sexp);
4500 rc = dispatch_bulk_commands (client, sexp);
4501 pthread_cleanup_pop (0);
4502 if (!rc)
4503 rc = bulk_build_result (sexp, (char **)&result);
4505 bulk_free_list (sexp);
4507 if (!rc)
4509 pthread_cleanup_push ((void *)xfree, result);
4510 rc = xfer_data (ctx, (char *)result, strlen ((char *)result));
4511 pthread_cleanup_pop (1);
4514 return send_error (ctx, rc);
4517 static gpg_error_t
4518 nop_command (assuan_context_t ctx, char *line)
4520 return send_error (ctx, 0);
4523 static gpg_error_t
4524 bye_notify (assuan_context_t ctx, char *line)
4526 struct client_s *cl = assuan_get_pointer (ctx);
4527 gpg_error_t ret = 0;
4529 (void)line;
4530 update_client_state (cl, CLIENT_STATE_DISCON);
4532 #ifdef WITH_GNUTLS
4533 cl->disco = 1;
4534 if (cl->thd->remote)
4536 int rc;
4540 struct timeval tv = { 0, 50000 };
4542 rc = gnutls_bye (cl->thd->tls->ses, GNUTLS_SHUT_WR);
4543 if (rc == GNUTLS_E_AGAIN)
4544 select (0, NULL, NULL, NULL, &tv);
4546 while (rc == GNUTLS_E_AGAIN);
4548 #endif
4550 /* This will let assuan_process_next() return. */
4551 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
4553 cl->last_rc = gpg_error_from_errno (errno);
4554 ret = cl->last_rc;
4557 cl->last_rc = 0; // BYE command result
4558 return ret;
4561 static gpg_error_t
4562 reset_notify (assuan_context_t ctx, char *line)
4564 struct client_s *client = assuan_get_pointer (ctx);
4566 (void)line;
4567 if (client)
4568 reset_client (client);
4570 return 0;
4574 * This is called before every Assuan command.
4576 static gpg_error_t
4577 command_startup (assuan_context_t ctx, const char *name)
4579 struct client_s *client = assuan_get_pointer (ctx);
4580 gpg_error_t rc = 0;
4581 struct command_table_s *cmd = NULL;
4583 log_write2 ("command='%s'", name);
4584 client->last_rc = client->opts = 0;
4586 for (int i = 0; command_table[i]; i++)
4588 if (!strcasecmp (name, command_table[i]->name))
4590 if (command_table[i]->ignore_startup)
4591 goto send_state;
4593 cmd = command_table[i];
4594 break;
4598 if (!cmd)
4599 return GPG_ERR_UNKNOWN_COMMAND;
4601 client->last_rc = rc = gpg_error (file_modified (client, cmd));
4603 send_state:
4604 if (!client->bulk_p && !rc)
4605 update_client_state (client, CLIENT_STATE_COMMAND);
4607 return rc;
4611 * This is called after every Assuan command.
4613 static void
4614 command_finalize (assuan_context_t ctx, gpg_error_t rc)
4616 struct client_s *client = assuan_get_pointer (ctx);
4618 // Needed for the STORE command. Really should be an OPT_.
4619 client->flags &= ~(FLAG_NO_INHERIT_ACL);
4621 if (!(client->flags & FLAG_LOCK_CMD))
4622 unlock_file_mutex (client, 0);
4624 unlock_flock (&client->flock_fd);
4625 log_write2 (_("command completed: rc=%u"), rc ? rc : client->last_rc);
4627 #ifdef WITH_GNUTLS
4628 client->thd->buffer_timeout = client->thd->last_buffer_size = 0;
4629 #endif
4631 if (!client->bulk_p && client->thd->state != CLIENT_STATE_DISCON)
4632 update_client_state (client, CLIENT_STATE_IDLE);
4634 client->bulk_p = NULL;
4637 static gpg_error_t
4638 parse_help_opt_html (void *data, void *value)
4640 struct client_s *client = data;
4642 (void) value;
4643 client->opts |= OPT_HTML;
4644 return 0;
4647 static gpg_error_t
4648 help_command (assuan_context_t ctx, char *line)
4650 gpg_error_t rc;
4651 int i;
4652 struct client_s *client = assuan_get_pointer (ctx);
4653 struct argv_s *args[] = {
4654 &(struct argv_s) {"html", OPTION_TYPE_NOARG, parse_help_opt_html},
4655 NULL
4658 rc = parse_options (&line, args, client, 1);
4659 if (rc)
4660 return send_error (ctx, rc);
4662 if (!line || !*line)
4664 char *tmp;
4665 char *help = str_dup (_("Usage: HELP [--html] [<COMMAND>]\n"
4666 "For commands that take an element path as an argument, each element is "
4667 "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."
4668 "@*@*COMMANDS:"));
4670 for (i = 0; command_table[i]; i++)
4672 if (!command_table[i]->help)
4673 continue;
4675 /* @npxref{} won't put a "See " or "see " in front of the command.
4676 * It's not a texinfo command but needed for --html. */
4677 tmp = str_asprintf ("%s %s%s%s", help,
4678 client->opts & OPT_HTML ? "@npxref{" : "",
4679 command_table[i]->name,
4680 client->opts & OPT_HTML ? "}" : "");
4681 xfree (help);
4682 help = tmp;
4685 tmp = strip_texi_and_wrap (help, client->opts & OPT_HTML);
4686 xfree (help);
4687 pthread_cleanup_push ((void *)xfree, tmp);
4688 rc = xfer_data (ctx, tmp, strlen (tmp));
4689 pthread_cleanup_pop (1);
4690 return send_error (ctx, rc);
4693 for (i = 0; command_table[i]; i++)
4695 if (!strcasecmp (line, command_table[i]->name))
4697 char *help, *tmp;
4699 if (!command_table[i]->help)
4700 break;
4702 help = strip_texi_and_wrap (command_table[i]->help,
4703 client->opts & OPT_HTML);
4704 tmp = str_asprintf ("%s%s",
4705 (client->opts & OPT_HTML) ? "" : _("Usage: "),
4706 help);
4707 xfree (help);
4708 pthread_cleanup_push ((void *)xfree, tmp);
4709 rc = xfer_data (ctx, tmp, strlen (tmp));
4710 pthread_cleanup_pop (1);
4711 return send_error (ctx, rc);
4715 return send_error (ctx, GPG_ERR_INV_NAME);
4718 static void
4719 new_command (const char *name, int inquire, int ignore, int unlock,
4720 int flock_type, gpg_error_t (*handler) (assuan_context_t, char *),
4721 const char *help)
4723 int i = 0;
4724 struct command_table_s **tmp;
4726 if (command_table)
4727 for (i = 0; command_table[i]; i++);
4729 tmp = xrealloc (command_table, (i + 2) * sizeof (struct command_table_s *));
4730 assert (tmp);
4731 command_table = tmp;
4732 command_table[i] = xcalloc (1, sizeof (struct command_table_s));
4733 command_table[i]->name = name;
4734 command_table[i]->inquire = inquire;
4735 command_table[i]->handler = handler;
4736 command_table[i]->ignore_startup = ignore;
4737 command_table[i]->unlock = unlock;
4738 command_table[i]->flock_type = flock_type;
4739 command_table[i++]->help = help;
4740 command_table[i] = NULL;
4743 void
4744 deinit_commands ()
4746 int i;
4748 for (i = 0; command_table[i]; i++)
4749 xfree (command_table[i]);
4751 xfree (command_table);
4754 static int
4755 sort_commands (const void *arg1, const void *arg2)
4757 struct command_table_s *const *a = arg1;
4758 struct command_table_s *const *b = arg2;
4760 if (!*a || !*b)
4761 return 0;
4762 else if (*a && !*b)
4763 return 1;
4764 else if (!*a && *b)
4765 return -1;
4767 return strcmp ((*a)->name, (*b)->name);
4770 static gpg_error_t
4771 passwd_command (assuan_context_t ctx, char *line)
4773 struct client_s *client = assuan_get_pointer (ctx);
4774 gpg_error_t rc;
4776 (void)line;
4777 rc = peer_is_invoker (client);
4778 if (rc)
4779 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
4781 if (client->flags & FLAG_NEW)
4782 return send_error (ctx, GPG_ERR_INV_STATE);
4784 client->crypto->keyfile = config_get_string (client->filename,
4785 "passphrase_file");
4786 rc = crypto_init_ctx (client->crypto, client->flags & FLAG_NO_PINENTRY,
4787 client->crypto->keyfile);
4788 if (!rc)
4789 rc = crypto_passwd (client, client->crypto);
4791 crypto_free_non_keys (client->crypto);
4792 return send_error (ctx, rc);
4795 static gpg_error_t
4796 parse_opt_data (void *data, void *value)
4798 struct client_s *client = data;
4800 (void) value;
4801 client->opts |= OPT_DATA;
4802 return 0;
4805 static gpg_error_t
4806 send_client_list (assuan_context_t ctx)
4808 struct client_s *client = assuan_get_pointer (ctx);
4809 gpg_error_t rc = 0;
4811 if (client->opts & OPT_VERBOSE)
4813 unsigned i, t;
4814 char **list = NULL;
4815 char *line;
4817 MUTEX_LOCK (&cn_mutex);
4818 pthread_cleanup_push ((void *)release_mutex_cb, &cn_mutex);
4819 t = slist_length (cn_thread_list);
4821 for (i = 0; i < t; i++)
4823 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
4824 char *tmp;
4826 if (thd->state == CLIENT_STATE_UNKNOWN)
4827 continue;
4829 tmp = build_client_info_line (thd, 0);
4830 if (tmp)
4832 char **l = strv_cat (list, tmp);
4833 if (!l)
4834 rc = GPG_ERR_ENOMEM;
4835 else
4836 list = l;
4838 else
4839 rc = GPG_ERR_ENOMEM;
4841 if (rc)
4843 strv_free (list);
4844 break;
4848 pthread_cleanup_pop (1);
4849 if (rc)
4850 return rc;
4852 line = strv_join ("\n", list);
4853 strv_free (list);
4854 pthread_cleanup_push ((void *)xfree, line);
4855 rc = xfer_data (ctx, line, strlen (line));
4856 pthread_cleanup_pop (1);
4857 return rc;
4860 if (client->opts & OPT_DATA)
4862 char buf[ASSUAN_LINELENGTH];
4864 MUTEX_LOCK (&cn_mutex);
4865 snprintf (buf, sizeof (buf), "%u", slist_length (cn_thread_list));
4866 MUTEX_UNLOCK (&cn_mutex);
4867 rc = xfer_data (ctx, buf, strlen (buf));
4869 else
4870 rc = send_status (ctx, STATUS_CLIENTS, NULL);
4872 return rc;
4875 static gpg_error_t
4876 getinfo_command (assuan_context_t ctx, char *line)
4878 struct client_s *client = assuan_get_pointer (ctx);
4879 gpg_error_t rc;
4880 char buf[ASSUAN_LINELENGTH];
4881 struct argv_s *args[] = {
4882 &(struct argv_s) {"data", OPTION_TYPE_NOARG, parse_opt_data},
4883 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_opt_verbose},
4884 NULL
4887 rc = parse_options (&line, args, client, 1);
4888 if (rc)
4889 return send_error (ctx, rc);
4891 if (!line || !*line)
4892 return send_error (ctx, GPG_ERR_SYNTAX);
4894 if (!strcasecmp (line, "clients"))
4896 rc = send_client_list (ctx);
4898 else if (!strcasecmp (line, "cache"))
4900 if (client->opts & OPT_DATA)
4902 snprintf (buf, sizeof (buf), "%u", cache_file_count ());
4903 rc = xfer_data (ctx, buf, strlen (buf));
4905 else
4906 rc = send_status (ctx, STATUS_CACHE, NULL);
4908 else if (!strcasecmp (line, "pid"))
4910 long pid = getpid ();
4912 snprintf (buf, sizeof (buf), "%li", pid);
4913 rc = xfer_data (ctx, buf, strlen (buf));
4915 else if (!strcasecmp (line, "version"))
4917 char *tmp = str_asprintf ("0x%06x %s", VERSION_HEX,
4918 #ifdef WITH_GNUTLS
4919 "GNUTLS "
4920 #endif
4921 #ifdef WITH_LIBACL
4922 "ACL "
4923 #endif
4924 "");
4925 pthread_cleanup_push (xfree, tmp);
4926 rc = xfer_data (ctx, tmp, strlen (tmp));
4927 pthread_cleanup_pop (1);
4929 else if (!strcasecmp (line, "last_error"))
4931 if (client->last_error)
4932 rc = xfer_data (ctx, client->last_error, strlen (client->last_error));
4933 else
4934 rc = GPG_ERR_NO_DATA;
4936 else if (!strcasecmp (line, "user"))
4938 char *user = NULL;
4940 #ifdef WITH_GNUTLS
4941 if (client->thd->remote)
4942 user = str_asprintf ("#%s", client->thd->tls->fp);
4943 else
4944 user = get_username (client->thd->peer->uid);
4945 #else
4946 user = get_username (client->thd->peer->uid);
4947 #endif
4948 if (user)
4950 pthread_cleanup_push ((void *)xfree, user);
4951 rc = xfer_data (ctx, user, strlen (user));
4952 pthread_cleanup_pop (1);
4954 else
4955 rc = GPG_ERR_NO_DATA;
4957 else
4958 rc = gpg_error (GPG_ERR_SYNTAX);
4960 return send_error (ctx, rc);
4963 static gpg_error_t
4964 parse_opt_secret (void *data, void *value)
4966 struct client_s *client = data;
4968 (void) value;
4969 client->opts |= OPT_SECRET;
4970 return 0;
4973 static gpg_error_t
4974 parse_keyinfo_opt_learn (void *data, void *value)
4976 struct client_s *client = data;
4978 (void)value;
4979 client->opts |= OPT_KEYINFO_LEARN;
4980 return 0;
4983 static gpg_error_t
4984 keyinfo_command (assuan_context_t ctx, char *line)
4986 struct client_s *client = assuan_get_pointer (ctx);
4987 gpg_error_t rc = 0;
4988 char **keys = NULL, **p = NULL;
4989 int sym = 0;
4990 struct argv_s *args[] = {
4991 &(struct argv_s) {"learn", OPTION_TYPE_NOARG, parse_keyinfo_opt_learn},
4992 NULL
4995 rc = parse_options (&line, args, client, 0);
4996 if (rc)
4997 return send_error (ctx, rc);
4999 if (line && *line)
5000 return send_error (ctx, GPG_ERR_SYNTAX);
5002 if (!(client->flags & FLAG_OPEN))
5003 return send_error (ctx, GPG_ERR_INV_STATE);
5005 if (client->opts & OPT_KEYINFO_LEARN)
5007 rc = cache_agent_command ("LEARN");
5008 return send_error (ctx, rc);
5011 if (client->flags & FLAG_NEW)
5012 return send_error (ctx, GPG_ERR_NO_DATA);
5014 rc = lock_flock (ctx, client->filename, FLOCK_TYPE_SH, &client->flock_fd);
5015 if (rc)
5016 return send_error (ctx, rc);
5018 rc = crypto_is_symmetric (client->filename);
5019 unlock_flock (&client->flock_fd);
5020 if (!rc)
5021 sym = 1;
5022 else if (rc != GPG_ERR_BAD_DATA)
5023 return send_error (ctx, rc);
5025 rc = 0;
5026 if (!sym)
5028 p = strv_catv (keys, client->crypto->pubkey);
5029 if (!p)
5030 rc = GPG_ERR_ENOMEM;
5031 else
5032 keys = p;
5035 if (!rc && client->crypto->sigkey)
5037 if (!strv_printf (&keys, "S%s", client->crypto->sigkey))
5039 strv_free (keys);
5040 return send_error (ctx, GPG_ERR_ENOMEM);
5044 if (!rc)
5046 if (keys)
5048 line = strv_join ("\n", keys);
5049 strv_free (keys);
5050 pthread_cleanup_push ((void *)xfree, line);
5051 if (line)
5052 rc = xfer_data (ctx, line, strlen (line));
5053 else
5054 rc = GPG_ERR_ENOMEM;
5056 pthread_cleanup_pop (1);
5058 else
5059 rc = GPG_ERR_NO_DATA;
5061 else
5062 strv_free (keys);
5064 return send_error (ctx, rc);
5067 static gpg_error_t
5068 deletekey_command (assuan_context_t ctx, char *line)
5070 gpg_error_t rc;
5071 struct client_s *client = assuan_get_pointer (ctx);
5072 struct crypto_s *crypto = NULL;
5073 char *keys[] = { NULL, NULL };
5074 gpgme_key_t *result;
5075 char **p = NULL;
5077 if (!(client->flags & FLAG_OPEN))
5078 return send_error (ctx, GPG_ERR_INV_STATE);
5080 rc = peer_is_invoker (client);
5081 if (rc)
5082 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
5084 if (client->flags & FLAG_NO_PINENTRY)
5085 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
5087 if (!*line)
5088 return send_error (ctx, GPG_ERR_SYNTAX);
5090 rc = crypto_keyid_to_16b_once (line);
5091 if (rc)
5092 return send_error (ctx, rc);
5094 for (p = client->crypto->pubkey; p && *p; p++)
5096 if (!strcmp (*p, line))
5097 break;
5100 if (!p)
5102 if (client->crypto->sigkey && strcmp (client->crypto->sigkey, line))
5103 return send_error (ctx, GPG_ERR_FORBIDDEN);
5104 else if (!client->crypto->sigkey)
5105 return send_error (ctx, GPG_ERR_NO_SECKEY);
5108 rc = crypto_init (&crypto, client->ctx, client->filename,
5109 client->flags & FLAG_NO_PINENTRY, NULL);
5110 if (rc)
5111 return send_error (ctx, rc);
5113 pthread_cleanup_push ((void *)crypto_free, crypto);
5114 keys[0] = line;
5115 rc = crypto_list_keys (crypto, keys, 1, &result);
5116 if (!rc)
5118 pthread_cleanup_push ((void *)crypto_free_key_list, result);
5119 rc = crypto_delete_key (client, crypto, *result, 1);
5120 pthread_cleanup_pop (1);
5123 pthread_cleanup_pop (1);
5124 return send_error (ctx, rc);
5127 static gpg_error_t
5128 kill_command (assuan_context_t ctx, char *line)
5130 struct client_s *client = assuan_get_pointer (ctx);
5131 gpg_error_t rc;
5132 unsigned i, t;
5134 if (!line || !*line)
5135 return send_error (ctx, GPG_ERR_SYNTAX);
5137 MUTEX_LOCK (&cn_mutex);
5138 pthread_cleanup_push ((void *)release_mutex_cb, &cn_mutex);
5139 t = slist_length (cn_thread_list);
5140 rc = GPG_ERR_ESRCH;
5142 for (i = 0; i < t; i++)
5144 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
5145 char *tmp = str_asprintf ("%p", thd->tid);
5147 if (strcmp (line, tmp))
5149 xfree (tmp);
5150 continue;
5153 xfree (tmp);
5154 rc = peer_is_invoker (client);
5155 if (!rc)
5157 #ifdef HAVE_PTHREAD_CANCEL
5158 pthread_cancel (thd->tid);
5159 #else
5160 pthread_kill (thd->tid, SIGUSR2);
5161 #endif
5162 break;
5164 else if (rc == GPG_ERR_EACCES)
5165 rc = GPG_ERR_FORBIDDEN;
5166 else if (rc)
5167 break;
5169 if (config_get_boolean ("global", "strict_kill"))
5170 break;
5172 #ifdef WITH_GNUTLS
5173 if (client->thd->remote && thd->remote)
5175 if (!thd->tls || !thd->tls->fp)
5177 rc = GPG_ERR_INV_STATE;
5178 break;
5180 if (!strcmp (client->thd->tls->fp, thd->tls->fp))
5182 #ifdef HAVE_PTHREAD_CANCEL
5183 pthread_cancel (thd->tid);
5184 #else
5185 pthread_kill (thd->tid, SIGUSR2);
5186 #endif
5187 rc = 0;
5188 break;
5191 else if (!client->thd->remote && !thd->remote)
5192 #endif
5194 if (client->thd->peer->uid == thd->peer->uid)
5196 #ifdef HAVE_PTHREAD_CANCEL
5197 pthread_cancel (thd->tid);
5198 #else
5199 pthread_kill (thd->tid, SIGUSR2);
5200 #endif
5201 rc = 0;
5204 break;
5207 pthread_cleanup_pop (1);
5208 return send_error (ctx, rc);
5211 static gpg_error_t
5212 listkeys_command (assuan_context_t ctx, char *line)
5214 struct client_s *client = assuan_get_pointer (ctx);
5215 struct crypto_s *crypto = NULL;
5216 char **pattern = NULL;
5217 gpgme_key_t *keys = NULL;
5218 char **result = NULL;
5219 gpg_error_t rc;
5220 struct argv_s *args[] = {
5221 &(struct argv_s) {"secret-only", OPTION_TYPE_NOARG, parse_opt_secret},
5222 NULL
5225 rc = parse_options (&line, args, client, 1);
5226 if (rc)
5227 return send_error (ctx, rc);
5229 rc = crypto_init (&crypto, client->ctx, client->filename,
5230 client->flags & FLAG_NO_PINENTRY, NULL);
5231 if (rc)
5232 return send_error (ctx, rc);
5234 pthread_cleanup_push ((void *)crypto_free, crypto);
5235 if (line)
5236 pattern = str_split (line, ",", 0);
5237 pthread_cleanup_push ((void *)(void *)strv_free, pattern);
5238 rc = crypto_list_keys (crypto, pattern, client->opts & OPT_SECRET,
5239 &keys);
5240 pthread_cleanup_pop (1);
5241 pthread_cleanup_pop (1);
5242 if (!rc)
5244 int i;
5246 for (i = 0; keys[i]; i++)
5248 char *p = crypto_key_info (keys[i]);
5249 char **r;
5251 if (!p)
5253 rc = GPG_ERR_ENOMEM;
5254 break;
5257 r = strv_cat (result, p);
5258 if (!r)
5260 rc = GPG_ERR_ENOMEM;
5261 break;
5264 result = r;
5267 if (!i)
5268 rc = GPG_ERR_NO_DATA;
5270 crypto_free_key_list (keys);
5273 if (!rc)
5275 line = strv_join ("\n", result);
5276 strv_free (result);
5277 pthread_cleanup_push ((void *)xfree, line);
5278 if (!line)
5279 rc = GPG_ERR_ENOMEM;
5280 else
5281 rc = xfer_data (ctx, line, strlen (line));
5283 pthread_cleanup_pop (1);
5285 else
5286 strv_free (result);
5288 if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
5289 || gpg_err_code (rc) == GPG_ERR_NO_SECKEY)
5290 rc = GPG_ERR_NO_DATA;
5292 return send_error (ctx, rc);
5295 void
5296 init_commands ()
5298 /* !BEGIN-HELP-TEXT!
5300 * This comment is used as a marker to generate the offline documentation
5301 * found in doc/pwmd.info. The indentation needs to be kept for the awk
5302 * script to determine where commands begin and end.
5304 new_command("HELP", 0, 1, 1, 0, help_command, _(
5305 "HELP [--html] [<COMMAND>]\n" /* Showing available commands. */
5306 "Show available commands or command specific help text."
5307 "@*@*"
5308 "The @option{--html} option will output the help text in HTML format."
5311 new_command("DELETEKEY", 0, 1, 1, FLOCK_TYPE_SH|FLOCK_TYPE_KEEP, deletekey_command, _(
5312 "DELETEKEY <keyid>\n" /* Deleting a key from the key ring. */
5313 "Deletes the public and secret key associated with key @var{keyid} from the "
5314 "keyring. The @var{keyid} must be one associated with the currently opened "
5315 "data file. "
5316 "Note that no confirmation occurs. Also note that when the key is deleted, "
5317 "the current or other data files using this key will no longer be able to be "
5318 "opened."
5321 new_command("KILL", 0, 1, 0, 0, kill_command, _(
5322 "KILL <thread_id>\n" /* Terminating another client. */
5323 "Terminates the client identified by @var{thread_id} and releases any file "
5324 "lock or other resources it has held. See @code{GETINFO} (@pxref{GETINFO}) "
5325 "for details about listing connected clients. An @code{invoking_user} "
5326 "(@pxref{Configuration}) may kill any client while others may only kill "
5327 "clients of the same @code{UID} or @abbr{TLS} fingerprint."
5330 new_command("LISTKEYS", 0, 1, 0, 0, listkeys_command, _(
5331 "LISTKEYS [--secret-only] [pattern[,<pattern>]]\n" /* Listing keys in the key ring. */
5332 "Returns a new line separated list of key information matching a comma "
5333 "separated list of @var{pattern}'s. When option @option{--secret-only} is "
5334 "specified, only keys matching @var{pattern} that also have a secret key "
5335 "available will be returned."
5338 new_command("KEYINFO", 0, 1, 0, 0, keyinfo_command, _(
5339 "KEYINFO [--learn]\n" /* Showing keys used for the current data file. */
5340 "Returns a new line separated list of key ID's that the currently opened "
5341 "data file has recipients and signers for. If the key is a signing key it "
5342 "will be prefixed with an @code{S}. If the file is a new one, or has no "
5343 "signers in the case of being symmetrically encrypted, the error code "
5344 "@code{GPG_ERR_NO_DATA} is returned."
5345 "@*@*"
5346 "When the @option{--learn} option is passed, keys on a smartcard will be "
5347 "imported."
5350 new_command("GETINFO", 0, 1, 1, 0, getinfo_command, _(
5351 "GETINFO [--data] [--verbose] CACHE | CLIENTS | PID | USER | LAST_ERROR | VERSION\n" /* Obtaining server and client information. */
5352 "Get server and other information. The information is returned via a status "
5353 "message (@pxref{Status Messages}) unless otherwise noted or @option{--data} "
5354 "is specified."
5355 "@*@*"
5356 "@var{CACHE} returns the number of cached documents."
5357 "@*@*"
5358 "@var{CLIENTS} returns the number of "
5359 "connected clients via a status message or a list of connected clients when "
5360 "the @option{--verbose} parameter is used (implies @option{--data}). A "
5361 "verbose line of a client list contains "
5362 "space delimited "
5363 "fields: the thread ID, client name, opened file (@code{/} if none opened), "
5364 "IP address if remote, file lock status, whether the current client is self "
5365 "or not, client state (see below), "
5366 "user ID or TLS fingerprint of the connected client, username if the "
5367 "client is a local one else @code{-}, and finally the time stamp of when the "
5368 "client connected."
5369 "@*@*"
5370 "Client state @code{0} is an unknown client state, state @code{1} indicates "
5371 "the client has connected but hasn't completed initializing, state @code{2} "
5372 "indicates that the client is idle, state @code{3} means the "
5373 "client is in a command and state @code{4} means the client is disconnecting. "
5374 "@*@*"
5375 "@var{PID} returns the process ID number of the server via a data response."
5376 "@*@*"
5377 "@var{VERSION} returns the server version number and compile-time features "
5378 "via a data response with each being space delimited."
5379 "@*@*"
5380 "@var{LAST_ERROR} returns a detailed description of the last failed command "
5381 "via a data response, when available."
5382 "@*@*"
5383 "@var{USER} returns the username or @abbr{TLS} hash of the connected client "
5384 "via a data response."
5387 new_command("PASSWD", 1, 0, 0, FLOCK_TYPE_EX|FLOCK_TYPE_KEEP, passwd_command, _(
5388 "PASSWD\n" /* Changing the passphrase for a key. */
5389 "Changes the passphrase of the secret key required to open the current "
5390 "data file. If the data file is symmetrically encrypted the error "
5391 "@code{GPG_ERR_NOT_SUPPORTED} is returned. When symmetrically encrypted "
5392 "the @code{SAVE} command (@pxref{SAVE}) should be used instead to prevent "
5393 "this command saving any unwanted changes to the @abbr{XML} document."
5394 "@*@*"
5395 "Note that when the current data file has been either encrypted or signed "
5396 "with a key stored on a smartcard this command will return an error. In this "
5397 "case you should instead use @command{gpg --card-edit} to change the "
5398 "pin of the smartcard or @command{gpg --edit-key} to change the passphrase "
5399 "of the key used to sign or encrypt the data file."
5400 "@*@*"
5401 "This command is not available to non-invoking clients "
5402 "(@pxref{Access Control})."
5405 new_command("OPEN", 1, 1, 1, FLOCK_TYPE_SH|FLOCK_TYPE_KEEP, open_command, _(
5406 "OPEN [--lock] <filename>\n" /* Opening a data file. */
5407 "Opens @var{filename}. When the @var{filename} is not found on the "
5408 "file-system then a new in-memory document will be created. If the file is "
5409 "found, it is looked for in the file cache and when found no passphrase will "
5410 "be required to open it. When not cached, @cite{pinentry(1)} will be used to "
5411 "retrieve the passphrase for decryption unless @option{disable-pinentry} "
5412 "(@pxref{OPTION}) was specified in which case @command{pwmd} will "
5413 "@emph{INQUIRE} the client for the passphrase. Note than when configuration "
5414 "option @option{strict_open} is enabled and the client is not an "
5415 "@option{invoking_user}, an error will be returned when the data file does "
5416 "not exist."
5417 "@*@*"
5418 "When the @option{--lock} option is passed then the file mutex will be "
5419 "locked as if the @code{LOCK} command (@pxref{LOCK}) had been sent after the "
5420 "file had been opened."
5423 new_command("GENKEY", 1, 1, 1, 0, genkey_command, _(
5424 "GENKEY --subkey-of=fpr | --userid=\"str\" [--no-expire | --expire=N] [--algo=\"str\"] [--no-passphrase] [--usage=\"default|sign|encrypt\"]\n" /* Generating a new key. */
5425 "Generates a new key based on option arguments. One of "
5426 "@option{--subkey-of} or @option{--userid} is "
5427 "required. The @option{--subkey-of} option will generate a subkey for the key "
5428 "of the specified fingerprint."
5431 new_command("SAVE", 1, 0, 0, FLOCK_TYPE_EX|FLOCK_TYPE_KEEP, save_command, _(
5432 "SAVE [--sign-keyid=[<fpr>]] [--symmetric | --keyid=<fpr>[,..] | --inquire-keyid]\n" /* Saving document changes to disk. */
5433 "Writes the in-memory @abbr{XML} document to disk. The file written to is the "
5434 "file that was opened when using the @code{OPEN} command (@pxref{OPEN})."
5435 "@*@*"
5436 "If the file is a new one one of @option{--symmetric}, @option{--keyid} or"
5437 "@option{--inquire-keyid} is required. When not @option{--symmetric} the "
5438 "option @option{--sign-keyid} is also required but optional otherwise."
5439 "@*@*"
5440 "You can encrypt the data file to a recipient other than the one that it "
5441 "was originally encrypted with by passing the @option{--keyid} or "
5442 "@option{--inquire-keyid} option with a comma separated list of "
5443 "public encryption key fingerprints as its argument. Use the "
5444 "@command{LISTKEYS} command (@pxref{LISTKEYS}) to show key information by "
5445 "pattern. The @option{--sign-keyid} option may also be used to sign the data "
5446 "file with an alternate key by specifying the fingerprint of a signing key. "
5447 "Only one signing key is supported unlike the @option{--keyid} option. "
5448 "A passphrase to decrypt the data file "
5449 "will be required when one or more of the original encryption keys or signing "
5450 "key are not found in either of these two options' arguments or when the data "
5451 "file is symmetrically encrypted regardless of the @code{require_save_key} "
5452 "configuration parameter. The original encryption keys and signing key will be "
5453 "used when neither of these options are specified."
5454 "@*@*"
5455 "The @option{--keyid} and @option{--sign-keyid} options are not available "
5456 "to non-invoking clients "
5457 "(@pxref{Access Control}) when the recipients or signer do not match those "
5458 "that were used when the file was @code{OPEN}'ed."
5459 "@*@*"
5460 "The @option{--symmetric} option specifies that a new data file be "
5461 "conventionally encrypted. These types of data files do not use a recipient "
5462 "public key but may optionally be signed by using the @option{--sign-keyid} "
5463 "option. To remove the signing key from a symmtrically encrypted data file, "
5464 "leave the option value empty."
5465 "@*@*"
5466 "Note that you cannot change encryption schemes once a data file has been "
5467 "saved."
5470 new_command("ISCACHED", 0, 1, 0, 0, iscached_command, _(
5471 "ISCACHED [--lock] [--agent [--sign]] <filename>\n" /* Testing cache status. */
5472 "Determines the file cache status of the specified @var{filename}. "
5473 "The default is to test whether the filename is cached in memory. Passing "
5474 "option @option{--agent} will test the @command{gpg-agent} cache for at most "
5475 "one cached key used for opening the data file (@pxref{OPEN}). To test if "
5476 "a signing key is cached, pass @option{--sign} along with @option{--agent}. "
5477 "Both the @option{--agent} and @option{--sign} options require an opened data "
5478 "file."
5479 "@*@*"
5480 "An @emph{OK} response is returned if the specified @var{filename} is found "
5481 "in the cache. If not found in the cache but exists on the filesystem "
5482 "then @code{GPG_ERR_NO_DATA} is returned. Otherwise a filesystem error is "
5483 "returned."
5484 "@*@*"
5485 "The @option{--lock} option will lock the file mutex of @var{filename} when "
5486 "the file exists; it does not need to be opened nor cached. The lock will be "
5487 "released when the client exits or sends the @code{UNLOCK} command "
5488 "(@pxref{UNLOCK}). When this option is passed the current data file is closed."
5491 new_command("CLEARCACHE", 0, 1, 1, 0, clearcache_command, _(
5492 "CLEARCACHE [<filename>]\n" /* Removing a cache entry. */
5493 "Clears a file cache entry for all or the specified @var{filename}. Note that "
5494 "this will also clear any @command{gpg-agent} cached keys which may cause "
5495 "problems if another data file shares the same keys as @var{filename}."
5496 "@*@*"
5497 "When clearing all cache entries a permissions test is done against the "
5498 "current client based on the @var{allowed} configuration parameter in a "
5499 "@var{filename} section. Both a cache entry may be cleared and an error "
5500 "returned depending on cached data files and client permissions."
5503 new_command("CACHETIMEOUT", 0, 1, 1, 0, cachetimeout_command, _(
5504 "CACHETIMEOUT <seconds>\n" /* Setting the cache timeout. */
5505 "The time in @var{seconds} until the currently opened data file will be "
5506 "removed from the cache. @code{-1} will keep the cache entry forever, "
5507 "@code{0} will require the passphrase for each @code{OPEN} command "
5508 "(@pxref{OPEN}) or @code{SAVE} (@pxref{SAVE}) command. @xref{Configuration}, "
5509 "and the @code{cache_timeout} parameter."
5512 new_command("LIST", 0, 0, 1, 0, list_command, _(
5513 "LIST [--inquire] [--recurse] [--sexp] [element[<TAB>child[..]]]\n" /* Showing document elements. */
5514 "If no element path is given then a newline separated list of root elements "
5515 "is returned with a data response. If given, then children of the specified "
5516 "element path are returned."
5517 "@*@*"
5518 "Each element path "
5519 "returned will have zero or more flags appened to it. These flags are "
5520 "delimited from the element path by a single space character. A flag itself "
5521 "is a single character. Flag @code{P} indicates that access to the element "
5522 "is denied. Flag @code{+} indicates that there are child nodes of "
5523 "the current element path. Flag @code{E} indicates that an element of the "
5524 "element path contained in a @var{target} attribute could not be found. Flag "
5525 "@code{O} indicates that a @var{target} attribute recursion limit was reached "
5526 "(@pxref{Configuration}). Flag @code{T}, followed by a single space character, "
5527 "then an element path, is the element path of the @var{target} attribute "
5528 "contained in the current element."
5529 "@*@*"
5530 "When a specified element path contains an error either from the final "
5531 "element in the path or any previous element, the path is still shown but "
5532 "will contain the error flag for the element with the error. Determining "
5533 "the actual element which contains the error is up to the client. This can be "
5534 "done by traversing the final element up to parent elements that contain the "
5535 "same error flag."
5536 "@*@*"
5537 "The option @option{--recurse} may be used to list the entire element tree "
5538 "for a specified element path or the entire tree for all root elements."
5539 "@*@*"
5540 "The option @option{--sexp} outputs the list in an s-expression and also "
5541 "appends an elements' attributes and attribute values. The syntax is:\n"
5542 "\n"
5543 "@example\n"
5544 "(11:list-result\n"
5545 " (4:path N:<path> 5:flags N:<flags>\n"
5546 " (5:attrs N:<name> N:<value> ...)\n"
5547 " )\n"
5548 " ...\n"
5549 ")\n"
5550 "@end example\n"
5551 "\n"
5552 "When the @option{--inquire} option is passed then all remaining non-option "
5553 "arguments are retrieved via a server @emph{INQUIRE}."
5556 new_command("REALPATH", 0, 0, 1, 0, realpath_command, _(
5557 "REALPATH [--inquire] element[<TAB>child[..]]\n" /* Resolving an element. */
5558 "Resolves all @code{target} attributes of the specified element path and "
5559 "returns the result with a data response. @xref{Target Attribute}, for details."
5560 "@*@*"
5561 "When the @option{--inquire} option is passed then all remaining non-option "
5562 "arguments are retrieved via a server @emph{INQUIRE}."
5565 new_command("STORE", 0, 0, 1, 0, store_command, _(
5566 "STORE [--no-inherit-acl] element[<TAB>child[..]]<TAB>[content]\n" /* Modifying the content of an element. */
5567 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
5568 "@*@*"
5569 "Creates a new element path or modifies the @var{content} of an existing "
5570 "element. If only a single element is specified then a new root element is "
5571 "created. Otherwise, elements are @key{TAB} delimited and the content will be "
5572 "set to the final @key{TAB} delimited element. If no @var{content} is "
5573 "specified after the final @key{TAB}, then the content of the existing "
5574 "element will be removed; or will be empty if creating a new element."
5575 "@*@*"
5576 "The option @option{--no-inherit-acl} prevents a newly created element from "
5577 "inheriting the value of the parent element @code{_acl} attribute. In either "
5578 "case, the current user is made the owner of the newly created element(s)."
5579 "@*@*"
5580 "The only restriction of an element name is that it not contain whitespace "
5581 "characters. There is no other whitespace between the @key{TAB} delimited "
5582 "elements. It is recommended that the content of an element be base64 encoded "
5583 "when it contains control or @key{TAB} characters to prevent @abbr{XML} "
5584 "parsing and @command{pwmd} syntax errors."
5587 new_command("RENAME", 0, 0, 1, 0, rename_command, _(
5588 "RENAME [--inquire] element[<TAB>child[..]] <value>\n" /* Renaming an element. */
5589 "Renames the specified @var{element} to the new @var{value}. If an element of "
5590 "the same name as the @var{value} already exists it will be overwritten."
5591 "@*@*"
5592 "When the @option{--inquire} option is passed then all remaining non-option "
5593 "arguments are retrieved via a server @emph{INQUIRE}."
5596 new_command("COPY", 0, 0, 1, 0, copy_command, _(
5597 "COPY [--inquire] source[<TAB>child[..]] dest[<TAB>child[..]]\n" /* Copying an element. */
5598 "Copies the entire element tree starting from the child node of the source "
5599 "element, to the destination element path. If the destination element path "
5600 "does not exist then it will be created; otherwise it is overwritten."
5601 "@*@*"
5602 "Note that attributes from the source element are merged into the "
5603 "destination element when the destination element path exists. When an "
5604 "attribute of the same name exists in both the source and destination "
5605 "elements then the destination attribute will be updated to the source "
5606 "attribute value."
5607 "@*@*"
5608 "When the @option{--inquire} option is passed then all remaining non-option "
5609 "arguments are retrieved via a server @emph{INQUIRE}."
5612 new_command("MOVE", 0, 0, 1, 0, move_command, _(
5613 "MOVE [--inquire] source[<TAB>child[..]] [dest[<TAB>child[..]]]\n" /* Moving an element. */
5614 "Moves the source element path to the destination element path. If the "
5615 "destination is not specified then it will be moved to the root node of the "
5616 "document. If the destination is specified and exists then it will be "
5617 "overwritten; otherwise non-existing elements of the destination element "
5618 "path will be created."
5619 "@*@*"
5620 "When the @option{--inquire} option is passed then all remaining non-option "
5621 "arguments are retrieved via a server @emph{INQUIRE}."
5624 new_command("DELETE", 0, 0, 1, 0, delete_command, _(
5625 "DELETE [--inquire] element[<TAB>child[..]]\n" /* Deleting an element. */
5626 "Removes the specified element path and all of its children. This may break "
5627 "an element with a @code{target} attribute (@pxref{Target Attribute}) that "
5628 "refers to this element or any of its children."
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("GET", 0, 0, 1, 0, get_command, _(
5635 "GET [--inquire] element[<TAB>child[..]]\n" /* Getting the content of an element. */
5636 "Retrieves the content of the specified element. The content is returned "
5637 "with a data response."
5638 "@*@*"
5639 "When the @option{--inquire} option is passed then all remaining non-option "
5640 "arguments are retrieved via a server @emph{INQUIRE}."
5643 new_command("ATTR", 0, 0, 1, 0, attr_command, _(
5644 "ATTR [--inquire] SET|GET|DELETE|LIST [<attribute>] element[<TAB>child[..]] ..\n" /* Modifying element attributes. */
5645 "@table @asis\n"
5646 "@item ATTR SET attribute element[<TAB>child[..]] [value]\n"
5647 " Stores or updates an @var{attribute} name and optional @var{value} of an "
5648 "element. When no @var{value} is specified any existing value will be removed."
5649 "@*@*"
5650 "@item ATTR DELETE attribute element[<TAB>child[..]]\n"
5651 " Removes an attribute from an element. If @var{attribute} is @code{_name} "
5652 "or @code{target} an error is returned. Use the @command{DELETE} command "
5653 "(@pxref{DELETE}) instead."
5654 "@*@*"
5655 "@item ATTR LIST element[<TAB>child[..]]\n"
5656 " Retrieves a newline separated list of attributes names and values "
5657 "from the specified element. Each attribute name and value is space delimited."
5658 "@*@*"
5659 "@item ATTR GET attribute element[<TAB>child[..]]\n"
5660 " Retrieves the value of an @var{attribute} from an element."
5661 "@end table\n"
5662 "@*@*"
5663 "When the @option{--inquire} option is passed then all remaining non-option "
5664 "arguments are retrieved via a server @emph{INQUIRE}."
5665 "@*@*"
5666 "@xref{Target Attribute}, for details about this special attribute and also "
5667 "@pxref{Other Attributes} for other attributes that are handled specially "
5668 "by @command{pwmd}."
5671 new_command("XPATH", 0, 0, 1, 0, xpath_command, _(
5672 "XPATH [--inquire] <expression>[<TAB>[value]]\n" /* Modifying more than one element. */
5673 "Evaluates an XPath @var{expression}. If no @var{value} argument is "
5674 "specified it is assumed the expression is a request to return a result. "
5675 "Otherwise, the result is set to the @var{value} argument and the document is "
5676 "updated. If there is no @var{value} after the @key{TAB} character, the value "
5677 "is assumed to be empty and the document is updated. For example:"
5678 "@sp 1\n"
5679 "@example\n"
5680 "XPATH //element[@@_name='password']@key{TAB}\n"
5681 "@end example\n"
5682 "@sp 1\n"
5683 "would clear the content of all @var{password} elements in the data file "
5684 "while leaving off the trailing @key{TAB} would return all @var{password} "
5685 "elements in @abbr{XML} format."
5686 "@*@*"
5687 "When the @option{--inquire} option is passed then all remaining non-option "
5688 "arguments are retrieved via a server @emph{INQUIRE}."
5689 "@*@*"
5690 "See @url{https://www.w3schools.com/xml/xpath_intro.asp} for @abbr{XPATH} "
5691 "expression syntax."
5694 new_command("XPATHATTR", 0, 0, 1, 0, xpathattr_command, _(
5695 "XPATHATTR [--inquire] SET|DELETE <name> <expression>[<TAB>[<value>]]\n" /* Modifying more than one element's attributes. */
5696 "Like the @code{XPATH} command (@pxref{XPATH}) but operates on element "
5697 "attributes and does not return a result. For the @var{SET} operation the "
5698 "@var{value} is optional but the field is required. If not specified then "
5699 "the attribute value will be empty. For example:"
5700 "@sp 1\n"
5701 "@example\n"
5702 "XPATHATTR SET password //element[@@_name='password']@key{TAB}\n"
5703 "@end example\n"
5704 "@sp 1\n"
5705 "would create a @var{password} attribute for each @var{password} element "
5706 "found in the document. The attribute value will be empty but still exist."
5707 "@*@*"
5708 "When the @option{--inquire} option is passed then all remaining non-option "
5709 "arguments are retrieved via a server @emph{INQUIRE}."
5710 "@*@*"
5711 "See @url{https://www.w3schools.com/xml/xpath_intro.asp} for @abbr{XPATH} "
5712 "expression syntax."
5715 new_command("IMPORT", 0, 0, 1, 0, import_command, _(
5716 "IMPORT [--root=element[<TAB>child[..]]]\n" /* Creating elements from XML. */
5717 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
5718 "@*@*"
5719 "Like the @code{STORE} command (@pxref{STORE}), but the @var{content} "
5720 "argument is raw @abbr{XML} data. The content is created as a child of "
5721 "the element path specified with the @option{--root} option or at the "
5722 "document root when not specified. Existing elements of the same name will "
5723 "be overwritten."
5724 "@*@*"
5725 "The content must begin with an @abbr{XML} element node. @xref{Introduction}, "
5726 "for details."
5729 new_command("DUMP", 0, 1, 1, 0, dump_command, _(
5730 "DUMP\n" /* Showing the XML document. */
5731 "Shows the in memory @abbr{XML} document with indenting. @xref{XPATH}, for "
5732 "dumping a specific node."
5735 new_command("LOCK", 0, 0, 0, 0, lock_command, _(
5736 "LOCK\n" /* Locking the current data file. */
5737 "Locks the mutex associated with the opened file. This prevents other clients "
5738 "from sending commands to the same opened file until the client "
5739 "that sent this command either disconnects or sends the @code{UNLOCK} "
5740 "command. @xref{UNLOCK}."
5743 new_command("UNLOCK", 0, 1, 0, 0, unlock_command, _(
5744 "UNLOCK\n" /* Removing a data file lock. */
5745 "Unlocks the file mutex which was locked with the @code{LOCK} command or "
5746 "a commands' @option{--lock} option (@pxref{LOCK}, @pxref{OPEN}, "
5747 "@pxref{ISCACHED})."
5750 new_command("GETCONFIG", 0, 1, 1, 0, getconfig_command, _(
5751 "GETCONFIG [filename] <parameter>\n" /* Obtaining a configuration value. */
5752 "Returns the value of a @command{pwmd} configuration @var{parameter} with a "
5753 "data response. If no file has been opened then the value for @var{filename} "
5754 "or the default from the @var{global} section will be returned. If a file "
5755 "has been opened and no @var{filename} is specified, the value previously "
5756 "set with the @code{OPTION} command (@pxref{OPTION}) will be returned."
5759 new_command("OPTION", 0, 1, 1, 0, option_command, _(
5760 "OPTION <NAME>=[<VALUE>]\n" /* Setting various client parameters. */
5761 "Sets a client option @var{name} to @var{value}. The value for an option is "
5762 "kept for the duration of the connection with the exception of the "
5763 "@command{pinentry} options which are defaults for all future connections "
5764 "(@pxref{Pinentry}). When @var{value} is empty the option is unset."
5765 "@*@*"
5766 "@table @asis\n"
5767 "@item DISABLE-PINENTRY\n"
5768 "Disable use of @command{pinentry} for passphrase retrieval. When @code{1}, a "
5769 "server inquire is sent to the client to obtain the passphrase. This option "
5770 "may be set as needed before the @code{OPEN} (@pxref{OPEN}), @code{PASSWD} "
5771 "(@pxref{PASSWD}) and @code{SAVE} (@pxref{SAVE}) commands. Set to @code{0} "
5772 "to use a @command{pinentry}."
5773 "@*@*"
5774 "@item DISPLAY\n"
5775 "Set or unset the X11 display to use when prompting for a passphrase."
5776 "@*@*"
5777 "@item TTYNAME\n"
5778 "Set the terminal device path to use when prompting for a passphrase."
5779 "@*@*"
5780 "@item TTYTYPE\n"
5781 "Set the terminal type for use with @option{TTYNAME}."
5782 "@*@*"
5783 "@item NAME\n"
5784 "Associates the thread ID of the connection with the specified textual "
5785 "representation. Useful for debugging log messages. May not contain whitespace."
5786 "@*@*"
5787 "@item LOCK-TIMEOUT\n"
5788 "When not @code{0}, the duration in tenths of a second to wait for the file "
5789 "mutex which has been locked by another thread to be released before returning "
5790 "an error. When @code{-1} the error will be returned immediately."
5791 "@*@*"
5792 "@item CLIENT-STATE\n"
5793 "When set to @code{1} then client state status messages for other clients are "
5794 "sent to the current client. The default is @code{0}."
5795 "@end table\n"
5798 new_command("LS", 0, 1, 1, 0, ls_command, _(
5799 "LS [--verbose]\n" /* Showing available data files. */
5800 "Returns a newline separated list of data files stored in the data directory "
5801 "@file{HOMEDIR/data} (@pxref{Invoking}) with a data response. When the "
5802 "@var{--verbose} option is passed, the space-separated filesystem inode "
5803 "access, modification and change times are appended to the line."
5806 new_command("BULK", 0, 1, 1, 0, bulk_command, _(
5807 "BULK [--inquire]\n" /* Run a series of commands in sequence. */
5808 "Parses a semi-canonical s-expression representing a series of protocol "
5809 "commands to be run in sequence (@pxref{Bulk Commands}). Returns a canonical "
5810 "s-expression containing each commands id, return value and result data "
5811 "(if any)."
5812 "@*@*"
5813 "When the @option{--inquire} option is passed then all remaining non-option "
5814 "arguments are retrieved via a server @emph{INQUIRE}."
5817 new_command("RESET", 0, 1, 1, 0, NULL, _(
5818 "RESET\n" /* Resetting the client state. */
5819 "Closes the currently opened file but keeps any previously set client options "
5820 "(@pxref{OPTION})."
5823 new_command("NOP", 0, 1, 1, 0, nop_command, _(
5824 "NOP\n" /* Testing the connection. */
5825 "This command does nothing. It is useful for testing the connection for a "
5826 "timeout condition."
5829 /* !END-HELP-TEXT! */
5830 new_command ("CANCEL", 0, 1, 1, 0, NULL, NULL);
5831 new_command ("END", 0, 1, 1, 0, NULL, NULL);
5832 new_command ("BYE", 0, 1, 1, 0, NULL, NULL);
5834 int i;
5835 for (i = 0; command_table[i]; i++);
5836 qsort (command_table, i - 1, sizeof (struct command_table_s *),
5837 sort_commands);
5840 gpg_error_t
5841 register_commands (assuan_context_t ctx)
5843 int i = 0, rc;
5845 for (; command_table[i]; i++)
5847 if (!command_table[i]->handler)
5848 continue;
5850 rc = assuan_register_command (ctx, command_table[i]->name,
5851 command_table[i]->handler,
5852 command_table[i]->help);
5853 if (rc)
5854 return rc;
5857 rc = assuan_register_bye_notify (ctx, bye_notify);
5858 if (rc)
5859 return rc;
5861 rc = assuan_register_reset_notify (ctx, reset_notify);
5862 if (rc)
5863 return rc;
5865 rc = assuan_register_pre_cmd_notify (ctx, command_startup);
5866 if (rc)
5867 return rc;
5869 return assuan_register_post_cmd_notify (ctx, command_finalize);