Fix a few 'gcc -fanalyzer' warnings.
[pwmd.git] / src / commands.c
blobcaa713388be1c7807c18345edff82a9561fd84b5
1 /*
2 Copyright (C) 2006-2023 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"
56 #include "command-opt.h"
58 #define FLOCK_TYPE_NONE 0
59 #define FLOCK_TYPE_SH 0x0001
60 #define FLOCK_TYPE_EX 0x0002
61 #define FLOCK_TYPE_KEEP 0x0004
63 static char env_display[256];
64 static char env_gpg_tty[256];
65 static char env_term[256];
66 static struct command_table_s **command_table;
68 static gpg_error_t do_lock (struct client_s *client, int add);
69 static gpg_error_t validate_checksum (struct client_s *, const char *filename,
70 struct cache_data_s *, unsigned char **,
71 size_t *, int);
72 static gpg_error_t update_checksum (struct client_s *client,
73 unsigned char *from_crc, size_t crclen);
74 static gpg_error_t command_startup (assuan_context_t ctx, const char *name);
75 static void command_finalize (assuan_context_t ctx, gpg_error_t rc);
77 /* When 'status' is true the 'self' field of the status line will be false
78 * because we never send the STATE status message to the same client that
79 * initiated it. */
80 static char *
81 build_client_info_line (struct client_thread_s *thd, int status)
83 char *uid, *username = NULL;
84 char *line;
86 #ifdef WITH_GNUTLS
87 if (thd->remote)
88 uid = str_asprintf("#%s", thd->tls->fp);
89 else
91 uid = str_asprintf("%u", thd->peer->uid);
92 username = get_username (thd->peer->uid);
94 #else
95 uid = str_asprintf("%u", thd->peer->uid);
96 username = get_username (thd->peer->uid);
97 #endif
98 line = str_asprintf ("%p %s %s %s %u %u %u %s %s %u",
99 thd->tid,
100 thd->name ? thd->name : "-",
101 thd->cl && thd->cl->filename
102 && (thd->cl->flags & FLAG_OPEN)
103 ? thd->cl->filename : "/",
104 #ifdef WITH_GNUTLS
105 thd->remote ? thd->peeraddr : "-",
106 #else
107 "-",
108 #endif
109 thd->cl && thd->cl->flags & FLAG_HAS_LOCK ? 1 : 0,
110 !status && pthread_equal (pthread_self (), thd->tid) ? 1 : 0,
111 thd->state, uid,
112 #ifdef WITH_GNUTLS
113 thd->remote ? "-" : username,
114 #else
115 username,
116 #endif
117 thd->conntime
120 xfree (username);
121 xfree (uid);
122 return line;
125 void
126 update_client_state (struct client_s *client, unsigned s)
128 MUTEX_LOCK (&cn_mutex);
129 if (client->thd->state == s)
131 MUTEX_UNLOCK (&cn_mutex);
132 return;
134 client->thd->state = s;
135 MUTEX_UNLOCK (&cn_mutex);
137 if (client->thd->state != CLIENT_STATE_UNKNOWN)
139 char *line = build_client_info_line (client->thd, 1);
141 pthread_cleanup_push (xfree, line);
142 if (line)
143 send_status_all_not_self (STATUS_STATE, "%s", line);
144 pthread_cleanup_pop (1);
148 static gpg_error_t
149 unlock_file_mutex (struct client_s *client, int remove)
151 gpg_error_t rc = 0;
153 // OPEN: keep the lock for the same file being reopened.
154 if (client->flags & FLAG_KEEP_LOCK && client->flags & FLAG_HAS_LOCK)
155 return 0;
157 if (!remove && !(client->flags & FLAG_HAS_LOCK))
158 return GPG_ERR_NOT_LOCKED;
160 rc = cache_unlock_mutex (client->filename, remove);
161 if (rc)
162 rc = GPG_ERR_INV_STATE;
163 else
164 client->flags &= ~(FLAG_HAS_LOCK | FLAG_LOCK_CMD);
166 return rc;
169 static gpg_error_t
170 lock_file_mutex (struct client_s *client, int add)
172 gpg_error_t rc = 0;
173 long timeout = config_get_long (client->filename, "cache_timeout");
175 if (client->flags & FLAG_HAS_LOCK)
176 return 0;
178 rc = cache_lock_mutex (client->ctx, client->filename,
179 client->lock_timeout, add, timeout);
180 if (!rc)
181 client->flags |= FLAG_HAS_LOCK;
183 return rc;
186 static gpg_error_t
187 file_modified (struct client_s *client, struct command_table_s *cmd)
189 gpg_error_t rc = 0;
190 int type = !cmd->flock_type || (cmd->flock_type & FLOCK_TYPE_SH)
191 ? LOCK_SH : LOCK_EX;
193 if (!(client->flags & FLAG_OPEN))
194 return GPG_ERR_INV_STATE;
196 rc = lock_file_mutex (client, 0);
197 if (rc && rc != GPG_ERR_NO_DATA)
198 return rc;
200 rc = lock_flock (client->ctx, client->filename, type, &client->flock_fd);
201 if (!rc)
203 rc = validate_checksum (client, client->filename, NULL, NULL, NULL, 0);
204 if (gpg_err_code (rc) == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
205 rc = 0;
206 else if (rc)
207 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
209 else if (gpg_err_code (rc) == GPG_ERR_ENOENT)
210 rc = 0;
212 /* FLAG_HAS_LOCK may have been set by the LOCK command or OPEN --lock. */
213 if ((cmd->unlock && !(client->flags & FLAG_HAS_LOCK)) || rc)
214 unlock_file_mutex (client, 0);
216 if (rc || !(cmd->flock_type & FLOCK_TYPE_KEEP))
217 unlock_flock (&client->flock_fd);
219 return rc;
222 static gpg_error_t
223 parse_xml (assuan_context_t ctx, int new)
225 struct client_s *client = assuan_get_pointer (ctx);
226 int cached = client->doc != NULL;
227 gpg_error_t rc = 0;
229 if (new)
231 client->doc = xml_new_document ();
232 if (client->doc)
234 xmlChar *result;
235 int len;
237 xmlDocDumpFormatMemory (client->doc, &result, &len, 0);
238 client->crypto->plaintext = result;
239 client->crypto->plaintext_size = len;
240 if (!client->crypto->plaintext)
242 xmlFreeDoc (client->doc);
243 client->doc = NULL;
244 rc = GPG_ERR_ENOMEM;
247 else
248 rc = GPG_ERR_ENOMEM;
250 else if (!cached)
251 rc = xml_parse_doc ((char *) client->crypto->plaintext,
252 client->crypto->plaintext_size,
253 (xmlDocPtr *)&client->doc);
255 return rc;
258 static void
259 free_client (struct client_s *client)
261 cache_plaintext_release (&client->doc);
262 xfree (client->crc);
263 xfree (client->filename);
264 xfree (client->last_error);
265 crypto_free (client->crypto);
266 client->crypto = NULL;
269 void
270 reset_client (struct client_s *client)
272 assuan_context_t ctx = client->ctx;
273 struct client_thread_s *thd = client->thd;
274 long lock_timeout = client->lock_timeout;
275 xmlErrorPtr xml_error = client->xml_error;
276 int no_pinentry = (client->flags & FLAG_NO_PINENTRY);
277 int flock_fd = client->flock_fd;
278 struct bulk_cmd_s *bulk_p = client->bulk_p;
280 cache_lock ();
281 unlock_file_mutex (client, client->flags & FLAG_NEW);
282 free_client (client);
283 memset (client, 0, sizeof (struct client_s));
284 client->flock_fd = flock_fd;
285 client->xml_error = xml_error;
286 client->ctx = ctx;
287 client->thd = thd;
288 client->lock_timeout = lock_timeout;
289 client->flags |= no_pinentry ? FLAG_NO_PINENTRY : 0;
290 client->bulk_p = bulk_p;
291 cache_unlock ();
294 static void
295 req_free (void *arg)
297 if (!arg)
298 return;
300 strv_free ((char **) arg);
303 static gpg_error_t
304 parse_open_opt_lock (void *data, void *value)
306 struct client_s *client = data;
308 (void)value;
309 client->opts |= OPT_LOCK_ON_OPEN;
310 return 0;
313 static gpg_error_t
314 parse_opt_inquire (void *data, void *value)
316 struct client_s *client = data;
318 (void) value;
319 client->opts |= OPT_INQUIRE;
320 return 0;
323 static gpg_error_t
324 update_checksum (struct client_s *client, unsigned char *from_crc,
325 size_t crclen)
327 unsigned char *crc;
328 size_t len;
329 struct cache_data_s *cdata;
330 gpg_error_t rc;
332 if (!from_crc)
334 rc = get_checksum (client->filename, &crc, &len);
335 if (rc)
336 return rc;
338 else
340 crc = from_crc;
341 len = crclen;
344 xfree (client->crc);
345 client->crc = xmalloc (len);
346 memcpy (client->crc, crc, len);
347 pthread_cleanup_push (xfree, crc);
348 cdata = cache_get_data (client->filename, NULL);
349 pthread_cleanup_pop (0);
350 if (cdata)
352 xfree (cdata->crc);
353 cdata->crc = xmalloc (len);
354 memcpy (cdata->crc, crc, len);
357 if (!from_crc)
358 xfree (crc);
359 return 0;
362 static gpg_error_t
363 validate_checksum (struct client_s *client, const char *filename,
364 struct cache_data_s *cdata, unsigned char **r_crc,
365 size_t *r_crclen, int from_cdata)
367 unsigned char *crc;
368 size_t len;
369 gpg_error_t rc;
370 int n = 0;
372 if (cdata && !cdata->crc)
373 return GPG_ERR_CHECKSUM;
375 rc = get_checksum (filename, &crc, &len);
376 if (rc)
377 return rc;
379 if (client->crc)
380 n = memcmp (client->crc, crc, len);
381 else if ((client->flags & FLAG_NEW) && cache_get_data (filename, NULL))
382 n = 1;
384 if ((!n && cdata) || (from_cdata && cdata && crc))
385 n = memcmp (cdata->crc, crc, len);
387 if (!n && r_crc)
389 *r_crc = crc;
390 *r_crclen = len;
392 else
393 xfree (crc);
395 return n ? GPG_ERR_CHECKSUM : 0;
398 static gpg_error_t
399 open_command (assuan_context_t ctx, char *line)
401 gpg_error_t rc;
402 struct client_s *client = assuan_get_pointer (ctx);
403 int same_file = 0;
404 assuan_peercred_t peer;
405 struct cache_data_s *cdata = NULL;
406 int cached = 0;
407 unsigned char *crc = NULL;
408 size_t crclen = 0;
409 int plaintext = 0;
410 struct argv_s *args[] = {
411 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_open_opt_lock},
412 NULL
415 rc = parse_options (&line, args, client, 1);
416 if (rc)
417 return send_error (ctx, rc);
419 rc = do_validate_peer (ctx, line, &peer, NULL);
420 if (rc == GPG_ERR_FORBIDDEN)
422 rc = peer_is_invoker (client);
423 if (rc == GPG_ERR_EACCES)
424 rc = GPG_ERR_FORBIDDEN;
427 if (rc)
428 return send_error (ctx, rc);
430 if (!valid_filename (line))
431 return send_error (ctx, GPG_ERR_INV_VALUE);
433 /* This client may have locked a different file with ISCACHED --lock than
434 * the current filename. This will remove that lock. */
435 same_file = client->filename && !strcmp (line, client->filename);
436 if (client->flags & FLAG_OPEN ||
437 (client->flags & FLAG_HAS_LOCK && !same_file))
439 unsigned opts = client->opts;
440 unsigned flags = client->flags;
442 if (same_file)
443 client->flags |= FLAG_KEEP_LOCK;
445 /* Another client wrote to the same data file as currently opened. */
446 cdata = cache_get_data (client->filename, NULL);
447 if (cdata && cdata->crc)
448 flags &= ~FLAG_NEW;
449 /* Remove cache entry for the new file that hadn't been written. */
450 else if (client->flags & FLAG_NEW)
451 cache_clear (NULL, client->filename, 0, 0);
453 cdata = NULL;
454 reset_client (client);
455 client->opts = opts;
456 client->flags |= flags;
457 client->flags &= ~(FLAG_LOCK_CMD);
458 if (!same_file)
459 client->flags &= ~(FLAG_HAS_LOCK | FLAG_NEW);
462 xfree (client->filename);
463 client->filename = str_dup (line);
464 if (!client->filename)
465 return send_error(ctx, GPG_ERR_ENOMEM);
467 /* Need to lock the mutex here because file_modified() cannot without
468 * knowing the filename. */
469 rc = lock_file_mutex (client, 1);
470 if (rc)
471 client->flags &= ~FLAG_OPEN;
473 if (!rc)
475 rc = lock_flock (ctx, client->filename, LOCK_SH, &client->flock_fd);
476 if (gpg_err_code (rc) == GPG_ERR_ENOENT)
477 rc = 0;
480 if (!rc)
482 char *keyfile = config_get_string (client->filename, "passphrase_file");
484 rc = crypto_init (&client->crypto, client->ctx, client->filename,
485 client->flags & FLAG_NO_PINENTRY, keyfile);
486 if (rc)
487 xfree (keyfile);
488 else
489 rc = open_check_file (client->filename, NULL, NULL, 1);
492 if (!rc || gpg_err_code (rc) == GPG_ERR_ENOENT)
494 int reload = 0;
495 int defer = 0;
497 if (rc) // new file
499 rc = 0;
501 if (config_get_boolean ("global", "strict_open"))
503 rc = peer_is_invoker (client);
504 if (rc == GPG_ERR_EACCES)
505 rc = GPG_ERR_FORBIDDEN;
508 if (!rc)
510 client->flags |= FLAG_NEW;
511 // data file disappeared. clear the cache entry.
512 cache_clear (NULL, client->filename, 1, 1);
513 cdata = NULL;
516 goto done;
519 cdata = cache_get_data (client->filename, &defer);
520 if (cdata && !defer
521 && !cache_plaintext_get (client->filename, &client->doc))
523 rc = validate_checksum (client, client->filename, cdata, &crc,
524 &crclen, 0);
525 if (rc)
527 log_write ("%s: %s", client->filename,
528 pwmd_strerror (rc));
529 cache_plaintext_release (&client->doc);
530 if (rc == GPG_ERR_CHECKSUM)
532 cache_clear (NULL, client->filename, 1, 1);
533 cdata = NULL;
534 goto decrypt;
538 #ifdef WITH_GNUTLS
539 if (!rc && client->thd->remote
540 && config_get_boolean (client->filename, "tcp_require_key")
541 && !(client->flags & FLAG_NEW))
543 rc = crypto_try_decrypt (client,
544 (client->flags & FLAG_NO_PINENTRY));
546 #endif
547 if (!rc)
549 strv_free (client->crypto->pubkey);
550 client->crypto->pubkey = NULL;
551 if (cdata->pubkey)
552 client->crypto->pubkey = strv_dup (cdata->pubkey);
554 xfree (client->crypto->sigkey);
555 client->crypto->sigkey = NULL;
556 if (cdata->sigkey)
557 client->crypto->sigkey = str_dup (cdata->sigkey);
559 cached = 1;
560 plaintext = 1;
563 else if (cdata && cdata->doc) // cached document
565 if (!rc && !(client->flags & FLAG_NEW))
567 rc = validate_checksum (client, client->filename, cdata, &crc,
568 &crclen, 0);
569 if (rc == GPG_ERR_CHECKSUM)
571 rc = 0;
572 reload = 1;
576 if (!rc)
578 rc = cache_iscached (client->filename, &defer, 0, 0);
579 if ((!rc || rc == GPG_ERR_ENOENT) && defer)
581 rc = 0;
582 reload = 2;
586 if (!rc && reload)
588 if (reload == 1)
589 log_write ("%s: %s", client->filename,
590 pwmd_strerror (GPG_ERR_CHECKSUM));
591 cache_clear (NULL, client->filename, 1, 1);
592 cdata = NULL;
593 rc = crypto_decrypt (client, client->crypto);
595 #ifdef WITH_GNUTLS
596 else if (!rc)
598 if (client->thd->remote
599 && config_get_boolean (client->filename, "tcp_require_key")
600 && !(client->flags & FLAG_NEW))
601 rc = crypto_try_decrypt (client,
602 (client->flags & FLAG_NO_PINENTRY));
604 #endif
606 if (!rc && cdata)
608 client->crypto->plaintext = cdata->doc;
609 client->crypto->plaintext_size = cdata->size;
610 rc = cache_decrypt (client->crypto);
611 if (!rc)
613 cdata->doc = NULL;
614 cdata->size = 0;
616 strv_free (client->crypto->pubkey);
617 client->crypto->pubkey = NULL;
618 if (cdata->pubkey)
619 client->crypto->pubkey = strv_dup (cdata->pubkey);
621 xfree (client->crypto->sigkey);
622 client->crypto->sigkey = NULL;
623 if (cdata->sigkey)
624 client->crypto->sigkey = str_dup (cdata->sigkey);
626 cached = 1;
628 else
630 client->crypto->plaintext = NULL;
631 client->crypto->plaintext_size = 0;
635 else // existing file
637 decrypt:
638 cached = cdata != NULL;
639 rc = crypto_decrypt (client, client->crypto);
643 done:
644 if (!rc && !plaintext)
646 rc = parse_xml (ctx, client->flags & FLAG_NEW);
647 if (!rc)
649 rc = cache_encrypt (client->crypto);
650 if (rc)
651 cache_clear (NULL, client->filename, 1, 1);
652 else
654 long timeout = config_get_long (client->filename,
655 "cache_timeout");
657 cache_free_data_once (cdata);
658 cdata = xcalloc (1, sizeof (struct cache_data_s));
659 cdata->doc = client->crypto->plaintext;
660 cdata->size = client->crypto->plaintext_size;
661 cdata->pubkey = strv_dup(client->crypto->pubkey);
662 cdata->sigkey = client->crypto->sigkey ? str_dup(client->crypto->sigkey) : NULL;
663 client->crypto->plaintext = NULL;
664 client->crypto->plaintext_size = 0;
666 if (cached) // wont increment the refcount
668 if (crclen)
670 xfree (client->crc);
671 client->crc = NULL;
672 xfree (cdata->crc);
673 cdata->crc = xmalloc (crclen);
674 memcpy (cdata->crc, crc, crclen);
677 rc = cache_set_data (client->filename, cdata);
678 /* The cache entry may have been removed and cache_set_data()
679 * already sent STATUS_CACHE. */
680 if (!cache_iscached (client->filename, NULL, 0, 0))
681 rc = send_status (ctx, STATUS_CACHE, NULL);
683 else
684 rc = cache_add_file (client->filename, cdata, timeout, same_file);
686 if (!rc)
687 cache_plaintext_set (client->filename, client->doc, 0);
692 if (!rc)
694 xfree (client->crc);
695 client->crc = NULL;
696 if (crc)
698 client->crc = xmalloc (crclen);
699 memcpy (client->crc, crc, crclen);
703 xfree (crc);
705 if (!rc && !(client->flags & FLAG_NEW) && !cached)
706 rc = update_checksum (client, NULL, 0);
708 if (!rc)
710 client->flags |= FLAG_OPEN;
712 if (client->flags & FLAG_NEW)
713 rc = send_status (ctx, STATUS_NEWFILE, NULL);
715 if (!rc && (client->opts & OPT_LOCK_ON_OPEN))
716 rc = do_lock (client, 0);
718 crypto_free_non_keys (client->crypto);
720 else
722 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
724 if (client->flags & FLAG_NEW)
725 cache_clear (NULL, client->filename, 1, 1);
727 crypto_free (client->crypto);
728 client->crypto = NULL;
729 client->flags &= ~FLAG_OPEN;
730 cache_plaintext_release (&client->doc);
733 return send_error (ctx, rc);
736 /* If not an invoking_user or is an existing file, check that the list of user
737 * supplied key ID's are in the list of current key ID's obtained when
738 * decrypting the data file.
740 static gpg_error_t
741 permitted_to_save (struct client_s *client, const char **keys,
742 const char **value)
744 gpg_error_t rc = 0;
745 const char **v;
747 if ((client->flags & FLAG_NEW) || (client->opts & OPT_SYMMETRIC))
748 return 0;
750 rc = peer_is_invoker (client);
751 if (!rc)
752 return 0;
753 else if (rc == GPG_ERR_EACCES)
754 rc = GPG_ERR_FORBIDDEN;
755 else if (rc)
756 return rc;
758 /* Empty match. */
759 if ((!value && !keys) || ((value && !*value) && (keys && !*keys)))
760 return 0;
762 for (v = value; v && *v; v++)
764 const char **k, *pv = *v;
765 int match = 0;
767 if (*pv == '0' && *(pv+1) == 'x')
768 pv += 2;
770 for (k = keys; k && *k; k++)
772 const char *pk = *k;
774 if (*pk == '0' && *(pk+1) == 'x')
775 pk += 2;
777 rc = !strcmp (pv, pk) ? 0 : GPG_ERR_FORBIDDEN;
778 if (rc)
779 rc = !strcmp (pv, *k) ? 0 : GPG_ERR_FORBIDDEN;
781 if (!rc)
783 match = 1;
784 break;
788 if (!match)
789 return GPG_ERR_FORBIDDEN;
792 return rc;
795 /* Requires that the keyid be a fingerprint in 16 byte form. */
796 static gpg_error_t
797 parse_save_opt_keyid_common (struct client_s *client, const char **list,
798 const char *value, char ***dst)
800 gpg_error_t rc = 0;
801 char **keys = NULL;
803 if (value && *value)
805 keys = str_split (value, ",", 0);
806 if (!keys)
807 return GPG_ERR_ENOMEM;
810 rc = crypto_keyid_to_16b (keys);
811 if (!rc)
812 rc = permitted_to_save (client, list, (const char **)keys);
814 if (!rc)
815 *dst = keys;
816 else
817 strv_free (keys);
819 return rc;
822 static gpg_error_t
823 parse_save_opt_keyid (void *data, void *value)
825 struct client_s *client = data;
826 const char *str = value;
827 char **dst = NULL;
828 gpg_error_t rc;
830 rc = parse_save_opt_keyid_common (client,
831 (const char **)client->crypto->pubkey,
832 str, &dst);
833 if (rc)
834 return rc;
836 client->crypto->save.pubkey = dst;
837 return 0;
840 static gpg_error_t
841 parse_save_opt_sign_keyid (void *data, void *value)
843 struct client_s *client = data;
844 const char *str = value;
845 char **dst = NULL;
846 gpg_error_t rc;
847 char **tmp = NULL;
849 if (client->crypto->sigkey)
851 if (!strv_printf (&tmp, "%s", client->crypto->sigkey))
852 return GPG_ERR_ENOMEM;
855 rc = parse_save_opt_keyid_common (client, (const char **)tmp, str, &dst);
856 strv_free (tmp);
857 if (rc)
858 return rc;
860 if (!dst)
861 client->opts |= OPT_NO_SIGNER;
862 else
863 client->crypto->save.sigkey = str_dup (*dst);
865 strv_free (dst);
866 return 0;
869 static gpg_error_t
870 parse_save_opt_inquire_keyid (void *data, void *value)
872 struct client_s *client = data;
874 (void)value;
876 if (!(client->flags & FLAG_NEW))
878 gpg_error_t rc = peer_is_invoker (client);
880 if (rc)
881 return rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc;
884 client->opts |= OPT_INQUIRE_KEYID;
885 return 0;
888 static gpg_error_t
889 parse_save_opt_symmetric (void *data, void *value)
891 struct client_s *client = data;
893 (void)value;
894 client->opts |= OPT_SYMMETRIC;
895 return 0;
898 static gpg_error_t
899 parse_genkey_opt_userid (void *data, void *value)
901 struct client_s *client = data;
903 if (!(client->flags & FLAG_NEW))
905 gpg_error_t rc = peer_is_invoker (client);
907 if (rc)
908 return rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc;
911 client->crypto->save.userid = str_dup (value);
912 return client->crypto->save.userid ? 0 : GPG_ERR_ENOMEM;
915 static gpg_error_t
916 parse_genkey_opt_algo (void *data, void *value)
918 struct client_s *client = data;
920 client->crypto->save.algo = str_dup (value);
921 return client->crypto->save.algo ? 0 : GPG_ERR_ENOMEM;
924 static gpg_error_t
925 parse_genkey_opt_no_expire (void *data, void *value)
927 struct client_s *client = data;
929 client->crypto->save.flags |= GPGME_CREATE_NOEXPIRE;
930 return 0;
933 static gpg_error_t
934 parse_genkey_opt_expire (void *data, void *value)
936 struct client_s *client = data;
937 gpg_error_t rc = 0;
938 char *p = NULL;
939 unsigned long t;
941 errno = 0;
942 t = strtoul (value, &p, 10);
944 if (!errno && p && *p)
945 rc = GPG_ERR_INV_VALUE;
946 else if (t == ULONG_MAX)
947 rc = GPG_ERR_INV_VALUE;
948 else if (errno)
949 rc = gpg_error_from_syserror ();
950 else
951 client->crypto->save.expire = t;
953 return rc;
956 static gpg_error_t
957 parse_genkey_opt_no_passphrase (void *data, void *value)
959 struct client_s *client = data;
961 (void)value;
962 client->crypto->save.flags |= GPGME_CREATE_NOPASSWD;
963 return 0;
966 /* Tests that the keys in new_keys are also in old_keys. */
967 static gpg_error_t
968 compare_keys (char **new_keys, char **old_keys)
970 char **o;
972 if (!old_keys || !*old_keys)
973 return 0;
975 crypto_keyid_to_16b (new_keys);
977 for (o = old_keys; *o; o++)
979 char **n;
981 for (n = new_keys; *n; n++)
983 if (!strcmp (*n, *o))
984 break;
987 if (!*n)
988 return GPG_ERR_NOT_FOUND;
991 return 0;
994 static gpg_error_t
995 inquire_keyid (struct client_s *client)
997 gpg_error_t rc;
998 unsigned char *result = NULL;
999 size_t len;
1000 const char *s = "KEYID";
1001 char ***orig;
1002 char ***save;
1004 orig = &client->crypto->pubkey;
1005 save = &client->crypto->save.pubkey;
1006 rc = assuan_inquire (client->ctx, s, &result, &len, 0);
1007 if (!rc)
1009 char **dst = NULL;
1011 rc = parse_save_opt_keyid_common (client, (const char **)*orig,
1012 (char *)result, &dst);
1013 if (!rc)
1014 *save = dst;
1017 xfree (result);
1018 return rc;
1022 /* When a key lookup in gpg-agent's cache fails, the agent tries the last
1023 * successful key to be unlocked. This prevents pwmd from successfully
1024 * clearing a signing key since the previous key, which more than likely
1025 * belongs to the same keypair as the encryption/decryption key, will have the
1026 * passphrase cached and therefore the signing key also cached. So we need to
1027 * clear both the signing and encryption keys to get the effect of requiring a
1028 * passphrase when generating a new keypair for an existing data file, or when
1029 * the "require_save_key" configuration parameter is set. This parameter is
1030 * mostly a failsafe of the gpg-agent option --ignore-cache-for-signing since
1031 * some/most/all users may fail to set it.
1033 static gpg_error_t
1034 save_command (assuan_context_t ctx, char *line)
1036 struct client_s *client = assuan_get_pointer (ctx);
1037 struct cache_data_s *cdata = NULL;
1038 int sym = 0;
1039 gpg_error_t rc = 0, cache_rc = 0;
1040 int defer = 0;
1041 struct argv_s *args[] = {
1042 &(struct argv_s) {"keyid", OPTION_TYPE_ARG, parse_save_opt_keyid},
1043 &(struct argv_s) {"inquire-keyid", OPTION_TYPE_NOARG,
1044 parse_save_opt_inquire_keyid },
1045 &(struct argv_s) {"sign-keyid", OPTION_TYPE_OPTARG,
1046 parse_save_opt_sign_keyid},
1047 &(struct argv_s) {"symmetric", OPTION_TYPE_NOARG,
1048 parse_save_opt_symmetric },
1049 NULL
1052 crypto_free_save (&client->crypto->save);
1053 client->crypto->save.expire = DEFAULT_EXPIRE;
1055 rc = crypto_is_symmetric (client->filename);
1056 if (!rc || rc == GPG_ERR_BAD_DATA || rc == GPG_ERR_ENOENT)
1058 if (!rc)
1060 client->opts |= OPT_SYMMETRIC;
1061 sym = 1;
1063 else if (rc == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
1064 rc = 0; // New file
1065 else
1066 rc = 0; // PKI
1069 if (rc)
1070 return send_error (ctx, rc);
1072 rc = parse_options (&line, args, client, 0);
1073 if (rc)
1074 return send_error (ctx, rc);
1076 if (config_get_boolean (client->filename, "require_save_key")
1077 || (client->opts & OPT_SYMMETRIC))
1078 client->opts |= OPT_ASK;
1080 rc = open_check_file (client->filename, NULL, NULL, 1);
1081 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
1083 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
1084 return send_error (ctx, rc);
1087 if (!rc)
1088 cache_rc = rc = cache_iscached (client->filename, &defer, 0, 1);
1090 if (gpg_err_code (rc) == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
1091 rc = 0;
1092 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
1093 rc = 0;
1095 if (rc)
1096 return send_error (ctx, rc);
1098 /* Specifying both a recipient and symmetric encryption is an error. */
1099 if ((client->opts & OPT_INQUIRE_KEYID) && (client->opts & OPT_SYMMETRIC))
1100 return send_error (ctx, GPG_ERR_CONFLICT);
1101 /* Existing file with a recipient and wanting symmetric is an error. */
1102 else if ((client->opts & OPT_SYMMETRIC) && client->crypto->save.pubkey)
1103 return send_error (ctx, GPG_ERR_CONFLICT);
1104 else if (client->crypto->save.pubkey && (client->opts & OPT_INQUIRE_KEYID))
1105 return send_error (ctx, GPG_ERR_CONFLICT);
1106 else if (!sym && (client->opts & OPT_SYMMETRIC) && !(client->flags & FLAG_NEW))
1107 return send_error (ctx, GPG_ERR_CONFLICT);
1108 /* New file that is not symmetric without either a recipient or signer. */
1109 else if ((client->flags & FLAG_NEW) && !(client->opts & OPT_SYMMETRIC)
1110 && (!client->crypto->save.pubkey || !client->crypto->save.sigkey))
1111 return send_error (ctx, GPG_ERR_SYNTAX);
1112 else if (client->opts & OPT_INQUIRE_KEYID)
1113 rc = inquire_keyid (client);
1115 if (!rc)
1117 client->crypto->keyfile = config_get_string (client->filename,
1118 "passphrase_file");
1119 rc = crypto_init_ctx (client->crypto, (client->flags & FLAG_NO_PINENTRY),
1120 client->crypto->keyfile);
1123 if (!rc && (client->flags & FLAG_NEW))
1125 /* Require --keyid when --sign-keyid exists to keep KEYINFO
1126 * synchronized. */
1127 if (!client->crypto->save.pubkey && client->crypto->save.sigkey
1128 && !(client->opts & OPT_SYMMETRIC))
1129 rc = GPG_ERR_NO_PUBKEY;
1131 else if (!rc)
1133 cdata = cache_get_data (client->filename, NULL);
1134 if (cdata)
1136 if (client->crypto->save.pubkey)
1137 rc = compare_keys (client->crypto->save.pubkey, cdata->pubkey);
1139 /* Always allow a signer for symmetric data files. */
1140 if (!rc && client->crypto->save.sigkey
1141 && !(client->opts & OPT_SYMMETRIC))
1142 rc = !strcmp (client->crypto->save.sigkey, cdata->sigkey)
1143 ? 0 : GPG_ERR_NOT_FOUND;
1145 /* Prevent saving to a recipient who is not in the original recipient
1146 * list without a passphrase. */
1147 if (rc || (client->crypto->sigkey && (client->opts & OPT_NO_SIGNER)))
1148 client->opts |= OPT_ASK;
1150 if (rc == GPG_ERR_NOT_FOUND)
1152 rc = peer_is_invoker (client);
1153 if (rc == GPG_ERR_EACCES)
1154 rc = GPG_ERR_FORBIDDEN;
1157 if (!client->crypto->save.pubkey
1158 && !(client->opts & OPT_SYMMETRIC))
1159 client->crypto->save.pubkey = strv_dup (cdata->pubkey);
1161 if (!rc && !client->crypto->save.sigkey && cdata->sigkey
1162 && !(client->opts & OPT_NO_SIGNER))
1163 client->crypto->save.sigkey = str_dup (cdata->sigkey);
1164 else if (!rc && !client->crypto->save.sigkey
1165 && (client->opts & OPT_NO_SIGNER)
1166 && !(client->opts & OPT_SYMMETRIC))
1167 rc = GPG_ERR_NO_SIGNATURE_SCHEME;
1169 else
1171 client->crypto->save.pubkey = strv_dup (client->crypto->pubkey);
1172 client->crypto->save.sigkey = str_dup (client->crypto->sigkey);
1176 if (!rc && !(client->flags & FLAG_NEW))
1178 /* Fixes {NEW_,SIGN_}PASSPHRASE inquire keywords. See passphrase_cb(). */
1179 if (client->opts & OPT_SYMMETRIC)
1180 client->crypto->flags |= CRYPTO_FLAG_PASSWD;
1182 if (client->opts & OPT_ASK)
1184 rc = cache_clear_agent_keys (client->filename, 1, 1);
1185 if (!rc)
1186 rc = crypto_try_decrypt (client, client->flags & FLAG_NO_PINENTRY);
1190 if (!rc && client->opts & OPT_SYMMETRIC)
1191 client->crypto->flags |= CRYPTO_FLAG_PASSWD_NEW;
1193 if (!rc)
1194 rc = xml_update_element_mtime (client, xmlDocGetRootElement (client->doc));
1196 if (!rc)
1198 xmlNodePtr root = xmlDocGetRootElement (client->doc);
1200 rc = xml_add_attribute (client, root, "_version", PACKAGE_VERSION);
1203 if (!rc)
1205 int size;
1207 xmlDocDumpFormatMemory (client->doc, &client->crypto->plaintext, &size,
1209 if (size > 0)
1210 client->crypto->plaintext_size = (size_t) size;
1211 else
1212 rc = GPG_ERR_ENOMEM;
1214 if (!rc)
1216 client->crypto->flags |= (client->opts & OPT_SYMMETRIC) ? CRYPTO_FLAG_SYMMETRIC : 0;
1217 client->crypto->flags |= (client->flags & FLAG_NEW) ? CRYPTO_FLAG_NEWFILE : 0;
1218 client->crypto->flags |= !(client->opts & OPT_SYMMETRIC) ? CRYPTO_FLAG_PASSWD_SIGN : 0;
1219 rc = crypto_encrypt (client, client->crypto);
1220 client->crypto->flags &= ~CRYPTO_FLAG_SYMMETRIC;
1223 if (!rc)
1225 unsigned char *crc = NULL;
1226 size_t crclen = 0;
1228 rc = crypto_write_file (client->crypto, &crc, &crclen);
1229 pthread_cleanup_push ((void *)xfree, crc);
1230 if (!rc)
1232 if (!cache_rc)
1233 cdata = cache_get_data (client->filename, NULL);
1234 else
1235 cdata = xcalloc (1, sizeof (struct cache_data_s));
1238 if (!rc)
1240 rc = cache_encrypt (client->crypto);
1241 if (rc)
1243 cache_clear (NULL, client->filename, 1, 1);
1244 client->flags &= ~(FLAG_NEW);
1246 strv_free (client->crypto->pubkey);
1247 client->crypto->pubkey = NULL;
1248 if (client->crypto->save.pubkey)
1249 client->crypto->pubkey = strv_dup (client->crypto->save.pubkey);
1251 xfree (client->crypto->sigkey);
1252 client->crypto->sigkey = NULL;
1253 if (client->crypto->save.sigkey)
1254 client->crypto->sigkey = str_dup (client->crypto->save.sigkey);
1258 if (!rc)
1260 long timeout = config_get_long (client->filename, "cache_timeout");
1261 xmlDocPtr doc = xmlCopyDoc (client->doc, 1);
1263 if (!doc)
1264 rc = GPG_ERR_ENOMEM;
1266 if (!rc)
1268 cache_plaintext_release (&client->doc);
1269 strv_free (cdata->pubkey);
1270 cdata->pubkey = client->crypto->save.pubkey;
1271 client->crypto->save.pubkey = NULL;
1273 xfree (cdata->sigkey);
1274 cdata->sigkey = client->crypto->save.sigkey;
1275 client->crypto->save.sigkey = NULL;
1277 xfree (cdata->crc);
1278 cdata->crc = NULL;
1280 /* cache_encrypt() does in-place encryption */
1281 xfree (cdata->doc);
1282 cdata->doc = client->crypto->plaintext;
1283 client->crypto->plaintext = NULL;
1284 cdata->size = client->crypto->plaintext_size;
1285 client->crypto->plaintext_size = 0;
1287 client->doc = doc;
1288 cache_plaintext_set (client->filename, client->doc, 0);
1290 /* Update in case the cache entry expires the next SAVE may
1291 * not have any known keys. */
1292 strv_free (client->crypto->pubkey);
1293 client->crypto->pubkey = NULL;
1294 if (cdata->pubkey)
1295 client->crypto->pubkey = strv_dup (cdata->pubkey);
1297 xfree (client->crypto->sigkey);
1298 client->crypto->sigkey = NULL;
1299 if (cdata->sigkey)
1300 client->crypto->sigkey = str_dup (cdata->sigkey);
1302 if (!cache_rc) // wont increment refcount
1303 rc = cache_set_data (client->filename, cdata);
1304 else
1305 rc = cache_add_file (client->filename, cdata, timeout, 0);
1308 if (!rc && (cache_rc || (client->flags & FLAG_NEW)))
1309 send_status_all (STATUS_CACHE, NULL);
1311 if (!rc)
1313 rc = update_checksum (client, crc, crclen);
1314 client->flags &= ~(FLAG_NEW);
1318 pthread_cleanup_pop (1);
1319 if (!rc)
1321 client->did_cow = 0;
1322 send_status_modified (client->ctx);
1327 crypto_free_non_keys (client->crypto);
1328 return send_error (ctx, rc);
1331 static gpg_error_t
1332 parse_genkey_opt_usage (void *data, void *v)
1334 struct client_s *client = data;
1335 char *value = v;
1337 if (!value || !*value)
1338 return GPG_ERR_INV_VALUE;
1339 else if (!strcmp (value, "sign"))
1340 client->crypto->save.flags |= GPGME_CREATE_SIGN;
1341 else if (!strcmp (value, "encrypt"))
1342 client->crypto->save.flags |= GPGME_CREATE_ENCR;
1343 else if (!strcmp (value, "default"))
1344 client->crypto->save.flags &= ~(GPGME_CREATE_ENCR|GPGME_CREATE_SIGN);
1345 else
1346 return GPG_ERR_INV_VALUE;
1348 return 0;
1351 gpg_error_t
1352 parse_genkey_opt_subkey_of (void *data, void *v)
1354 gpg_error_t rc;
1355 struct client_s *client = data;
1356 char *value = v;
1357 char *tmp[] = { value, NULL };
1358 gpgme_key_t *keys = NULL;
1360 rc = peer_is_invoker (client);
1361 if (rc)
1362 return rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc;
1364 if (!value || !*value)
1365 return GPG_ERR_INV_VALUE;
1367 rc = crypto_list_keys (client->crypto, tmp, 1, &keys);
1368 if (rc)
1369 return rc;
1371 if (!keys || !*keys)
1373 crypto_free_key_list (keys);
1374 return GPG_ERR_NO_SECKEY;
1377 client->crypto->save.mainkey = keys;
1378 return 0;
1381 static gpg_error_t
1382 genkey_command (assuan_context_t ctx, char *line)
1384 struct client_s *client = assuan_get_pointer (ctx);
1385 struct crypto_s *crypto, *orig;
1386 gpg_error_t rc = 0;
1387 struct argv_s *args[] = {
1388 &(struct argv_s) {"userid", OPTION_TYPE_ARG,
1389 parse_genkey_opt_userid},
1390 &(struct argv_s) {"expire", OPTION_TYPE_ARG,
1391 parse_genkey_opt_expire},
1392 &(struct argv_s) {"no-expire", OPTION_TYPE_NOARG,
1393 parse_genkey_opt_no_expire},
1394 &(struct argv_s) {"algo", OPTION_TYPE_ARG,
1395 parse_genkey_opt_algo},
1396 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG,
1397 parse_genkey_opt_no_passphrase},
1398 &(struct argv_s) {"usage", OPTION_TYPE_ARG,
1399 parse_genkey_opt_usage},
1400 &(struct argv_s) {"subkey-of", OPTION_TYPE_ARG,
1401 parse_genkey_opt_subkey_of},
1402 NULL
1405 if (!(client->flags & FLAG_OPEN))
1406 return send_error (ctx, GPG_ERR_INV_STATE);
1408 rc = crypto_init (&crypto, ctx, client->filename,
1409 client->flags & FLAG_NO_PINENTRY, NULL);
1410 if (rc)
1411 return send_error (ctx, rc);
1413 pthread_cleanup_push ((void *)crypto_free, client->crypto);
1414 orig = client->crypto;
1415 client->crypto = crypto;
1416 rc = parse_options (&line, args, client, 0);
1417 if (!rc)
1419 if (!client->crypto->save.userid && !client->crypto->save.mainkey)
1420 rc = GPG_ERR_SYNTAX;
1421 else
1423 client->crypto->flags |= CRYPTO_FLAG_NEWFILE;
1424 rc = crypto_genkey (client, client->crypto);
1428 pthread_cleanup_pop (0);
1429 crypto_free (crypto);
1430 client->crypto = orig;
1431 return send_error (ctx, rc);
1434 static gpg_error_t
1435 do_delete (assuan_context_t ctx, char *line)
1437 struct client_s *client = assuan_get_pointer (ctx);
1438 struct xml_request_s *req;
1439 xmlNodePtr n;
1440 gpg_error_t rc;
1442 if (!line || !*line)
1443 return GPG_ERR_SYNTAX;
1445 rc = xml_new_request (client, line, XML_CMD_DELETE, &req);
1446 if (rc)
1447 return rc;
1449 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1450 xml_free_request (req);
1451 if (rc)
1452 return rc;
1454 rc = xml_is_element_owner (client, n, 0);
1455 if (!rc)
1456 rc = xml_unlink_node (client, n);
1458 return rc;
1461 /* Won't update cdata->plaintext. Other clients are working on the original or
1462 * copy of the same document. The first client to SAVE wins and requires others
1463 * to reopen the data file due to a checksum error. */
1464 static gpg_error_t
1465 copy_on_write (struct client_s *client)
1467 struct cache_data_s *cdata;
1469 if (client->did_cow)
1470 return 0;
1472 cdata = cache_get_data (client->filename, NULL);
1473 if (cdata)
1475 gpg_error_t rc;
1476 xmlDocPtr doc = xmlCopyDoc (client->doc, 1);
1478 if (!doc)
1479 return GPG_ERR_ENOMEM;
1481 rc = cache_plaintext_set (client->filename, doc, 1);
1482 if (rc)
1484 xmlFree (doc);
1485 return rc;
1488 (void)cache_plaintext_release (&client->doc);
1489 client->doc = doc;
1490 client->did_cow = 1;
1491 return 0;
1494 return GPG_ERR_NO_DATA;
1497 static gpg_error_t
1498 delete_command (assuan_context_t ctx, char *line)
1500 struct client_s *client = assuan_get_pointer (ctx);
1501 gpg_error_t rc;
1502 struct argv_s *args[] = {
1503 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1504 NULL
1507 rc = parse_options (&line, args, client, 1);
1508 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1509 rc = GPG_ERR_SYNTAX;
1510 if (rc)
1511 return send_error (ctx, rc);
1513 rc = copy_on_write (client);
1514 if (rc)
1515 return send_error (ctx, rc);
1517 if (client->opts & OPT_INQUIRE)
1519 unsigned char *result;
1520 size_t len;
1522 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1523 if (rc)
1524 return send_error (ctx, rc);
1526 pthread_cleanup_push ((void *)xfree, result);
1527 rc = do_delete (ctx, (char *)result);
1528 pthread_cleanup_pop (1);
1530 else
1531 rc = do_delete (ctx, line);
1533 return send_error (ctx, rc);
1536 static gpg_error_t
1537 update_element_expirey (struct client_s *client, xmlNodePtr n)
1539 gpg_error_t rc = 0;
1540 xmlChar *expire, *incr;
1541 char *p;
1542 time_t e, e_orig, i;
1543 time_t now = time (NULL);
1545 expire = xml_attribute_value (n, (xmlChar *)"_expire");
1546 if (!expire)
1547 return 0;
1549 errno = 0;
1550 e = strtoul ((char *)expire, &p, 10);
1551 if (errno || *p || e == ULONG_MAX || *expire == '-')
1553 xmlFree (expire);
1554 rc = GPG_ERR_ERANGE;
1555 goto fail;
1558 xmlFree (expire);
1559 incr = xml_attribute_value (n, (xmlChar *)"_age");
1560 if (!incr)
1561 return 0;
1563 i = strtoul ((char *)incr, &p, 10);
1564 if (errno || *p || i == ULONG_MAX || *incr == '-')
1566 xmlFree (incr);
1567 rc = GPG_ERR_ERANGE;
1568 goto fail;
1571 xmlFree (incr);
1572 e_orig = e;
1573 e = now + i;
1574 p = str_asprintf ("%lu", e);
1575 if (!p)
1577 rc = GPG_ERR_ENOMEM;
1578 goto fail;
1581 rc = xml_add_attribute (client, n, "_expire", p);
1582 xfree (p);
1583 if (!rc)
1584 rc = send_status (client->ctx, STATUS_EXPIRE, "%lu %lu", e_orig, e);
1586 fail:
1587 return rc;
1590 static gpg_error_t
1591 parse_opt_store_no_acl_inherit (void *data, void *value)
1593 struct client_s *client = data;
1595 (void)value;
1596 client->opts |= OPT_NO_INHERIT_ACL;
1597 return 0;
1600 static gpg_error_t
1601 store_command (assuan_context_t ctx, char *line)
1603 struct client_s *client = assuan_get_pointer (ctx);
1604 gpg_error_t rc;
1605 size_t len;
1606 unsigned char *result;
1607 xmlNodePtr n, parent;
1608 int has_content;
1609 char *content = NULL;
1610 struct xml_request_s *req;
1611 struct argv_s *args[] = {
1612 &(struct argv_s) {"no-inherit-acl", OPTION_TYPE_NOARG,
1613 parse_opt_store_no_acl_inherit},
1614 NULL
1617 rc = parse_options (&line, args, client, 1);
1618 if (rc)
1619 return send_error (ctx, rc);
1621 if (!client->bulk_p && line && *line)
1622 return send_error (ctx, GPG_ERR_SYNTAX);
1624 rc = copy_on_write (client);
1625 if (rc)
1626 return send_error (ctx, rc);
1628 if (!client->bulk_p)
1630 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1631 if (rc)
1632 return send_error (ctx, rc);
1633 rc = xml_new_request (client, (char *)result, XML_CMD_STORE, &req);
1634 if (!result || !*result)
1636 xfree (result);
1637 return send_error (ctx, GPG_ERR_SYNTAX);
1640 len = strv_length (req->args);
1641 has_content = result[strlen ((char *)result) - 1] != '\t' && len > 1;
1642 xfree (result);
1644 else
1646 rc = xml_new_request (client, line, XML_CMD_STORE, &req);
1647 len = strv_length (req->args);
1648 has_content = line && line[strlen (line) - 1] != '\t' && len > 1;
1651 if (rc)
1652 return send_error (ctx, rc);
1654 /* Prevent passing the element content around to save some memory
1655 * (has_content). */
1656 if (*(req->args+1) && !xml_valid_element_path (req->args, has_content))
1658 xml_free_request (req);
1659 return send_error (ctx, GPG_ERR_INV_VALUE);
1662 if (has_content || !*req->args[len-1])
1664 content = req->args[len-1];
1665 req->args[len-1] = NULL;
1668 if (strv_length (req->args) > 1)
1670 rc = xml_check_recursion (client, req);
1671 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
1672 goto fail;
1675 parent = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1677 if (!rc && len > 1)
1679 rc = xml_is_element_owner (client, parent, 0);
1680 if (!rc)
1682 n = xml_find_text_node (parent->children);
1683 if (n)
1684 xmlNodeSetContent (n, (xmlChar *) content);
1685 else
1686 xmlNodeAddContent (parent, (xmlChar *) content);
1688 (void)xml_update_element_mtime (client, parent);
1689 (void)update_element_expirey (client, parent);
1693 fail:
1694 xfree (content);
1695 xml_free_request (req);
1696 return send_error (ctx, rc);
1699 static gpg_error_t
1700 xfer_data (assuan_context_t ctx, const char *line, int total)
1702 struct client_s *client = assuan_get_pointer (ctx);
1703 int to_send = total < ASSUAN_LINELENGTH ? total : ASSUAN_LINELENGTH;
1704 int sent = 0;
1705 gpg_error_t rc = 0;
1707 if (!(client->flags & FLAG_LOCK_CMD))
1708 rc = unlock_file_mutex (client, 0);
1709 if (rc && rc != GPG_ERR_NOT_LOCKED)
1710 return rc;
1712 if (client->bulk_p)
1714 client->bulk_p->result = xmalloc (total+1);
1715 if (!client->bulk_p->result)
1716 return GPG_ERR_ENOMEM;
1717 memcpy (client->bulk_p->result, line, total);
1718 client->bulk_p->result[total] = 0;
1719 client->bulk_p->result_len = total;
1720 return 0;
1723 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1724 if (rc)
1725 return rc;
1729 if (sent + to_send > total)
1730 to_send = total - sent;
1732 rc = assuan_send_data (ctx, (char *) line + sent, to_send);
1733 if (!rc)
1734 sent += to_send;
1736 while (!rc && sent < total);
1738 return rc;
1741 static gpg_error_t
1742 do_get (assuan_context_t ctx, char *line)
1744 struct client_s *client = assuan_get_pointer (ctx);
1745 gpg_error_t rc;
1746 struct xml_request_s *req;
1747 xmlNodePtr n;
1749 if (!line || !*line)
1750 return GPG_ERR_SYNTAX;
1752 rc = xml_new_request (client, line, XML_CMD_NONE, &req);
1753 if (rc)
1754 return rc;
1756 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1757 if (!rc)
1759 if (n && n->children)
1761 xmlNodePtr tmp = n;
1763 n = xml_find_text_node (n->children);
1764 if (!n || !n->content || !*n->content)
1765 rc = GPG_ERR_NO_DATA;
1766 else
1768 rc = xfer_data (ctx, (char *) n->content, xmlStrlen (n->content));
1769 if (!rc)
1771 xmlChar *expire = xml_attribute_value (tmp,
1772 (xmlChar *)"_expire");
1773 if (expire)
1775 time_t now = time (NULL);
1776 time_t e;
1777 char *p;
1779 errno = 0;
1780 e = strtoul ((char *)expire, &p, 10);
1781 if (errno || *p || e == ULONG_MAX || *expire == '-')
1782 log_write (_("invalid expire attribute value: %s"),
1783 expire);
1784 else if (now >= e)
1786 pthread_cleanup_push (xmlFree, expire);
1787 rc = send_status (ctx, STATUS_EXPIRE, "%lu 0", e);
1788 pthread_cleanup_pop (0);
1791 xmlFree (expire);
1796 else
1797 rc = GPG_ERR_NO_DATA;
1800 xml_free_request (req);
1801 return rc;
1804 static gpg_error_t
1805 get_command (assuan_context_t ctx, char *line)
1807 struct client_s *client = assuan_get_pointer (ctx);
1808 gpg_error_t rc;
1809 struct argv_s *args[] = {
1810 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1811 NULL
1814 rc = parse_options (&line, args, client, 1);
1815 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1816 rc = GPG_ERR_SYNTAX;
1817 if (rc)
1818 return send_error (ctx, rc);
1820 if (client->opts & OPT_INQUIRE)
1822 unsigned char *result;
1823 size_t len;
1825 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1826 if (rc)
1827 return send_error (ctx, rc);
1829 pthread_cleanup_push ((void *)xfree, result);
1830 rc = do_get (ctx, (char *)result);
1831 pthread_cleanup_pop (1);
1833 else
1834 rc = do_get (ctx, line);
1836 return send_error (ctx, rc);
1839 static void list_command_free1 (void *arg);
1840 static gpg_error_t
1841 realpath_command (assuan_context_t ctx, char *line)
1843 gpg_error_t rc;
1844 char **realpath = NULL;
1845 struct client_s *client = assuan_get_pointer (ctx);
1846 struct argv_s *args[] = {
1847 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1848 NULL
1851 rc = parse_options (&line, args, client, 1);
1852 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1853 rc = GPG_ERR_SYNTAX;
1854 if (rc)
1855 return send_error (ctx, rc);
1857 if (client->opts & OPT_INQUIRE)
1859 unsigned char *result;
1860 size_t len;
1862 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1863 if (rc)
1864 return send_error (ctx, rc);
1866 pthread_cleanup_push ((void *)xfree, result);
1867 (void)xml_resolve_path (client, client->doc, result, &realpath, &rc);
1868 pthread_cleanup_pop (1);
1870 else
1871 (void)xml_resolve_path (client, client->doc, (unsigned char *)line,
1872 &realpath, &rc);
1874 if (!rc)
1876 char *tmp = strv_join ((char *)"\t", realpath);
1878 strv_free (realpath);
1879 if (!tmp)
1880 return send_error (ctx, GPG_ERR_ENOMEM);
1882 pthread_cleanup_push ((void *)xfree, tmp);
1883 rc = xfer_data (ctx, tmp, strlen (tmp));
1884 pthread_cleanup_pop (1);
1887 return send_error (ctx, rc);
1890 static void
1891 list_command_free1 (void *arg)
1893 if (arg)
1894 string_free ((struct string_s *) arg, 1);
1897 static gpg_error_t
1898 parse_list_opt_recurse (void *data, void *value)
1900 struct client_s *client = data;
1902 (void)value;
1903 client->opts |= OPT_LIST_RECURSE;
1904 return 0;
1907 static gpg_error_t
1908 parse_opt_verbose (void *data, void *value)
1910 struct client_s *client = data;
1912 (void)value;
1913 client->opts |= OPT_VERBOSE;
1914 return 0;
1917 static gpg_error_t
1918 parse_opt_sexp (void *data, void *value)
1920 struct client_s *client = data;
1922 (void)value;
1923 client->opts |= OPT_SEXP;
1924 return 0;
1927 static gpg_error_t
1928 list_path_once (struct client_s *client, char *line,
1929 struct element_list_s *elements, struct string_s *result)
1931 gpg_error_t rc;
1933 rc = xml_create_path_list (client, client->doc, NULL, elements, line, 0);
1934 if (rc == GPG_ERR_ELOOP || rc == GPG_ERR_EACCES)
1935 rc = 0;
1937 if (!rc)
1939 int total = slist_length (elements->list);
1941 if (total)
1943 int i;
1945 for (i = 0; i < total; i++)
1947 char *tmp = slist_nth_data (elements->list, i);
1949 string_append_printf (result, "%s%s", tmp,
1950 i + 1 == total ? "" : "\n");
1953 else
1954 rc = GPG_ERR_NO_DATA;
1957 return rc;
1960 #define RESUMABLE_ERROR(rc) (rc == GPG_ERR_ELOOP || rc == GPG_ERR_EACCES \
1961 || rc == GPG_ERR_ELEMENT_NOT_FOUND || !rc)
1962 static gpg_error_t
1963 attribute_list_common (struct client_s *client, const char *path,
1964 char ***result)
1966 char **attrlist = NULL;
1967 int i = 0;
1968 int target = 0;
1969 xmlAttrPtr a;
1970 xmlNodePtr n, an, r;
1971 gpg_error_t rc;
1972 struct xml_request_s *req;
1974 rc = xml_new_request (client, path, XML_CMD_ATTR_LIST, &req);
1975 if (rc)
1976 return rc;
1978 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1979 xml_free_request (req);
1980 if (rc)
1981 return rc;
1983 gpg_error_t acl_rc = 0;
1984 again:
1985 acl_rc = xml_acl_check (client, n);
1986 for (a = n->properties; a; a = a->next)
1988 char **pa;
1989 int reserved = xml_reserved_attribute ((char *)a->name);
1991 if (acl_rc == GPG_ERR_EACCES && !reserved)
1992 continue;
1993 else if (acl_rc && acl_rc != GPG_ERR_EACCES)
1995 rc = acl_rc;
1996 break;
1999 if (reserved && target)
2000 continue;
2002 pa = xrealloc (attrlist, (i + 2) * sizeof (char *));
2003 if (!pa)
2005 log_write ("%s(%i): %s", __FILE__, __LINE__,
2006 pwmd_strerror (GPG_ERR_ENOMEM));
2007 rc = GPG_ERR_ENOMEM;
2008 break;
2011 attrlist = pa;
2012 an = a->children;
2013 attrlist[i] = str_asprintf ("%s %s", (char *) a->name, an && an->content
2014 ? (char *)an->content : "");
2016 if (!attrlist[i])
2018 log_write ("%s(%i): %s", __FILE__, __LINE__,
2019 pwmd_strerror (GPG_ERR_ENOMEM));
2020 rc = GPG_ERR_ENOMEM;
2021 break;
2024 attrlist[++i] = NULL;
2027 if (!rc && !attrlist)
2028 return GPG_ERR_NO_DATA;
2030 if (!rc && !target)
2032 r = xml_resolve_path (client, client->doc, (xmlChar *)path, NULL, &rc);
2033 if (RESUMABLE_ERROR (rc))
2035 rc = 0;
2036 if (r && r != n)
2038 target = 1;
2039 n = r;
2040 goto again;
2045 if (!rc)
2046 *result = attrlist;
2047 else
2048 strv_free (attrlist);
2050 return rc;
2053 static gpg_error_t
2054 create_list_sexp (struct client_s *client, struct string_s *string,
2055 struct string_s **r_string)
2057 struct string_s *str = string;
2058 gpg_error_t rc = 0;
2059 struct string_s *result = string_new ("(11:list-result");
2060 char **strv = str_split (str->str, "\n", 0);
2061 int t = strv_length (strv);
2062 int i;
2064 string_large (result);
2066 for (i = 0; i < t; i++)
2068 char **tmpv = str_split (strv[i], " ", 0);
2069 char **attrlist = NULL;
2071 result = string_append_printf (result, "(4:path%i:%s", strlen (tmpv[0]),
2072 tmpv[0]);
2073 if (tmpv[1])
2074 result = string_append_printf (result, "5:flags%i:%s", strlen (tmpv[1]),
2075 tmpv[1]);
2076 else
2077 result = string_append (result, "5:flags0:");
2079 rc = attribute_list_common (client, tmpv[0], &attrlist);
2080 if (!rc)
2082 int ai;
2083 int at = strv_length (attrlist);
2085 result = string_append (result, "(5:attrs");
2087 for (ai = 0; ai < at; ai++)
2089 char **attrv = str_split (attrlist[ai], " ", 0);
2090 char *value = strv_join (" ", attrv+1);
2092 result = string_append_printf (result, "%i:%s%i:%s",
2093 strlen (attrv[0]), attrv[0],
2094 strlen (value), value);
2095 strv_free (attrv);
2096 xfree (value);
2099 result = string_append (result, ")");
2102 result = string_append (result, ")");
2103 strv_free (attrlist);
2104 strv_free (tmpv);
2107 strv_free (strv);
2108 result = string_append (result, ")");
2109 if (!rc)
2110 *r_string = result;
2112 return rc;
2115 static gpg_error_t
2116 do_list (assuan_context_t ctx, char *line)
2118 struct client_s *client = assuan_get_pointer (ctx);
2119 gpg_error_t rc = GPG_ERR_NO_DATA;
2120 struct element_list_s *elements = NULL;
2121 struct string_s *result = NULL;
2123 if (!line || !*line)
2125 struct string_s *str = string_new (NULL);
2126 xmlNodePtr n;
2128 if (!str)
2129 return GPG_ERR_ENOMEM;
2131 string_large (str);
2132 pthread_cleanup_push ((void *)list_command_free1, str);
2133 n = xmlDocGetRootElement (client->doc);
2134 for (n = n->children; n; n = n->next)
2136 xmlChar *name;
2138 if (n->type != XML_ELEMENT_NODE)
2139 continue;
2141 name = xmlGetProp (n, (xmlChar *)"_name");
2142 if (!name)
2144 rc = GPG_ERR_ENOMEM;
2145 break;
2148 elements = xcalloc (1, sizeof (struct element_list_s));
2149 if (!elements)
2151 xmlFree (name);
2152 rc = GPG_ERR_ENOMEM;
2153 break;
2156 elements->prefix = string_new (NULL);
2157 if (!elements->prefix)
2159 xmlFree (name);
2160 xml_free_element_list (elements);
2161 rc = GPG_ERR_ENOMEM;
2162 break;
2165 elements->recurse = client->opts & OPT_LIST_RECURSE;
2166 elements->root_only = !elements->recurse;
2167 pthread_cleanup_push ((void *)xml_free_element_list, elements);
2168 rc = list_path_once (client, (char *)name, elements, str);
2169 xmlFree (name);
2170 pthread_cleanup_pop (1);
2171 if (rc)
2172 break;
2174 if (n->next)
2175 string_append (str, "\n");
2178 if (!rc)
2180 if (client->opts & OPT_SEXP)
2182 rc = create_list_sexp (client, str, &result);
2183 if (!rc)
2185 pthread_cleanup_push ((void *)list_command_free1, result);
2186 rc = xfer_data (ctx, result->str, result->len);
2187 pthread_cleanup_pop (1);
2190 else
2191 rc = xfer_data (ctx, str->str, str->len);
2194 pthread_cleanup_pop (1);
2195 return rc;
2198 elements = xcalloc (1, sizeof (struct element_list_s));
2199 if (!elements)
2200 return GPG_ERR_ENOMEM;
2202 elements->prefix = string_new (NULL);
2203 if (!elements->prefix)
2205 xml_free_element_list (elements);
2206 return GPG_ERR_ENOMEM;
2209 elements->recurse = client->opts & OPT_LIST_RECURSE;
2210 pthread_cleanup_push ((void *)xml_free_element_list, elements);
2211 struct string_s *str = string_new (NULL);
2212 string_large (str);
2213 pthread_cleanup_push ((void *)list_command_free1, str);
2214 rc = list_path_once (client, line, elements, str);
2215 if (!rc)
2217 if (client->opts & OPT_SEXP)
2219 rc = create_list_sexp (client, str, &result);
2220 if (!rc)
2222 pthread_cleanup_push ((void *)list_command_free1, result);
2223 rc = xfer_data (ctx, result->str, result->len);
2224 pthread_cleanup_pop (1);
2227 else
2228 rc = xfer_data (ctx, str->str, str->len);
2231 pthread_cleanup_pop (1);
2232 pthread_cleanup_pop (1);
2233 return rc;
2236 static gpg_error_t
2237 list_command (assuan_context_t ctx, char *line)
2239 struct client_s *client = assuan_get_pointer (ctx);
2240 gpg_error_t rc;
2241 struct argv_s *args[] = {
2242 &(struct argv_s) {"recurse", OPTION_TYPE_NOARG, parse_list_opt_recurse},
2243 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2244 /* These are deprecated but kept for backward compatibility with older
2245 * clients. */
2246 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, NULL},
2247 &(struct argv_s) {"with-target", OPTION_TYPE_NOARG, NULL},
2248 &(struct argv_s) {"all", OPTION_TYPE_NOARG, parse_list_opt_recurse},
2249 &(struct argv_s) {"no-recurse", OPTION_TYPE_NOARG, NULL},
2250 &(struct argv_s) {"sexp", OPTION_TYPE_NOARG, parse_opt_sexp},
2251 NULL
2254 if (disable_list_and_dump == 1)
2255 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2257 rc = parse_options (&line, args, client, 1);
2258 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2259 rc = GPG_ERR_SYNTAX;
2260 if (rc)
2261 return send_error (ctx, rc);
2263 if (client->opts & OPT_INQUIRE)
2265 unsigned char *result;
2266 size_t len;
2268 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2269 if (rc)
2270 return send_error (ctx, rc);
2272 pthread_cleanup_push ((void *)xfree, result);
2273 rc = do_list (ctx, (char *)result);
2274 pthread_cleanup_pop (1);
2276 else
2277 rc = do_list (ctx, line);
2279 return send_error (ctx, rc);
2283 * args[0] - element path
2285 static gpg_error_t
2286 attribute_list (assuan_context_t ctx, char **args)
2288 struct client_s *client = assuan_get_pointer (ctx);
2289 char **attrlist = NULL;
2290 gpg_error_t rc;
2291 char *line;
2293 if (!args || !args[0] || !*args[0])
2294 return GPG_ERR_SYNTAX;
2296 rc = attribute_list_common (client, args[0], &attrlist);
2297 pthread_cleanup_push ((void *)req_free, attrlist);
2299 if (!rc)
2301 line = strv_join ("\n", attrlist);
2302 if (line)
2304 pthread_cleanup_push ((void *)xfree, line);
2305 rc = xfer_data (ctx, line, strlen (line));
2306 pthread_cleanup_pop (1);
2308 else
2310 log_write ("%s(%i): %s", __FILE__, __LINE__,
2311 pwmd_strerror (GPG_ERR_ENOMEM));
2312 rc = GPG_ERR_ENOMEM;
2316 pthread_cleanup_pop (1);
2317 return rc;
2321 * args[0] - attribute
2322 * args[1] - element path
2324 static gpg_error_t
2325 attribute_delete (struct client_s *client, char **args)
2327 gpg_error_t rc;
2328 xmlNodePtr n;
2330 if (!args || !args[0] || !*args[0] || !args[1] || !*args[1])
2331 return GPG_ERR_SYNTAX;
2333 rc = xml_protected_attr (args[0]);
2334 if (rc || !strcmp (args[0], "_target"))
2335 return rc ? rc : GPG_ERR_EPERM;
2337 rc = copy_on_write (client);
2338 if (rc)
2339 return rc;
2341 if (!xml_reserved_attribute (args[0]))
2342 n = xml_resolve_path (client, client->doc, (xmlChar *)args[1], NULL, &rc);
2343 else
2345 struct xml_request_s *req;
2347 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
2348 if (rc)
2349 return rc;
2351 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2352 xml_free_request (req);
2355 if (!rc)
2356 rc = xml_is_element_owner (client, n, 0);
2358 if (!rc)
2359 rc = xml_delete_attribute (client, n, (xmlChar *) args[0]);
2361 return rc;
2365 * Creates the "_target" attribute. When other commands encounter an element
2366 * with this attribute they follow the "_target" after appending remaining
2367 * elements from the original element path to the target. The exception is the
2368 * ATTR command that operates on the element itself (for reserved attribute
2369 * names) and not the target.
2371 * If the source element path doesn't exist when using 'ATTR SET target', it is
2372 * created, but the destination element path must exist. This is similar to the
2373 * ls(1) command: ln -s src dst.
2375 * args[0] - source element path
2376 * args[1] - destination element path
2378 static gpg_error_t
2379 set_target_attribute (struct client_s *client, char **args)
2381 struct xml_request_s *req = NULL;
2382 char **src, **dst;
2383 gpg_error_t rc;
2384 xmlNodePtr n;
2386 if (!args || !args[0] || !args[1])
2387 return GPG_ERR_SYNTAX;
2389 src = str_split (args[0], "\t", 0);
2390 if (!src)
2391 return GPG_ERR_SYNTAX;
2393 if (!xml_valid_element_path (src, 0))
2395 strv_free (src);
2396 return GPG_ERR_INV_VALUE;
2399 dst = str_split (args[1], "\t", 0);
2400 if (!dst)
2402 strv_free (src);
2403 return GPG_ERR_SYNTAX;
2406 rc = copy_on_write (client);
2407 if (rc)
2408 goto fail;
2410 // Be sure the destination element path exists. */
2411 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
2412 if (rc)
2413 goto fail;
2415 (void)xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2416 if (rc && rc != GPG_ERR_EACCES)
2417 goto fail;
2419 xml_free_request (req);
2420 req = NULL;
2422 if (!strcmp (args[0], args[1]))
2424 rc = GPG_ERR_EEXIST;
2425 goto fail;
2428 rc = xml_new_request (client, args[0], XML_CMD_ATTR_TARGET, &req);
2429 if (rc)
2430 goto fail;
2432 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2433 if (rc && rc != GPG_ERR_EACCES)
2434 goto fail;
2436 if (!rc)
2438 rc = xml_add_attribute (client, n, "_target", args[1]);
2439 if (!rc)
2441 rc = xml_remove_user_attributes (client, n);
2442 if (!rc)
2443 rc = xml_unlink_node (client, n->children);
2447 fail:
2448 strv_free (src);
2449 strv_free (dst);
2450 xml_free_request (req);
2451 return rc;
2455 * args[0] - attribute
2456 * args[1] - element path
2458 static gpg_error_t
2459 attribute_get (assuan_context_t ctx, char **args)
2461 struct client_s *client = assuan_get_pointer (ctx);
2462 xmlNodePtr n;
2463 xmlChar *a;
2464 gpg_error_t rc;
2465 struct xml_request_s *req;
2467 if (!args || !args[0] || !*args[0] || !args[1] || !*args[1])
2468 return GPG_ERR_SYNTAX;
2470 if (!xml_reserved_attribute (args[0]))
2471 n = xml_resolve_path (client, client->doc, (xmlChar *)args[1], NULL, &rc);
2472 else
2474 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
2475 if (rc)
2476 return rc;
2478 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2479 xml_free_request (req);
2482 if (rc)
2483 return rc;
2485 a = xmlGetProp (n, (xmlChar *) args[0]);
2486 if (!a)
2487 return GPG_ERR_NOT_FOUND;
2489 pthread_cleanup_push ((void *)xmlFree, a);
2491 if (*a)
2492 rc = xfer_data (ctx, (char *) a, xmlStrlen (a));
2493 else
2494 rc = GPG_ERR_NO_DATA;
2496 pthread_cleanup_pop (1);
2497 return rc;
2501 * args[0] - attribute
2502 * args[1] - element path
2503 * args[2] - value
2505 static gpg_error_t
2506 attribute_set (struct client_s *client, char **args)
2508 struct xml_request_s *req;
2509 gpg_error_t rc;
2510 xmlNodePtr n;
2512 if (!args || !args[0] || !args[1])
2513 return GPG_ERR_SYNTAX;
2516 * Reserved attribute names.
2518 if ((rc = xml_protected_attr (args[0])))
2519 return rc;
2520 else if (!strcmp (args[0], "_target"))
2521 return set_target_attribute (client, args + 1);
2522 else if (!strcmp (args[0], "_acl"))
2523 rc = xml_valid_username (args[2]);
2524 else if (!xml_valid_attribute (args[0]))
2525 return GPG_ERR_INV_VALUE;
2527 if (rc)
2528 return rc;
2530 if (!xml_valid_attribute_value (args[2]))
2531 return GPG_ERR_INV_VALUE;
2533 rc = copy_on_write (client);
2534 if (rc)
2535 return rc;
2537 if (!xml_reserved_attribute (args[0]))
2539 n = xml_resolve_path (client, client->doc, (xmlChar *)args[1], NULL, &rc);
2540 if (!rc)
2542 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
2543 if (!rc)
2545 rc = xml_check_recursion (client, req);
2546 xml_free_request (req);
2550 else
2552 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
2553 if (rc)
2554 return rc;
2556 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2557 xml_free_request (req);
2560 if (!rc)
2561 rc = xml_is_element_owner (client, n, 0);
2563 if (!rc)
2564 rc = xml_add_attribute (client, n, args[0], args[2]);
2566 return rc;
2570 * req[0] - command
2571 * req[1] - attribute name or element path if command is LIST
2572 * req[2] - element path
2573 * req[2] - element path or value
2576 static gpg_error_t
2577 do_attr (assuan_context_t ctx, char *line)
2579 struct client_s *client = assuan_get_pointer (ctx);
2580 gpg_error_t rc = 0;
2581 char **req;
2583 if (!line || !*line)
2584 return GPG_ERR_SYNTAX;
2586 req = str_split (line, " ", 4);
2587 if (!req || !req[0] || !req[1])
2589 strv_free (req);
2590 return GPG_ERR_SYNTAX;
2593 pthread_cleanup_push ((void *)req_free, req);
2595 if (strcasecmp (req[0], "SET") == 0)
2596 rc = attribute_set (client, req + 1);
2597 else if (strcasecmp (req[0], "GET") == 0)
2598 rc = attribute_get (ctx, req + 1);
2599 else if (strcasecmp (req[0], "DELETE") == 0)
2600 rc = attribute_delete (client, req + 1);
2601 else if (strcasecmp (req[0], "LIST") == 0)
2602 rc = attribute_list (ctx, req + 1);
2603 else
2604 rc = GPG_ERR_SYNTAX;
2606 client->flags &= ~(FLAG_ACL_IGNORE|FLAG_ACL_ERROR);
2607 pthread_cleanup_pop (1);
2608 return rc;
2611 static gpg_error_t
2612 attr_command (assuan_context_t ctx, char *line)
2614 struct client_s *client = assuan_get_pointer (ctx);
2615 gpg_error_t rc;
2616 struct argv_s *args[] = {
2617 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2618 NULL
2621 rc = parse_options (&line, args, client, 1);
2622 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2623 rc = GPG_ERR_SYNTAX;
2624 if (rc)
2625 return send_error (ctx, rc);
2627 if (client->opts & OPT_INQUIRE)
2629 unsigned char *result;
2630 size_t len;
2632 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2633 if (rc)
2634 return send_error (ctx, rc);
2636 pthread_cleanup_push ((void *)xfree, result);
2637 rc = do_attr (ctx, (char *)result);
2638 pthread_cleanup_pop (1);
2640 else
2641 rc = do_attr (ctx, line);
2643 return send_error (ctx, rc);
2646 static gpg_error_t
2647 parse_iscached_opt_lock (void *data, void *value)
2649 struct client_s *client = data;
2651 (void) value;
2652 client->opts |= OPT_LOCK;
2653 return 0;
2656 static gpg_error_t
2657 parse_iscached_opt_agent (void *data, void *value)
2659 struct client_s *client = data;
2661 (void) value;
2662 client->opts |= OPT_CACHE_AGENT;
2663 return 0;
2666 static gpg_error_t
2667 parse_iscached_opt_sign (void *data, void *value)
2669 struct client_s *client = data;
2671 (void) value;
2672 client->opts |= OPT_CACHE_SIGN;
2673 return 0;
2676 static gpg_error_t
2677 iscached_command (assuan_context_t ctx, char *line)
2679 struct client_s *client = assuan_get_pointer (ctx);
2680 gpg_error_t rc;
2681 int defer = 0;
2682 struct argv_s *args[] = {
2683 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_iscached_opt_lock},
2684 &(struct argv_s) {"agent", OPTION_TYPE_NOARG, parse_iscached_opt_agent},
2685 &(struct argv_s) {"sign", OPTION_TYPE_NOARG, parse_iscached_opt_sign},
2686 NULL
2689 if (!line || !*line)
2690 return send_error (ctx, GPG_ERR_SYNTAX);
2692 rc = parse_options (&line, args, client, 1);
2693 if (rc)
2694 return send_error (ctx, rc);
2695 else if (!valid_filename (line))
2696 return send_error (ctx, GPG_ERR_INV_VALUE);
2698 if (!(client->flags & FLAG_OPEN)
2699 && ((client->opts & OPT_CACHE_AGENT) || (client->opts & OPT_CACHE_SIGN)))
2700 return send_error (ctx, GPG_ERR_INV_STATE);
2702 rc = cache_iscached (line, &defer, (client->opts & OPT_CACHE_AGENT),
2703 (client->opts & OPT_CACHE_SIGN));
2704 if (!rc && defer)
2705 rc = GPG_ERR_NO_DATA;
2707 if (!rc)
2709 struct cache_data_s *cdata = cache_get_data (line, NULL);
2711 if (cdata)
2713 rc = validate_checksum (client, line, cdata, NULL, NULL, 1);
2714 if (rc == GPG_ERR_CHECKSUM)
2715 rc = GPG_ERR_NO_DATA;
2719 if (client->opts & OPT_LOCK
2720 && (!rc || gpg_err_code (rc) == GPG_ERR_NO_DATA
2721 || gpg_err_code (rc) == GPG_ERR_ENOENT))
2723 gpg_error_t trc = rc;
2725 if (client->filename && strcmp (line, client->filename))
2726 reset_client (client);
2728 xfree (client->filename);
2729 client->filename = str_dup (line);
2730 rc = do_lock (client, 1);
2731 if (!rc)
2732 rc = trc;
2735 return send_error (ctx, rc);
2738 static gpg_error_t
2739 clearcache_command (assuan_context_t ctx, char *line)
2741 struct client_s *client = assuan_get_pointer (ctx);
2742 gpg_error_t rc = 0, all_rc = 0;
2743 int i;
2744 int t;
2745 int all = 0;
2746 struct client_thread_s *once = NULL;
2747 unsigned count;
2749 cache_lock ();
2750 pthread_cleanup_push (cache_unlock, NULL);
2751 count = cache_file_count ();
2752 MUTEX_LOCK (&cn_mutex);
2753 pthread_cleanup_push ((void *)release_mutex_cb, &cn_mutex);
2755 if (!line || !*line)
2756 all = 1;
2758 t = slist_length (cn_thread_list);
2760 for (i = 0; i < t; i++)
2762 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2763 assuan_peercred_t peer;
2765 if (!thd->cl)
2766 continue;
2768 /* Lock each connected clients' file mutex to prevent any other client
2769 * from accessing the cache entry (the file mutex is locked upon
2770 * command startup). The cache for the entry is not cleared if the
2771 * file mutex is locked by another client to prevent this function
2772 * from blocking. Rather, it returns an error.
2774 if (all)
2776 if (thd->cl->filename)
2778 rc = do_validate_peer (ctx, thd->cl->filename, &peer, NULL);
2779 /* The current client doesn't have permission to open the other
2780 * filename do to "access" configuration parameter in a filename
2781 * section. Since we are clearning all cache entries the error
2782 * will be returned later during cache_clear(). */
2783 if (rc)
2785 rc = 0;
2786 continue;
2789 else // Idle client without opened file?
2790 continue;
2792 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->filename, -1, 0, -1);
2793 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2795 /* The current client owns the lock. */
2796 if (pthread_equal (pthread_self (), thd->tid))
2797 rc = 0;
2798 else
2800 if (cache_iscached (thd->cl->filename, NULL, 0, 0)
2801 == GPG_ERR_NO_DATA)
2803 rc = 0;
2804 continue;
2807 /* The cache entry will be cleared when the other client
2808 * disconnects and cache_timer_thread() does its thing. */
2809 cache_defer_clear (thd->cl->filename);
2812 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
2814 rc = 0;
2815 continue;
2818 if (!rc)
2820 rc = cache_clear (NULL, thd->cl->filename, 1, 0);
2821 cache_unlock_mutex (thd->cl->filename, 0);
2824 if (rc)
2825 all_rc = rc;
2827 rc = 0;
2829 else
2831 /* A single data filename was specified. Lock only this data file
2832 * mutex and free the cache entry. */
2833 rc = do_validate_peer (ctx, line, &peer, NULL);
2834 if (rc == GPG_ERR_FORBIDDEN)
2835 rc = peer_is_invoker (client);
2837 if (rc == GPG_ERR_EACCES)
2838 rc = GPG_ERR_FORBIDDEN;
2840 if (!rc && thd->cl->filename && !strcmp (thd->cl->filename , line))
2842 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->filename, -1, 0, -1);
2843 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2845 /* The current client owns the lock. */
2846 if (pthread_equal (pthread_self (), thd->tid))
2847 rc = 0;
2850 if (!rc)
2852 once = thd;
2853 rc = cache_clear (NULL, thd->cl->filename, 1, 0);
2854 cache_unlock_mutex (thd->cl->filename, 0);
2856 else
2857 cache_defer_clear (thd->cl->filename);
2859 /* Found a client with the opened file. The cache entry has been
2860 * either cleared (self) or deferred to be cleared. */
2861 break;
2866 /* Only connected clients' cache entries have been cleared. Now clear any
2867 * remaining cache entries without clients but only if there wasn't an
2868 * error from above since this would defeat the locking check of the
2869 * remaining entries. */
2870 if (all && !all_rc && cache_file_count ())
2872 rc = cache_clear (client, NULL, 1, 0);
2873 if (rc == GPG_ERR_EACCES)
2874 rc = GPG_ERR_FORBIDDEN;
2877 /* No clients are using the specified file. */
2878 else if (!all_rc && !rc && !once)
2879 rc = cache_clear (NULL, line, 1, 0);
2881 /* Release the connection mutex. */
2882 pthread_cleanup_pop (1);
2884 if (!rc || (cache_file_count () && count != cache_file_count ()))
2885 send_status_all (STATUS_CACHE, NULL);
2887 /* Release the cache mutex. */
2888 pthread_cleanup_pop (1);
2890 /* One or more files were locked while clearing all cache entries. */
2891 if (all_rc)
2892 rc = all_rc;
2894 return send_error (ctx, rc);
2897 static gpg_error_t
2898 cachetimeout_command (assuan_context_t ctx, char *line)
2900 struct client_s *client = assuan_get_pointer (ctx);
2901 long timeout;
2902 char **req = str_split (line, " ", 0);
2903 char *p;
2904 gpg_error_t rc = 0;
2906 if (!(client->flags & FLAG_OPEN))
2907 return send_error (ctx, GPG_ERR_INV_STATE);
2909 if (!req || !*req || strv_length (req) > 1)
2911 strv_free (req);
2912 return send_error (ctx, GPG_ERR_SYNTAX);
2915 errno = 0;
2916 timeout = strtol (req[0], &p, 10);
2917 if (errno != 0 || *p || timeout < (long)-1)
2918 rc = GPG_ERR_SYNTAX;
2920 if (!rc)
2922 rc = cache_set_timeout (client->filename, timeout);
2923 if (!rc || gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
2925 rc = 0;
2926 MUTEX_LOCK (&rcfile_mutex);
2927 config_set_long_param (&global_config, client->filename,
2928 "cache_timeout", req[0]);
2929 MUTEX_UNLOCK (&rcfile_mutex);
2933 strv_free (req);
2934 return send_error (ctx, rc);
2937 static gpg_error_t
2938 dump_command (assuan_context_t ctx, char *line)
2940 xmlChar *xml;
2941 int len;
2942 struct client_s *client = assuan_get_pointer (ctx);
2943 gpg_error_t rc;
2945 if (disable_list_and_dump == 1)
2946 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2948 if (line && *line)
2949 return send_error (ctx, GPG_ERR_SYNTAX);
2951 rc = peer_is_invoker(client);
2952 if (rc)
2953 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
2955 xmlDocDumpFormatMemory (client->doc, &xml, &len, 1);
2957 if (!xml)
2959 log_write ("%s(%i): %s", __FILE__, __LINE__,
2960 pwmd_strerror (GPG_ERR_ENOMEM));
2961 return send_error (ctx, GPG_ERR_ENOMEM);
2964 pthread_cleanup_push ((void *)xmlFree, xml);
2965 rc = xfer_data (ctx, (char *) xml, len);
2966 pthread_cleanup_pop (1);
2967 return send_error (ctx, rc);
2970 static gpg_error_t
2971 getconfig_command (assuan_context_t ctx, char *line)
2973 struct client_s *client = assuan_get_pointer (ctx);
2974 gpg_error_t rc = 0;
2975 char filename[255] = { 0 }, param[747] = { 0 };
2976 char *p, *tmp = NULL, *fp = client->filename, *paramp = line;
2978 if (!line || !*line)
2979 return send_error (ctx, GPG_ERR_SYNTAX);
2981 if (strchr (line, ' '))
2983 int ret = sscanf (line, " %254[^ ] %746c", filename, param);
2985 if (ret <= 0)
2986 return send_error (ctx, gpg_error_from_syserror());
2987 paramp = param;
2988 fp = filename;
2991 if (fp && !valid_filename (fp))
2992 return send_error (ctx, GPG_ERR_INV_VALUE);
2994 paramp = str_down (paramp);
2995 p = config_get_value (fp ? fp : "global", paramp);
2996 if (!p)
2997 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2999 tmp = expand_homedir (p);
3000 xfree (p);
3001 if (!tmp)
3003 log_write ("%s(%i): %s", __FILE__, __LINE__,
3004 pwmd_strerror (GPG_ERR_ENOMEM));
3005 return send_error (ctx, GPG_ERR_ENOMEM);
3008 p = tmp;
3009 pthread_cleanup_push ((void *)xfree, p);
3010 rc = xfer_data (ctx, p, strlen (p));
3011 pthread_cleanup_pop (1);
3012 return send_error (ctx, rc);
3015 struct xpath_s
3017 xmlXPathContextPtr xp;
3018 xmlXPathObjectPtr result;
3019 xmlBufferPtr buf;
3020 char **req;
3023 static void
3024 xpath_command_free (void *arg)
3026 struct xpath_s *xpath = arg;
3028 if (!xpath)
3029 return;
3031 req_free (xpath->req);
3033 if (xpath->buf)
3034 xmlBufferFree (xpath->buf);
3036 if (xpath->result)
3037 xmlXPathFreeObject (xpath->result);
3039 if (xpath->xp)
3040 xmlXPathFreeContext (xpath->xp);
3042 xfree (xpath);
3045 static gpg_error_t
3046 do_xpath (assuan_context_t ctx, char *line)
3048 gpg_error_t rc;
3049 struct client_s *client = assuan_get_pointer (ctx);
3050 struct xpath_s *xpath = NULL;
3052 if (!line || !*line)
3053 return GPG_ERR_SYNTAX;
3055 xpath = xcalloc (1, sizeof (struct xpath_s));
3056 if (!xpath)
3057 return GPG_ERR_ENOMEM;
3059 if ((xpath->req = str_split (line, "\t", 2)) == NULL)
3061 if (strv_printf (&xpath->req, "%s", line) == 0)
3063 xpath_command_free (xpath);
3064 return GPG_ERR_ENOMEM;
3068 if (xpath->req[1])
3070 rc = copy_on_write (client);
3071 if (rc)
3072 goto fail;
3075 xpath->xp = xmlXPathNewContext (client->doc);
3076 if (!xpath->xp)
3078 rc = GPG_ERR_BAD_DATA;
3079 goto fail;
3082 xpath->result =
3083 xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
3084 if (!xpath->result)
3086 rc = GPG_ERR_BAD_DATA;
3087 goto fail;
3090 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
3092 rc = GPG_ERR_ELEMENT_NOT_FOUND;
3093 goto fail;
3096 rc = xml_recurse_xpath_nodeset (client, client->doc,
3097 xpath->result->nodesetval,
3098 (xmlChar *) xpath->req[1], &xpath->buf, 0,
3099 NULL);
3100 if (rc)
3101 goto fail;
3102 else if (!xpath->req[1] && !xmlBufferLength (xpath->buf))
3104 rc = GPG_ERR_NO_DATA;
3105 goto fail;
3107 else if (xpath->req[1])
3109 rc = 0;
3110 goto fail;
3113 pthread_cleanup_push ((void *)xpath_command_free, xpath);
3114 rc = xfer_data (ctx, (char *) xmlBufferContent (xpath->buf),
3115 xmlBufferLength (xpath->buf));
3116 pthread_cleanup_pop (0);
3117 fail:
3118 xpath_command_free (xpath);
3119 return rc;
3122 static gpg_error_t
3123 xpath_command (assuan_context_t ctx, char *line)
3125 struct client_s *client = assuan_get_pointer (ctx);
3126 gpg_error_t rc;
3127 struct argv_s *args[] = {
3128 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3129 NULL
3132 if (disable_list_and_dump == 1)
3133 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
3135 rc = peer_is_invoker(client);
3136 if (rc)
3137 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
3139 rc = parse_options (&line, args, client, 1);
3140 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3141 rc = GPG_ERR_SYNTAX;
3142 if (rc)
3143 return send_error (ctx, rc);
3145 if (client->opts & OPT_INQUIRE)
3147 unsigned char *result;
3148 size_t len;
3150 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3151 if (rc)
3152 return send_error (ctx, rc);
3154 pthread_cleanup_push ((void *)xfree, result);
3155 rc = do_xpath (ctx, (char *)result);
3156 pthread_cleanup_pop (1);
3158 else
3159 rc = do_xpath (ctx, line);
3161 return send_error (ctx, rc);
3164 static gpg_error_t
3165 do_xpathattr (assuan_context_t ctx, char *line)
3167 struct client_s *client = assuan_get_pointer (ctx);
3168 gpg_error_t rc;
3169 char **req = NULL;
3170 int cmd = 0; //SET
3171 struct xpath_s *xpath = NULL;
3173 if (!line || !*line)
3174 return GPG_ERR_SYNTAX;
3176 if ((req = str_split (line, " ", 3)) == NULL)
3177 return GPG_ERR_ENOMEM;
3179 if (!req[0])
3181 rc = GPG_ERR_SYNTAX;
3182 goto fail;
3185 if (!strcasecmp (req[0], "SET"))
3186 cmd = 0;
3187 else if (!strcasecmp (req[0], "DELETE"))
3188 cmd = 1;
3189 else
3191 rc = GPG_ERR_SYNTAX;
3192 goto fail;
3195 if (!req[1] || !req[2])
3197 rc = GPG_ERR_SYNTAX;
3198 goto fail;
3201 xpath = xcalloc (1, sizeof (struct xpath_s));
3202 if (!xpath)
3204 rc = GPG_ERR_ENOMEM;
3205 goto fail;
3208 if ((xpath->req = str_split (req[2], "\t", 3)) == NULL)
3210 rc = GPG_ERR_ENOMEM;
3211 goto fail;
3214 if (!xpath->req[0] || (!xpath->req[1] && !cmd) || (xpath->req[1] && cmd))
3216 rc = GPG_ERR_SYNTAX;
3217 goto fail;
3220 rc = copy_on_write (client);
3221 if (rc)
3222 goto fail;
3224 xpath->xp = xmlXPathNewContext (client->doc);
3225 if (!xpath->xp)
3227 rc = GPG_ERR_BAD_DATA;
3228 goto fail;
3231 xpath->result = xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
3232 if (!xpath->result)
3234 rc = GPG_ERR_BAD_DATA;
3235 goto fail;
3238 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
3240 rc = GPG_ERR_ELEMENT_NOT_FOUND;
3241 goto fail;
3244 rc = xml_recurse_xpath_nodeset (client, client->doc,
3245 xpath->result->nodesetval,
3246 (xmlChar *) xpath->req[1], &xpath->buf, cmd,
3247 (xmlChar *) req[1]);
3249 fail:
3250 xpath_command_free (xpath);
3251 strv_free (req);
3252 return rc;
3255 /* XPATHATTR SET|DELETE <name> <expression>[<TAB>[value]] */
3256 static gpg_error_t
3257 xpathattr_command (assuan_context_t ctx, char *line)
3259 struct client_s *client = assuan_get_pointer (ctx);
3260 gpg_error_t rc;
3261 struct argv_s *args[] = {
3262 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3263 NULL
3266 if (disable_list_and_dump == 1)
3267 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
3269 rc = peer_is_invoker(client);
3270 if (rc)
3271 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
3273 rc = parse_options (&line, args, client, 1);
3274 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3275 rc = GPG_ERR_SYNTAX;
3276 if (rc)
3277 return send_error (ctx, rc);
3279 if (client->opts & OPT_INQUIRE)
3281 unsigned char *result;
3282 size_t len;
3284 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3285 if (rc)
3286 return send_error (ctx, rc);
3288 pthread_cleanup_push ((void *)xfree, result);
3289 rc = do_xpathattr (ctx, (char *)result);
3290 pthread_cleanup_pop (1);
3292 else
3293 rc = do_xpathattr (ctx, line);
3295 return send_error (ctx, rc);
3298 static gpg_error_t
3299 do_import (struct client_s *client, const char *root_element,
3300 unsigned char *content)
3302 xmlDocPtr doc = NULL;
3303 xmlNodePtr n = NULL, root;
3304 gpg_error_t rc = 0;
3305 struct string_s *str = NULL, *tstr = NULL;
3306 struct xml_request_s *req = NULL;
3308 if (!content || !*content)
3309 return GPG_ERR_SYNTAX;
3311 if (root_element)
3313 rc = xml_new_request (client, root_element, XML_CMD_STORE, &req);
3314 if (rc)
3316 xfree (content);
3317 return rc;
3320 if (!xml_valid_element_path (req->args, 0))
3322 xml_free_request (req);
3323 xfree (content);
3324 return GPG_ERR_INV_VALUE;
3328 str = string_new_content ((char *)content);
3329 tstr = string_prepend (str, "<pwmd>");
3330 if (tstr)
3332 str = tstr;
3333 tstr = string_append (str, "</pwmd>");
3334 if (!tstr)
3335 rc = GPG_ERR_ENOMEM;
3336 else
3337 str = tstr;
3339 else
3340 rc = GPG_ERR_ENOMEM;
3342 if (rc)
3343 goto fail;
3345 doc = xmlReadDoc ((xmlChar *) str->str, NULL, "UTF-8", XML_PARSE_NOBLANKS);
3346 string_free (str, 1);
3347 if (!doc)
3349 rc = GPG_ERR_BAD_DATA;
3350 goto fail;
3353 root = xmlDocGetRootElement (doc);
3354 root = root->children;
3355 if (!root || root->type != XML_ELEMENT_NODE)
3357 rc = GPG_ERR_BAD_DATA;
3358 goto fail;
3361 rc = xml_validate_import (client, root);
3362 if (rc)
3363 goto fail;
3365 if (req)
3367 /* Create the new specified root element path, if needed. */
3368 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc),
3369 &rc);
3370 if (rc)
3371 goto fail;
3373 /* Overwrite the children of the specified root element path. */
3374 (void)xml_unlink_node (client, n->children);
3375 n->children = NULL;
3377 else
3378 n = xmlDocGetRootElement (client->doc);
3380 if (n)
3382 xmlNodePtr copy;
3383 xmlChar *name = xml_attribute_value (root, (xmlChar *)"_name");
3385 if (!name)
3386 rc = GPG_ERR_BAD_DATA;
3387 else
3388 rc = xml_is_element_owner (client, n, 0);
3390 if (!rc && !req)
3392 /* No --root argument passed. Overwrite the current documents' root
3393 * element matching the root element of the imported data. */
3394 xml_free_request (req);
3395 req = NULL;
3396 rc = xml_new_request (client, (char *)name, XML_CMD_DELETE, &req);
3397 xmlFree (name);
3398 if (!rc)
3400 xmlNodePtr tmp;
3402 tmp = xml_find_elements (client, req,
3403 xmlDocGetRootElement (req->doc), &rc);
3404 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3405 goto fail;
3407 if (!rc)
3409 rc = xml_is_element_owner (client, tmp, 0);
3410 if (rc)
3411 goto fail;
3414 (void)xml_unlink_node (client, tmp);
3415 rc = 0;
3419 if (!rc)
3421 copy = xmlCopyNodeList (root);
3422 if (!copy)
3423 rc = GPG_ERR_ENOMEM;
3424 else
3426 n = xmlAddChildList (n, copy);
3427 if (!n)
3428 rc = GPG_ERR_ENOMEM;
3433 if (!rc && n && n->parent)
3434 rc = xml_update_element_mtime (client, n->parent);
3436 fail:
3437 xml_free_request (req);
3439 if (doc)
3440 xmlFreeDoc (doc);
3442 return rc;
3445 static gpg_error_t
3446 parse_import_opt_root (void *data, void *value)
3448 struct client_s *client = data;
3450 client->import_root = str_dup (value);
3451 return client->import_root ? 0 : GPG_ERR_ENOMEM;
3454 static gpg_error_t
3455 import_command (assuan_context_t ctx, char *line)
3457 gpg_error_t rc;
3458 struct client_s *client = assuan_get_pointer (ctx);
3459 unsigned char *result;
3460 size_t len;
3461 struct argv_s *args[] = {
3462 &(struct argv_s) {
3463 "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->thd->send_state = n;
3618 else
3619 client->thd->send_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 list = NULL;
4341 rc = GPG_ERR_ENOMEM;
4342 break;
4345 xfree (list);
4346 list = tmp;
4350 strv_free (v);
4351 if (rc || !list)
4352 return send_error (ctx, rc ? rc : GPG_ERR_NO_DATA);
4354 list[strlen (list) - 1] = 0;
4355 pthread_cleanup_push (xfree, list);
4356 rc = xfer_data (ctx, list, strlen (list));
4357 pthread_cleanup_pop (1);
4358 return send_error (ctx, rc);
4361 /* Run all commands in the command list 'head'. The return code isn't
4362 * considered at all for a command. It is stored in the list and later sent to
4363 * the client. */
4364 static gpg_error_t
4365 dispatch_bulk_commands (struct client_s *client, struct sexp_s **list)
4367 unsigned i;
4368 unsigned id = 0;
4369 gpg_error_t rc = 0;
4371 for (i = 0; list && list[i];)
4373 struct bulk_cmd_s *cur = list[i]->user;
4375 if (!strcmp (list[i]->tag, "command"))
4377 i++;
4378 continue;
4380 else if (!strcmp (list[i]->tag, "id"))
4382 id = i++;
4383 continue;
4386 if ((client->flags & FLAG_NO_PINENTRY) && cur->cmd->inquire)
4388 rc = send_status (client->ctx, STATUS_BULK, "BEGIN %s",
4389 list[id]->data);
4390 if (rc)
4391 break;
4394 if (!cur)
4395 continue;
4397 client->bulk_p = cur;
4398 cur->ran = 1;
4400 cur->rc = command_startup (client->ctx, cur->cmd->name);
4401 if (!cur->rc)
4402 cur->rc = cur->cmd->handler (client->ctx, list[i]->data);
4404 if ((client->flags & FLAG_NO_PINENTRY) && cur->cmd->inquire)
4406 (void)send_status (client->ctx, STATUS_BULK, "END %s",
4407 list[id]->data);
4409 command_finalize (client->ctx, cur->rc);
4410 cur->rc = cur->rc ? cur->rc : client->last_rc;
4412 do {
4413 if (list[i+1] && !strcmp (list[i+1]->tag, "rc"))
4415 gpg_error_t erc = 0;
4416 int match = 0;
4418 if (list[i+1]->data)
4420 char **rcs = str_split (list[i+1]->data, "|", 0);
4421 char **p;
4423 for (p = rcs; p && *p; p++)
4425 erc = strtoul (*p, NULL, 10);
4426 if (erc == cur->rc)
4428 match = 1;
4429 break;
4433 strv_free (rcs);
4436 if (!match)
4438 i++;
4439 continue;
4442 rc = dispatch_bulk_commands (client, list[++i]->next);
4444 else
4446 i++;
4447 break;
4449 } while (1);
4452 return rc;
4455 static gpg_error_t
4456 bulk_command (assuan_context_t ctx, char *line)
4458 struct client_s *client = assuan_get_pointer (ctx);
4459 gpg_error_t rc = 0;
4460 unsigned char *result, *p;
4461 size_t len;
4462 struct sexp_s **sexp = NULL;
4463 struct argv_s *args[] = {
4464 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
4465 NULL
4468 rc = parse_options (&line, args, client, 1);
4469 if (rc)
4470 return send_error (ctx, rc);
4472 if ((client->opts & OPT_INQUIRE) && line && *line)
4473 rc = GPG_ERR_SYNTAX;
4474 else if (!(client->opts & OPT_INQUIRE) && (!line || !*line))
4475 rc = GPG_ERR_SYNTAX;
4477 if (rc)
4478 return send_error (ctx, rc);
4480 if (client->opts & OPT_INQUIRE)
4482 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
4483 if (rc)
4484 return send_error (ctx, rc);
4485 p = result;
4487 else
4489 p = (unsigned char *)line;
4490 len = line && *line ? strlen (line) : 0;
4493 if (!len)
4494 return send_error (ctx, GPG_ERR_SYNTAX);
4496 rc = bulk_parse_commands (&sexp, (const char *)p, command_table);
4497 if (client->opts & OPT_INQUIRE)
4498 xfree (result);
4500 if (rc)
4501 return send_error (ctx, rc);
4503 pthread_cleanup_push ((void *)bulk_free_list, sexp);
4504 rc = dispatch_bulk_commands (client, sexp);
4505 pthread_cleanup_pop (0);
4506 if (!rc)
4507 rc = bulk_build_result (sexp, (char **)&result);
4509 bulk_free_list (sexp);
4511 if (!rc)
4513 pthread_cleanup_push ((void *)xfree, result);
4514 rc = xfer_data (ctx, (char *)result, strlen ((char *)result));
4515 pthread_cleanup_pop (1);
4518 return send_error (ctx, rc);
4521 static gpg_error_t
4522 nop_command (assuan_context_t ctx, char *line)
4524 return send_error (ctx, 0);
4527 static gpg_error_t
4528 bye_notify (assuan_context_t ctx, char *line)
4530 struct client_s *cl = assuan_get_pointer (ctx);
4531 gpg_error_t ret = 0;
4533 (void)line;
4534 update_client_state (cl, CLIENT_STATE_DISCON);
4536 #ifdef WITH_GNUTLS
4537 cl->disco = 1;
4538 if (cl->thd->remote)
4540 int rc;
4544 struct timeval tv = { 0, 50000 };
4546 rc = gnutls_bye (cl->thd->tls->ses, GNUTLS_SHUT_WR);
4547 if (rc == GNUTLS_E_AGAIN)
4548 select (0, NULL, NULL, NULL, &tv);
4550 while (rc == GNUTLS_E_AGAIN);
4552 #endif
4554 /* This will let assuan_process_next() return. */
4555 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
4557 cl->last_rc = gpg_error_from_errno (errno);
4558 ret = cl->last_rc;
4561 cl->last_rc = 0; // BYE command result
4562 return ret;
4565 static gpg_error_t
4566 reset_notify (assuan_context_t ctx, char *line)
4568 struct client_s *client = assuan_get_pointer (ctx);
4570 (void)line;
4571 if (client)
4572 reset_client (client);
4574 return 0;
4578 * This is called before every Assuan command.
4580 static gpg_error_t
4581 command_startup (assuan_context_t ctx, const char *name)
4583 struct client_s *client = assuan_get_pointer (ctx);
4584 gpg_error_t rc = 0;
4585 struct command_table_s *cmd = NULL;
4587 log_write2 ("command='%s'", name);
4588 client->last_rc = client->opts = 0;
4590 for (int i = 0; command_table[i]; i++)
4592 if (!strcasecmp (name, command_table[i]->name))
4594 if (command_table[i]->ignore_startup)
4595 goto send_state;
4597 cmd = command_table[i];
4598 break;
4602 if (!cmd)
4603 return GPG_ERR_UNKNOWN_COMMAND;
4605 client->last_rc = rc = gpg_error (file_modified (client, cmd));
4607 send_state:
4608 if (!client->bulk_p && !rc)
4609 update_client_state (client, CLIENT_STATE_COMMAND);
4611 return rc;
4615 * This is called after every Assuan command.
4617 static void
4618 command_finalize (assuan_context_t ctx, gpg_error_t rc)
4620 struct client_s *client = assuan_get_pointer (ctx);
4622 if (!(client->flags & FLAG_LOCK_CMD))
4623 unlock_file_mutex (client, 0);
4625 unlock_flock (&client->flock_fd);
4626 log_write2 (_("command completed: rc=%u"), rc ? rc : client->last_rc);
4628 #ifdef WITH_GNUTLS
4629 client->thd->buffer_timeout = client->thd->last_buffer_size = 0;
4630 #endif
4632 if (!client->bulk_p && client->thd->state != CLIENT_STATE_DISCON)
4633 update_client_state (client, CLIENT_STATE_IDLE);
4635 client->bulk_p = NULL;
4638 static gpg_error_t
4639 parse_help_opt_html (void *data, void *value)
4641 struct client_s *client = data;
4643 (void) value;
4644 client->opts |= OPT_HTML;
4645 return 0;
4648 static gpg_error_t
4649 help_command (assuan_context_t ctx, char *line)
4651 gpg_error_t rc;
4652 int i;
4653 struct client_s *client = assuan_get_pointer (ctx);
4654 struct argv_s *args[] = {
4655 &(struct argv_s) {"html", OPTION_TYPE_NOARG, parse_help_opt_html},
4656 NULL
4659 rc = parse_options (&line, args, client, 1);
4660 if (rc)
4661 return send_error (ctx, rc);
4663 if (!line || !*line)
4665 char *tmp;
4666 char *help = str_dup (_("Usage: HELP [--html] [<COMMAND>]\n"
4667 "For commands that take an element path as an argument, each element is "
4668 "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."
4669 "@*@*COMMANDS:"));
4671 for (i = 0; command_table[i]; i++)
4673 if (!command_table[i]->help)
4674 continue;
4676 /* @npxref{} won't put a "See " or "see " in front of the command.
4677 * It's not a texinfo command but needed for --html. */
4678 tmp = str_asprintf ("%s %s%s%s", help,
4679 client->opts & OPT_HTML ? "@npxref{" : "",
4680 command_table[i]->name,
4681 client->opts & OPT_HTML ? "}" : "");
4682 xfree (help);
4683 help = tmp;
4686 tmp = strip_texi_and_wrap (help, client->opts & OPT_HTML);
4687 xfree (help);
4688 pthread_cleanup_push ((void *)xfree, tmp);
4689 rc = xfer_data (ctx, tmp, strlen (tmp));
4690 pthread_cleanup_pop (1);
4691 return send_error (ctx, rc);
4694 for (i = 0; command_table[i]; i++)
4696 if (!strcasecmp (line, command_table[i]->name))
4698 char *help, *tmp;
4700 if (!command_table[i]->help)
4701 break;
4703 help = strip_texi_and_wrap (command_table[i]->help,
4704 client->opts & OPT_HTML);
4705 tmp = str_asprintf ("%s%s",
4706 (client->opts & OPT_HTML) ? "" : _("Usage: "),
4707 help);
4708 xfree (help);
4709 pthread_cleanup_push ((void *)xfree, tmp);
4710 rc = xfer_data (ctx, tmp, strlen (tmp));
4711 pthread_cleanup_pop (1);
4712 return send_error (ctx, rc);
4716 return send_error (ctx, GPG_ERR_INV_NAME);
4719 static void
4720 new_command (const char *name, int inquire, int ignore, int unlock,
4721 int flock_type, gpg_error_t (*handler) (assuan_context_t, char *),
4722 const char *help)
4724 int i = 0;
4725 struct command_table_s **tmp;
4727 if (command_table)
4728 for (i = 0; command_table[i]; i++);
4730 tmp = xrealloc (command_table, (i + 2) * sizeof (struct command_table_s *));
4731 assert (tmp);
4732 command_table = tmp;
4733 command_table[i] = xcalloc (1, sizeof (struct command_table_s));
4734 command_table[i]->name = name;
4735 command_table[i]->inquire = inquire;
4736 command_table[i]->handler = handler;
4737 command_table[i]->ignore_startup = ignore;
4738 command_table[i]->unlock = unlock;
4739 command_table[i]->flock_type = flock_type;
4740 command_table[i++]->help = help;
4741 command_table[i] = NULL;
4744 void
4745 deinit_commands ()
4747 int i;
4749 for (i = 0; command_table[i]; i++)
4750 xfree (command_table[i]);
4752 xfree (command_table);
4755 static int
4756 sort_commands (const void *arg1, const void *arg2)
4758 struct command_table_s *const *a = arg1;
4759 struct command_table_s *const *b = arg2;
4761 if (!*a || !*b)
4762 return 0;
4763 else if (*a && !*b)
4764 return 1;
4765 else if (!*a && *b)
4766 return -1;
4768 return strcmp ((*a)->name, (*b)->name);
4771 static gpg_error_t
4772 passwd_command (assuan_context_t ctx, char *line)
4774 struct client_s *client = assuan_get_pointer (ctx);
4775 gpg_error_t rc;
4777 (void)line;
4778 rc = peer_is_invoker (client);
4779 if (rc)
4780 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
4782 if (client->flags & FLAG_NEW)
4783 return send_error (ctx, GPG_ERR_INV_STATE);
4785 client->crypto->keyfile = config_get_string (client->filename,
4786 "passphrase_file");
4787 rc = crypto_init_ctx (client->crypto, client->flags & FLAG_NO_PINENTRY,
4788 client->crypto->keyfile);
4789 if (!rc)
4790 rc = crypto_passwd (client, client->crypto);
4792 crypto_free_non_keys (client->crypto);
4793 return send_error (ctx, rc);
4796 static gpg_error_t
4797 parse_opt_data (void *data, void *value)
4799 struct client_s *client = data;
4801 (void) value;
4802 client->opts |= OPT_DATA;
4803 return 0;
4806 static gpg_error_t
4807 send_client_list (assuan_context_t ctx)
4809 struct client_s *client = assuan_get_pointer (ctx);
4810 gpg_error_t rc = 0;
4812 if (client->opts & OPT_VERBOSE)
4814 unsigned i, t;
4815 char **list = NULL;
4816 char *line;
4818 MUTEX_LOCK (&cn_mutex);
4819 pthread_cleanup_push ((void *)release_mutex_cb, &cn_mutex);
4820 t = slist_length (cn_thread_list);
4822 for (i = 0; i < t; i++)
4824 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
4825 char *tmp;
4827 if (thd->state == CLIENT_STATE_UNKNOWN)
4828 continue;
4830 tmp = build_client_info_line (thd, 0);
4831 if (tmp)
4833 char **l = strv_cat (list, tmp);
4834 if (!l)
4835 rc = GPG_ERR_ENOMEM;
4836 else
4837 list = l;
4839 else
4840 rc = GPG_ERR_ENOMEM;
4842 if (rc)
4844 strv_free (list);
4845 break;
4849 pthread_cleanup_pop (1);
4850 if (rc)
4851 return rc;
4853 line = strv_join ("\n", list);
4854 strv_free (list);
4855 pthread_cleanup_push ((void *)xfree, line);
4856 rc = xfer_data (ctx, line, strlen (line));
4857 pthread_cleanup_pop (1);
4858 return rc;
4861 if (client->opts & OPT_DATA)
4863 char buf[ASSUAN_LINELENGTH];
4865 MUTEX_LOCK (&cn_mutex);
4866 snprintf (buf, sizeof (buf), "%u", slist_length (cn_thread_list));
4867 MUTEX_UNLOCK (&cn_mutex);
4868 rc = xfer_data (ctx, buf, strlen (buf));
4870 else
4871 rc = send_status (ctx, STATUS_CLIENTS, NULL);
4873 return rc;
4876 static gpg_error_t
4877 getinfo_command (assuan_context_t ctx, char *line)
4879 struct client_s *client = assuan_get_pointer (ctx);
4880 gpg_error_t rc;
4881 char buf[ASSUAN_LINELENGTH];
4882 struct argv_s *args[] = {
4883 &(struct argv_s) {"data", OPTION_TYPE_NOARG, parse_opt_data},
4884 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_opt_verbose},
4885 NULL
4888 rc = parse_options (&line, args, client, 1);
4889 if (rc)
4890 return send_error (ctx, rc);
4892 if (!line || !*line)
4893 return send_error (ctx, GPG_ERR_SYNTAX);
4895 if (!strcasecmp (line, "clients"))
4897 rc = send_client_list (ctx);
4899 else if (!strcasecmp (line, "cache"))
4901 if (client->opts & OPT_DATA)
4903 snprintf (buf, sizeof (buf), "%u", cache_file_count ());
4904 rc = xfer_data (ctx, buf, strlen (buf));
4906 else
4907 rc = send_status (ctx, STATUS_CACHE, NULL);
4909 else if (!strcasecmp (line, "pid"))
4911 long pid = getpid ();
4913 snprintf (buf, sizeof (buf), "%li", pid);
4914 rc = xfer_data (ctx, buf, strlen (buf));
4916 else if (!strcasecmp (line, "version"))
4918 char *tmp = str_asprintf ("0x%06x %s", VERSION_HEX,
4919 #ifdef WITH_GNUTLS
4920 "GNUTLS "
4921 #endif
4922 #ifdef WITH_LIBACL
4923 "ACL "
4924 #endif
4925 "");
4926 pthread_cleanup_push (xfree, tmp);
4927 rc = xfer_data (ctx, tmp, strlen (tmp));
4928 pthread_cleanup_pop (1);
4930 else if (!strcasecmp (line, "last_error"))
4932 if (client->last_error)
4933 rc = xfer_data (ctx, client->last_error, strlen (client->last_error));
4934 else
4935 rc = GPG_ERR_NO_DATA;
4937 else if (!strcasecmp (line, "user"))
4939 char *user = NULL;
4941 #ifdef WITH_GNUTLS
4942 if (client->thd->remote)
4943 user = str_asprintf ("#%s", client->thd->tls->fp);
4944 else
4945 user = get_username (client->thd->peer->uid);
4946 #else
4947 user = get_username (client->thd->peer->uid);
4948 #endif
4949 if (user)
4951 pthread_cleanup_push ((void *)xfree, user);
4952 rc = xfer_data (ctx, user, strlen (user));
4953 pthread_cleanup_pop (1);
4955 else
4956 rc = GPG_ERR_NO_DATA;
4958 else
4959 rc = gpg_error (GPG_ERR_SYNTAX);
4961 return send_error (ctx, rc);
4964 static gpg_error_t
4965 parse_opt_secret (void *data, void *value)
4967 struct client_s *client = data;
4969 (void) value;
4970 client->opts |= OPT_SECRET;
4971 return 0;
4974 static gpg_error_t
4975 parse_keyinfo_opt_learn (void *data, void *value)
4977 struct client_s *client = data;
4979 (void)value;
4980 client->opts |= OPT_KEYINFO_LEARN;
4981 return 0;
4984 static gpg_error_t
4985 keyinfo_command (assuan_context_t ctx, char *line)
4987 struct client_s *client = assuan_get_pointer (ctx);
4988 gpg_error_t rc = 0;
4989 char **keys = NULL, **p = NULL;
4990 int sym = 0;
4991 struct argv_s *args[] = {
4992 &(struct argv_s) {"learn", OPTION_TYPE_NOARG, parse_keyinfo_opt_learn},
4993 NULL
4996 rc = parse_options (&line, args, client, 0);
4997 if (rc)
4998 return send_error (ctx, rc);
5000 if (line && *line)
5001 return send_error (ctx, GPG_ERR_SYNTAX);
5003 if (!(client->flags & FLAG_OPEN))
5004 return send_error (ctx, GPG_ERR_INV_STATE);
5006 if (client->opts & OPT_KEYINFO_LEARN)
5008 rc = cache_agent_command ("LEARN");
5009 return send_error (ctx, rc);
5012 if (client->flags & FLAG_NEW)
5013 return send_error (ctx, GPG_ERR_NO_DATA);
5015 rc = lock_flock (ctx, client->filename, FLOCK_TYPE_SH, &client->flock_fd);
5016 if (rc)
5017 return send_error (ctx, rc);
5019 rc = crypto_is_symmetric (client->filename);
5020 unlock_flock (&client->flock_fd);
5021 if (!rc)
5022 sym = 1;
5023 else if (rc != GPG_ERR_BAD_DATA)
5024 return send_error (ctx, rc);
5026 rc = 0;
5027 if (!sym)
5029 p = strv_catv (keys, client->crypto->pubkey);
5030 if (!p)
5031 rc = GPG_ERR_ENOMEM;
5032 else
5033 keys = p;
5036 if (!rc && client->crypto->sigkey)
5038 if (!strv_printf (&keys, "S%s", client->crypto->sigkey))
5040 strv_free (keys);
5041 return send_error (ctx, GPG_ERR_ENOMEM);
5045 if (!rc)
5047 if (keys)
5049 line = strv_join ("\n", keys);
5050 strv_free (keys);
5051 pthread_cleanup_push ((void *)xfree, line);
5052 if (line)
5053 rc = xfer_data (ctx, line, strlen (line));
5054 else
5055 rc = GPG_ERR_ENOMEM;
5057 pthread_cleanup_pop (1);
5059 else
5060 rc = GPG_ERR_NO_DATA;
5062 else
5063 strv_free (keys);
5065 return send_error (ctx, rc);
5068 static gpg_error_t
5069 deletekey_command (assuan_context_t ctx, char *line)
5071 gpg_error_t rc;
5072 struct client_s *client = assuan_get_pointer (ctx);
5073 struct crypto_s *crypto = NULL;
5074 char *keys[] = { NULL, NULL };
5075 gpgme_key_t *result;
5077 rc = peer_is_invoker (client);
5078 if (rc)
5079 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
5081 if (!*line)
5082 return send_error (ctx, GPG_ERR_SYNTAX);
5084 rc = crypto_keyid_to_16b_once (line);
5085 if (rc)
5086 return send_error (ctx, rc);
5088 rc = crypto_init (&crypto, client->ctx, client->filename,
5089 client->flags & FLAG_NO_PINENTRY, NULL);
5090 if (rc)
5091 return send_error (ctx, rc);
5093 pthread_cleanup_push ((void *)crypto_free, crypto);
5094 keys[0] = line;
5095 rc = crypto_list_keys (crypto, keys, 1, &result);
5096 if (!rc)
5098 pthread_cleanup_push ((void *)crypto_free_key_list, result);
5099 rc = crypto_delete_key (client, crypto, *result, 1);
5100 pthread_cleanup_pop (1);
5103 pthread_cleanup_pop (1);
5104 return send_error (ctx, rc);
5107 static gpg_error_t
5108 kill_command (assuan_context_t ctx, char *line)
5110 struct client_s *client = assuan_get_pointer (ctx);
5111 gpg_error_t rc;
5112 unsigned i, t;
5114 if (!line || !*line)
5115 return send_error (ctx, GPG_ERR_SYNTAX);
5117 MUTEX_LOCK (&cn_mutex);
5118 pthread_cleanup_push ((void *)release_mutex_cb, &cn_mutex);
5119 t = slist_length (cn_thread_list);
5120 rc = GPG_ERR_ESRCH;
5122 for (i = 0; i < t; i++)
5124 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
5125 char *tmp = str_asprintf ("%p", thd->tid);
5127 if (strcmp (line, tmp))
5129 xfree (tmp);
5130 continue;
5133 xfree (tmp);
5134 rc = peer_is_invoker (client);
5135 if (!rc)
5137 #ifdef HAVE_PTHREAD_CANCEL
5138 pthread_cancel (thd->tid);
5139 #else
5140 pthread_kill (thd->tid, SIGUSR2);
5141 #endif
5142 break;
5144 else if (rc == GPG_ERR_EACCES)
5145 rc = GPG_ERR_FORBIDDEN;
5146 else if (rc)
5147 break;
5149 if (config_get_boolean ("global", "strict_kill"))
5150 break;
5152 #ifdef WITH_GNUTLS
5153 if (client->thd->remote && thd->remote)
5155 if (!thd->tls || !thd->tls->fp)
5157 rc = GPG_ERR_INV_STATE;
5158 break;
5160 if (!strcmp (client->thd->tls->fp, thd->tls->fp))
5162 #ifdef HAVE_PTHREAD_CANCEL
5163 pthread_cancel (thd->tid);
5164 #else
5165 pthread_kill (thd->tid, SIGUSR2);
5166 #endif
5167 rc = 0;
5168 break;
5171 else if (!client->thd->remote && !thd->remote)
5172 #endif
5174 if (client->thd->peer->uid == thd->peer->uid)
5176 #ifdef HAVE_PTHREAD_CANCEL
5177 pthread_cancel (thd->tid);
5178 #else
5179 pthread_kill (thd->tid, SIGUSR2);
5180 #endif
5181 rc = 0;
5184 break;
5187 pthread_cleanup_pop (1);
5188 return send_error (ctx, rc);
5191 static gpg_error_t
5192 listkeys_command (assuan_context_t ctx, char *line)
5194 struct client_s *client = assuan_get_pointer (ctx);
5195 struct crypto_s *crypto = NULL;
5196 char **pattern = NULL;
5197 gpgme_key_t *keys = NULL;
5198 char **result = NULL;
5199 gpg_error_t rc;
5200 struct argv_s *args[] = {
5201 &(struct argv_s) {"secret-only", OPTION_TYPE_NOARG, parse_opt_secret},
5202 NULL
5205 rc = parse_options (&line, args, client, 1);
5206 if (rc)
5207 return send_error (ctx, rc);
5209 rc = crypto_init (&crypto, client->ctx, client->filename,
5210 client->flags & FLAG_NO_PINENTRY, NULL);
5211 if (rc)
5212 return send_error (ctx, rc);
5214 pthread_cleanup_push ((void *)crypto_free, crypto);
5215 if (line)
5216 pattern = str_split (line, ",", 0);
5217 pthread_cleanup_push ((void *)(void *)strv_free, pattern);
5218 rc = crypto_list_keys (crypto, pattern, client->opts & OPT_SECRET,
5219 &keys);
5220 pthread_cleanup_pop (1);
5221 pthread_cleanup_pop (1);
5222 if (!rc)
5224 int i;
5226 for (i = 0; keys[i]; i++)
5228 char *p = crypto_key_info (keys[i]);
5229 char **r;
5231 if (!p)
5233 rc = GPG_ERR_ENOMEM;
5234 break;
5237 r = strv_cat (result, p);
5238 if (!r)
5240 rc = GPG_ERR_ENOMEM;
5241 break;
5244 result = r;
5247 if (!i)
5248 rc = GPG_ERR_NO_DATA;
5250 crypto_free_key_list (keys);
5253 if (!rc)
5255 line = strv_join ("\n", result);
5256 strv_free (result);
5257 pthread_cleanup_push ((void *)xfree, line);
5258 if (!line)
5259 rc = GPG_ERR_ENOMEM;
5260 else
5261 rc = xfer_data (ctx, line, strlen (line));
5263 pthread_cleanup_pop (1);
5265 else
5266 strv_free (result);
5268 if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
5269 || gpg_err_code (rc) == GPG_ERR_NO_SECKEY)
5270 rc = GPG_ERR_NO_DATA;
5272 return send_error (ctx, rc);
5275 void
5276 init_commands ()
5278 /* !BEGIN-HELP-TEXT!
5280 * This comment is used as a marker to generate the offline documentation
5281 * found in doc/pwmd.info. The indentation needs to be kept for the awk
5282 * script to determine where commands begin and end.
5284 new_command("HELP", 0, 1, 1, 0, help_command, _(
5285 "HELP [--html] [<COMMAND>]\n" /* Showing available commands. */
5286 "Show available commands or command specific help text."
5287 "@*@*"
5288 "The @option{--html} option will output the help text in HTML format."
5291 new_command("DELETEKEY", 0, 1, 1, FLOCK_TYPE_SH|FLOCK_TYPE_KEEP, deletekey_command, _(
5292 "DELETEKEY <keyid>\n" /* Deleting a key from the key ring. */
5293 "Deletes the public and secret key associated with key @var{keyid} from the "
5294 "keyring. The @var{keyid} must be one associated with the currently opened "
5295 "data file. "
5296 "Note that no confirmation occurs. Also note that when the key is deleted, "
5297 "the current or other data files using this key will no longer be able to be "
5298 "opened."
5301 new_command("KILL", 0, 1, 0, 0, kill_command, _(
5302 "KILL <thread_id>\n" /* Terminating another client. */
5303 "Terminates the client identified by @var{thread_id} and releases any file "
5304 "lock or other resources it has held. See @code{GETINFO} (@pxref{GETINFO}) "
5305 "for details about listing connected clients. An @code{invoking_user} "
5306 "(@pxref{Configuration}) may kill any client while others may only kill "
5307 "clients of the same @code{UID} or @abbr{TLS} fingerprint."
5310 new_command("LISTKEYS", 0, 1, 0, 0, listkeys_command, _(
5311 "LISTKEYS [--secret-only] [pattern[,<pattern>]]\n" /* Listing keys in the key ring. */
5312 "Returns a new line separated list of key information matching a comma "
5313 "separated list of @var{pattern}'s. When option @option{--secret-only} is "
5314 "specified, only keys matching @var{pattern} that also have a secret key "
5315 "available will be returned."
5318 new_command("KEYINFO", 0, 1, 0, 0, keyinfo_command, _(
5319 "KEYINFO [--learn]\n" /* Showing keys used for the current data file. */
5320 "Returns a new line separated list of key ID's that the currently opened "
5321 "data file has recipients and signers for. If the key is a signing key it "
5322 "will be prefixed with an @code{S}. If the file is a new one, or has no "
5323 "signers in the case of being symmetrically encrypted, the error code "
5324 "@code{GPG_ERR_NO_DATA} is returned."
5325 "@*@*"
5326 "When the @option{--learn} option is passed, keys on a smartcard will be "
5327 "imported."
5330 new_command("GETINFO", 0, 1, 1, 0, getinfo_command, _(
5331 "GETINFO [--data] [--verbose] CACHE | CLIENTS | PID | USER | LAST_ERROR | VERSION\n" /* Obtaining server and client information. */
5332 "Get server and other information. The information is returned via a status "
5333 "message (@pxref{Status Messages}) unless otherwise noted or @option{--data} "
5334 "is specified."
5335 "@*@*"
5336 "@var{CACHE} returns the number of cached documents."
5337 "@*@*"
5338 "@var{CLIENTS} returns the number of "
5339 "connected clients via a status message or a list of connected clients when "
5340 "the @option{--verbose} parameter is used (implies @option{--data}). A "
5341 "verbose line of a client list contains "
5342 "space delimited "
5343 "fields: the thread ID, client name, opened file (@code{/} if none opened), "
5344 "IP address if remote, file lock status, whether the current client is self "
5345 "or not, client state (see below), "
5346 "user ID or TLS fingerprint of the connected client, username if the "
5347 "client is a local one else @code{-}, and finally the time stamp of when the "
5348 "client connected."
5349 "@*@*"
5350 "Client state @code{0} is an unknown client state, state @code{1} indicates "
5351 "the client has connected but hasn't completed initializing, state @code{2} "
5352 "indicates that the client is idle, state @code{3} means the "
5353 "client is in a command and state @code{4} means the client is disconnecting. "
5354 "@*@*"
5355 "@var{PID} returns the process ID number of the server via a data response."
5356 "@*@*"
5357 "@var{VERSION} returns the server version number and compile-time features "
5358 "via a data response with each being space delimited."
5359 "@*@*"
5360 "@var{LAST_ERROR} returns a detailed description of the last failed command "
5361 "via a data response, when available."
5362 "@*@*"
5363 "@var{USER} returns the username or @abbr{TLS} hash of the connected client "
5364 "via a data response."
5367 new_command("PASSWD", 1, 0, 0, FLOCK_TYPE_EX|FLOCK_TYPE_KEEP, passwd_command, _(
5368 "PASSWD\n" /* Changing the passphrase for a key. */
5369 "Changes the passphrase of the secret key required to open the current "
5370 "data file. If the data file is symmetrically encrypted the error "
5371 "@code{GPG_ERR_NOT_SUPPORTED} is returned. When symmetrically encrypted "
5372 "the @code{SAVE} command (@pxref{SAVE}) should be used instead to prevent "
5373 "this command saving any unwanted changes to the @abbr{XML} document."
5374 "@*@*"
5375 "Note that when the current data file has been either encrypted or signed "
5376 "with a key stored on a smartcard this command will return an error. In this "
5377 "case you should instead use @command{gpg --card-edit} to change the "
5378 "pin of the smartcard or @command{gpg --edit-key} to change the passphrase "
5379 "of the key used to sign or encrypt the data file."
5380 "@*@*"
5381 "This command is not available to non-invoking clients "
5382 "(@pxref{Access Control})."
5385 new_command("OPEN", 1, 1, 1, FLOCK_TYPE_SH|FLOCK_TYPE_KEEP, open_command, _(
5386 "OPEN [--lock] <filename>\n" /* Opening a data file. */
5387 "Opens @var{filename}. When the @var{filename} is not found on the "
5388 "file-system then a new in-memory document will be created. If the file is "
5389 "found, it is looked for in the file cache and when found no passphrase will "
5390 "be required to open it. When not cached, @cite{pinentry(1)} will be used to "
5391 "retrieve the passphrase for decryption unless @option{disable-pinentry} "
5392 "(@pxref{OPTION}) was specified in which case @command{pwmd} will "
5393 "@emph{INQUIRE} the client for the passphrase. Note than when configuration "
5394 "option @option{strict_open} is enabled and the client is not an "
5395 "@option{invoking_user}, an error will be returned when the data file does "
5396 "not exist."
5397 "@*@*"
5398 "When the @option{--lock} option is passed then the file mutex will be "
5399 "locked as if the @code{LOCK} command (@pxref{LOCK}) had been sent after the "
5400 "file had been opened."
5403 new_command("GENKEY", 1, 1, 1, 0, genkey_command, _(
5404 "GENKEY --subkey-of=fpr | --userid=\"str\" [--no-expire | --expire=N] [--algo=\"str\"] [--no-passphrase] [--usage=\"default|sign|encrypt\"]\n" /* Generating a new key. */
5405 "Generates a new key based on option arguments. One of "
5406 "@option{--subkey-of} or @option{--userid} is "
5407 "required. The @option{--subkey-of} option will generate a subkey for the key "
5408 "of the specified fingerprint."
5409 "@*@*"
5410 "Note that this may take a long time to complete especially if you do not "
5411 "have a hardware RNG. There are software RNG's that will speed this up "
5412 "but are also not as secure."
5415 new_command("SAVE", 1, 0, 0, FLOCK_TYPE_EX|FLOCK_TYPE_KEEP, save_command, _(
5416 "SAVE [--sign-keyid=[<fpr>]] [--symmetric | --keyid=<fpr>[,..] | --inquire-keyid]\n" /* Saving document changes to disk. */
5417 "Writes the in-memory @abbr{XML} document to disk. The file written to is the "
5418 "file that was opened when using the @code{OPEN} command (@pxref{OPEN})."
5419 "@*@*"
5420 "If the file is a new one one of @option{--symmetric}, @option{--keyid} or"
5421 "@option{--inquire-keyid} is required. When not @option{--symmetric} the "
5422 "option @option{--sign-keyid} is also required but optional otherwise."
5423 "@*@*"
5424 "You can encrypt the data file to a recipient other than the one that it "
5425 "was originally encrypted with by passing the @option{--keyid} or "
5426 "@option{--inquire-keyid} option with a comma separated list of "
5427 "public encryption key fingerprints as its argument. Use the "
5428 "@command{LISTKEYS} command (@pxref{LISTKEYS}) to show key information by "
5429 "pattern. The @option{--sign-keyid} option may also be used to sign the data "
5430 "file with an alternate key by specifying the fingerprint of a signing key. "
5431 "Only one signing key is supported unlike the @option{--keyid} option. "
5432 "A passphrase to decrypt the data file "
5433 "will be required when one or more of the original encryption keys or signing "
5434 "key are not found in either of these two options' arguments or when the data "
5435 "file is symmetrically encrypted regardless of the @code{require_save_key} "
5436 "configuration parameter. The original encryption keys and signing key will be "
5437 "used when neither of these options are specified."
5438 "@*@*"
5439 "The @option{--keyid} and @option{--sign-keyid} options are not available "
5440 "to non-invoking clients "
5441 "(@pxref{Access Control}) when the recipients or signer do not match those "
5442 "that were used when the file was @code{OPEN}'ed."
5443 "@*@*"
5444 "The @option{--symmetric} option specifies that a new data file be "
5445 "conventionally encrypted. These types of data files do not use a recipient "
5446 "public key but may optionally be signed by using the @option{--sign-keyid} "
5447 "option. To remove the signing key from a symmtrically encrypted data file, "
5448 "leave the option value empty."
5449 "@*@*"
5450 "Note that you cannot change encryption schemes once a data file has been "
5451 "saved."
5454 new_command("ISCACHED", 0, 1, 0, 0, iscached_command, _(
5455 "ISCACHED [--lock] [--agent [--sign]] <filename>\n" /* Testing cache status. */
5456 "Determines the file cache status of the specified @var{filename}. "
5457 "The default is to test whether the filename is cached in memory. Passing "
5458 "option @option{--agent} will test the @command{gpg-agent} cache for at most "
5459 "one cached key used for opening the data file (@pxref{OPEN}). To test if "
5460 "a signing key is cached, pass @option{--sign} along with @option{--agent}. "
5461 "Both the @option{--agent} and @option{--sign} options require an opened data "
5462 "file."
5463 "@*@*"
5464 "An @emph{OK} response is returned if the specified @var{filename} is found "
5465 "in the cache. If not found in the cache but exists on the filesystem "
5466 "then @code{GPG_ERR_NO_DATA} is returned. Otherwise a filesystem error is "
5467 "returned."
5468 "@*@*"
5469 "The @option{--lock} option will lock the file mutex of @var{filename} when "
5470 "the file exists; it does not need to be opened nor cached. The lock will be "
5471 "released when the client exits or sends the @code{UNLOCK} command "
5472 "(@pxref{UNLOCK}). When this option is passed the current data file is closed."
5475 new_command("CLEARCACHE", 0, 1, 1, 0, clearcache_command, _(
5476 "CLEARCACHE [<filename>]\n" /* Removing a cache entry. */
5477 "Clears a file cache entry for all or the specified @var{filename}. Note that "
5478 "this will also clear any @command{gpg-agent} cached keys which may cause "
5479 "problems if another data file shares the same keys as @var{filename}."
5480 "@*@*"
5481 "When clearing all cache entries a permissions test is done against the "
5482 "current client based on the @var{allowed} configuration parameter in a "
5483 "@var{filename} section. Both a cache entry may be cleared and an error "
5484 "returned depending on cached data files and client permissions."
5487 new_command("CACHETIMEOUT", 0, 1, 1, 0, cachetimeout_command, _(
5488 "CACHETIMEOUT <seconds>\n" /* Setting the cache timeout. */
5489 "The time in @var{seconds} until the currently opened data file will be "
5490 "removed from the cache. @code{-1} will keep the cache entry forever, "
5491 "@code{0} will require the passphrase for each @code{OPEN} command "
5492 "(@pxref{OPEN}) or @code{SAVE} (@pxref{SAVE}) command. @xref{Configuration}, "
5493 "and the @code{cache_timeout} parameter."
5496 new_command("LIST", 0, 0, 1, 0, list_command, _(
5497 "LIST [--inquire] [--recurse] [--sexp] [element[<TAB>child[..]]]\n" /* Showing document elements. */
5498 "If no element path is given then a newline separated list of root elements "
5499 "is returned with a data response. If given, then children of the specified "
5500 "element path are returned."
5501 "@*@*"
5502 "Each element path "
5503 "returned will have zero or more flags appened to it. These flags are "
5504 "delimited from the element path by a single space character. A flag itself "
5505 "is a single character. Flag @code{P} indicates that access to the element "
5506 "is denied. Flag @code{+} indicates that there are child nodes of "
5507 "the current element path. Flag @code{E} indicates that an element of the "
5508 "element path contained in a @var{target} attribute could not be found. Flag "
5509 "@code{O} indicates that a @var{target} attribute recursion limit was reached "
5510 "(@pxref{Configuration}). Flag @code{T}, followed by a single space character, "
5511 "then an element path, is the element path of the @var{target} attribute "
5512 "contained in the current element."
5513 "@*@*"
5514 "When a specified element path contains an error either from the final "
5515 "element in the path or any previous element, the path is still shown but "
5516 "will contain the error flag for the element with the error. Determining "
5517 "the actual element which contains the error is up to the client. This can be "
5518 "done by traversing the final element up to parent elements that contain the "
5519 "same error flag."
5520 "@*@*"
5521 "The option @option{--recurse} may be used to list the entire element tree "
5522 "for a specified element path or the entire tree for all root elements."
5523 "@*@*"
5524 "The option @option{--sexp} outputs the list in an s-expression and also "
5525 "appends an elements' attributes and attribute values. The syntax is:\n"
5526 "\n"
5527 "@example\n"
5528 "(11:list-result\n"
5529 " (4:path N:<path> 5:flags N:<flags>\n"
5530 " (5:attrs N:<name> N:<value> ...)\n"
5531 " )\n"
5532 " ...\n"
5533 ")\n"
5534 "@end example\n"
5535 "\n"
5536 "When the @option{--inquire} option is passed then all remaining non-option "
5537 "arguments are retrieved via a server @emph{INQUIRE}."
5540 new_command("REALPATH", 0, 0, 1, 0, realpath_command, _(
5541 "REALPATH [--inquire] element[<TAB>child[..]]\n" /* Resolving an element. */
5542 "Resolves all @code{target} attributes of the specified element path and "
5543 "returns the result with a data response. @xref{Target Attribute}, for details."
5544 "@*@*"
5545 "When the @option{--inquire} option is passed then all remaining non-option "
5546 "arguments are retrieved via a server @emph{INQUIRE}."
5549 new_command("STORE", 0, 0, 1, 0, store_command, _(
5550 "STORE [--no-inherit-acl] element[<TAB>child[..]]<TAB>[content]\n" /* Modifying the content of an element. */
5551 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
5552 "@*@*"
5553 "Creates a new element path or modifies the @var{content} of an existing "
5554 "element. If only a single element is specified then a new root element is "
5555 "created. Otherwise, elements are @key{TAB} delimited and the content will be "
5556 "set to the final @key{TAB} delimited element. If no @var{content} is "
5557 "specified after the final @key{TAB}, then the content of the existing "
5558 "element will be removed; or will be empty if creating a new element."
5559 "@*@*"
5560 "The option @option{--no-inherit-acl} prevents a newly created element from "
5561 "inheriting the value of the parent element @code{_acl} attribute. In either "
5562 "case, the current user is made the owner of the newly created element(s)."
5563 "@*@*"
5564 "The only restriction of an element name is that it not contain whitespace "
5565 "characters. There is no other whitespace between the @key{TAB} delimited "
5566 "elements. It is recommended that the content of an element be base64 encoded "
5567 "when it contains control or @key{TAB} characters to prevent @abbr{XML} "
5568 "parsing and @command{pwmd} syntax errors."
5571 new_command("RENAME", 0, 0, 1, 0, rename_command, _(
5572 "RENAME [--inquire] element[<TAB>child[..]] <value>\n" /* Renaming an element. */
5573 "Renames the specified @var{element} to the new @var{value}. If an element of "
5574 "the same name as the @var{value} already exists it will be overwritten."
5575 "@*@*"
5576 "When the @option{--inquire} option is passed then all remaining non-option "
5577 "arguments are retrieved via a server @emph{INQUIRE}."
5580 new_command("COPY", 0, 0, 1, 0, copy_command, _(
5581 "COPY [--inquire] source[<TAB>child[..]] dest[<TAB>child[..]]\n" /* Copying an element. */
5582 "Copies the entire element tree starting from the child node of the source "
5583 "element, to the destination element path. If the destination element path "
5584 "does not exist then it will be created; otherwise it is overwritten."
5585 "@*@*"
5586 "Note that attributes from the source element are merged into the "
5587 "destination element when the destination element path exists. When an "
5588 "attribute of the same name exists in both the source and destination "
5589 "elements then the destination attribute will be updated to the source "
5590 "attribute value."
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("MOVE", 0, 0, 1, 0, move_command, _(
5597 "MOVE [--inquire] source[<TAB>child[..]] [dest[<TAB>child[..]]]\n" /* Moving an element. */
5598 "Moves the source element path to the destination element path. If the "
5599 "destination is not specified then it will be moved to the root node of the "
5600 "document. If the destination is specified and exists then it will be "
5601 "overwritten; otherwise non-existing elements of the destination element "
5602 "path will be created."
5603 "@*@*"
5604 "When the @option{--inquire} option is passed then all remaining non-option "
5605 "arguments are retrieved via a server @emph{INQUIRE}."
5608 new_command("DELETE", 0, 0, 1, 0, delete_command, _(
5609 "DELETE [--inquire] element[<TAB>child[..]]\n" /* Deleting an element. */
5610 "Removes the specified element path and all of its children. This may break "
5611 "an element with a @code{target} attribute (@pxref{Target Attribute}) that "
5612 "refers to this element or any of its children."
5613 "@*@*"
5614 "When the @option{--inquire} option is passed then all remaining non-option "
5615 "arguments are retrieved via a server @emph{INQUIRE}."
5618 new_command("GET", 0, 0, 1, 0, get_command, _(
5619 "GET [--inquire] element[<TAB>child[..]]\n" /* Getting the content of an element. */
5620 "Retrieves the content of the specified element. The content is returned "
5621 "with a data response."
5622 "@*@*"
5623 "When the @option{--inquire} option is passed then all remaining non-option "
5624 "arguments are retrieved via a server @emph{INQUIRE}."
5627 new_command("ATTR", 0, 0, 1, 0, attr_command, _(
5628 "ATTR [--inquire] SET|GET|DELETE|LIST [<attribute>] element[<TAB>child[..]] ..\n" /* Modifying element attributes. */
5629 "@table @asis\n"
5630 "@item ATTR SET attribute element[<TAB>child[..]] [value]\n"
5631 " Stores or updates an @var{attribute} name and optional @var{value} of an "
5632 "element. When no @var{value} is specified any existing value will be removed."
5633 "@*@*"
5634 "@item ATTR DELETE attribute element[<TAB>child[..]]\n"
5635 " Removes an attribute from an element. If @var{attribute} is @code{_name} "
5636 "or @code{target} an error is returned. Use the @command{DELETE} command "
5637 "(@pxref{DELETE}) instead."
5638 "@*@*"
5639 "@item ATTR LIST element[<TAB>child[..]]\n"
5640 " Retrieves a newline separated list of attributes names and values "
5641 "from the specified element. Each attribute name and value is space delimited."
5642 "@*@*"
5643 "@item ATTR GET attribute element[<TAB>child[..]]\n"
5644 " Retrieves the value of an @var{attribute} from an element."
5645 "@end table\n"
5646 "@*@*"
5647 "When the @option{--inquire} option is passed then all remaining non-option "
5648 "arguments are retrieved via a server @emph{INQUIRE}."
5649 "@*@*"
5650 "@xref{Target Attribute}, for details about this special attribute and also "
5651 "@pxref{Other Attributes} for other attributes that are handled specially "
5652 "by @command{pwmd}."
5655 new_command("XPATH", 0, 0, 1, 0, xpath_command, _(
5656 "XPATH [--inquire] <expression>[<TAB>[value]]\n" /* Modifying more than one element. */
5657 "Evaluates an XPath @var{expression}. If no @var{value} argument is "
5658 "specified it is assumed the expression is a request to return a result. "
5659 "Otherwise, the result is set to the @var{value} argument and the document is "
5660 "updated. If there is no @var{value} after the @key{TAB} character, the value "
5661 "is assumed to be empty and the document is updated. For example:"
5662 "@sp 1\n"
5663 "@example\n"
5664 "XPATH //element[@@_name='password']@key{TAB}\n"
5665 "@end example\n"
5666 "@sp 1\n"
5667 "would clear the content of all @var{password} elements in the data file "
5668 "while leaving off the trailing @key{TAB} would return all @var{password} "
5669 "elements in @abbr{XML} format."
5670 "@*@*"
5671 "When the @option{--inquire} option is passed then all remaining non-option "
5672 "arguments are retrieved via a server @emph{INQUIRE}."
5673 "@*@*"
5674 "See @url{https://www.w3schools.com/xml/xpath_intro.asp} for @abbr{XPATH} "
5675 "expression syntax."
5678 new_command("XPATHATTR", 0, 0, 1, 0, xpathattr_command, _(
5679 "XPATHATTR [--inquire] SET|DELETE <name> <expression>[<TAB>[<value>]]\n" /* Modifying more than one element's attributes. */
5680 "Like the @code{XPATH} command (@pxref{XPATH}) but operates on element "
5681 "attributes and does not return a result. For the @var{SET} operation the "
5682 "@var{value} is optional but the field is required. If not specified then "
5683 "the attribute value will be empty. For example:"
5684 "@sp 1\n"
5685 "@example\n"
5686 "XPATHATTR SET password //element[@@_name='password']@key{TAB}\n"
5687 "@end example\n"
5688 "@sp 1\n"
5689 "would create a @var{password} attribute for each @var{password} element "
5690 "found in the document. The attribute value will be empty but still exist."
5691 "@*@*"
5692 "When the @option{--inquire} option is passed then all remaining non-option "
5693 "arguments are retrieved via a server @emph{INQUIRE}."
5694 "@*@*"
5695 "See @url{https://www.w3schools.com/xml/xpath_intro.asp} for @abbr{XPATH} "
5696 "expression syntax."
5699 new_command("IMPORT", 0, 0, 1, 0, import_command, _(
5700 "IMPORT [--root=element[<TAB>child[..]]]\n" /* Creating elements from XML. */
5701 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
5702 "@*@*"
5703 "Like the @code{STORE} command (@pxref{STORE}), but the @var{content} "
5704 "argument is raw @abbr{XML} data. The content is created as a child of "
5705 "the element path specified with the @option{--root} option or at the "
5706 "document root when not specified. Existing elements of the same name will "
5707 "be overwritten."
5708 "@*@*"
5709 "The content must begin with an @abbr{XML} element node. @xref{Introduction}, "
5710 "for details."
5713 new_command("DUMP", 0, 1, 1, 0, dump_command, _(
5714 "DUMP\n" /* Showing the XML document. */
5715 "Shows the in memory @abbr{XML} document with indenting. @xref{XPATH}, for "
5716 "dumping a specific node."
5719 new_command("LOCK", 0, 0, 0, 0, lock_command, _(
5720 "LOCK\n" /* Locking the current data file. */
5721 "Locks the mutex associated with the opened file. This prevents other clients "
5722 "from sending commands to the same opened file until the client "
5723 "that sent this command either disconnects or sends the @code{UNLOCK} "
5724 "command. @xref{UNLOCK}."
5727 new_command("UNLOCK", 0, 1, 0, 0, unlock_command, _(
5728 "UNLOCK\n" /* Removing a data file lock. */
5729 "Unlocks the file mutex which was locked with the @code{LOCK} command or "
5730 "a commands' @option{--lock} option (@pxref{LOCK}, @pxref{OPEN}, "
5731 "@pxref{ISCACHED})."
5734 new_command("GETCONFIG", 0, 1, 1, 0, getconfig_command, _(
5735 "GETCONFIG [filename] <parameter>\n" /* Obtaining a configuration value. */
5736 "Returns the value of a @command{pwmd} configuration @var{parameter} with a "
5737 "data response. If no file has been opened then the value for @var{filename} "
5738 "or the default from the @var{global} section will be returned. If a file "
5739 "has been opened and no @var{filename} is specified, the value previously "
5740 "set with the @code{OPTION} command (@pxref{OPTION}) will be returned."
5743 new_command("OPTION", 0, 1, 1, 0, option_command, _(
5744 "OPTION <NAME>=[<VALUE>]\n" /* Setting various client parameters. */
5745 "Sets a client option @var{name} to @var{value}. The value for an option is "
5746 "kept for the duration of the connection with the exception of the "
5747 "@command{pinentry} options which are defaults for all future connections "
5748 "(@pxref{Pinentry}). When @var{value} is empty the option is unset."
5749 "@*@*"
5750 "@table @asis\n"
5751 "@item DISABLE-PINENTRY\n"
5752 "Disable use of @command{pinentry} for passphrase retrieval. When @code{1}, a "
5753 "server inquire is sent to the client to obtain the passphrase. This option "
5754 "may be set as needed before the @code{OPEN} (@pxref{OPEN}), @code{PASSWD} "
5755 "(@pxref{PASSWD}) and @code{SAVE} (@pxref{SAVE}) commands. Set to @code{0} "
5756 "to use a @command{pinentry}."
5757 "@*@*"
5758 "@item DISPLAY\n"
5759 "Set or unset the X11 display to use when prompting for a passphrase."
5760 "@*@*"
5761 "@item TTYNAME\n"
5762 "Set the terminal device path to use when prompting for a passphrase."
5763 "@*@*"
5764 "@item TTYTYPE\n"
5765 "Set the terminal type for use with @option{TTYNAME}."
5766 "@*@*"
5767 "@item NAME\n"
5768 "Associates the thread ID of the connection with the specified textual "
5769 "representation. Useful for debugging log messages. May not contain whitespace."
5770 "@*@*"
5771 "@item LOCK-TIMEOUT\n"
5772 "When not @code{0}, the duration in tenths of a second to wait for the file "
5773 "mutex which has been locked by another thread to be released before returning "
5774 "an error. When @code{-1} the error will be returned immediately."
5775 "@*@*"
5776 "@item CLIENT-STATE\n"
5777 "When set to @code{1} then client state status messages for other clients are "
5778 "sent to the current client. The default is @code{0}."
5779 "@end table\n"
5782 new_command("LS", 0, 1, 1, 0, ls_command, _(
5783 "LS [--verbose]\n" /* Showing available data files. */
5784 "Returns a newline separated list of data files stored in the data directory "
5785 "@file{HOMEDIR/data} (@pxref{Invoking}) with a data response. When the "
5786 "@var{--verbose} option is passed, the space-separated filesystem inode "
5787 "access, modification and change times are appended to the line."
5790 new_command("BULK", 0, 1, 1, 0, bulk_command, _(
5791 "BULK [--inquire]\n" /* Run a series of commands in sequence. */
5792 "Parses a semi-canonical s-expression representing a series of protocol "
5793 "commands to be run in sequence (@pxref{Bulk Commands}). Returns a canonical "
5794 "s-expression containing each commands id, return value and result data "
5795 "(if any)."
5796 "@*@*"
5797 "When the @option{--inquire} option is passed then all remaining non-option "
5798 "arguments are retrieved via a server @emph{INQUIRE}."
5801 new_command("RESET", 0, 1, 1, 0, NULL, _(
5802 "RESET\n" /* Resetting the client state. */
5803 "Closes the currently opened file but keeps any previously set client options "
5804 "(@pxref{OPTION})."
5807 new_command("NOP", 0, 1, 1, 0, nop_command, _(
5808 "NOP\n" /* Testing the connection. */
5809 "This command does nothing. It is useful for testing the connection for a "
5810 "timeout condition."
5813 /* !END-HELP-TEXT! */
5814 new_command ("CANCEL", 0, 1, 1, 0, NULL, NULL);
5815 new_command ("END", 0, 1, 1, 0, NULL, NULL);
5816 new_command ("BYE", 0, 1, 1, 0, NULL, NULL);
5818 int i;
5819 for (i = 0; command_table[i]; i++);
5820 qsort (command_table, i - 1, sizeof (struct command_table_s *),
5821 sort_commands);
5824 gpg_error_t
5825 register_commands (assuan_context_t ctx)
5827 int i = 0, rc;
5829 for (; command_table[i]; i++)
5831 if (!command_table[i]->handler)
5832 continue;
5834 rc = assuan_register_command (ctx, command_table[i]->name,
5835 command_table[i]->handler,
5836 command_table[i]->help);
5837 if (rc)
5838 return rc;
5841 rc = assuan_register_bye_notify (ctx, bye_notify);
5842 if (rc)
5843 return rc;
5845 rc = assuan_register_reset_notify (ctx, reset_notify);
5846 if (rc)
5847 return rc;
5849 rc = assuan_register_pre_cmd_notify (ctx, command_startup);
5850 if (rc)
5851 return rc;
5853 return assuan_register_post_cmd_notify (ctx, command_finalize);