Fix EXPIRE status message.
[pwmd.git] / src / commands.c
blobc370d638f645611a3780f5ff6901c983fce71eca
1 /*
2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015,
3 2016, 2017
4 Ben Kibbey <bjk@luxsci.net>
6 This file is part of pwmd.
8 Pwmd is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 2 of the License, or
11 (at your option) any later version.
13 Pwmd is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
21 #ifdef HAVE_CONFIG_H
22 #include <config.h>
23 #endif
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <err.h>
29 #include <errno.h>
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <fcntl.h>
33 #include <ctype.h>
34 #include <dirent.h>
35 #include <pthread.h>
36 #include <stdint.h>
37 #include <assert.h>
38 #include <signal.h>
40 #include "pwmd-error.h"
41 #include <gcrypt.h>
43 #include "mem.h"
44 #include "xml.h"
45 #include "util-misc.h"
46 #include "common.h"
47 #include "rcfile.h"
48 #include "cache.h"
49 #include "commands.h"
50 #include "mutex.h"
51 #include "crypto.h"
52 #include "acl.h"
54 /* These are command option flags. */
55 #define OPT_INQUIRE 0x0001
56 #define OPT_NO_PASSPHRASE 0x0002
57 #define OPT_ASK 0x0004
58 #define OPT_LIST_RECURSE 0x0008
59 #define OPT_VERBOSE 0x0010
60 #define OPT_LOCK 0x0020
61 #define OPT_LOCK_ON_OPEN 0x0040
62 #define OPT_SIGN 0x0080
63 #define OPT_LIST_ALL 0x0100
64 #define OPT_DATA 0x0200
65 #define OPT_NO_AGENT 0x0400
66 #define OPT_SECRET 0x0800
67 #define OPT_INQUIRE_KEYID 0x1000
68 #define OPT_SYMMETRIC 0x4000
69 #define OPT_NO_SIGNER 0x8000
70 #define OPT_HTML 0x10000
71 #define OPT_CACHE_AGENT 0x20000
72 #define OPT_CACHE_SIGN 0x40000
73 #define OPT_KEYINFO_LEARN 0x80000
75 #define FLOCK_TYPE_NONE 0
76 #define FLOCK_TYPE_SH 0x0001
77 #define FLOCK_TYPE_EX 0x0002
78 #define FLOCK_TYPE_KEEP 0x0004
80 static char env_display[256];
81 static char env_gpg_tty[256];
82 static char env_term[256];
84 struct command_table_s
86 const char *name;
87 gpg_error_t (*handler) (assuan_context_t, char *line);
88 const char *help;
89 int ignore_startup;
90 int unlock; // unlock the file mutex after validating the checksum
91 unsigned flock_type;
94 static struct command_table_s **command_table;
96 static gpg_error_t do_lock (struct client_s *client, int add);
97 static gpg_error_t validate_checksum (struct client_s *, const char *filename,
98 struct cache_data_s *, unsigned char **,
99 size_t *);
100 static gpg_error_t update_checksum (struct client_s *client,
101 unsigned char *from_crc, size_t crclen);
103 /* When 'status' is true the 'self' field of the status line will be false
104 * because we never send the STATE status message to the same client that
105 * initiated it. */
106 static char *
107 build_client_info_line (struct client_thread_s *thd, int status)
109 char *uid, *username = NULL;
110 char *line;
112 #ifdef WITH_GNUTLS
113 if (thd->remote)
114 uid = str_asprintf("#%s", thd->tls->fp);
115 else
117 uid = str_asprintf("%u", thd->peer->uid);
118 username = get_username (thd->peer->uid);
120 #else
121 uid = str_asprintf("%u", thd->peer->uid);
122 username = get_username (thd->peer->uid);
123 #endif
124 line = str_asprintf ("%p %s %s %s %u %u %u %s %s %u",
125 thd->tid,
126 thd->name ? thd->name : "-",
127 thd->cl && thd->cl->filename
128 && (thd->cl->flags & FLAG_OPEN)
129 ? thd->cl->filename : "/",
130 #ifdef WITH_GNUTLS
131 thd->remote ? thd->peeraddr : "-",
132 #else
133 "-",
134 #endif
135 thd->cl && thd->cl->flags & FLAG_HAS_LOCK ? 1 : 0,
136 !status && pthread_equal (pthread_self (), thd->tid) ? 1 : 0,
137 thd->state, uid,
138 #ifdef WITH_GNUTLS
139 thd->remote ? "-" : username,
140 #else
141 username,
142 #endif
143 thd->conntime
146 xfree (username);
147 xfree (uid);
148 return line;
151 void
152 update_client_state (struct client_s *client, unsigned s)
154 MUTEX_LOCK (&cn_mutex);
155 client->thd->state = s;
156 MUTEX_UNLOCK (&cn_mutex);
158 if (client->thd->state != CLIENT_STATE_UNKNOWN)
160 char *line = build_client_info_line (client->thd, 1);
162 pthread_cleanup_push (xfree, line);
163 if (line)
164 send_status_all_not_self (STATUS_STATE, "%s", line);
165 pthread_cleanup_pop (1);
169 static gpg_error_t
170 unlock_file_mutex (struct client_s *client, int remove)
172 gpg_error_t rc = 0;
174 // OPEN: keep the lock for the same file being reopened.
175 if (client->flags & FLAG_KEEP_LOCK && client->flags & FLAG_HAS_LOCK)
176 return 0;
178 if (!(client->flags & FLAG_HAS_LOCK))
179 return GPG_ERR_NOT_LOCKED;
181 rc = cache_unlock_mutex (client->filename, remove);
182 if (rc)
183 rc = GPG_ERR_INV_STATE;
184 else
185 client->flags &= ~(FLAG_HAS_LOCK | FLAG_LOCK_CMD);
187 return rc;
190 static gpg_error_t
191 lock_file_mutex (struct client_s *client, int add)
193 gpg_error_t rc = 0;
194 long timeout = config_get_long (client->filename, "cache_timeout");
196 if (client->flags & FLAG_HAS_LOCK)
197 return 0;
199 rc = cache_lock_mutex (client->ctx, client->filename,
200 client->lock_timeout, add, timeout);
201 if (!rc)
202 client->flags |= FLAG_HAS_LOCK;
204 return rc;
207 static gpg_error_t
208 file_modified (struct client_s *client, struct command_table_s *cmd)
210 gpg_error_t rc = 0;
211 int type = !cmd->flock_type || (cmd->flock_type & FLOCK_TYPE_SH)
212 ? LOCK_SH : LOCK_EX;
214 if (!(client->flags & FLAG_OPEN))
215 return GPG_ERR_INV_STATE;
217 rc = lock_file_mutex (client, 0);
218 if (rc && rc != GPG_ERR_NO_DATA)
219 return rc;
221 rc = lock_flock (client->ctx, client->filename, type, &client->flock_fd);
222 if (!rc)
224 rc = validate_checksum (client, client->filename, NULL, NULL, NULL);
225 if (gpg_err_code (rc) == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
226 rc = 0;
227 else if (rc)
228 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
230 else if (gpg_err_code (rc) == GPG_ERR_ENOENT)
231 rc = 0;
233 /* FLAG_HAS_LOCK may have been set by the LOCK command or OPEN --lock. */
234 if ((cmd->unlock && !(client->flags & FLAG_HAS_LOCK)) || rc)
235 unlock_file_mutex (client, 0);
237 if (rc || !(cmd->flock_type & FLOCK_TYPE_KEEP))
238 unlock_flock (&client->flock_fd);
240 return rc;
243 static gpg_error_t
244 parse_xml (assuan_context_t ctx, int new)
246 struct client_s *client = assuan_get_pointer (ctx);
247 int cached = client->doc != NULL;
248 gpg_error_t rc = 0;
250 if (new)
252 client->doc = xml_new_document ();
253 if (client->doc)
255 xmlChar *result;
256 int len;
258 xmlDocDumpFormatMemory (client->doc, &result, &len, 0);
259 client->crypto->plaintext = result;
260 client->crypto->plaintext_size = len;
261 if (!client->crypto->plaintext)
263 xmlFreeDoc (client->doc);
264 client->doc = NULL;
265 rc = GPG_ERR_ENOMEM;
268 else
269 rc = GPG_ERR_ENOMEM;
271 else if (!cached)
272 rc = xml_parse_doc ((char *) client->crypto->plaintext,
273 client->crypto->plaintext_size,
274 (xmlDocPtr *)&client->doc);
276 return rc;
279 static void
280 free_client (struct client_s *client)
282 cache_plaintext_release (&client->doc);
283 xfree (client->crc);
284 xfree (client->filename);
285 xfree (client->last_error);
286 crypto_free (client->crypto);
287 client->crypto = NULL;
290 void
291 reset_client (struct client_s *client)
293 assuan_context_t ctx = client->ctx;
294 struct client_thread_s *thd = client->thd;
295 long lock_timeout = client->lock_timeout;
296 xmlErrorPtr xml_error = client->xml_error;
297 int no_pinentry = (client->flags & FLAG_NO_PINENTRY);
298 int flock_fd = client->flock_fd;
300 unlock_file_mutex (client, client->flags & FLAG_NEW);
301 free_client (client);
302 memset (client, 0, sizeof (struct client_s));
303 client->flock_fd = flock_fd;
304 client->xml_error = xml_error;
305 client->ctx = ctx;
306 client->thd = thd;
307 client->lock_timeout = lock_timeout;
308 client->flags |= no_pinentry ? FLAG_NO_PINENTRY : 0;
311 static void
312 req_free (void *arg)
314 if (!arg)
315 return;
317 strv_free ((char **) arg);
320 static gpg_error_t
321 parse_open_opt_lock (void *data, void *value)
323 struct client_s *client = data;
325 (void)value;
326 client->opts |= OPT_LOCK_ON_OPEN;
327 return 0;
330 static gpg_error_t
331 parse_opt_inquire (void *data, void *value)
333 struct client_s *client = data;
335 (void) value;
336 client->opts |= OPT_INQUIRE;
337 return 0;
340 static gpg_error_t
341 update_checksum (struct client_s *client, unsigned char *from_crc,
342 size_t crclen)
344 unsigned char *crc;
345 size_t len;
346 struct cache_data_s *cdata;
347 gpg_error_t rc;
349 if (!from_crc)
351 rc = get_checksum (client->filename, &crc, &len);
352 if (rc)
353 return rc;
355 else
357 crc = from_crc;
358 len = crclen;
361 xfree (client->crc);
362 client->crc = xmalloc (len);
363 memcpy (client->crc, crc, len);
364 pthread_cleanup_push (xfree, crc);
365 cdata = cache_get_data (client->filename, NULL);
366 pthread_cleanup_pop (0);
367 if (cdata)
369 xfree (cdata->crc);
370 cdata->crc = xmalloc (len);
371 memcpy (cdata->crc, crc, len);
374 if (!from_crc)
375 xfree (crc);
376 return 0;
379 static gpg_error_t
380 validate_checksum (struct client_s *client, const char *filename,
381 struct cache_data_s *cdata, unsigned char **r_crc,
382 size_t *r_crclen)
384 unsigned char *crc;
385 size_t len;
386 gpg_error_t rc;
387 int n = 0;
389 if (cdata && !cdata->crc)
390 return GPG_ERR_CHECKSUM;
392 rc = get_checksum (filename, &crc, &len);
393 if (rc)
394 return rc;
396 if (client->crc)
397 n = memcmp (client->crc, crc, len);
398 else if ((client->flags & FLAG_NEW) && cache_get_data (filename, NULL))
399 n = 1;
401 if (!n && cdata)
402 n = memcmp (cdata->crc, crc, len);
404 if (!n && r_crc)
406 *r_crc = crc;
407 *r_crclen = len;
409 else
410 xfree (crc);
412 return n ? GPG_ERR_CHECKSUM : 0;
415 static gpg_error_t
416 open_command (assuan_context_t ctx, char *line)
418 gpg_error_t rc;
419 struct client_s *client = assuan_get_pointer (ctx);
420 int same_file = 0;
421 assuan_peercred_t peer;
422 struct cache_data_s *cdata = NULL;
423 int cached = 0;
424 unsigned char *crc = NULL;
425 size_t crclen = 0;
426 int plaintext = 0;
427 struct argv_s *args[] = {
428 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_open_opt_lock},
429 NULL
432 rc = parse_options (&line, args, client, 1);
433 if (rc)
434 return send_error (ctx, rc);
436 rc = do_validate_peer (ctx, line, &peer);
437 if (rc == GPG_ERR_FORBIDDEN)
439 rc = peer_is_invoker (client);
440 if (rc == GPG_ERR_EACCES)
441 rc = GPG_ERR_FORBIDDEN;
444 if (rc)
445 return send_error (ctx, rc);
447 if (!valid_filename (line))
448 return send_error (ctx, GPG_ERR_INV_VALUE);
450 /* This client may have locked a different file with ISCACHED --lock than
451 * the current filename. This will remove that lock. */
452 same_file = client->filename && !strcmp (line, client->filename);
453 if (client->flags & FLAG_OPEN ||
454 (client->flags & FLAG_HAS_LOCK && !same_file))
456 unsigned opts = client->opts;
457 unsigned flags = client->flags;
459 if (same_file)
460 client->flags |= FLAG_KEEP_LOCK;
462 /* Another client wrote to the same data file as currently opened. */
463 if (cache_get_data (client->filename, NULL))
464 flags &= ~FLAG_NEW;
465 /* Remove cache entry for the new file that hadn't been written. */
466 else if (client->flags & FLAG_NEW)
467 cache_clear (NULL, client->filename, 0, 0);
469 reset_client (client);
470 client->opts = opts;
471 client->flags |= flags;
472 client->flags &= ~(FLAG_LOCK_CMD);
473 if (!same_file)
474 client->flags &= ~(FLAG_HAS_LOCK | FLAG_NEW);
477 client->filename = str_dup (line);
478 if (!client->filename)
479 return send_error(ctx, GPG_ERR_ENOMEM);
481 /* Need to lock the mutex here because file_modified() cannot without
482 * knowing the filename. */
483 rc = lock_file_mutex (client, 1);
484 if (rc)
485 client->flags &= ~FLAG_OPEN;
487 if (!rc)
489 rc = lock_flock (ctx, client->filename, LOCK_SH, &client->flock_fd);
490 if (gpg_err_code (rc) == GPG_ERR_ENOENT)
491 rc = 0;
494 if (!rc)
496 char *keyfile = config_get_string (client->filename, "passphrase_file");
498 rc = crypto_init (&client->crypto, client->ctx, client->filename,
499 client->flags & FLAG_NO_PINENTRY, keyfile);
500 if (rc)
501 xfree (keyfile);
502 else
503 rc = open_check_file (client->filename, NULL, NULL, 1);
506 if (!rc || gpg_err_code (rc) == GPG_ERR_ENOENT)
508 int reload = 0;
509 int defer = 0;
511 if (rc) // new file
513 rc = 0;
515 if (config_get_boolean ("global", "strict_open"))
517 rc = peer_is_invoker (client);
518 if (rc == GPG_ERR_EACCES)
519 rc = GPG_ERR_FORBIDDEN;
522 if (!rc)
524 client->flags |= FLAG_NEW;
525 // data file disappeared. clear the cache entry.
526 cache_clear (NULL, client->filename, 1, 1);
527 cdata = NULL;
530 goto done;
533 cdata = cache_get_data (client->filename, &defer);
534 if (cdata && !defer
535 && !cache_plaintext_get (client->filename, &client->doc))
537 rc = validate_checksum (client, client->filename, cdata, &crc,
538 &crclen);
539 if (rc)
541 log_write ("%s: %s", client->filename,
542 pwmd_strerror (rc));
543 cache_plaintext_release (&client->doc);
544 if (rc == GPG_ERR_CHECKSUM)
546 cache_clear (NULL, client->filename, 1, 1);
547 cdata = NULL;
548 goto decrypt;
552 #ifdef WITH_GNUTLS
553 if (!rc && client->thd->remote
554 && config_get_boolean (client->filename, "tcp_require_key")
555 && !(client->flags & FLAG_NEW))
557 rc = crypto_try_decrypt (client,
558 (client->flags & FLAG_NO_PINENTRY));
560 #endif
561 if (!rc)
563 strv_free (client->crypto->pubkey);
564 client->crypto->pubkey = NULL;
565 if (cdata->pubkey)
566 client->crypto->pubkey = strv_dup (cdata->pubkey);
568 xfree (client->crypto->sigkey);
569 client->crypto->sigkey = NULL;
570 if (cdata->sigkey)
571 client->crypto->sigkey = str_dup (cdata->sigkey);
573 cached = 1;
574 plaintext = 1;
577 else if (cdata && cdata->doc) // cached document
579 if (!rc && !(client->flags & FLAG_NEW))
581 rc = validate_checksum (client, client->filename, cdata, &crc,
582 &crclen);
583 if (rc == GPG_ERR_CHECKSUM)
585 rc = 0;
586 reload = 1;
590 if (!rc)
592 rc = cache_iscached (client->filename, &defer, 0, 0);
593 if ((!rc || rc == GPG_ERR_ENOENT) && defer)
595 rc = 0;
596 reload = 2;
600 if (!rc && reload)
602 if (reload == 1)
603 log_write ("%s: %s", client->filename,
604 pwmd_strerror (GPG_ERR_CHECKSUM));
605 cache_clear (NULL, client->filename, 1, 1);
606 cdata = NULL;
607 rc = crypto_decrypt (client, client->crypto);
609 #ifdef WITH_GNUTLS
610 else if (!rc)
612 if (client->thd->remote
613 && config_get_boolean (client->filename, "tcp_require_key")
614 && !(client->flags & FLAG_NEW))
615 rc = crypto_try_decrypt (client,
616 (client->flags & FLAG_NO_PINENTRY));
618 #endif
620 if (!rc && cdata)
622 client->crypto->plaintext = cdata->doc;
623 client->crypto->plaintext_size = cdata->size;
624 rc = cache_decrypt (client->crypto);
625 if (!rc)
627 cdata->doc = NULL;
628 cdata->size = 0;
630 strv_free (client->crypto->pubkey);
631 client->crypto->pubkey = NULL;
632 if (cdata->pubkey)
633 client->crypto->pubkey = strv_dup (cdata->pubkey);
635 xfree (client->crypto->sigkey);
636 client->crypto->sigkey = NULL;
637 if (cdata->sigkey)
638 client->crypto->sigkey = str_dup (cdata->sigkey);
640 cached = 1;
642 else
644 client->crypto->plaintext = NULL;
645 client->crypto->plaintext_size = 0;
649 else // existing file
651 decrypt:
652 cached = cdata != NULL;
653 rc = crypto_decrypt (client, client->crypto);
657 done:
658 if (!rc && !plaintext)
660 rc = parse_xml (ctx, client->flags & FLAG_NEW);
661 if (!rc)
663 rc = cache_encrypt (client->crypto);
664 if (rc)
665 cache_clear (NULL, client->filename, 1, 1);
666 else
668 long timeout = config_get_long (client->filename,
669 "cache_timeout");
671 cache_free_data_once (cdata);
672 cdata = xcalloc (1, sizeof (struct cache_data_s));
673 cdata->doc = client->crypto->plaintext;
674 cdata->size = client->crypto->plaintext_size;
675 cdata->pubkey = strv_dup(client->crypto->pubkey);
676 cdata->sigkey = client->crypto->sigkey ? str_dup(client->crypto->sigkey) : NULL;
677 client->crypto->plaintext = NULL;
678 client->crypto->plaintext_size = 0;
680 if (cached) // wont increment the refcount
682 if (crclen)
684 xfree (client->crc);
685 client->crc = NULL;
686 xfree (cdata->crc);
687 cdata->crc = xmalloc (crclen);
688 memcpy (cdata->crc, crc, crclen);
691 rc = cache_set_data (client->filename, cdata);
692 /* The cache entry may have been removed and cache_set_data()
693 * already sent STATUS_CACHE. */
694 if (!cache_iscached (client->filename, NULL, 0, 0))
695 rc = send_status (ctx, STATUS_CACHE, NULL);
697 else
698 rc = cache_add_file (client->filename, cdata, timeout);
700 if (!rc)
701 cache_plaintext_set (client->filename, client->doc, 0);
705 else 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);
732 if (rc)
734 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
736 if (client->flags & FLAG_NEW)
737 cache_clear (NULL, client->filename, 1, 1);
739 crypto_free (client->crypto);
740 client->crypto = NULL;
741 client->flags &= ~FLAG_OPEN;
742 cache_plaintext_release (&client->doc);
744 else
745 crypto_free_non_keys (client->crypto);
747 return send_error (ctx, rc);
750 /* If not the invoking_user or is an existing file, check that the list of user
751 * supplied key ID's are in the list of current key ID's obtained when
752 * decrypting the data file.
754 static gpg_error_t
755 permitted_to_save (struct client_s *client, const char **keys,
756 const char **value)
758 gpg_error_t rc = 0;
759 const char **v;
761 if ((client->flags & FLAG_NEW) || (client->opts & OPT_SYMMETRIC))
762 return 0;
764 rc = peer_is_invoker (client);
765 if (!rc)
766 return 0;
767 else if (rc == GPG_ERR_EACCES)
768 rc = GPG_ERR_FORBIDDEN;
769 else if (rc)
770 return rc;
772 /* Empty match. */
773 if ((!value && !keys) || ((value && !*value) && (keys && !*keys)))
774 return 0;
776 for (v = value; v && *v; v++)
778 const char **k, *pv = *v;
779 int match = 0;
781 if (*pv == '0' && *(pv+1) == 'x')
782 pv += 2;
784 for (k = keys; k && *k; k++)
786 const char *pk = *k;
788 if (*pk == '0' && *(pk+1) == 'x')
789 pk += 2;
791 rc = !strcmp (pv, pk) ? 0 : GPG_ERR_FORBIDDEN;
792 if (rc)
793 rc = !strcmp (pv, *k) ? 0 : GPG_ERR_FORBIDDEN;
795 if (!rc)
797 match = 1;
798 break;
802 if (!match)
803 return GPG_ERR_FORBIDDEN;
806 return rc;
809 /* Requires that the keyid be a fingerprint in 16 byte form. */
810 static gpg_error_t
811 parse_save_opt_keyid_common (struct client_s *client, const char **list,
812 const char *value, char ***dst)
814 gpg_error_t rc = 0;
815 char **keys = NULL;
817 if (value && *value)
819 keys = str_split (value, ",", 0);
820 if (!keys)
821 return GPG_ERR_ENOMEM;
824 rc = crypto_keyid_to_16b (keys);
825 if (!rc)
826 rc = permitted_to_save (client, list, (const char **)keys);
828 if (!rc)
829 *dst = keys;
830 else
831 strv_free (keys);
833 return rc;
836 static gpg_error_t
837 parse_save_opt_keyid (void *data, void *value)
839 struct client_s *client = data;
840 const char *str = value;
841 char **dst = NULL;
842 gpg_error_t rc;
844 rc = parse_save_opt_keyid_common (client,
845 (const char **)client->crypto->pubkey,
846 str, &dst);
847 if (rc)
848 return rc;
850 client->crypto->save.pubkey = dst;
851 return 0;
854 static gpg_error_t
855 parse_save_opt_sign_keyid (void *data, void *value)
857 struct client_s *client = data;
858 const char *str = value;
859 char **dst = NULL;
860 gpg_error_t rc;
861 char **tmp = NULL;
863 if (client->crypto->sigkey)
865 if (!strv_printf (&tmp, "%s", client->crypto->sigkey))
866 return GPG_ERR_ENOMEM;
869 rc = parse_save_opt_keyid_common (client, (const char **)tmp, str, &dst);
870 strv_free (tmp);
871 if (rc)
872 return rc;
874 if (!dst)
875 client->opts |= OPT_NO_SIGNER;
876 else
877 client->crypto->save.sigkey = str_dup (*dst);
879 strv_free (dst);
880 return 0;
883 static gpg_error_t
884 parse_save_opt_inquire_keyid (void *data, void *value)
886 struct client_s *client = data;
888 (void)value;
890 if (!(client->flags & FLAG_NEW))
892 gpg_error_t rc = peer_is_invoker (client);
894 if (rc)
895 return rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc;
898 client->opts |= OPT_INQUIRE_KEYID;
899 return 0;
902 static gpg_error_t
903 parse_save_opt_symmetric (void *data, void *value)
905 struct client_s *client = data;
907 (void)value;
908 client->opts |= OPT_SYMMETRIC;
909 return 0;
912 static gpg_error_t
913 parse_genkey_opt_userid (void *data, void *value)
915 struct client_s *client = data;
917 if (!(client->flags & FLAG_NEW))
919 gpg_error_t rc = peer_is_invoker (client);
921 if (rc)
922 return rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc;
925 client->crypto->save.userid = str_dup (value);
926 return client->crypto->save.userid ? 0 : GPG_ERR_ENOMEM;
929 static gpg_error_t
930 parse_genkey_opt_algo (void *data, void *value)
932 struct client_s *client = data;
934 client->crypto->save.algo = str_dup (value);
935 return client->crypto->save.algo ? 0 : GPG_ERR_ENOMEM;
938 static gpg_error_t
939 parse_genkey_opt_expire (void *data, void *value)
941 struct client_s *client = data;
942 gpg_error_t rc = 0;
943 char *p = NULL;
944 unsigned long t;
946 errno = 0;
947 t = strtoul (value, &p, 10);
949 if (!errno && p && *p)
950 rc = GPG_ERR_INV_VALUE;
951 else if (t == ULONG_MAX)
952 rc = GPG_ERR_INV_VALUE;
953 else if (errno)
954 rc = gpg_error_from_syserror ();
955 else
956 client->crypto->save.expire = t;
958 return rc;
961 static gpg_error_t
962 parse_genkey_opt_no_passphrase (void *data, void *value)
964 struct client_s *client = data;
966 (void)value;
967 client->crypto->save.flags |= GPGME_CREATE_NOPASSWD;
968 return 0;
971 /* Tests that the keys in new_keys are also in old_keys. */
972 static gpg_error_t
973 compare_keys (char **new_keys, char **old_keys)
975 char **o;
977 if (!old_keys || !*old_keys)
978 return 0;
980 crypto_keyid_to_16b (new_keys);
982 for (o = old_keys; *o; o++)
984 char **n;
986 for (n = new_keys; *n; n++)
988 if (!strcmp (*n, *o))
989 break;
992 if (!*n)
993 return GPG_ERR_NOT_FOUND;
996 return 0;
999 static gpg_error_t
1000 inquire_keyid (struct client_s *client)
1002 gpg_error_t rc;
1003 unsigned char *result = NULL;
1004 size_t len;
1005 const char *s = "KEYID";
1006 char ***orig;
1007 char ***save;
1009 orig = &client->crypto->pubkey;
1010 save = &client->crypto->save.pubkey;
1011 rc = assuan_inquire (client->ctx, s, &result, &len, 0);
1012 if (!rc)
1014 char **dst = NULL;
1016 rc = parse_save_opt_keyid_common (client, (const char **)*orig,
1017 (char *)result, &dst);
1018 if (!rc)
1019 *save = dst;
1022 xfree (result);
1023 return rc;
1027 /* When a key lookup in gpg-agent's cache fails, the agent tries the last
1028 * successful key to be unlocked. This prevents pwmd from successfully
1029 * clearing a signing key since the previous key, which more than likely
1030 * belongs to the same keypair as the encryption/decryption key, will have the
1031 * passphrase cached and therefore the signing key also cached. So we need to
1032 * clear both the signing and encryption keys to get the effect of requiring a
1033 * passphrase when generating a new keypair for an existing data file, or when
1034 * the "require_save_key" configuration parameter is set. This parameter is
1035 * mostly a failsafe of the gpg-agent option --ignore-cache-for-signing since
1036 * some/most/all users may fail to set it.
1038 static gpg_error_t
1039 save_command (assuan_context_t ctx, char *line)
1041 struct client_s *client = assuan_get_pointer (ctx);
1042 struct cache_data_s *cdata = NULL;
1043 int sym = 0;
1044 gpg_error_t rc = 0, cache_rc = 0;
1045 int defer = 0;
1046 struct argv_s *args[] = {
1047 &(struct argv_s) {"keyid", OPTION_TYPE_ARG, parse_save_opt_keyid},
1048 &(struct argv_s) {"inquire-keyid", OPTION_TYPE_NOARG,
1049 parse_save_opt_inquire_keyid },
1050 &(struct argv_s) {"sign-keyid", OPTION_TYPE_OPTARG,
1051 parse_save_opt_sign_keyid},
1052 &(struct argv_s) {"symmetric", OPTION_TYPE_NOARG,
1053 parse_save_opt_symmetric },
1054 NULL
1057 crypto_free_save (&client->crypto->save);
1058 client->crypto->save.expire = DEFAULT_EXPIRE;
1060 rc = crypto_is_symmetric (client->filename);
1061 if (!rc || rc == GPG_ERR_BAD_DATA || rc == GPG_ERR_ENOENT)
1063 if (!rc)
1065 client->opts |= OPT_SYMMETRIC;
1066 sym = 1;
1068 else if (rc == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
1069 rc = 0; // New file
1070 else
1071 rc = 0; // PKI
1074 if (rc)
1075 return send_error (ctx, rc);
1077 rc = parse_options (&line, args, client, 0);
1078 if (rc)
1079 return send_error (ctx, rc);
1081 if (config_get_boolean (client->filename, "require_save_key")
1082 || (client->opts & OPT_SYMMETRIC))
1083 client->opts |= OPT_ASK;
1085 rc = open_check_file (client->filename, NULL, NULL, 1);
1086 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
1088 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
1089 return send_error (ctx, rc);
1092 if (!rc)
1093 cache_rc = rc = cache_iscached (client->filename, &defer, 0, 1);
1095 if (gpg_err_code (rc) == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
1096 rc = 0;
1097 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
1098 rc = 0;
1100 if (rc)
1101 return send_error (ctx, rc);
1103 /* Specifying both a recipient and symmetric encryption is an error. */
1104 if ((client->opts & OPT_INQUIRE_KEYID) && (client->opts & OPT_SYMMETRIC))
1105 return send_error (ctx, GPG_ERR_CONFLICT);
1106 /* Existing file with a recipient and wanting symmetric is an error. */
1107 else if ((client->opts & OPT_SYMMETRIC) && client->crypto->save.pubkey)
1108 return send_error (ctx, GPG_ERR_CONFLICT);
1109 else if (client->crypto->save.pubkey && (client->opts & OPT_INQUIRE_KEYID))
1110 return send_error (ctx, GPG_ERR_CONFLICT);
1111 else if (!sym && (client->opts & OPT_SYMMETRIC) && !(client->flags & FLAG_NEW))
1112 return send_error (ctx, GPG_ERR_CONFLICT);
1113 /* New file that is not symmetric without either a recipient or signer. */
1114 else if ((client->flags & FLAG_NEW) && !(client->opts & OPT_SYMMETRIC)
1115 && (!client->crypto->save.pubkey || !client->crypto->save.sigkey))
1116 return send_error (ctx, GPG_ERR_SYNTAX);
1117 else if (client->opts & OPT_INQUIRE_KEYID)
1118 rc = inquire_keyid (client);
1120 if (!rc)
1122 client->crypto->keyfile = config_get_string (client->filename,
1123 "passphrase_file");
1124 rc = crypto_init_ctx (client->crypto, (client->flags & FLAG_NO_PINENTRY),
1125 client->crypto->keyfile);
1128 if (!rc && (client->flags & FLAG_NEW))
1130 /* Require --keyid when --sign-keyid exists to keep KEYINFO
1131 * synchronized. */
1132 if (!client->crypto->save.pubkey && client->crypto->save.sigkey
1133 && !(client->opts & OPT_SYMMETRIC))
1134 rc = GPG_ERR_NO_PUBKEY;
1136 else if (!rc)
1138 cdata = cache_get_data (client->filename, NULL);
1139 if (cdata)
1141 if (client->crypto->save.pubkey)
1142 rc = compare_keys (client->crypto->save.pubkey, cdata->pubkey);
1144 /* Always allow a signer for symmetric data files. */
1145 if (!rc && client->crypto->save.sigkey
1146 && !(client->opts & OPT_SYMMETRIC))
1147 rc = !strcmp (client->crypto->save.sigkey, cdata->sigkey)
1148 ? 0 : GPG_ERR_NOT_FOUND;
1150 /* Prevent saving to a recipient who is not in the original recipient
1151 * list without a passphrase. */
1152 if (rc || (client->crypto->sigkey && (client->opts & OPT_NO_SIGNER)))
1153 client->opts |= OPT_ASK;
1155 if (rc == GPG_ERR_NOT_FOUND)
1157 rc = peer_is_invoker (client);
1158 if (rc == GPG_ERR_EACCES)
1159 rc = GPG_ERR_FORBIDDEN;
1162 if (!client->crypto->save.pubkey
1163 && !(client->opts & OPT_SYMMETRIC))
1164 client->crypto->save.pubkey = strv_dup (cdata->pubkey);
1166 if (!rc && !client->crypto->save.sigkey && cdata->sigkey
1167 && !(client->opts & OPT_NO_SIGNER))
1168 client->crypto->save.sigkey = str_dup (cdata->sigkey);
1169 else if (!rc && !client->crypto->save.sigkey
1170 && (client->opts & OPT_NO_SIGNER)
1171 && !(client->opts & OPT_SYMMETRIC))
1172 rc = GPG_ERR_NO_SIGNATURE_SCHEME;
1174 else
1176 client->crypto->save.pubkey = strv_dup (client->crypto->pubkey);
1177 client->crypto->save.sigkey = str_dup (client->crypto->sigkey);
1181 if (!rc && !(client->flags & FLAG_NEW))
1183 /* Fixes {NEW_,SIGN_}PASSPHRASE inquire keywords. See passphrase_cb(). */
1184 if (client->opts & OPT_SYMMETRIC)
1185 client->crypto->flags |= CRYPTO_FLAG_PASSWD;
1187 if (client->opts & OPT_ASK)
1189 rc = cache_clear_agent_keys (client->filename, 1, 1);
1190 if (!rc)
1191 rc = crypto_try_decrypt (client, client->flags & FLAG_NO_PINENTRY);
1195 if (!rc && client->opts & OPT_SYMMETRIC)
1196 client->crypto->flags |= CRYPTO_FLAG_PASSWD_NEW;
1198 if (!rc)
1199 rc = xml_update_element_mtime (client, xmlDocGetRootElement (client->doc));
1201 if (!rc)
1203 int size;
1205 xmlDocDumpFormatMemory (client->doc, &client->crypto->plaintext, &size,
1207 if (size > 0)
1208 client->crypto->plaintext_size = (size_t) size;
1209 else
1210 rc = GPG_ERR_ENOMEM;
1212 if (!rc)
1214 client->crypto->flags |= (client->opts & OPT_SYMMETRIC) ? CRYPTO_FLAG_SYMMETRIC : 0;
1215 client->crypto->flags |= (client->flags & FLAG_NEW) ? CRYPTO_FLAG_NEWFILE : 0;
1216 client->crypto->flags |= !(client->opts & OPT_SYMMETRIC) ? CRYPTO_FLAG_PASSWD_SIGN : 0;
1217 rc = crypto_encrypt (client, client->crypto);
1218 client->crypto->flags &= ~CRYPTO_FLAG_SYMMETRIC;
1221 if (!rc)
1223 unsigned char *crc = NULL;
1224 size_t crclen = 0;
1226 rc = crypto_write_file (client->crypto, &crc, &crclen);
1227 pthread_cleanup_push ((void *)xfree, crc);
1228 if (!rc)
1230 if (!cache_rc)
1231 cdata = cache_get_data (client->filename, NULL);
1232 else
1233 cdata = xcalloc (1, sizeof (struct cache_data_s));
1236 if (!rc)
1238 rc = cache_encrypt (client->crypto);
1239 if (rc)
1241 cache_clear (NULL, client->filename, 1, 1);
1242 client->flags &= ~(FLAG_NEW);
1244 strv_free (client->crypto->pubkey);
1245 client->crypto->pubkey = NULL;
1246 if (client->crypto->save.pubkey)
1247 client->crypto->pubkey = strv_dup (client->crypto->save.pubkey);
1249 xfree (client->crypto->sigkey);
1250 client->crypto->sigkey = NULL;
1251 if (client->crypto->save.sigkey)
1252 client->crypto->sigkey = str_dup (client->crypto->save.sigkey);
1256 if (!rc)
1258 long timeout = config_get_long (client->filename, "cache_timeout");
1259 xmlDocPtr doc = xmlCopyDoc (client->doc, 1);
1261 if (!doc)
1262 rc = GPG_ERR_ENOMEM;
1264 if (!rc)
1266 cache_plaintext_release (&client->doc);
1267 strv_free (cdata->pubkey);
1268 cdata->pubkey = client->crypto->save.pubkey;
1269 client->crypto->save.pubkey = NULL;
1271 xfree (cdata->sigkey);
1272 cdata->sigkey = client->crypto->save.sigkey;
1273 client->crypto->save.sigkey = NULL;
1275 xfree (cdata->crc);
1276 cdata->crc = NULL;
1278 /* cache_encrypt() does in-place encryption */
1279 xfree (cdata->doc);
1280 cdata->doc = client->crypto->plaintext;
1281 client->crypto->plaintext = NULL;
1282 cdata->size = client->crypto->plaintext_size;
1283 client->crypto->plaintext_size = 0;
1285 client->doc = doc;
1286 cache_plaintext_set (client->filename, client->doc, 0);
1288 /* Update in case the cache entry expires the next SAVE may
1289 * not have any known keys. */
1290 strv_free (client->crypto->pubkey);
1291 client->crypto->pubkey = NULL;
1292 if (cdata->pubkey)
1293 client->crypto->pubkey = strv_dup (cdata->pubkey);
1295 xfree (client->crypto->sigkey);
1296 client->crypto->sigkey = NULL;
1297 if (cdata->sigkey)
1298 client->crypto->sigkey = str_dup (cdata->sigkey);
1300 if (!cache_rc) // wont increment refcount
1301 rc = cache_set_data (client->filename, cdata);
1302 else
1303 rc = cache_add_file (client->filename, cdata, timeout);
1306 if (!rc && (cache_rc || (client->flags & FLAG_NEW)))
1307 send_status_all (STATUS_CACHE, NULL);
1309 if (!rc)
1311 rc = update_checksum (client, crc, crclen);
1312 client->flags &= ~(FLAG_NEW);
1316 pthread_cleanup_pop (1);
1317 if (!rc)
1318 client->did_cow = 0;
1322 crypto_free_non_keys (client->crypto);
1323 return send_error (ctx, rc);
1326 static gpg_error_t
1327 parse_genkey_opt_usage (void *data, void *v)
1329 struct client_s *client = data;
1330 char *value = v;
1332 if (!value || !*value)
1333 return GPG_ERR_INV_VALUE;
1334 else if (!strcmp (value, "sign"))
1335 client->crypto->save.flags |= GPGME_CREATE_SIGN;
1336 else if (!strcmp (value, "encrypt"))
1337 client->crypto->save.flags |= GPGME_CREATE_ENCR;
1338 else if (!strcmp (value, "default"))
1339 client->crypto->save.flags &= ~(GPGME_CREATE_ENCR|GPGME_CREATE_SIGN);
1340 else
1341 return GPG_ERR_INV_VALUE;
1343 return 0;
1346 gpg_error_t
1347 parse_genkey_opt_subkey_of (void *data, void *v)
1349 gpg_error_t rc;
1350 struct client_s *client = data;
1351 char *value = v;
1352 char *tmp[] = { value, NULL };
1353 gpgme_key_t *keys = NULL;
1355 rc = peer_is_invoker (client);
1356 if (rc)
1357 return rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc;
1359 if (!value || !*value)
1360 return GPG_ERR_INV_VALUE;
1362 rc = crypto_list_keys (client->crypto, tmp, 1, &keys);
1363 if (rc)
1364 return rc;
1366 if (!keys || !*keys)
1368 crypto_free_key_list (keys);
1369 return GPG_ERR_NO_SECKEY;
1372 client->crypto->save.mainkey = keys;
1373 return 0;
1376 static gpg_error_t
1377 genkey_command (assuan_context_t ctx, char *line)
1379 struct client_s *client = assuan_get_pointer (ctx);
1380 struct crypto_s *crypto, *orig;
1381 gpg_error_t rc = 0;
1382 struct argv_s *args[] = {
1383 &(struct argv_s) {"userid", OPTION_TYPE_ARG,
1384 parse_genkey_opt_userid},
1385 &(struct argv_s) {"expire", OPTION_TYPE_ARG,
1386 parse_genkey_opt_expire},
1387 &(struct argv_s) {"algo", OPTION_TYPE_ARG,
1388 parse_genkey_opt_algo},
1389 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG,
1390 parse_genkey_opt_no_passphrase},
1391 &(struct argv_s) {"usage", OPTION_TYPE_ARG,
1392 parse_genkey_opt_usage},
1393 &(struct argv_s) {"subkey-of", OPTION_TYPE_ARG,
1394 parse_genkey_opt_subkey_of},
1395 NULL
1398 rc = crypto_init (&crypto, ctx, client->filename,
1399 client->flags & FLAG_NO_PINENTRY, NULL);
1400 if (rc)
1401 return send_error (ctx, rc);
1403 pthread_cleanup_push ((void *)crypto_free, client->crypto);
1404 orig = client->crypto;
1405 client->crypto = crypto;
1406 rc = parse_options (&line, args, client, 0);
1407 if (rc)
1408 goto fail;
1410 if (!client->crypto->save.userid && !client->crypto->save.mainkey)
1412 rc = GPG_ERR_SYNTAX;
1413 goto fail;
1416 client->crypto->flags |= CRYPTO_FLAG_NEWFILE;
1417 rc = crypto_genkey (client, client->crypto);
1419 fail:
1420 pthread_cleanup_pop (0);
1421 crypto_free (crypto);
1422 client->crypto = orig;
1423 return send_error (ctx, rc);
1426 static gpg_error_t
1427 do_delete (assuan_context_t ctx, char *line)
1429 struct client_s *client = assuan_get_pointer (ctx);
1430 struct xml_request_s *req;
1431 xmlNodePtr n;
1432 gpg_error_t rc;
1434 rc = xml_new_request (client, line, XML_CMD_DELETE, &req);
1435 if (rc)
1436 return rc;
1438 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1439 xml_free_request (req);
1440 if (rc)
1441 return rc;
1443 rc = xml_is_element_owner (client, n);
1444 if (!rc)
1445 rc = xml_unlink_node (client, n);
1447 return rc;
1450 /* Won't update cdata->plaintext. Other clients are working on the original or
1451 * copy of the same document. The first client to SAVE wins and requires others
1452 * to reopen the data file do to a checksum error. */
1453 static gpg_error_t
1454 copy_on_write (struct client_s *client)
1456 struct cache_data_s *cdata;
1458 if (client->did_cow)
1459 return 0;
1461 cdata = cache_get_data (client->filename, NULL);
1462 if (cdata)
1464 gpg_error_t rc;
1465 xmlDocPtr doc = xmlCopyDoc (client->doc, 1);
1467 if (!doc)
1468 return GPG_ERR_ENOMEM;
1470 rc = cache_plaintext_set (client->filename, doc, 1);
1471 if (rc)
1473 xmlFree (doc);
1474 return rc;
1477 (void)cache_plaintext_release (&client->doc);
1478 client->doc = doc;
1479 client->did_cow = 1;
1480 return 0;
1483 return GPG_ERR_NO_DATA;
1486 static gpg_error_t
1487 delete_command (assuan_context_t ctx, char *line)
1489 struct client_s *client = assuan_get_pointer (ctx);
1490 gpg_error_t rc;
1491 struct argv_s *args[] = {
1492 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1493 NULL
1496 rc = parse_options (&line, args, client, 1);
1497 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1498 rc = GPG_ERR_SYNTAX;
1499 if (rc)
1500 return send_error (ctx, rc);
1502 rc = copy_on_write (client);
1503 if (rc)
1504 return send_error (ctx, rc);
1506 if (client->opts & OPT_INQUIRE)
1508 unsigned char *result;
1509 size_t len;
1511 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1512 if (rc)
1513 return send_error (ctx, rc);
1515 pthread_cleanup_push ((void *)xfree, result);
1516 rc = do_delete (ctx, (char *)result);
1517 pthread_cleanup_pop (1);
1519 else
1520 rc = do_delete (ctx, line);
1522 return send_error (ctx, rc);
1525 static gpg_error_t
1526 update_element_expirey (struct client_s *client, xmlNodePtr n)
1528 gpg_error_t rc = 0;
1529 xmlChar *expire, *incr;
1530 char *p;
1531 time_t e, e_orig, i;
1532 time_t now = time (NULL);
1534 expire = xml_attribute_value (n, (xmlChar *)"expire");
1535 if (!expire)
1536 return 0;
1538 errno = 0;
1539 e = strtoul ((char *)expire, &p, 10);
1540 if (errno || *p || e == ULONG_MAX || *expire == '-')
1542 xmlFree (expire);
1543 rc = GPG_ERR_ERANGE;
1544 goto fail;
1547 xmlFree (expire);
1548 incr = xml_attribute_value (n, (xmlChar *)"expire_increment");
1549 if (!incr)
1550 return 0;
1552 i = strtoul ((char *)incr, &p, 10);
1553 if (errno || *p || i == ULONG_MAX || *incr == '-')
1555 xmlFree (incr);
1556 rc = GPG_ERR_ERANGE;
1557 goto fail;
1560 xmlFree (incr);
1561 e_orig = e;
1562 e = e > now ? e : now + i;
1563 p = str_asprintf ("%lu", e);
1564 if (!p)
1566 rc = GPG_ERR_ENOMEM;
1567 goto fail;
1570 rc = xml_add_attribute (client, n, "expire", p);
1571 xfree (p);
1572 if (!rc)
1573 rc = send_status (client->ctx, STATUS_EXPIRE, "%lu %lu", e_orig, e);
1575 fail:
1576 return rc;
1579 static gpg_error_t
1580 store_command (assuan_context_t ctx, char *line)
1582 struct client_s *client = assuan_get_pointer (ctx);
1583 gpg_error_t rc;
1584 size_t len;
1585 unsigned char *result;
1586 xmlNodePtr n, parent;
1587 int has_content;
1588 char *content = NULL;
1589 struct xml_request_s *req;
1591 if (line && *line)
1592 return send_error (ctx, GPG_ERR_SYNTAX);
1594 rc = copy_on_write (client);
1595 if (rc)
1596 return send_error (ctx, rc);
1598 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1599 if (rc)
1600 return send_error (ctx, rc);
1602 rc = xml_new_request (client, (char *)result, XML_CMD_STORE, &req);
1603 xfree (result);
1604 if (rc)
1605 return send_error (ctx, rc);
1607 /* Prevent passing the element content around to save some memory. */
1608 len = strv_length (req->args);
1609 has_content = line && line[strlen (line) - 1] != '\t' && len > 1;
1610 if (*(req->args+1) && !xml_valid_element_path (req->args, has_content))
1612 xml_free_request (req);
1613 return send_error (ctx, GPG_ERR_INV_VALUE);
1616 if (has_content || !*req->args[len-1])
1618 content = req->args[len-1];
1619 req->args[len-1] = NULL;
1622 if (strv_length (req->args) > 1)
1624 rc = xml_check_recursion (client, req);
1625 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
1626 goto fail;
1629 parent = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1631 if (!rc && len > 1)
1633 rc = xml_is_element_owner (client, parent);
1634 if (!rc)
1636 n = xml_find_text_node (parent->children);
1637 if (n)
1638 xmlNodeSetContent (n, (xmlChar *) content);
1639 else
1640 xmlNodeAddContent (parent, (xmlChar *) content);
1642 (void)xml_update_element_mtime (client, parent);
1643 (void)update_element_expirey (client, parent);
1647 fail:
1648 xfree (content);
1649 xml_free_request (req);
1650 return send_error (ctx, rc);
1653 static gpg_error_t
1654 xfer_data (assuan_context_t ctx, const char *line, int total)
1656 struct client_s *client = assuan_get_pointer (ctx);
1657 int to_send;
1658 int sent = 0;
1659 gpg_error_t rc = 0;
1660 int progress = config_get_integer ("global", "xfer_progress");
1661 int flush = 0;
1663 if (!(client->flags & FLAG_LOCK_CMD))
1664 rc = unlock_file_mutex (client, 0);
1665 if (rc && rc != GPG_ERR_NOT_LOCKED)
1666 return rc;
1668 progress =
1669 progress > 0 ? (progress / ASSUAN_LINELENGTH) * ASSUAN_LINELENGTH : 0;
1670 to_send = total < ASSUAN_LINELENGTH ? total : ASSUAN_LINELENGTH;
1671 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1673 if (rc)
1674 return rc;
1676 again:
1679 if (sent + to_send > total)
1680 to_send = total - sent;
1682 rc = assuan_send_data (ctx, flush ? NULL : (char *) line + sent,
1683 flush ? 0 : to_send);
1684 if (!rc)
1686 sent += flush ? 0 : to_send;
1688 if ((progress && !(sent % progress) && sent != total) ||
1689 (sent == total && flush))
1690 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1692 if (!flush && !rc && sent == total)
1694 flush = 1;
1695 goto again;
1699 while (!rc && sent < total);
1701 return rc;
1704 static gpg_error_t
1705 do_get (assuan_context_t ctx, char *line)
1707 struct client_s *client = assuan_get_pointer (ctx);
1708 gpg_error_t rc;
1709 struct xml_request_s *req;
1710 xmlNodePtr n;
1712 rc = xml_new_request (client, line, XML_CMD_NONE, &req);
1713 if (rc)
1714 return rc;
1716 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1717 if (!rc)
1719 if (n && n->children)
1721 xmlNodePtr tmp = n;
1723 n = xml_find_text_node (n->children);
1724 if (!n || !n->content || !*n->content)
1725 rc = GPG_ERR_NO_DATA;
1726 else
1728 rc = xfer_data (ctx, (char *) n->content, xmlStrlen (n->content));
1729 if (!rc)
1731 xmlChar *expire = xml_attribute_value (tmp,
1732 (xmlChar *)"expire");
1733 if (expire)
1735 time_t now = time (NULL);
1736 time_t e;
1737 char *p;
1739 errno = 0;
1740 e = strtoul ((char *)expire, &p, 10);
1741 if (errno || *p || e == ULONG_MAX || *expire == '-')
1742 log_write (_("invalid expire attribute value: %s"),
1743 expire);
1744 else if (now >= e)
1746 pthread_cleanup_push (xmlFree, expire);
1747 rc = send_status (ctx, STATUS_EXPIRE, "%lu 0", e);
1748 pthread_cleanup_pop (0);
1751 xmlFree (expire);
1756 else
1757 rc = GPG_ERR_NO_DATA;
1760 xml_free_request (req);
1761 return rc;
1764 static gpg_error_t
1765 get_command (assuan_context_t ctx, char *line)
1767 struct client_s *client = assuan_get_pointer (ctx);
1768 gpg_error_t rc;
1769 struct argv_s *args[] = {
1770 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1771 NULL
1774 rc = parse_options (&line, args, client, 1);
1775 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1776 rc = GPG_ERR_SYNTAX;
1777 if (rc)
1778 return send_error (ctx, rc);
1780 if (client->opts & OPT_INQUIRE)
1782 unsigned char *result;
1783 size_t len;
1785 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1786 if (rc)
1787 return send_error (ctx, rc);
1789 pthread_cleanup_push ((void *)xfree, result);
1790 rc = do_get (ctx, (char *)result);
1791 pthread_cleanup_pop (1);
1793 else
1794 rc = do_get (ctx, line);
1796 return send_error (ctx, rc);
1799 static void list_command_free1 (void *arg);
1800 static gpg_error_t
1801 realpath_command (assuan_context_t ctx, char *line)
1803 gpg_error_t rc;
1804 char **realpath = NULL;
1805 struct client_s *client = assuan_get_pointer (ctx);
1806 struct argv_s *args[] = {
1807 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1808 NULL
1811 rc = parse_options (&line, args, client, 1);
1812 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1813 rc = GPG_ERR_SYNTAX;
1814 if (rc)
1815 return send_error (ctx, rc);
1817 if (client->opts & OPT_INQUIRE)
1819 unsigned char *result;
1820 size_t len;
1822 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1823 if (rc)
1824 return send_error (ctx, rc);
1826 pthread_cleanup_push ((void *)xfree, result);
1827 (void)xml_resolve_path (client, client->doc, result, &realpath, &rc);
1828 pthread_cleanup_pop (1);
1830 else
1831 (void)xml_resolve_path (client, client->doc, (unsigned char *)line,
1832 &realpath, &rc);
1834 if (!rc)
1836 char *tmp = strv_join ((char *)"\t", realpath);
1838 strv_free (realpath);
1839 if (!tmp)
1840 return send_error (ctx, GPG_ERR_ENOMEM);
1842 pthread_cleanup_push ((void *)xfree, tmp);
1843 rc = xfer_data (ctx, tmp, strlen (tmp));
1844 pthread_cleanup_pop (1);
1847 return send_error (ctx, rc);
1850 static void
1851 list_command_free1 (void *arg)
1853 if (arg)
1854 string_free ((struct string_s *) arg, 1);
1857 static gpg_error_t
1858 parse_list_opt_recurse (void *data, void *value)
1860 struct client_s *client = data;
1862 (void)value;
1863 client->opts |= OPT_LIST_RECURSE;
1864 return 0;
1867 static gpg_error_t
1868 parse_opt_verbose (void *data, void *value)
1870 struct client_s *client = data;
1872 (void)value;
1873 client->opts |= OPT_VERBOSE;
1874 return 0;
1877 static gpg_error_t
1878 list_path_once (struct client_s *client, char *line,
1879 struct element_list_s *elements, struct string_s *result)
1881 gpg_error_t rc;
1883 rc = xml_create_path_list (client, client->doc, NULL, elements, line, 0);
1884 if (rc == GPG_ERR_ELOOP || rc == GPG_ERR_EACCES)
1885 rc = 0;
1887 if (!rc)
1889 int total = slist_length (elements->list);
1891 if (total)
1893 int i;
1895 for (i = 0; i < total; i++)
1897 char *tmp = slist_nth_data (elements->list, i);
1899 string_append_printf (result, "%s%s", tmp,
1900 i + 1 == total ? "" : "\n");
1903 else
1904 rc = GPG_ERR_NO_DATA;
1907 return rc;
1910 static gpg_error_t
1911 do_list (assuan_context_t ctx, char *line)
1913 struct client_s *client = assuan_get_pointer (ctx);
1914 gpg_error_t rc = GPG_ERR_NO_DATA;
1915 struct element_list_s *elements = NULL;
1917 if (!line || !*line)
1919 struct string_s *str = string_new (NULL);
1920 xmlNodePtr n;
1922 if (!str)
1923 return GPG_ERR_ENOMEM;
1925 pthread_cleanup_push ((void *)list_command_free1, str);
1926 n = xmlDocGetRootElement (client->doc);
1927 for (n = n->children; n; n = n->next)
1929 xmlChar *name;
1931 if (n->type != XML_ELEMENT_NODE)
1932 continue;
1934 name = xmlGetProp (n, (xmlChar *)"_name");
1935 if (!name)
1937 rc = GPG_ERR_ENOMEM;
1938 break;
1941 elements = xcalloc (1, sizeof (struct element_list_s));
1942 if (!elements)
1944 xmlFree (name);
1945 rc = GPG_ERR_ENOMEM;
1946 break;
1949 elements->prefix = string_new (NULL);
1950 if (!elements->prefix)
1952 xmlFree (name);
1953 xml_free_element_list (elements);
1954 rc = GPG_ERR_ENOMEM;
1955 break;
1958 elements->recurse = client->opts & OPT_LIST_RECURSE;
1959 elements->root_only = !elements->recurse;
1960 pthread_cleanup_push ((void *)xml_free_element_list, elements);
1961 rc = list_path_once (client, (char *)name, elements, str);
1962 xmlFree (name);
1963 pthread_cleanup_pop (1);
1964 if (rc)
1965 break;
1967 if (n->next)
1968 string_append (str, "\n");
1971 if (!rc)
1972 rc = xfer_data (ctx, str->str, str->len);
1974 pthread_cleanup_pop (1);
1975 return rc;
1978 elements = xcalloc (1, sizeof (struct element_list_s));
1979 if (!elements)
1980 return GPG_ERR_ENOMEM;
1982 elements->prefix = string_new (NULL);
1983 if (!elements->prefix)
1985 xml_free_element_list (elements);
1986 return GPG_ERR_ENOMEM;
1989 elements->recurse = client->opts & OPT_LIST_RECURSE;
1990 pthread_cleanup_push ((void *)xml_free_element_list, elements);
1991 struct string_s *str = string_new (NULL);
1992 pthread_cleanup_push ((void *)list_command_free1, str);
1993 rc = list_path_once (client, line, elements, str);
1994 if (!rc)
1995 rc = xfer_data (ctx, str->str, str->len);
1997 pthread_cleanup_pop (1);
1998 pthread_cleanup_pop (1);
1999 return rc;
2002 static gpg_error_t
2003 list_command (assuan_context_t ctx, char *line)
2005 struct client_s *client = assuan_get_pointer (ctx);
2006 gpg_error_t rc;
2007 struct argv_s *args[] = {
2008 &(struct argv_s) {"recurse", OPTION_TYPE_NOARG, parse_list_opt_recurse},
2009 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2010 /* These are deprecated but kept for backward compatibility with older
2011 * clients. */
2012 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, NULL},
2013 &(struct argv_s) {"with-target", OPTION_TYPE_NOARG, NULL},
2014 &(struct argv_s) {"all", OPTION_TYPE_NOARG, parse_list_opt_recurse},
2015 &(struct argv_s) {"no-recurse", OPTION_TYPE_NOARG, NULL},
2016 NULL
2019 if (disable_list_and_dump == 1)
2020 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2022 rc = parse_options (&line, args, client, 1);
2023 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2024 rc = GPG_ERR_SYNTAX;
2025 if (rc)
2026 return send_error (ctx, rc);
2028 if (client->opts & OPT_INQUIRE)
2030 unsigned char *result;
2031 size_t len;
2033 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2034 if (rc)
2035 return send_error (ctx, rc);
2037 pthread_cleanup_push ((void *)xfree, result);
2038 rc = do_list (ctx, (char *)result);
2039 pthread_cleanup_pop (1);
2041 else
2042 rc = do_list (ctx, line);
2044 return send_error (ctx, rc);
2047 #define RESUMABLE_ERROR(rc) (rc == GPG_ERR_ELOOP || rc == GPG_ERR_EACCES \
2048 || rc == GPG_ERR_ELEMENT_NOT_FOUND || !rc)
2050 * args[0] - element path
2052 static gpg_error_t
2053 attribute_list (assuan_context_t ctx, char **args)
2055 struct client_s *client = assuan_get_pointer (ctx);
2056 char **attrlist = NULL;
2057 int i = 0;
2058 int target = 0;
2059 xmlAttrPtr a;
2060 xmlNodePtr n, an, r;
2061 char *line;
2062 gpg_error_t rc;
2063 struct xml_request_s *req;
2065 if (!args || !args[0] || !*args[0])
2066 return GPG_ERR_SYNTAX;
2068 rc = xml_new_request (client, args[0], XML_CMD_ATTR_LIST, &req);
2069 if (rc)
2070 return rc;
2072 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2073 xml_free_request (req);
2074 if (rc)
2075 return rc;
2077 again:
2078 for (a = n->properties; a; a = a->next)
2080 char **pa;
2082 if (target && xml_reserved_attribute ((char *)a->name))
2083 continue;
2085 pa = xrealloc (attrlist, (i + 2) * sizeof (char *));
2086 if (!pa)
2088 if (attrlist)
2089 strv_free (attrlist);
2091 log_write ("%s(%i): %s", __FILE__, __LINE__,
2092 pwmd_strerror (GPG_ERR_ENOMEM));
2093 return GPG_ERR_ENOMEM;
2096 attrlist = pa;
2097 an = a->children;
2098 attrlist[i] = str_asprintf ("%s %s", (char *) a->name, an && an->content
2099 ? (char *)an->content : "");
2101 if (!attrlist[i])
2103 strv_free (attrlist);
2104 log_write ("%s(%i): %s", __FILE__, __LINE__,
2105 pwmd_strerror (GPG_ERR_ENOMEM));
2106 return GPG_ERR_ENOMEM;
2109 attrlist[++i] = NULL;
2112 if (!attrlist)
2113 return GPG_ERR_NO_DATA;
2115 if (!target)
2117 r = xml_resolve_path (client, client->doc, (xmlChar *)args[0], NULL, &rc);
2118 if (!RESUMABLE_ERROR (rc))
2120 strv_free (attrlist);
2121 return rc;
2123 else if (!rc && r != n)
2125 target = 1;
2126 n = r;
2127 goto again;
2130 rc = 0;
2133 line = strv_join ("\n", attrlist);
2134 if (!line)
2136 log_write ("%s(%i): %s", __FILE__, __LINE__,
2137 pwmd_strerror (GPG_ERR_ENOMEM));
2138 strv_free (attrlist);
2139 return GPG_ERR_ENOMEM;
2142 pthread_cleanup_push ((void *)xfree, line);
2143 pthread_cleanup_push ((void *)req_free, attrlist);
2144 rc = xfer_data (ctx, line, strlen (line));
2145 pthread_cleanup_pop (1);
2146 pthread_cleanup_pop (1);
2147 return rc;
2151 * args[0] - attribute
2152 * args[1] - element path
2154 static gpg_error_t
2155 attribute_delete (struct client_s *client, char **args)
2157 gpg_error_t rc;
2158 xmlNodePtr n;
2160 if (!args || !args[0] || !*args[0] || !args[1] || !*args[1])
2161 return GPG_ERR_SYNTAX;
2163 if (!strcmp (args[0], "_name") || !strcmp (args[0], "target"))
2164 return GPG_ERR_INV_ATTR;
2166 rc = copy_on_write (client);
2167 if (rc)
2168 return rc;
2170 if (!xml_reserved_attribute (args[0]))
2171 n = xml_resolve_path (client, client->doc, (xmlChar *)args[1], NULL, &rc);
2172 else
2174 struct xml_request_s *req;
2176 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
2177 if (rc)
2178 return rc;
2180 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2181 xml_free_request (req);
2184 if (!rc)
2185 rc = xml_is_element_owner (client, n);
2187 if (!rc)
2188 rc = xml_delete_attribute (client, n, (xmlChar *) args[0]);
2190 return rc;
2194 * Creates the "target" attribute. When other commands encounter an element
2195 * with this attribute they follow the "target" after appending remaining
2196 * elements from the original element path to the target. The exception is the
2197 * ATTR command that operates on the element itself (for reserved attribute
2198 * names) and not the target.
2200 * If the source element path doesn't exist when using 'ATTR SET target', it is
2201 * created, but the destination element path must exist. This is simliar to the
2202 * ls(1) command: ln -s src dst.
2204 * args[0] - source element path
2205 * args[1] - destination element path
2207 static gpg_error_t
2208 set_target_attribute (struct client_s *client, char **args)
2210 struct xml_request_s *req = NULL;
2211 char **src, **dst;
2212 gpg_error_t rc;
2213 xmlNodePtr n;
2215 if (!args || !args[0] || !args[1])
2216 return GPG_ERR_SYNTAX;
2218 src = str_split (args[0], "\t", 0);
2219 if (!src)
2220 return GPG_ERR_SYNTAX;
2222 if (!xml_valid_element_path (src, 0))
2224 strv_free (src);
2225 return GPG_ERR_INV_VALUE;
2228 dst = str_split (args[1], "\t", 0);
2229 if (!dst)
2231 strv_free (src);
2232 return GPG_ERR_SYNTAX;
2235 rc = copy_on_write (client);
2236 if (rc)
2237 goto fail;
2239 // Be sure the destination element path exists. */
2240 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
2241 if (rc)
2242 goto fail;
2244 (void)xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2245 if (rc && rc != GPG_ERR_EACCES)
2246 goto fail;
2248 xml_free_request (req);
2249 req = NULL;
2251 if (!strcmp (args[0], args[1]))
2253 rc = GPG_ERR_EEXIST;
2254 goto fail;
2257 rc = xml_new_request (client, args[0], XML_CMD_ATTR_TARGET, &req);
2258 if (rc)
2259 goto fail;
2261 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2262 if (rc && rc != GPG_ERR_EACCES)
2263 goto fail;
2265 if (!rc)
2267 rc = xml_add_attribute (client, n, "target", args[1]);
2268 if (!rc)
2269 rc = xml_unlink_node (client, n->children);
2272 fail:
2273 strv_free (src);
2274 strv_free (dst);
2275 xml_free_request (req);
2276 return rc;
2280 * args[0] - attribute
2281 * args[1] - element path
2283 static gpg_error_t
2284 attribute_get (assuan_context_t ctx, char **args)
2286 struct client_s *client = assuan_get_pointer (ctx);
2287 xmlNodePtr n;
2288 xmlChar *a;
2289 gpg_error_t rc;
2290 struct xml_request_s *req;
2292 if (!args || !args[0] || !*args[0] || !args[1] || !*args[1])
2293 return GPG_ERR_SYNTAX;
2295 if (!xml_reserved_attribute (args[0]))
2296 n = xml_resolve_path (client, client->doc, (xmlChar *)args[1], NULL, &rc);
2297 else
2299 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
2300 if (rc)
2301 return rc;
2303 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2304 xml_free_request (req);
2307 if (rc)
2308 return rc;
2310 a = xmlGetProp (n, (xmlChar *) args[0]);
2311 if (!a)
2312 return GPG_ERR_NOT_FOUND;
2314 pthread_cleanup_push ((void *)xmlFree, a);
2316 if (*a)
2317 rc = xfer_data (ctx, (char *) a, xmlStrlen (a));
2318 else
2319 rc = GPG_ERR_NO_DATA;
2321 pthread_cleanup_pop (1);
2322 return rc;
2326 * args[0] - attribute
2327 * args[1] - element path
2328 * args[2] - value
2330 static gpg_error_t
2331 attribute_set (struct client_s *client, char **args)
2333 struct xml_request_s *req;
2334 gpg_error_t rc;
2335 xmlNodePtr n;
2337 if (!args || !args[0] || !args[1])
2338 return GPG_ERR_SYNTAX;
2341 * Reserved attribute names.
2343 if (!strcmp (args[0], "_name")) // Use the RENAME command instead
2344 return GPG_ERR_INV_ATTR;
2345 else if (!strcmp (args[0], "target"))
2346 return set_target_attribute (client, args + 1);
2347 else if (!xml_valid_attribute (args[0]))
2348 return GPG_ERR_INV_VALUE;
2350 if (!xml_valid_attribute_value (args[2]))
2351 return GPG_ERR_INV_VALUE;
2353 rc = copy_on_write (client);
2354 if (rc)
2355 return rc;
2357 if (!xml_reserved_attribute (args[0]))
2359 n = xml_resolve_path (client, client->doc, (xmlChar *)args[1], NULL, &rc);
2360 if (!rc)
2362 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
2363 if (!rc)
2365 rc = xml_check_recursion (client, req);
2366 xml_free_request (req);
2370 else
2372 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
2373 if (rc)
2374 return rc;
2376 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2377 xml_free_request (req);
2380 if (!rc)
2381 rc = xml_is_element_owner (client, n);
2383 if (!rc)
2384 rc = xml_add_attribute (client, n, args[0], args[2]);
2386 return rc;
2390 * req[0] - command
2391 * req[1] - attribute name or element path if command is LIST
2392 * req[2] - element path
2393 * req[2] - element path or value
2396 static gpg_error_t
2397 do_attr (assuan_context_t ctx, char *line)
2399 struct client_s *client = assuan_get_pointer (ctx);
2400 gpg_error_t rc = 0;
2401 char **req;
2403 req = str_split (line, " ", 4);
2404 if (!req || !req[0] || !req[1])
2406 strv_free (req);
2407 return GPG_ERR_SYNTAX;
2410 pthread_cleanup_push ((void *)req_free, req);
2412 if (strcasecmp (req[0], "SET") == 0)
2413 rc = attribute_set (client, req + 1);
2414 else if (strcasecmp (req[0], "GET") == 0)
2415 rc = attribute_get (ctx, req + 1);
2416 else if (strcasecmp (req[0], "DELETE") == 0)
2417 rc = attribute_delete (client, req + 1);
2418 else if (strcasecmp (req[0], "LIST") == 0)
2419 rc = attribute_list (ctx, req + 1);
2420 else
2421 rc = GPG_ERR_SYNTAX;
2423 client->flags &= ~(FLAG_ACL_IGNORE|FLAG_ACL_ERROR);
2424 pthread_cleanup_pop (1);
2425 return rc;
2428 static gpg_error_t
2429 attr_command (assuan_context_t ctx, char *line)
2431 struct client_s *client = assuan_get_pointer (ctx);
2432 gpg_error_t rc;
2433 struct argv_s *args[] = {
2434 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2435 NULL
2438 rc = parse_options (&line, args, client, 1);
2439 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2440 rc = GPG_ERR_SYNTAX;
2441 if (rc)
2442 return send_error (ctx, rc);
2444 if (client->opts & OPT_INQUIRE)
2446 unsigned char *result;
2447 size_t len;
2449 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2450 if (rc)
2451 return send_error (ctx, rc);
2453 pthread_cleanup_push ((void *)xfree, result);
2454 rc = do_attr (ctx, (char *)result);
2455 pthread_cleanup_pop (1);
2457 else
2458 rc = do_attr (ctx, line);
2460 return send_error (ctx, rc);
2463 static gpg_error_t
2464 parse_iscached_opt_lock (void *data, void *value)
2466 struct client_s *client = data;
2468 (void) value;
2469 client->opts |= OPT_LOCK;
2470 return 0;
2473 static gpg_error_t
2474 parse_iscached_opt_agent (void *data, void *value)
2476 struct client_s *client = data;
2478 (void) value;
2479 client->opts |= OPT_CACHE_AGENT;
2480 return 0;
2483 static gpg_error_t
2484 parse_iscached_opt_sign (void *data, void *value)
2486 struct client_s *client = data;
2488 (void) value;
2489 client->opts |= OPT_CACHE_SIGN;
2490 return 0;
2493 static gpg_error_t
2494 iscached_command (assuan_context_t ctx, char *line)
2496 struct client_s *client = assuan_get_pointer (ctx);
2497 gpg_error_t rc;
2498 int defer = 0;
2499 struct argv_s *args[] = {
2500 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_iscached_opt_lock},
2501 &(struct argv_s) {"agent", OPTION_TYPE_NOARG, parse_iscached_opt_agent},
2502 &(struct argv_s) {"sign", OPTION_TYPE_NOARG, parse_iscached_opt_sign},
2503 NULL
2506 if (!line || !*line)
2507 return send_error (ctx, GPG_ERR_SYNTAX);
2509 rc = parse_options (&line, args, client, 1);
2510 if (rc)
2511 return send_error (ctx, rc);
2512 else if (!valid_filename (line))
2513 return send_error (ctx, GPG_ERR_INV_VALUE);
2515 if (!(client->flags & FLAG_OPEN)
2516 && ((client->opts & OPT_CACHE_AGENT) || (client->opts & OPT_CACHE_SIGN)))
2517 return send_error (ctx, GPG_ERR_INV_STATE);
2519 rc = cache_iscached (line, &defer, (client->opts & OPT_CACHE_AGENT),
2520 (client->opts & OPT_CACHE_SIGN));
2521 if (!rc && defer)
2522 rc = GPG_ERR_NO_DATA;
2524 if (!rc)
2526 struct cache_data_s *cdata = cache_get_data (line, NULL);
2528 if (cdata)
2530 rc = validate_checksum (client, line, cdata, NULL, NULL);
2531 if (rc == GPG_ERR_CHECKSUM)
2532 rc = GPG_ERR_NO_DATA;
2536 if (client->opts & OPT_LOCK
2537 && (!rc || gpg_err_code (rc) == GPG_ERR_NO_DATA))
2539 gpg_error_t trc = rc;
2541 if (strcmp (line, client->filename))
2542 reset_client (client);
2544 xfree (client->filename);
2545 client->filename = str_dup (line);
2546 rc = do_lock (client, 1);
2547 if (!rc)
2548 rc = trc;
2551 return send_error (ctx, rc);
2554 static gpg_error_t
2555 clearcache_command (assuan_context_t ctx, char *line)
2557 struct client_s *client = assuan_get_pointer (ctx);
2558 gpg_error_t rc = 0, all_rc = 0;
2559 int i;
2560 int t;
2561 int all = 0;
2562 struct client_thread_s *once = NULL;
2563 unsigned count;
2565 cache_lock ();
2566 pthread_cleanup_push (cache_release_mutex, NULL);
2567 count = cache_file_count ();
2568 MUTEX_LOCK (&cn_mutex);
2569 pthread_cleanup_push ((void *)release_mutex_cb, &cn_mutex);
2571 if (!line || !*line)
2572 all = 1;
2574 t = slist_length (cn_thread_list);
2576 for (i = 0; i < t; i++)
2578 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2579 assuan_peercred_t peer;
2581 if (!thd->cl)
2582 continue;
2584 /* Lock each connected clients' file mutex to prevent any other client
2585 * from accessing the cache entry (the file mutex is locked upon
2586 * command startup). The cache for the entry is not cleared if the
2587 * file mutex is locked by another client to prevent this function
2588 * from blocking. Rather, it returns an error.
2590 if (all)
2592 if (thd->cl->filename)
2594 rc = do_validate_peer (ctx, thd->cl->filename, &peer);
2595 /* The current client doesn't have permission to open the other
2596 * filename do to "access" configuration parameter in a filename
2597 * section. Since we are clearning all cache entries the error
2598 * will be returned later during cache_clear(). */
2599 if (rc)
2601 rc = 0;
2602 continue;
2605 else // Idle client without opened file?
2606 continue;
2608 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->filename, -1, 0, -1);
2609 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2611 /* The current client owns the lock. */
2612 if (pthread_equal (pthread_self (), thd->tid))
2613 rc = 0;
2614 else
2616 if (cache_iscached (thd->cl->filename, NULL, 0, 0)
2617 == GPG_ERR_NO_DATA)
2619 rc = 0;
2620 continue;
2623 /* The cache entry will be cleared when the other client
2624 * disconnects and cache_timer_thread() does its thing. */
2625 cache_defer_clear (thd->cl->filename);
2628 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
2630 rc = 0;
2631 continue;
2634 if (!rc)
2636 rc = cache_clear (NULL, thd->cl->filename, 1, 0);
2637 cache_unlock_mutex (thd->cl->filename, 0);
2640 if (rc)
2641 all_rc = rc;
2643 rc = 0;
2645 else
2647 /* A single data filename was specified. Lock only this data file
2648 * mutex and free the cache entry. */
2649 rc = do_validate_peer (ctx, line, &peer);
2650 if (rc == GPG_ERR_FORBIDDEN)
2651 rc = peer_is_invoker (client);
2653 if (rc == GPG_ERR_EACCES)
2654 rc = GPG_ERR_FORBIDDEN;
2656 if (!rc && thd->cl->filename && !strcmp (thd->cl->filename , line))
2658 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->filename, -1, 0, -1);
2659 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2661 /* The current client owns the lock. */
2662 if (pthread_equal (pthread_self (), thd->tid))
2663 rc = 0;
2666 if (!rc)
2668 once = thd;
2669 rc = cache_clear (NULL, thd->cl->filename, 1, 0);
2670 cache_unlock_mutex (thd->cl->filename, 0);
2672 else
2673 cache_defer_clear (thd->cl->filename);
2675 /* Found a client with the opened file. The cache entry has been
2676 * either cleared (self) or defered to be cleared. */
2677 break;
2682 /* Only connected clients' cache entries have been cleared. Now clear any
2683 * remaining cache entries without clients but only if there wasn't an
2684 * error from above since this would defeat the locking check of the
2685 * remaining entries. */
2686 if (all && !all_rc && cache_file_count ())
2688 rc = cache_clear (client, NULL, 1, 0);
2689 if (rc == GPG_ERR_EACCES)
2690 rc = GPG_ERR_FORBIDDEN;
2693 /* No clients are using the specified file. */
2694 else if (!all_rc && !rc && !once)
2695 rc = cache_clear (NULL, line, 1, 0);
2697 /* Release the connection mutex. */
2698 pthread_cleanup_pop (1);
2700 if (!rc || (cache_file_count () && count != cache_file_count ()))
2701 send_status_all (STATUS_CACHE, NULL);
2703 /* Release the cache mutex. */
2704 pthread_cleanup_pop (1);
2706 /* One or more files were locked while clearing all cache entries. */
2707 if (all_rc)
2708 rc = all_rc;
2710 return send_error (ctx, rc);
2713 static gpg_error_t
2714 cachetimeout_command (assuan_context_t ctx, char *line)
2716 struct client_s *client = assuan_get_pointer (ctx);
2717 long timeout;
2718 char **req = str_split (line, " ", 0);
2719 char *p;
2720 gpg_error_t rc = 0;
2721 assuan_peercred_t peer;
2723 if (!req || !*req || !req[1] || !*req[1])
2725 strv_free (req);
2726 return send_error (ctx, GPG_ERR_SYNTAX);
2729 errno = 0;
2730 timeout = strtol (req[1], &p, 10);
2731 if (errno != 0 || *p || timeout < (long)-1)
2733 strv_free (req);
2734 return send_error (ctx, GPG_ERR_SYNTAX);
2737 rc = do_validate_peer (ctx, req[0], &peer);
2738 if (rc == GPG_ERR_FORBIDDEN)
2740 rc = peer_is_invoker (client);
2741 if (rc == GPG_ERR_EACCES)
2742 rc = GPG_ERR_FORBIDDEN;
2745 if (!rc)
2747 rc = cache_set_timeout (req[0], timeout);
2748 if (!rc || gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
2750 rc = 0;
2751 MUTEX_LOCK (&rcfile_mutex);
2752 config_set_long_param (&global_config, req[0], "cache_timeout",
2753 req[1]);
2754 MUTEX_UNLOCK (&rcfile_mutex);
2758 strv_free (req);
2759 return send_error (ctx, rc);
2762 static gpg_error_t
2763 dump_command (assuan_context_t ctx, char *line)
2765 xmlChar *xml;
2766 int len;
2767 struct client_s *client = assuan_get_pointer (ctx);
2768 gpg_error_t rc;
2770 if (disable_list_and_dump == 1)
2771 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2773 if (line && *line)
2774 return send_error (ctx, GPG_ERR_SYNTAX);
2776 rc = peer_is_invoker(client);
2777 if (rc)
2778 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
2780 xmlDocDumpFormatMemory (client->doc, &xml, &len, 1);
2782 if (!xml)
2784 log_write ("%s(%i): %s", __FILE__, __LINE__,
2785 pwmd_strerror (GPG_ERR_ENOMEM));
2786 return send_error (ctx, GPG_ERR_ENOMEM);
2789 pthread_cleanup_push ((void *)xmlFree, xml);
2790 rc = xfer_data (ctx, (char *) xml, len);
2791 pthread_cleanup_pop (1);
2792 return send_error (ctx, rc);
2795 static gpg_error_t
2796 getconfig_command (assuan_context_t ctx, char *line)
2798 struct client_s *client = assuan_get_pointer (ctx);
2799 gpg_error_t rc = 0;
2800 char filename[255] = { 0 }, param[747] = { 0 };
2801 char *p, *tmp = NULL, *fp = client->filename, *paramp = line;
2803 if (!line || !*line)
2804 return send_error (ctx, GPG_ERR_SYNTAX);
2806 if (strchr (line, ' '))
2808 int ret = sscanf (line, " %254[^ ] %746c", filename, param);
2810 if (ret <= 0)
2811 return send_error (ctx, gpg_error_from_syserror());
2812 paramp = param;
2813 fp = filename;
2816 if (fp && !valid_filename (fp))
2817 return send_error (ctx, GPG_ERR_INV_VALUE);
2819 paramp = str_down (paramp);
2820 p = config_get_value (fp ? fp : "global", paramp);
2821 if (!p)
2822 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2824 tmp = expand_homedir (p);
2825 xfree (p);
2826 if (!tmp)
2828 log_write ("%s(%i): %s", __FILE__, __LINE__,
2829 pwmd_strerror (GPG_ERR_ENOMEM));
2830 return send_error (ctx, GPG_ERR_ENOMEM);
2833 p = tmp;
2834 pthread_cleanup_push ((void *)xfree, p);
2835 rc = xfer_data (ctx, p, strlen (p));
2836 pthread_cleanup_pop (1);
2837 return send_error (ctx, rc);
2840 struct xpath_s
2842 xmlXPathContextPtr xp;
2843 xmlXPathObjectPtr result;
2844 xmlBufferPtr buf;
2845 char **req;
2848 static void
2849 xpath_command_free (void *arg)
2851 struct xpath_s *xpath = arg;
2853 if (!xpath)
2854 return;
2856 req_free (xpath->req);
2858 if (xpath->buf)
2859 xmlBufferFree (xpath->buf);
2861 if (xpath->result)
2862 xmlXPathFreeObject (xpath->result);
2864 if (xpath->xp)
2865 xmlXPathFreeContext (xpath->xp);
2868 static gpg_error_t
2869 do_xpath (assuan_context_t ctx, char *line)
2871 gpg_error_t rc;
2872 struct client_s *client = assuan_get_pointer (ctx);
2873 struct xpath_s _x = { 0 };
2874 struct xpath_s *xpath = &_x;
2876 if (!line || !*line)
2877 return GPG_ERR_SYNTAX;
2879 if ((xpath->req = str_split (line, "\t", 2)) == NULL)
2881 if (strv_printf (&xpath->req, "%s", line) == 0)
2882 return GPG_ERR_ENOMEM;
2885 if (xpath->req[1])
2887 rc = copy_on_write (client);
2888 if (rc)
2889 goto fail;
2892 xpath->xp = xmlXPathNewContext (client->doc);
2893 if (!xpath->xp)
2895 rc = GPG_ERR_BAD_DATA;
2896 goto fail;
2899 xpath->result =
2900 xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2901 if (!xpath->result)
2903 rc = GPG_ERR_BAD_DATA;
2904 goto fail;
2907 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2909 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2910 goto fail;
2913 rc = xml_recurse_xpath_nodeset (client, client->doc,
2914 xpath->result->nodesetval,
2915 (xmlChar *) xpath->req[1], &xpath->buf, 0,
2916 NULL);
2917 if (rc)
2918 goto fail;
2919 else if (!xpath->req[1] && !xmlBufferLength (xpath->buf))
2921 rc = GPG_ERR_NO_DATA;
2922 goto fail;
2924 else if (xpath->req[1])
2926 rc = 0;
2927 goto fail;
2930 pthread_cleanup_push ((void *)xpath_command_free, &xpath);
2931 rc = xfer_data (ctx, (char *) xmlBufferContent (xpath->buf),
2932 xmlBufferLength (xpath->buf));
2933 pthread_cleanup_pop (0);
2934 fail:
2935 xpath_command_free (xpath);
2936 return rc;
2939 static gpg_error_t
2940 xpath_command (assuan_context_t ctx, char *line)
2942 struct client_s *client = assuan_get_pointer (ctx);
2943 gpg_error_t rc;
2944 struct argv_s *args[] = {
2945 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2946 NULL
2949 if (disable_list_and_dump == 1)
2950 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2952 rc = peer_is_invoker(client);
2953 if (rc)
2954 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
2956 rc = parse_options (&line, args, client, 1);
2957 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2958 rc = GPG_ERR_SYNTAX;
2959 if (rc)
2960 return send_error (ctx, rc);
2962 if (client->opts & OPT_INQUIRE)
2964 unsigned char *result;
2965 size_t len;
2967 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2968 if (rc)
2969 return send_error (ctx, rc);
2971 pthread_cleanup_push ((void *)xfree, result);
2972 rc = do_xpath (ctx, (char *)result);
2973 pthread_cleanup_pop (1);
2975 else
2976 rc = do_xpath (ctx, line);
2978 return send_error (ctx, rc);
2981 static gpg_error_t
2982 do_xpathattr (assuan_context_t ctx, char *line)
2984 struct client_s *client = assuan_get_pointer (ctx);
2985 gpg_error_t rc;
2986 char **req = NULL;
2987 int cmd = 0; //SET
2988 struct xpath_s _x = { 0 };
2989 struct xpath_s *xpath = &_x;
2991 if (!line || !*line)
2992 return GPG_ERR_SYNTAX;
2994 if ((req = str_split (line, " ", 3)) == NULL)
2995 return GPG_ERR_ENOMEM;
2997 if (!req[0])
2999 rc = GPG_ERR_SYNTAX;
3000 goto fail;
3003 if (!strcasecmp (req[0], "SET"))
3004 cmd = 0;
3005 else if (!strcasecmp (req[0], "DELETE"))
3006 cmd = 1;
3007 else
3009 rc = GPG_ERR_SYNTAX;
3010 goto fail;
3013 if (!req[1] || !req[2])
3015 rc = GPG_ERR_SYNTAX;
3016 goto fail;
3019 if ((xpath->req = str_split (req[2], "\t", 3)) == NULL)
3021 rc = GPG_ERR_ENOMEM;
3022 goto fail;
3025 if (!xpath->req[0] || (!xpath->req[1] && !cmd) || (xpath->req[1] && cmd))
3027 rc = GPG_ERR_SYNTAX;
3028 goto fail;
3031 rc = copy_on_write (client);
3032 if (rc)
3033 goto fail;
3035 xpath->xp = xmlXPathNewContext (client->doc);
3036 if (!xpath->xp)
3038 rc = GPG_ERR_BAD_DATA;
3039 goto fail;
3042 xpath->result = xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
3043 if (!xpath->result)
3045 rc = GPG_ERR_BAD_DATA;
3046 goto fail;
3049 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
3051 rc = GPG_ERR_ELEMENT_NOT_FOUND;
3052 goto fail;
3055 rc = xml_recurse_xpath_nodeset (client, client->doc,
3056 xpath->result->nodesetval,
3057 (xmlChar *) xpath->req[1], &xpath->buf, cmd,
3058 (xmlChar *) req[1]);
3060 fail:
3061 xpath_command_free (xpath);
3062 strv_free (req);
3063 return rc;
3066 /* XPATHATTR SET|DELETE <name> <expression>[<TAB>[value]] */
3067 static gpg_error_t
3068 xpathattr_command (assuan_context_t ctx, char *line)
3070 struct client_s *client = assuan_get_pointer (ctx);
3071 gpg_error_t rc;
3072 struct argv_s *args[] = {
3073 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3074 NULL
3077 if (disable_list_and_dump == 1)
3078 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
3080 rc = peer_is_invoker(client);
3081 if (rc)
3082 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
3084 rc = parse_options (&line, args, client, 1);
3085 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3086 rc = GPG_ERR_SYNTAX;
3087 if (rc)
3088 return send_error (ctx, rc);
3090 if (client->opts & OPT_INQUIRE)
3092 unsigned char *result;
3093 size_t len;
3095 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3096 if (rc)
3097 return send_error (ctx, rc);
3099 pthread_cleanup_push ((void *)xfree, result);
3100 rc = do_xpathattr (ctx, (char *)result);
3101 pthread_cleanup_pop (1);
3103 else
3104 rc = do_xpathattr (ctx, line);
3106 return send_error (ctx, rc);
3109 static gpg_error_t
3110 do_import (struct client_s *client, const char *root_element,
3111 unsigned char *content)
3113 xmlDocPtr doc = NULL;
3114 xmlNodePtr n = NULL, root;
3115 gpg_error_t rc = 0;
3116 struct string_s *str = NULL, *tstr = NULL;
3117 struct xml_request_s *req = NULL;
3119 if (!content || !*content)
3120 return GPG_ERR_SYNTAX;
3122 if (root_element)
3124 rc = xml_new_request (client, root_element, XML_CMD_STORE, &req);
3125 if (rc)
3127 xfree (content);
3128 return rc;
3131 if (!xml_valid_element_path (req->args, 0))
3133 xml_free_request (req);
3134 xfree (content);
3135 return GPG_ERR_INV_VALUE;
3139 str = string_new_content ((char *)content);
3140 tstr = string_prepend (str, "<pwmd>");
3141 if (tstr)
3143 str = tstr;
3144 tstr = string_append (str, "</pwmd>");
3145 if (!tstr)
3146 rc = GPG_ERR_ENOMEM;
3148 else
3149 rc = GPG_ERR_ENOMEM;
3151 if (rc)
3152 goto fail;
3154 doc = xmlReadDoc ((xmlChar *) str->str, NULL, "UTF-8", XML_PARSE_NOBLANKS);
3155 string_free (str, 1);
3156 if (!doc)
3158 rc = GPG_ERR_BAD_DATA;
3159 goto fail;
3162 root = xmlDocGetRootElement (doc);
3163 root = root->children;
3164 if (root->type != XML_ELEMENT_NODE)
3166 rc = GPG_ERR_BAD_DATA;
3167 goto fail;
3170 rc = xml_validate_import (client, root);
3171 if (rc)
3172 goto fail;
3174 if (req)
3176 /* Create the new specified root element path, if needed. */
3177 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc),
3178 &rc);
3179 if (rc)
3180 goto fail;
3182 /* Overwrite the children of the specified root element path. */
3183 (void)xml_unlink_node (client, n->children);
3184 n->children = NULL;
3186 else
3187 n = xmlDocGetRootElement (client->doc);
3189 if (n)
3191 xmlNodePtr copy;
3192 xmlChar *name = xml_attribute_value (root, (xmlChar *)"_name");
3194 if (!name)
3195 rc = GPG_ERR_BAD_DATA;
3196 else if (!req)
3198 /* No --root argument passed. Overwrite the current documents' root
3199 * element matching the root element of the imported data. */
3200 xml_free_request (req);
3201 req = NULL;
3202 rc = xml_new_request (client, (char *)name, XML_CMD_DELETE, &req);
3203 xmlFree (name);
3204 if (!rc)
3206 xmlNodePtr tmp;
3208 tmp = xml_find_elements (client, req,
3209 xmlDocGetRootElement (req->doc), &rc);
3210 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3211 goto fail;
3213 if (!rc)
3214 (void)xml_unlink_node (client, tmp);
3216 rc = 0;
3220 if (!rc)
3222 copy = xmlCopyNodeList (root);
3223 if (!copy)
3224 rc = GPG_ERR_ENOMEM;
3225 else
3227 n = xmlAddChildList (n, copy);
3228 if (!n)
3229 rc = GPG_ERR_ENOMEM;
3234 if (!rc && n && n->parent)
3235 rc = xml_update_element_mtime (client, n->parent);
3237 fail:
3238 xml_free_request (req);
3240 if (doc)
3241 xmlFreeDoc (doc);
3243 return rc;
3246 static gpg_error_t
3247 parse_import_opt_root (void *data, void *value)
3249 struct client_s *client = data;
3251 client->import_root = str_dup (value);
3252 return client->import_root ? 0 : GPG_ERR_ENOMEM;
3255 static gpg_error_t
3256 import_command (assuan_context_t ctx, char *line)
3258 gpg_error_t rc;
3259 struct client_s *client = assuan_get_pointer (ctx);
3260 unsigned char *result;
3261 size_t len;
3262 struct argv_s *args[] = {
3263 &(struct argv_s) {"root", OPTION_TYPE_ARG, parse_import_opt_root},
3264 NULL
3267 xfree (client->import_root);
3268 client->import_root = NULL;
3269 rc = parse_options (&line, args, client, 0);
3270 if (rc)
3271 return send_error (ctx, rc);
3273 rc = copy_on_write (client);
3274 if (rc)
3275 return send_error (ctx, rc);
3277 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3278 if (rc)
3280 xfree (client->import_root);
3281 client->import_root = NULL;
3282 return send_error (ctx, rc);
3285 rc = do_import (client, client->import_root, result);
3286 xfree (client->import_root);
3287 client->import_root = NULL;
3288 return send_error (ctx, rc);
3291 static gpg_error_t
3292 do_lock (struct client_s *client, int add)
3294 gpg_error_t rc = lock_file_mutex (client, add);
3296 if (!rc)
3297 client->flags |= FLAG_LOCK_CMD;
3299 return rc;
3302 static gpg_error_t
3303 lock_command (assuan_context_t ctx, char *line)
3305 struct client_s *client = assuan_get_pointer (ctx);
3306 gpg_error_t rc;
3308 if (line && *line)
3309 return send_error (ctx, GPG_ERR_SYNTAX);
3311 rc = do_lock (client, 0);
3312 return send_error (ctx, rc);
3315 static gpg_error_t
3316 unlock_command (assuan_context_t ctx, char *line)
3318 struct client_s *client = assuan_get_pointer (ctx);
3319 gpg_error_t rc;
3321 if (line && *line)
3322 return send_error (ctx, GPG_ERR_SYNTAX);
3324 rc = unlock_file_mutex (client, 0);
3325 return send_error (ctx, rc);
3328 static void
3329 set_env (const char *name, char *buf, size_t size, const char *value)
3331 MUTEX_LOCK (&rcfile_mutex);
3332 if (!value || !*value)
3334 unsetenv (name);
3335 buf[0] = 0;
3337 else if (!buf[0] || strcmp (buf, value))
3339 snprintf (buf, size, "%s=%s", name, value);
3340 putenv (buf);
3343 MUTEX_UNLOCK (&rcfile_mutex);
3346 static gpg_error_t
3347 option_command (assuan_context_t ctx, char *line)
3349 struct client_s *client = assuan_get_pointer (ctx);
3350 gpg_error_t rc = 0;
3351 char namebuf[255] = { 0 };
3352 char *name = namebuf;
3353 char *value = NULL, *p, *tmp = NULL;
3355 p = strchr (line, '=');
3356 if (!p)
3358 strncpy (namebuf, line, sizeof(namebuf));
3359 namebuf[sizeof(namebuf)-1] = 0;
3361 else
3363 strncpy (namebuf, line, strlen (line)-strlen (p));
3364 namebuf[sizeof(namebuf)-1] = 0;
3365 value = p+1;
3368 log_write2 ("OPTION name='%s' value='%s'", name, value);
3370 if (strcasecmp (name, (char *) "lock-timeout") == 0)
3372 long n = 0;
3374 if (value)
3376 n = strtol (value, &tmp, 10);
3377 if (tmp && *tmp)
3378 return send_error (ctx, GPG_ERR_INV_VALUE);
3381 client->lock_timeout = n;
3383 else if (strcasecmp (name, (char *) "client-state") == 0)
3385 long n = 0;
3387 MUTEX_LOCK (&client->thd->status_mutex);
3388 if (value)
3390 n = strtol (value, &tmp, 10);
3391 if ((tmp && *tmp) || (n < 0 || n > 1))
3393 MUTEX_UNLOCK (&client->thd->status_mutex);
3394 return send_error (ctx, GPG_ERR_INV_VALUE);
3396 client->client_state = n;
3398 else
3399 client->client_state = 0;
3400 MUTEX_UNLOCK (&client->thd->status_mutex);
3402 else if (strcasecmp (name, (char *) "NAME") == 0)
3404 if (value && strchr (value, ' '))
3405 rc = GPG_ERR_INV_VALUE;
3406 else
3408 MUTEX_LOCK (&cn_mutex);
3409 tmp = pthread_getspecific (thread_name_key);
3410 pthread_setspecific (thread_name_key, NULL);
3411 xfree (tmp);
3412 xfree (client->thd->name);
3413 client->thd->name = NULL;
3414 if (value && *value)
3416 pthread_setspecific (thread_name_key, str_dup (value));
3417 client->thd->name = str_dup (value);
3419 MUTEX_UNLOCK (&cn_mutex);
3422 else if (strcasecmp (name, "disable-pinentry") == 0)
3424 int n = 1;
3426 if (value && *value)
3428 n = (int) strtol (value, &tmp, 10);
3429 if (*tmp || n < 0 || n > 1)
3430 return send_error (ctx, GPG_ERR_INV_VALUE);
3433 if (n)
3434 client->flags |= FLAG_NO_PINENTRY;
3435 else
3436 client->flags &= ~FLAG_NO_PINENTRY;
3438 else if (strcasecmp (name, "ttyname") == 0)
3439 set_env ("GPG_TTY", env_gpg_tty, sizeof (env_gpg_tty), value);
3440 else if (strcasecmp (name, "ttytype") == 0)
3441 set_env ("TERM", env_term, sizeof (env_term), value);
3442 else if (strcasecmp (name, "display") == 0)
3443 set_env ("DISPLAY", env_display, sizeof (env_display), value);
3444 else if (strcasecmp (name, "lc_messages") == 0)
3447 else if (strcasecmp (name, "lc_ctype") == 0)
3450 else if (strcasecmp (name, "desc") == 0)
3453 else if (strcasecmp (name, "pinentry-timeout") == 0)
3456 else
3457 rc = GPG_ERR_UNKNOWN_OPTION;
3459 return send_error (ctx, rc);
3462 static gpg_error_t
3463 do_rename (assuan_context_t ctx, char *line)
3465 struct client_s *client = assuan_get_pointer (ctx);
3466 char **args, *p;
3467 xmlNodePtr src, dst;
3468 struct string_s *str = NULL, *tstr;
3469 struct xml_request_s *req;
3470 gpg_error_t rc;
3472 args = str_split (line, " ", 0);
3473 if (!args || strv_length (args) != 2)
3475 strv_free (args);
3476 return GPG_ERR_SYNTAX;
3479 if (!xml_valid_element ((xmlChar *) args[1]))
3481 strv_free (args);
3482 return GPG_ERR_INV_VALUE;
3485 rc = xml_new_request (client, args[0], XML_CMD_RENAME, &req);
3486 if (rc)
3488 strv_free (args);
3489 return rc;
3492 src = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3493 if (rc)
3494 goto fail;
3496 rc = xml_is_element_owner (client, src);
3497 if (rc)
3498 goto fail;
3500 xmlChar *a = xmlGetProp (src, (xmlChar *) "_name");
3501 if (!a)
3503 rc = GPG_ERR_ENOMEM;
3504 goto fail;
3507 /* To prevent unwanted effects:
3509 * <element _name="a"><element _name="b"/></element>
3511 * RENAME a<TAB>b b
3513 if (xmlStrEqual (a, (xmlChar *) args[1]))
3515 xmlFree (a);
3516 rc = GPG_ERR_EEXIST;
3517 goto fail;
3520 xmlFree (a);
3521 str = string_new (args[0]);
3522 if (!str)
3524 rc = GPG_ERR_ENOMEM;
3525 goto fail;
3528 p = strrchr (str->str, '\t');
3529 if (p)
3530 tstr = string_truncate (str, strlen (str->str)-strlen (p));
3531 else
3532 tstr = string_truncate (str, 0);
3534 if (!tstr)
3536 string_free (str, 1);
3537 rc = GPG_ERR_ENOMEM;
3538 goto fail;
3541 str = tstr;
3542 tstr = string_append_printf (str, "%s%s", str->len ? "\t" : "", args[1]);
3543 if (!tstr)
3545 string_free (str, 1);
3546 rc = GPG_ERR_ENOMEM;
3547 goto fail;
3550 str = tstr;
3551 xml_free_request (req);
3552 rc = xml_new_request (client, str->str, XML_CMD_RENAME, &req);
3553 string_free (str, 1);
3554 if (rc)
3556 req = NULL;
3557 goto fail;
3560 dst = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3561 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3562 goto fail;
3564 rc = 0;
3566 /* Target may exist:
3568 * <element _name="a"/>
3569 * <element _name="b" target="a"/>
3571 * RENAME b a
3573 if (src == dst)
3575 rc = GPG_ERR_EEXIST;
3576 goto fail;
3579 if (dst)
3581 rc = xml_is_element_owner (client, dst);
3582 if (rc)
3583 goto fail;
3585 rc = xml_add_attribute (client, src, "_name", args[1]);
3586 if (!rc)
3587 xml_unlink_node (client, dst);
3589 else
3590 rc = xml_add_attribute (client, src, "_name", args[1]);
3592 fail:
3593 xml_free_request (req);
3594 strv_free (args);
3595 return rc;
3598 static gpg_error_t
3599 rename_command (assuan_context_t ctx, char *line)
3601 struct client_s *client = assuan_get_pointer (ctx);
3602 gpg_error_t rc;
3603 struct argv_s *args[] = {
3604 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3605 NULL
3608 rc = parse_options (&line, args, client, 1);
3609 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3610 rc = GPG_ERR_SYNTAX;
3611 if (rc)
3612 return send_error (ctx, rc);
3614 rc = copy_on_write (client);
3615 if (rc)
3616 return send_error (ctx, rc);
3618 if (client->opts & OPT_INQUIRE)
3620 unsigned char *result;
3621 size_t len;
3623 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3624 if (rc)
3625 return send_error (ctx, rc);
3627 pthread_cleanup_push ((void *)xfree, result);
3628 rc = do_rename (ctx, (char *)result);
3629 pthread_cleanup_pop (1);
3631 else
3632 rc = do_rename (ctx, line);
3634 return send_error (ctx, rc);
3637 static gpg_error_t
3638 do_copy (assuan_context_t ctx, char *line)
3640 struct client_s *client = assuan_get_pointer (ctx);
3641 char **args, **targs;
3642 xmlNodePtr src, dst, tree = NULL;
3643 struct xml_request_s *req;
3644 gpg_error_t rc;
3646 args = str_split (line, " ", 0);
3647 if (!args || strv_length (args) != 2)
3649 strv_free (args);
3650 return GPG_ERR_SYNTAX;
3653 targs = str_split (args[1], "\t", 0);
3654 if (!targs)
3656 strv_free (args);
3657 return GPG_ERR_SYNTAX;
3660 if (!xml_valid_element_path (targs, 0))
3662 strv_free (args);
3663 strv_free (targs);
3664 return GPG_ERR_INV_VALUE;
3666 strv_free (targs);
3668 rc = xml_new_request (client, args[0], XML_CMD_NONE, &req);
3669 if (rc)
3671 strv_free (args);
3672 return rc;
3675 src = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3676 if (rc)
3677 goto fail;
3679 tree = xmlCopyNodeList (src);
3680 if (!tree)
3682 rc = GPG_ERR_ENOMEM;
3683 goto fail;
3686 xml_free_request (req);
3687 /* Create the destination element path if it does not exist. */
3688 rc = xml_new_request (client, args[1], XML_CMD_STORE, &req);
3689 if (rc)
3691 req = NULL;
3692 goto fail;
3695 dst = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3696 if (rc)
3697 goto fail;
3699 rc = xml_is_element_owner (client, dst);
3700 if (rc)
3701 goto fail;
3703 rc = xml_validate_target (client, req->doc, args[1], src);
3704 if (rc || src == dst)
3706 rc = rc ? rc : GPG_ERR_EEXIST;
3707 goto fail;
3710 /* Merge any attributes from the src node to the initial dst node. */
3711 for (xmlAttrPtr attr = tree->properties; attr; attr = attr->next)
3713 if (xmlStrEqual (attr->name, (xmlChar *) "_name"))
3714 continue;
3716 xmlAttrPtr a = xmlHasProp (dst, attr->name);
3717 if (a)
3718 xmlRemoveProp (a);
3720 xmlChar *tmp = xmlNodeGetContent (attr->children);
3721 xmlNewProp (dst, attr->name, tmp);
3722 xmlFree (tmp);
3723 /* Create the default attributes. */
3724 rc = xml_add_attribute (client, dst, NULL, NULL);
3727 xmlNodePtr n = dst->children;
3728 (void)xml_unlink_node (client, n);
3729 dst->children = NULL;
3731 if (tree->children)
3733 n = xmlCopyNodeList (tree->children);
3734 if (!n)
3736 rc = GPG_ERR_ENOMEM;
3737 goto fail;
3740 n = xmlAddChildList (dst, n);
3741 if (!n)
3743 rc = GPG_ERR_ENOMEM;
3744 goto fail;
3747 rc = xml_update_element_mtime (client, xmlDocGetRootElement (client->doc)
3748 == dst->parent ? dst : dst->parent);
3751 fail:
3752 if (tree)
3753 (void)xml_unlink_node (client, tree);
3755 xml_free_request (req);
3756 strv_free (args);
3757 return rc;
3760 static gpg_error_t
3761 copy_command (assuan_context_t ctx, char *line)
3763 struct client_s *client = assuan_get_pointer (ctx);
3764 gpg_error_t rc;
3765 struct argv_s *args[] = {
3766 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3767 NULL
3770 rc = parse_options (&line, args, client, 1);
3771 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3772 rc = GPG_ERR_SYNTAX;
3773 if (rc)
3774 return send_error (ctx, rc);
3776 rc = copy_on_write (client);
3777 if (rc)
3778 return send_error (ctx, rc);
3780 if (client->opts & OPT_INQUIRE)
3782 unsigned char *result;
3783 size_t len;
3785 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3786 if (rc)
3787 return send_error (ctx, rc);
3789 pthread_cleanup_push ((void *)xfree, result);
3790 rc = do_copy (ctx, (char *)result);
3791 pthread_cleanup_pop (1);
3793 else
3794 rc = do_copy (ctx, line);
3796 return send_error (ctx, rc);
3799 static gpg_error_t
3800 do_move (assuan_context_t ctx, char *line)
3802 struct client_s *client = assuan_get_pointer (ctx);
3803 char **args;
3804 xmlNodePtr src, dst;
3805 struct xml_request_s *req;
3806 gpg_error_t rc;
3808 args = str_split (line, " ", 0);
3809 if (!args || strv_length (args) != 2)
3811 strv_free (args);
3812 return GPG_ERR_SYNTAX;
3815 if (*args[1])
3817 char **targs = str_split (args[1], "\t", 0);
3818 if (!targs)
3820 strv_free (args);
3821 return GPG_ERR_ENOMEM;
3824 if (!xml_valid_element_path (targs, 0))
3826 strv_free (targs);
3827 strv_free (args);
3828 return GPG_ERR_INV_VALUE;
3831 strv_free (targs);
3834 rc = xml_new_request (client, args[0], XML_CMD_MOVE, &req);
3835 if (rc)
3837 strv_free (args);
3838 return rc;
3841 src = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3842 if (rc)
3843 goto fail;
3845 rc = xml_is_element_owner (client, src);
3846 if (rc)
3847 goto fail;
3849 xml_free_request (req);
3850 req = NULL;
3851 if (*args[1])
3853 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
3854 if (rc)
3855 goto fail;
3857 dst = xml_find_elements (client, req, xmlDocGetRootElement (req->doc),
3858 &rc);
3860 else
3861 dst = xmlDocGetRootElement (client->doc);
3863 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3864 goto fail;
3866 rc = 0;
3868 for (xmlNodePtr n = dst; n; n = n->parent)
3870 if (n == src)
3872 rc = GPG_ERR_EEXIST;
3873 goto fail;
3877 if (dst)
3879 xmlChar *a = xml_attribute_value (src, (xmlChar *) "_name");
3880 xmlNodePtr dup = xml_find_element (client, dst->children, (char *) a, &rc);
3882 xmlFree (a);
3883 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3884 goto fail;
3886 rc = 0;
3888 if (dup)
3890 if (dup == src)
3892 rc = GPG_ERR_EEXIST;
3893 goto fail;
3896 if (dst == xmlDocGetRootElement (client->doc))
3898 xmlNodePtr n = src;
3899 int match = 0;
3901 while (n->parent && n->parent != dst)
3902 n = n->parent;
3904 a = xml_attribute_value (n, (xmlChar *) "_name");
3905 xmlChar *b = xml_attribute_value (src, (xmlChar *) "_name");
3907 if (xmlStrEqual (a, b))
3909 match = 1;
3910 xmlUnlinkNode (src);
3911 (void)xml_unlink_node (client, n);
3914 xmlFree (a);
3915 xmlFree (b);
3917 if (!match)
3918 (void)xml_unlink_node (client, dup);
3920 else
3921 xmlUnlinkNode (dup);
3925 if (!dst && req && req->args && *req->args)
3927 struct xml_request_s *nreq = NULL;
3928 xmlChar *name = xml_attribute_value (src, (xmlChar *) "_name");
3930 if (src->parent == xmlDocGetRootElement (client->doc)
3931 && !strcmp ((char *) name, *req->args))
3933 xmlFree (name);
3934 rc = GPG_ERR_EEXIST;
3935 goto fail;
3938 xmlFree (name);
3939 rc = xml_new_request (client, args[1], XML_CMD_STORE, &nreq);
3940 if (!rc)
3942 dst = xml_find_elements (client, nreq,
3943 xmlDocGetRootElement (nreq->doc), &rc);
3944 xml_free_request (nreq);
3947 if (rc)
3948 goto fail;
3951 xml_update_element_mtime (client, src->parent);
3952 xmlUnlinkNode (src);
3954 dst = xmlAddChildList (dst, src);
3955 if (!dst)
3956 rc = GPG_ERR_ENOMEM;
3957 else
3958 xml_update_element_mtime (client, dst->parent);
3960 fail:
3961 xml_free_request (req);
3962 strv_free (args);
3963 return rc;
3966 static gpg_error_t
3967 move_command (assuan_context_t ctx, char *line)
3969 struct client_s *client = assuan_get_pointer (ctx);
3970 gpg_error_t rc;
3971 struct argv_s *args[] = {
3972 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3973 NULL
3976 rc = parse_options (&line, args, client, 1);
3977 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3978 rc = GPG_ERR_SYNTAX;
3979 if (rc)
3980 return send_error (ctx, rc);
3982 rc = copy_on_write (client);
3983 if (rc)
3984 return send_error (ctx, rc);
3986 if (client->opts & OPT_INQUIRE)
3988 unsigned char *result;
3989 size_t len;
3991 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3992 if (rc)
3993 return send_error (ctx, rc);
3995 pthread_cleanup_push ((void *)xfree, result);
3996 rc = do_move (ctx, (char *)result);
3997 pthread_cleanup_pop (1);
3999 else
4000 rc = do_move (ctx, line);
4002 return send_error (ctx, rc);
4005 static int
4006 sort_files (const void *arg1, const void *arg2)
4008 char *const *a = arg1;
4009 char *const *b = arg2;
4011 return strcmp (*a, *b);
4014 static gpg_error_t
4015 ls_command (assuan_context_t ctx, char *line)
4017 gpg_error_t rc;
4018 char *tmp;
4019 char *dir;
4020 DIR *d;
4021 char *list = NULL;
4022 char **v = NULL;
4023 #ifdef HAVE_READDIR_R
4024 size_t len;
4025 struct dirent *cur = NULL, *p;
4026 #else
4027 struct dirent *cur = NULL;
4028 #endif
4030 if (line && *line)
4031 return send_error (ctx, GPG_ERR_SYNTAX);
4033 tmp = str_asprintf ("%s/data", homedir);
4034 dir = expand_homedir (tmp);
4035 xfree (tmp);
4036 if (!dir)
4037 return send_error (ctx, GPG_ERR_ENOMEM);
4039 d = opendir (dir);
4040 rc = gpg_error_from_errno (errno);
4042 if (!d)
4044 xfree (dir);
4045 return send_error (ctx, rc);
4048 #ifdef HAVE_READDIR_R
4049 len = offsetof (struct dirent, d_name) + pathconf (dir, _PC_NAME_MAX) + 1;
4050 p = xmalloc (len);
4051 if (!p)
4053 xfree (dir);
4054 closedir (d);
4055 return send_error (ctx, GPG_ERR_ENOMEM);
4057 pthread_cleanup_push (xfree, p);
4058 #endif
4060 pthread_cleanup_push ((void *)closedir, d);
4061 xfree (dir);
4062 rc = 0;
4064 #ifdef HAVE_READDIR_R
4065 while (!readdir_r (d, p, &cur) && cur)
4066 #else
4067 while ((cur = readdir (d)))
4068 #endif
4070 char **vtmp;
4072 pthread_cleanup_push ((void *)strv_free, v);
4073 rc = open_check_file (cur->d_name, NULL, NULL, 1);
4074 if (rc)
4075 continue;
4077 tmp = str_dup (cur->d_name);
4078 if (!tmp)
4080 rc = GPG_ERR_ENOMEM;
4081 break;
4084 vtmp = strv_cat (v, tmp);
4085 if (!vtmp)
4087 xfree (tmp);
4088 rc = GPG_ERR_ENOMEM;
4089 break;
4092 v = vtmp;
4093 pthread_cleanup_pop (0);
4096 pthread_cleanup_pop (1); // closedir (d)
4097 #ifdef HAVE_READDIR_R
4098 pthread_cleanup_pop (1); // xfree (p)
4099 #endif
4101 if (rc && rc != GPG_ERR_ENODEV)
4103 strv_free (v);
4104 return send_error (ctx, rc);
4107 rc = 0;
4108 if (v && *v)
4110 unsigned n, t = strv_length (v);
4112 qsort (v, t, sizeof (char **), sort_files);
4114 for (n = 0; n < t; n++)
4116 tmp = str_asprintf ("%s%s\n", list ? list : "", v[n]);
4117 if (!tmp)
4119 xfree (list);
4120 rc = GPG_ERR_ENOMEM;
4121 break;
4124 xfree (list);
4125 list = tmp;
4129 strv_free (v);
4130 if (!list)
4131 return send_error (ctx, GPG_ERR_NO_DATA);
4133 list[strlen (list) - 1] = 0;
4134 pthread_cleanup_push (xfree, list);
4135 rc = xfer_data (ctx, list, strlen (list));
4136 pthread_cleanup_pop (1);
4137 return send_error (ctx, rc);
4140 static gpg_error_t
4141 bye_notify (assuan_context_t ctx, char *line)
4143 struct client_s *cl = assuan_get_pointer (ctx);
4144 gpg_error_t ret = 0;
4146 (void)line;
4147 update_client_state (cl, CLIENT_STATE_DISCON);
4149 #ifdef WITH_GNUTLS
4150 cl->disco = 1;
4151 if (cl->thd->remote)
4153 int rc;
4157 struct timeval tv = { 0, 50000 };
4159 rc = gnutls_bye (cl->thd->tls->ses, GNUTLS_SHUT_RDWR);
4160 if (rc == GNUTLS_E_AGAIN)
4161 select (0, NULL, NULL, NULL, &tv);
4163 while (rc == GNUTLS_E_AGAIN);
4165 #endif
4167 /* This will let assuan_process_next() return. */
4168 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
4170 cl->last_rc = gpg_error_from_errno (errno);
4171 ret = cl->last_rc;
4174 cl->last_rc = 0; // BYE command result
4175 return ret;
4178 static gpg_error_t
4179 reset_notify (assuan_context_t ctx, char *line)
4181 struct client_s *client = assuan_get_pointer (ctx);
4183 (void)line;
4184 if (client)
4185 reset_client (client);
4187 return 0;
4191 * This is called before every Assuan command.
4193 static gpg_error_t
4194 command_startup (assuan_context_t ctx, const char *name)
4196 struct client_s *client = assuan_get_pointer (ctx);
4197 gpg_error_t rc;
4198 struct command_table_s *cmd = NULL;
4200 log_write2 ("command='%s'", name);
4201 client->last_rc = client->opts = 0;
4203 for (int i = 0; command_table[i]; i++)
4205 if (!strcasecmp (name, command_table[i]->name))
4207 if (command_table[i]->ignore_startup)
4208 return 0;
4209 cmd = command_table[i];
4210 break;
4214 if (!cmd)
4215 return GPG_ERR_UNKNOWN_COMMAND;
4217 client->last_rc = rc = gpg_error (file_modified (client, cmd));
4218 if (!rc)
4219 update_client_state (client, CLIENT_STATE_COMMAND);
4221 return rc;
4225 * This is called after every Assuan command.
4227 static void
4228 command_finalize (assuan_context_t ctx, gpg_error_t rc)
4230 struct client_s *client = assuan_get_pointer (ctx);
4232 if (!(client->flags & FLAG_LOCK_CMD))
4233 unlock_file_mutex (client, 0);
4235 unlock_flock (&client->flock_fd);
4236 log_write2 (_("command completed: rc=%u"), rc ? rc : client->last_rc);
4237 client->last_rc = gpg_error (GPG_ERR_UNKNOWN_COMMAND);
4238 #ifdef WITH_GNUTLS
4239 client->thd->buffer_timeout = client->thd->last_buffer_size = 0;
4240 #endif
4241 if (client->thd->state != CLIENT_STATE_DISCON)
4242 update_client_state (client, CLIENT_STATE_IDLE);
4245 static gpg_error_t
4246 parse_help_opt_html (void *data, void *value)
4248 struct client_s *client = data;
4250 (void) value;
4251 client->opts |= OPT_HTML;
4252 return 0;
4255 static gpg_error_t
4256 help_command (assuan_context_t ctx, char *line)
4258 gpg_error_t rc;
4259 int i;
4260 struct client_s *client = assuan_get_pointer (ctx);
4261 struct argv_s *args[] = {
4262 &(struct argv_s) {"html", OPTION_TYPE_NOARG, parse_help_opt_html},
4263 NULL
4266 rc = parse_options (&line, args, client, 1);
4267 if (rc)
4268 return send_error (ctx, rc);
4270 if (!line || !*line)
4272 char *tmp;
4273 char *help = str_dup (_("Usage: HELP [--html] [<COMMAND>]\n"
4274 "For commands that take an element path as an argument, each element is "
4275 "separated with an ASCII @key{TAB} character (ASCII 0x09)."
4276 "@*@*COMMANDS:"));
4278 for (i = 0; command_table[i]; i++)
4280 if (!command_table[i]->help)
4281 continue;
4283 /* @npxref{} won't put a "See " or "see " in front of the command.
4284 * It's not a texinfo command but needed for --html. */
4285 tmp = str_asprintf ("%s %s%s%s", help,
4286 client->opts & OPT_HTML ? "@npxref{" : "",
4287 command_table[i]->name,
4288 client->opts & OPT_HTML ? "}" : "");
4289 xfree (help);
4290 help = tmp;
4293 tmp = strip_texi_and_wrap (help, client->opts & OPT_HTML);
4294 xfree (help);
4295 pthread_cleanup_push ((void *)xfree, tmp);
4296 rc = xfer_data (ctx, tmp, strlen (tmp));
4297 pthread_cleanup_pop (1);
4298 return send_error (ctx, rc);
4301 for (i = 0; command_table[i]; i++)
4303 if (!strcasecmp (line, command_table[i]->name))
4305 char *help, *tmp;
4307 if (!command_table[i]->help)
4308 break;
4310 help = strip_texi_and_wrap (command_table[i]->help,
4311 client->opts & OPT_HTML);
4312 tmp = str_asprintf ("%s%s",
4313 (client->opts & OPT_HTML) ? "" : _("Usage: "),
4314 help);
4315 xfree (help);
4316 pthread_cleanup_push ((void *)xfree, tmp);
4317 rc = xfer_data (ctx, tmp, strlen (tmp));
4318 pthread_cleanup_pop (1);
4319 return send_error (ctx, rc);
4323 return send_error (ctx, GPG_ERR_INV_NAME);
4326 static void
4327 new_command (const char *name, int ignore, int unlock, int flock_type,
4328 gpg_error_t (*handler) (assuan_context_t, char *),
4329 const char *help)
4331 int i = 0;
4332 struct command_table_s **tmp;
4334 if (command_table)
4335 for (i = 0; command_table[i]; i++);
4337 tmp = xrealloc (command_table, (i + 2) * sizeof (struct command_table_s *));
4338 assert (tmp);
4339 command_table = tmp;
4340 command_table[i] = xcalloc (1, sizeof (struct command_table_s));
4341 command_table[i]->name = name;
4342 command_table[i]->handler = handler;
4343 command_table[i]->ignore_startup = ignore;
4344 command_table[i]->unlock = unlock;
4345 command_table[i]->flock_type = flock_type;
4346 command_table[i++]->help = help;
4347 command_table[i] = NULL;
4350 void
4351 deinit_commands ()
4353 int i;
4355 for (i = 0; command_table[i]; i++)
4356 xfree (command_table[i]);
4358 xfree (command_table);
4361 static int
4362 sort_commands (const void *arg1, const void *arg2)
4364 struct command_table_s *const *a = arg1;
4365 struct command_table_s *const *b = arg2;
4367 if (!*a || !*b)
4368 return 0;
4369 else if (*a && !*b)
4370 return 1;
4371 else if (!*a && *b)
4372 return -1;
4374 return strcmp ((*a)->name, (*b)->name);
4377 static gpg_error_t
4378 passwd_command (assuan_context_t ctx, char *line)
4380 struct client_s *client = assuan_get_pointer (ctx);
4381 gpg_error_t rc;
4383 (void)line;
4384 rc = peer_is_invoker (client);
4385 if (rc)
4386 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
4388 if (client->flags & FLAG_NEW)
4389 return send_error (ctx, GPG_ERR_INV_STATE);
4391 client->crypto->keyfile = config_get_string (client->filename,
4392 "passphrase_file");
4393 rc = crypto_init_ctx (client->crypto, client->flags & FLAG_NO_PINENTRY,
4394 client->crypto->keyfile);
4395 if (!rc)
4396 rc = crypto_passwd (client, client->crypto);
4398 crypto_free_non_keys (client->crypto);
4399 return send_error (ctx, rc);
4402 static gpg_error_t
4403 parse_opt_data (void *data, void *value)
4405 struct client_s *client = data;
4407 (void) value;
4408 client->opts |= OPT_DATA;
4409 return 0;
4412 static gpg_error_t
4413 send_client_list (assuan_context_t ctx)
4415 struct client_s *client = assuan_get_pointer (ctx);
4416 gpg_error_t rc = 0;
4418 if (client->opts & OPT_VERBOSE)
4420 unsigned i, t;
4421 char **list = NULL;
4422 char *line;
4424 MUTEX_LOCK (&cn_mutex);
4425 pthread_cleanup_push ((void *)release_mutex_cb, &cn_mutex);
4426 t = slist_length (cn_thread_list);
4428 for (i = 0; i < t; i++)
4430 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
4431 char *tmp;
4433 if (thd->state == CLIENT_STATE_UNKNOWN)
4434 continue;
4436 tmp = build_client_info_line (thd, 0);
4437 if (tmp)
4439 char **l = strv_cat (list, tmp);
4440 if (!l)
4441 rc = GPG_ERR_ENOMEM;
4442 else
4443 list = l;
4445 else
4446 rc = GPG_ERR_ENOMEM;
4448 if (rc)
4450 strv_free (list);
4451 break;
4455 pthread_cleanup_pop (1);
4456 if (rc)
4457 return rc;
4459 line = strv_join ("\n", list);
4460 strv_free (list);
4461 pthread_cleanup_push ((void *)xfree, line);
4462 rc = xfer_data (ctx, line, strlen (line));
4463 pthread_cleanup_pop (1);
4464 return rc;
4467 if (client->opts & OPT_DATA)
4469 char buf[ASSUAN_LINELENGTH];
4471 MUTEX_LOCK (&cn_mutex);
4472 snprintf (buf, sizeof (buf), "%u", slist_length (cn_thread_list));
4473 MUTEX_UNLOCK (&cn_mutex);
4474 rc = xfer_data (ctx, buf, strlen (buf));
4476 else
4477 rc = send_status (ctx, STATUS_CLIENTS, NULL);
4479 return rc;
4482 static gpg_error_t
4483 getinfo_command (assuan_context_t ctx, char *line)
4485 struct client_s *client = assuan_get_pointer (ctx);
4486 gpg_error_t rc;
4487 char buf[ASSUAN_LINELENGTH];
4488 struct argv_s *args[] = {
4489 &(struct argv_s) {"data", OPTION_TYPE_NOARG, parse_opt_data},
4490 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_opt_verbose},
4491 NULL
4494 rc = parse_options (&line, args, client, 1);
4495 if (rc)
4496 return send_error (ctx, rc);
4498 if (!strcasecmp (line, "clients"))
4500 rc = send_client_list (ctx);
4502 else if (!strcasecmp (line, "cache"))
4504 if (client->opts & OPT_DATA)
4506 snprintf (buf, sizeof (buf), "%u", cache_file_count ());
4507 rc = xfer_data (ctx, buf, strlen (buf));
4509 else
4510 rc = send_status (ctx, STATUS_CACHE, NULL);
4512 else if (!strcasecmp (line, "pid"))
4514 pid_t pid = getpid ();
4516 snprintf (buf, sizeof (buf), "%u", pid);
4517 rc = xfer_data (ctx, buf, strlen (buf));
4519 else if (!strcasecmp (line, "version"))
4521 char *tmp = str_asprintf ("0x%06x %s", VERSION_HEX,
4522 #ifdef WITH_GNUTLS
4523 "GNUTLS "
4524 #endif
4525 #ifdef WITH_LIBACL
4526 "ACL "
4527 #endif
4528 "");
4529 pthread_cleanup_push (xfree, tmp);
4530 rc = xfer_data (ctx, tmp, strlen (tmp));
4531 pthread_cleanup_pop (1);
4533 else if (!strcasecmp (line, "last_error"))
4535 if (client->last_error)
4536 rc = xfer_data (ctx, client->last_error, strlen (client->last_error));
4537 else
4538 rc = GPG_ERR_NO_DATA;
4540 else if (!strcasecmp (line, "user"))
4542 char *user = NULL;
4544 #ifdef WITH_GNUTLS
4545 if (client->thd->remote)
4546 user = str_asprintf ("#%s", client->thd->tls->fp);
4547 else
4548 user = get_username (client->thd->peer->uid);
4549 #else
4550 user = get_username (client->thd->peer->uid);
4551 #endif
4552 if (user)
4554 pthread_cleanup_push ((void *)xfree, user);
4555 rc = xfer_data (ctx, user, strlen (user));
4556 pthread_cleanup_pop (1);
4558 else
4559 rc = GPG_ERR_NO_DATA;
4561 else
4562 rc = gpg_error (GPG_ERR_SYNTAX);
4564 return send_error (ctx, rc);
4567 static gpg_error_t
4568 parse_opt_secret (void *data, void *value)
4570 struct client_s *client = data;
4572 (void) value;
4573 client->opts |= OPT_SECRET;
4574 return 0;
4577 static gpg_error_t
4578 parse_keyinfo_opt_learn (void *data, void *value)
4580 struct client_s *client = data;
4582 (void)value;
4583 client->opts |= OPT_KEYINFO_LEARN;
4584 return 0;
4587 static gpg_error_t
4588 keyinfo_command (assuan_context_t ctx, char *line)
4590 struct client_s *client = assuan_get_pointer (ctx);
4591 gpg_error_t rc = 0;
4592 char **keys = NULL, **p = NULL;
4593 int sym = 0;
4594 struct argv_s *args[] = {
4595 &(struct argv_s) {"learn", OPTION_TYPE_NOARG, parse_keyinfo_opt_learn},
4596 NULL
4599 rc = parse_options (&line, args, client, 0);
4600 if (rc)
4601 return send_error (ctx, rc);
4603 if (line && *line)
4604 return send_error (ctx, GPG_ERR_SYNTAX);
4606 if (!(client->flags & FLAG_OPEN))
4607 return send_error (ctx, GPG_ERR_INV_STATE);
4609 if (client->opts & OPT_KEYINFO_LEARN)
4611 rc = cache_agent_command ("LEARN");
4612 return send_error (ctx, rc);
4615 if (client->flags & FLAG_NEW)
4616 return send_error (ctx, GPG_ERR_NO_DATA);
4618 rc = lock_flock (ctx, client->filename, FLOCK_TYPE_SH, &client->flock_fd);
4619 if (rc)
4620 return send_error (ctx, rc);
4622 rc = crypto_is_symmetric (client->filename);
4623 unlock_flock (&client->flock_fd);
4624 if (!rc)
4625 sym = 1;
4626 else if (rc != GPG_ERR_BAD_DATA)
4627 return send_error (ctx, rc);
4629 rc = 0;
4630 if (!sym)
4632 p = strv_catv (keys, client->crypto->pubkey);
4633 if (!p)
4634 rc = GPG_ERR_ENOMEM;
4635 else
4636 keys = p;
4639 if (!rc && client->crypto->sigkey)
4641 if (!strv_printf (&keys, "S%s", client->crypto->sigkey))
4643 strv_free (keys);
4644 return send_error (ctx, GPG_ERR_ENOMEM);
4648 if (!rc)
4650 if (keys)
4652 line = strv_join ("\n", keys);
4653 strv_free (keys);
4654 pthread_cleanup_push ((void *)xfree, line);
4655 if (line)
4656 rc = xfer_data (ctx, line, strlen (line));
4657 else
4658 rc = GPG_ERR_ENOMEM;
4660 pthread_cleanup_pop (1);
4662 else
4663 rc = GPG_ERR_NO_DATA;
4665 else
4666 strv_free (keys);
4668 return send_error (ctx, rc);
4671 static gpg_error_t
4672 deletekey_command (assuan_context_t ctx, char *line)
4674 gpg_error_t rc;
4675 struct client_s *client = assuan_get_pointer (ctx);
4676 struct crypto_s *crypto = NULL;
4677 char *keys[] = { NULL, NULL };
4678 gpgme_key_t *result;
4679 char **p = NULL;
4681 if (!(client->flags & FLAG_OPEN))
4682 return send_error (ctx, GPG_ERR_INV_STATE);
4684 rc = peer_is_invoker (client);
4685 if (rc)
4686 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
4688 if (client->flags & FLAG_NO_PINENTRY)
4689 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
4691 if (!*line)
4692 return send_error (ctx, GPG_ERR_SYNTAX);
4694 rc = crypto_keyid_to_16b_once (line);
4695 if (rc)
4696 return send_error (ctx, rc);
4698 for (p = client->crypto->pubkey; p && *p; p++)
4700 if (!strcmp (*p, line))
4701 break;
4704 if (!p)
4706 if (client->crypto->sigkey && strcmp (client->crypto->sigkey, line))
4707 return send_error (ctx, GPG_ERR_FORBIDDEN);
4708 else if (!client->crypto->sigkey)
4709 return send_error (ctx, GPG_ERR_NO_SECKEY);
4712 rc = crypto_init (&crypto, client->ctx, client->filename,
4713 client->flags & FLAG_NO_PINENTRY, NULL);
4714 if (rc)
4715 return send_error (ctx, rc);
4717 pthread_cleanup_push ((void *)crypto_free, crypto);
4718 keys[0] = line;
4719 rc = crypto_list_keys (crypto, keys, 1, &result);
4720 if (!rc)
4722 pthread_cleanup_push ((void *)crypto_free_key_list, result);
4723 rc = crypto_delete_key (client, crypto, *result, 1);
4724 pthread_cleanup_pop (1);
4727 pthread_cleanup_pop (1);
4728 if (gpg_err_source (rc) == GPG_ERR_SOURCE_GPGME
4729 && gpg_err_code (rc) == GPG_ERR_CANCELED)
4730 rc = gpg_error (GPG_ERR_NOT_CONFIRMED);
4732 return send_error (ctx, rc);
4735 static gpg_error_t
4736 kill_command (assuan_context_t ctx, char *line)
4738 struct client_s *client = assuan_get_pointer (ctx);
4739 gpg_error_t rc;
4740 unsigned i, t;
4742 if (!line || !*line)
4743 return send_error (ctx, GPG_ERR_SYNTAX);
4745 MUTEX_LOCK (&cn_mutex);
4746 pthread_cleanup_push ((void *)release_mutex_cb, &cn_mutex);
4747 t = slist_length (cn_thread_list);
4748 rc = GPG_ERR_ESRCH;
4750 for (i = 0; i < t; i++)
4752 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
4753 char *tmp = str_asprintf ("%p", thd->tid);
4755 if (strcmp (line, tmp))
4757 xfree (tmp);
4758 continue;
4761 xfree (tmp);
4762 rc = peer_is_invoker (client);
4763 if (!rc)
4765 #ifdef HAVE_PTHREAD_CANCEL
4766 pthread_cancel (thd->tid);
4767 #else
4768 pthread_kill (thd->tid, SIGUSR2);
4769 #endif
4770 break;
4772 else if (rc == GPG_ERR_EACCES)
4773 rc = GPG_ERR_FORBIDDEN;
4774 else if (rc)
4775 break;
4777 if (config_get_boolean ("global", "strict_kill"))
4778 break;
4780 #ifdef WITH_GNUTLS
4781 if (client->thd->remote && thd->remote)
4783 if (!thd->tls || !thd->tls->fp)
4785 rc = GPG_ERR_INV_STATE;
4786 break;
4788 if (!strcmp (client->thd->tls->fp, thd->tls->fp))
4790 #ifdef HAVE_PTHREAD_CANCEL
4791 pthread_cancel (thd->tid);
4792 #else
4793 pthread_kill (thd->tid, SIGUSR2);
4794 #endif
4795 break;
4798 else if (!client->thd->remote && !thd->remote)
4799 #endif
4801 if (client->thd->peer->uid == thd->peer->uid)
4803 #ifdef HAVE_PTHREAD_CANCEL
4804 pthread_cancel (thd->tid);
4805 #else
4806 pthread_kill (thd->tid, SIGUSR2);
4807 #endif
4810 break;
4813 pthread_cleanup_pop (1);
4814 return send_error (ctx, rc);
4817 static gpg_error_t
4818 listkeys_command (assuan_context_t ctx, char *line)
4820 struct client_s *client = assuan_get_pointer (ctx);
4821 struct crypto_s *crypto = NULL;
4822 char **pattern = NULL;
4823 gpgme_key_t *keys = NULL;
4824 char **result = NULL;
4825 gpg_error_t rc;
4826 struct argv_s *args[] = {
4827 &(struct argv_s) {"secret-only", OPTION_TYPE_NOARG, parse_opt_secret},
4828 NULL
4831 rc = parse_options (&line, args, client, 1);
4832 if (rc)
4833 return send_error (ctx, rc);
4835 rc = crypto_init (&crypto, client->ctx, client->filename,
4836 client->flags & FLAG_NO_PINENTRY, NULL);
4837 if (rc)
4838 return send_error (ctx, rc);
4840 pthread_cleanup_push ((void *)crypto_free, crypto);
4841 pattern = str_split (line, ",", 0);
4842 pthread_cleanup_push ((void *)(void *)strv_free, pattern);
4843 rc = crypto_list_keys (crypto, pattern, client->opts & OPT_SECRET,
4844 &keys);
4845 pthread_cleanup_pop (1);
4846 pthread_cleanup_pop (1);
4847 if (!rc)
4849 int i;
4851 for (i = 0; keys[i]; i++)
4853 char *p = crypto_key_info (keys[i]);
4854 char **r;
4856 if (!p)
4858 rc = GPG_ERR_ENOMEM;
4859 break;
4862 r = strv_cat (result, p);
4863 if (!r)
4865 rc = GPG_ERR_ENOMEM;
4866 break;
4869 result = r;
4872 if (!i)
4873 rc = GPG_ERR_NO_DATA;
4875 crypto_free_key_list (keys);
4878 if (!rc)
4880 line = strv_join ("\n", result);
4881 strv_free (result);
4882 pthread_cleanup_push ((void *)xfree, line);
4883 if (!line)
4884 rc = GPG_ERR_ENOMEM;
4885 else
4886 rc = xfer_data (ctx, line, strlen (line));
4888 pthread_cleanup_pop (1);
4890 else
4891 strv_free (result);
4893 if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
4894 || gpg_err_code (rc) == GPG_ERR_NO_SECKEY)
4895 rc = GPG_ERR_NO_DATA;
4897 return send_error (ctx, rc);
4900 void
4901 init_commands ()
4903 /* !BEGIN-HELP-TEXT!
4905 * This comment is used as a marker to generate the offline documentation
4906 * found in doc/pwmd.info. The indentation needs to be kept for the awk
4907 * script to determine where commands begin and end.
4909 new_command("HELP", 1, 1, 0, help_command, _(
4910 "HELP [--html] [<COMMAND>]\n" /* Showing available commands. */
4911 "Show available commands or command specific help text."
4912 "@*@*"
4913 "The @option{--html} option will output the help text in HTML format."
4916 new_command("DELETEKEY", 1, 1, FLOCK_TYPE_SH|FLOCK_TYPE_KEEP, deletekey_command, _(
4917 "DELETEKEY <keyid>\n" /* Deleting a key from the key ring. */
4918 "Deletes the secret key associated with key @var{keyid} from the keyring. "
4919 "Note that when the key is deleted, the current or other data files using "
4920 "this key will no longer be able to be opened."
4923 new_command("KILL", 1, 0, 0, kill_command, _(
4924 "KILL <thread_id>\n" /* Terminating another client. */
4925 "Terminates the client identified by @var{thread_id} and releases any file "
4926 "lock or other resources it has held. See @code{GETINFO} (@pxref{GETINFO}) "
4927 "for details about listing connected clients. An @code{invoking_user} "
4928 "(@pxref{Configuration}) may kill any client while others may only kill "
4929 "clients of the same @code{UID} or @abbr{TLS} fingerprint."
4932 new_command("LISTKEYS", 1, 0, 0, listkeys_command, _(
4933 "LISTKEYS [--secret-only] [pattern[,<pattern>]]\n" /* Listing keys in the key ring. */
4934 "Returns a new line separated list of key information matching a comma "
4935 "separated list of @var{pattern}'s. When option @option{--secret-only} is "
4936 "specified, only keys matching @var{pattern} that also have a secret key "
4937 "available will be returned."
4940 new_command("KEYINFO", 1, 0, 0, keyinfo_command, _(
4941 "KEYINFO [--learn]\n" /* Showing keys used for the current data file. */
4942 "Returns a new line separated list of key ID's that the currently opened "
4943 "data file has recipients and signers for. If the key is a signing key it "
4944 "will be prefixed with an @code{S}. If the file is a new one, or has no "
4945 "signers in the case of being symmetrically encrypted, the error code "
4946 "@code{GPG_ERR_NO_DATA} is returned."
4947 "@*@*"
4948 "When the @option{--learn} option is passed, keys on a smartcard will be "
4949 "imported."
4952 new_command("GETINFO", 1, 1, 0, getinfo_command, _(
4953 "GETINFO [--data] [--verbose] CACHE | CLIENTS | PID | USER | LAST_ERROR | VERSION\n" /* Obtaining server and client information. */
4954 "Get server and other information. The information is returned via a status "
4955 "message (@pxref{Status Messages}) unless otherwise noted or @option{--data} "
4956 "is specified."
4957 "@*@*"
4958 "@var{CACHE} returns the number of cached documents."
4959 "@*@*"
4960 "@var{CLIENTS} returns the number of "
4961 "connected clients via a status message or a list of connected clients when "
4962 "the @option{--verbose} parameter is used (implies @option{--data}). A "
4963 "verbose line of a client list contains "
4964 "space delimited "
4965 "fields: the thread ID, client name, opened file (@code{/} if none opened), "
4966 "IP address if remote, file lock status, whether the current client is self "
4967 "or not, client state (see below), "
4968 "user ID or TLS fingerprint of the connected client, username if the "
4969 "client is a local one else @code{-}, and finally the time stamp of when the "
4970 "client connected."
4971 "@*@*"
4972 "Client state @code{0} is an unknown client state, state @code{1} indicates "
4973 "the client has connected but hasn't completed initializing, state @code{2} "
4974 "indicates that the client is idle, state @code{3} means the "
4975 "client is in a command and state @code{4} means the client is disconnecting. "
4976 "@*@*"
4977 "@var{PID} returns the process ID number of the server via a data response."
4978 "@*@*"
4979 "@var{VERSION} returns the server version number and compile-time features "
4980 "via a data response with each being space delimited."
4981 "@*@*"
4982 "@var{LAST_ERROR} returns a detailed description of the last failed command "
4983 "via a data response, when available."
4984 "@*@*"
4985 "@var{USER} returns the username or @abbr{TLS} hash of the connected client "
4986 "via a data response."
4989 new_command("PASSWD", 0, 0, FLOCK_TYPE_EX|FLOCK_TYPE_KEEP, passwd_command, _(
4990 "PASSWD\n" /* Changing the passphrase for a key. */
4991 "Changes the passphrase of the secret key required to open the current "
4992 "data file. If the data file is symmetrically encrypted, the error "
4993 "@code{GPG_ERR_NOT_SUPPORTED} is returned. When symmetrically encrypted, "
4994 "the @code{SAVE} command (@pxref{SAVE}) should be used instead to prevent "
4995 "this command saving any unwanted changes to the @abbr{XML} document."
4996 "@*@*"
4997 "This command is not available to non-invoking clients "
4998 "(@pxref{Access Control})."
5001 new_command("OPEN", 1, 1, FLOCK_TYPE_SH|FLOCK_TYPE_KEEP, open_command, _(
5002 "OPEN [--lock] <filename>\n" /* Opening a data file. */
5003 "Opens @var{filename}. When the @var{filename} is not found on the "
5004 "file-system then a new in-memory document will be created. If the file is "
5005 "found, it is looked for in the file cache and when found no passphrase will "
5006 "be required to open it. When not cached, @cite{pinentry(1)} will be used to "
5007 "retrieve the passphrase for decryption unless @option{disable-pinentry} "
5008 "(@pxref{OPTION}) was specified in which case @command{pwmd} will "
5009 "@emph{INQUIRE} the client for the passphrase. Note than when configuration "
5010 "option @option{strict_open} is enabled and the client is not an "
5011 "@option{invoking_user}, an error will be returned when the data file does "
5012 "not exist."
5013 "@*@*"
5014 "When the @option{--lock} option is passed then the file mutex will be "
5015 "locked as if the @code{LOCK} command (@pxref{LOCK}) had been sent after the "
5016 "file had been opened."
5019 new_command("GENKEY", 1, 1, 0, genkey_command, _(
5020 "GENKEY --subkey-of=fpr | --userid=\"str\" [--expire=N] [--algo=\"str\"] [--no-passphrase] [--usage=\"default|sign|encrypt\"]\n" /* Generating a new key. */
5021 "Generates a new key based on option arguments. One of "
5022 "@option{--subkey-of} or @option{--userid} is "
5023 "required. The @option{--subkey-of} option will generate a subkey for the key "
5024 "of the specified fingerprint."
5027 new_command("SAVE", 0, 0, FLOCK_TYPE_EX|FLOCK_TYPE_KEEP, save_command, _(
5028 "SAVE [--sign-keyid=[<fpr>]] [--symmetric | --keyid=<fpr>[,..] | --inquire-keyid]\n" /* Saving document changes to disk. */
5029 "Writes the in-memory @abbr{XML} document to disk. The file written to is the "
5030 "file that was opened when using the @code{OPEN} command (@pxref{OPEN})."
5031 "@*@*"
5032 "If the file is a new one, one of @option{--symmetric}, @option{--keyid} or"
5033 "@option{--inquire-keyid} is required. When not @option{--symmetric}, option "
5034 "@option{--sign-keyid} is also required, but optional otherwise."
5035 "@*@*"
5036 "You can encrypt the data file to a recipient other than the one that it "
5037 "was originally encrypted with by passing the @option{--keyid} or "
5038 "@option{--inquire-keyid} option with a comma separated list of "
5039 "public encryption key fingerprints as its argument. Use the "
5040 "@command{LISTKEYS} command (@pxref{LISTKEYS}) to show key information by "
5041 "pattern. The @option{--sign-keyid} option may also be used to sign the data "
5042 "file with an alternate key by specifying the fingerprint of a signing key. "
5043 "Only one signing key is supported unlike the @option{--keyid} option. "
5044 "A passphrase to decrypt the data file "
5045 "will be required when one or more of the original encryption keys or signing "
5046 "key are not found in either of these two options' arguments or when the data "
5047 "file is symmetrically encrypted reguardless of the @code{require_save_key} "
5048 "configuration parameter. The original encryption keys and signing key will be "
5049 "used when neither of these options are specified."
5050 "@*@*"
5051 "The @option{--keyid} and @option{--sign-keyid} options are not available "
5052 "to non-invoking clients "
5053 "(@pxref{Access Control}) when the recipients or signer do not match those "
5054 "that were used when the file was @code{OPEN}'ed."
5055 "@*@*"
5056 "The @option{--symmetric} option specifies that a new data file be "
5057 "conventionally encrypted. These types of data files do not use a recipient "
5058 "public key but may optionally be signed by using the @option{--sign-keyid} "
5059 "option. To remove the signing key from a symmtrically encrypted data file, "
5060 "leave the option value empty."
5061 "@*@*"
5062 "Note that you cannot change encryption schemes once a data file has been "
5063 "saved."
5066 new_command("ISCACHED", 1, 0, 0, iscached_command, _(
5067 "ISCACHED [--lock] [--agent [--sign]] <filename>\n" /* Testing cache status. */
5068 "Determines the file cache status of the specified @var{filename}. "
5069 "The default is to test whether the filename is cached in memory. Passing "
5070 "option @option{--agent} will test the @command{gpg-agent} cache for at most "
5071 "one cached key used for opening the data file (@pxref{OPEN}). To test if "
5072 "a signing key is cached, pass @option{--sign} along with @option{--agent}. "
5073 "Both the @option{--agent} and @option{--sign} options require an opened data "
5074 "file."
5075 "@*@*"
5076 "An @emph{OK} response is returned if the specified @var{filename} is found "
5077 "in the cache. If not found in the cache but exists on the filesystem "
5078 "then @code{GPG_ERR_NO_DATA} is returned. Otherwise a filesystem error is "
5079 "returned."
5080 "@*@*"
5081 "The @option{--lock} option will lock the file mutex of @var{filename} when "
5082 "the file exists; it does not need to be opened nor cached. The lock will be "
5083 "released when the client exits or sends the @code{UNLOCK} command "
5084 "(@pxref{UNLOCK}). When this option is passed the current data file is closed."
5087 new_command("CLEARCACHE", 1, 1, 0, clearcache_command, _(
5088 "CLEARCACHE [<filename>]\n" /* Removing a cache entry. */
5089 "Clears a file cache entry for all or the specified @var{filename}. Note that "
5090 "this will also clear any @command{gpg-agent} cached keys which may cause "
5091 "problems if another data file shares the same keys as @var{filename}."
5092 "@*@*"
5093 "When clearing all cache entries a permissions test is done against the "
5094 "current client based on the @var{allowed} configuration parameter in a "
5095 "@var{filename} section. Both a cache entry may be cleared and an error "
5096 "returned depending on cached data files and client permissions."
5099 new_command("CACHETIMEOUT", 1, 1, 0, cachetimeout_command, _(
5100 "CACHETIMEOUT <filename> <seconds>\n" /* Setting the cache timeout. */
5101 "The time in @var{seconds} until @var{filename} will be removed from the "
5102 "cache. @code{-1} will keep the cache entry forever, @code{0} will require "
5103 "the passphrase for each @code{OPEN} command (@pxref{OPEN}) or @code{SAVE} "
5104 "(@pxref{SAVE}) command. @xref{Configuration}, and the @code{cache_timeout} "
5105 "parameter."
5108 new_command("LIST", 0, 1, 0, list_command, _(
5109 "LIST [--inquire] [--recurse] [element[<TAB>child[..]]]\n" /* Showing document elements. */
5110 "If no element path is given then a newline separated list of root elements "
5111 "is returned with a data response. If given, then children of the specified "
5112 "element path are returned."
5113 "@*@*"
5114 "Each element path "
5115 "returned will have zero or more flags appened to it. These flags are "
5116 "delimited from the element path by a single space character. A flag itself "
5117 "is a single character. Flag @code{P} indicates that access to the element "
5118 "is denied. Flag @code{+} indicates that there are child nodes of "
5119 "the current element path. Flag @code{E} indicates that an element of the "
5120 "element path contained in a @var{target} attribute could not be found. Flag "
5121 "@code{O} indicates that a @var{target} attribute recursion limit was reached "
5122 "(@pxref{Configuration}). Flag @code{T}, followed by a single space character, "
5123 "then an element path, is the element path of the @var{target} attribute "
5124 "contained in the current element."
5125 "@*@*"
5126 "When a specified element path contains an error, beit from the final "
5127 "element in the path or any previous element, the path is still shown but "
5128 "will contain the error flag for the element with the error. Determining "
5129 "the actual element which contains the error is up to the client. This can be "
5130 "done by traversing the final element up to parent elements that contain the "
5131 "same error flag."
5132 "@*@*"
5133 "The option @option{--recurse} may be used to list the entire element tree "
5134 "for a specified element path or the entire tree for all root elements."
5135 "@*@*"
5136 "When the @option{--inquire} option is passed then all remaining non-option "
5137 "arguments are retrieved via a server @emph{INQUIRE}."
5140 new_command("REALPATH", 0, 1, 0, realpath_command, _(
5141 "REALPATH [--inquire] element[<TAB>child[..]]\n" /* Resolving an element. */
5142 "Resolves all @code{target} attributes of the specified element path and "
5143 "returns the result with a data response. @xref{Target Attribute}, for details."
5144 "@*@*"
5145 "When the @option{--inquire} option is passed then all remaining non-option "
5146 "arguments are retrieved via a server @emph{INQUIRE}."
5149 new_command("STORE", 0, 1, 0, store_command, _(
5150 "STORE element[<TAB>child[..]]<TAB>[content]\n" /* Modifying the content of an element. */
5151 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
5152 "@*@*"
5153 "Creates a new element path or modifies the @var{content} of an existing "
5154 "element. If only a single element is specified then a new root element is "
5155 "created. Otherwise, elements are @key{TAB} delimited and the content will be "
5156 "set to the final @key{TAB} delimited element. If no @var{content} is "
5157 "specified after the final @key{TAB}, then the content of the existing "
5158 "element will be removed; or will be empty if creating a new element."
5159 "@*@*"
5160 "The only restriction of an element name is that it not contain whitespace "
5161 "characters. There is no other whitespace between the @key{TAB} delimited "
5162 "elements. It is recommended that the content of an element be base64 encoded "
5163 "when it contains control or @key{TAB} characters to prevent @abbr{XML} "
5164 "parsing and @command{pwmd} syntax errors."
5167 new_command("RENAME", 0, 1, 0, rename_command, _(
5168 "RENAME [--inquire] element[<TAB>child[..]] <value>\n" /* Renaming an element. */
5169 "Renames the specified @var{element} to the new @var{value}. If an element of "
5170 "the same name as the @var{value} already exists it will be overwritten."
5171 "@*@*"
5172 "When the @option{--inquire} option is passed then all remaining non-option "
5173 "arguments are retrieved via a server @emph{INQUIRE}."
5176 new_command("COPY", 0, 1, 0, copy_command, _(
5177 "COPY [--inquire] source[<TAB>child[..]] dest[<TAB>child[..]]\n" /* Copying an element. */
5178 "Copies the entire element tree starting from the child node of the source "
5179 "element, to the destination element path. If the destination element path "
5180 "does not exist then it will be created; otherwise it is overwritten."
5181 "@*@*"
5182 "Note that attributes from the source element are merged into the "
5183 "destination element when the destination element path exists. When an "
5184 "attribute of the same name exists in both the source and destination "
5185 "elements then the destination attribute will be updated to the source "
5186 "attribute value."
5187 "@*@*"
5188 "When the @option{--inquire} option is passed then all remaining non-option "
5189 "arguments are retrieved via a server @emph{INQUIRE}."
5192 new_command("MOVE", 0, 1, 0, move_command, _(
5193 "MOVE [--inquire] source[<TAB>child[..]] [dest[<TAB>child[..]]]\n" /* Moving an element. */
5194 "Moves the source element path to the destination element path. If the "
5195 "destination is not specified then it will be moved to the root node of the "
5196 "document. If the destination is specified and exists then it will be "
5197 "overwritten; otherwise non-existing elements of the destination element "
5198 "path will be created."
5199 "@*@*"
5200 "When the @option{--inquire} option is passed then all remaining non-option "
5201 "arguments are retrieved via a server @emph{INQUIRE}."
5204 new_command("DELETE", 0, 1, 0, delete_command, _(
5205 "DELETE [--inquire] element[<TAB>child[..]]\n" /* Deleting an element. */
5206 "Removes the specified element path and all of its children. This may break "
5207 "an element with a @code{target} attribute (@pxref{Target Attribute}) that "
5208 "refers to this element or any of its children."
5209 "@*@*"
5210 "When the @option{--inquire} option is passed then all remaining non-option "
5211 "arguments are retrieved via a server @emph{INQUIRE}."
5214 new_command("GET", 0, 1, 0, get_command, _(
5215 "GET [--inquire] element[<TAB>child[..]]\n" /* Getting the content of an element. */
5216 "Retrieves the content of the specified element. The content is returned "
5217 "with a data response."
5218 "@*@*"
5219 "When the @option{--inquire} option is passed then all remaining non-option "
5220 "arguments are retrieved via a server @emph{INQUIRE}."
5223 new_command("ATTR", 0, 1, 0, attr_command, _(
5224 "ATTR [--inquire] SET|GET|DELETE|LIST [<attribute>] element[<TAB>child[..]] ..\n" /* Modifying element attributes. */
5225 "@table @asis\n"
5226 "@item ATTR SET attribute element[<TAB>child[..]] [value]\n"
5227 " Stores or updates an @var{attribute} name and optional @var{value} of an "
5228 "element. When no @var{value} is specified any existing value will be removed."
5229 "@*@*"
5230 "@item ATTR DELETE attribute element[<TAB>child[..]]\n"
5231 " Removes an attribute from an element. If @var{attribute} is @code{_name} "
5232 "or @code{target} an error is returned. Use the @command{DELETE} command "
5233 "(@pxref{DELETE}) instead."
5234 "@*@*"
5235 "@item ATTR LIST element[<TAB>child[..]]\n"
5236 " Retrieves a newline separated list of attributes names and values "
5237 "from the specified element. Each attribute name and value is space delimited."
5238 "@*@*"
5239 "@item ATTR GET attribute element[<TAB>child[..]]\n"
5240 " Retrieves the value of an @var{attribute} from an element."
5241 "@end table\n"
5242 "@*@*"
5243 "When the @option{--inquire} option is passed then all remaining non-option "
5244 "arguments are retrieved via a server @emph{INQUIRE}."
5245 "@*@*"
5246 "@xref{Target Attribute}, for details about this special attribute and also "
5247 "@pxref{Other Attributes} for other attributes that are handled specially "
5248 "by @command{pwmd}."
5251 new_command("XPATH", 0, 1, 0, xpath_command, _(
5252 "XPATH [--inquire] <expression>[<TAB>[value]]\n" /* Modifying more than one element. */
5253 "Evaluates an XPath @var{expression}. If no @var{value} argument is "
5254 "specified it is assumed the expression is a request to return a result. "
5255 "Otherwise, the result is set to the @var{value} argument and the document is "
5256 "updated. If there is no @var{value} after the @key{TAB} character, the value "
5257 "is assumed to be empty and the document is updated. For example:"
5258 "@sp 1\n"
5259 "@example\n"
5260 "XPATH //element[@@_name='password']@key{TAB}\n"
5261 "@end example\n"
5262 "@sp 1\n"
5263 "would clear the content of all @var{password} elements in the data file "
5264 "while leaving off the trailing @key{TAB} would return all @var{password} "
5265 "elements in @abbr{XML} format."
5266 "@*@*"
5267 "When the @option{--inquire} option is passed then all remaining non-option "
5268 "arguments are retrieved via a server @emph{INQUIRE}."
5269 "@*@*"
5270 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
5271 "expression syntax."
5274 new_command("XPATHATTR", 0, 1, 0, xpathattr_command, _(
5275 "XPATHATTR [--inquire] SET|DELETE <name> <expression>[<TAB>[<value>]]\n" /* Modifying more than one element's attributes. */
5276 "Like the @code{XPATH} command (@pxref{XPATH}) but operates on element "
5277 "attributes and does not return a result. For the @var{SET} operation the "
5278 "@var{value} is optional but the field is required. If not specified then "
5279 "the attribute value will be empty. For example:"
5280 "@sp 1\n"
5281 "@example\n"
5282 "XPATHATTR SET password //element[@@_name='password']@key{TAB}\n"
5283 "@end example\n"
5284 "@sp 1\n"
5285 "would create a @var{password} attribute for each @var{password} element "
5286 "found in the document. The attribute value will be empty but still exist."
5287 "@*@*"
5288 "When the @option{--inquire} option is passed then all remaining non-option "
5289 "arguments are retrieved via a server @emph{INQUIRE}."
5290 "@*@*"
5291 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
5292 "expression syntax."
5295 new_command("IMPORT", 0, 1, 0, import_command, _(
5296 "IMPORT [--root=element[<TAB>child[..]]]\n" /* Creating elements from XML. */
5297 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
5298 "@*@*"
5299 "Like the @code{STORE} command (@pxref{STORE}), but the @var{content} "
5300 "argument is raw @abbr{XML} data. The content is created as a child of "
5301 "the element path specified with the @option{--root} option or at the "
5302 "document root when not specified. Existing elements of the same name will "
5303 "be overwritten."
5304 "@*@*"
5305 "The content must begin with an @abbr{XML} element node. @xref{Introduction}, "
5306 "for details."
5309 new_command("DUMP", 1, 1, 0, dump_command, _(
5310 "DUMP\n" /* Showing the XML document. */
5311 "Shows the in memory @abbr{XML} document with indenting. @xref{XPATH}, for "
5312 "dumping a specific node."
5315 new_command("LOCK", 0, 0, 0, lock_command, _(
5316 "LOCK\n" /* Locking the current data file. */
5317 "Locks the mutex associated with the opened file. This prevents other clients "
5318 "from sending commands to the same opened file until the client "
5319 "that sent this command either disconnects or sends the @code{UNLOCK} "
5320 "command. @xref{UNLOCK}."
5323 new_command("UNLOCK", 1, 0, 0, unlock_command, _(
5324 "UNLOCK\n" /* Removing a data file lock. */
5325 "Unlocks the file mutex which was locked with the @code{LOCK} command or "
5326 "a commands' @option{--lock} option (@pxref{LOCK}, @pxref{OPEN}, "
5327 "@pxref{ISCACHED})."
5330 new_command("GETCONFIG", 1, 1, 0, getconfig_command, _(
5331 "GETCONFIG [filename] <parameter>\n" /* Obtaining a configuration value. */
5332 "Returns the value of a @command{pwmd} configuration @var{parameter} with a "
5333 "data response. If no file has been opened then the value for @var{filename} "
5334 "or the default from the @var{global} section will be returned. If a file "
5335 "has been opened and no @var{filename} is specified, the value previously "
5336 "set with the @code{OPTION} command (@pxref{OPTION}) will be returned."
5339 new_command("OPTION", 1, 1, 0, option_command, _(
5340 "OPTION <NAME>=[<VALUE>]\n" /* Setting various client parameters. */
5341 "Sets a client option @var{name} to @var{value}. The value for an option is "
5342 "kept for the duration of the connection with the exception of the "
5343 "@command{pinentry} options which are defaults for all future connections "
5344 "(@pxref{Pinentry}). When @var{value} is empty the option is unset."
5345 "@*@*"
5346 "@table @asis\n"
5347 "@item DISABLE-PINENTRY\n"
5348 "Disable use of @command{pinentry} for passphrase retrieval. When @code{1}, a "
5349 "server inquire is sent to the client to obtain the passphrase. This option "
5350 "may be set as needed before the @code{OPEN} (@pxref{OPEN}), @code{PASSWD} "
5351 "(@pxref{PASSWD}) and @code{SAVE} (@pxref{SAVE}) commands. Set to @code{0} "
5352 "to use a @command{pinentry}."
5353 "@*@*"
5354 "@item DISPLAY\n"
5355 "Set or unset the X11 display to use when prompting for a passphrase."
5356 "@*@*"
5357 "@item TTYNAME\n"
5358 "Set the terminal device path to use when prompting for a passphrase."
5359 "@*@*"
5360 "@item TTYTYPE\n"
5361 "Set the terminal type for use with @option{TTYNAME}."
5362 "@*@*"
5363 "@item NAME\n"
5364 "Associates the thread ID of the connection with the specified textual "
5365 "representation. Useful for debugging log messages. May not contain whitespace."
5366 "@*@*"
5367 "@item LOCK-TIMEOUT\n"
5368 "When not @code{0}, the duration in tenths of a second to wait for the file "
5369 "mutex which has been locked by another thread to be released before returning "
5370 "an error. When @code{-1} the error will be returned immediately."
5371 "@*@*"
5372 "@item CLIENT-STATE\n"
5373 "When set to @code{1} then client state status messages for other clients are "
5374 "sent to the current client. The default is @code{0}."
5375 "@end table\n"
5378 new_command("LS", 1, 1, 0, ls_command, _(
5379 "LS\n" /* Showing available data files. */
5380 "Returns a newline separated list of data files stored in the data directory "
5381 "@file{HOMEDIR/data} (@pxref{Invoking}) with a data response."
5384 new_command("RESET", 1, 1, 0, NULL, _(
5385 "RESET\n" /* Resetting the client state. */
5386 "Closes the currently opened file but keeps any previously set client options "
5387 "(@pxref{OPTION})."
5390 new_command("NOP", 1, 1, 0, NULL, _(
5391 "NOP\n" /* Testing the connection. */
5392 "This command does nothing. It is useful for testing the connection for a "
5393 "timeout condition."
5396 /* !END-HELP-TEXT! */
5397 new_command ("CANCEL", 1, 1, 0, NULL, NULL);
5398 new_command ("END", 1, 1, 0, NULL, NULL);
5399 new_command ("BYE", 1, 1, 0, NULL, NULL);
5401 int i;
5402 for (i = 0; command_table[i]; i++);
5403 qsort (command_table, i - 1, sizeof (struct command_table_s *),
5404 sort_commands);
5407 gpg_error_t
5408 register_commands (assuan_context_t ctx)
5410 int i = 0, rc;
5412 for (; command_table[i]; i++)
5414 if (!command_table[i]->handler)
5415 continue;
5417 rc = assuan_register_command (ctx, command_table[i]->name,
5418 command_table[i]->handler,
5419 command_table[i]->help);
5420 if (rc)
5421 return rc;
5424 rc = assuan_register_bye_notify (ctx, bye_notify);
5425 if (rc)
5426 return rc;
5428 rc = assuan_register_reset_notify (ctx, reset_notify);
5429 if (rc)
5430 return rc;
5432 rc = assuan_register_pre_cmd_notify (ctx, command_startup);
5433 if (rc)
5434 return rc;
5436 return assuan_register_post_cmd_notify (ctx, command_finalize);