docs: Fix some typos and grammer.
[pwmd.git] / src / commands.c
blob244fa61768c9f18176c00844b8bbac6c3b83bad2
1 /*
2 Copyright (C) 2006-2020 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 as published by
8 the Free Software Foundation, either version 2 of the License, or
9 (at your option) any later version.
11 Pwmd is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
19 #ifdef HAVE_CONFIG_H
20 #include <config.h>
21 #endif
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <unistd.h>
26 #include <err.h>
27 #include <errno.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <fcntl.h>
31 #include <ctype.h>
32 #include <dirent.h>
33 #include <pthread.h>
34 #include <stdint.h>
35 #include <assert.h>
36 #include <signal.h>
38 #include "pwmd-error.h"
39 #include <gcrypt.h>
41 #include "mem.h"
42 #include "xml.h"
43 #include "util-misc.h"
44 #include "common.h"
45 #include "rcfile.h"
46 #include "cache.h"
47 #include "commands.h"
48 #include "mutex.h"
49 #include "crypto.h"
50 #include "acl.h"
52 /* These are command option flags. */
53 #define OPT_INQUIRE 0x0001
54 #define OPT_NO_PASSPHRASE 0x0002
55 #define OPT_ASK 0x0004
56 #define OPT_LIST_RECURSE 0x0008
57 #define OPT_VERBOSE 0x0010
58 #define OPT_LOCK 0x0020
59 #define OPT_LOCK_ON_OPEN 0x0040
60 #define OPT_SIGN 0x0080
61 #define OPT_LIST_ALL 0x0100
62 #define OPT_DATA 0x0200
63 #define OPT_NO_AGENT 0x0400
64 #define OPT_SECRET 0x0800
65 #define OPT_INQUIRE_KEYID 0x1000
66 #define OPT_SYMMETRIC 0x4000
67 #define OPT_NO_SIGNER 0x8000
68 #define OPT_HTML 0x10000
69 #define OPT_CACHE_AGENT 0x20000
70 #define OPT_CACHE_SIGN 0x40000
71 #define OPT_KEYINFO_LEARN 0x80000
73 #define FLOCK_TYPE_NONE 0
74 #define FLOCK_TYPE_SH 0x0001
75 #define FLOCK_TYPE_EX 0x0002
76 #define FLOCK_TYPE_KEEP 0x0004
78 static char env_display[256];
79 static char env_gpg_tty[256];
80 static char env_term[256];
81 static struct command_table_s **command_table;
83 static gpg_error_t do_lock (struct client_s *client, int add);
84 static gpg_error_t validate_checksum (struct client_s *, const char *filename,
85 struct cache_data_s *, unsigned char **,
86 size_t *, int);
87 static gpg_error_t update_checksum (struct client_s *client,
88 unsigned char *from_crc, size_t crclen);
89 static gpg_error_t command_startup (assuan_context_t ctx, const char *name);
90 static void command_finalize (assuan_context_t ctx, gpg_error_t rc);
92 /* When 'status' is true the 'self' field of the status line will be false
93 * because we never send the STATE status message to the same client that
94 * initiated it. */
95 static char *
96 build_client_info_line (struct client_thread_s *thd, int status)
98 char *uid, *username = NULL;
99 char *line;
101 #ifdef WITH_GNUTLS
102 if (thd->remote)
103 uid = str_asprintf("#%s", thd->tls->fp);
104 else
106 uid = str_asprintf("%u", thd->peer->uid);
107 username = get_username (thd->peer->uid);
109 #else
110 uid = str_asprintf("%u", thd->peer->uid);
111 username = get_username (thd->peer->uid);
112 #endif
113 line = str_asprintf ("%p %s %s %s %u %u %u %s %s %u",
114 thd->tid,
115 thd->name ? thd->name : "-",
116 thd->cl && thd->cl->filename
117 && (thd->cl->flags & FLAG_OPEN)
118 ? thd->cl->filename : "/",
119 #ifdef WITH_GNUTLS
120 thd->remote ? thd->peeraddr : "-",
121 #else
122 "-",
123 #endif
124 thd->cl && thd->cl->flags & FLAG_HAS_LOCK ? 1 : 0,
125 !status && pthread_equal (pthread_self (), thd->tid) ? 1 : 0,
126 thd->state, uid,
127 #ifdef WITH_GNUTLS
128 thd->remote ? "-" : username,
129 #else
130 username,
131 #endif
132 thd->conntime
135 xfree (username);
136 xfree (uid);
137 return line;
140 void
141 update_client_state (struct client_s *client, unsigned s)
143 MUTEX_LOCK (&cn_mutex);
144 if (client->thd->state == s)
146 MUTEX_UNLOCK (&cn_mutex);
147 return;
149 client->thd->state = s;
150 MUTEX_UNLOCK (&cn_mutex);
152 if (client->thd->state != CLIENT_STATE_UNKNOWN)
154 char *line = build_client_info_line (client->thd, 1);
156 pthread_cleanup_push (xfree, line);
157 if (line)
158 send_status_all_not_self (STATUS_STATE, "%s", line);
159 pthread_cleanup_pop (1);
163 static gpg_error_t
164 unlock_file_mutex (struct client_s *client, int remove)
166 gpg_error_t rc = 0;
168 // OPEN: keep the lock for the same file being reopened.
169 if (client->flags & FLAG_KEEP_LOCK && client->flags & FLAG_HAS_LOCK)
170 return 0;
172 if (!(client->flags & FLAG_HAS_LOCK))
173 return GPG_ERR_NOT_LOCKED;
175 rc = cache_unlock_mutex (client->filename, remove);
176 if (rc)
177 rc = GPG_ERR_INV_STATE;
178 else
179 client->flags &= ~(FLAG_HAS_LOCK | FLAG_LOCK_CMD);
181 return rc;
184 static gpg_error_t
185 lock_file_mutex (struct client_s *client, int add)
187 gpg_error_t rc = 0;
188 long timeout = config_get_long (client->filename, "cache_timeout");
190 if (client->flags & FLAG_HAS_LOCK)
191 return 0;
193 rc = cache_lock_mutex (client->ctx, client->filename,
194 client->lock_timeout, add, timeout);
195 if (!rc)
196 client->flags |= FLAG_HAS_LOCK;
198 return rc;
201 static gpg_error_t
202 file_modified (struct client_s *client, struct command_table_s *cmd)
204 gpg_error_t rc = 0;
205 int type = !cmd->flock_type || (cmd->flock_type & FLOCK_TYPE_SH)
206 ? LOCK_SH : LOCK_EX;
208 if (!(client->flags & FLAG_OPEN))
209 return GPG_ERR_INV_STATE;
211 rc = lock_file_mutex (client, 0);
212 if (rc && rc != GPG_ERR_NO_DATA)
213 return rc;
215 rc = lock_flock (client->ctx, client->filename, type, &client->flock_fd);
216 if (!rc)
218 rc = validate_checksum (client, client->filename, NULL, NULL, NULL, 0);
219 if (gpg_err_code (rc) == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
220 rc = 0;
221 else if (rc)
222 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
224 else if (gpg_err_code (rc) == GPG_ERR_ENOENT)
225 rc = 0;
227 /* FLAG_HAS_LOCK may have been set by the LOCK command or OPEN --lock. */
228 if ((cmd->unlock && !(client->flags & FLAG_HAS_LOCK)) || rc)
229 unlock_file_mutex (client, 0);
231 if (rc || !(cmd->flock_type & FLOCK_TYPE_KEEP))
232 unlock_flock (&client->flock_fd);
234 return rc;
237 static gpg_error_t
238 parse_xml (assuan_context_t ctx, int new)
240 struct client_s *client = assuan_get_pointer (ctx);
241 int cached = client->doc != NULL;
242 gpg_error_t rc = 0;
244 if (new)
246 client->doc = xml_new_document ();
247 if (client->doc)
249 xmlChar *result;
250 int len;
252 xmlDocDumpFormatMemory (client->doc, &result, &len, 0);
253 client->crypto->plaintext = result;
254 client->crypto->plaintext_size = len;
255 if (!client->crypto->plaintext)
257 xmlFreeDoc (client->doc);
258 client->doc = NULL;
259 rc = GPG_ERR_ENOMEM;
262 else
263 rc = GPG_ERR_ENOMEM;
265 else if (!cached)
266 rc = xml_parse_doc ((char *) client->crypto->plaintext,
267 client->crypto->plaintext_size,
268 (xmlDocPtr *)&client->doc);
270 return rc;
273 static void
274 free_client (struct client_s *client)
276 cache_plaintext_release (&client->doc);
277 xfree (client->crc);
278 xfree (client->filename);
279 xfree (client->last_error);
280 crypto_free (client->crypto);
281 client->crypto = NULL;
284 void
285 reset_client (struct client_s *client)
287 assuan_context_t ctx = client->ctx;
288 struct client_thread_s *thd = client->thd;
289 long lock_timeout = client->lock_timeout;
290 xmlErrorPtr xml_error = client->xml_error;
291 int no_pinentry = (client->flags & FLAG_NO_PINENTRY);
292 int flock_fd = client->flock_fd;
293 struct bulk_cmd_s *bulk_p = client->bulk_p;
295 unlock_file_mutex (client, client->flags & FLAG_NEW);
296 free_client (client);
297 memset (client, 0, sizeof (struct client_s));
298 client->flock_fd = flock_fd;
299 client->xml_error = xml_error;
300 client->ctx = ctx;
301 client->thd = thd;
302 client->lock_timeout = lock_timeout;
303 client->flags |= no_pinentry ? FLAG_NO_PINENTRY : 0;
304 client->bulk_p = bulk_p;
307 static void
308 req_free (void *arg)
310 if (!arg)
311 return;
313 strv_free ((char **) arg);
316 static gpg_error_t
317 parse_open_opt_lock (void *data, void *value)
319 struct client_s *client = data;
321 (void)value;
322 client->opts |= OPT_LOCK_ON_OPEN;
323 return 0;
326 static gpg_error_t
327 parse_opt_inquire (void *data, void *value)
329 struct client_s *client = data;
331 (void) value;
332 client->opts |= OPT_INQUIRE;
333 return 0;
336 static gpg_error_t
337 update_checksum (struct client_s *client, unsigned char *from_crc,
338 size_t crclen)
340 unsigned char *crc;
341 size_t len;
342 struct cache_data_s *cdata;
343 gpg_error_t rc;
345 if (!from_crc)
347 rc = get_checksum (client->filename, &crc, &len);
348 if (rc)
349 return rc;
351 else
353 crc = from_crc;
354 len = crclen;
357 xfree (client->crc);
358 client->crc = xmalloc (len);
359 memcpy (client->crc, crc, len);
360 pthread_cleanup_push (xfree, crc);
361 cdata = cache_get_data (client->filename, NULL);
362 pthread_cleanup_pop (0);
363 if (cdata)
365 xfree (cdata->crc);
366 cdata->crc = xmalloc (len);
367 memcpy (cdata->crc, crc, len);
370 if (!from_crc)
371 xfree (crc);
372 return 0;
375 static gpg_error_t
376 validate_checksum (struct client_s *client, const char *filename,
377 struct cache_data_s *cdata, unsigned char **r_crc,
378 size_t *r_crclen, int from_cdata)
380 unsigned char *crc;
381 size_t len;
382 gpg_error_t rc;
383 int n = 0;
385 if (cdata && !cdata->crc)
386 return GPG_ERR_CHECKSUM;
388 rc = get_checksum (filename, &crc, &len);
389 if (rc)
390 return rc;
392 if (client->crc)
393 n = memcmp (client->crc, crc, len);
394 else if ((client->flags & FLAG_NEW) && cache_get_data (filename, NULL))
395 n = 1;
397 if ((!n && cdata) || (from_cdata && cdata && crc))
398 n = memcmp (cdata->crc, crc, len);
400 if (!n && r_crc)
402 *r_crc = crc;
403 *r_crclen = len;
405 else
406 xfree (crc);
408 return n ? GPG_ERR_CHECKSUM : 0;
411 static gpg_error_t
412 open_command (assuan_context_t ctx, char *line)
414 gpg_error_t rc;
415 struct client_s *client = assuan_get_pointer (ctx);
416 int same_file = 0;
417 assuan_peercred_t peer;
418 struct cache_data_s *cdata = NULL;
419 int cached = 0;
420 unsigned char *crc = NULL;
421 size_t crclen = 0;
422 int plaintext = 0;
423 struct argv_s *args[] = {
424 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_open_opt_lock},
425 NULL
428 rc = parse_options (&line, args, client, 1);
429 if (rc)
430 return send_error (ctx, rc);
432 rc = do_validate_peer (ctx, line, &peer, NULL);
433 if (rc == GPG_ERR_FORBIDDEN)
435 rc = peer_is_invoker (client);
436 if (rc == GPG_ERR_EACCES)
437 rc = GPG_ERR_FORBIDDEN;
440 if (rc)
441 return send_error (ctx, rc);
443 if (!valid_filename (line))
444 return send_error (ctx, GPG_ERR_INV_VALUE);
446 /* This client may have locked a different file with ISCACHED --lock than
447 * the current filename. This will remove that lock. */
448 same_file = client->filename && !strcmp (line, client->filename);
449 if (client->flags & FLAG_OPEN ||
450 (client->flags & FLAG_HAS_LOCK && !same_file))
452 unsigned opts = client->opts;
453 unsigned flags = client->flags;
455 if (same_file)
456 client->flags |= FLAG_KEEP_LOCK;
458 /* Another client wrote to the same data file as currently opened. */
459 cdata = cache_get_data (client->filename, NULL);
460 if (cdata && cdata->crc)
461 flags &= ~FLAG_NEW;
462 /* Remove cache entry for the new file that hadn't been written. */
463 else if (client->flags & FLAG_NEW)
464 cache_clear (NULL, client->filename, 0, 0);
466 cdata = NULL;
467 reset_client (client);
468 client->opts = opts;
469 client->flags |= flags;
470 client->flags &= ~(FLAG_LOCK_CMD);
471 if (!same_file)
472 client->flags &= ~(FLAG_HAS_LOCK | FLAG_NEW);
475 xfree (client->filename);
476 client->filename = str_dup (line);
477 if (!client->filename)
478 return send_error(ctx, GPG_ERR_ENOMEM);
480 /* Need to lock the mutex here because file_modified() cannot without
481 * knowing the filename. */
482 rc = lock_file_mutex (client, 1);
483 if (rc)
484 client->flags &= ~FLAG_OPEN;
486 if (!rc)
488 rc = lock_flock (ctx, client->filename, LOCK_SH, &client->flock_fd);
489 if (gpg_err_code (rc) == GPG_ERR_ENOENT)
490 rc = 0;
493 if (!rc)
495 char *keyfile = config_get_string (client->filename, "passphrase_file");
497 rc = crypto_init (&client->crypto, client->ctx, client->filename,
498 client->flags & FLAG_NO_PINENTRY, keyfile);
499 if (rc)
500 xfree (keyfile);
501 else
502 rc = open_check_file (client->filename, NULL, NULL, 1);
505 if (!rc || gpg_err_code (rc) == GPG_ERR_ENOENT)
507 int reload = 0;
508 int defer = 0;
510 if (rc) // new file
512 rc = 0;
514 if (config_get_boolean ("global", "strict_open"))
516 rc = peer_is_invoker (client);
517 if (rc == GPG_ERR_EACCES)
518 rc = GPG_ERR_FORBIDDEN;
521 if (!rc)
523 client->flags |= FLAG_NEW;
524 // data file disappeared. clear the cache entry.
525 cache_clear (NULL, client->filename, 1, 1);
526 cdata = NULL;
529 goto done;
532 cdata = cache_get_data (client->filename, &defer);
533 if (cdata && !defer
534 && !cache_plaintext_get (client->filename, &client->doc))
536 rc = validate_checksum (client, client->filename, cdata, &crc,
537 &crclen, 0);
538 if (rc)
540 log_write ("%s: %s", client->filename,
541 pwmd_strerror (rc));
542 cache_plaintext_release (&client->doc);
543 if (rc == GPG_ERR_CHECKSUM)
545 cache_clear (NULL, client->filename, 1, 1);
546 cdata = NULL;
547 goto decrypt;
551 #ifdef WITH_GNUTLS
552 if (!rc && client->thd->remote
553 && config_get_boolean (client->filename, "tcp_require_key")
554 && !(client->flags & FLAG_NEW))
556 rc = crypto_try_decrypt (client,
557 (client->flags & FLAG_NO_PINENTRY));
559 #endif
560 if (!rc)
562 strv_free (client->crypto->pubkey);
563 client->crypto->pubkey = NULL;
564 if (cdata->pubkey)
565 client->crypto->pubkey = strv_dup (cdata->pubkey);
567 xfree (client->crypto->sigkey);
568 client->crypto->sigkey = NULL;
569 if (cdata->sigkey)
570 client->crypto->sigkey = str_dup (cdata->sigkey);
572 cached = 1;
573 plaintext = 1;
576 else if (cdata && cdata->doc) // cached document
578 if (!rc && !(client->flags & FLAG_NEW))
580 rc = validate_checksum (client, client->filename, cdata, &crc,
581 &crclen, 0);
582 if (rc == GPG_ERR_CHECKSUM)
584 rc = 0;
585 reload = 1;
589 if (!rc)
591 rc = cache_iscached (client->filename, &defer, 0, 0);
592 if ((!rc || rc == GPG_ERR_ENOENT) && defer)
594 rc = 0;
595 reload = 2;
599 if (!rc && reload)
601 if (reload == 1)
602 log_write ("%s: %s", client->filename,
603 pwmd_strerror (GPG_ERR_CHECKSUM));
604 cache_clear (NULL, client->filename, 1, 1);
605 cdata = NULL;
606 rc = crypto_decrypt (client, client->crypto);
608 #ifdef WITH_GNUTLS
609 else if (!rc)
611 if (client->thd->remote
612 && config_get_boolean (client->filename, "tcp_require_key")
613 && !(client->flags & FLAG_NEW))
614 rc = crypto_try_decrypt (client,
615 (client->flags & FLAG_NO_PINENTRY));
617 #endif
619 if (!rc && cdata)
621 client->crypto->plaintext = cdata->doc;
622 client->crypto->plaintext_size = cdata->size;
623 rc = cache_decrypt (client->crypto);
624 if (!rc)
626 cdata->doc = NULL;
627 cdata->size = 0;
629 strv_free (client->crypto->pubkey);
630 client->crypto->pubkey = NULL;
631 if (cdata->pubkey)
632 client->crypto->pubkey = strv_dup (cdata->pubkey);
634 xfree (client->crypto->sigkey);
635 client->crypto->sigkey = NULL;
636 if (cdata->sigkey)
637 client->crypto->sigkey = str_dup (cdata->sigkey);
639 cached = 1;
641 else
643 client->crypto->plaintext = NULL;
644 client->crypto->plaintext_size = 0;
648 else // existing file
650 decrypt:
651 cached = cdata != NULL;
652 rc = crypto_decrypt (client, client->crypto);
656 done:
657 if (!rc && !plaintext)
659 rc = parse_xml (ctx, client->flags & FLAG_NEW);
660 if (!rc)
662 rc = cache_encrypt (client->crypto);
663 if (rc)
664 cache_clear (NULL, client->filename, 1, 1);
665 else
667 long timeout = config_get_long (client->filename,
668 "cache_timeout");
670 cache_free_data_once (cdata);
671 cdata = xcalloc (1, sizeof (struct cache_data_s));
672 cdata->doc = client->crypto->plaintext;
673 cdata->size = client->crypto->plaintext_size;
674 cdata->pubkey = strv_dup(client->crypto->pubkey);
675 cdata->sigkey = client->crypto->sigkey ? str_dup(client->crypto->sigkey) : NULL;
676 client->crypto->plaintext = NULL;
677 client->crypto->plaintext_size = 0;
679 if (cached) // wont increment the refcount
681 if (crclen)
683 xfree (client->crc);
684 client->crc = NULL;
685 xfree (cdata->crc);
686 cdata->crc = xmalloc (crclen);
687 memcpy (cdata->crc, crc, crclen);
690 rc = cache_set_data (client->filename, cdata);
691 /* The cache entry may have been removed and cache_set_data()
692 * already sent STATUS_CACHE. */
693 if (!cache_iscached (client->filename, NULL, 0, 0))
694 rc = send_status (ctx, STATUS_CACHE, NULL);
696 else
697 rc = cache_add_file (client->filename, cdata, timeout);
699 if (!rc)
700 cache_plaintext_set (client->filename, client->doc, 0);
705 if (!rc)
707 xfree (client->crc);
708 client->crc = NULL;
709 if (crc)
711 client->crc = xmalloc (crclen);
712 memcpy (client->crc, crc, crclen);
716 xfree (crc);
718 if (!rc && !(client->flags & FLAG_NEW) && !cached)
719 rc = update_checksum (client, NULL, 0);
721 if (!rc)
723 client->flags |= FLAG_OPEN;
725 if (client->flags & FLAG_NEW)
726 rc = send_status (ctx, STATUS_NEWFILE, NULL);
728 if (!rc && (client->opts & OPT_LOCK_ON_OPEN))
729 rc = do_lock (client, 0);
731 crypto_free_non_keys (client->crypto);
733 else
735 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
737 if (client->flags & FLAG_NEW)
738 cache_clear (NULL, client->filename, 1, 1);
740 crypto_free (client->crypto);
741 client->crypto = NULL;
742 client->flags &= ~FLAG_OPEN;
743 cache_plaintext_release (&client->doc);
746 return send_error (ctx, rc);
749 /* If not an invoking_user or is an existing file, check that the list of user
750 * supplied key ID's are in the list of current key ID's obtained when
751 * decrypting the data file.
753 static gpg_error_t
754 permitted_to_save (struct client_s *client, const char **keys,
755 const char **value)
757 gpg_error_t rc = 0;
758 const char **v;
760 if ((client->flags & FLAG_NEW) || (client->opts & OPT_SYMMETRIC))
761 return 0;
763 rc = peer_is_invoker (client);
764 if (!rc)
765 return 0;
766 else if (rc == GPG_ERR_EACCES)
767 rc = GPG_ERR_FORBIDDEN;
768 else if (rc)
769 return rc;
771 /* Empty match. */
772 if ((!value && !keys) || ((value && !*value) && (keys && !*keys)))
773 return 0;
775 for (v = value; v && *v; v++)
777 const char **k, *pv = *v;
778 int match = 0;
780 if (*pv == '0' && *(pv+1) == 'x')
781 pv += 2;
783 for (k = keys; k && *k; k++)
785 const char *pk = *k;
787 if (*pk == '0' && *(pk+1) == 'x')
788 pk += 2;
790 rc = !strcmp (pv, pk) ? 0 : GPG_ERR_FORBIDDEN;
791 if (rc)
792 rc = !strcmp (pv, *k) ? 0 : GPG_ERR_FORBIDDEN;
794 if (!rc)
796 match = 1;
797 break;
801 if (!match)
802 return GPG_ERR_FORBIDDEN;
805 return rc;
808 /* Requires that the keyid be a fingerprint in 16 byte form. */
809 static gpg_error_t
810 parse_save_opt_keyid_common (struct client_s *client, const char **list,
811 const char *value, char ***dst)
813 gpg_error_t rc = 0;
814 char **keys = NULL;
816 if (value && *value)
818 keys = str_split (value, ",", 0);
819 if (!keys)
820 return GPG_ERR_ENOMEM;
823 rc = crypto_keyid_to_16b (keys);
824 if (!rc)
825 rc = permitted_to_save (client, list, (const char **)keys);
827 if (!rc)
828 *dst = keys;
829 else
830 strv_free (keys);
832 return rc;
835 static gpg_error_t
836 parse_save_opt_keyid (void *data, void *value)
838 struct client_s *client = data;
839 const char *str = value;
840 char **dst = NULL;
841 gpg_error_t rc;
843 rc = parse_save_opt_keyid_common (client,
844 (const char **)client->crypto->pubkey,
845 str, &dst);
846 if (rc)
847 return rc;
849 client->crypto->save.pubkey = dst;
850 return 0;
853 static gpg_error_t
854 parse_save_opt_sign_keyid (void *data, void *value)
856 struct client_s *client = data;
857 const char *str = value;
858 char **dst = NULL;
859 gpg_error_t rc;
860 char **tmp = NULL;
862 if (client->crypto->sigkey)
864 if (!strv_printf (&tmp, "%s", client->crypto->sigkey))
865 return GPG_ERR_ENOMEM;
868 rc = parse_save_opt_keyid_common (client, (const char **)tmp, str, &dst);
869 strv_free (tmp);
870 if (rc)
871 return rc;
873 if (!dst)
874 client->opts |= OPT_NO_SIGNER;
875 else
876 client->crypto->save.sigkey = str_dup (*dst);
878 strv_free (dst);
879 return 0;
882 static gpg_error_t
883 parse_save_opt_inquire_keyid (void *data, void *value)
885 struct client_s *client = data;
887 (void)value;
889 if (!(client->flags & FLAG_NEW))
891 gpg_error_t rc = peer_is_invoker (client);
893 if (rc)
894 return rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc;
897 client->opts |= OPT_INQUIRE_KEYID;
898 return 0;
901 static gpg_error_t
902 parse_save_opt_symmetric (void *data, void *value)
904 struct client_s *client = data;
906 (void)value;
907 client->opts |= OPT_SYMMETRIC;
908 return 0;
911 static gpg_error_t
912 parse_genkey_opt_userid (void *data, void *value)
914 struct client_s *client = data;
916 if (!(client->flags & FLAG_NEW))
918 gpg_error_t rc = peer_is_invoker (client);
920 if (rc)
921 return rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc;
924 client->crypto->save.userid = str_dup (value);
925 return client->crypto->save.userid ? 0 : GPG_ERR_ENOMEM;
928 static gpg_error_t
929 parse_genkey_opt_algo (void *data, void *value)
931 struct client_s *client = data;
933 client->crypto->save.algo = str_dup (value);
934 return client->crypto->save.algo ? 0 : GPG_ERR_ENOMEM;
937 static gpg_error_t
938 parse_genkey_opt_no_expire (void *data, void *value)
940 struct client_s *client = data;
942 client->crypto->save.flags |= GPGME_CREATE_NOEXPIRE;
943 return 0;
946 static gpg_error_t
947 parse_genkey_opt_expire (void *data, void *value)
949 struct client_s *client = data;
950 gpg_error_t rc = 0;
951 char *p = NULL;
952 unsigned long t;
954 errno = 0;
955 t = strtoul (value, &p, 10);
957 if (!errno && p && *p)
958 rc = GPG_ERR_INV_VALUE;
959 else if (t == ULONG_MAX)
960 rc = GPG_ERR_INV_VALUE;
961 else if (errno)
962 rc = gpg_error_from_syserror ();
963 else
964 client->crypto->save.expire = t;
966 return rc;
969 static gpg_error_t
970 parse_genkey_opt_no_passphrase (void *data, void *value)
972 struct client_s *client = data;
974 (void)value;
975 client->crypto->save.flags |= GPGME_CREATE_NOPASSWD;
976 return 0;
979 /* Tests that the keys in new_keys are also in old_keys. */
980 static gpg_error_t
981 compare_keys (char **new_keys, char **old_keys)
983 char **o;
985 if (!old_keys || !*old_keys)
986 return 0;
988 crypto_keyid_to_16b (new_keys);
990 for (o = old_keys; *o; o++)
992 char **n;
994 for (n = new_keys; *n; n++)
996 if (!strcmp (*n, *o))
997 break;
1000 if (!*n)
1001 return GPG_ERR_NOT_FOUND;
1004 return 0;
1007 static gpg_error_t
1008 inquire_keyid (struct client_s *client)
1010 gpg_error_t rc;
1011 unsigned char *result = NULL;
1012 size_t len;
1013 const char *s = "KEYID";
1014 char ***orig;
1015 char ***save;
1017 orig = &client->crypto->pubkey;
1018 save = &client->crypto->save.pubkey;
1019 rc = assuan_inquire (client->ctx, s, &result, &len, 0);
1020 if (!rc)
1022 char **dst = NULL;
1024 rc = parse_save_opt_keyid_common (client, (const char **)*orig,
1025 (char *)result, &dst);
1026 if (!rc)
1027 *save = dst;
1030 xfree (result);
1031 return rc;
1035 /* When a key lookup in gpg-agent's cache fails, the agent tries the last
1036 * successful key to be unlocked. This prevents pwmd from successfully
1037 * clearing a signing key since the previous key, which more than likely
1038 * belongs to the same keypair as the encryption/decryption key, will have the
1039 * passphrase cached and therefore the signing key also cached. So we need to
1040 * clear both the signing and encryption keys to get the effect of requiring a
1041 * passphrase when generating a new keypair for an existing data file, or when
1042 * the "require_save_key" configuration parameter is set. This parameter is
1043 * mostly a failsafe of the gpg-agent option --ignore-cache-for-signing since
1044 * some/most/all users may fail to set it.
1046 static gpg_error_t
1047 save_command (assuan_context_t ctx, char *line)
1049 struct client_s *client = assuan_get_pointer (ctx);
1050 struct cache_data_s *cdata = NULL;
1051 int sym = 0;
1052 gpg_error_t rc = 0, cache_rc = 0;
1053 int defer = 0;
1054 struct argv_s *args[] = {
1055 &(struct argv_s) {"keyid", OPTION_TYPE_ARG, parse_save_opt_keyid},
1056 &(struct argv_s) {"inquire-keyid", OPTION_TYPE_NOARG,
1057 parse_save_opt_inquire_keyid },
1058 &(struct argv_s) {"sign-keyid", OPTION_TYPE_OPTARG,
1059 parse_save_opt_sign_keyid},
1060 &(struct argv_s) {"symmetric", OPTION_TYPE_NOARG,
1061 parse_save_opt_symmetric },
1062 NULL
1065 crypto_free_save (&client->crypto->save);
1066 client->crypto->save.expire = DEFAULT_EXPIRE;
1068 rc = crypto_is_symmetric (client->filename);
1069 if (!rc || rc == GPG_ERR_BAD_DATA || rc == GPG_ERR_ENOENT)
1071 if (!rc)
1073 client->opts |= OPT_SYMMETRIC;
1074 sym = 1;
1076 else if (rc == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
1077 rc = 0; // New file
1078 else
1079 rc = 0; // PKI
1082 if (rc)
1083 return send_error (ctx, rc);
1085 rc = parse_options (&line, args, client, 0);
1086 if (rc)
1087 return send_error (ctx, rc);
1089 if (config_get_boolean (client->filename, "require_save_key")
1090 || (client->opts & OPT_SYMMETRIC))
1091 client->opts |= OPT_ASK;
1093 rc = open_check_file (client->filename, NULL, NULL, 1);
1094 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
1096 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
1097 return send_error (ctx, rc);
1100 if (!rc)
1101 cache_rc = rc = cache_iscached (client->filename, &defer, 0, 1);
1103 if (gpg_err_code (rc) == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
1104 rc = 0;
1105 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
1106 rc = 0;
1108 if (rc)
1109 return send_error (ctx, rc);
1111 /* Specifying both a recipient and symmetric encryption is an error. */
1112 if ((client->opts & OPT_INQUIRE_KEYID) && (client->opts & OPT_SYMMETRIC))
1113 return send_error (ctx, GPG_ERR_CONFLICT);
1114 /* Existing file with a recipient and wanting symmetric is an error. */
1115 else if ((client->opts & OPT_SYMMETRIC) && client->crypto->save.pubkey)
1116 return send_error (ctx, GPG_ERR_CONFLICT);
1117 else if (client->crypto->save.pubkey && (client->opts & OPT_INQUIRE_KEYID))
1118 return send_error (ctx, GPG_ERR_CONFLICT);
1119 else if (!sym && (client->opts & OPT_SYMMETRIC) && !(client->flags & FLAG_NEW))
1120 return send_error (ctx, GPG_ERR_CONFLICT);
1121 /* New file that is not symmetric without either a recipient or signer. */
1122 else if ((client->flags & FLAG_NEW) && !(client->opts & OPT_SYMMETRIC)
1123 && (!client->crypto->save.pubkey || !client->crypto->save.sigkey))
1124 return send_error (ctx, GPG_ERR_SYNTAX);
1125 else if (client->opts & OPT_INQUIRE_KEYID)
1126 rc = inquire_keyid (client);
1128 if (!rc)
1130 client->crypto->keyfile = config_get_string (client->filename,
1131 "passphrase_file");
1132 rc = crypto_init_ctx (client->crypto, (client->flags & FLAG_NO_PINENTRY),
1133 client->crypto->keyfile);
1136 if (!rc && (client->flags & FLAG_NEW))
1138 /* Require --keyid when --sign-keyid exists to keep KEYINFO
1139 * synchronized. */
1140 if (!client->crypto->save.pubkey && client->crypto->save.sigkey
1141 && !(client->opts & OPT_SYMMETRIC))
1142 rc = GPG_ERR_NO_PUBKEY;
1144 else if (!rc)
1146 cdata = cache_get_data (client->filename, NULL);
1147 if (cdata)
1149 if (client->crypto->save.pubkey)
1150 rc = compare_keys (client->crypto->save.pubkey, cdata->pubkey);
1152 /* Always allow a signer for symmetric data files. */
1153 if (!rc && client->crypto->save.sigkey
1154 && !(client->opts & OPT_SYMMETRIC))
1155 rc = !strcmp (client->crypto->save.sigkey, cdata->sigkey)
1156 ? 0 : GPG_ERR_NOT_FOUND;
1158 /* Prevent saving to a recipient who is not in the original recipient
1159 * list without a passphrase. */
1160 if (rc || (client->crypto->sigkey && (client->opts & OPT_NO_SIGNER)))
1161 client->opts |= OPT_ASK;
1163 if (rc == GPG_ERR_NOT_FOUND)
1165 rc = peer_is_invoker (client);
1166 if (rc == GPG_ERR_EACCES)
1167 rc = GPG_ERR_FORBIDDEN;
1170 if (!client->crypto->save.pubkey
1171 && !(client->opts & OPT_SYMMETRIC))
1172 client->crypto->save.pubkey = strv_dup (cdata->pubkey);
1174 if (!rc && !client->crypto->save.sigkey && cdata->sigkey
1175 && !(client->opts & OPT_NO_SIGNER))
1176 client->crypto->save.sigkey = str_dup (cdata->sigkey);
1177 else if (!rc && !client->crypto->save.sigkey
1178 && (client->opts & OPT_NO_SIGNER)
1179 && !(client->opts & OPT_SYMMETRIC))
1180 rc = GPG_ERR_NO_SIGNATURE_SCHEME;
1182 else
1184 client->crypto->save.pubkey = strv_dup (client->crypto->pubkey);
1185 client->crypto->save.sigkey = str_dup (client->crypto->sigkey);
1189 if (!rc && !(client->flags & FLAG_NEW))
1191 /* Fixes {NEW_,SIGN_}PASSPHRASE inquire keywords. See passphrase_cb(). */
1192 if (client->opts & OPT_SYMMETRIC)
1193 client->crypto->flags |= CRYPTO_FLAG_PASSWD;
1195 if (client->opts & OPT_ASK)
1197 rc = cache_clear_agent_keys (client->filename, 1, 1);
1198 if (!rc)
1199 rc = crypto_try_decrypt (client, client->flags & FLAG_NO_PINENTRY);
1203 if (!rc && client->opts & OPT_SYMMETRIC)
1204 client->crypto->flags |= CRYPTO_FLAG_PASSWD_NEW;
1206 if (!rc)
1207 rc = xml_update_element_mtime (client, xmlDocGetRootElement (client->doc));
1209 if (!rc)
1211 xmlNodePtr root = xmlDocGetRootElement (client->doc);
1213 rc = xml_add_attribute (client, root, "_version", PACKAGE_VERSION);
1216 if (!rc)
1218 int size;
1220 xmlDocDumpFormatMemory (client->doc, &client->crypto->plaintext, &size,
1222 if (size > 0)
1223 client->crypto->plaintext_size = (size_t) size;
1224 else
1225 rc = GPG_ERR_ENOMEM;
1227 if (!rc)
1229 client->crypto->flags |= (client->opts & OPT_SYMMETRIC) ? CRYPTO_FLAG_SYMMETRIC : 0;
1230 client->crypto->flags |= (client->flags & FLAG_NEW) ? CRYPTO_FLAG_NEWFILE : 0;
1231 client->crypto->flags |= !(client->opts & OPT_SYMMETRIC) ? CRYPTO_FLAG_PASSWD_SIGN : 0;
1232 rc = crypto_encrypt (client, client->crypto);
1233 client->crypto->flags &= ~CRYPTO_FLAG_SYMMETRIC;
1236 if (!rc)
1238 unsigned char *crc = NULL;
1239 size_t crclen = 0;
1241 rc = crypto_write_file (client->crypto, &crc, &crclen);
1242 pthread_cleanup_push ((void *)xfree, crc);
1243 if (!rc)
1245 if (!cache_rc)
1246 cdata = cache_get_data (client->filename, NULL);
1247 else
1248 cdata = xcalloc (1, sizeof (struct cache_data_s));
1251 if (!rc)
1253 rc = cache_encrypt (client->crypto);
1254 if (rc)
1256 cache_clear (NULL, client->filename, 1, 1);
1257 client->flags &= ~(FLAG_NEW);
1259 strv_free (client->crypto->pubkey);
1260 client->crypto->pubkey = NULL;
1261 if (client->crypto->save.pubkey)
1262 client->crypto->pubkey = strv_dup (client->crypto->save.pubkey);
1264 xfree (client->crypto->sigkey);
1265 client->crypto->sigkey = NULL;
1266 if (client->crypto->save.sigkey)
1267 client->crypto->sigkey = str_dup (client->crypto->save.sigkey);
1271 if (!rc)
1273 long timeout = config_get_long (client->filename, "cache_timeout");
1274 xmlDocPtr doc = xmlCopyDoc (client->doc, 1);
1276 if (!doc)
1277 rc = GPG_ERR_ENOMEM;
1279 if (!rc)
1281 cache_plaintext_release (&client->doc);
1282 strv_free (cdata->pubkey);
1283 cdata->pubkey = client->crypto->save.pubkey;
1284 client->crypto->save.pubkey = NULL;
1286 xfree (cdata->sigkey);
1287 cdata->sigkey = client->crypto->save.sigkey;
1288 client->crypto->save.sigkey = NULL;
1290 xfree (cdata->crc);
1291 cdata->crc = NULL;
1293 /* cache_encrypt() does in-place encryption */
1294 xfree (cdata->doc);
1295 cdata->doc = client->crypto->plaintext;
1296 client->crypto->plaintext = NULL;
1297 cdata->size = client->crypto->plaintext_size;
1298 client->crypto->plaintext_size = 0;
1300 client->doc = doc;
1301 cache_plaintext_set (client->filename, client->doc, 0);
1303 /* Update in case the cache entry expires the next SAVE may
1304 * not have any known keys. */
1305 strv_free (client->crypto->pubkey);
1306 client->crypto->pubkey = NULL;
1307 if (cdata->pubkey)
1308 client->crypto->pubkey = strv_dup (cdata->pubkey);
1310 xfree (client->crypto->sigkey);
1311 client->crypto->sigkey = NULL;
1312 if (cdata->sigkey)
1313 client->crypto->sigkey = str_dup (cdata->sigkey);
1315 if (!cache_rc) // wont increment refcount
1316 rc = cache_set_data (client->filename, cdata);
1317 else
1318 rc = cache_add_file (client->filename, cdata, timeout);
1321 if (!rc && (cache_rc || (client->flags & FLAG_NEW)))
1322 send_status_all (STATUS_CACHE, NULL);
1324 if (!rc)
1326 rc = update_checksum (client, crc, crclen);
1327 client->flags &= ~(FLAG_NEW);
1331 pthread_cleanup_pop (1);
1332 if (!rc)
1333 client->did_cow = 0;
1337 crypto_free_non_keys (client->crypto);
1338 return send_error (ctx, rc);
1341 static gpg_error_t
1342 parse_genkey_opt_usage (void *data, void *v)
1344 struct client_s *client = data;
1345 char *value = v;
1347 if (!value || !*value)
1348 return GPG_ERR_INV_VALUE;
1349 else if (!strcmp (value, "sign"))
1350 client->crypto->save.flags |= GPGME_CREATE_SIGN;
1351 else if (!strcmp (value, "encrypt"))
1352 client->crypto->save.flags |= GPGME_CREATE_ENCR;
1353 else if (!strcmp (value, "default"))
1354 client->crypto->save.flags &= ~(GPGME_CREATE_ENCR|GPGME_CREATE_SIGN);
1355 else
1356 return GPG_ERR_INV_VALUE;
1358 return 0;
1361 gpg_error_t
1362 parse_genkey_opt_subkey_of (void *data, void *v)
1364 gpg_error_t rc;
1365 struct client_s *client = data;
1366 char *value = v;
1367 char *tmp[] = { value, NULL };
1368 gpgme_key_t *keys = NULL;
1370 rc = peer_is_invoker (client);
1371 if (rc)
1372 return rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc;
1374 if (!value || !*value)
1375 return GPG_ERR_INV_VALUE;
1377 rc = crypto_list_keys (client->crypto, tmp, 1, &keys);
1378 if (rc)
1379 return rc;
1381 if (!keys || !*keys)
1383 crypto_free_key_list (keys);
1384 return GPG_ERR_NO_SECKEY;
1387 client->crypto->save.mainkey = keys;
1388 return 0;
1391 static gpg_error_t
1392 genkey_command (assuan_context_t ctx, char *line)
1394 struct client_s *client = assuan_get_pointer (ctx);
1395 struct crypto_s *crypto, *orig;
1396 gpg_error_t rc = 0;
1397 struct argv_s *args[] = {
1398 &(struct argv_s) {"userid", OPTION_TYPE_ARG,
1399 parse_genkey_opt_userid},
1400 &(struct argv_s) {"expire", OPTION_TYPE_ARG,
1401 parse_genkey_opt_expire},
1402 &(struct argv_s) {"no-expire", OPTION_TYPE_NOARG,
1403 parse_genkey_opt_no_expire},
1404 &(struct argv_s) {"algo", OPTION_TYPE_ARG,
1405 parse_genkey_opt_algo},
1406 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG,
1407 parse_genkey_opt_no_passphrase},
1408 &(struct argv_s) {"usage", OPTION_TYPE_ARG,
1409 parse_genkey_opt_usage},
1410 &(struct argv_s) {"subkey-of", OPTION_TYPE_ARG,
1411 parse_genkey_opt_subkey_of},
1412 NULL
1415 if (!(client->flags & FLAG_OPEN))
1416 return send_error (ctx, GPG_ERR_INV_STATE);
1418 rc = crypto_init (&crypto, ctx, client->filename,
1419 client->flags & FLAG_NO_PINENTRY, NULL);
1420 if (rc)
1421 return send_error (ctx, rc);
1423 pthread_cleanup_push ((void *)crypto_free, client->crypto);
1424 orig = client->crypto;
1425 client->crypto = crypto;
1426 rc = parse_options (&line, args, client, 0);
1427 if (!rc)
1429 if (!client->crypto->save.userid && !client->crypto->save.mainkey)
1430 rc = GPG_ERR_SYNTAX;
1431 else
1433 client->crypto->flags |= CRYPTO_FLAG_NEWFILE;
1434 rc = crypto_genkey (client, client->crypto);
1438 pthread_cleanup_pop (0);
1439 crypto_free (crypto);
1440 client->crypto = orig;
1441 return send_error (ctx, rc);
1444 static gpg_error_t
1445 do_delete (assuan_context_t ctx, char *line)
1447 struct client_s *client = assuan_get_pointer (ctx);
1448 struct xml_request_s *req;
1449 xmlNodePtr n;
1450 gpg_error_t rc;
1452 if (!line || !*line)
1453 return GPG_ERR_SYNTAX;
1455 rc = xml_new_request (client, line, XML_CMD_DELETE, &req);
1456 if (rc)
1457 return rc;
1459 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1460 xml_free_request (req);
1461 if (rc)
1462 return rc;
1464 rc = xml_is_element_owner (client, n);
1465 if (!rc)
1466 rc = xml_unlink_node (client, n);
1468 return rc;
1471 /* Won't update cdata->plaintext. Other clients are working on the original or
1472 * copy of the same document. The first client to SAVE wins and requires others
1473 * to reopen the data file do to a checksum error. */
1474 static gpg_error_t
1475 copy_on_write (struct client_s *client)
1477 struct cache_data_s *cdata;
1479 if (client->did_cow)
1480 return 0;
1482 cdata = cache_get_data (client->filename, NULL);
1483 if (cdata)
1485 gpg_error_t rc;
1486 xmlDocPtr doc = xmlCopyDoc (client->doc, 1);
1488 if (!doc)
1489 return GPG_ERR_ENOMEM;
1491 rc = cache_plaintext_set (client->filename, doc, 1);
1492 if (rc)
1494 xmlFree (doc);
1495 return rc;
1498 (void)cache_plaintext_release (&client->doc);
1499 client->doc = doc;
1500 client->did_cow = 1;
1501 return 0;
1504 return GPG_ERR_NO_DATA;
1507 static gpg_error_t
1508 delete_command (assuan_context_t ctx, char *line)
1510 struct client_s *client = assuan_get_pointer (ctx);
1511 gpg_error_t rc;
1512 struct argv_s *args[] = {
1513 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1514 NULL
1517 rc = parse_options (&line, args, client, 1);
1518 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1519 rc = GPG_ERR_SYNTAX;
1520 if (rc)
1521 return send_error (ctx, rc);
1523 rc = copy_on_write (client);
1524 if (rc)
1525 return send_error (ctx, rc);
1527 if (client->opts & OPT_INQUIRE)
1529 unsigned char *result;
1530 size_t len;
1532 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1533 if (rc)
1534 return send_error (ctx, rc);
1536 pthread_cleanup_push ((void *)xfree, result);
1537 rc = do_delete (ctx, (char *)result);
1538 pthread_cleanup_pop (1);
1540 else
1541 rc = do_delete (ctx, line);
1543 return send_error (ctx, rc);
1546 static gpg_error_t
1547 update_element_expirey (struct client_s *client, xmlNodePtr n)
1549 gpg_error_t rc = 0;
1550 xmlChar *expire, *incr;
1551 char *p;
1552 time_t e, e_orig, i;
1553 time_t now = time (NULL);
1555 expire = xml_attribute_value (n, (xmlChar *)"_expire");
1556 if (!expire)
1557 return 0;
1559 errno = 0;
1560 e = strtoul ((char *)expire, &p, 10);
1561 if (errno || *p || e == ULONG_MAX || *expire == '-')
1563 xmlFree (expire);
1564 rc = GPG_ERR_ERANGE;
1565 goto fail;
1568 xmlFree (expire);
1569 incr = xml_attribute_value (n, (xmlChar *)"_age");
1570 if (!incr)
1571 return 0;
1573 i = strtoul ((char *)incr, &p, 10);
1574 if (errno || *p || i == ULONG_MAX || *incr == '-')
1576 xmlFree (incr);
1577 rc = GPG_ERR_ERANGE;
1578 goto fail;
1581 xmlFree (incr);
1582 e_orig = e;
1583 e = now + i;
1584 p = str_asprintf ("%lu", e);
1585 if (!p)
1587 rc = GPG_ERR_ENOMEM;
1588 goto fail;
1591 rc = xml_add_attribute (client, n, "_expire", p);
1592 xfree (p);
1593 if (!rc)
1594 rc = send_status (client->ctx, STATUS_EXPIRE, "%lu %lu", e_orig, e);
1596 fail:
1597 return rc;
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;
1612 if (!client->bulk_p && line && *line)
1613 return send_error (ctx, GPG_ERR_SYNTAX);
1615 rc = copy_on_write (client);
1616 if (rc)
1617 return send_error (ctx, rc);
1619 if (!client->bulk_p)
1621 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1622 if (rc)
1623 return send_error (ctx, rc);
1624 rc = xml_new_request (client, (char *)result, XML_CMD_STORE, &req);
1625 if (!result || !*result)
1627 xfree (result);
1628 return send_error (ctx, GPG_ERR_SYNTAX);
1631 len = strv_length (req->args);
1632 has_content = result[strlen ((char *)result) - 1] != '\t' && len > 1;
1633 xfree (result);
1635 else
1637 rc = xml_new_request (client, line, XML_CMD_STORE, &req);
1638 len = strv_length (req->args);
1639 has_content = line && line[strlen (line) - 1] != '\t' && len > 1;
1642 if (rc)
1643 return send_error (ctx, rc);
1645 /* Prevent passing the element content around to save some memory
1646 * (has_content). */
1647 if (*(req->args+1) && !xml_valid_element_path (req->args, has_content))
1649 xml_free_request (req);
1650 return send_error (ctx, GPG_ERR_INV_VALUE);
1653 if (has_content || !*req->args[len-1])
1655 content = req->args[len-1];
1656 req->args[len-1] = NULL;
1659 if (strv_length (req->args) > 1)
1661 rc = xml_check_recursion (client, req);
1662 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
1663 goto fail;
1666 parent = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1668 if (!rc && len > 1)
1670 rc = xml_is_element_owner (client, parent);
1671 if (!rc)
1673 n = xml_find_text_node (parent->children);
1674 if (n)
1675 xmlNodeSetContent (n, (xmlChar *) content);
1676 else
1677 xmlNodeAddContent (parent, (xmlChar *) content);
1679 (void)xml_update_element_mtime (client, parent);
1680 (void)update_element_expirey (client, parent);
1684 fail:
1685 xfree (content);
1686 xml_free_request (req);
1687 return send_error (ctx, rc);
1690 static gpg_error_t
1691 xfer_data (assuan_context_t ctx, const char *line, int total)
1693 struct client_s *client = assuan_get_pointer (ctx);
1694 int to_send = total < ASSUAN_LINELENGTH ? total : ASSUAN_LINELENGTH;
1695 int sent = 0;
1696 gpg_error_t rc = 0;
1698 if (!(client->flags & FLAG_LOCK_CMD))
1699 rc = unlock_file_mutex (client, 0);
1700 if (rc && rc != GPG_ERR_NOT_LOCKED)
1701 return rc;
1703 if (client->bulk_p)
1705 client->bulk_p->result = xmalloc (total+1);
1706 if (!client->bulk_p->result)
1707 return GPG_ERR_ENOMEM;
1708 memcpy (client->bulk_p->result, line, total);
1709 client->bulk_p->result[total] = 0;
1710 client->bulk_p->result_len = total;
1711 return 0;
1714 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1715 if (rc)
1716 return rc;
1720 if (sent + to_send > total)
1721 to_send = total - sent;
1723 rc = assuan_send_data (ctx, (char *) line + sent, to_send);
1724 if (!rc)
1725 sent += to_send;
1727 while (!rc && sent < total);
1729 return rc;
1732 static gpg_error_t
1733 do_get (assuan_context_t ctx, char *line)
1735 struct client_s *client = assuan_get_pointer (ctx);
1736 gpg_error_t rc;
1737 struct xml_request_s *req;
1738 xmlNodePtr n;
1740 if (!line || !*line)
1741 return GPG_ERR_SYNTAX;
1743 rc = xml_new_request (client, line, XML_CMD_NONE, &req);
1744 if (rc)
1745 return rc;
1747 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1748 if (!rc)
1750 if (n && n->children)
1752 xmlNodePtr tmp = n;
1754 n = xml_find_text_node (n->children);
1755 if (!n || !n->content || !*n->content)
1756 rc = GPG_ERR_NO_DATA;
1757 else
1759 rc = xfer_data (ctx, (char *) n->content, xmlStrlen (n->content));
1760 if (!rc)
1762 xmlChar *expire = xml_attribute_value (tmp,
1763 (xmlChar *)"_expire");
1764 if (expire)
1766 time_t now = time (NULL);
1767 time_t e;
1768 char *p;
1770 errno = 0;
1771 e = strtoul ((char *)expire, &p, 10);
1772 if (errno || *p || e == ULONG_MAX || *expire == '-')
1773 log_write (_("invalid expire attribute value: %s"),
1774 expire);
1775 else if (now >= e)
1777 pthread_cleanup_push (xmlFree, expire);
1778 rc = send_status (ctx, STATUS_EXPIRE, "%lu 0", e);
1779 pthread_cleanup_pop (0);
1782 xmlFree (expire);
1787 else
1788 rc = GPG_ERR_NO_DATA;
1791 xml_free_request (req);
1792 return rc;
1795 static gpg_error_t
1796 get_command (assuan_context_t ctx, char *line)
1798 struct client_s *client = assuan_get_pointer (ctx);
1799 gpg_error_t rc;
1800 struct argv_s *args[] = {
1801 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1802 NULL
1805 rc = parse_options (&line, args, client, 1);
1806 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1807 rc = GPG_ERR_SYNTAX;
1808 if (rc)
1809 return send_error (ctx, rc);
1811 if (client->opts & OPT_INQUIRE)
1813 unsigned char *result;
1814 size_t len;
1816 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1817 if (rc)
1818 return send_error (ctx, rc);
1820 pthread_cleanup_push ((void *)xfree, result);
1821 rc = do_get (ctx, (char *)result);
1822 pthread_cleanup_pop (1);
1824 else
1825 rc = do_get (ctx, line);
1827 return send_error (ctx, rc);
1830 static void list_command_free1 (void *arg);
1831 static gpg_error_t
1832 realpath_command (assuan_context_t ctx, char *line)
1834 gpg_error_t rc;
1835 char **realpath = NULL;
1836 struct client_s *client = assuan_get_pointer (ctx);
1837 struct argv_s *args[] = {
1838 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1839 NULL
1842 rc = parse_options (&line, args, client, 1);
1843 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1844 rc = GPG_ERR_SYNTAX;
1845 if (rc)
1846 return send_error (ctx, rc);
1848 if (client->opts & OPT_INQUIRE)
1850 unsigned char *result;
1851 size_t len;
1853 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1854 if (rc)
1855 return send_error (ctx, rc);
1857 pthread_cleanup_push ((void *)xfree, result);
1858 (void)xml_resolve_path (client, client->doc, result, &realpath, &rc);
1859 pthread_cleanup_pop (1);
1861 else
1862 (void)xml_resolve_path (client, client->doc, (unsigned char *)line,
1863 &realpath, &rc);
1865 if (!rc)
1867 char *tmp = strv_join ((char *)"\t", realpath);
1869 strv_free (realpath);
1870 if (!tmp)
1871 return send_error (ctx, GPG_ERR_ENOMEM);
1873 pthread_cleanup_push ((void *)xfree, tmp);
1874 rc = xfer_data (ctx, tmp, strlen (tmp));
1875 pthread_cleanup_pop (1);
1878 return send_error (ctx, rc);
1881 static void
1882 list_command_free1 (void *arg)
1884 if (arg)
1885 string_free ((struct string_s *) arg, 1);
1888 static gpg_error_t
1889 parse_list_opt_recurse (void *data, void *value)
1891 struct client_s *client = data;
1893 (void)value;
1894 client->opts |= OPT_LIST_RECURSE;
1895 return 0;
1898 static gpg_error_t
1899 parse_opt_verbose (void *data, void *value)
1901 struct client_s *client = data;
1903 (void)value;
1904 client->opts |= OPT_VERBOSE;
1905 return 0;
1908 static gpg_error_t
1909 list_path_once (struct client_s *client, char *line,
1910 struct element_list_s *elements, struct string_s *result)
1912 gpg_error_t rc;
1914 rc = xml_create_path_list (client, client->doc, NULL, elements, line, 0);
1915 if (rc == GPG_ERR_ELOOP || rc == GPG_ERR_EACCES)
1916 rc = 0;
1918 if (!rc)
1920 int total = slist_length (elements->list);
1922 if (total)
1924 int i;
1926 for (i = 0; i < total; i++)
1928 char *tmp = slist_nth_data (elements->list, i);
1930 string_append_printf (result, "%s%s", tmp,
1931 i + 1 == total ? "" : "\n");
1934 else
1935 rc = GPG_ERR_NO_DATA;
1938 return rc;
1941 static gpg_error_t
1942 do_list (assuan_context_t ctx, char *line)
1944 struct client_s *client = assuan_get_pointer (ctx);
1945 gpg_error_t rc = GPG_ERR_NO_DATA;
1946 struct element_list_s *elements = NULL;
1948 if (!line || !*line)
1950 struct string_s *str = string_new (NULL);
1951 xmlNodePtr n;
1953 if (!str)
1954 return GPG_ERR_ENOMEM;
1956 pthread_cleanup_push ((void *)list_command_free1, str);
1957 n = xmlDocGetRootElement (client->doc);
1958 for (n = n->children; n; n = n->next)
1960 xmlChar *name;
1962 if (n->type != XML_ELEMENT_NODE)
1963 continue;
1965 name = xmlGetProp (n, (xmlChar *)"_name");
1966 if (!name)
1968 rc = GPG_ERR_ENOMEM;
1969 break;
1972 elements = xcalloc (1, sizeof (struct element_list_s));
1973 if (!elements)
1975 xmlFree (name);
1976 rc = GPG_ERR_ENOMEM;
1977 break;
1980 elements->prefix = string_new (NULL);
1981 if (!elements->prefix)
1983 xmlFree (name);
1984 xml_free_element_list (elements);
1985 rc = GPG_ERR_ENOMEM;
1986 break;
1989 elements->recurse = client->opts & OPT_LIST_RECURSE;
1990 elements->root_only = !elements->recurse;
1991 pthread_cleanup_push ((void *)xml_free_element_list, elements);
1992 rc = list_path_once (client, (char *)name, elements, str);
1993 xmlFree (name);
1994 pthread_cleanup_pop (1);
1995 if (rc)
1996 break;
1998 if (n->next)
1999 string_append (str, "\n");
2002 if (!rc)
2003 rc = xfer_data (ctx, str->str, str->len);
2005 pthread_cleanup_pop (1);
2006 return rc;
2009 elements = xcalloc (1, sizeof (struct element_list_s));
2010 if (!elements)
2011 return GPG_ERR_ENOMEM;
2013 elements->prefix = string_new (NULL);
2014 if (!elements->prefix)
2016 xml_free_element_list (elements);
2017 return GPG_ERR_ENOMEM;
2020 elements->recurse = client->opts & OPT_LIST_RECURSE;
2021 pthread_cleanup_push ((void *)xml_free_element_list, elements);
2022 struct string_s *str = string_new (NULL);
2023 pthread_cleanup_push ((void *)list_command_free1, str);
2024 rc = list_path_once (client, line, elements, str);
2025 if (!rc)
2026 rc = xfer_data (ctx, str->str, str->len);
2028 pthread_cleanup_pop (1);
2029 pthread_cleanup_pop (1);
2030 return rc;
2033 static gpg_error_t
2034 list_command (assuan_context_t ctx, char *line)
2036 struct client_s *client = assuan_get_pointer (ctx);
2037 gpg_error_t rc;
2038 struct argv_s *args[] = {
2039 &(struct argv_s) {"recurse", OPTION_TYPE_NOARG, parse_list_opt_recurse},
2040 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2041 /* These are deprecated but kept for backward compatibility with older
2042 * clients. */
2043 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, NULL},
2044 &(struct argv_s) {"with-target", OPTION_TYPE_NOARG, NULL},
2045 &(struct argv_s) {"all", OPTION_TYPE_NOARG, parse_list_opt_recurse},
2046 &(struct argv_s) {"no-recurse", OPTION_TYPE_NOARG, NULL},
2047 NULL
2050 if (disable_list_and_dump == 1)
2051 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2053 rc = parse_options (&line, args, client, 1);
2054 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2055 rc = GPG_ERR_SYNTAX;
2056 if (rc)
2057 return send_error (ctx, rc);
2059 if (client->opts & OPT_INQUIRE)
2061 unsigned char *result;
2062 size_t len;
2064 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2065 if (rc)
2066 return send_error (ctx, rc);
2068 pthread_cleanup_push ((void *)xfree, result);
2069 rc = do_list (ctx, (char *)result);
2070 pthread_cleanup_pop (1);
2072 else
2073 rc = do_list (ctx, line);
2075 return send_error (ctx, rc);
2078 #define RESUMABLE_ERROR(rc) (rc == GPG_ERR_ELOOP || rc == GPG_ERR_EACCES \
2079 || rc == GPG_ERR_ELEMENT_NOT_FOUND || !rc)
2081 * args[0] - element path
2083 static gpg_error_t
2084 attribute_list (assuan_context_t ctx, char **args)
2086 struct client_s *client = assuan_get_pointer (ctx);
2087 char **attrlist = NULL;
2088 int i = 0;
2089 int target = 0;
2090 xmlAttrPtr a;
2091 xmlNodePtr n, an, r;
2092 char *line;
2093 gpg_error_t rc;
2094 struct xml_request_s *req;
2096 if (!args || !args[0] || !*args[0])
2097 return GPG_ERR_SYNTAX;
2099 rc = xml_new_request (client, args[0], XML_CMD_ATTR_LIST, &req);
2100 if (rc)
2101 return rc;
2103 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2104 xml_free_request (req);
2105 if (rc)
2106 return rc;
2108 gpg_error_t acl_rc = 0;
2109 again:
2110 acl_rc = xml_acl_check (client, n);
2111 for (a = n->properties; a; a = a->next)
2113 char **pa;
2114 int reserved = xml_reserved_attribute ((char *)a->name);
2116 if (acl_rc == GPG_ERR_EACCES && !reserved)
2117 continue;
2118 else if (acl_rc && acl_rc != GPG_ERR_EACCES)
2120 rc = acl_rc;
2121 break;
2124 if (reserved && target)
2125 continue;
2127 pa = xrealloc (attrlist, (i + 2) * sizeof (char *));
2128 if (!pa)
2130 log_write ("%s(%i): %s", __FILE__, __LINE__,
2131 pwmd_strerror (GPG_ERR_ENOMEM));
2132 rc = GPG_ERR_ENOMEM;
2133 break;
2136 attrlist = pa;
2137 an = a->children;
2138 attrlist[i] = str_asprintf ("%s %s", (char *) a->name, an && an->content
2139 ? (char *)an->content : "");
2141 if (!attrlist[i])
2143 log_write ("%s(%i): %s", __FILE__, __LINE__,
2144 pwmd_strerror (GPG_ERR_ENOMEM));
2145 rc = GPG_ERR_ENOMEM;
2146 break;
2149 attrlist[++i] = NULL;
2152 if (!rc && !attrlist)
2153 return GPG_ERR_NO_DATA;
2155 if (!rc && !target)
2157 r = xml_resolve_path (client, client->doc, (xmlChar *)args[0], NULL, &rc);
2158 if (RESUMABLE_ERROR (rc))
2160 rc = 0;
2161 if (r && r != n)
2163 target = 1;
2164 n = r;
2165 goto again;
2170 pthread_cleanup_push ((void *)req_free, attrlist);
2172 if (!rc)
2174 line = strv_join ("\n", attrlist);
2175 if (line)
2177 pthread_cleanup_push ((void *)xfree, line);
2178 rc = xfer_data (ctx, line, strlen (line));
2179 pthread_cleanup_pop (1);
2181 else
2183 log_write ("%s(%i): %s", __FILE__, __LINE__,
2184 pwmd_strerror (GPG_ERR_ENOMEM));
2185 rc = GPG_ERR_ENOMEM;
2189 pthread_cleanup_pop (1);
2190 return rc;
2194 * args[0] - attribute
2195 * args[1] - element path
2197 static gpg_error_t
2198 attribute_delete (struct client_s *client, char **args)
2200 gpg_error_t rc;
2201 xmlNodePtr n;
2203 if (!args || !args[0] || !*args[0] || !args[1] || !*args[1])
2204 return GPG_ERR_SYNTAX;
2206 rc = xml_protected_attr (args[0]);
2207 if (rc || !strcmp (args[0], "_target"))
2208 return rc ? rc : GPG_ERR_EPERM;
2210 rc = copy_on_write (client);
2211 if (rc)
2212 return rc;
2214 if (!xml_reserved_attribute (args[0]))
2215 n = xml_resolve_path (client, client->doc, (xmlChar *)args[1], NULL, &rc);
2216 else
2218 struct xml_request_s *req;
2220 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
2221 if (rc)
2222 return rc;
2224 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2225 xml_free_request (req);
2228 if (!rc)
2229 rc = xml_is_element_owner (client, n);
2231 if (!rc)
2232 rc = xml_delete_attribute (client, n, (xmlChar *) args[0]);
2234 return rc;
2238 * Creates the "_target" attribute. When other commands encounter an element
2239 * with this attribute they follow the "_target" after appending remaining
2240 * elements from the original element path to the target. The exception is the
2241 * ATTR command that operates on the element itself (for reserved attribute
2242 * names) and not the target.
2244 * If the source element path doesn't exist when using 'ATTR SET target', it is
2245 * created, but the destination element path must exist. This is similar to the
2246 * ls(1) command: ln -s src dst.
2248 * args[0] - source element path
2249 * args[1] - destination element path
2251 static gpg_error_t
2252 set_target_attribute (struct client_s *client, char **args)
2254 struct xml_request_s *req = NULL;
2255 char **src, **dst;
2256 gpg_error_t rc;
2257 xmlNodePtr n;
2259 if (!args || !args[0] || !args[1])
2260 return GPG_ERR_SYNTAX;
2262 src = str_split (args[0], "\t", 0);
2263 if (!src)
2264 return GPG_ERR_SYNTAX;
2266 if (!xml_valid_element_path (src, 0))
2268 strv_free (src);
2269 return GPG_ERR_INV_VALUE;
2272 dst = str_split (args[1], "\t", 0);
2273 if (!dst)
2275 strv_free (src);
2276 return GPG_ERR_SYNTAX;
2279 rc = copy_on_write (client);
2280 if (rc)
2281 goto fail;
2283 // Be sure the destination element path exists. */
2284 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
2285 if (rc)
2286 goto fail;
2288 (void)xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2289 if (rc && rc != GPG_ERR_EACCES)
2290 goto fail;
2292 xml_free_request (req);
2293 req = NULL;
2295 if (!strcmp (args[0], args[1]))
2297 rc = GPG_ERR_EEXIST;
2298 goto fail;
2301 rc = xml_new_request (client, args[0], XML_CMD_ATTR_TARGET, &req);
2302 if (rc)
2303 goto fail;
2305 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2306 if (rc && rc != GPG_ERR_EACCES)
2307 goto fail;
2309 if (!rc)
2311 rc = xml_add_attribute (client, n, "_target", args[1]);
2312 if (!rc)
2314 rc = xml_remove_user_attributes (client, n);
2315 if (!rc)
2316 rc = xml_unlink_node (client, n->children);
2320 fail:
2321 strv_free (src);
2322 strv_free (dst);
2323 xml_free_request (req);
2324 return rc;
2328 * args[0] - attribute
2329 * args[1] - element path
2331 static gpg_error_t
2332 attribute_get (assuan_context_t ctx, char **args)
2334 struct client_s *client = assuan_get_pointer (ctx);
2335 xmlNodePtr n;
2336 xmlChar *a;
2337 gpg_error_t rc;
2338 struct xml_request_s *req;
2340 if (!args || !args[0] || !*args[0] || !args[1] || !*args[1])
2341 return GPG_ERR_SYNTAX;
2343 if (!xml_reserved_attribute (args[0]))
2344 n = xml_resolve_path (client, client->doc, (xmlChar *)args[1], NULL, &rc);
2345 else
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 return rc;
2358 a = xmlGetProp (n, (xmlChar *) args[0]);
2359 if (!a)
2360 return GPG_ERR_NOT_FOUND;
2362 pthread_cleanup_push ((void *)xmlFree, a);
2364 if (*a)
2365 rc = xfer_data (ctx, (char *) a, xmlStrlen (a));
2366 else
2367 rc = GPG_ERR_NO_DATA;
2369 pthread_cleanup_pop (1);
2370 return rc;
2374 * args[0] - attribute
2375 * args[1] - element path
2376 * args[2] - value
2378 static gpg_error_t
2379 attribute_set (struct client_s *client, char **args)
2381 struct xml_request_s *req;
2382 gpg_error_t rc;
2383 xmlNodePtr n;
2385 if (!args || !args[0] || !args[1])
2386 return GPG_ERR_SYNTAX;
2389 * Reserved attribute names.
2391 if ((rc = xml_protected_attr (args[0])))
2392 return rc;
2393 else if (!strcmp (args[0], "_target"))
2394 return set_target_attribute (client, args + 1);
2395 else if (!strcmp (args[0], "_acl"))
2396 rc = xml_valid_username (args[2]);
2397 else if (!xml_valid_attribute (args[0]))
2398 return GPG_ERR_INV_VALUE;
2400 if (rc)
2401 return rc;
2403 if (!xml_valid_attribute_value (args[2]))
2404 return GPG_ERR_INV_VALUE;
2406 rc = copy_on_write (client);
2407 if (rc)
2408 return rc;
2410 if (!xml_reserved_attribute (args[0]))
2412 n = xml_resolve_path (client, client->doc, (xmlChar *)args[1], NULL, &rc);
2413 if (!rc)
2415 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
2416 if (!rc)
2418 rc = xml_check_recursion (client, req);
2419 xml_free_request (req);
2423 else
2425 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
2426 if (rc)
2427 return rc;
2429 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2430 xml_free_request (req);
2433 if (!rc)
2434 rc = xml_is_element_owner (client, n);
2436 if (!rc)
2437 rc = xml_add_attribute (client, n, args[0], args[2]);
2439 return rc;
2443 * req[0] - command
2444 * req[1] - attribute name or element path if command is LIST
2445 * req[2] - element path
2446 * req[2] - element path or value
2449 static gpg_error_t
2450 do_attr (assuan_context_t ctx, char *line)
2452 struct client_s *client = assuan_get_pointer (ctx);
2453 gpg_error_t rc = 0;
2454 char **req;
2456 if (!line || !*line)
2457 return GPG_ERR_SYNTAX;
2459 req = str_split (line, " ", 4);
2460 if (!req || !req[0] || !req[1])
2462 strv_free (req);
2463 return GPG_ERR_SYNTAX;
2466 pthread_cleanup_push ((void *)req_free, req);
2468 if (strcasecmp (req[0], "SET") == 0)
2469 rc = attribute_set (client, req + 1);
2470 else if (strcasecmp (req[0], "GET") == 0)
2471 rc = attribute_get (ctx, req + 1);
2472 else if (strcasecmp (req[0], "DELETE") == 0)
2473 rc = attribute_delete (client, req + 1);
2474 else if (strcasecmp (req[0], "LIST") == 0)
2475 rc = attribute_list (ctx, req + 1);
2476 else
2477 rc = GPG_ERR_SYNTAX;
2479 client->flags &= ~(FLAG_ACL_IGNORE|FLAG_ACL_ERROR);
2480 pthread_cleanup_pop (1);
2481 return rc;
2484 static gpg_error_t
2485 attr_command (assuan_context_t ctx, char *line)
2487 struct client_s *client = assuan_get_pointer (ctx);
2488 gpg_error_t rc;
2489 struct argv_s *args[] = {
2490 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2491 NULL
2494 rc = parse_options (&line, args, client, 1);
2495 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2496 rc = GPG_ERR_SYNTAX;
2497 if (rc)
2498 return send_error (ctx, rc);
2500 if (client->opts & OPT_INQUIRE)
2502 unsigned char *result;
2503 size_t len;
2505 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2506 if (rc)
2507 return send_error (ctx, rc);
2509 pthread_cleanup_push ((void *)xfree, result);
2510 rc = do_attr (ctx, (char *)result);
2511 pthread_cleanup_pop (1);
2513 else
2514 rc = do_attr (ctx, line);
2516 return send_error (ctx, rc);
2519 static gpg_error_t
2520 parse_iscached_opt_lock (void *data, void *value)
2522 struct client_s *client = data;
2524 (void) value;
2525 client->opts |= OPT_LOCK;
2526 return 0;
2529 static gpg_error_t
2530 parse_iscached_opt_agent (void *data, void *value)
2532 struct client_s *client = data;
2534 (void) value;
2535 client->opts |= OPT_CACHE_AGENT;
2536 return 0;
2539 static gpg_error_t
2540 parse_iscached_opt_sign (void *data, void *value)
2542 struct client_s *client = data;
2544 (void) value;
2545 client->opts |= OPT_CACHE_SIGN;
2546 return 0;
2549 static gpg_error_t
2550 iscached_command (assuan_context_t ctx, char *line)
2552 struct client_s *client = assuan_get_pointer (ctx);
2553 gpg_error_t rc;
2554 int defer = 0;
2555 struct argv_s *args[] = {
2556 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_iscached_opt_lock},
2557 &(struct argv_s) {"agent", OPTION_TYPE_NOARG, parse_iscached_opt_agent},
2558 &(struct argv_s) {"sign", OPTION_TYPE_NOARG, parse_iscached_opt_sign},
2559 NULL
2562 if (!line || !*line)
2563 return send_error (ctx, GPG_ERR_SYNTAX);
2565 rc = parse_options (&line, args, client, 1);
2566 if (rc)
2567 return send_error (ctx, rc);
2568 else if (!valid_filename (line))
2569 return send_error (ctx, GPG_ERR_INV_VALUE);
2571 if (!(client->flags & FLAG_OPEN)
2572 && ((client->opts & OPT_CACHE_AGENT) || (client->opts & OPT_CACHE_SIGN)))
2573 return send_error (ctx, GPG_ERR_INV_STATE);
2575 rc = cache_iscached (line, &defer, (client->opts & OPT_CACHE_AGENT),
2576 (client->opts & OPT_CACHE_SIGN));
2577 if (!rc && defer)
2578 rc = GPG_ERR_NO_DATA;
2580 if (!rc)
2582 struct cache_data_s *cdata = cache_get_data (line, NULL);
2584 if (cdata)
2586 rc = validate_checksum (client, line, cdata, NULL, NULL, 1);
2587 if (rc == GPG_ERR_CHECKSUM)
2588 rc = GPG_ERR_NO_DATA;
2592 if (client->opts & OPT_LOCK
2593 && (!rc || gpg_err_code (rc) == GPG_ERR_NO_DATA
2594 || gpg_err_code (rc) == GPG_ERR_ENOENT))
2596 gpg_error_t trc = rc;
2598 if (client->filename && strcmp (line, client->filename))
2599 reset_client (client);
2601 xfree (client->filename);
2602 client->filename = str_dup (line);
2603 rc = do_lock (client, 1);
2604 if (!rc)
2605 rc = trc;
2608 return send_error (ctx, rc);
2611 static gpg_error_t
2612 clearcache_command (assuan_context_t ctx, char *line)
2614 struct client_s *client = assuan_get_pointer (ctx);
2615 gpg_error_t rc = 0, all_rc = 0;
2616 int i;
2617 int t;
2618 int all = 0;
2619 struct client_thread_s *once = NULL;
2620 unsigned count;
2622 cache_lock ();
2623 pthread_cleanup_push (cache_release_mutex, NULL);
2624 count = cache_file_count ();
2625 MUTEX_LOCK (&cn_mutex);
2626 pthread_cleanup_push ((void *)release_mutex_cb, &cn_mutex);
2628 if (!line || !*line)
2629 all = 1;
2631 t = slist_length (cn_thread_list);
2633 for (i = 0; i < t; i++)
2635 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2636 assuan_peercred_t peer;
2638 if (!thd->cl)
2639 continue;
2641 /* Lock each connected clients' file mutex to prevent any other client
2642 * from accessing the cache entry (the file mutex is locked upon
2643 * command startup). The cache for the entry is not cleared if the
2644 * file mutex is locked by another client to prevent this function
2645 * from blocking. Rather, it returns an error.
2647 if (all)
2649 if (thd->cl->filename)
2651 rc = do_validate_peer (ctx, thd->cl->filename, &peer, NULL);
2652 /* The current client doesn't have permission to open the other
2653 * filename do to "access" configuration parameter in a filename
2654 * section. Since we are clearning all cache entries the error
2655 * will be returned later during cache_clear(). */
2656 if (rc)
2658 rc = 0;
2659 continue;
2662 else // Idle client without opened file?
2663 continue;
2665 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->filename, -1, 0, -1);
2666 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2668 /* The current client owns the lock. */
2669 if (pthread_equal (pthread_self (), thd->tid))
2670 rc = 0;
2671 else
2673 if (cache_iscached (thd->cl->filename, NULL, 0, 0)
2674 == GPG_ERR_NO_DATA)
2676 rc = 0;
2677 continue;
2680 /* The cache entry will be cleared when the other client
2681 * disconnects and cache_timer_thread() does its thing. */
2682 cache_defer_clear (thd->cl->filename);
2685 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
2687 rc = 0;
2688 continue;
2691 if (!rc)
2693 rc = cache_clear (NULL, thd->cl->filename, 1, 0);
2694 cache_unlock_mutex (thd->cl->filename, 0);
2697 if (rc)
2698 all_rc = rc;
2700 rc = 0;
2702 else
2704 /* A single data filename was specified. Lock only this data file
2705 * mutex and free the cache entry. */
2706 rc = do_validate_peer (ctx, line, &peer, NULL);
2707 if (rc == GPG_ERR_FORBIDDEN)
2708 rc = peer_is_invoker (client);
2710 if (rc == GPG_ERR_EACCES)
2711 rc = GPG_ERR_FORBIDDEN;
2713 if (!rc && thd->cl->filename && !strcmp (thd->cl->filename , line))
2715 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->filename, -1, 0, -1);
2716 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2718 /* The current client owns the lock. */
2719 if (pthread_equal (pthread_self (), thd->tid))
2720 rc = 0;
2723 if (!rc)
2725 once = thd;
2726 rc = cache_clear (NULL, thd->cl->filename, 1, 0);
2727 cache_unlock_mutex (thd->cl->filename, 0);
2729 else
2730 cache_defer_clear (thd->cl->filename);
2732 /* Found a client with the opened file. The cache entry has been
2733 * either cleared (self) or deferred to be cleared. */
2734 break;
2739 /* Only connected clients' cache entries have been cleared. Now clear any
2740 * remaining cache entries without clients but only if there wasn't an
2741 * error from above since this would defeat the locking check of the
2742 * remaining entries. */
2743 if (all && !all_rc && cache_file_count ())
2745 rc = cache_clear (client, NULL, 1, 0);
2746 if (rc == GPG_ERR_EACCES)
2747 rc = GPG_ERR_FORBIDDEN;
2750 /* No clients are using the specified file. */
2751 else if (!all_rc && !rc && !once)
2752 rc = cache_clear (NULL, line, 1, 0);
2754 /* Release the connection mutex. */
2755 pthread_cleanup_pop (1);
2757 if (!rc || (cache_file_count () && count != cache_file_count ()))
2758 send_status_all (STATUS_CACHE, NULL);
2760 /* Release the cache mutex. */
2761 pthread_cleanup_pop (1);
2763 /* One or more files were locked while clearing all cache entries. */
2764 if (all_rc)
2765 rc = all_rc;
2767 return send_error (ctx, rc);
2770 static gpg_error_t
2771 cachetimeout_command (assuan_context_t ctx, char *line)
2773 struct client_s *client = assuan_get_pointer (ctx);
2774 long timeout;
2775 char **req = str_split (line, " ", 0);
2776 char *p;
2777 gpg_error_t rc = 0;
2779 if (!(client->flags & FLAG_OPEN))
2780 return send_error (ctx, GPG_ERR_INV_STATE);
2782 if (!req || !*req || strv_length (req) > 1)
2784 strv_free (req);
2785 return send_error (ctx, GPG_ERR_SYNTAX);
2788 errno = 0;
2789 timeout = strtol (req[0], &p, 10);
2790 if (errno != 0 || *p || timeout < (long)-1)
2791 rc = GPG_ERR_SYNTAX;
2793 if (!rc)
2795 rc = cache_set_timeout (client->filename, timeout);
2796 if (!rc || gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
2798 rc = 0;
2799 MUTEX_LOCK (&rcfile_mutex);
2800 config_set_long_param (&global_config, client->filename,
2801 "cache_timeout", req[0]);
2802 MUTEX_UNLOCK (&rcfile_mutex);
2806 strv_free (req);
2807 return send_error (ctx, rc);
2810 static gpg_error_t
2811 dump_command (assuan_context_t ctx, char *line)
2813 xmlChar *xml;
2814 int len;
2815 struct client_s *client = assuan_get_pointer (ctx);
2816 gpg_error_t rc;
2818 if (disable_list_and_dump == 1)
2819 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2821 if (line && *line)
2822 return send_error (ctx, GPG_ERR_SYNTAX);
2824 rc = peer_is_invoker(client);
2825 if (rc)
2826 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
2828 xmlDocDumpFormatMemory (client->doc, &xml, &len, 1);
2830 if (!xml)
2832 log_write ("%s(%i): %s", __FILE__, __LINE__,
2833 pwmd_strerror (GPG_ERR_ENOMEM));
2834 return send_error (ctx, GPG_ERR_ENOMEM);
2837 pthread_cleanup_push ((void *)xmlFree, xml);
2838 rc = xfer_data (ctx, (char *) xml, len);
2839 pthread_cleanup_pop (1);
2840 return send_error (ctx, rc);
2843 static gpg_error_t
2844 getconfig_command (assuan_context_t ctx, char *line)
2846 struct client_s *client = assuan_get_pointer (ctx);
2847 gpg_error_t rc = 0;
2848 char filename[255] = { 0 }, param[747] = { 0 };
2849 char *p, *tmp = NULL, *fp = client->filename, *paramp = line;
2851 if (!line || !*line)
2852 return send_error (ctx, GPG_ERR_SYNTAX);
2854 if (strchr (line, ' '))
2856 int ret = sscanf (line, " %254[^ ] %746c", filename, param);
2858 if (ret <= 0)
2859 return send_error (ctx, gpg_error_from_syserror());
2860 paramp = param;
2861 fp = filename;
2864 if (fp && !valid_filename (fp))
2865 return send_error (ctx, GPG_ERR_INV_VALUE);
2867 paramp = str_down (paramp);
2868 p = config_get_value (fp ? fp : "global", paramp);
2869 if (!p)
2870 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2872 tmp = expand_homedir (p);
2873 xfree (p);
2874 if (!tmp)
2876 log_write ("%s(%i): %s", __FILE__, __LINE__,
2877 pwmd_strerror (GPG_ERR_ENOMEM));
2878 return send_error (ctx, GPG_ERR_ENOMEM);
2881 p = tmp;
2882 pthread_cleanup_push ((void *)xfree, p);
2883 rc = xfer_data (ctx, p, strlen (p));
2884 pthread_cleanup_pop (1);
2885 return send_error (ctx, rc);
2888 struct xpath_s
2890 xmlXPathContextPtr xp;
2891 xmlXPathObjectPtr result;
2892 xmlBufferPtr buf;
2893 char **req;
2896 static void
2897 xpath_command_free (void *arg)
2899 struct xpath_s *xpath = arg;
2901 if (!xpath)
2902 return;
2904 req_free (xpath->req);
2906 if (xpath->buf)
2907 xmlBufferFree (xpath->buf);
2909 if (xpath->result)
2910 xmlXPathFreeObject (xpath->result);
2912 if (xpath->xp)
2913 xmlXPathFreeContext (xpath->xp);
2916 static gpg_error_t
2917 do_xpath (assuan_context_t ctx, char *line)
2919 gpg_error_t rc;
2920 struct client_s *client = assuan_get_pointer (ctx);
2921 struct xpath_s _x = { 0 };
2922 struct xpath_s *xpath = &_x;
2924 if (!line || !*line)
2925 return GPG_ERR_SYNTAX;
2927 if ((xpath->req = str_split (line, "\t", 2)) == NULL)
2929 if (strv_printf (&xpath->req, "%s", line) == 0)
2930 return GPG_ERR_ENOMEM;
2933 if (xpath->req[1])
2935 rc = copy_on_write (client);
2936 if (rc)
2937 goto fail;
2940 xpath->xp = xmlXPathNewContext (client->doc);
2941 if (!xpath->xp)
2943 rc = GPG_ERR_BAD_DATA;
2944 goto fail;
2947 xpath->result =
2948 xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2949 if (!xpath->result)
2951 rc = GPG_ERR_BAD_DATA;
2952 goto fail;
2955 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2957 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2958 goto fail;
2961 rc = xml_recurse_xpath_nodeset (client, client->doc,
2962 xpath->result->nodesetval,
2963 (xmlChar *) xpath->req[1], &xpath->buf, 0,
2964 NULL);
2965 if (rc)
2966 goto fail;
2967 else if (!xpath->req[1] && !xmlBufferLength (xpath->buf))
2969 rc = GPG_ERR_NO_DATA;
2970 goto fail;
2972 else if (xpath->req[1])
2974 rc = 0;
2975 goto fail;
2978 pthread_cleanup_push ((void *)xpath_command_free, &xpath);
2979 rc = xfer_data (ctx, (char *) xmlBufferContent (xpath->buf),
2980 xmlBufferLength (xpath->buf));
2981 pthread_cleanup_pop (0);
2982 fail:
2983 xpath_command_free (xpath);
2984 return rc;
2987 static gpg_error_t
2988 xpath_command (assuan_context_t ctx, char *line)
2990 struct client_s *client = assuan_get_pointer (ctx);
2991 gpg_error_t rc;
2992 struct argv_s *args[] = {
2993 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2994 NULL
2997 if (disable_list_and_dump == 1)
2998 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
3000 rc = peer_is_invoker(client);
3001 if (rc)
3002 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
3004 rc = parse_options (&line, args, client, 1);
3005 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3006 rc = GPG_ERR_SYNTAX;
3007 if (rc)
3008 return send_error (ctx, rc);
3010 if (client->opts & OPT_INQUIRE)
3012 unsigned char *result;
3013 size_t len;
3015 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3016 if (rc)
3017 return send_error (ctx, rc);
3019 pthread_cleanup_push ((void *)xfree, result);
3020 rc = do_xpath (ctx, (char *)result);
3021 pthread_cleanup_pop (1);
3023 else
3024 rc = do_xpath (ctx, line);
3026 return send_error (ctx, rc);
3029 static gpg_error_t
3030 do_xpathattr (assuan_context_t ctx, char *line)
3032 struct client_s *client = assuan_get_pointer (ctx);
3033 gpg_error_t rc;
3034 char **req = NULL;
3035 int cmd = 0; //SET
3036 struct xpath_s _x = { 0 };
3037 struct xpath_s *xpath = &_x;
3039 if (!line || !*line)
3040 return GPG_ERR_SYNTAX;
3042 if ((req = str_split (line, " ", 3)) == NULL)
3043 return GPG_ERR_ENOMEM;
3045 if (!req[0])
3047 rc = GPG_ERR_SYNTAX;
3048 goto fail;
3051 if (!strcasecmp (req[0], "SET"))
3052 cmd = 0;
3053 else if (!strcasecmp (req[0], "DELETE"))
3054 cmd = 1;
3055 else
3057 rc = GPG_ERR_SYNTAX;
3058 goto fail;
3061 if (!req[1] || !req[2])
3063 rc = GPG_ERR_SYNTAX;
3064 goto fail;
3067 if ((xpath->req = str_split (req[2], "\t", 3)) == NULL)
3069 rc = GPG_ERR_ENOMEM;
3070 goto fail;
3073 if (!xpath->req[0] || (!xpath->req[1] && !cmd) || (xpath->req[1] && cmd))
3075 rc = GPG_ERR_SYNTAX;
3076 goto fail;
3079 rc = copy_on_write (client);
3080 if (rc)
3081 goto fail;
3083 xpath->xp = xmlXPathNewContext (client->doc);
3084 if (!xpath->xp)
3086 rc = GPG_ERR_BAD_DATA;
3087 goto fail;
3090 xpath->result = xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
3091 if (!xpath->result)
3093 rc = GPG_ERR_BAD_DATA;
3094 goto fail;
3097 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
3099 rc = GPG_ERR_ELEMENT_NOT_FOUND;
3100 goto fail;
3103 rc = xml_recurse_xpath_nodeset (client, client->doc,
3104 xpath->result->nodesetval,
3105 (xmlChar *) xpath->req[1], &xpath->buf, cmd,
3106 (xmlChar *) req[1]);
3108 fail:
3109 xpath_command_free (xpath);
3110 strv_free (req);
3111 return rc;
3114 /* XPATHATTR SET|DELETE <name> <expression>[<TAB>[value]] */
3115 static gpg_error_t
3116 xpathattr_command (assuan_context_t ctx, char *line)
3118 struct client_s *client = assuan_get_pointer (ctx);
3119 gpg_error_t rc;
3120 struct argv_s *args[] = {
3121 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3122 NULL
3125 if (disable_list_and_dump == 1)
3126 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
3128 rc = peer_is_invoker(client);
3129 if (rc)
3130 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
3132 rc = parse_options (&line, args, client, 1);
3133 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3134 rc = GPG_ERR_SYNTAX;
3135 if (rc)
3136 return send_error (ctx, rc);
3138 if (client->opts & OPT_INQUIRE)
3140 unsigned char *result;
3141 size_t len;
3143 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3144 if (rc)
3145 return send_error (ctx, rc);
3147 pthread_cleanup_push ((void *)xfree, result);
3148 rc = do_xpathattr (ctx, (char *)result);
3149 pthread_cleanup_pop (1);
3151 else
3152 rc = do_xpathattr (ctx, line);
3154 return send_error (ctx, rc);
3157 static gpg_error_t
3158 do_import (struct client_s *client, const char *root_element,
3159 unsigned char *content)
3161 xmlDocPtr doc = NULL;
3162 xmlNodePtr n = NULL, root;
3163 gpg_error_t rc = 0;
3164 struct string_s *str = NULL, *tstr = NULL;
3165 struct xml_request_s *req = NULL;
3167 if (!content || !*content)
3168 return GPG_ERR_SYNTAX;
3170 if (root_element)
3172 rc = xml_new_request (client, root_element, XML_CMD_STORE, &req);
3173 if (rc)
3175 xfree (content);
3176 return rc;
3179 if (!xml_valid_element_path (req->args, 0))
3181 xml_free_request (req);
3182 xfree (content);
3183 return GPG_ERR_INV_VALUE;
3187 str = string_new_content ((char *)content);
3188 tstr = string_prepend (str, "<pwmd>");
3189 if (tstr)
3191 str = tstr;
3192 tstr = string_append (str, "</pwmd>");
3193 if (!tstr)
3194 rc = GPG_ERR_ENOMEM;
3195 else
3196 str = tstr;
3198 else
3199 rc = GPG_ERR_ENOMEM;
3201 if (rc)
3202 goto fail;
3204 doc = xmlReadDoc ((xmlChar *) str->str, NULL, "UTF-8", XML_PARSE_NOBLANKS);
3205 string_free (str, 1);
3206 if (!doc)
3208 rc = GPG_ERR_BAD_DATA;
3209 goto fail;
3212 root = xmlDocGetRootElement (doc);
3213 root = root->children;
3214 if (root->type != XML_ELEMENT_NODE)
3216 rc = GPG_ERR_BAD_DATA;
3217 goto fail;
3220 rc = xml_validate_import (client, root);
3221 if (rc)
3222 goto fail;
3224 if (req)
3226 /* Create the new specified root element path, if needed. */
3227 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc),
3228 &rc);
3229 if (rc)
3230 goto fail;
3232 /* Overwrite the children of the specified root element path. */
3233 (void)xml_unlink_node (client, n->children);
3234 n->children = NULL;
3236 else
3237 n = xmlDocGetRootElement (client->doc);
3239 if (n)
3241 xmlNodePtr copy;
3242 xmlChar *name = xml_attribute_value (root, (xmlChar *)"_name");
3244 if (!name)
3245 rc = GPG_ERR_BAD_DATA;
3246 else if (!req)
3248 /* No --root argument passed. Overwrite the current documents' root
3249 * element matching the root element of the imported data. */
3250 xml_free_request (req);
3251 req = NULL;
3252 rc = xml_new_request (client, (char *)name, XML_CMD_DELETE, &req);
3253 xmlFree (name);
3254 if (!rc)
3256 xmlNodePtr tmp;
3258 tmp = xml_find_elements (client, req,
3259 xmlDocGetRootElement (req->doc), &rc);
3260 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3261 goto fail;
3263 if (!rc)
3264 (void)xml_unlink_node (client, tmp);
3266 rc = 0;
3270 if (!rc)
3272 copy = xmlCopyNodeList (root);
3273 if (!copy)
3274 rc = GPG_ERR_ENOMEM;
3275 else
3277 n = xmlAddChildList (n, copy);
3278 if (!n)
3279 rc = GPG_ERR_ENOMEM;
3284 if (!rc && n && n->parent)
3285 rc = xml_update_element_mtime (client, n->parent);
3287 fail:
3288 xml_free_request (req);
3290 if (doc)
3291 xmlFreeDoc (doc);
3293 return rc;
3296 static gpg_error_t
3297 parse_import_opt_root (void *data, void *value)
3299 struct client_s *client = data;
3301 client->import_root = str_dup (value);
3302 return client->import_root ? 0 : GPG_ERR_ENOMEM;
3305 static gpg_error_t
3306 import_command (assuan_context_t ctx, char *line)
3308 gpg_error_t rc;
3309 struct client_s *client = assuan_get_pointer (ctx);
3310 unsigned char *result;
3311 size_t len;
3312 struct argv_s *args[] = {
3313 &(struct argv_s) {"root", OPTION_TYPE_ARG, parse_import_opt_root},
3314 NULL
3317 xfree (client->import_root);
3318 client->import_root = NULL;
3319 rc = parse_options (&line, args, client, client->bulk_p ? 1 : 0);
3320 if (rc)
3321 return send_error (ctx, rc);
3323 rc = copy_on_write (client);
3324 if (rc)
3325 return send_error (ctx, rc);
3327 if (!client->bulk_p)
3329 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3330 if (rc)
3332 xfree (client->import_root);
3333 client->import_root = NULL;
3334 return send_error (ctx, rc);
3336 rc = do_import (client, client->import_root, result);
3338 else
3340 char *p = str_dup (line);
3342 if (!p)
3343 rc = GPG_ERR_ENOMEM;
3344 else
3345 rc = do_import (client, client->import_root, (unsigned char *)p);
3348 xfree (client->import_root);
3349 client->import_root = NULL;
3350 return send_error (ctx, rc);
3353 static gpg_error_t
3354 do_lock (struct client_s *client, int add)
3356 gpg_error_t rc = lock_file_mutex (client, add);
3358 if (!rc)
3359 client->flags |= FLAG_LOCK_CMD;
3361 return rc;
3364 static gpg_error_t
3365 lock_command (assuan_context_t ctx, char *line)
3367 struct client_s *client = assuan_get_pointer (ctx);
3368 gpg_error_t rc;
3370 if (line && *line)
3371 return send_error (ctx, GPG_ERR_SYNTAX);
3373 rc = do_lock (client, 0);
3374 return send_error (ctx, rc);
3377 static gpg_error_t
3378 unlock_command (assuan_context_t ctx, char *line)
3380 struct client_s *client = assuan_get_pointer (ctx);
3381 gpg_error_t rc;
3383 if (line && *line)
3384 return send_error (ctx, GPG_ERR_SYNTAX);
3386 rc = unlock_file_mutex (client, 0);
3387 return send_error (ctx, rc);
3390 static void
3391 set_env (const char *name, char *buf, size_t size, const char *value)
3393 MUTEX_LOCK (&rcfile_mutex);
3394 if (!value || !*value)
3396 unsetenv (name);
3397 buf[0] = 0;
3399 else if (!buf[0] || strcmp (buf, value))
3401 snprintf (buf, size, "%s=%s", name, value);
3402 putenv (buf);
3405 MUTEX_UNLOCK (&rcfile_mutex);
3408 static gpg_error_t
3409 option_command (assuan_context_t ctx, char *line)
3411 struct client_s *client = assuan_get_pointer (ctx);
3412 gpg_error_t rc = 0;
3413 char namebuf[255] = { 0 };
3414 char *name = namebuf;
3415 char *value = NULL, *p, *tmp = NULL;
3417 p = strchr (line, '=');
3418 if (!p)
3420 strncpy (namebuf, line, sizeof(namebuf));
3421 namebuf[sizeof(namebuf)-1] = 0;
3423 else
3425 tmp = str_dup (line);
3426 if (!tmp)
3427 return send_error (ctx, GPG_ERR_ENOMEM);
3429 tmp[strlen (line) - strlen (p)] = 0;
3430 strncpy (namebuf, tmp, sizeof (namebuf));
3431 namebuf[sizeof(namebuf)-1] = 0;
3432 xfree (tmp);
3433 tmp = NULL;
3434 value = p+1;
3437 log_write2 ("OPTION name='%s' value='%s'", name, value);
3439 if (strcasecmp (name, (char *) "lock-timeout") == 0)
3441 long n = 0;
3443 if (value)
3445 n = strtol (value, &tmp, 10);
3446 if (tmp && *tmp)
3447 return send_error (ctx, GPG_ERR_INV_VALUE);
3450 client->lock_timeout = n;
3452 else if (strcasecmp (name, (char *) "client-state") == 0)
3454 long n = 0;
3456 MUTEX_LOCK (&client->thd->status_mutex);
3457 if (value)
3459 n = strtol (value, &tmp, 10);
3460 if ((tmp && *tmp) || (n < 0 || n > 1))
3462 MUTEX_UNLOCK (&client->thd->status_mutex);
3463 return send_error (ctx, GPG_ERR_INV_VALUE);
3465 client->client_state = n;
3467 else
3468 client->client_state = 0;
3469 MUTEX_UNLOCK (&client->thd->status_mutex);
3471 else if (strcasecmp (name, (char *) "NAME") == 0)
3473 if (value && strchr (value, ' '))
3474 rc = GPG_ERR_INV_VALUE;
3475 else
3477 MUTEX_LOCK (&cn_mutex);
3478 tmp = pthread_getspecific (thread_name_key);
3479 pthread_setspecific (thread_name_key, NULL);
3480 xfree (tmp);
3481 xfree (client->thd->name);
3482 client->thd->name = NULL;
3483 if (value && *value)
3485 pthread_setspecific (thread_name_key, str_dup (value));
3486 client->thd->name = str_dup (value);
3488 MUTEX_UNLOCK (&cn_mutex);
3491 else if (strcasecmp (name, "disable-pinentry") == 0)
3493 int n = 1;
3495 if (value && *value)
3497 n = (int) strtol (value, &tmp, 10);
3498 if (*tmp || n < 0 || n > 1)
3499 return send_error (ctx, GPG_ERR_INV_VALUE);
3502 if (n)
3503 client->flags |= FLAG_NO_PINENTRY;
3504 else
3505 client->flags &= ~FLAG_NO_PINENTRY;
3507 else if (strcasecmp (name, "ttyname") == 0)
3508 set_env ("GPG_TTY", env_gpg_tty, sizeof (env_gpg_tty), value);
3509 else if (strcasecmp (name, "ttytype") == 0)
3510 set_env ("TERM", env_term, sizeof (env_term), value);
3511 else if (strcasecmp (name, "display") == 0)
3512 set_env ("DISPLAY", env_display, sizeof (env_display), value);
3513 else if (strcasecmp (name, "lc_messages") == 0)
3516 else if (strcasecmp (name, "lc_ctype") == 0)
3519 else if (strcasecmp (name, "desc") == 0)
3522 else if (strcasecmp (name, "pinentry-timeout") == 0)
3525 else
3526 rc = GPG_ERR_UNKNOWN_OPTION;
3528 return send_error (ctx, rc);
3531 static gpg_error_t
3532 do_rename (assuan_context_t ctx, char *line)
3534 struct client_s *client = assuan_get_pointer (ctx);
3535 char **args, *p;
3536 xmlNodePtr src, dst;
3537 struct string_s *str = NULL, *tstr;
3538 struct xml_request_s *req;
3539 gpg_error_t rc;
3541 if (!line || !*line)
3542 return GPG_ERR_SYNTAX;
3544 args = str_split (line, " ", 0);
3545 if (!args || strv_length (args) != 2)
3547 strv_free (args);
3548 return GPG_ERR_SYNTAX;
3551 if (!xml_valid_element ((xmlChar *) args[1]))
3553 strv_free (args);
3554 return GPG_ERR_INV_VALUE;
3557 rc = xml_new_request (client, args[0], XML_CMD_RENAME, &req);
3558 if (rc)
3560 strv_free (args);
3561 return rc;
3564 src = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3565 if (rc)
3566 goto fail;
3568 rc = xml_is_element_owner (client, src);
3569 if (rc)
3570 goto fail;
3572 xmlChar *a = xmlGetProp (src, (xmlChar *) "_name");
3573 if (!a)
3575 rc = GPG_ERR_ENOMEM;
3576 goto fail;
3579 /* To prevent unwanted effects:
3581 * <element _name="a"><element _name="b"/></element>
3583 * RENAME a<TAB>b b
3585 if (xmlStrEqual (a, (xmlChar *) args[1]))
3587 xmlFree (a);
3588 rc = GPG_ERR_EEXIST;
3589 goto fail;
3592 xmlFree (a);
3593 str = string_new (args[0]);
3594 if (!str)
3596 rc = GPG_ERR_ENOMEM;
3597 goto fail;
3600 p = strrchr (str->str, '\t');
3601 if (p)
3602 tstr = string_truncate (str, strlen (str->str)-strlen (p));
3603 else
3604 tstr = string_truncate (str, 0);
3606 if (!tstr)
3608 string_free (str, 1);
3609 rc = GPG_ERR_ENOMEM;
3610 goto fail;
3613 str = tstr;
3614 tstr = string_append_printf (str, "%s%s", str->len ? "\t" : "", args[1]);
3615 if (!tstr)
3617 string_free (str, 1);
3618 rc = GPG_ERR_ENOMEM;
3619 goto fail;
3622 str = tstr;
3623 xml_free_request (req);
3624 rc = xml_new_request (client, str->str, XML_CMD_RENAME, &req);
3625 string_free (str, 1);
3626 if (rc)
3628 req = NULL;
3629 goto fail;
3632 dst = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3633 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3634 goto fail;
3636 rc = 0;
3638 /* Target may exist:
3640 * <element _name="a"/>
3641 * <element _name="b" target="a"/>
3643 * RENAME b a
3645 if (src == dst)
3647 rc = GPG_ERR_EEXIST;
3648 goto fail;
3651 if (dst)
3653 rc = xml_is_element_owner (client, dst);
3654 if (rc)
3655 goto fail;
3657 rc = xml_add_attribute (client, src, "_name", args[1]);
3658 if (!rc)
3659 xml_unlink_node (client, dst);
3661 else
3662 rc = xml_add_attribute (client, src, "_name", args[1]);
3664 fail:
3665 xml_free_request (req);
3666 strv_free (args);
3667 return rc;
3670 static gpg_error_t
3671 rename_command (assuan_context_t ctx, char *line)
3673 struct client_s *client = assuan_get_pointer (ctx);
3674 gpg_error_t rc;
3675 struct argv_s *args[] = {
3676 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3677 NULL
3680 rc = parse_options (&line, args, client, 1);
3681 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3682 rc = GPG_ERR_SYNTAX;
3683 if (rc)
3684 return send_error (ctx, rc);
3686 rc = copy_on_write (client);
3687 if (rc)
3688 return send_error (ctx, rc);
3690 if (client->opts & OPT_INQUIRE)
3692 unsigned char *result;
3693 size_t len;
3695 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3696 if (rc)
3697 return send_error (ctx, rc);
3699 pthread_cleanup_push ((void *)xfree, result);
3700 rc = do_rename (ctx, (char *)result);
3701 pthread_cleanup_pop (1);
3703 else
3704 rc = do_rename (ctx, line);
3706 return send_error (ctx, rc);
3709 static gpg_error_t
3710 do_copy (assuan_context_t ctx, char *line)
3712 struct client_s *client = assuan_get_pointer (ctx);
3713 char **args, **targs;
3714 xmlNodePtr src, dst, tree = NULL;
3715 struct xml_request_s *req;
3716 gpg_error_t rc;
3718 if (!line || !*line)
3719 return GPG_ERR_SYNTAX;
3721 args = str_split (line, " ", 0);
3722 if (!args || strv_length (args) != 2)
3724 strv_free (args);
3725 return GPG_ERR_SYNTAX;
3728 targs = str_split (args[1], "\t", 0);
3729 if (!targs)
3731 strv_free (args);
3732 return GPG_ERR_SYNTAX;
3735 if (!xml_valid_element_path (targs, 0))
3737 strv_free (args);
3738 strv_free (targs);
3739 return GPG_ERR_INV_VALUE;
3741 strv_free (targs);
3743 rc = xml_new_request (client, args[0], XML_CMD_NONE, &req);
3744 if (rc)
3746 strv_free (args);
3747 return rc;
3750 src = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3751 if (rc)
3752 goto fail;
3754 tree = xmlCopyNodeList (src);
3755 if (!tree)
3757 rc = GPG_ERR_ENOMEM;
3758 goto fail;
3761 xml_free_request (req);
3762 /* Create the destination element path if it does not exist. */
3763 rc = xml_new_request (client, args[1], XML_CMD_STORE, &req);
3764 if (rc)
3766 req = NULL;
3767 goto fail;
3770 dst = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3771 if (rc)
3772 goto fail;
3774 rc = xml_is_element_owner (client, dst);
3775 if (rc)
3776 goto fail;
3778 rc = xml_validate_target (client, req->doc, args[1], src);
3779 if (rc || src == dst)
3781 rc = rc ? rc : GPG_ERR_EEXIST;
3782 goto fail;
3785 /* Merge any attributes from the src node to the initial dst node. */
3786 for (xmlAttrPtr attr = tree->properties; attr; attr = attr->next)
3788 if (xmlStrEqual (attr->name, (xmlChar *) "_name"))
3789 continue;
3791 xmlAttrPtr a = xmlHasProp (dst, attr->name);
3792 if (a)
3793 xmlRemoveProp (a);
3795 xmlChar *tmp = xmlNodeGetContent (attr->children);
3796 xmlNewProp (dst, attr->name, tmp);
3797 xmlFree (tmp);
3798 /* Create the default attributes. */
3799 rc = xml_add_attribute (client, dst, NULL, NULL);
3802 xmlNodePtr n = dst->children;
3803 (void)xml_unlink_node (client, n);
3804 dst->children = NULL;
3806 if (tree->children)
3808 n = xmlCopyNodeList (tree->children);
3809 if (!n)
3811 rc = GPG_ERR_ENOMEM;
3812 goto fail;
3815 n = xmlAddChildList (dst, n);
3816 if (!n)
3818 rc = GPG_ERR_ENOMEM;
3819 goto fail;
3822 rc = xml_update_element_mtime (client, xmlDocGetRootElement (client->doc)
3823 == dst->parent ? dst : dst->parent);
3826 fail:
3827 if (tree)
3828 (void)xml_unlink_node (client, tree);
3830 xml_free_request (req);
3831 strv_free (args);
3832 return rc;
3835 static gpg_error_t
3836 copy_command (assuan_context_t ctx, char *line)
3838 struct client_s *client = assuan_get_pointer (ctx);
3839 gpg_error_t rc;
3840 struct argv_s *args[] = {
3841 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3842 NULL
3845 rc = parse_options (&line, args, client, 1);
3846 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3847 rc = GPG_ERR_SYNTAX;
3848 if (rc)
3849 return send_error (ctx, rc);
3851 rc = copy_on_write (client);
3852 if (rc)
3853 return send_error (ctx, rc);
3855 if (client->opts & OPT_INQUIRE)
3857 unsigned char *result;
3858 size_t len;
3860 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3861 if (rc)
3862 return send_error (ctx, rc);
3864 pthread_cleanup_push ((void *)xfree, result);
3865 rc = do_copy (ctx, (char *)result);
3866 pthread_cleanup_pop (1);
3868 else
3869 rc = do_copy (ctx, line);
3871 return send_error (ctx, rc);
3874 static gpg_error_t
3875 do_move (assuan_context_t ctx, char *line)
3877 struct client_s *client = assuan_get_pointer (ctx);
3878 char **args;
3879 xmlNodePtr src, dst;
3880 struct xml_request_s *req;
3881 gpg_error_t rc;
3883 if (!line || !*line)
3884 return GPG_ERR_SYNTAX;
3886 args = str_split (line, " ", 0);
3887 if (!args || strv_length (args) != 2)
3889 strv_free (args);
3890 return GPG_ERR_SYNTAX;
3893 if (*args[1])
3895 char **targs = str_split (args[1], "\t", 0);
3896 if (!targs)
3898 strv_free (args);
3899 return GPG_ERR_ENOMEM;
3902 if (!xml_valid_element_path (targs, 0))
3904 strv_free (targs);
3905 strv_free (args);
3906 return GPG_ERR_INV_VALUE;
3909 strv_free (targs);
3912 rc = xml_new_request (client, args[0], XML_CMD_MOVE, &req);
3913 if (rc)
3915 strv_free (args);
3916 return rc;
3919 src = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3920 if (rc)
3921 goto fail;
3923 rc = xml_is_element_owner (client, src);
3924 if (rc)
3925 goto fail;
3927 xml_free_request (req);
3928 req = NULL;
3929 if (*args[1])
3931 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
3932 if (rc)
3933 goto fail;
3935 dst = xml_find_elements (client, req, xmlDocGetRootElement (req->doc),
3936 &rc);
3938 else
3939 dst = xmlDocGetRootElement (client->doc);
3941 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3942 goto fail;
3944 rc = 0;
3946 for (xmlNodePtr n = dst; n; n = n->parent)
3948 if (n == src)
3950 rc = GPG_ERR_EEXIST;
3951 goto fail;
3955 if (dst)
3957 xmlChar *a = xml_attribute_value (src, (xmlChar *) "_name");
3958 xmlNodePtr dup = xml_find_element (client, dst->children, (char *) a, &rc);
3960 xmlFree (a);
3961 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3962 goto fail;
3964 rc = 0;
3966 if (dup)
3968 if (dup == src)
3970 rc = GPG_ERR_EEXIST;
3971 goto fail;
3974 if (dst == xmlDocGetRootElement (client->doc))
3976 xmlNodePtr n = src;
3977 int match = 0;
3979 while (n->parent && n->parent != dst)
3980 n = n->parent;
3982 a = xml_attribute_value (n, (xmlChar *) "_name");
3983 xmlChar *b = xml_attribute_value (src, (xmlChar *) "_name");
3985 if (xmlStrEqual (a, b))
3987 match = 1;
3988 xmlUnlinkNode (src);
3989 (void)xml_unlink_node (client, n);
3992 xmlFree (a);
3993 xmlFree (b);
3995 if (!match)
3996 (void)xml_unlink_node (client, dup);
3998 else
3999 xmlUnlinkNode (dup);
4003 if (!dst && req && req->args && *req->args)
4005 struct xml_request_s *nreq = NULL;
4006 xmlChar *name = xml_attribute_value (src, (xmlChar *) "_name");
4008 if (src->parent == xmlDocGetRootElement (client->doc)
4009 && !strcmp ((char *) name, *req->args))
4011 xmlFree (name);
4012 rc = GPG_ERR_EEXIST;
4013 goto fail;
4016 xmlFree (name);
4017 rc = xml_new_request (client, args[1], XML_CMD_STORE, &nreq);
4018 if (!rc)
4020 dst = xml_find_elements (client, nreq,
4021 xmlDocGetRootElement (nreq->doc), &rc);
4022 xml_free_request (nreq);
4025 if (rc)
4026 goto fail;
4029 xml_update_element_mtime (client, src->parent);
4030 xmlUnlinkNode (src);
4032 dst = xmlAddChildList (dst, src);
4033 if (!dst)
4034 rc = GPG_ERR_ENOMEM;
4035 else
4036 xml_update_element_mtime (client, dst->parent);
4038 fail:
4039 xml_free_request (req);
4040 strv_free (args);
4041 return rc;
4044 static gpg_error_t
4045 move_command (assuan_context_t ctx, char *line)
4047 struct client_s *client = assuan_get_pointer (ctx);
4048 gpg_error_t rc;
4049 struct argv_s *args[] = {
4050 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
4051 NULL
4054 rc = parse_options (&line, args, client, 1);
4055 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
4056 rc = GPG_ERR_SYNTAX;
4057 if (rc)
4058 return send_error (ctx, rc);
4060 rc = copy_on_write (client);
4061 if (rc)
4062 return send_error (ctx, rc);
4064 if (client->opts & OPT_INQUIRE)
4066 unsigned char *result;
4067 size_t len;
4069 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
4070 if (rc)
4071 return send_error (ctx, rc);
4073 pthread_cleanup_push ((void *)xfree, result);
4074 rc = do_move (ctx, (char *)result);
4075 pthread_cleanup_pop (1);
4077 else
4078 rc = do_move (ctx, line);
4080 return send_error (ctx, rc);
4083 static int
4084 sort_files (const void *arg1, const void *arg2)
4086 char *const *a = arg1;
4087 char *const *b = arg2;
4089 return strcmp (*a, *b);
4092 static gpg_error_t
4093 ls_command (assuan_context_t ctx, char *line)
4095 struct client_s *client = assuan_get_pointer (ctx);
4096 gpg_error_t rc;
4097 char *tmp;
4098 char *dir;
4099 DIR *d;
4100 char *list = NULL;
4101 char **v = NULL;
4102 struct dirent *cur = NULL;
4103 struct argv_s *args[] = {
4104 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_opt_verbose},
4105 NULL
4108 rc = parse_options (&line, args, client, 0);
4109 if (rc)
4110 return send_error (ctx, rc);
4112 tmp = str_asprintf ("%s/data", homedir);
4113 dir = expand_homedir (tmp);
4114 xfree (tmp);
4115 if (!dir)
4116 return send_error (ctx, GPG_ERR_ENOMEM);
4118 d = opendir (dir);
4119 rc = gpg_error_from_errno (errno);
4121 if (!d)
4123 xfree (dir);
4124 return send_error (ctx, rc);
4127 pthread_cleanup_push ((void *)closedir, d);
4128 xfree (dir);
4129 rc = 0;
4131 while ((cur = readdir (d)))
4133 char **vtmp;
4134 struct stat st;
4136 rc = open_check_file (cur->d_name, NULL, &st, 1);
4137 if (rc)
4138 continue;
4140 if (client->opts & OPT_VERBOSE)
4141 tmp = str_asprintf ("%s %lu.%lu %lu.%lu %lu.%lu", cur->d_name,
4142 st.st_atim.tv_sec, st.st_atim.tv_nsec,
4143 st.st_mtim.tv_sec, st.st_mtim.tv_nsec,
4144 st.st_ctim.tv_sec, st.st_ctim.tv_nsec);
4145 else
4146 tmp = str_dup (cur->d_name);
4148 if (!tmp)
4150 rc = GPG_ERR_ENOMEM;
4151 break;
4154 vtmp = strv_cat (v, tmp);
4155 if (!vtmp)
4157 xfree (tmp);
4158 rc = GPG_ERR_ENOMEM;
4159 break;
4162 v = vtmp;
4165 pthread_cleanup_pop (1); // closedir (d)
4167 if (rc && rc != GPG_ERR_ENODEV)
4169 strv_free (v);
4170 return send_error (ctx, rc);
4173 rc = 0;
4174 if (v && *v)
4176 unsigned n, t = strv_length (v);
4178 qsort (v, t, sizeof (char **), sort_files);
4180 for (n = 0; n < t; n++)
4182 tmp = str_asprintf ("%s%s\n", list ? list : "", v[n]);
4183 if (!tmp)
4185 xfree (list);
4186 rc = GPG_ERR_ENOMEM;
4187 break;
4190 xfree (list);
4191 list = tmp;
4195 strv_free (v);
4196 if (rc || !list)
4197 return send_error (ctx, rc ? rc : GPG_ERR_NO_DATA);
4199 list[strlen (list) - 1] = 0;
4200 pthread_cleanup_push (xfree, list);
4201 rc = xfer_data (ctx, list, strlen (list));
4202 pthread_cleanup_pop (1);
4203 return send_error (ctx, rc);
4206 /* Run all commands in the command list 'head'. The return code isn't
4207 * considered at all for a command. It is stored in the list and later sent to
4208 * the client. */
4209 static gpg_error_t
4210 dispatch_bulk_commands (struct client_s *client, struct sexp_s **list)
4212 unsigned i;
4213 unsigned id = 0;
4214 gpg_error_t rc = 0;
4216 for (i = 0; list && list[i];)
4218 struct bulk_cmd_s *cur = list[i]->user;
4220 if (!strcmp (list[i]->tag, "command"))
4222 i++;
4223 continue;
4225 else if (!strcmp (list[i]->tag, "id"))
4227 id = i++;
4228 continue;
4231 if ((client->flags & FLAG_NO_PINENTRY) && cur->cmd->inquire)
4233 rc = send_status (client->ctx, STATUS_BULK, "BEGIN %s",
4234 list[id]->data);
4235 if (rc)
4236 break;
4239 client->bulk_p = cur;
4240 cur->ran = 1;
4242 cur->rc = command_startup (client->ctx, cur->cmd->name);
4243 if (!cur->rc)
4244 cur->rc = cur->cmd->handler (client->ctx, list[i]->data);
4246 if ((client->flags & FLAG_NO_PINENTRY) && cur->cmd->inquire)
4248 (void)send_status (client->ctx, STATUS_BULK, "END %s",
4249 list[id]->data);
4251 command_finalize (client->ctx, cur->rc);
4252 cur->rc = cur->rc ? cur->rc : client->last_rc;
4254 do {
4255 if (list[i+1] && !strcmp (list[i+1]->tag, "rc"))
4257 gpg_error_t erc = 0;
4258 int match = 0;
4260 if (list[i+1]->data)
4262 char **rcs = str_split (list[i+1]->data, "|", 0);
4263 char **p;
4265 for (p = rcs; p && *p; p++)
4267 erc = strtoul (*p, NULL, 10);
4268 if (erc == cur->rc)
4270 match = 1;
4271 break;
4275 strv_free (rcs);
4278 if (!match)
4280 i++;
4281 continue;
4284 rc = dispatch_bulk_commands (client, list[++i]->next);
4286 else
4288 i++;
4289 break;
4291 } while (1);
4294 return rc;
4297 static gpg_error_t
4298 bulk_command (assuan_context_t ctx, char *line)
4300 struct client_s *client = assuan_get_pointer (ctx);
4301 gpg_error_t rc = 0;
4302 unsigned char *result, *p;
4303 size_t len;
4304 struct sexp_s **sexp = NULL;
4305 struct argv_s *args[] = {
4306 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
4307 NULL
4310 rc = parse_options (&line, args, client, 1);
4311 if (rc)
4312 return send_error (ctx, rc);
4314 if ((client->opts & OPT_INQUIRE) && line && *line)
4315 rc = GPG_ERR_SYNTAX;
4316 else if (!(client->opts & OPT_INQUIRE) && (!line || !*line))
4317 rc = GPG_ERR_SYNTAX;
4319 if (rc)
4320 return send_error (ctx, rc);
4322 if (client->opts & OPT_INQUIRE)
4324 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
4325 if (rc)
4326 return send_error (ctx, rc);
4327 p = result;
4329 else
4331 p = (unsigned char *)line;
4332 len = line && *line ? strlen (line) : 0;
4335 if (!len)
4336 return send_error (ctx, GPG_ERR_SYNTAX);
4338 rc = bulk_parse_commands (&sexp, (const char *)p, command_table);
4339 if (client->opts & OPT_INQUIRE)
4340 xfree (result);
4342 if (rc)
4343 return send_error (ctx, rc);
4345 pthread_cleanup_push ((void *)bulk_free_list, sexp);
4346 rc = dispatch_bulk_commands (client, sexp);
4347 pthread_cleanup_pop (0);
4348 if (!rc)
4349 rc = bulk_build_result (sexp, (char **)&result);
4351 bulk_free_list (sexp);
4353 if (!rc)
4355 pthread_cleanup_push ((void *)xfree, result);
4356 rc = xfer_data (ctx, (char *)result, strlen ((char *)result));
4357 pthread_cleanup_pop (1);
4360 return send_error (ctx, rc);
4363 static gpg_error_t
4364 nop_command (assuan_context_t ctx, char *line)
4366 return send_error (ctx, 0);
4369 static gpg_error_t
4370 bye_notify (assuan_context_t ctx, char *line)
4372 struct client_s *cl = assuan_get_pointer (ctx);
4373 gpg_error_t ret = 0;
4375 (void)line;
4376 update_client_state (cl, CLIENT_STATE_DISCON);
4378 #ifdef WITH_GNUTLS
4379 cl->disco = 1;
4380 if (cl->thd->remote)
4382 int rc;
4386 struct timeval tv = { 0, 50000 };
4388 rc = gnutls_bye (cl->thd->tls->ses, GNUTLS_SHUT_RDWR);
4389 if (rc == GNUTLS_E_AGAIN)
4390 select (0, NULL, NULL, NULL, &tv);
4392 while (rc == GNUTLS_E_AGAIN);
4394 #endif
4396 /* This will let assuan_process_next() return. */
4397 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
4399 cl->last_rc = gpg_error_from_errno (errno);
4400 ret = cl->last_rc;
4403 cl->last_rc = 0; // BYE command result
4404 return ret;
4407 static gpg_error_t
4408 reset_notify (assuan_context_t ctx, char *line)
4410 struct client_s *client = assuan_get_pointer (ctx);
4412 (void)line;
4413 if (client)
4414 reset_client (client);
4416 return 0;
4420 * This is called before every Assuan command.
4422 static gpg_error_t
4423 command_startup (assuan_context_t ctx, const char *name)
4425 struct client_s *client = assuan_get_pointer (ctx);
4426 gpg_error_t rc = 0;
4427 struct command_table_s *cmd = NULL;
4429 log_write2 ("command='%s'", name);
4430 client->last_rc = client->opts = 0;
4432 for (int i = 0; command_table[i]; i++)
4434 if (!strcasecmp (name, command_table[i]->name))
4436 if (command_table[i]->ignore_startup)
4437 goto send_state;
4439 cmd = command_table[i];
4440 break;
4444 if (!cmd)
4445 return GPG_ERR_UNKNOWN_COMMAND;
4447 client->last_rc = rc = gpg_error (file_modified (client, cmd));
4449 send_state:
4450 if (!client->bulk_p && !rc)
4451 update_client_state (client, CLIENT_STATE_COMMAND);
4453 return rc;
4457 * This is called after every Assuan command.
4459 static void
4460 command_finalize (assuan_context_t ctx, gpg_error_t rc)
4462 struct client_s *client = assuan_get_pointer (ctx);
4464 if (!(client->flags & FLAG_LOCK_CMD))
4465 unlock_file_mutex (client, 0);
4467 unlock_flock (&client->flock_fd);
4468 log_write2 (_("command completed: rc=%u"), rc ? rc : client->last_rc);
4470 #ifdef WITH_GNUTLS
4471 client->thd->buffer_timeout = client->thd->last_buffer_size = 0;
4472 #endif
4474 if (!client->bulk_p && client->thd->state != CLIENT_STATE_DISCON)
4475 update_client_state (client, CLIENT_STATE_IDLE);
4477 client->bulk_p = NULL;
4480 static gpg_error_t
4481 parse_help_opt_html (void *data, void *value)
4483 struct client_s *client = data;
4485 (void) value;
4486 client->opts |= OPT_HTML;
4487 return 0;
4490 static gpg_error_t
4491 help_command (assuan_context_t ctx, char *line)
4493 gpg_error_t rc;
4494 int i;
4495 struct client_s *client = assuan_get_pointer (ctx);
4496 struct argv_s *args[] = {
4497 &(struct argv_s) {"html", OPTION_TYPE_NOARG, parse_help_opt_html},
4498 NULL
4501 rc = parse_options (&line, args, client, 1);
4502 if (rc)
4503 return send_error (ctx, rc);
4505 if (!line || !*line)
4507 char *tmp;
4508 char *help = str_dup (_("Usage: HELP [--html] [<COMMAND>]\n"
4509 "For commands that take an element path as an argument, each element is "
4510 "separated with an ASCII @key{TAB} character (ASCII 0x09)."
4511 "@*@*COMMANDS:"));
4513 for (i = 0; command_table[i]; i++)
4515 if (!command_table[i]->help)
4516 continue;
4518 /* @npxref{} won't put a "See " or "see " in front of the command.
4519 * It's not a texinfo command but needed for --html. */
4520 tmp = str_asprintf ("%s %s%s%s", help,
4521 client->opts & OPT_HTML ? "@npxref{" : "",
4522 command_table[i]->name,
4523 client->opts & OPT_HTML ? "}" : "");
4524 xfree (help);
4525 help = tmp;
4528 tmp = strip_texi_and_wrap (help, client->opts & OPT_HTML);
4529 xfree (help);
4530 pthread_cleanup_push ((void *)xfree, tmp);
4531 rc = xfer_data (ctx, tmp, strlen (tmp));
4532 pthread_cleanup_pop (1);
4533 return send_error (ctx, rc);
4536 for (i = 0; command_table[i]; i++)
4538 if (!strcasecmp (line, command_table[i]->name))
4540 char *help, *tmp;
4542 if (!command_table[i]->help)
4543 break;
4545 help = strip_texi_and_wrap (command_table[i]->help,
4546 client->opts & OPT_HTML);
4547 tmp = str_asprintf ("%s%s",
4548 (client->opts & OPT_HTML) ? "" : _("Usage: "),
4549 help);
4550 xfree (help);
4551 pthread_cleanup_push ((void *)xfree, tmp);
4552 rc = xfer_data (ctx, tmp, strlen (tmp));
4553 pthread_cleanup_pop (1);
4554 return send_error (ctx, rc);
4558 return send_error (ctx, GPG_ERR_INV_NAME);
4561 static void
4562 new_command (const char *name, int inquire, int ignore, int unlock,
4563 int flock_type, gpg_error_t (*handler) (assuan_context_t, char *),
4564 const char *help)
4566 int i = 0;
4567 struct command_table_s **tmp;
4569 if (command_table)
4570 for (i = 0; command_table[i]; i++);
4572 tmp = xrealloc (command_table, (i + 2) * sizeof (struct command_table_s *));
4573 assert (tmp);
4574 command_table = tmp;
4575 command_table[i] = xcalloc (1, sizeof (struct command_table_s));
4576 command_table[i]->name = name;
4577 command_table[i]->inquire = inquire;
4578 command_table[i]->handler = handler;
4579 command_table[i]->ignore_startup = ignore;
4580 command_table[i]->unlock = unlock;
4581 command_table[i]->flock_type = flock_type;
4582 command_table[i++]->help = help;
4583 command_table[i] = NULL;
4586 void
4587 deinit_commands ()
4589 int i;
4591 for (i = 0; command_table[i]; i++)
4592 xfree (command_table[i]);
4594 xfree (command_table);
4597 static int
4598 sort_commands (const void *arg1, const void *arg2)
4600 struct command_table_s *const *a = arg1;
4601 struct command_table_s *const *b = arg2;
4603 if (!*a || !*b)
4604 return 0;
4605 else if (*a && !*b)
4606 return 1;
4607 else if (!*a && *b)
4608 return -1;
4610 return strcmp ((*a)->name, (*b)->name);
4613 static gpg_error_t
4614 passwd_command (assuan_context_t ctx, char *line)
4616 struct client_s *client = assuan_get_pointer (ctx);
4617 gpg_error_t rc;
4619 (void)line;
4620 rc = peer_is_invoker (client);
4621 if (rc)
4622 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
4624 if (client->flags & FLAG_NEW)
4625 return send_error (ctx, GPG_ERR_INV_STATE);
4627 client->crypto->keyfile = config_get_string (client->filename,
4628 "passphrase_file");
4629 rc = crypto_init_ctx (client->crypto, client->flags & FLAG_NO_PINENTRY,
4630 client->crypto->keyfile);
4631 if (!rc)
4632 rc = crypto_passwd (client, client->crypto);
4634 crypto_free_non_keys (client->crypto);
4635 return send_error (ctx, rc);
4638 static gpg_error_t
4639 parse_opt_data (void *data, void *value)
4641 struct client_s *client = data;
4643 (void) value;
4644 client->opts |= OPT_DATA;
4645 return 0;
4648 static gpg_error_t
4649 send_client_list (assuan_context_t ctx)
4651 struct client_s *client = assuan_get_pointer (ctx);
4652 gpg_error_t rc = 0;
4654 if (client->opts & OPT_VERBOSE)
4656 unsigned i, t;
4657 char **list = NULL;
4658 char *line;
4660 MUTEX_LOCK (&cn_mutex);
4661 pthread_cleanup_push ((void *)release_mutex_cb, &cn_mutex);
4662 t = slist_length (cn_thread_list);
4664 for (i = 0; i < t; i++)
4666 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
4667 char *tmp;
4669 if (thd->state == CLIENT_STATE_UNKNOWN)
4670 continue;
4672 tmp = build_client_info_line (thd, 0);
4673 if (tmp)
4675 char **l = strv_cat (list, tmp);
4676 if (!l)
4677 rc = GPG_ERR_ENOMEM;
4678 else
4679 list = l;
4681 else
4682 rc = GPG_ERR_ENOMEM;
4684 if (rc)
4686 strv_free (list);
4687 break;
4691 pthread_cleanup_pop (1);
4692 if (rc)
4693 return rc;
4695 line = strv_join ("\n", list);
4696 strv_free (list);
4697 pthread_cleanup_push ((void *)xfree, line);
4698 rc = xfer_data (ctx, line, strlen (line));
4699 pthread_cleanup_pop (1);
4700 return rc;
4703 if (client->opts & OPT_DATA)
4705 char buf[ASSUAN_LINELENGTH];
4707 MUTEX_LOCK (&cn_mutex);
4708 snprintf (buf, sizeof (buf), "%u", slist_length (cn_thread_list));
4709 MUTEX_UNLOCK (&cn_mutex);
4710 rc = xfer_data (ctx, buf, strlen (buf));
4712 else
4713 rc = send_status (ctx, STATUS_CLIENTS, NULL);
4715 return rc;
4718 static gpg_error_t
4719 getinfo_command (assuan_context_t ctx, char *line)
4721 struct client_s *client = assuan_get_pointer (ctx);
4722 gpg_error_t rc;
4723 char buf[ASSUAN_LINELENGTH];
4724 struct argv_s *args[] = {
4725 &(struct argv_s) {"data", OPTION_TYPE_NOARG, parse_opt_data},
4726 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_opt_verbose},
4727 NULL
4730 rc = parse_options (&line, args, client, 1);
4731 if (rc)
4732 return send_error (ctx, rc);
4734 if (!line || !*line)
4735 return send_error (ctx, GPG_ERR_SYNTAX);
4737 if (!strcasecmp (line, "clients"))
4739 rc = send_client_list (ctx);
4741 else if (!strcasecmp (line, "cache"))
4743 if (client->opts & OPT_DATA)
4745 snprintf (buf, sizeof (buf), "%u", cache_file_count ());
4746 rc = xfer_data (ctx, buf, strlen (buf));
4748 else
4749 rc = send_status (ctx, STATUS_CACHE, NULL);
4751 else if (!strcasecmp (line, "pid"))
4753 pid_t pid = getpid ();
4755 snprintf (buf, sizeof (buf), "%u", pid);
4756 rc = xfer_data (ctx, buf, strlen (buf));
4758 else if (!strcasecmp (line, "version"))
4760 char *tmp = str_asprintf ("0x%06x %s", VERSION_HEX,
4761 #ifdef WITH_GNUTLS
4762 "GNUTLS "
4763 #endif
4764 #ifdef WITH_LIBACL
4765 "ACL "
4766 #endif
4767 "");
4768 pthread_cleanup_push (xfree, tmp);
4769 rc = xfer_data (ctx, tmp, strlen (tmp));
4770 pthread_cleanup_pop (1);
4772 else if (!strcasecmp (line, "last_error"))
4774 if (client->last_error)
4775 rc = xfer_data (ctx, client->last_error, strlen (client->last_error));
4776 else
4777 rc = GPG_ERR_NO_DATA;
4779 else if (!strcasecmp (line, "user"))
4781 char *user = NULL;
4783 #ifdef WITH_GNUTLS
4784 if (client->thd->remote)
4785 user = str_asprintf ("#%s", client->thd->tls->fp);
4786 else
4787 user = get_username (client->thd->peer->uid);
4788 #else
4789 user = get_username (client->thd->peer->uid);
4790 #endif
4791 if (user)
4793 pthread_cleanup_push ((void *)xfree, user);
4794 rc = xfer_data (ctx, user, strlen (user));
4795 pthread_cleanup_pop (1);
4797 else
4798 rc = GPG_ERR_NO_DATA;
4800 else
4801 rc = gpg_error (GPG_ERR_SYNTAX);
4803 return send_error (ctx, rc);
4806 static gpg_error_t
4807 parse_opt_secret (void *data, void *value)
4809 struct client_s *client = data;
4811 (void) value;
4812 client->opts |= OPT_SECRET;
4813 return 0;
4816 static gpg_error_t
4817 parse_keyinfo_opt_learn (void *data, void *value)
4819 struct client_s *client = data;
4821 (void)value;
4822 client->opts |= OPT_KEYINFO_LEARN;
4823 return 0;
4826 static gpg_error_t
4827 keyinfo_command (assuan_context_t ctx, char *line)
4829 struct client_s *client = assuan_get_pointer (ctx);
4830 gpg_error_t rc = 0;
4831 char **keys = NULL, **p = NULL;
4832 int sym = 0;
4833 struct argv_s *args[] = {
4834 &(struct argv_s) {"learn", OPTION_TYPE_NOARG, parse_keyinfo_opt_learn},
4835 NULL
4838 rc = parse_options (&line, args, client, 0);
4839 if (rc)
4840 return send_error (ctx, rc);
4842 if (line && *line)
4843 return send_error (ctx, GPG_ERR_SYNTAX);
4845 if (!(client->flags & FLAG_OPEN))
4846 return send_error (ctx, GPG_ERR_INV_STATE);
4848 if (client->opts & OPT_KEYINFO_LEARN)
4850 rc = cache_agent_command ("LEARN");
4851 return send_error (ctx, rc);
4854 if (client->flags & FLAG_NEW)
4855 return send_error (ctx, GPG_ERR_NO_DATA);
4857 rc = lock_flock (ctx, client->filename, FLOCK_TYPE_SH, &client->flock_fd);
4858 if (rc)
4859 return send_error (ctx, rc);
4861 rc = crypto_is_symmetric (client->filename);
4862 unlock_flock (&client->flock_fd);
4863 if (!rc)
4864 sym = 1;
4865 else if (rc != GPG_ERR_BAD_DATA)
4866 return send_error (ctx, rc);
4868 rc = 0;
4869 if (!sym)
4871 p = strv_catv (keys, client->crypto->pubkey);
4872 if (!p)
4873 rc = GPG_ERR_ENOMEM;
4874 else
4875 keys = p;
4878 if (!rc && client->crypto->sigkey)
4880 if (!strv_printf (&keys, "S%s", client->crypto->sigkey))
4882 strv_free (keys);
4883 return send_error (ctx, GPG_ERR_ENOMEM);
4887 if (!rc)
4889 if (keys)
4891 line = strv_join ("\n", keys);
4892 strv_free (keys);
4893 pthread_cleanup_push ((void *)xfree, line);
4894 if (line)
4895 rc = xfer_data (ctx, line, strlen (line));
4896 else
4897 rc = GPG_ERR_ENOMEM;
4899 pthread_cleanup_pop (1);
4901 else
4902 rc = GPG_ERR_NO_DATA;
4904 else
4905 strv_free (keys);
4907 return send_error (ctx, rc);
4910 static gpg_error_t
4911 deletekey_command (assuan_context_t ctx, char *line)
4913 gpg_error_t rc;
4914 struct client_s *client = assuan_get_pointer (ctx);
4915 struct crypto_s *crypto = NULL;
4916 char *keys[] = { NULL, NULL };
4917 gpgme_key_t *result;
4918 char **p = NULL;
4920 if (!(client->flags & FLAG_OPEN))
4921 return send_error (ctx, GPG_ERR_INV_STATE);
4923 rc = peer_is_invoker (client);
4924 if (rc)
4925 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
4927 if (client->flags & FLAG_NO_PINENTRY)
4928 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
4930 if (!*line)
4931 return send_error (ctx, GPG_ERR_SYNTAX);
4933 rc = crypto_keyid_to_16b_once (line);
4934 if (rc)
4935 return send_error (ctx, rc);
4937 for (p = client->crypto->pubkey; p && *p; p++)
4939 if (!strcmp (*p, line))
4940 break;
4943 if (!p)
4945 if (client->crypto->sigkey && strcmp (client->crypto->sigkey, line))
4946 return send_error (ctx, GPG_ERR_FORBIDDEN);
4947 else if (!client->crypto->sigkey)
4948 return send_error (ctx, GPG_ERR_NO_SECKEY);
4951 rc = crypto_init (&crypto, client->ctx, client->filename,
4952 client->flags & FLAG_NO_PINENTRY, NULL);
4953 if (rc)
4954 return send_error (ctx, rc);
4956 pthread_cleanup_push ((void *)crypto_free, crypto);
4957 keys[0] = line;
4958 rc = crypto_list_keys (crypto, keys, 1, &result);
4959 if (!rc)
4961 pthread_cleanup_push ((void *)crypto_free_key_list, result);
4962 rc = crypto_delete_key (client, crypto, *result, 1);
4963 pthread_cleanup_pop (1);
4966 pthread_cleanup_pop (1);
4967 return send_error (ctx, rc);
4970 static gpg_error_t
4971 kill_command (assuan_context_t ctx, char *line)
4973 struct client_s *client = assuan_get_pointer (ctx);
4974 gpg_error_t rc;
4975 unsigned i, t;
4977 if (!line || !*line)
4978 return send_error (ctx, GPG_ERR_SYNTAX);
4980 MUTEX_LOCK (&cn_mutex);
4981 pthread_cleanup_push ((void *)release_mutex_cb, &cn_mutex);
4982 t = slist_length (cn_thread_list);
4983 rc = GPG_ERR_ESRCH;
4985 for (i = 0; i < t; i++)
4987 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
4988 char *tmp = str_asprintf ("%p", thd->tid);
4990 if (strcmp (line, tmp))
4992 xfree (tmp);
4993 continue;
4996 xfree (tmp);
4997 rc = peer_is_invoker (client);
4998 if (!rc)
5000 #ifdef HAVE_PTHREAD_CANCEL
5001 pthread_cancel (thd->tid);
5002 #else
5003 pthread_kill (thd->tid, SIGUSR2);
5004 #endif
5005 break;
5007 else if (rc == GPG_ERR_EACCES)
5008 rc = GPG_ERR_FORBIDDEN;
5009 else if (rc)
5010 break;
5012 if (config_get_boolean ("global", "strict_kill"))
5013 break;
5015 #ifdef WITH_GNUTLS
5016 if (client->thd->remote && thd->remote)
5018 if (!thd->tls || !thd->tls->fp)
5020 rc = GPG_ERR_INV_STATE;
5021 break;
5023 if (!strcmp (client->thd->tls->fp, thd->tls->fp))
5025 #ifdef HAVE_PTHREAD_CANCEL
5026 pthread_cancel (thd->tid);
5027 #else
5028 pthread_kill (thd->tid, SIGUSR2);
5029 #endif
5030 rc = 0;
5031 break;
5034 else if (!client->thd->remote && !thd->remote)
5035 #endif
5037 if (client->thd->peer->uid == thd->peer->uid)
5039 #ifdef HAVE_PTHREAD_CANCEL
5040 pthread_cancel (thd->tid);
5041 #else
5042 pthread_kill (thd->tid, SIGUSR2);
5043 #endif
5044 rc = 0;
5047 break;
5050 pthread_cleanup_pop (1);
5051 return send_error (ctx, rc);
5054 static gpg_error_t
5055 listkeys_command (assuan_context_t ctx, char *line)
5057 struct client_s *client = assuan_get_pointer (ctx);
5058 struct crypto_s *crypto = NULL;
5059 char **pattern = NULL;
5060 gpgme_key_t *keys = NULL;
5061 char **result = NULL;
5062 gpg_error_t rc;
5063 struct argv_s *args[] = {
5064 &(struct argv_s) {"secret-only", OPTION_TYPE_NOARG, parse_opt_secret},
5065 NULL
5068 rc = parse_options (&line, args, client, 1);
5069 if (rc)
5070 return send_error (ctx, rc);
5072 rc = crypto_init (&crypto, client->ctx, client->filename,
5073 client->flags & FLAG_NO_PINENTRY, NULL);
5074 if (rc)
5075 return send_error (ctx, rc);
5077 pthread_cleanup_push ((void *)crypto_free, crypto);
5078 if (line)
5079 pattern = str_split (line, ",", 0);
5080 pthread_cleanup_push ((void *)(void *)strv_free, pattern);
5081 rc = crypto_list_keys (crypto, pattern, client->opts & OPT_SECRET,
5082 &keys);
5083 pthread_cleanup_pop (1);
5084 pthread_cleanup_pop (1);
5085 if (!rc)
5087 int i;
5089 for (i = 0; keys[i]; i++)
5091 char *p = crypto_key_info (keys[i]);
5092 char **r;
5094 if (!p)
5096 rc = GPG_ERR_ENOMEM;
5097 break;
5100 r = strv_cat (result, p);
5101 if (!r)
5103 rc = GPG_ERR_ENOMEM;
5104 break;
5107 result = r;
5110 if (!i)
5111 rc = GPG_ERR_NO_DATA;
5113 crypto_free_key_list (keys);
5116 if (!rc)
5118 line = strv_join ("\n", result);
5119 strv_free (result);
5120 pthread_cleanup_push ((void *)xfree, line);
5121 if (!line)
5122 rc = GPG_ERR_ENOMEM;
5123 else
5124 rc = xfer_data (ctx, line, strlen (line));
5126 pthread_cleanup_pop (1);
5128 else
5129 strv_free (result);
5131 if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
5132 || gpg_err_code (rc) == GPG_ERR_NO_SECKEY)
5133 rc = GPG_ERR_NO_DATA;
5135 return send_error (ctx, rc);
5138 void
5139 init_commands ()
5141 /* !BEGIN-HELP-TEXT!
5143 * This comment is used as a marker to generate the offline documentation
5144 * found in doc/pwmd.info. The indentation needs to be kept for the awk
5145 * script to determine where commands begin and end.
5147 new_command("HELP", 0, 1, 1, 0, help_command, _(
5148 "HELP [--html] [<COMMAND>]\n" /* Showing available commands. */
5149 "Show available commands or command specific help text."
5150 "@*@*"
5151 "The @option{--html} option will output the help text in HTML format."
5154 new_command("DELETEKEY", 0, 1, 1, FLOCK_TYPE_SH|FLOCK_TYPE_KEEP, deletekey_command, _(
5155 "DELETEKEY <keyid>\n" /* Deleting a key from the key ring. */
5156 "Deletes the public and secret key associated with key @var{keyid} from the "
5157 "keyring. The @var{keyid} must be one associated with the currently opened "
5158 "data file. "
5159 "Note that no confirmation occurs. Also note that when the key is deleted, "
5160 "the current or other data files using this key will no longer be able to be "
5161 "opened."
5164 new_command("KILL", 0, 1, 0, 0, kill_command, _(
5165 "KILL <thread_id>\n" /* Terminating another client. */
5166 "Terminates the client identified by @var{thread_id} and releases any file "
5167 "lock or other resources it has held. See @code{GETINFO} (@pxref{GETINFO}) "
5168 "for details about listing connected clients. An @code{invoking_user} "
5169 "(@pxref{Configuration}) may kill any client while others may only kill "
5170 "clients of the same @code{UID} or @abbr{TLS} fingerprint."
5173 new_command("LISTKEYS", 0, 1, 0, 0, listkeys_command, _(
5174 "LISTKEYS [--secret-only] [pattern[,<pattern>]]\n" /* Listing keys in the key ring. */
5175 "Returns a new line separated list of key information matching a comma "
5176 "separated list of @var{pattern}'s. When option @option{--secret-only} is "
5177 "specified, only keys matching @var{pattern} that also have a secret key "
5178 "available will be returned."
5181 new_command("KEYINFO", 0, 1, 0, 0, keyinfo_command, _(
5182 "KEYINFO [--learn]\n" /* Showing keys used for the current data file. */
5183 "Returns a new line separated list of key ID's that the currently opened "
5184 "data file has recipients and signers for. If the key is a signing key it "
5185 "will be prefixed with an @code{S}. If the file is a new one, or has no "
5186 "signers in the case of being symmetrically encrypted, the error code "
5187 "@code{GPG_ERR_NO_DATA} is returned."
5188 "@*@*"
5189 "When the @option{--learn} option is passed, keys on a smartcard will be "
5190 "imported."
5193 new_command("GETINFO", 0, 1, 1, 0, getinfo_command, _(
5194 "GETINFO [--data] [--verbose] CACHE | CLIENTS | PID | USER | LAST_ERROR | VERSION\n" /* Obtaining server and client information. */
5195 "Get server and other information. The information is returned via a status "
5196 "message (@pxref{Status Messages}) unless otherwise noted or @option{--data} "
5197 "is specified."
5198 "@*@*"
5199 "@var{CACHE} returns the number of cached documents."
5200 "@*@*"
5201 "@var{CLIENTS} returns the number of "
5202 "connected clients via a status message or a list of connected clients when "
5203 "the @option{--verbose} parameter is used (implies @option{--data}). A "
5204 "verbose line of a client list contains "
5205 "space delimited "
5206 "fields: the thread ID, client name, opened file (@code{/} if none opened), "
5207 "IP address if remote, file lock status, whether the current client is self "
5208 "or not, client state (see below), "
5209 "user ID or TLS fingerprint of the connected client, username if the "
5210 "client is a local one else @code{-}, and finally the time stamp of when the "
5211 "client connected."
5212 "@*@*"
5213 "Client state @code{0} is an unknown client state, state @code{1} indicates "
5214 "the client has connected but hasn't completed initializing, state @code{2} "
5215 "indicates that the client is idle, state @code{3} means the "
5216 "client is in a command and state @code{4} means the client is disconnecting. "
5217 "@*@*"
5218 "@var{PID} returns the process ID number of the server via a data response."
5219 "@*@*"
5220 "@var{VERSION} returns the server version number and compile-time features "
5221 "via a data response with each being space delimited."
5222 "@*@*"
5223 "@var{LAST_ERROR} returns a detailed description of the last failed command "
5224 "via a data response, when available."
5225 "@*@*"
5226 "@var{USER} returns the username or @abbr{TLS} hash of the connected client "
5227 "via a data response."
5230 new_command("PASSWD", 1, 0, 0, FLOCK_TYPE_EX|FLOCK_TYPE_KEEP, passwd_command, _(
5231 "PASSWD\n" /* Changing the passphrase for a key. */
5232 "Changes the passphrase of the secret key required to open the current "
5233 "data file. If the data file is symmetrically encrypted the error "
5234 "@code{GPG_ERR_NOT_SUPPORTED} is returned. When symmetrically encrypted "
5235 "the @code{SAVE} command (@pxref{SAVE}) should be used instead to prevent "
5236 "this command saving any unwanted changes to the @abbr{XML} document."
5237 "@*@*"
5238 "Note that when the current data file has been either encrypted or signed "
5239 "with a key stored on a smartcard this command will return an error. In this "
5240 "case you should instead use @command{gpg --card-edit} to change the "
5241 "pin of the smartcard or @command{gpg --edit-key} to change the passphrase "
5242 "of the key used to sign or encrypt the data file."
5243 "@*@*"
5244 "This command is not available to non-invoking clients "
5245 "(@pxref{Access Control})."
5248 new_command("OPEN", 1, 1, 1, FLOCK_TYPE_SH|FLOCK_TYPE_KEEP, open_command, _(
5249 "OPEN [--lock] <filename>\n" /* Opening a data file. */
5250 "Opens @var{filename}. When the @var{filename} is not found on the "
5251 "file-system then a new in-memory document will be created. If the file is "
5252 "found, it is looked for in the file cache and when found no passphrase will "
5253 "be required to open it. When not cached, @cite{pinentry(1)} will be used to "
5254 "retrieve the passphrase for decryption unless @option{disable-pinentry} "
5255 "(@pxref{OPTION}) was specified in which case @command{pwmd} will "
5256 "@emph{INQUIRE} the client for the passphrase. Note than when configuration "
5257 "option @option{strict_open} is enabled and the client is not an "
5258 "@option{invoking_user}, an error will be returned when the data file does "
5259 "not exist."
5260 "@*@*"
5261 "When the @option{--lock} option is passed then the file mutex will be "
5262 "locked as if the @code{LOCK} command (@pxref{LOCK}) had been sent after the "
5263 "file had been opened."
5266 new_command("GENKEY", 1, 1, 1, 0, genkey_command, _(
5267 "GENKEY --subkey-of=fpr | --userid=\"str\" [--no-expire | --expire=N] [--algo=\"str\"] [--no-passphrase] [--usage=\"default|sign|encrypt\"]\n" /* Generating a new key. */
5268 "Generates a new key based on option arguments. One of "
5269 "@option{--subkey-of} or @option{--userid} is "
5270 "required. The @option{--subkey-of} option will generate a subkey for the key "
5271 "of the specified fingerprint."
5274 new_command("SAVE", 1, 0, 0, FLOCK_TYPE_EX|FLOCK_TYPE_KEEP, save_command, _(
5275 "SAVE [--sign-keyid=[<fpr>]] [--symmetric | --keyid=<fpr>[,..] | --inquire-keyid]\n" /* Saving document changes to disk. */
5276 "Writes the in-memory @abbr{XML} document to disk. The file written to is the "
5277 "file that was opened when using the @code{OPEN} command (@pxref{OPEN})."
5278 "@*@*"
5279 "If the file is a new one one of @option{--symmetric}, @option{--keyid} or"
5280 "@option{--inquire-keyid} is required. When not @option{--symmetric} the "
5281 "option @option{--sign-keyid} is also required but optional otherwise."
5282 "@*@*"
5283 "You can encrypt the data file to a recipient other than the one that it "
5284 "was originally encrypted with by passing the @option{--keyid} or "
5285 "@option{--inquire-keyid} option with a comma separated list of "
5286 "public encryption key fingerprints as its argument. Use the "
5287 "@command{LISTKEYS} command (@pxref{LISTKEYS}) to show key information by "
5288 "pattern. The @option{--sign-keyid} option may also be used to sign the data "
5289 "file with an alternate key by specifying the fingerprint of a signing key. "
5290 "Only one signing key is supported unlike the @option{--keyid} option. "
5291 "A passphrase to decrypt the data file "
5292 "will be required when one or more of the original encryption keys or signing "
5293 "key are not found in either of these two options' arguments or when the data "
5294 "file is symmetrically encrypted regardless of the @code{require_save_key} "
5295 "configuration parameter. The original encryption keys and signing key will be "
5296 "used when neither of these options are specified."
5297 "@*@*"
5298 "The @option{--keyid} and @option{--sign-keyid} options are not available "
5299 "to non-invoking clients "
5300 "(@pxref{Access Control}) when the recipients or signer do not match those "
5301 "that were used when the file was @code{OPEN}'ed."
5302 "@*@*"
5303 "The @option{--symmetric} option specifies that a new data file be "
5304 "conventionally encrypted. These types of data files do not use a recipient "
5305 "public key but may optionally be signed by using the @option{--sign-keyid} "
5306 "option. To remove the signing key from a symmtrically encrypted data file, "
5307 "leave the option value empty."
5308 "@*@*"
5309 "Note that you cannot change encryption schemes once a data file has been "
5310 "saved."
5313 new_command("ISCACHED", 0, 1, 0, 0, iscached_command, _(
5314 "ISCACHED [--lock] [--agent [--sign]] <filename>\n" /* Testing cache status. */
5315 "Determines the file cache status of the specified @var{filename}. "
5316 "The default is to test whether the filename is cached in memory. Passing "
5317 "option @option{--agent} will test the @command{gpg-agent} cache for at most "
5318 "one cached key used for opening the data file (@pxref{OPEN}). To test if "
5319 "a signing key is cached, pass @option{--sign} along with @option{--agent}. "
5320 "Both the @option{--agent} and @option{--sign} options require an opened data "
5321 "file."
5322 "@*@*"
5323 "An @emph{OK} response is returned if the specified @var{filename} is found "
5324 "in the cache. If not found in the cache but exists on the filesystem "
5325 "then @code{GPG_ERR_NO_DATA} is returned. Otherwise a filesystem error is "
5326 "returned."
5327 "@*@*"
5328 "The @option{--lock} option will lock the file mutex of @var{filename} when "
5329 "the file exists; it does not need to be opened nor cached. The lock will be "
5330 "released when the client exits or sends the @code{UNLOCK} command "
5331 "(@pxref{UNLOCK}). When this option is passed the current data file is closed."
5334 new_command("CLEARCACHE", 0, 1, 1, 0, clearcache_command, _(
5335 "CLEARCACHE [<filename>]\n" /* Removing a cache entry. */
5336 "Clears a file cache entry for all or the specified @var{filename}. Note that "
5337 "this will also clear any @command{gpg-agent} cached keys which may cause "
5338 "problems if another data file shares the same keys as @var{filename}."
5339 "@*@*"
5340 "When clearing all cache entries a permissions test is done against the "
5341 "current client based on the @var{allowed} configuration parameter in a "
5342 "@var{filename} section. Both a cache entry may be cleared and an error "
5343 "returned depending on cached data files and client permissions."
5346 new_command("CACHETIMEOUT", 0, 1, 1, 0, cachetimeout_command, _(
5347 "CACHETIMEOUT <seconds>\n" /* Setting the cache timeout. */
5348 "The time in @var{seconds} until the currently opened data file will be "
5349 "removed from the cache. @code{-1} will keep the cache entry forever, "
5350 "@code{0} will require the passphrase for each @code{OPEN} command "
5351 "(@pxref{OPEN}) or @code{SAVE} (@pxref{SAVE}) command. @xref{Configuration}, "
5352 "and the @code{cache_timeout} parameter."
5355 new_command("LIST", 0, 0, 1, 0, list_command, _(
5356 "LIST [--inquire] [--recurse] [element[<TAB>child[..]]]\n" /* Showing document elements. */
5357 "If no element path is given then a newline separated list of root elements "
5358 "is returned with a data response. If given, then children of the specified "
5359 "element path are returned."
5360 "@*@*"
5361 "Each element path "
5362 "returned will have zero or more flags appened to it. These flags are "
5363 "delimited from the element path by a single space character. A flag itself "
5364 "is a single character. Flag @code{P} indicates that access to the element "
5365 "is denied. Flag @code{+} indicates that there are child nodes of "
5366 "the current element path. Flag @code{E} indicates that an element of the "
5367 "element path contained in a @var{target} attribute could not be found. Flag "
5368 "@code{O} indicates that a @var{target} attribute recursion limit was reached "
5369 "(@pxref{Configuration}). Flag @code{T}, followed by a single space character, "
5370 "then an element path, is the element path of the @var{target} attribute "
5371 "contained in the current element."
5372 "@*@*"
5373 "When a specified element path contains an error either from the final "
5374 "element in the path or any previous element, the path is still shown but "
5375 "will contain the error flag for the element with the error. Determining "
5376 "the actual element which contains the error is up to the client. This can be "
5377 "done by traversing the final element up to parent elements that contain the "
5378 "same error flag."
5379 "@*@*"
5380 "The option @option{--recurse} may be used to list the entire element tree "
5381 "for a specified element path or the entire tree for all root elements."
5382 "@*@*"
5383 "When the @option{--inquire} option is passed then all remaining non-option "
5384 "arguments are retrieved via a server @emph{INQUIRE}."
5387 new_command("REALPATH", 0, 0, 1, 0, realpath_command, _(
5388 "REALPATH [--inquire] element[<TAB>child[..]]\n" /* Resolving an element. */
5389 "Resolves all @code{target} attributes of the specified element path and "
5390 "returns the result with a data response. @xref{Target Attribute}, for details."
5391 "@*@*"
5392 "When the @option{--inquire} option is passed then all remaining non-option "
5393 "arguments are retrieved via a server @emph{INQUIRE}."
5396 new_command("STORE", 0, 0, 1, 0, store_command, _(
5397 "STORE element[<TAB>child[..]]<TAB>[content]\n" /* Modifying the content of an element. */
5398 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
5399 "@*@*"
5400 "Creates a new element path or modifies the @var{content} of an existing "
5401 "element. If only a single element is specified then a new root element is "
5402 "created. Otherwise, elements are @key{TAB} delimited and the content will be "
5403 "set to the final @key{TAB} delimited element. If no @var{content} is "
5404 "specified after the final @key{TAB}, then the content of the existing "
5405 "element will be removed; or will be empty if creating a new element."
5406 "@*@*"
5407 "The only restriction of an element name is that it not contain whitespace "
5408 "characters. There is no other whitespace between the @key{TAB} delimited "
5409 "elements. It is recommended that the content of an element be base64 encoded "
5410 "when it contains control or @key{TAB} characters to prevent @abbr{XML} "
5411 "parsing and @command{pwmd} syntax errors."
5414 new_command("RENAME", 0, 0, 1, 0, rename_command, _(
5415 "RENAME [--inquire] element[<TAB>child[..]] <value>\n" /* Renaming an element. */
5416 "Renames the specified @var{element} to the new @var{value}. If an element of "
5417 "the same name as the @var{value} already exists it will be overwritten."
5418 "@*@*"
5419 "When the @option{--inquire} option is passed then all remaining non-option "
5420 "arguments are retrieved via a server @emph{INQUIRE}."
5423 new_command("COPY", 0, 0, 1, 0, copy_command, _(
5424 "COPY [--inquire] source[<TAB>child[..]] dest[<TAB>child[..]]\n" /* Copying an element. */
5425 "Copies the entire element tree starting from the child node of the source "
5426 "element, to the destination element path. If the destination element path "
5427 "does not exist then it will be created; otherwise it is overwritten."
5428 "@*@*"
5429 "Note that attributes from the source element are merged into the "
5430 "destination element when the destination element path exists. When an "
5431 "attribute of the same name exists in both the source and destination "
5432 "elements then the destination attribute will be updated to the source "
5433 "attribute value."
5434 "@*@*"
5435 "When the @option{--inquire} option is passed then all remaining non-option "
5436 "arguments are retrieved via a server @emph{INQUIRE}."
5439 new_command("MOVE", 0, 0, 1, 0, move_command, _(
5440 "MOVE [--inquire] source[<TAB>child[..]] [dest[<TAB>child[..]]]\n" /* Moving an element. */
5441 "Moves the source element path to the destination element path. If the "
5442 "destination is not specified then it will be moved to the root node of the "
5443 "document. If the destination is specified and exists then it will be "
5444 "overwritten; otherwise non-existing elements of the destination element "
5445 "path will be created."
5446 "@*@*"
5447 "When the @option{--inquire} option is passed then all remaining non-option "
5448 "arguments are retrieved via a server @emph{INQUIRE}."
5451 new_command("DELETE", 0, 0, 1, 0, delete_command, _(
5452 "DELETE [--inquire] element[<TAB>child[..]]\n" /* Deleting an element. */
5453 "Removes the specified element path and all of its children. This may break "
5454 "an element with a @code{target} attribute (@pxref{Target Attribute}) that "
5455 "refers to this element or any of its children."
5456 "@*@*"
5457 "When the @option{--inquire} option is passed then all remaining non-option "
5458 "arguments are retrieved via a server @emph{INQUIRE}."
5461 new_command("GET", 0, 0, 1, 0, get_command, _(
5462 "GET [--inquire] element[<TAB>child[..]]\n" /* Getting the content of an element. */
5463 "Retrieves the content of the specified element. The content is returned "
5464 "with a data response."
5465 "@*@*"
5466 "When the @option{--inquire} option is passed then all remaining non-option "
5467 "arguments are retrieved via a server @emph{INQUIRE}."
5470 new_command("ATTR", 0, 0, 1, 0, attr_command, _(
5471 "ATTR [--inquire] SET|GET|DELETE|LIST [<attribute>] element[<TAB>child[..]] ..\n" /* Modifying element attributes. */
5472 "@table @asis\n"
5473 "@item ATTR SET attribute element[<TAB>child[..]] [value]\n"
5474 " Stores or updates an @var{attribute} name and optional @var{value} of an "
5475 "element. When no @var{value} is specified any existing value will be removed."
5476 "@*@*"
5477 "@item ATTR DELETE attribute element[<TAB>child[..]]\n"
5478 " Removes an attribute from an element. If @var{attribute} is @code{_name} "
5479 "or @code{target} an error is returned. Use the @command{DELETE} command "
5480 "(@pxref{DELETE}) instead."
5481 "@*@*"
5482 "@item ATTR LIST element[<TAB>child[..]]\n"
5483 " Retrieves a newline separated list of attributes names and values "
5484 "from the specified element. Each attribute name and value is space delimited."
5485 "@*@*"
5486 "@item ATTR GET attribute element[<TAB>child[..]]\n"
5487 " Retrieves the value of an @var{attribute} from an element."
5488 "@end table\n"
5489 "@*@*"
5490 "When the @option{--inquire} option is passed then all remaining non-option "
5491 "arguments are retrieved via a server @emph{INQUIRE}."
5492 "@*@*"
5493 "@xref{Target Attribute}, for details about this special attribute and also "
5494 "@pxref{Other Attributes} for other attributes that are handled specially "
5495 "by @command{pwmd}."
5498 new_command("XPATH", 0, 0, 1, 0, xpath_command, _(
5499 "XPATH [--inquire] <expression>[<TAB>[value]]\n" /* Modifying more than one element. */
5500 "Evaluates an XPath @var{expression}. If no @var{value} argument is "
5501 "specified it is assumed the expression is a request to return a result. "
5502 "Otherwise, the result is set to the @var{value} argument and the document is "
5503 "updated. If there is no @var{value} after the @key{TAB} character, the value "
5504 "is assumed to be empty and the document is updated. For example:"
5505 "@sp 1\n"
5506 "@example\n"
5507 "XPATH //element[@@_name='password']@key{TAB}\n"
5508 "@end example\n"
5509 "@sp 1\n"
5510 "would clear the content of all @var{password} elements in the data file "
5511 "while leaving off the trailing @key{TAB} would return all @var{password} "
5512 "elements in @abbr{XML} format."
5513 "@*@*"
5514 "When the @option{--inquire} option is passed then all remaining non-option "
5515 "arguments are retrieved via a server @emph{INQUIRE}."
5516 "@*@*"
5517 "See @url{https://www.w3schools.com/xml/xpath_intro.asp} for @abbr{XPATH} "
5518 "expression syntax."
5521 new_command("XPATHATTR", 0, 0, 1, 0, xpathattr_command, _(
5522 "XPATHATTR [--inquire] SET|DELETE <name> <expression>[<TAB>[<value>]]\n" /* Modifying more than one element's attributes. */
5523 "Like the @code{XPATH} command (@pxref{XPATH}) but operates on element "
5524 "attributes and does not return a result. For the @var{SET} operation the "
5525 "@var{value} is optional but the field is required. If not specified then "
5526 "the attribute value will be empty. For example:"
5527 "@sp 1\n"
5528 "@example\n"
5529 "XPATHATTR SET password //element[@@_name='password']@key{TAB}\n"
5530 "@end example\n"
5531 "@sp 1\n"
5532 "would create a @var{password} attribute for each @var{password} element "
5533 "found in the document. The attribute value will be empty but still exist."
5534 "@*@*"
5535 "When the @option{--inquire} option is passed then all remaining non-option "
5536 "arguments are retrieved via a server @emph{INQUIRE}."
5537 "@*@*"
5538 "See @url{https://www.w3schools.com/xml/xpath_intro.asp} for @abbr{XPATH} "
5539 "expression syntax."
5542 new_command("IMPORT", 0, 0, 1, 0, import_command, _(
5543 "IMPORT [--root=element[<TAB>child[..]]]\n" /* Creating elements from XML. */
5544 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
5545 "@*@*"
5546 "Like the @code{STORE} command (@pxref{STORE}), but the @var{content} "
5547 "argument is raw @abbr{XML} data. The content is created as a child of "
5548 "the element path specified with the @option{--root} option or at the "
5549 "document root when not specified. Existing elements of the same name will "
5550 "be overwritten."
5551 "@*@*"
5552 "The content must begin with an @abbr{XML} element node. @xref{Introduction}, "
5553 "for details."
5556 new_command("DUMP", 0, 1, 1, 0, dump_command, _(
5557 "DUMP\n" /* Showing the XML document. */
5558 "Shows the in memory @abbr{XML} document with indenting. @xref{XPATH}, for "
5559 "dumping a specific node."
5562 new_command("LOCK", 0, 0, 0, 0, lock_command, _(
5563 "LOCK\n" /* Locking the current data file. */
5564 "Locks the mutex associated with the opened file. This prevents other clients "
5565 "from sending commands to the same opened file until the client "
5566 "that sent this command either disconnects or sends the @code{UNLOCK} "
5567 "command. @xref{UNLOCK}."
5570 new_command("UNLOCK", 0, 1, 0, 0, unlock_command, _(
5571 "UNLOCK\n" /* Removing a data file lock. */
5572 "Unlocks the file mutex which was locked with the @code{LOCK} command or "
5573 "a commands' @option{--lock} option (@pxref{LOCK}, @pxref{OPEN}, "
5574 "@pxref{ISCACHED})."
5577 new_command("GETCONFIG", 0, 1, 1, 0, getconfig_command, _(
5578 "GETCONFIG [filename] <parameter>\n" /* Obtaining a configuration value. */
5579 "Returns the value of a @command{pwmd} configuration @var{parameter} with a "
5580 "data response. If no file has been opened then the value for @var{filename} "
5581 "or the default from the @var{global} section will be returned. If a file "
5582 "has been opened and no @var{filename} is specified, the value previously "
5583 "set with the @code{OPTION} command (@pxref{OPTION}) will be returned."
5586 new_command("OPTION", 0, 1, 1, 0, option_command, _(
5587 "OPTION <NAME>=[<VALUE>]\n" /* Setting various client parameters. */
5588 "Sets a client option @var{name} to @var{value}. The value for an option is "
5589 "kept for the duration of the connection with the exception of the "
5590 "@command{pinentry} options which are defaults for all future connections "
5591 "(@pxref{Pinentry}). When @var{value} is empty the option is unset."
5592 "@*@*"
5593 "@table @asis\n"
5594 "@item DISABLE-PINENTRY\n"
5595 "Disable use of @command{pinentry} for passphrase retrieval. When @code{1}, a "
5596 "server inquire is sent to the client to obtain the passphrase. This option "
5597 "may be set as needed before the @code{OPEN} (@pxref{OPEN}), @code{PASSWD} "
5598 "(@pxref{PASSWD}) and @code{SAVE} (@pxref{SAVE}) commands. Set to @code{0} "
5599 "to use a @command{pinentry}."
5600 "@*@*"
5601 "@item DISPLAY\n"
5602 "Set or unset the X11 display to use when prompting for a passphrase."
5603 "@*@*"
5604 "@item TTYNAME\n"
5605 "Set the terminal device path to use when prompting for a passphrase."
5606 "@*@*"
5607 "@item TTYTYPE\n"
5608 "Set the terminal type for use with @option{TTYNAME}."
5609 "@*@*"
5610 "@item NAME\n"
5611 "Associates the thread ID of the connection with the specified textual "
5612 "representation. Useful for debugging log messages. May not contain whitespace."
5613 "@*@*"
5614 "@item LOCK-TIMEOUT\n"
5615 "When not @code{0}, the duration in tenths of a second to wait for the file "
5616 "mutex which has been locked by another thread to be released before returning "
5617 "an error. When @code{-1} the error will be returned immediately."
5618 "@*@*"
5619 "@item CLIENT-STATE\n"
5620 "When set to @code{1} then client state status messages for other clients are "
5621 "sent to the current client. The default is @code{0}."
5622 "@end table\n"
5625 new_command("LS", 0, 1, 1, 0, ls_command, _(
5626 "LS [--verbose]\n" /* Showing available data files. */
5627 "Returns a newline separated list of data files stored in the data directory "
5628 "@file{HOMEDIR/data} (@pxref{Invoking}) with a data response. When the "
5629 "@var{--verbose} option is passed, the space-separated filesystem inode "
5630 "access, modification and change times are appended to the line."
5633 new_command("BULK", 0, 1, 1, 0, bulk_command, _(
5634 "BULK [--inquire]\n" /* Run a series of commands in sequence. */
5635 "Parses a semi-canonical s-expression representing a series of protocol "
5636 "commands to be run in sequence (@pxref{Bulk Commands}). Returns a canonical "
5637 "s-expression containing each commands id, return value and result data "
5638 "(if any)."
5639 "@*@*"
5640 "When the @option{--inquire} option is passed then all remaining non-option "
5641 "arguments are retrieved via a server @emph{INQUIRE}."
5644 new_command("RESET", 0, 1, 1, 0, NULL, _(
5645 "RESET\n" /* Resetting the client state. */
5646 "Closes the currently opened file but keeps any previously set client options "
5647 "(@pxref{OPTION})."
5650 new_command("NOP", 0, 1, 1, 0, nop_command, _(
5651 "NOP\n" /* Testing the connection. */
5652 "This command does nothing. It is useful for testing the connection for a "
5653 "timeout condition."
5656 /* !END-HELP-TEXT! */
5657 new_command ("CANCEL", 0, 1, 1, 0, NULL, NULL);
5658 new_command ("END", 0, 1, 1, 0, NULL, NULL);
5659 new_command ("BYE", 0, 1, 1, 0, NULL, NULL);
5661 int i;
5662 for (i = 0; command_table[i]; i++);
5663 qsort (command_table, i - 1, sizeof (struct command_table_s *),
5664 sort_commands);
5667 gpg_error_t
5668 register_commands (assuan_context_t ctx)
5670 int i = 0, rc;
5672 for (; command_table[i]; i++)
5674 if (!command_table[i]->handler)
5675 continue;
5677 rc = assuan_register_command (ctx, command_table[i]->name,
5678 command_table[i]->handler,
5679 command_table[i]->help);
5680 if (rc)
5681 return rc;
5684 rc = assuan_register_bye_notify (ctx, bye_notify);
5685 if (rc)
5686 return rc;
5688 rc = assuan_register_reset_notify (ctx, reset_notify);
5689 if (rc)
5690 return rc;
5692 rc = assuan_register_pre_cmd_notify (ctx, command_startup);
5693 if (rc)
5694 return rc;
5696 return assuan_register_post_cmd_notify (ctx, command_finalize);