Fix potential invalid free().
[pwmd.git] / src / commands.c
blob1d74f8540851e14a75894e450e9abc03b6d27780
1 /*
2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015,
3 2016
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 struct command_table_s
82 const char *name;
83 gpg_error_t (*handler) (assuan_context_t, char *line);
84 const char *help;
85 int ignore_startup;
86 int unlock; // unlock the file mutex after validating the checksum
87 unsigned flock_type;
90 static struct command_table_s **command_table;
92 static gpg_error_t do_lock (struct client_s *client, int add);
93 static gpg_error_t validate_checksum (struct client_s *, const char *filename,
94 struct cache_data_s *, unsigned char **,
95 size_t *);
96 static gpg_error_t update_checksum (struct client_s *client,
97 unsigned char *from_crc, size_t crclen);
99 /* When 'status' is true the 'self' field of the status line will be false
100 * because we never send the STATE status message to the same client that
101 * initiated it. */
102 static char *
103 build_client_info_line (struct client_thread_s *thd, int status)
105 char *uid, *username = NULL;
106 char *line;
108 #ifdef WITH_GNUTLS
109 if (thd->remote)
110 uid = str_asprintf("#%s", thd->tls->fp);
111 else
113 uid = str_asprintf("%u", thd->peer->uid);
114 username = get_username (thd->peer->uid);
116 #else
117 uid = str_asprintf("%u", thd->peer->uid);
118 username = get_username (thd->peer->uid);
119 #endif
120 line = str_asprintf ("%p %s %s %s %u %u %u %s %s %u",
121 thd->tid,
122 thd->name ? thd->name : "-",
123 thd->cl && thd->cl->filename
124 && (thd->cl->flags & FLAG_OPEN)
125 ? thd->cl->filename : "/",
126 #ifdef WITH_GNUTLS
127 thd->remote ? thd->peeraddr : "-",
128 #else
129 "-",
130 #endif
131 thd->cl && thd->cl->flags & FLAG_HAS_LOCK ? 1 : 0,
132 !status && pthread_equal (pthread_self (), thd->tid) ? 1 : 0,
133 thd->state, uid,
134 #ifdef WITH_GNUTLS
135 thd->remote ? "-" : username,
136 #else
137 username,
138 #endif
139 thd->conntime
142 xfree (username);
143 xfree (uid);
144 return line;
147 void
148 update_client_state (struct client_s *client, unsigned s)
150 MUTEX_LOCK (&cn_mutex);
151 client->thd->state = s;
152 MUTEX_UNLOCK (&cn_mutex);
154 if (client->thd->state != CLIENT_STATE_UNKNOWN)
156 char *line = build_client_info_line (client->thd, 1);
158 pthread_cleanup_push (xfree, line);
159 if (line)
160 send_status_all_not_self (STATUS_STATE, "%s", line);
161 pthread_cleanup_pop (1);
165 static gpg_error_t
166 unlock_file_mutex (struct client_s *client, int remove)
168 gpg_error_t rc = 0;
170 // OPEN: keep the lock for the same file being reopened.
171 if (client->flags & FLAG_KEEP_LOCK && client->flags & FLAG_HAS_LOCK)
172 return 0;
174 if (!(client->flags & FLAG_HAS_LOCK))
175 return GPG_ERR_NOT_LOCKED;
177 rc = cache_unlock_mutex (client->filename, remove);
178 if (rc)
179 rc = GPG_ERR_INV_STATE;
180 else
181 client->flags &= ~(FLAG_HAS_LOCK | FLAG_LOCK_CMD);
183 return rc;
186 static gpg_error_t
187 lock_file_mutex (struct client_s *client, int add)
189 gpg_error_t rc = 0;
190 long timeout = config_get_long (client->filename, "cache_timeout");
192 if (client->flags & FLAG_HAS_LOCK)
193 return 0;
195 rc = cache_lock_mutex (client->ctx, client->filename,
196 client->lock_timeout, add, timeout);
197 if (!rc)
198 client->flags |= FLAG_HAS_LOCK;
200 return rc;
203 static gpg_error_t
204 file_modified (struct client_s *client, struct command_table_s *cmd)
206 gpg_error_t rc = 0;
207 int type = !cmd->flock_type || (cmd->flock_type & FLOCK_TYPE_SH)
208 ? LOCK_SH : LOCK_EX;
210 if (!(client->flags & FLAG_OPEN))
211 return GPG_ERR_INV_STATE;
213 rc = lock_file_mutex (client, 0);
214 if (rc && rc != GPG_ERR_NO_DATA)
215 return rc;
217 rc = lock_flock (client->ctx, client->filename, type, &client->flock_fd);
218 if (!rc)
220 rc = validate_checksum (client, client->filename, NULL, NULL, NULL);
221 if (gpg_err_code (rc) == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
222 rc = 0;
223 else if (rc)
224 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
226 else if (gpg_err_code (rc) == GPG_ERR_ENOENT)
227 rc = 0;
229 /* FLAG_HAS_LOCK may have been set by the LOCK command or OPEN --lock. */
230 if ((cmd->unlock && !(client->flags & FLAG_HAS_LOCK)) || rc)
231 unlock_file_mutex (client, 0);
233 if (rc || !(cmd->flock_type & FLOCK_TYPE_KEEP))
234 unlock_flock (&client->flock_fd);
236 return rc;
239 static gpg_error_t
240 parse_xml (assuan_context_t ctx, int new)
242 struct client_s *client = assuan_get_pointer (ctx);
243 int cached = client->doc != NULL;
244 gpg_error_t rc = 0;
246 if (new)
248 client->doc = xml_new_document ();
249 if (client->doc)
251 xmlChar *result;
252 int len;
254 xmlDocDumpFormatMemory (client->doc, &result, &len, 0);
255 client->crypto->plaintext = result;
256 client->crypto->plaintext_size = len;
257 if (!client->crypto->plaintext)
259 xmlFreeDoc (client->doc);
260 client->doc = NULL;
261 rc = GPG_ERR_ENOMEM;
264 else
265 rc = GPG_ERR_ENOMEM;
267 else if (!cached)
268 rc = xml_parse_doc ((char *) client->crypto->plaintext,
269 client->crypto->plaintext_size,
270 (xmlDocPtr *)&client->doc);
272 return rc;
275 static void
276 free_client (struct client_s *client)
278 cache_plaintext_release (&client->doc);
279 xfree (client->crc);
280 xfree (client->filename);
281 xfree (client->last_error);
282 crypto_free (client->crypto);
283 client->crypto = NULL;
286 void
287 reset_client (struct client_s *client)
289 assuan_context_t ctx = client->ctx;
290 struct client_thread_s *thd = client->thd;
291 long lock_timeout = client->lock_timeout;
292 xmlErrorPtr xml_error = client->xml_error;
293 int no_pinentry = (client->flags & FLAG_NO_PINENTRY);
294 int flock_fd = client->flock_fd;
296 unlock_file_mutex (client, client->flags & FLAG_NEW);
297 free_client (client);
298 memset (client, 0, sizeof (struct client_s));
299 client->flock_fd = flock_fd;
300 client->xml_error = xml_error;
301 client->ctx = ctx;
302 client->thd = thd;
303 client->lock_timeout = lock_timeout;
304 client->flags |= no_pinentry ? FLAG_NO_PINENTRY : 0;
307 static void
308 req_free (void *arg)
310 if (!arg)
311 return;
313 strv_free ((char **) arg);
316 static gpg_error_t
317 parse_open_opt_lock (void *data, void *value)
319 struct client_s *client = data;
321 (void)value;
322 client->opts |= OPT_LOCK_ON_OPEN;
323 return 0;
326 static gpg_error_t
327 parse_opt_inquire (void *data, void *value)
329 struct client_s *client = data;
331 (void) value;
332 client->opts |= OPT_INQUIRE;
333 return 0;
336 static gpg_error_t
337 update_checksum (struct client_s *client, unsigned char *from_crc,
338 size_t crclen)
340 unsigned char *crc;
341 size_t len;
342 struct cache_data_s *cdata;
343 gpg_error_t rc;
345 if (!from_crc)
347 rc = get_checksum (client->filename, &crc, &len);
348 if (rc)
349 return rc;
351 else
353 crc = from_crc;
354 len = crclen;
357 xfree (client->crc);
358 client->crc = xmalloc (len);
359 memcpy (client->crc, crc, len);
360 cdata = cache_get_data (client->filename, NULL);
361 if (cdata)
363 xfree (cdata->crc);
364 cdata->crc = xmalloc (len);
365 memcpy (cdata->crc, crc, len);
368 return 0;
371 static gpg_error_t
372 validate_checksum (struct client_s *client, const char *filename,
373 struct cache_data_s *cdata, unsigned char **r_crc,
374 size_t *r_crclen)
376 unsigned char *crc;
377 size_t len;
378 gpg_error_t rc;
379 int n = 0;
381 if (cdata && !cdata->crc)
382 return GPG_ERR_CHECKSUM;
384 rc = get_checksum (filename, &crc, &len);
385 if (rc)
386 return rc;
388 if (client->crc)
389 n = memcmp (client->crc, crc, len);
391 if (!n && cdata)
392 n = memcmp (cdata->crc, crc, len);
394 if (!n && r_crc)
396 *r_crc = crc;
397 *r_crclen = len;
399 else
400 xfree (crc);
402 return n ? GPG_ERR_CHECKSUM : 0;
405 static gpg_error_t
406 open_command (assuan_context_t ctx, char *line)
408 gpg_error_t rc;
409 struct client_s *client = assuan_get_pointer (ctx);
410 int same_file = 0;
411 assuan_peercred_t peer;
412 struct cache_data_s *cdata = NULL;
413 int cached = 0;
414 unsigned char *crc = NULL;
415 size_t crclen = 0;
416 int plaintext = 0;
417 struct argv_s *args[] = {
418 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_open_opt_lock},
419 NULL
422 rc = parse_options (&line, args, client, 1);
423 if (rc)
424 return send_error (ctx, rc);
426 rc = do_validate_peer (ctx, line, &peer);
427 if (rc == GPG_ERR_FORBIDDEN)
428 rc = peer_is_invoker (client);
430 if (rc)
431 return send_error (ctx, rc);
433 if (!valid_filename (line))
434 return send_error (ctx, GPG_ERR_INV_VALUE);
436 /* This client may have locked a different file with ISCACHED --lock than
437 * the current filename. This will remove that lock. */
438 same_file = client->filename && !strcmp (line, client->filename);
439 if (client->flags & FLAG_OPEN ||
440 (client->flags & FLAG_HAS_LOCK && !same_file))
442 unsigned opts = client->opts;
443 unsigned flags = client->flags;
445 if (same_file)
446 client->flags |= FLAG_KEEP_LOCK;
447 else if (client->flags & FLAG_NEW)
448 cache_clear (NULL, client->filename, 0, 0);
450 reset_client (client);
451 client->opts = opts;
452 client->flags |= flags;
453 client->flags &= ~(FLAG_LOCK_CMD);
454 if (!same_file)
455 client->flags &= ~(FLAG_HAS_LOCK | FLAG_NEW);
458 client->filename = str_dup (line);
459 if (!client->filename)
460 return send_error(ctx, GPG_ERR_ENOMEM);
462 /* Need to lock the mutex here because file_modified() cannot without
463 * knowing the filename. */
464 rc = lock_file_mutex (client, 1);
465 if (rc)
466 client->flags &= ~FLAG_OPEN;
468 if (!rc)
470 rc = lock_flock (ctx, client->filename, LOCK_SH, &client->flock_fd);
471 if (gpg_err_code (rc) == GPG_ERR_ENOENT)
472 rc = 0;
475 if (!rc)
477 char *keyfile = config_get_string (client->filename, "passphrase_file");
479 rc = crypto_init (&client->crypto, client->ctx, client->filename,
480 client->flags & FLAG_NO_PINENTRY, keyfile);
481 if (rc)
482 xfree (keyfile);
483 else
484 rc = open_check_file (client->filename, NULL, NULL, 1);
487 if (!rc || gpg_err_code (rc) == GPG_ERR_ENOENT)
489 int reload = 0;
490 int defer = 0;
492 if (rc) // new file
494 rc = 0;
496 if (config_get_boolean ("global", "strict_open"))
497 rc = peer_is_invoker (client);
499 if (!rc)
501 client->flags |= FLAG_NEW;
502 // data file disappeared. clear the cache entry.
503 cache_clear (NULL, client->filename, 1, 1);
504 cdata = NULL;
507 goto done;
510 cdata = cache_get_data (client->filename, &defer);
511 if (cdata && !defer
512 && !cache_plaintext_get (client->filename, &client->doc))
514 rc = validate_checksum (client, client->filename, cdata, &crc,
515 &crclen);
516 if (rc)
518 log_write ("%s: %s", client->filename,
519 pwmd_strerror (rc));
520 cache_plaintext_release (&client->doc);
521 if (rc == GPG_ERR_CHECKSUM)
523 cache_clear (NULL, client->filename, 1, 1);
524 cdata = NULL;
525 goto decrypt;
529 #ifdef WITH_GNUTLS
530 if (!rc && client->thd->remote
531 && config_get_boolean (client->filename, "tcp_require_key")
532 && !(client->flags & FLAG_NEW))
534 rc = crypto_try_decrypt (client,
535 (client->flags & FLAG_NO_PINENTRY));
537 #endif
538 if (!rc)
540 strv_free (client->crypto->pubkey);
541 client->crypto->pubkey = NULL;
542 if (cdata->pubkey)
543 client->crypto->pubkey = strv_dup (cdata->pubkey);
545 xfree (client->crypto->sigkey);
546 client->crypto->sigkey = NULL;
547 if (cdata->sigkey)
548 client->crypto->sigkey = str_dup (cdata->sigkey);
550 cached = 1;
551 plaintext = 1;
554 else if (cdata && cdata->doc) // cached document
556 if (!rc && !(client->flags & FLAG_NEW))
558 rc = validate_checksum (client, client->filename, cdata, &crc,
559 &crclen);
560 if (rc == GPG_ERR_CHECKSUM)
562 rc = 0;
563 reload = 1;
567 if (!rc)
569 rc = cache_iscached (client->filename, &defer, 0, 0);
570 if ((!rc || rc == GPG_ERR_ENOENT) && defer)
572 rc = 0;
573 reload = 2;
577 if (!rc && reload)
579 if (reload == 1)
580 log_write ("%s: %s", client->filename,
581 pwmd_strerror (GPG_ERR_CHECKSUM));
582 cache_clear (NULL, client->filename, 1, 1);
583 cdata = NULL;
584 rc = crypto_decrypt (client, client->crypto);
586 #ifdef WITH_GNUTLS
587 else if (!rc)
589 if (client->thd->remote
590 && config_get_boolean (client->filename, "tcp_require_key")
591 && !(client->flags & FLAG_NEW))
592 rc = crypto_try_decrypt (client,
593 (client->flags & FLAG_NO_PINENTRY));
595 #endif
597 if (!rc && cdata)
599 client->crypto->plaintext = cdata->doc;
600 client->crypto->plaintext_size = cdata->size;
601 rc = cache_decrypt (client->crypto);
602 if (!rc)
604 cdata->doc = NULL;
605 cdata->size = 0;
607 strv_free (client->crypto->pubkey);
608 client->crypto->pubkey = NULL;
609 if (cdata->pubkey)
610 client->crypto->pubkey = strv_dup (cdata->pubkey);
612 xfree (client->crypto->sigkey);
613 client->crypto->sigkey = NULL;
614 if (cdata->sigkey)
615 client->crypto->sigkey = str_dup (cdata->sigkey);
617 cached = 1;
619 else
621 client->crypto->plaintext = NULL;
622 client->crypto->plaintext_size = 0;
626 else // existing file
628 decrypt:
629 cached = cdata != NULL;
630 rc = crypto_decrypt (client, client->crypto);
634 done:
635 if (!rc && !plaintext)
637 rc = parse_xml (ctx, client->flags & FLAG_NEW);
638 if (!rc)
640 rc = cache_encrypt (client->crypto);
641 if (rc)
642 cache_clear (NULL, client->filename, 1, 1);
643 else
645 long timeout = config_get_long (client->filename,
646 "cache_timeout");
648 cache_free_data_once (cdata);
649 cdata = xcalloc (1, sizeof (struct cache_data_s));
650 cdata->doc = client->crypto->plaintext;
651 cdata->size = client->crypto->plaintext_size;
652 cdata->pubkey = strv_dup(client->crypto->pubkey);
653 cdata->sigkey = client->crypto->sigkey ? str_dup(client->crypto->sigkey) : NULL;
654 client->crypto->plaintext = NULL;
655 client->crypto->plaintext_size = 0;
657 if (cached) // wont increment the refcount
659 /* Prevent using another FD to update the checksum for a
660 * cached data file. The validity has already been
661 * verified. */
662 xfree (client->crc);
663 client->crc = NULL;
664 if (crclen)
666 client->crc = xmalloc (crclen);
667 memcpy (client->crc, crc, crclen);
668 xfree (cdata->crc);
669 cdata->crc = xmalloc (crclen);
670 memcpy (cdata->crc, crc, crclen);
673 rc = cache_set_data (client->filename, cdata);
674 /* The cache entry may have been removed and cache_set_data()
675 * already sent STATUS_CACHE. */
676 if (!cache_iscached (client->filename, NULL, 0, 0))
677 rc = send_status (ctx, STATUS_CACHE, NULL);
679 else
680 rc = cache_add_file (client->filename, cdata, timeout);
682 if (!rc)
683 cache_plaintext_set (client->filename, client->doc, 0);
687 else if (!rc)
688 client->crc = crc;
689 else
690 xfree (crc);
692 if (!rc && !(client->flags & FLAG_NEW) && !cached)
693 rc = update_checksum (client, NULL, 0);
695 if (!rc)
697 client->flags |= FLAG_OPEN;
699 if (client->flags & FLAG_NEW)
700 rc = send_status (ctx, STATUS_NEWFILE, NULL);
702 if (!rc && (client->opts & OPT_LOCK_ON_OPEN))
703 rc = do_lock (client, 0);
706 if (rc)
708 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
710 if (client->flags & FLAG_NEW)
711 cache_clear (NULL, client->filename, 1, 1);
713 crypto_free (client->crypto);
714 client->crypto = NULL;
715 client->flags &= ~FLAG_OPEN;
716 cache_plaintext_release (&client->doc);
718 else
719 crypto_free_non_keys (client->crypto);
721 return send_error (ctx, rc);
724 /* If not the invoking_user or is an existing file, check that the list of user
725 * supplied key ID's are in the list of current key ID's obtained when
726 * decrypting the data file.
728 static gpg_error_t
729 permitted_to_save (struct client_s *client, const char **keys,
730 const char **value)
732 gpg_error_t rc = 0;
733 const char **v;
735 if ((client->flags & FLAG_NEW) || (client->opts & OPT_SYMMETRIC))
736 return 0;
738 rc = peer_is_invoker (client);
739 if (!rc)
740 return 0;
741 else if (rc == GPG_ERR_EACCES)
742 rc = GPG_ERR_FORBIDDEN;
743 else if (rc)
744 return rc;
746 /* Empty match. */
747 if ((!value && !keys) || ((value && !*value) && (keys && !*keys)))
748 return 0;
750 for (v = value; v && *v; v++)
752 const char **k, *pv = *v;
753 int match = 0;
755 if (*pv == '0' && *(pv+1) == 'x')
756 pv += 2;
758 for (k = keys; k && *k; k++)
760 const char *pk = *k;
762 if (*pk == '0' && *(pk+1) == 'x')
763 pk += 2;
765 rc = !strcmp (pv, pk) ? 0 : GPG_ERR_FORBIDDEN;
766 if (rc)
767 rc = !strcmp (pv, *k) ? 0 : GPG_ERR_FORBIDDEN;
769 if (!rc)
771 match = 1;
772 break;
776 if (!match)
777 return GPG_ERR_FORBIDDEN;
780 return rc;
783 /* Requires that the keyid be a fingerprint in 16 byte form. */
784 static gpg_error_t
785 parse_save_opt_keyid_common (struct client_s *client, const char **list,
786 const char *value, char ***dst)
788 gpg_error_t rc = 0;
789 char **keys = NULL;
791 if (value && *value)
793 keys = str_split (value, ",", 0);
794 if (!keys)
795 return GPG_ERR_ENOMEM;
798 rc = crypto_keyid_to_16b (keys);
799 if (!rc)
800 rc = permitted_to_save (client, list, (const char **)keys);
802 if (!rc)
803 *dst = keys;
804 else
805 strv_free (keys);
807 return rc;
810 static gpg_error_t
811 parse_save_opt_keyid (void *data, void *value)
813 struct client_s *client = data;
814 const char *str = value;
815 char **dst = NULL;
816 gpg_error_t rc;
818 rc = parse_save_opt_keyid_common (client,
819 (const char **)client->crypto->pubkey,
820 str, &dst);
821 if (rc)
822 return rc;
824 client->crypto->save.pubkey = dst;
825 return 0;
828 static gpg_error_t
829 parse_save_opt_sign_keyid (void *data, void *value)
831 struct client_s *client = data;
832 const char *str = value;
833 char **dst = NULL;
834 gpg_error_t rc;
835 char **tmp = NULL;
837 if (client->crypto->sigkey)
839 if (!strv_printf (&tmp, "%s", client->crypto->sigkey))
840 return GPG_ERR_ENOMEM;
843 rc = parse_save_opt_keyid_common (client, (const char **)tmp, str, &dst);
844 strv_free (tmp);
845 if (rc)
846 return rc;
848 if (!dst)
849 client->opts |= OPT_NO_SIGNER;
850 else
851 client->crypto->save.sigkey = str_dup (*dst);
853 strv_free (dst);
854 return 0;
857 static gpg_error_t
858 parse_save_opt_inquire_keyid (void *data, void *value)
860 struct client_s *client = data;
862 (void)value;
864 if (!(client->flags & FLAG_NEW))
866 gpg_error_t rc = peer_is_invoker (client);
868 if (rc)
869 return rc;
872 client->opts |= OPT_INQUIRE_KEYID;
873 return 0;
876 static gpg_error_t
877 parse_save_opt_symmetric (void *data, void *value)
879 struct client_s *client = data;
881 (void)value;
882 client->opts |= OPT_SYMMETRIC;
883 return 0;
886 static gpg_error_t
887 parse_genkey_opt_userid (void *data, void *value)
889 struct client_s *client = data;
891 if (!(client->flags & FLAG_NEW))
893 gpg_error_t rc = peer_is_invoker (client);
895 if (rc == GPG_ERR_EACCES)
896 rc = GPG_ERR_FORBIDDEN;
898 if (rc)
899 return rc;
902 client->crypto->save.userid = str_dup (value);
903 return client->crypto->save.userid ? 0 : GPG_ERR_ENOMEM;
906 static gpg_error_t
907 parse_genkey_opt_algo (void *data, void *value)
909 struct client_s *client = data;
911 client->crypto->save.algo = str_dup (value);
912 return client->crypto->save.algo ? 0 : GPG_ERR_ENOMEM;
915 static gpg_error_t
916 parse_genkey_opt_expire (void *data, void *value)
918 struct client_s *client = data;
919 gpg_error_t rc = 0;
920 char *p = NULL;
921 unsigned long t;
923 errno = 0;
924 t = strtoul (value, &p, 10);
926 if (!errno && p && *p)
927 rc = GPG_ERR_INV_VALUE;
928 else if (t == ULONG_MAX)
929 rc = GPG_ERR_INV_VALUE;
930 else if (errno)
931 rc = gpg_error_from_syserror ();
932 else
933 client->crypto->save.expire = t;
935 return rc;
938 static gpg_error_t
939 parse_genkey_opt_no_passphrase (void *data, void *value)
941 struct client_s *client = data;
943 (void)value;
944 client->crypto->save.flags |= GPGME_CREATE_NOPASSWD;
945 return 0;
948 /* Tests that the keys in new_keys are also in old_keys. */
949 static gpg_error_t
950 compare_keys (char **new_keys, char **old_keys)
952 char **o;
954 if (!old_keys || !*old_keys)
955 return 0;
957 crypto_keyid_to_16b (new_keys);
959 for (o = old_keys; *o; o++)
961 char **n;
963 for (n = new_keys; *n; n++)
965 if (!strcmp (*n, *o))
966 break;
969 if (!*n)
970 return GPG_ERR_NOT_FOUND;
973 return 0;
976 static gpg_error_t
977 inquire_keyid (struct client_s *client)
979 gpg_error_t rc;
980 unsigned char *result = NULL;
981 size_t len;
982 const char *s = "KEYID";
983 char ***orig;
984 char ***save;
986 orig = &client->crypto->pubkey;
987 save = &client->crypto->save.pubkey;
988 rc = assuan_inquire (client->ctx, s, &result, &len, 0);
989 if (!rc)
991 char **dst = NULL;
993 rc = parse_save_opt_keyid_common (client, (const char **)*orig,
994 (char *)result, &dst);
995 if (!rc)
996 *save = dst;
999 xfree (result);
1000 return rc;
1004 /* When a key lookup in gpg-agent's cache fails, the agent tries the last
1005 * successful key to be unlocked. This prevents pwmd from successfully
1006 * clearing a signing key since the previous key, which more than likely
1007 * belongs to the same keypair as the encryption/decryption key, will have the
1008 * passphrase cached and therefore the signing key also cached. So we need to
1009 * clear both the signing and encryption keys to get the effect of requiring a
1010 * passphrase when generating a new keypair for an existing data file, or when
1011 * the "require_save_key" configuration parameter is set. This parameter is
1012 * mostly a failsafe of the gpg-agent option --ignore-cache-for-signing since
1013 * some/most/all users may fail to set it.
1015 static gpg_error_t
1016 save_command (assuan_context_t ctx, char *line)
1018 struct client_s *client = assuan_get_pointer (ctx);
1019 struct cache_data_s *cdata = NULL;
1020 int sym = 0;
1021 gpg_error_t rc = 0, cache_rc = 0;
1022 int defer = 0;
1023 struct argv_s *args[] = {
1024 &(struct argv_s) {"keyid", OPTION_TYPE_ARG, parse_save_opt_keyid},
1025 &(struct argv_s) {"inquire-keyid", OPTION_TYPE_NOARG,
1026 parse_save_opt_inquire_keyid },
1027 &(struct argv_s) {"sign-keyid", OPTION_TYPE_OPTARG,
1028 parse_save_opt_sign_keyid},
1029 &(struct argv_s) {"symmetric", OPTION_TYPE_NOARG,
1030 parse_save_opt_symmetric },
1031 NULL
1034 crypto_free_save (&client->crypto->save);
1035 client->crypto->save.expire = DEFAULT_EXPIRE;
1037 rc = crypto_is_symmetric (client->filename);
1038 if (!rc || rc == GPG_ERR_BAD_DATA || rc == GPG_ERR_ENOENT)
1040 if (!rc)
1042 client->opts |= OPT_SYMMETRIC;
1043 sym = 1;
1045 else if (rc == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
1046 rc = 0; // New file
1047 else
1048 rc = 0; // PKI
1051 if (rc)
1052 return send_error (ctx, rc);
1054 rc = parse_options (&line, args, client, 0);
1055 if (rc)
1056 return send_error (ctx, rc);
1058 if (config_get_boolean (client->filename, "require_save_key")
1059 || (client->opts & OPT_SYMMETRIC))
1060 client->opts |= OPT_ASK;
1062 rc = open_check_file (client->filename, NULL, NULL, 1);
1063 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
1065 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
1066 return send_error (ctx, rc);
1069 if (!rc)
1070 cache_rc = rc = cache_iscached (client->filename, &defer, 0, 1);
1072 if (gpg_err_code (rc) == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
1073 rc = 0;
1074 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
1075 rc = 0;
1077 if (rc)
1078 return send_error (ctx, rc);
1080 /* Specifying both a recipient and symmetric encryption is an error. */
1081 if ((client->opts & OPT_INQUIRE_KEYID) && (client->opts & OPT_SYMMETRIC))
1082 return send_error (ctx, GPG_ERR_CONFLICT);
1083 /* Existing file with a recipient and wanting symmetric is an error. */
1084 else if ((client->opts & OPT_SYMMETRIC) && client->crypto->save.pubkey)
1085 return send_error (ctx, GPG_ERR_CONFLICT);
1086 else if (client->crypto->save.pubkey && (client->opts & OPT_INQUIRE_KEYID))
1087 return send_error (ctx, GPG_ERR_CONFLICT);
1088 else if (!sym && (client->opts & OPT_SYMMETRIC) && !(client->flags & FLAG_NEW))
1089 return send_error (ctx, GPG_ERR_CONFLICT);
1090 /* New file that is not symmetric without either a recipient or signer. */
1091 else if ((client->flags & FLAG_NEW) && !(client->opts & OPT_SYMMETRIC)
1092 && (!client->crypto->save.pubkey || !client->crypto->save.sigkey))
1093 return send_error (ctx, GPG_ERR_SYNTAX);
1094 else if (client->opts & OPT_INQUIRE_KEYID)
1095 rc = inquire_keyid (client);
1097 if (!rc)
1099 client->crypto->keyfile = config_get_string (client->filename,
1100 "passphrase_file");
1101 rc = crypto_init_ctx (client->crypto, (client->flags & FLAG_NO_PINENTRY),
1102 client->crypto->keyfile);
1105 if (!rc && (client->flags & FLAG_NEW))
1107 /* Require --keyid when --sign-keyid exists to keep KEYINFO
1108 * synchronized. */
1109 if (!client->crypto->save.pubkey && client->crypto->save.sigkey
1110 && !(client->opts & OPT_SYMMETRIC))
1111 rc = GPG_ERR_NO_PUBKEY;
1113 else if (!rc)
1115 cdata = cache_get_data (client->filename, NULL);
1116 if (cdata)
1118 if (client->crypto->save.pubkey)
1119 rc = compare_keys (client->crypto->save.pubkey, cdata->pubkey);
1121 /* Always allow a signer for symmetric data files. */
1122 if (!rc && client->crypto->save.sigkey
1123 && !(client->opts & OPT_SYMMETRIC))
1124 rc = !strcmp (client->crypto->save.sigkey, cdata->sigkey)
1125 ? 0 : GPG_ERR_NOT_FOUND;
1127 /* Prevent saving to a recipient who is not in the original recipient
1128 * list without a passphrase. */
1129 if (rc || (client->crypto->sigkey && (client->opts & OPT_NO_SIGNER)))
1130 client->opts |= OPT_ASK;
1132 if (rc == GPG_ERR_NOT_FOUND)
1134 rc = peer_is_invoker (client);
1135 if (rc == GPG_ERR_EACCES)
1136 rc = GPG_ERR_FORBIDDEN;
1139 if (!client->crypto->save.pubkey
1140 && !(client->opts & OPT_SYMMETRIC))
1141 client->crypto->save.pubkey = strv_dup (cdata->pubkey);
1143 if (!rc && !client->crypto->save.sigkey && cdata->sigkey
1144 && !(client->opts & OPT_NO_SIGNER))
1145 client->crypto->save.sigkey = str_dup (cdata->sigkey);
1146 else if (!rc && !client->crypto->save.sigkey
1147 && (client->opts & OPT_NO_SIGNER)
1148 && !(client->opts & OPT_SYMMETRIC))
1149 rc = GPG_ERR_NO_SIGNATURE_SCHEME;
1151 else
1153 client->crypto->save.pubkey = strv_dup (client->crypto->pubkey);
1154 client->crypto->save.sigkey = str_dup (client->crypto->sigkey);
1158 if (!rc && !(client->flags & FLAG_NEW))
1160 /* Fixes {NEW_,SIGN_}PASSPHRASE inquire keywords. See passphrase_cb(). */
1161 if (client->opts & OPT_SYMMETRIC)
1162 client->crypto->flags |= CRYPTO_FLAG_PASSWD;
1164 if (client->opts & OPT_ASK)
1166 rc = cache_clear_agent_keys (client->filename, 1, 1);
1167 if (!rc)
1168 rc = crypto_try_decrypt (client, client->flags & FLAG_NO_PINENTRY);
1172 if (!rc && client->opts & OPT_SYMMETRIC)
1173 client->crypto->flags |= CRYPTO_FLAG_PASSWD_NEW;
1175 if (!rc)
1176 rc = xml_update_element_mtime (client, xmlDocGetRootElement (client->doc));
1178 if (!rc)
1180 int size;
1182 xmlDocDumpFormatMemory (client->doc, &client->crypto->plaintext, &size,
1184 if (size > 0)
1185 client->crypto->plaintext_size = (size_t) size;
1186 else
1187 rc = GPG_ERR_ENOMEM;
1189 if (!rc)
1191 client->crypto->flags |= (client->opts & OPT_SYMMETRIC) ? CRYPTO_FLAG_SYMMETRIC : 0;
1192 client->crypto->flags |= (client->flags & FLAG_NEW) ? CRYPTO_FLAG_NEWFILE : 0;
1193 client->crypto->flags |= !(client->opts & OPT_SYMMETRIC) ? CRYPTO_FLAG_PASSWD_SIGN : 0;
1194 rc = crypto_encrypt (client, client->crypto);
1195 client->crypto->flags &= ~CRYPTO_FLAG_SYMMETRIC;
1198 if (!rc)
1200 unsigned char *crc = NULL;
1201 size_t crclen = 0;
1203 rc = crypto_write_file (client->crypto, &crc, &crclen);
1204 pthread_cleanup_push ((void *)xfree, crc);
1205 if (!rc)
1207 if (!cache_rc)
1208 cdata = cache_get_data (client->filename, NULL);
1209 else
1210 cdata = xcalloc (1, sizeof (struct cache_data_s));
1213 if (!rc)
1215 rc = cache_encrypt (client->crypto);
1216 if (rc)
1218 cache_clear (NULL, client->filename, 1, 1);
1219 client->flags &= ~(FLAG_NEW);
1221 strv_free (client->crypto->pubkey);
1222 client->crypto->pubkey = NULL;
1223 if (client->crypto->save.pubkey)
1224 client->crypto->pubkey = strv_dup (client->crypto->save.pubkey);
1226 xfree (client->crypto->sigkey);
1227 client->crypto->sigkey = NULL;
1228 if (client->crypto->save.sigkey)
1229 client->crypto->sigkey = str_dup (client->crypto->save.sigkey);
1233 if (!rc)
1235 long timeout = config_get_long (client->filename, "cache_timeout");
1236 xmlDocPtr doc = xmlCopyDoc (client->doc, 1);
1238 if (!doc)
1239 rc = GPG_ERR_ENOMEM;
1241 if (!rc)
1243 cache_plaintext_release (&client->doc);
1244 strv_free (cdata->pubkey);
1245 cdata->pubkey = client->crypto->save.pubkey;
1246 client->crypto->save.pubkey = NULL;
1248 xfree (cdata->sigkey);
1249 cdata->sigkey = client->crypto->save.sigkey;
1250 client->crypto->save.sigkey = NULL;
1252 xfree (cdata->crc);
1253 cdata->crc = NULL;
1255 /* cache_encrypt() does in-place encryption */
1256 xfree (cdata->doc);
1257 cdata->doc = client->crypto->plaintext;
1258 client->crypto->plaintext = NULL;
1259 cdata->size = client->crypto->plaintext_size;
1260 client->crypto->plaintext_size = 0;
1262 client->doc = doc;
1263 cache_plaintext_set (client->filename, client->doc, 0);
1265 /* Update in case the cache entry expires the next SAVE may
1266 * not have any known keys. */
1267 strv_free (client->crypto->pubkey);
1268 client->crypto->pubkey = NULL;
1269 if (cdata->pubkey)
1270 client->crypto->pubkey = strv_dup (cdata->pubkey);
1272 xfree (client->crypto->sigkey);
1273 client->crypto->sigkey = NULL;
1274 if (cdata->sigkey)
1275 client->crypto->sigkey = str_dup (cdata->sigkey);
1277 if (!cache_rc) // wont increment refcount
1278 rc = cache_set_data (client->filename, cdata);
1279 else
1280 rc = cache_add_file (client->filename, cdata, timeout);
1283 if (!rc && (cache_rc || (client->flags & FLAG_NEW)))
1284 send_status_all (STATUS_CACHE, NULL);
1286 if (!rc)
1288 rc = update_checksum (client, crc, crclen);
1289 client->flags &= ~(FLAG_NEW);
1293 pthread_cleanup_pop (1);
1294 if (!rc)
1295 client->did_cow = 0;
1299 crypto_free_non_keys (client->crypto);
1300 return send_error (ctx, rc);
1303 static gpg_error_t
1304 parse_genkey_opt_usage (void *data, void *v)
1306 struct client_s *client = data;
1307 char *value = v;
1309 if (!value || !*value)
1310 return GPG_ERR_INV_VALUE;
1311 else if (!strcmp (value, "sign"))
1312 client->crypto->save.flags |= GPGME_CREATE_SIGN;
1313 else if (!strcmp (value, "encrypt"))
1314 client->crypto->save.flags |= GPGME_CREATE_ENCR;
1315 else if (!strcmp (value, "default"))
1316 client->crypto->save.flags &= ~(GPGME_CREATE_ENCR|GPGME_CREATE_SIGN);
1317 else
1318 return GPG_ERR_INV_VALUE;
1320 return 0;
1323 gpg_error_t
1324 parse_genkey_opt_subkey_of (void *data, void *v)
1326 gpg_error_t rc;
1327 struct client_s *client = data;
1328 char *value = v;
1329 char *tmp[] = { value, NULL };
1330 gpgme_key_t *keys = NULL;
1332 rc = peer_is_invoker (client);
1333 if (rc)
1334 return rc;
1336 if (!value || !*value)
1337 return GPG_ERR_INV_VALUE;
1339 rc = crypto_list_keys (client->crypto, tmp, 1, &keys);
1340 if (rc)
1341 return rc;
1343 if (!keys || !*keys)
1345 crypto_free_key_list (keys);
1346 return GPG_ERR_NO_SECKEY;
1349 client->crypto->save.mainkey = keys;
1350 return 0;
1353 static gpg_error_t
1354 genkey_command (assuan_context_t ctx, char *line)
1356 struct client_s *client = assuan_get_pointer (ctx);
1357 struct crypto_s *crypto, *orig;
1358 gpg_error_t rc = 0;
1359 struct argv_s *args[] = {
1360 &(struct argv_s) {"userid", OPTION_TYPE_ARG,
1361 parse_genkey_opt_userid},
1362 &(struct argv_s) {"expire", OPTION_TYPE_ARG,
1363 parse_genkey_opt_expire},
1364 &(struct argv_s) {"algo", OPTION_TYPE_ARG,
1365 parse_genkey_opt_algo},
1366 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG,
1367 parse_genkey_opt_no_passphrase},
1368 &(struct argv_s) {"usage", OPTION_TYPE_ARG,
1369 parse_genkey_opt_usage},
1370 &(struct argv_s) {"subkey-of", OPTION_TYPE_ARG,
1371 parse_genkey_opt_subkey_of},
1372 NULL
1375 orig = client->crypto;
1376 rc = crypto_init (&crypto, ctx, client->filename,
1377 client->flags & FLAG_NO_PINENTRY, NULL);
1378 if (rc)
1379 return send_error (ctx, rc);
1381 client->crypto = crypto;
1382 rc = parse_options (&line, args, client, 0);
1383 if (rc)
1384 goto fail;
1386 if (!client->crypto->save.userid && !client->crypto->save.mainkey)
1388 rc = GPG_ERR_SYNTAX;
1389 goto fail;
1392 client->crypto->flags |= CRYPTO_FLAG_NEWFILE;
1394 if (client->crypto->save.userid || client->crypto->save.mainkey)
1395 rc = crypto_genkey (client, client->crypto);
1397 fail:
1398 crypto_free (crypto);
1399 client->crypto = orig;
1400 return send_error (ctx, rc);
1403 static gpg_error_t
1404 do_delete (assuan_context_t ctx, char *line)
1406 struct client_s *client = assuan_get_pointer (ctx);
1407 struct xml_request_s *req;
1408 xmlNodePtr n;
1409 gpg_error_t rc;
1411 rc = xml_new_request (client, line, XML_CMD_DELETE, &req);
1412 if (rc)
1413 return rc;
1415 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1416 xml_free_request (req);
1417 if (rc)
1418 return rc;
1420 rc = xml_is_element_owner (client, n);
1421 if (!rc)
1422 rc = xml_unlink_node (client, n);
1424 return rc;
1427 /* Won't update cdata->plaintext. Other clients are working on the original or
1428 * copy of the same document. The first client to SAVE wins and requires others
1429 * to reopen the data file do to a checksum error. */
1430 static gpg_error_t
1431 copy_on_write (struct client_s *client)
1433 struct cache_data_s *cdata;
1435 if (client->did_cow)
1436 return 0;
1438 cdata = cache_get_data (client->filename, NULL);
1439 if (cdata)
1441 gpg_error_t rc;
1442 xmlDocPtr doc = xmlCopyDoc (client->doc, 1);
1444 if (!doc)
1445 return GPG_ERR_ENOMEM;
1447 rc = cache_plaintext_set (client->filename, doc, 1);
1448 if (rc)
1450 xmlFree (doc);
1451 return rc;
1454 (void)cache_plaintext_release (&client->doc);
1455 client->doc = doc;
1456 client->did_cow = 1;
1457 return 0;
1460 return GPG_ERR_NO_DATA;
1463 static gpg_error_t
1464 delete_command (assuan_context_t ctx, char *line)
1466 struct client_s *client = assuan_get_pointer (ctx);
1467 gpg_error_t rc;
1468 struct argv_s *args[] = {
1469 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1470 NULL
1473 rc = parse_options (&line, args, client, 1);
1474 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1475 rc = GPG_ERR_SYNTAX;
1476 if (rc)
1477 return send_error (ctx, rc);
1479 rc = copy_on_write (client);
1480 if (rc)
1481 return send_error (ctx, rc);
1483 if (client->opts & OPT_INQUIRE)
1485 unsigned char *result;
1486 size_t len;
1488 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1489 if (rc)
1490 return send_error (ctx, rc);
1492 pthread_cleanup_push ((void *)xfree, result);
1493 rc = do_delete (ctx, (char *)result);
1494 pthread_cleanup_pop (1);
1496 else
1497 rc = do_delete (ctx, line);
1499 return send_error (ctx, rc);
1502 static gpg_error_t
1503 update_element_expirey (struct client_s *client, xmlNodePtr n)
1505 gpg_error_t rc = 0;
1506 xmlChar *expire, *incr;
1507 char *p;
1508 time_t e, e_orig, i;
1509 time_t now = time (NULL);
1511 expire = xml_attribute_value (n, (xmlChar *)"expire");
1512 if (!expire)
1513 return 0;
1515 errno = 0;
1516 e = strtoul ((char *)expire, &p, 10);
1517 if (errno || *p || e == ULONG_MAX || *expire == '-')
1519 xmlFree (expire);
1520 rc = GPG_ERR_ERANGE;
1521 goto fail;
1524 xmlFree (expire);
1525 incr = xml_attribute_value (n, (xmlChar *)"expire_increment");
1526 if (!incr)
1527 return 0;
1529 i = strtoul ((char *)incr, &p, 10);
1530 if (errno || *p || i == ULONG_MAX || *incr == '-')
1532 xmlFree (incr);
1533 rc = GPG_ERR_ERANGE;
1534 goto fail;
1537 xmlFree (incr);
1538 e_orig = e;
1539 e = now + i;
1540 p = str_asprintf ("%lu", e);
1541 if (!p)
1543 rc = GPG_ERR_ENOMEM;
1544 goto fail;
1547 rc = xml_add_attribute (client, n, "expire", p);
1548 xfree (p);
1549 if (!rc)
1550 rc = send_status (client->ctx, STATUS_EXPIRE, "%lu %lu", e_orig, e);
1552 fail:
1553 return rc;
1556 static gpg_error_t
1557 store_command (assuan_context_t ctx, char *line)
1559 struct client_s *client = assuan_get_pointer (ctx);
1560 gpg_error_t rc;
1561 size_t len;
1562 unsigned char *result;
1563 xmlNodePtr n, parent;
1564 int has_content;
1565 char *content = NULL;
1566 struct xml_request_s *req;
1568 if (line && *line)
1569 return send_error (ctx, GPG_ERR_SYNTAX);
1571 rc = copy_on_write (client);
1572 if (rc)
1573 return send_error (ctx, rc);
1575 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1576 if (rc)
1577 return send_error (ctx, rc);
1579 rc = xml_new_request (client, (char *)result, XML_CMD_STORE, &req);
1580 xfree (result);
1581 if (rc)
1582 return send_error (ctx, rc);
1584 /* Prevent passing the element content around to save some memory. */
1585 len = strv_length (req->args);
1586 has_content = line && line[strlen (line) - 1] != '\t' && len > 1;
1587 if (*(req->args+1) && !xml_valid_element_path (req->args, has_content))
1589 xml_free_request (req);
1590 return send_error (ctx, GPG_ERR_INV_VALUE);
1593 if (has_content || !*req->args[len-1])
1595 content = req->args[len-1];
1596 req->args[len-1] = NULL;
1599 if (strv_length (req->args) > 1)
1601 rc = xml_check_recursion (client, req);
1602 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
1603 goto fail;
1606 parent = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1608 if (!rc && len > 1)
1610 rc = xml_is_element_owner (client, parent);
1611 if (!rc)
1613 n = xml_find_text_node (parent->children);
1614 if (n)
1615 xmlNodeSetContent (n, (xmlChar *) content);
1616 else
1617 xmlNodeAddContent (parent, (xmlChar *) content);
1619 (void)xml_update_element_mtime (client, parent);
1620 (void)update_element_expirey (client, parent);
1624 fail:
1625 xfree (content);
1626 xml_free_request (req);
1627 return send_error (ctx, rc);
1630 static gpg_error_t
1631 xfer_data (assuan_context_t ctx, const char *line, int total)
1633 struct client_s *client = assuan_get_pointer (ctx);
1634 int to_send;
1635 int sent = 0;
1636 gpg_error_t rc = 0;
1637 int progress = config_get_integer ("global", "xfer_progress");
1638 int flush = 0;
1640 if (!(client->flags & FLAG_LOCK_CMD))
1641 rc = unlock_file_mutex (client, 0);
1642 if (rc && rc != GPG_ERR_NOT_LOCKED)
1643 return rc;
1645 progress =
1646 progress > 0 ? (progress / ASSUAN_LINELENGTH) * ASSUAN_LINELENGTH : 0;
1647 to_send = total < ASSUAN_LINELENGTH ? total : ASSUAN_LINELENGTH;
1648 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1650 if (rc)
1651 return rc;
1653 again:
1656 if (sent + to_send > total)
1657 to_send = total - sent;
1659 rc = assuan_send_data (ctx, flush ? NULL : (char *) line + sent,
1660 flush ? 0 : to_send);
1661 if (!rc)
1663 sent += flush ? 0 : to_send;
1665 if ((progress && !(sent % progress) && sent != total) ||
1666 (sent == total && flush))
1667 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1669 if (!flush && !rc && sent == total)
1671 flush = 1;
1672 goto again;
1676 while (!rc && sent < total);
1678 return rc;
1681 static gpg_error_t
1682 do_get (assuan_context_t ctx, char *line)
1684 struct client_s *client = assuan_get_pointer (ctx);
1685 gpg_error_t rc;
1686 struct xml_request_s *req;
1687 xmlNodePtr n;
1689 rc = xml_new_request (client, line, XML_CMD_NONE, &req);
1690 if (rc)
1691 return rc;
1693 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1694 if (!rc)
1696 if (n && n->children)
1698 xmlNodePtr tmp = n;
1700 n = xml_find_text_node (n->children);
1701 if (!n || !n->content || !*n->content)
1702 rc = GPG_ERR_NO_DATA;
1703 else
1705 rc = xfer_data (ctx, (char *) n->content, xmlStrlen (n->content));
1706 if (!rc)
1708 xmlChar *expire = xml_attribute_value (tmp,
1709 (xmlChar *)"expire");
1710 if (expire)
1712 time_t now = time (NULL);
1713 time_t e;
1714 char *p;
1716 errno = 0;
1717 e = strtoul ((char *)expire, &p, 10);
1718 if (errno || *p || e == ULONG_MAX || *expire == '-')
1719 log_write (_("invalid expire attribute value: %s"),
1720 expire);
1721 else if (now >= e)
1722 rc = send_status (ctx, STATUS_EXPIRE, "%lu 0", e);
1724 xmlFree (expire);
1729 else
1730 rc = GPG_ERR_NO_DATA;
1733 xml_free_request (req);
1734 return rc;
1737 static gpg_error_t
1738 get_command (assuan_context_t ctx, char *line)
1740 struct client_s *client = assuan_get_pointer (ctx);
1741 gpg_error_t rc;
1742 struct argv_s *args[] = {
1743 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1744 NULL
1747 rc = parse_options (&line, args, client, 1);
1748 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1749 rc = GPG_ERR_SYNTAX;
1750 if (rc)
1751 return send_error (ctx, rc);
1753 if (client->opts & OPT_INQUIRE)
1755 unsigned char *result;
1756 size_t len;
1758 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1759 if (rc)
1760 return send_error (ctx, rc);
1762 pthread_cleanup_push ((void *)xfree, result);
1763 rc = do_get (ctx, (char *)result);
1764 pthread_cleanup_pop (1);
1766 else
1767 rc = do_get (ctx, line);
1769 return send_error (ctx, rc);
1772 static void list_command_free1 (void *arg);
1773 static gpg_error_t
1774 realpath_command (assuan_context_t ctx, char *line)
1776 gpg_error_t rc;
1777 char **realpath = NULL;
1778 struct client_s *client = assuan_get_pointer (ctx);
1779 struct argv_s *args[] = {
1780 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1781 NULL
1784 rc = parse_options (&line, args, client, 1);
1785 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1786 rc = GPG_ERR_SYNTAX;
1787 if (rc)
1788 return send_error (ctx, rc);
1790 if (client->opts & OPT_INQUIRE)
1792 unsigned char *result;
1793 size_t len;
1795 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1796 if (rc)
1797 return send_error (ctx, rc);
1799 pthread_cleanup_push ((void *)xfree, result);
1800 (void)xml_resolve_path (client, client->doc, result, &realpath, &rc);
1801 pthread_cleanup_pop (1);
1803 else
1804 (void)xml_resolve_path (client, client->doc, (unsigned char *)line,
1805 &realpath, &rc);
1807 if (!rc)
1809 char *tmp = strv_join ((char *)"\t", realpath);
1811 strv_free (realpath);
1812 if (!tmp)
1813 return send_error (ctx, GPG_ERR_ENOMEM);
1815 pthread_cleanup_push ((void *)xfree, tmp);
1816 rc = xfer_data (ctx, tmp, strlen (tmp));
1817 pthread_cleanup_pop (1);
1820 return send_error (ctx, rc);
1823 static void
1824 list_command_free1 (void *arg)
1826 if (arg)
1827 string_free ((struct string_s *) arg, 1);
1830 static gpg_error_t
1831 parse_list_opt_recurse (void *data, void *value)
1833 struct client_s *client = data;
1835 (void)value;
1836 client->opts |= OPT_LIST_RECURSE;
1837 return 0;
1840 static gpg_error_t
1841 parse_opt_verbose (void *data, void *value)
1843 struct client_s *client = data;
1845 (void)value;
1846 client->opts |= OPT_VERBOSE;
1847 return 0;
1850 static gpg_error_t
1851 list_path_once (struct client_s *client, char *line,
1852 struct element_list_s *elements, struct string_s *result)
1854 gpg_error_t rc;
1856 rc = xml_create_path_list (client, client->doc, NULL, elements, line, 0);
1857 if (rc == GPG_ERR_ELOOP || rc == GPG_ERR_EACCES)
1858 rc = 0;
1860 if (!rc)
1862 int total = slist_length (elements->list);
1864 if (total)
1866 int i;
1868 for (i = 0; i < total; i++)
1870 char *tmp = slist_nth_data (elements->list, i);
1872 string_append_printf (result, "%s%s", tmp,
1873 i + 1 == total ? "" : "\n");
1876 else
1877 rc = GPG_ERR_NO_DATA;
1880 return rc;
1883 static gpg_error_t
1884 do_list (assuan_context_t ctx, char *line)
1886 struct client_s *client = assuan_get_pointer (ctx);
1887 gpg_error_t rc = GPG_ERR_NO_DATA;
1888 struct element_list_s *elements = NULL;
1890 if (!line || !*line)
1892 struct string_s *str = string_new (NULL);
1893 xmlNodePtr n;
1895 if (!str)
1896 return GPG_ERR_ENOMEM;
1898 pthread_cleanup_push ((void *)list_command_free1, str);
1899 n = xmlDocGetRootElement (client->doc);
1900 for (n = n->children; n; n = n->next)
1902 xmlChar *name;
1904 if (n->type != XML_ELEMENT_NODE)
1905 continue;
1907 name = xmlGetProp (n, (xmlChar *)"_name");
1908 if (!name)
1910 rc = GPG_ERR_ENOMEM;
1911 break;
1914 elements = xcalloc (1, sizeof (struct element_list_s));
1915 if (!elements)
1917 xmlFree (name);
1918 rc = GPG_ERR_ENOMEM;
1919 break;
1922 elements->prefix = string_new (NULL);
1923 if (!elements->prefix)
1925 xmlFree (name);
1926 xml_free_element_list (elements);
1927 rc = GPG_ERR_ENOMEM;
1928 break;
1931 elements->recurse = client->opts & OPT_LIST_RECURSE;
1932 elements->root_only = !elements->recurse;
1933 pthread_cleanup_push ((void *)xml_free_element_list, elements);
1934 rc = list_path_once (client, (char *)name, elements, str);
1935 xmlFree (name);
1936 pthread_cleanup_pop (1);
1937 if (rc)
1938 break;
1940 if (n->next)
1941 string_append (str, "\n");
1944 if (!rc)
1945 rc = xfer_data (ctx, str->str, str->len);
1947 pthread_cleanup_pop (1);
1948 return rc;
1951 elements = xcalloc (1, sizeof (struct element_list_s));
1952 if (!elements)
1953 return GPG_ERR_ENOMEM;
1955 elements->prefix = string_new (NULL);
1956 if (!elements->prefix)
1958 xml_free_element_list (elements);
1959 return GPG_ERR_ENOMEM;
1962 elements->recurse = client->opts & OPT_LIST_RECURSE;
1963 pthread_cleanup_push ((void *)xml_free_element_list, elements);
1964 struct string_s *str = string_new (NULL);
1965 pthread_cleanup_push ((void *)list_command_free1, str);
1966 rc = list_path_once (client, line, elements, str);
1967 if (!rc)
1968 rc = xfer_data (ctx, str->str, str->len);
1970 pthread_cleanup_pop (1);
1971 pthread_cleanup_pop (1);
1972 return rc;
1975 static gpg_error_t
1976 list_command (assuan_context_t ctx, char *line)
1978 struct client_s *client = assuan_get_pointer (ctx);
1979 gpg_error_t rc;
1980 struct argv_s *args[] = {
1981 &(struct argv_s) {"recurse", OPTION_TYPE_NOARG, parse_list_opt_recurse},
1982 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1983 /* These are deprecated but kept for backward compatibility with older
1984 * clients. */
1985 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, NULL},
1986 &(struct argv_s) {"with-target", OPTION_TYPE_NOARG, NULL},
1987 &(struct argv_s) {"all", OPTION_TYPE_NOARG, parse_list_opt_recurse},
1988 &(struct argv_s) {"no-recurse", OPTION_TYPE_NOARG, NULL},
1989 NULL
1992 if (disable_list_and_dump == 1)
1993 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
1995 rc = parse_options (&line, args, client, 1);
1996 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1997 rc = GPG_ERR_SYNTAX;
1998 if (rc)
1999 return send_error (ctx, rc);
2001 if (client->opts & OPT_INQUIRE)
2003 unsigned char *result;
2004 size_t len;
2006 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2007 if (rc)
2008 return send_error (ctx, rc);
2010 pthread_cleanup_push ((void *)xfree, result);
2011 rc = do_list (ctx, (char *)result);
2012 pthread_cleanup_pop (1);
2014 else
2015 rc = do_list (ctx, line);
2017 return send_error (ctx, rc);
2020 #define RESUMABLE_ERROR(rc) (rc == GPG_ERR_ELOOP || rc == GPG_ERR_EACCES \
2021 || rc == GPG_ERR_ELEMENT_NOT_FOUND || !rc)
2023 * args[0] - element path
2025 static gpg_error_t
2026 attribute_list (assuan_context_t ctx, char **args)
2028 struct client_s *client = assuan_get_pointer (ctx);
2029 char **attrlist = NULL;
2030 int i = 0;
2031 int target = 0;
2032 xmlAttrPtr a;
2033 xmlNodePtr n, an, r;
2034 char *line;
2035 gpg_error_t rc;
2036 struct xml_request_s *req;
2038 if (!args || !args[0] || !*args[0])
2039 return GPG_ERR_SYNTAX;
2041 rc = xml_new_request (client, args[0], XML_CMD_ATTR_LIST, &req);
2042 if (rc)
2043 return rc;
2045 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2046 xml_free_request (req);
2047 if (rc)
2048 return rc;
2050 again:
2051 for (a = n->properties; a; a = a->next)
2053 char **pa;
2055 if (target && xml_reserved_attribute ((char *)a->name))
2056 continue;
2058 pa = xrealloc (attrlist, (i + 2) * sizeof (char *));
2059 if (!pa)
2061 if (attrlist)
2062 strv_free (attrlist);
2064 log_write ("%s(%i): %s", __FILE__, __LINE__,
2065 pwmd_strerror (GPG_ERR_ENOMEM));
2066 return GPG_ERR_ENOMEM;
2069 attrlist = pa;
2070 an = a->children;
2071 attrlist[i] = str_asprintf ("%s %s", (char *) a->name, an && an->content
2072 ? (char *)an->content : "");
2074 if (!attrlist[i])
2076 strv_free (attrlist);
2077 log_write ("%s(%i): %s", __FILE__, __LINE__,
2078 pwmd_strerror (GPG_ERR_ENOMEM));
2079 return GPG_ERR_ENOMEM;
2082 attrlist[++i] = NULL;
2085 if (!attrlist)
2086 return GPG_ERR_NO_DATA;
2088 if (!target)
2090 r = xml_resolve_path (client, client->doc, (xmlChar *)args[0], NULL, &rc);
2091 if (!RESUMABLE_ERROR (rc))
2093 strv_free (attrlist);
2094 return rc;
2096 else if (!rc && r != n)
2098 target = 1;
2099 n = r;
2100 goto again;
2103 rc = 0;
2106 line = strv_join ("\n", attrlist);
2107 if (!line)
2109 log_write ("%s(%i): %s", __FILE__, __LINE__,
2110 pwmd_strerror (GPG_ERR_ENOMEM));
2111 strv_free (attrlist);
2112 return GPG_ERR_ENOMEM;
2115 pthread_cleanup_push ((void *)xfree, line);
2116 pthread_cleanup_push ((void *)req_free, attrlist);
2117 rc = xfer_data (ctx, line, strlen (line));
2118 pthread_cleanup_pop (1);
2119 pthread_cleanup_pop (1);
2120 return rc;
2124 * args[0] - attribute
2125 * args[1] - element path
2127 static gpg_error_t
2128 attribute_delete (struct client_s *client, char **args)
2130 gpg_error_t rc;
2131 xmlNodePtr n;
2133 if (!args || !args[0] || !*args[0] || !args[1] || !*args[1])
2134 return GPG_ERR_SYNTAX;
2136 if (!strcmp (args[0], "_name") || !strcmp (args[0], "target"))
2137 return GPG_ERR_INV_ATTR;
2139 rc = copy_on_write (client);
2140 if (rc)
2141 return rc;
2143 if (!xml_reserved_attribute (args[0]))
2144 n = xml_resolve_path (client, client->doc, (xmlChar *)args[1], NULL, &rc);
2145 else
2147 struct xml_request_s *req;
2149 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
2150 if (rc)
2151 return rc;
2153 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2154 xml_free_request (req);
2157 if (!rc)
2158 rc = xml_is_element_owner (client, n);
2160 if (!rc)
2161 rc = xml_delete_attribute (client, n, (xmlChar *) args[0]);
2163 return rc;
2167 * Creates the "target" attribute. When other commands encounter an element
2168 * with this attribute they follow the "target" after appending remaining
2169 * elements from the original element path to the target. The exception is the
2170 * ATTR command that operates on the element itself (for reserved attribute
2171 * names) and not the target.
2173 * If the source element path doesn't exist when using 'ATTR SET target', it is
2174 * created, but the destination element path must exist. This is simliar to the
2175 * ls(1) command: ln -s src dst.
2177 * args[0] - source element path
2178 * args[1] - destination element path
2180 static gpg_error_t
2181 set_target_attribute (struct client_s *client, char **args)
2183 struct xml_request_s *req = NULL;
2184 char **src, **dst;
2185 gpg_error_t rc;
2186 xmlNodePtr n;
2188 if (!args || !args[0] || !args[1])
2189 return GPG_ERR_SYNTAX;
2191 src = str_split (args[0], "\t", 0);
2192 if (!src)
2193 return GPG_ERR_SYNTAX;
2195 if (!xml_valid_element_path (src, 0))
2197 strv_free (src);
2198 return GPG_ERR_INV_VALUE;
2201 dst = str_split (args[1], "\t", 0);
2202 if (!dst)
2204 strv_free (src);
2205 return GPG_ERR_SYNTAX;
2208 rc = copy_on_write (client);
2209 if (rc)
2210 goto fail;
2212 // Be sure the destination element path exists. */
2213 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
2214 if (rc)
2215 goto fail;
2217 (void)xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2218 if (rc && rc != GPG_ERR_EACCES)
2219 goto fail;
2221 xml_free_request (req);
2222 req = NULL;
2224 if (!strcmp (args[0], args[1]))
2226 rc = GPG_ERR_EEXIST;
2227 goto fail;
2230 rc = xml_new_request (client, args[0], XML_CMD_ATTR_TARGET, &req);
2231 if (rc)
2232 goto fail;
2234 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2235 if (rc && rc != GPG_ERR_EACCES)
2236 goto fail;
2238 if (!rc)
2240 rc = xml_add_attribute (client, n, "target", args[1]);
2241 if (!rc)
2242 rc = xml_unlink_node (client, n->children);
2245 fail:
2246 strv_free (src);
2247 strv_free (dst);
2248 xml_free_request (req);
2249 return rc;
2253 * args[0] - attribute
2254 * args[1] - element path
2256 static gpg_error_t
2257 attribute_get (assuan_context_t ctx, char **args)
2259 struct client_s *client = assuan_get_pointer (ctx);
2260 xmlNodePtr n;
2261 xmlChar *a;
2262 gpg_error_t rc;
2263 struct xml_request_s *req;
2265 if (!args || !args[0] || !*args[0] || !args[1] || !*args[1])
2266 return GPG_ERR_SYNTAX;
2268 if (!xml_reserved_attribute (args[0]))
2269 n = xml_resolve_path (client, client->doc, (xmlChar *)args[1], NULL, &rc);
2270 else
2272 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
2273 if (rc)
2274 return rc;
2276 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2277 xml_free_request (req);
2280 if (rc)
2281 return rc;
2283 a = xmlGetProp (n, (xmlChar *) args[0]);
2284 if (!a)
2285 return GPG_ERR_NOT_FOUND;
2287 pthread_cleanup_push ((void *)xmlFree, a);
2289 if (*a)
2290 rc = xfer_data (ctx, (char *) a, xmlStrlen (a));
2291 else
2292 rc = GPG_ERR_NO_DATA;
2294 pthread_cleanup_pop (1);
2295 return rc;
2299 * args[0] - attribute
2300 * args[1] - element path
2301 * args[2] - value
2303 static gpg_error_t
2304 attribute_set (struct client_s *client, char **args)
2306 struct xml_request_s *req;
2307 gpg_error_t rc;
2308 xmlNodePtr n;
2310 if (!args || !args[0] || !args[1])
2311 return GPG_ERR_SYNTAX;
2314 * Reserved attribute names.
2316 if (!strcmp (args[0], "_name")) // Use the RENAME command instead
2317 return GPG_ERR_INV_ATTR;
2318 else if (!strcmp (args[0], "target"))
2319 return set_target_attribute (client, args + 1);
2320 else if (!xml_valid_attribute (args[0]))
2321 return GPG_ERR_INV_VALUE;
2323 if (!xml_valid_attribute_value (args[2]))
2324 return GPG_ERR_INV_VALUE;
2326 rc = copy_on_write (client);
2327 if (rc)
2328 return rc;
2330 if (!xml_reserved_attribute (args[0]))
2332 n = xml_resolve_path (client, client->doc, (xmlChar *)args[1], NULL, &rc);
2333 if (!rc)
2335 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
2336 if (!rc)
2338 rc = xml_check_recursion (client, req);
2339 xml_free_request (req);
2343 else
2345 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
2346 if (rc)
2347 return rc;
2349 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2350 xml_free_request (req);
2353 if (!rc)
2354 rc = xml_is_element_owner (client, n);
2356 if (!rc)
2357 rc = xml_add_attribute (client, n, args[0], args[2]);
2359 return rc;
2363 * req[0] - command
2364 * req[1] - attribute name or element path if command is LIST
2365 * req[2] - element path
2366 * req[2] - element path or value
2369 static gpg_error_t
2370 do_attr (assuan_context_t ctx, char *line)
2372 struct client_s *client = assuan_get_pointer (ctx);
2373 gpg_error_t rc = 0;
2374 char **req;
2376 req = str_split (line, " ", 4);
2377 if (!req || !req[0] || !req[1])
2379 strv_free (req);
2380 return GPG_ERR_SYNTAX;
2383 pthread_cleanup_push ((void *)req_free, req);
2385 if (strcasecmp (req[0], "SET") == 0)
2386 rc = attribute_set (client, req + 1);
2387 else if (strcasecmp (req[0], "GET") == 0)
2388 rc = attribute_get (ctx, req + 1);
2389 else if (strcasecmp (req[0], "DELETE") == 0)
2390 rc = attribute_delete (client, req + 1);
2391 else if (strcasecmp (req[0], "LIST") == 0)
2392 rc = attribute_list (ctx, req + 1);
2393 else
2394 rc = GPG_ERR_SYNTAX;
2396 client->flags &= ~(FLAG_ACL_IGNORE|FLAG_ACL_ERROR);
2397 pthread_cleanup_pop (1);
2398 return rc;
2401 static gpg_error_t
2402 attr_command (assuan_context_t ctx, char *line)
2404 struct client_s *client = assuan_get_pointer (ctx);
2405 gpg_error_t rc;
2406 struct argv_s *args[] = {
2407 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2408 NULL
2411 rc = parse_options (&line, args, client, 1);
2412 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2413 rc = GPG_ERR_SYNTAX;
2414 if (rc)
2415 return send_error (ctx, rc);
2417 if (client->opts & OPT_INQUIRE)
2419 unsigned char *result;
2420 size_t len;
2422 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2423 if (rc)
2424 return send_error (ctx, rc);
2426 pthread_cleanup_push ((void *)xfree, result);
2427 rc = do_attr (ctx, (char *)result);
2428 pthread_cleanup_pop (1);
2430 else
2431 rc = do_attr (ctx, line);
2433 return send_error (ctx, rc);
2436 static gpg_error_t
2437 parse_iscached_opt_lock (void *data, void *value)
2439 struct client_s *client = data;
2441 (void) value;
2442 client->opts |= OPT_LOCK;
2443 return 0;
2446 static gpg_error_t
2447 parse_iscached_opt_agent (void *data, void *value)
2449 struct client_s *client = data;
2451 (void) value;
2452 client->opts |= OPT_CACHE_AGENT;
2453 return 0;
2456 static gpg_error_t
2457 parse_iscached_opt_sign (void *data, void *value)
2459 struct client_s *client = data;
2461 (void) value;
2462 client->opts |= OPT_CACHE_SIGN;
2463 return 0;
2466 static gpg_error_t
2467 iscached_command (assuan_context_t ctx, char *line)
2469 struct client_s *client = assuan_get_pointer (ctx);
2470 gpg_error_t rc;
2471 int defer = 0;
2472 struct argv_s *args[] = {
2473 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_iscached_opt_lock},
2474 &(struct argv_s) {"agent", OPTION_TYPE_NOARG, parse_iscached_opt_agent},
2475 &(struct argv_s) {"sign", OPTION_TYPE_NOARG, parse_iscached_opt_sign},
2476 NULL
2479 if (!line || !*line)
2480 return send_error (ctx, GPG_ERR_SYNTAX);
2482 rc = parse_options (&line, args, client, 1);
2483 if (rc)
2484 return send_error (ctx, rc);
2485 else if (!valid_filename (line))
2486 return send_error (ctx, GPG_ERR_INV_VALUE);
2488 if (!(client->flags & FLAG_OPEN)
2489 && ((client->opts & OPT_CACHE_AGENT) || (client->opts & OPT_CACHE_SIGN)))
2490 return send_error (ctx, GPG_ERR_INV_STATE);
2492 rc = cache_iscached (line, &defer, (client->opts & OPT_CACHE_AGENT),
2493 (client->opts & OPT_CACHE_SIGN));
2494 if (!rc && defer)
2495 rc = GPG_ERR_NO_DATA;
2497 if (!rc)
2499 struct cache_data_s *cdata = cache_get_data (line, NULL);
2501 if (cdata)
2503 rc = validate_checksum (client, line, cdata, NULL, NULL);
2504 if (rc == GPG_ERR_CHECKSUM)
2505 rc = GPG_ERR_NO_DATA;
2509 if (client->opts & OPT_LOCK
2510 && (!rc || gpg_err_code (rc) == GPG_ERR_NO_DATA))
2512 gpg_error_t trc = rc;
2514 if (strcmp (line, client->filename))
2515 reset_client (client);
2517 xfree (client->filename);
2518 client->filename = str_dup (line);
2519 rc = do_lock (client, 1);
2520 if (!rc)
2521 rc = trc;
2524 return send_error (ctx, rc);
2527 static gpg_error_t
2528 clearcache_command (assuan_context_t ctx, char *line)
2530 struct client_s *client = assuan_get_pointer (ctx);
2531 gpg_error_t rc = 0, all_rc = 0;
2532 int i;
2533 int t;
2534 int all = 0;
2535 struct client_thread_s *once = NULL;
2536 unsigned count;
2538 cache_lock ();
2539 pthread_cleanup_push (cache_release_mutex, NULL);
2540 count = cache_file_count ();
2541 MUTEX_LOCK (&cn_mutex);
2542 pthread_cleanup_push ((void *)release_mutex_cb, &cn_mutex);
2544 if (!line || !*line)
2545 all = 1;
2547 t = slist_length (cn_thread_list);
2549 for (i = 0; i < t; i++)
2551 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2552 assuan_peercred_t peer;
2554 if (!thd->cl)
2555 continue;
2557 /* Lock each connected clients' file mutex to prevent any other client
2558 * from accessing the cache entry (the file mutex is locked upon
2559 * command startup). The cache for the entry is not cleared if the
2560 * file mutex is locked by another client to prevent this function
2561 * from blocking. Rather, it returns an error.
2563 if (all)
2565 if (thd->cl->filename)
2567 rc = do_validate_peer (ctx, thd->cl->filename, &peer);
2568 /* The current client doesn't have permission to open the other
2569 * filename do to "access" configuration parameter in a filename
2570 * section. Since we are clearning all cache entries the error
2571 * will be returned later during cache_clear(). */
2572 if (rc)
2574 rc = 0;
2575 continue;
2578 else // Idle client without opened file?
2579 continue;
2581 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->filename, -1, 0, -1);
2582 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2584 /* The current client owns the lock. */
2585 if (pthread_equal (pthread_self (), thd->tid))
2586 rc = 0;
2587 else
2589 if (cache_iscached (thd->cl->filename, NULL, 0, 0)
2590 == GPG_ERR_NO_DATA)
2592 rc = 0;
2593 continue;
2596 /* The cache entry will be cleared when the other client
2597 * disconnects and cache_timer_thread() does its thing. */
2598 cache_defer_clear (thd->cl->filename);
2601 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
2603 rc = 0;
2604 continue;
2607 if (!rc)
2609 rc = cache_clear (NULL, thd->cl->filename, 1, 0);
2610 cache_unlock_mutex (thd->cl->filename, 0);
2613 if (rc)
2614 all_rc = rc;
2616 rc = 0;
2618 else
2620 /* A single data filename was specified. Lock only this data file
2621 * mutex and free the cache entry. */
2622 rc = do_validate_peer (ctx, line, &peer);
2623 if (rc == GPG_ERR_FORBIDDEN)
2624 rc = peer_is_invoker (client);
2626 if (rc == GPG_ERR_EACCES)
2627 rc = GPG_ERR_FORBIDDEN;
2629 if (!rc && thd->cl->filename && !strcmp (thd->cl->filename , line))
2631 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->filename, -1, 0, -1);
2632 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2634 /* The current client owns the lock. */
2635 if (pthread_equal (pthread_self (), thd->tid))
2636 rc = 0;
2639 if (!rc)
2641 once = thd;
2642 rc = cache_clear (NULL, thd->cl->filename, 1, 0);
2643 cache_unlock_mutex (thd->cl->filename, 0);
2645 else
2646 cache_defer_clear (thd->cl->filename);
2648 /* Found a client with the opened file. The cache entry has been
2649 * either cleared (self) or defered to be cleared. */
2650 break;
2655 /* Only connected clients' cache entries have been cleared. Now clear any
2656 * remaining cache entries without clients but only if there wasn't an
2657 * error from above since this would defeat the locking check of the
2658 * remaining entries. */
2659 if (all && !all_rc && cache_file_count ())
2661 rc = cache_clear (client, NULL, 1, 0);
2662 if (rc == GPG_ERR_EACCES)
2663 rc = GPG_ERR_FORBIDDEN;
2666 /* No clients are using the specified file. */
2667 else if (!all_rc && !rc && !once)
2668 rc = cache_clear (NULL, line, 1, 0);
2670 /* Release the connection mutex. */
2671 pthread_cleanup_pop (1);
2673 if (!rc || (cache_file_count () && count != cache_file_count ()))
2674 send_status_all (STATUS_CACHE, NULL);
2676 /* Release the cache mutex. */
2677 pthread_cleanup_pop (1);
2679 /* One or more files were locked while clearing all cache entries. */
2680 if (all_rc)
2681 rc = all_rc;
2683 return send_error (ctx, rc);
2686 static gpg_error_t
2687 cachetimeout_command (assuan_context_t ctx, char *line)
2689 struct client_s *client = assuan_get_pointer (ctx);
2690 long timeout;
2691 char **req = str_split (line, " ", 0);
2692 char *p;
2693 gpg_error_t rc = 0;
2694 assuan_peercred_t peer;
2696 if (!req || !*req || !req[1] || !*req[1])
2698 strv_free (req);
2699 return send_error (ctx, GPG_ERR_SYNTAX);
2702 errno = 0;
2703 timeout = strtol (req[1], &p, 10);
2704 if (errno != 0 || *p || timeout < (long)-1)
2706 strv_free (req);
2707 return send_error (ctx, GPG_ERR_SYNTAX);
2710 rc = do_validate_peer (ctx, req[0], &peer);
2711 if (rc == GPG_ERR_FORBIDDEN)
2713 rc = peer_is_invoker (client);
2714 if (rc == GPG_ERR_EACCES)
2715 rc = GPG_ERR_FORBIDDEN;
2718 if (!rc)
2720 rc = cache_set_timeout (req[0], timeout);
2721 if (!rc || gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
2723 rc = 0;
2724 MUTEX_LOCK (&rcfile_mutex);
2725 config_set_long_param (&global_config, req[0], "cache_timeout",
2726 req[1]);
2727 MUTEX_UNLOCK (&rcfile_mutex);
2731 strv_free (req);
2732 return send_error (ctx, rc);
2735 static gpg_error_t
2736 dump_command (assuan_context_t ctx, char *line)
2738 xmlChar *xml;
2739 int len;
2740 struct client_s *client = assuan_get_pointer (ctx);
2741 gpg_error_t rc;
2743 if (disable_list_and_dump == 1)
2744 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2746 if (line && *line)
2747 return send_error (ctx, GPG_ERR_SYNTAX);
2749 rc = peer_is_invoker(client);
2750 if (rc)
2751 return send_error (ctx, rc);
2753 xmlDocDumpFormatMemory (client->doc, &xml, &len, 1);
2755 if (!xml)
2757 log_write ("%s(%i): %s", __FILE__, __LINE__,
2758 pwmd_strerror (GPG_ERR_ENOMEM));
2759 return send_error (ctx, GPG_ERR_ENOMEM);
2762 pthread_cleanup_push ((void *)xmlFree, xml);
2763 rc = xfer_data (ctx, (char *) xml, len);
2764 pthread_cleanup_pop (1);
2765 return send_error (ctx, rc);
2768 static gpg_error_t
2769 getconfig_command (assuan_context_t ctx, char *line)
2771 struct client_s *client = assuan_get_pointer (ctx);
2772 gpg_error_t rc = 0;
2773 char filename[255] = { 0 }, param[747] = { 0 };
2774 char *p, *tmp = NULL, *fp = client->filename, *paramp = line;
2776 if (!line || !*line)
2777 return send_error (ctx, GPG_ERR_SYNTAX);
2779 if (strchr (line, ' '))
2781 int ret = sscanf (line, " %254[^ ] %746c", filename, param);
2783 if (ret <= 0)
2784 return send_error (ctx, gpg_error_from_syserror());
2785 paramp = param;
2786 fp = filename;
2789 if (fp && !valid_filename (fp))
2790 return send_error (ctx, GPG_ERR_INV_VALUE);
2792 paramp = str_down (paramp);
2793 p = config_get_value (fp ? fp : "global", paramp);
2794 if (!p)
2795 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2797 tmp = expand_homedir (p);
2798 xfree (p);
2799 if (!tmp)
2801 log_write ("%s(%i): %s", __FILE__, __LINE__,
2802 pwmd_strerror (GPG_ERR_ENOMEM));
2803 return send_error (ctx, GPG_ERR_ENOMEM);
2806 p = tmp;
2807 pthread_cleanup_push ((void *)xfree, p);
2808 rc = xfer_data (ctx, p, strlen (p));
2809 pthread_cleanup_pop (1);
2810 return send_error (ctx, rc);
2813 struct xpath_s
2815 xmlXPathContextPtr xp;
2816 xmlXPathObjectPtr result;
2817 xmlBufferPtr buf;
2818 char **req;
2821 static void
2822 xpath_command_free (void *arg)
2824 struct xpath_s *xpath = arg;
2826 if (!xpath)
2827 return;
2829 req_free (xpath->req);
2831 if (xpath->buf)
2832 xmlBufferFree (xpath->buf);
2834 if (xpath->result)
2835 xmlXPathFreeObject (xpath->result);
2837 if (xpath->xp)
2838 xmlXPathFreeContext (xpath->xp);
2841 static gpg_error_t
2842 do_xpath (assuan_context_t ctx, char *line)
2844 gpg_error_t rc;
2845 struct client_s *client = assuan_get_pointer (ctx);
2846 struct xpath_s _x = { 0 };
2847 struct xpath_s *xpath = &_x;
2849 if (!line || !*line)
2850 return GPG_ERR_SYNTAX;
2852 if ((xpath->req = str_split (line, "\t", 2)) == NULL)
2854 if (strv_printf (&xpath->req, "%s", line) == 0)
2855 return GPG_ERR_ENOMEM;
2858 if (xpath->req[1])
2860 rc = copy_on_write (client);
2861 if (rc)
2862 goto fail;
2865 xpath->xp = xmlXPathNewContext (client->doc);
2866 if (!xpath->xp)
2868 rc = GPG_ERR_BAD_DATA;
2869 goto fail;
2872 xpath->result =
2873 xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2874 if (!xpath->result)
2876 rc = GPG_ERR_BAD_DATA;
2877 goto fail;
2880 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2882 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2883 goto fail;
2886 rc = xml_recurse_xpath_nodeset (client, client->doc,
2887 xpath->result->nodesetval,
2888 (xmlChar *) xpath->req[1], &xpath->buf, 0,
2889 NULL);
2890 if (rc)
2891 goto fail;
2892 else if (!xpath->req[1] && !xmlBufferLength (xpath->buf))
2894 rc = GPG_ERR_NO_DATA;
2895 goto fail;
2897 else if (xpath->req[1])
2899 rc = 0;
2900 goto fail;
2903 pthread_cleanup_push ((void *)xpath_command_free, &xpath);
2904 rc = xfer_data (ctx, (char *) xmlBufferContent (xpath->buf),
2905 xmlBufferLength (xpath->buf));
2906 pthread_cleanup_pop (0);
2907 fail:
2908 xpath_command_free (xpath);
2909 return rc;
2912 static gpg_error_t
2913 xpath_command (assuan_context_t ctx, char *line)
2915 struct client_s *client = assuan_get_pointer (ctx);
2916 gpg_error_t rc;
2917 struct argv_s *args[] = {
2918 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2919 NULL
2922 if (disable_list_and_dump == 1)
2923 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2925 rc = peer_is_invoker(client);
2926 if (rc)
2927 return send_error (ctx, rc);
2929 rc = parse_options (&line, args, client, 1);
2930 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2931 rc = GPG_ERR_SYNTAX;
2932 if (rc)
2933 return send_error (ctx, rc);
2935 if (client->opts & OPT_INQUIRE)
2937 unsigned char *result;
2938 size_t len;
2940 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2941 if (rc)
2942 return send_error (ctx, rc);
2944 pthread_cleanup_push ((void *)xfree, result);
2945 rc = do_xpath (ctx, (char *)result);
2946 pthread_cleanup_pop (1);
2948 else
2949 rc = do_xpath (ctx, line);
2951 return send_error (ctx, rc);
2954 static gpg_error_t
2955 do_xpathattr (assuan_context_t ctx, char *line)
2957 struct client_s *client = assuan_get_pointer (ctx);
2958 gpg_error_t rc;
2959 char **req = NULL;
2960 int cmd = 0; //SET
2961 struct xpath_s _x = { 0 };
2962 struct xpath_s *xpath = &_x;
2964 if (!line || !*line)
2965 return GPG_ERR_SYNTAX;
2967 if ((req = str_split (line, " ", 3)) == NULL)
2968 return GPG_ERR_ENOMEM;
2970 if (!req[0])
2972 rc = GPG_ERR_SYNTAX;
2973 goto fail;
2976 if (!strcasecmp (req[0], "SET"))
2977 cmd = 0;
2978 else if (!strcasecmp (req[0], "DELETE"))
2979 cmd = 1;
2980 else
2982 rc = GPG_ERR_SYNTAX;
2983 goto fail;
2986 if (!req[1] || !req[2])
2988 rc = GPG_ERR_SYNTAX;
2989 goto fail;
2992 if ((xpath->req = str_split (req[2], "\t", 3)) == NULL)
2994 rc = GPG_ERR_ENOMEM;
2995 goto fail;
2998 if (!xpath->req[0] || (!xpath->req[1] && !cmd) || (xpath->req[1] && cmd))
3000 rc = GPG_ERR_SYNTAX;
3001 goto fail;
3004 rc = copy_on_write (client);
3005 if (rc)
3006 goto fail;
3008 xpath->xp = xmlXPathNewContext (client->doc);
3009 if (!xpath->xp)
3011 rc = GPG_ERR_BAD_DATA;
3012 goto fail;
3015 xpath->result = xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
3016 if (!xpath->result)
3018 rc = GPG_ERR_BAD_DATA;
3019 goto fail;
3022 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
3024 rc = GPG_ERR_ELEMENT_NOT_FOUND;
3025 goto fail;
3028 rc = xml_recurse_xpath_nodeset (client, client->doc,
3029 xpath->result->nodesetval,
3030 (xmlChar *) xpath->req[1], &xpath->buf, cmd,
3031 (xmlChar *) req[1]);
3033 fail:
3034 xpath_command_free (xpath);
3035 strv_free (req);
3036 return rc;
3039 /* XPATHATTR SET|DELETE <name> <expression>[<TAB>[value]] */
3040 static gpg_error_t
3041 xpathattr_command (assuan_context_t ctx, char *line)
3043 struct client_s *client = assuan_get_pointer (ctx);
3044 gpg_error_t rc;
3045 struct argv_s *args[] = {
3046 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3047 NULL
3050 if (disable_list_and_dump == 1)
3051 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
3053 rc = peer_is_invoker(client);
3054 if (rc)
3055 return send_error (ctx, rc);
3057 rc = parse_options (&line, args, client, 1);
3058 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3059 rc = GPG_ERR_SYNTAX;
3060 if (rc)
3061 return send_error (ctx, rc);
3063 if (client->opts & OPT_INQUIRE)
3065 unsigned char *result;
3066 size_t len;
3068 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3069 if (rc)
3070 return send_error (ctx, rc);
3072 pthread_cleanup_push ((void *)xfree, result);
3073 rc = do_xpathattr (ctx, (char *)result);
3074 pthread_cleanup_pop (1);
3076 else
3077 rc = do_xpathattr (ctx, line);
3079 return send_error (ctx, rc);
3082 static gpg_error_t
3083 do_import (struct client_s *client, const char *root_element,
3084 unsigned char *content)
3086 xmlDocPtr doc = NULL;
3087 xmlNodePtr n = NULL, root;
3088 gpg_error_t rc = 0;
3089 struct string_s *str = NULL, *tstr = NULL;
3090 struct xml_request_s *req = NULL;
3092 if (!content || !*content)
3093 return GPG_ERR_SYNTAX;
3095 if (root_element)
3097 rc = xml_new_request (client, root_element, XML_CMD_STORE, &req);
3098 if (rc)
3100 xfree (content);
3101 return rc;
3104 if (!xml_valid_element_path (req->args, 0))
3106 xml_free_request (req);
3107 xfree (content);
3108 return GPG_ERR_INV_VALUE;
3112 str = string_new_content ((char *)content);
3113 tstr = string_prepend (str, "<pwmd>");
3114 if (tstr)
3116 str = tstr;
3117 tstr = string_append (str, "</pwmd>");
3118 if (!tstr)
3119 rc = GPG_ERR_ENOMEM;
3121 else
3122 rc = GPG_ERR_ENOMEM;
3124 if (rc)
3125 goto fail;
3127 doc = xmlReadDoc ((xmlChar *) str->str, NULL, "UTF-8", XML_PARSE_NOBLANKS);
3128 string_free (str, 1);
3129 if (!doc)
3131 rc = GPG_ERR_BAD_DATA;
3132 goto fail;
3135 root = xmlDocGetRootElement (doc);
3136 root = root->children;
3137 if (root->type != XML_ELEMENT_NODE)
3139 rc = GPG_ERR_BAD_DATA;
3140 goto fail;
3143 rc = xml_validate_import (client, root);
3144 if (rc)
3145 goto fail;
3147 if (req)
3149 /* Create the new specified root element path, if needed. */
3150 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc),
3151 &rc);
3152 if (rc)
3153 goto fail;
3155 /* Overwrite the children of the specified root element path. */
3156 (void)xml_unlink_node (client, n->children);
3157 n->children = NULL;
3159 else
3160 n = xmlDocGetRootElement (client->doc);
3162 if (n)
3164 xmlNodePtr copy;
3165 xmlChar *name = xml_attribute_value (root, (xmlChar *)"_name");
3167 if (!name)
3168 rc = GPG_ERR_BAD_DATA;
3169 else if (!req)
3171 /* No --root argument passed. Overwrite the current documents' root
3172 * element matching the root element of the imported data. */
3173 xml_free_request (req);
3174 req = NULL;
3175 rc = xml_new_request (client, (char *)name, XML_CMD_DELETE, &req);
3176 xmlFree (name);
3177 if (!rc)
3179 xmlNodePtr tmp;
3181 tmp = xml_find_elements (client, req,
3182 xmlDocGetRootElement (req->doc), &rc);
3183 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3184 goto fail;
3186 if (!rc)
3187 (void)xml_unlink_node (client, tmp);
3189 rc = 0;
3193 if (!rc)
3195 copy = xmlCopyNodeList (root);
3196 if (!copy)
3197 rc = GPG_ERR_ENOMEM;
3198 else
3200 n = xmlAddChildList (n, copy);
3201 if (!n)
3202 rc = GPG_ERR_ENOMEM;
3207 if (!rc && n && n->parent)
3208 rc = xml_update_element_mtime (client, n->parent);
3210 fail:
3211 xml_free_request (req);
3213 if (doc)
3214 xmlFreeDoc (doc);
3216 return rc;
3219 static gpg_error_t
3220 parse_import_opt_root (void *data, void *value)
3222 struct client_s *client = data;
3224 client->import_root = str_dup (value);
3225 return client->import_root ? 0 : GPG_ERR_ENOMEM;
3228 static gpg_error_t
3229 import_command (assuan_context_t ctx, char *line)
3231 gpg_error_t rc;
3232 struct client_s *client = assuan_get_pointer (ctx);
3233 unsigned char *result;
3234 size_t len;
3235 struct argv_s *args[] = {
3236 &(struct argv_s) {"root", OPTION_TYPE_ARG, parse_import_opt_root},
3237 NULL
3240 xfree (client->import_root);
3241 client->import_root = NULL;
3242 rc = parse_options (&line, args, client, 0);
3243 if (rc)
3244 return send_error (ctx, rc);
3246 rc = copy_on_write (client);
3247 if (rc)
3248 return send_error (ctx, rc);
3250 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3251 if (rc)
3253 xfree (client->import_root);
3254 client->import_root = NULL;
3255 return send_error (ctx, rc);
3258 rc = do_import (client, client->import_root, result);
3259 xfree (client->import_root);
3260 client->import_root = NULL;
3261 return send_error (ctx, rc);
3264 static gpg_error_t
3265 do_lock (struct client_s *client, int add)
3267 gpg_error_t rc = lock_file_mutex (client, add);
3269 if (!rc)
3270 client->flags |= FLAG_LOCK_CMD;
3272 return rc;
3275 static gpg_error_t
3276 lock_command (assuan_context_t ctx, char *line)
3278 struct client_s *client = assuan_get_pointer (ctx);
3279 gpg_error_t rc;
3281 if (line && *line)
3282 return send_error (ctx, GPG_ERR_SYNTAX);
3284 rc = do_lock (client, 0);
3285 return send_error (ctx, rc);
3288 static gpg_error_t
3289 unlock_command (assuan_context_t ctx, char *line)
3291 struct client_s *client = assuan_get_pointer (ctx);
3292 gpg_error_t rc;
3294 if (line && *line)
3295 return send_error (ctx, GPG_ERR_SYNTAX);
3297 rc = unlock_file_mutex (client, 0);
3298 return send_error (ctx, rc);
3301 static void
3302 get_set_env (const char *name, const char *value)
3304 if (value && *value)
3305 setenv (name, value, 1);
3306 else
3307 unsetenv (name);
3310 static gpg_error_t
3311 option_command (assuan_context_t ctx, char *line)
3313 struct client_s *client = assuan_get_pointer (ctx);
3314 gpg_error_t rc = 0;
3315 char namebuf[255] = { 0 };
3316 char *name = namebuf;
3317 char *value = NULL, *p, *tmp = NULL;
3319 p = strchr (line, '=');
3320 if (!p)
3322 strncpy (namebuf, line, sizeof(namebuf));
3323 namebuf[sizeof(namebuf)-1] = 0;
3325 else
3327 strncpy (namebuf, line, strlen (line)-strlen (p));
3328 namebuf[sizeof(namebuf)-1] = 0;
3329 value = p+1;
3332 log_write2 ("OPTION name='%s' value='%s'", name, value);
3334 if (strcasecmp (name, (char *) "lock-timeout") == 0)
3336 long n = 0;
3338 if (value)
3340 n = strtol (value, &tmp, 10);
3341 if (tmp && *tmp)
3342 return send_error (ctx, GPG_ERR_INV_VALUE);
3345 client->lock_timeout = n;
3347 else if (strcasecmp (name, (char *) "client-state") == 0)
3349 long n = 0;
3351 if (value)
3353 n = strtol (value, &tmp, 10);
3354 if ((tmp && *tmp) || (n < 0 || n > 1))
3355 return send_error (ctx, GPG_ERR_INV_VALUE);
3356 client->client_state = n;
3358 else
3359 client->client_state = 0;
3361 else if (strcasecmp (name, (char *) "NAME") == 0)
3363 if (value && strchr (value, ' '))
3364 rc = GPG_ERR_INV_VALUE;
3365 else
3367 tmp = pthread_getspecific (thread_name_key);
3368 pthread_setspecific (thread_name_key, NULL);
3369 xfree (tmp);
3371 MUTEX_LOCK (&cn_mutex);
3372 xfree (client->thd->name);
3373 client->thd->name = NULL;
3374 if (value && *value)
3376 pthread_setspecific (thread_name_key, str_dup (value));
3377 client->thd->name = str_dup (value);
3379 MUTEX_UNLOCK (&cn_mutex);
3382 else if (strcasecmp (name, "disable-pinentry") == 0)
3384 int n = 1;
3386 if (value && *value)
3388 n = (int) strtol (value, &tmp, 10);
3389 if (*tmp || n < 0 || n > 1)
3390 return send_error (ctx, GPG_ERR_INV_VALUE);
3393 if (n)
3394 client->flags |= FLAG_NO_PINENTRY;
3395 else
3396 client->flags &= ~FLAG_NO_PINENTRY;
3398 else if (strcasecmp (name, "ttyname") == 0)
3400 get_set_env ("GPG_TTY", value);
3402 else if (strcasecmp (name, "ttytype") == 0)
3404 get_set_env ("TERM", value);
3406 else if (strcasecmp (name, "display") == 0)
3408 get_set_env ("DISPLAY", value);
3410 else if (strcasecmp (name, "lc_messages") == 0)
3413 else if (strcasecmp (name, "lc_ctype") == 0)
3416 else if (strcasecmp (name, "desc") == 0)
3419 else if (strcasecmp (name, "pinentry-timeout") == 0)
3422 else
3423 rc = GPG_ERR_UNKNOWN_OPTION;
3425 return send_error (ctx, rc);
3428 static gpg_error_t
3429 do_rename (assuan_context_t ctx, char *line)
3431 struct client_s *client = assuan_get_pointer (ctx);
3432 char **args, *p;
3433 xmlNodePtr src, dst;
3434 struct string_s *str = NULL, *tstr;
3435 struct xml_request_s *req;
3436 gpg_error_t rc;
3438 args = str_split (line, " ", 0);
3439 if (!args || strv_length (args) != 2)
3441 strv_free (args);
3442 return GPG_ERR_SYNTAX;
3445 if (!xml_valid_element ((xmlChar *) args[1]))
3447 strv_free (args);
3448 return GPG_ERR_INV_VALUE;
3451 rc = xml_new_request (client, args[0], XML_CMD_RENAME, &req);
3452 if (rc)
3454 strv_free (args);
3455 return rc;
3458 src = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3459 if (rc)
3460 goto fail;
3462 rc = xml_is_element_owner (client, src);
3463 if (rc)
3464 goto fail;
3466 xmlChar *a = xmlGetProp (src, (xmlChar *) "_name");
3467 if (!a)
3469 rc = GPG_ERR_ENOMEM;
3470 goto fail;
3473 /* To prevent unwanted effects:
3475 * <element _name="a"><element _name="b"/></element>
3477 * RENAME a<TAB>b b
3479 if (xmlStrEqual (a, (xmlChar *) args[1]))
3481 xmlFree (a);
3482 rc = GPG_ERR_EEXIST;
3483 goto fail;
3486 xmlFree (a);
3487 str = string_new (args[0]);
3488 if (!str)
3490 rc = GPG_ERR_ENOMEM;
3491 goto fail;
3494 p = strrchr (str->str, '\t');
3495 if (p)
3496 tstr = string_truncate (str, strlen (str->str)-strlen (p));
3497 else
3498 tstr = string_truncate (str, 0);
3500 if (!tstr)
3502 string_free (str, 1);
3503 rc = GPG_ERR_ENOMEM;
3504 goto fail;
3507 str = tstr;
3508 tstr = string_append_printf (str, "%s%s", str->len ? "\t" : "", args[1]);
3509 if (!tstr)
3511 string_free (str, 1);
3512 rc = GPG_ERR_ENOMEM;
3513 goto fail;
3516 str = tstr;
3517 xml_free_request (req);
3518 rc = xml_new_request (client, str->str, XML_CMD_RENAME, &req);
3519 string_free (str, 1);
3520 if (rc)
3522 req = NULL;
3523 goto fail;
3526 dst = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3527 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3528 goto fail;
3530 rc = 0;
3532 /* Target may exist:
3534 * <element _name="a"/>
3535 * <element _name="b" target="a"/>
3537 * RENAME b a
3539 if (src == dst)
3541 rc = GPG_ERR_EEXIST;
3542 goto fail;
3545 if (dst)
3547 rc = xml_is_element_owner (client, dst);
3548 if (rc)
3549 goto fail;
3551 rc = xml_add_attribute (client, src, "_name", args[1]);
3552 if (!rc)
3553 xml_unlink_node (client, dst);
3555 else
3556 rc = xml_add_attribute (client, src, "_name", args[1]);
3558 fail:
3559 xml_free_request (req);
3560 strv_free (args);
3561 return rc;
3564 static gpg_error_t
3565 rename_command (assuan_context_t ctx, char *line)
3567 struct client_s *client = assuan_get_pointer (ctx);
3568 gpg_error_t rc;
3569 struct argv_s *args[] = {
3570 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3571 NULL
3574 rc = parse_options (&line, args, client, 1);
3575 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3576 rc = GPG_ERR_SYNTAX;
3577 if (rc)
3578 return send_error (ctx, rc);
3580 rc = copy_on_write (client);
3581 if (rc)
3582 return send_error (ctx, rc);
3584 if (client->opts & OPT_INQUIRE)
3586 unsigned char *result;
3587 size_t len;
3589 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3590 if (rc)
3591 return send_error (ctx, rc);
3593 pthread_cleanup_push ((void *)xfree, result);
3594 rc = do_rename (ctx, (char *)result);
3595 pthread_cleanup_pop (1);
3597 else
3598 rc = do_rename (ctx, line);
3600 return send_error (ctx, rc);
3603 static gpg_error_t
3604 do_copy (assuan_context_t ctx, char *line)
3606 struct client_s *client = assuan_get_pointer (ctx);
3607 char **args, **targs;
3608 xmlNodePtr src, dst, tree = NULL;
3609 struct xml_request_s *req;
3610 gpg_error_t rc;
3612 args = str_split (line, " ", 0);
3613 if (!args || strv_length (args) != 2)
3615 strv_free (args);
3616 return GPG_ERR_SYNTAX;
3619 targs = str_split (args[1], "\t", 0);
3620 if (!targs)
3622 strv_free (args);
3623 return GPG_ERR_SYNTAX;
3626 if (!xml_valid_element_path (targs, 0))
3628 strv_free (args);
3629 strv_free (targs);
3630 return GPG_ERR_INV_VALUE;
3632 strv_free (targs);
3634 rc = xml_new_request (client, args[0], XML_CMD_NONE, &req);
3635 if (rc)
3637 strv_free (args);
3638 return rc;
3641 src = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3642 if (rc)
3643 goto fail;
3645 tree = xmlCopyNodeList (src);
3646 if (!tree)
3648 rc = GPG_ERR_ENOMEM;
3649 goto fail;
3652 xml_free_request (req);
3653 /* Create the destination element path if it does not exist. */
3654 rc = xml_new_request (client, args[1], XML_CMD_STORE, &req);
3655 if (rc)
3657 req = NULL;
3658 goto fail;
3661 dst = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3662 if (rc)
3663 goto fail;
3665 rc = xml_is_element_owner (client, dst);
3666 if (rc)
3667 goto fail;
3669 rc = xml_validate_target (client, req->doc, args[1], src);
3670 if (rc || src == dst)
3672 rc = rc ? rc : GPG_ERR_EEXIST;
3673 goto fail;
3676 /* Merge any attributes from the src node to the initial dst node. */
3677 for (xmlAttrPtr attr = tree->properties; attr; attr = attr->next)
3679 if (xmlStrEqual (attr->name, (xmlChar *) "_name"))
3680 continue;
3682 xmlAttrPtr a = xmlHasProp (dst, attr->name);
3683 if (a)
3684 xmlRemoveProp (a);
3686 xmlChar *tmp = xmlNodeGetContent (attr->children);
3687 xmlNewProp (dst, attr->name, tmp);
3688 xmlFree (tmp);
3689 /* Create the default attributes. */
3690 rc = xml_add_attribute (client, dst, NULL, NULL);
3693 xmlNodePtr n = dst->children;
3694 (void)xml_unlink_node (client, n);
3695 dst->children = NULL;
3697 if (tree->children)
3699 n = xmlCopyNodeList (tree->children);
3700 if (!n)
3702 rc = GPG_ERR_ENOMEM;
3703 goto fail;
3706 n = xmlAddChildList (dst, n);
3707 if (!n)
3709 rc = GPG_ERR_ENOMEM;
3710 goto fail;
3713 rc = xml_update_element_mtime (client, xmlDocGetRootElement (client->doc)
3714 == dst->parent ? dst : dst->parent);
3717 fail:
3718 if (tree)
3719 (void)xml_unlink_node (client, tree);
3721 xml_free_request (req);
3722 strv_free (args);
3723 return rc;
3726 static gpg_error_t
3727 copy_command (assuan_context_t ctx, char *line)
3729 struct client_s *client = assuan_get_pointer (ctx);
3730 gpg_error_t rc;
3731 struct argv_s *args[] = {
3732 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3733 NULL
3736 rc = parse_options (&line, args, client, 1);
3737 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3738 rc = GPG_ERR_SYNTAX;
3739 if (rc)
3740 return send_error (ctx, rc);
3742 rc = copy_on_write (client);
3743 if (rc)
3744 return send_error (ctx, rc);
3746 if (client->opts & OPT_INQUIRE)
3748 unsigned char *result;
3749 size_t len;
3751 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3752 if (rc)
3753 return send_error (ctx, rc);
3755 pthread_cleanup_push ((void *)xfree, result);
3756 rc = do_copy (ctx, (char *)result);
3757 pthread_cleanup_pop (1);
3759 else
3760 rc = do_copy (ctx, line);
3762 return send_error (ctx, rc);
3765 static gpg_error_t
3766 do_move (assuan_context_t ctx, char *line)
3768 struct client_s *client = assuan_get_pointer (ctx);
3769 char **args;
3770 xmlNodePtr src, dst;
3771 struct xml_request_s *req;
3772 gpg_error_t rc;
3774 args = str_split (line, " ", 0);
3775 if (!args || strv_length (args) != 2)
3777 strv_free (args);
3778 return GPG_ERR_SYNTAX;
3781 if (*args[1])
3783 char **targs = str_split (args[1], "\t", 0);
3784 if (!targs)
3786 strv_free (args);
3787 return GPG_ERR_ENOMEM;
3790 if (!xml_valid_element_path (targs, 0))
3792 strv_free (targs);
3793 strv_free (args);
3794 return GPG_ERR_INV_VALUE;
3797 strv_free (targs);
3800 rc = xml_new_request (client, args[0], XML_CMD_MOVE, &req);
3801 if (rc)
3803 strv_free (args);
3804 return rc;
3807 src = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3808 if (rc)
3809 goto fail;
3811 rc = xml_is_element_owner (client, src);
3812 if (rc)
3813 goto fail;
3815 xml_free_request (req);
3816 req = NULL;
3817 if (*args[1])
3819 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
3820 if (rc)
3821 goto fail;
3823 dst = xml_find_elements (client, req, xmlDocGetRootElement (req->doc),
3824 &rc);
3826 else
3827 dst = xmlDocGetRootElement (client->doc);
3829 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3830 goto fail;
3832 rc = 0;
3834 for (xmlNodePtr n = dst; n; n = n->parent)
3836 if (n == src)
3838 rc = GPG_ERR_EEXIST;
3839 goto fail;
3843 if (dst)
3845 xmlChar *a = xml_attribute_value (src, (xmlChar *) "_name");
3846 xmlNodePtr dup = xml_find_element (client, dst->children, (char *) a, &rc);
3848 xmlFree (a);
3849 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3850 goto fail;
3852 rc = 0;
3854 if (dup)
3856 if (dup == src)
3858 rc = GPG_ERR_EEXIST;
3859 goto fail;
3862 if (dst == xmlDocGetRootElement (client->doc))
3864 xmlNodePtr n = src;
3865 int match = 0;
3867 while (n->parent && n->parent != dst)
3868 n = n->parent;
3870 a = xml_attribute_value (n, (xmlChar *) "_name");
3871 xmlChar *b = xml_attribute_value (src, (xmlChar *) "_name");
3873 if (xmlStrEqual (a, b))
3875 match = 1;
3876 xmlUnlinkNode (src);
3877 (void)xml_unlink_node (client, n);
3880 xmlFree (a);
3881 xmlFree (b);
3883 if (!match)
3884 (void)xml_unlink_node (client, dup);
3886 else
3887 xmlUnlinkNode (dup);
3891 if (!dst && req && req->args && *req->args)
3893 struct xml_request_s *nreq = NULL;
3894 xmlChar *name = xml_attribute_value (src, (xmlChar *) "_name");
3896 if (src->parent == xmlDocGetRootElement (client->doc)
3897 && !strcmp ((char *) name, *req->args))
3899 xmlFree (name);
3900 rc = GPG_ERR_EEXIST;
3901 goto fail;
3904 xmlFree (name);
3905 rc = xml_new_request (client, args[1], XML_CMD_STORE, &nreq);
3906 if (!rc)
3908 dst = xml_find_elements (client, nreq,
3909 xmlDocGetRootElement (nreq->doc), &rc);
3910 xml_free_request (nreq);
3913 if (rc)
3914 goto fail;
3917 xml_update_element_mtime (client, src->parent);
3918 xmlUnlinkNode (src);
3920 dst = xmlAddChildList (dst, src);
3921 if (!dst)
3922 rc = GPG_ERR_ENOMEM;
3923 else
3924 xml_update_element_mtime (client, dst->parent);
3926 fail:
3927 xml_free_request (req);
3928 strv_free (args);
3929 return rc;
3932 static gpg_error_t
3933 move_command (assuan_context_t ctx, char *line)
3935 struct client_s *client = assuan_get_pointer (ctx);
3936 gpg_error_t rc;
3937 struct argv_s *args[] = {
3938 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3939 NULL
3942 rc = parse_options (&line, args, client, 1);
3943 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3944 rc = GPG_ERR_SYNTAX;
3945 if (rc)
3946 return send_error (ctx, rc);
3948 rc = copy_on_write (client);
3949 if (rc)
3950 return send_error (ctx, rc);
3952 if (client->opts & OPT_INQUIRE)
3954 unsigned char *result;
3955 size_t len;
3957 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3958 if (rc)
3959 return send_error (ctx, rc);
3961 pthread_cleanup_push ((void *)xfree, result);
3962 rc = do_move (ctx, (char *)result);
3963 pthread_cleanup_pop (1);
3965 else
3966 rc = do_move (ctx, line);
3968 return send_error (ctx, rc);
3971 static gpg_error_t
3972 ls_command (assuan_context_t ctx, char *line)
3974 gpg_error_t rc;
3975 char *tmp;
3976 char *dir;
3977 DIR *d;
3978 char *list = NULL;
3979 #ifdef HAVE_READDIR_R
3980 size_t len;
3981 struct dirent *cur = NULL, *p;
3982 #else
3983 struct dirent *cur = NULL;
3984 #endif
3986 if (line && *line)
3987 return send_error (ctx, GPG_ERR_SYNTAX);
3989 tmp = str_asprintf ("%s/data", homedir);
3990 dir = expand_homedir (tmp);
3991 xfree (tmp);
3992 if (!dir)
3993 return send_error (ctx, GPG_ERR_ENOMEM);
3995 d = opendir (dir);
3996 rc = gpg_error_from_errno (errno);
3998 if (!d)
4000 xfree (dir);
4001 return send_error (ctx, rc);
4004 #ifdef HAVE_READDIR_R
4005 len = offsetof (struct dirent, d_name) + pathconf (dir, _PC_NAME_MAX) + 1;
4006 p = xmalloc (len);
4007 if (!p)
4009 xfree (dir);
4010 closedir (d);
4011 return send_error (ctx, GPG_ERR_ENOMEM);
4013 pthread_cleanup_push (xfree, p);
4014 #endif
4016 pthread_cleanup_push ((void *)closedir, d);
4017 xfree (dir);
4018 rc = 0;
4020 #ifdef HAVE_READDIR_R
4021 while (!readdir_r (d, p, &cur) && cur)
4022 #else
4023 while ((cur = readdir (d)))
4024 #endif
4026 rc = open_check_file (cur->d_name, NULL, NULL, 1);
4027 if (rc)
4028 continue;
4030 tmp = str_asprintf ("%s%s\n", list ? list : "", cur->d_name);
4031 if (!tmp)
4033 if (list)
4034 xfree (list);
4036 rc = GPG_ERR_ENOMEM;
4037 break;
4040 xfree (list);
4041 list = tmp;
4044 pthread_cleanup_pop (1); // closedir (d)
4045 #ifdef HAVE_READDIR_R
4046 pthread_cleanup_pop (1); // xfree (p)
4047 #endif
4049 if (rc)
4050 return send_error (ctx, rc);
4052 if (!list)
4053 return send_error (ctx, GPG_ERR_NO_DATA);
4055 list[strlen (list) - 1] = 0;
4056 pthread_cleanup_push (xfree, list);
4057 rc = xfer_data (ctx, list, strlen (list));
4058 pthread_cleanup_pop (1);
4059 return send_error (ctx, rc);
4062 static gpg_error_t
4063 bye_notify (assuan_context_t ctx, char *line)
4065 struct client_s *cl = assuan_get_pointer (ctx);
4066 gpg_error_t ret = 0;
4068 (void)line;
4069 update_client_state (cl, CLIENT_STATE_DISCON);
4071 #ifdef WITH_GNUTLS
4072 cl->disco = 1;
4073 if (cl->thd->remote)
4075 int rc;
4079 struct timeval tv = { 0, 50000 };
4081 rc = gnutls_bye (cl->thd->tls->ses, GNUTLS_SHUT_RDWR);
4082 if (rc == GNUTLS_E_AGAIN)
4083 select (0, NULL, NULL, NULL, &tv);
4085 while (rc == GNUTLS_E_AGAIN);
4087 #endif
4089 /* This will let assuan_process_next() return. */
4090 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
4092 cl->last_rc = gpg_error_from_errno (errno);
4093 ret = cl->last_rc;
4096 cl->last_rc = 0; // BYE command result
4097 return ret;
4100 static gpg_error_t
4101 reset_notify (assuan_context_t ctx, char *line)
4103 struct client_s *client = assuan_get_pointer (ctx);
4105 (void)line;
4106 if (client)
4107 reset_client (client);
4109 return 0;
4113 * This is called before every Assuan command.
4115 static gpg_error_t
4116 command_startup (assuan_context_t ctx, const char *name)
4118 struct client_s *client = assuan_get_pointer (ctx);
4119 gpg_error_t rc;
4120 struct command_table_s *cmd = NULL;
4122 log_write2 ("command='%s'", name);
4123 client->last_rc = client->opts = 0;
4125 for (int i = 0; command_table[i]; i++)
4127 if (!strcasecmp (name, command_table[i]->name))
4129 if (command_table[i]->ignore_startup)
4130 return 0;
4131 cmd = command_table[i];
4132 break;
4136 if (!cmd)
4137 return GPG_ERR_UNKNOWN_COMMAND;
4139 client->last_rc = rc = gpg_error (file_modified (client, cmd));
4140 if (!rc)
4141 update_client_state (client, CLIENT_STATE_COMMAND);
4143 return rc;
4147 * This is called after every Assuan command.
4149 static void
4150 command_finalize (assuan_context_t ctx, gpg_error_t rc)
4152 struct client_s *client = assuan_get_pointer (ctx);
4154 if (!(client->flags & FLAG_LOCK_CMD))
4155 unlock_file_mutex (client, 0);
4157 unlock_flock (&client->flock_fd);
4158 log_write2 (_("command completed: rc=%u"), rc ? rc : client->last_rc);
4159 client->last_rc = gpg_error (GPG_ERR_UNKNOWN_COMMAND);
4160 #ifdef WITH_GNUTLS
4161 client->thd->buffer_timeout = client->thd->last_buffer_size = 0;
4162 #endif
4163 if (client->thd->state != CLIENT_STATE_DISCON)
4164 update_client_state (client, CLIENT_STATE_IDLE);
4167 static gpg_error_t
4168 parse_help_opt_html (void *data, void *value)
4170 struct client_s *client = data;
4172 (void) value;
4173 client->opts |= OPT_HTML;
4174 return 0;
4177 static gpg_error_t
4178 help_command (assuan_context_t ctx, char *line)
4180 gpg_error_t rc;
4181 int i;
4182 struct client_s *client = assuan_get_pointer (ctx);
4183 struct argv_s *args[] = {
4184 &(struct argv_s) {"html", OPTION_TYPE_NOARG, parse_help_opt_html},
4185 NULL
4188 rc = parse_options (&line, args, client, 1);
4189 if (rc)
4190 return send_error (ctx, rc);
4192 if (!line || !*line)
4194 char *tmp;
4195 char *help = str_dup (_("Usage: HELP [--html] [<COMMAND>]\n"
4196 "For commands that take an element path as an argument, each element is "
4197 "separated with an ASCII @key{TAB} character (ASCII 0x09)."
4198 "@*@*COMMANDS:"));
4200 for (i = 0; command_table[i]; i++)
4202 if (!command_table[i]->help)
4203 continue;
4205 /* @npxref{} won't put a "See " or "see " in front of the command.
4206 * It's not a texinfo command but needed for --html. */
4207 tmp = str_asprintf ("%s %s%s%s", help,
4208 client->opts & OPT_HTML ? "@npxref{" : "",
4209 command_table[i]->name,
4210 client->opts & OPT_HTML ? "}" : "");
4211 xfree (help);
4212 help = tmp;
4215 tmp = strip_texi_and_wrap (help, client->opts & OPT_HTML);
4216 xfree (help);
4217 pthread_cleanup_push ((void *)xfree, tmp);
4218 rc = xfer_data (ctx, tmp, strlen (tmp));
4219 pthread_cleanup_pop (1);
4220 return send_error (ctx, rc);
4223 for (i = 0; command_table[i]; i++)
4225 if (!strcasecmp (line, command_table[i]->name))
4227 char *help, *tmp;
4229 if (!command_table[i]->help)
4230 break;
4232 help = strip_texi_and_wrap (command_table[i]->help,
4233 client->opts & OPT_HTML);
4234 tmp = str_asprintf ("%s%s",
4235 (client->opts & OPT_HTML) ? "" : _("Usage: "),
4236 help);
4237 xfree (help);
4238 pthread_cleanup_push ((void *)xfree, tmp);
4239 rc = xfer_data (ctx, tmp, strlen (tmp));
4240 pthread_cleanup_pop (1);
4241 return send_error (ctx, rc);
4245 return send_error (ctx, GPG_ERR_INV_NAME);
4248 static void
4249 new_command (const char *name, int ignore, int unlock, int flock_type,
4250 gpg_error_t (*handler) (assuan_context_t, char *),
4251 const char *help)
4253 int i = 0;
4254 struct command_table_s **tmp;
4256 if (command_table)
4257 for (i = 0; command_table[i]; i++);
4259 tmp = xrealloc (command_table, (i + 2) * sizeof (struct command_table_s *));
4260 assert (tmp);
4261 command_table = tmp;
4262 command_table[i] = xcalloc (1, sizeof (struct command_table_s));
4263 command_table[i]->name = name;
4264 command_table[i]->handler = handler;
4265 command_table[i]->ignore_startup = ignore;
4266 command_table[i]->unlock = unlock;
4267 command_table[i]->flock_type = flock_type;
4268 command_table[i++]->help = help;
4269 command_table[i] = NULL;
4272 void
4273 deinit_commands ()
4275 int i;
4277 for (i = 0; command_table[i]; i++)
4278 xfree (command_table[i]);
4280 xfree (command_table);
4283 static int
4284 sort_commands (const void *arg1, const void *arg2)
4286 struct command_table_s *const *a = arg1;
4287 struct command_table_s *const *b = arg2;
4289 if (!*a || !*b)
4290 return 0;
4291 else if (*a && !*b)
4292 return 1;
4293 else if (!*a && *b)
4294 return -1;
4296 return strcmp ((*a)->name, (*b)->name);
4299 static gpg_error_t
4300 passwd_command (assuan_context_t ctx, char *line)
4302 struct client_s *client = assuan_get_pointer (ctx);
4303 gpg_error_t rc;
4305 (void)line;
4306 rc = peer_is_invoker (client);
4307 if (rc == GPG_ERR_EACCES)
4308 return send_error (ctx, GPG_ERR_FORBIDDEN);
4309 else if (rc)
4310 return send_error (ctx, rc);
4312 if (client->flags & FLAG_NEW)
4313 return send_error (ctx, GPG_ERR_INV_STATE);
4315 client->crypto->keyfile = config_get_string (client->filename,
4316 "passphrase_file");
4317 rc = crypto_init_ctx (client->crypto, client->flags & FLAG_NO_PINENTRY,
4318 client->crypto->keyfile);
4319 if (rc)
4320 return send_error (ctx, rc);
4322 if (!rc)
4323 rc = crypto_passwd (client, client->crypto);
4325 crypto_free_non_keys (client->crypto);
4326 return send_error (ctx, rc);
4329 static gpg_error_t
4330 parse_opt_data (void *data, void *value)
4332 struct client_s *client = data;
4334 (void) value;
4335 client->opts |= OPT_DATA;
4336 return 0;
4339 static gpg_error_t
4340 send_client_list (assuan_context_t ctx)
4342 struct client_s *client = assuan_get_pointer (ctx);
4343 gpg_error_t rc = 0;
4345 if (client->opts & OPT_VERBOSE)
4347 unsigned i, t;
4348 char **list = NULL;
4349 char *line;
4351 MUTEX_LOCK (&cn_mutex);
4352 pthread_cleanup_push ((void *)release_mutex_cb, &cn_mutex);
4353 t = slist_length (cn_thread_list);
4355 for (i = 0; i < t; i++)
4357 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
4358 char *tmp;
4360 if (thd->state == CLIENT_STATE_UNKNOWN)
4361 continue;
4363 tmp = build_client_info_line (thd, 0);
4364 if (tmp)
4366 char **l = strv_cat (list, tmp);
4367 if (!l)
4368 rc = GPG_ERR_ENOMEM;
4369 else
4370 list = l;
4372 else
4373 rc = GPG_ERR_ENOMEM;
4375 if (rc)
4377 strv_free (list);
4378 break;
4382 pthread_cleanup_pop (1);
4383 if (rc)
4384 return rc;
4386 line = strv_join ("\n", list);
4387 strv_free (list);
4388 pthread_cleanup_push ((void *)xfree, line);
4389 rc = xfer_data (ctx, line, strlen (line));
4390 pthread_cleanup_pop (1);
4391 return rc;
4394 if (client->opts & OPT_DATA)
4396 char buf[ASSUAN_LINELENGTH];
4398 MUTEX_LOCK (&cn_mutex);
4399 snprintf (buf, sizeof (buf), "%u", slist_length (cn_thread_list));
4400 MUTEX_UNLOCK (&cn_mutex);
4401 rc = xfer_data (ctx, buf, strlen (buf));
4403 else
4404 rc = send_status (ctx, STATUS_CLIENTS, NULL);
4406 return rc;
4409 static gpg_error_t
4410 getinfo_command (assuan_context_t ctx, char *line)
4412 struct client_s *client = assuan_get_pointer (ctx);
4413 gpg_error_t rc;
4414 char buf[ASSUAN_LINELENGTH];
4415 struct argv_s *args[] = {
4416 &(struct argv_s) {"data", OPTION_TYPE_NOARG, parse_opt_data},
4417 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_opt_verbose},
4418 NULL
4421 rc = parse_options (&line, args, client, 1);
4422 if (rc)
4423 return send_error (ctx, rc);
4425 if (!strcasecmp (line, "clients"))
4427 rc = send_client_list (ctx);
4429 else if (!strcasecmp (line, "cache"))
4431 if (client->opts & OPT_DATA)
4433 snprintf (buf, sizeof (buf), "%u", cache_file_count ());
4434 rc = xfer_data (ctx, buf, strlen (buf));
4436 else
4437 rc = send_status (ctx, STATUS_CACHE, NULL);
4439 else if (!strcasecmp (line, "pid"))
4441 pid_t pid = getpid ();
4443 snprintf (buf, sizeof (buf), "%u", pid);
4444 rc = xfer_data (ctx, buf, strlen (buf));
4446 else if (!strcasecmp (line, "version"))
4448 char *tmp = str_asprintf ("0x%06x %s", VERSION_HEX,
4449 #ifdef WITH_GNUTLS
4450 "GNUTLS "
4451 #endif
4452 #ifdef WITH_LIBACL
4453 "ACL "
4454 #endif
4455 "");
4456 pthread_cleanup_push (xfree, tmp);
4457 rc = xfer_data (ctx, tmp, strlen (tmp));
4458 pthread_cleanup_pop (1);
4460 else if (!strcasecmp (line, "last_error"))
4462 if (client->last_error)
4463 rc = xfer_data (ctx, client->last_error, strlen (client->last_error));
4464 else
4465 rc = GPG_ERR_NO_DATA;
4467 else if (!strcasecmp (line, "user"))
4469 char *user = NULL;
4471 #ifdef WITH_GNUTLS
4472 if (client->thd->remote)
4473 user = str_asprintf ("#%s", client->thd->tls->fp);
4474 else
4475 user = get_username (client->thd->peer->uid);
4476 #else
4477 user = get_username (client->thd->peer->uid);
4478 #endif
4479 if (user)
4481 pthread_cleanup_push ((void *)xfree, user);
4482 rc = xfer_data (ctx, user, strlen (user));
4483 pthread_cleanup_pop (1);
4485 else
4486 rc = GPG_ERR_NO_DATA;
4488 else
4489 rc = gpg_error (GPG_ERR_SYNTAX);
4491 return send_error (ctx, rc);
4494 static gpg_error_t
4495 parse_opt_secret (void *data, void *value)
4497 struct client_s *client = data;
4499 (void) value;
4500 client->opts |= OPT_SECRET;
4501 return 0;
4504 static gpg_error_t
4505 parse_keyinfo_opt_learn (void *data, void *value)
4507 struct client_s *client = data;
4509 (void)value;
4510 client->opts |= OPT_KEYINFO_LEARN;
4511 return 0;
4514 static gpg_error_t
4515 keyinfo_command (assuan_context_t ctx, char *line)
4517 struct client_s *client = assuan_get_pointer (ctx);
4518 gpg_error_t rc = 0;
4519 char **keys = NULL, **p = NULL;
4520 int sym = 0;
4521 struct argv_s *args[] = {
4522 &(struct argv_s) {"learn", OPTION_TYPE_NOARG, parse_keyinfo_opt_learn},
4523 NULL
4526 rc = parse_options (&line, args, client, 0);
4527 if (rc)
4528 return send_error (ctx, rc);
4530 if (line && *line)
4531 return send_error (ctx, GPG_ERR_SYNTAX);
4533 if (!(client->flags & FLAG_OPEN))
4534 return send_error (ctx, GPG_ERR_INV_STATE);
4536 if (client->opts & OPT_KEYINFO_LEARN)
4538 rc = cache_agent_command ("LEARN");
4539 return send_error (ctx, rc);
4542 if (client->flags & FLAG_NEW)
4543 return send_error (ctx, GPG_ERR_NO_DATA);
4545 rc = lock_flock (ctx, client->filename, FLOCK_TYPE_SH, &client->flock_fd);
4546 if (rc)
4547 return send_error (ctx, rc);
4549 rc = crypto_is_symmetric (client->filename);
4550 unlock_flock (&client->flock_fd);
4551 if (!rc)
4552 sym = 1;
4553 else if (rc != GPG_ERR_BAD_DATA)
4554 return send_error (ctx, rc);
4556 rc = 0;
4557 if (!sym)
4559 p = strv_catv (keys, client->crypto->pubkey);
4560 if (!p)
4561 rc = GPG_ERR_ENOMEM;
4562 else
4563 keys = p;
4566 if (!rc && client->crypto->sigkey)
4568 if (!strv_printf (&keys, "S%s", client->crypto->sigkey))
4570 strv_free (keys);
4571 return send_error (ctx, GPG_ERR_ENOMEM);
4575 if (!rc)
4577 if (keys)
4579 line = strv_join ("\n", keys);
4580 strv_free (keys);
4581 pthread_cleanup_push ((void *)xfree, line);
4582 if (line)
4583 rc = xfer_data (ctx, line, strlen (line));
4584 else
4585 rc = GPG_ERR_ENOMEM;
4587 pthread_cleanup_pop (1);
4589 else
4590 rc = GPG_ERR_NO_DATA;
4592 else
4593 strv_free (keys);
4595 return send_error (ctx, rc);
4598 static gpg_error_t
4599 deletekey_command (assuan_context_t ctx, char *line)
4601 gpg_error_t rc;
4602 struct client_s *client = assuan_get_pointer (ctx);
4603 struct crypto_s *crypto = NULL;
4604 char *keys[] = { NULL, NULL };
4605 gpgme_key_t *result;
4606 char **p = NULL;
4608 if (!(client->flags & FLAG_OPEN))
4609 return send_error (ctx, GPG_ERR_INV_STATE);
4611 rc = peer_is_invoker (client);
4612 if (rc)
4613 return send_error (ctx, rc);
4615 if (client->flags & FLAG_NO_PINENTRY)
4616 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
4618 if (!*line)
4619 return send_error (ctx, GPG_ERR_SYNTAX);
4621 rc = crypto_keyid_to_16b_once (line);
4622 if (rc)
4623 return send_error (ctx, rc);
4625 for (p = client->crypto->pubkey; p && *p; p++)
4627 if (!strcmp (*p, line))
4628 break;
4631 if (!p)
4633 if (client->crypto->sigkey && strcmp (client->crypto->sigkey, line))
4634 return send_error (ctx, GPG_ERR_FORBIDDEN);
4635 else if (!client->crypto->sigkey)
4636 return send_error (ctx, GPG_ERR_NO_SECKEY);
4639 rc = crypto_init (&crypto, client->ctx, client->filename,
4640 client->flags & FLAG_NO_PINENTRY, NULL);
4641 if (rc)
4642 return send_error (ctx, rc);
4644 pthread_cleanup_push ((void *)crypto_free, crypto);
4645 keys[0] = line;
4646 rc = crypto_list_keys (crypto, keys, 1, &result);
4647 if (!rc)
4649 pthread_cleanup_push ((void *)crypto_free_key_list, result);
4650 rc = crypto_delete_key (client, crypto, *result, 1);
4651 pthread_cleanup_pop (1);
4654 pthread_cleanup_pop (1);
4655 if (gpg_err_source (rc) == GPG_ERR_SOURCE_GPGME
4656 && gpg_err_code (rc) == GPG_ERR_CANCELED)
4657 rc = gpg_error (GPG_ERR_NOT_CONFIRMED);
4659 return send_error (ctx, rc);
4662 static gpg_error_t
4663 kill_command (assuan_context_t ctx, char *line)
4665 struct client_s *client = assuan_get_pointer (ctx);
4666 gpg_error_t rc;
4667 unsigned i, t;
4669 if (!line || !*line)
4670 return send_error (ctx, GPG_ERR_SYNTAX);
4672 MUTEX_LOCK (&cn_mutex);
4673 pthread_cleanup_push ((void *)release_mutex_cb, &cn_mutex);
4674 t = slist_length (cn_thread_list);
4675 rc = GPG_ERR_ESRCH;
4677 for (i = 0; i < t; i++)
4679 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
4680 char *tmp = str_asprintf ("%p", thd->tid);
4682 if (strcmp (line, tmp))
4684 xfree (tmp);
4685 continue;
4688 xfree (tmp);
4689 rc = peer_is_invoker (client);
4690 if (!rc)
4692 #ifdef HAVE_PTHREAD_CANCEL
4693 pthread_cancel (thd->tid);
4694 #else
4695 pthread_kill (thd->tid, SIGUSR2);
4696 #endif
4697 break;
4699 else if (rc == GPG_ERR_EACCES)
4700 rc = GPG_ERR_FORBIDDEN;
4701 else if (rc)
4702 break;
4704 if (config_get_boolean ("global", "strict_kill"))
4705 break;
4707 #ifdef WITH_GNUTLS
4708 if (client->thd->remote && thd->remote)
4710 if (!thd->tls || !thd->tls->fp)
4712 rc = GPG_ERR_INV_STATE;
4713 break;
4715 if (!strcmp (client->thd->tls->fp, thd->tls->fp))
4717 #ifdef HAVE_PTHREAD_CANCEL
4718 pthread_cancel (thd->tid);
4719 #else
4720 pthread_kill (thd->tid, SIGUSR2);
4721 #endif
4722 break;
4725 else if (!client->thd->remote && !thd->remote)
4726 #endif
4728 if (client->thd->peer->uid == thd->peer->uid)
4730 #ifdef HAVE_PTHREAD_CANCEL
4731 pthread_cancel (thd->tid);
4732 #else
4733 pthread_kill (thd->tid, SIGUSR2);
4734 #endif
4737 break;
4740 pthread_cleanup_pop (1);
4741 return send_error (ctx, rc);
4744 static gpg_error_t
4745 listkeys_command (assuan_context_t ctx, char *line)
4747 struct client_s *client = assuan_get_pointer (ctx);
4748 struct crypto_s *crypto = NULL;
4749 char **pattern = NULL;
4750 gpgme_key_t *keys = NULL;
4751 char **result = NULL;
4752 gpg_error_t rc;
4753 struct argv_s *args[] = {
4754 &(struct argv_s) {"secret-only", OPTION_TYPE_NOARG, parse_opt_secret},
4755 NULL
4758 rc = parse_options (&line, args, client, 1);
4759 if (rc)
4760 return send_error (ctx, rc);
4762 rc = crypto_init (&crypto, client->ctx, client->filename,
4763 client->flags & FLAG_NO_PINENTRY, NULL);
4764 if (rc)
4765 return send_error (ctx, rc);
4767 pthread_cleanup_push ((void *)crypto_free, crypto);
4768 pattern = str_split (line, ",", 0);
4769 pthread_cleanup_push ((void *)(void *)strv_free, pattern);
4770 rc = crypto_list_keys (crypto, pattern, client->opts & OPT_SECRET,
4771 &keys);
4772 pthread_cleanup_pop (1);
4773 pthread_cleanup_pop (1);
4774 if (!rc)
4776 int i;
4778 for (i = 0; keys[i]; i++)
4780 char *p = crypto_key_info (keys[i]);
4781 char **r;
4783 if (!p)
4785 rc = GPG_ERR_ENOMEM;
4786 break;
4789 r = strv_cat (result, p);
4790 if (!r)
4792 rc = GPG_ERR_ENOMEM;
4793 break;
4796 result = r;
4799 if (!i)
4800 rc = GPG_ERR_NO_DATA;
4802 crypto_free_key_list (keys);
4805 if (!rc)
4807 line = strv_join ("\n", result);
4808 strv_free (result);
4809 pthread_cleanup_push ((void *)xfree, line);
4810 if (!line)
4811 rc = GPG_ERR_ENOMEM;
4812 else
4813 rc = xfer_data (ctx, line, strlen (line));
4815 pthread_cleanup_pop (1);
4817 else
4818 strv_free (result);
4820 if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
4821 || gpg_err_code (rc) == GPG_ERR_NO_SECKEY)
4822 rc = GPG_ERR_NO_DATA;
4824 return send_error (ctx, rc);
4827 void
4828 init_commands ()
4830 /* !BEGIN-HELP-TEXT!
4832 * This comment is used as a marker to generate the offline documentation
4833 * found in doc/pwmd.info. The indentation needs to be kept for the awk
4834 * script to determine where commands begin and end.
4836 new_command("HELP", 1, 1, 0, help_command, _(
4837 "HELP [--html] [<COMMAND>]\n"
4838 "Show available commands or command specific help text."
4839 "@*@*"
4840 "The @option{--html} option will output the help text in HTML format."
4843 new_command("DELETEKEY", 1, 1, FLOCK_TYPE_SH|FLOCK_TYPE_KEEP, deletekey_command, _(
4844 "DELETEKEY <keyid>\n"
4845 "Deletes the secret key associated with key @var{keyid} from the keyring. "
4846 "Note that when the key is deleted, the current or other data files using "
4847 "this key will no longer be able to be opened."
4850 new_command("KILL", 1, 0, 0, kill_command, _(
4851 "KILL <thread_id>\n"
4852 "Terminates the client identified by @var{thread_id} and releases any file "
4853 "lock or other resources it has held. See @code{GETINFO} (@pxref{GETINFO}) "
4854 "for details about listing connected clients. An @code{invoking_user} "
4855 "(@pxref{Configuration}) may kill any client while others may only kill "
4856 "clients of the same @code{UID} or @abbr{TLS} fingerprint."
4859 new_command("LISTKEYS", 1, 0, 0, listkeys_command, _(
4860 "LISTKEYS [--secret-only] [pattern[,<pattern>]]\n"
4861 "Returns a new line separated list of key information matching a comma "
4862 "separated list of @var{pattern}'s. When option @option{--secret-only} is "
4863 "specified, only keys matching @var{pattern} that also have a secret key "
4864 "available will be returned."
4867 new_command("KEYINFO", 1, 0, 0, keyinfo_command, _(
4868 "KEYINFO [--learn]\n"
4869 "Returns a new line separated list of key ID's that the currently opened "
4870 "data file has recipients and signers for. If the key is a signing key it "
4871 "will be prefixed with an @code{S}. If the file is a new one, or has no "
4872 "signers in the case of being symmetrically encrypted, the error code "
4873 "@code{GPG_ERR_NO_DATA} is returned."
4874 "@*@*"
4875 "When the @option{--learn} option is passed, keys on a smartcard will be "
4876 "imported."
4879 new_command("GETINFO", 1, 1, 0, getinfo_command, _(
4880 "GETINFO [--data] [--verbose] CACHE | CLIENTS | PID | USER | LAST_ERROR | VERSION\n"
4881 "Get server and other information. The information is returned via a status "
4882 "message (@pxref{Status Messages}) unless otherwise noted or @option{--data} "
4883 "is specified."
4884 "@*@*"
4885 "@var{CACHE} returns the number of cached documents."
4886 "@*@*"
4887 "@var{CLIENTS} returns the number of "
4888 "connected clients via a status message or a list of connected clients when "
4889 "the @option{--verbose} parameter is used (implies @option{--data}). A "
4890 "verbose line of a client list contains "
4891 "space delimited "
4892 "fields: the thread ID, client name, opened file (@code{/} if none opened), "
4893 "IP address if remote, file lock status, whether the current client is self "
4894 "or not, client state (see below), "
4895 "user ID or TLS fingerprint of the connected client, username if the "
4896 "client is a local one else @code{-}, and finally the time stamp of when the "
4897 "client connected."
4898 "@*@*"
4899 "Client state @code{0} is an unknown client state, state @code{1} indicates "
4900 "the client has connected but hasn't completed initializing, state @code{2} "
4901 "indicates that the client is idle, state @code{3} means the "
4902 "client is in a command and state @code{4} means the client is disconnecting. "
4903 "@*@*"
4904 "@var{PID} returns the process ID number of the server via a data response."
4905 "@*@*"
4906 "@var{VERSION} returns the server version number and compile-time features "
4907 "via a data response with each being space delimited."
4908 "@*@*"
4909 "@var{LAST_ERROR} returns a detailed description of the last failed command "
4910 "via a data response, when available."
4911 "@*@*"
4912 "@var{USER} returns the username or @abbr{TLS} hash of the connected client "
4913 "via a data response."
4916 new_command("PASSWD", 0, 0, FLOCK_TYPE_EX|FLOCK_TYPE_KEEP, passwd_command, _(
4917 "PASSWD\n"
4918 "Changes the passphrase of the secret key required to open the current "
4919 "data file. If the data file is symmetrically encrypted, the error "
4920 "@code{GPG_ERR_NOT_SUPPORTED} is returned. When symmetrically encrypted, "
4921 "the @code{SAVE} command (@pxref{SAVE}) should be used instead to prevent "
4922 "this command saving any unwanted changes to the @abbr{XML} document."
4923 "@*@*"
4924 "This command is not available to non-invoking clients "
4925 "(@pxref{Access Control})."
4928 new_command("OPEN", 1, 1, FLOCK_TYPE_SH|FLOCK_TYPE_KEEP, open_command, _(
4929 "OPEN [--lock] <filename>\n"
4930 "Opens @var{filename}. When the @var{filename} is not found on the "
4931 "file-system then a new in-memory document will be created. If the file is "
4932 "found, it is looked for in the file cache and when found no passphrase will "
4933 "be required to open it. When not cached, @cite{pinentry(1)} will be used to "
4934 "retrieve the passphrase for decryption unless @option{disable-pinentry} "
4935 "(@pxref{OPTION}) was specified in which case @command{pwmd} will "
4936 "@emph{INQUIRE} the client for the passphrase. Note than when configuration "
4937 "option @option{strict_open} is enabled and the client is not an "
4938 "@option{invoking_user}, an error will be returned when the data file does "
4939 "not exist."
4940 "@*@*"
4941 "When the @option{--lock} option is passed then the file mutex will be "
4942 "locked as if the @code{LOCK} command (@pxref{LOCK}) had been sent after the "
4943 "file had been opened."
4946 new_command("GENKEY", 1, 1, 0, genkey_command, _(
4947 "GENKEY --subkey-of=fpr | --userid=\"str\" [--expire=N] [--algo=\"str\"] [--no-passphrase] [--usage=\"default|sign|encrypt\"\n"
4948 "Generates a new key based on option arguments. One of "
4949 "@option{--subkey-of} or @option{--userid} is "
4950 "required. The @option{--subkey-of} option will generate a subkey for the key "
4951 "of the specified fingerprint."
4954 new_command("SAVE", 0, 0, FLOCK_TYPE_EX|FLOCK_TYPE_KEEP, save_command, _(
4955 "SAVE [--sign-keyid=[<fpr>]] [--symmetric | --keyid=<fpr>[,..] | --inquire-keyid]\n"
4956 "Writes the in-memory @abbr{XML} document to disk. The file written to is the "
4957 "file that was opened when using the @code{OPEN} command (@pxref{OPEN})."
4958 "@*@*"
4959 "If the file is a new one, one of @option{--symmetric}, @option{--keyid} or"
4960 "@option{--inquire-keyid} is required. When not @option{--symmetric}, option "
4961 "@option{--sign-keyid} is also required, but optional otherwise."
4962 "@*@*"
4963 "You can encrypt the data file to a recipient other than the one that it "
4964 "was originally encrypted with by passing the @option{--keyid} or "
4965 "@option{--inquire-keyid} option with a comma separated list of "
4966 "public encryption key fingerprints as its argument. Use the "
4967 "@command{LISTKEYS} command (@pxref{LISTKEYS}) to show key information by "
4968 "pattern. The @option{--sign-keyid} option may also be used to sign the data "
4969 "file with an alternate key by specifying the fingerprint of a signing key. "
4970 "Only one signing key is supported unlike the @option{--keyid} option. "
4971 "A passphrase to decrypt the data file "
4972 "will be required when one or more of the original encryption keys or signing "
4973 "key are not found in either of these two options' arguments or when the data "
4974 "file is symmetrically encrypted reguardless of the @code{require_save_key} "
4975 "configuration parameter. The original encryption keys and signing key will be "
4976 "used when neither of these options are specified."
4977 "@*@*"
4978 "The @option{--keyid} and @option{--sign-keyid} options are not available "
4979 "to non-invoking clients "
4980 "(@pxref{Access Control}) when the recipients or signer do not match those "
4981 "that were used when the file was @code{OPEN}'ed."
4982 "@*@*"
4983 "The @option{--symmetric} option specifies that a new data file be "
4984 "conventionally encrypted. These types of data files do not use a recipient "
4985 "public key but may optionally be signed by using the @option{--sign-keyid} "
4986 "option. To remove the signing key from a symmtrically encrypted data file, "
4987 "leave the option value empty."
4988 "@*@*"
4989 "Note that you cannot change encryption schemes once a data file has been "
4990 "saved."
4993 new_command("ISCACHED", 1, 0, 0, iscached_command, _(
4994 "ISCACHED [--lock] [--agent [--sign]] <filename>\n"
4995 "Determines the file cache status of the specified @var{filename}. "
4996 "The default is to test whether the filename is cached in memory. Passing "
4997 "option @option{--agent} will test the @command{gpg-agent} cache for at most "
4998 "one cached key used for opening the data file (@pxref{OPEN}). To test if "
4999 "a signing key is cached, pass @option{--sign} along with @option{--agent}. "
5000 "Both the @option{--agent} and @option{--sign} options require an opened data "
5001 "file."
5002 "@*@*"
5003 "An @emph{OK} response is returned if the specified @var{filename} is found "
5004 "in the cache. If not found in the cache but exists on the filesystem "
5005 "then @code{GPG_ERR_NO_DATA} is returned. Otherwise a filesystem error is "
5006 "returned."
5007 "@*@*"
5008 "The @option{--lock} option will lock the file mutex of @var{filename} when "
5009 "the file exists; it does not need to be opened nor cached. The lock will be "
5010 "released when the client exits or sends the @code{UNLOCK} command "
5011 "(@pxref{UNLOCK}). When this option is passed the current data file is closed."
5014 new_command("CLEARCACHE", 1, 1, 0, clearcache_command, _(
5015 "CLEARCACHE [<filename>]\n"
5016 "Clears a file cache entry for all or the specified @var{filename}. Note that "
5017 "this will also clear any @command{gpg-agent} cached keys which may cause "
5018 "problems if another data file shares the same keys as @var{filename}."
5019 "@*@*"
5020 "When clearing all cache entries a permissions test is done against the "
5021 "current client based on the @var{allowed} configuration parameter in a "
5022 "@var{filename} section. Both a cache entry may be cleared and an error "
5023 "returned depending on cached data files and client permissions."
5026 new_command("CACHETIMEOUT", 1, 1, 0, cachetimeout_command, _(
5027 "CACHETIMEOUT <filename> <seconds>\n"
5028 "The time in @var{seconds} until @var{filename} will be removed from the "
5029 "cache. @code{-1} will keep the cache entry forever, @code{0} will require "
5030 "the passphrase for each @code{OPEN} command (@pxref{OPEN}) or @code{SAVE} "
5031 "(@pxref{SAVE}) command. @xref{Configuration}, and the @code{cache_timeout} "
5032 "parameter."
5035 new_command("LIST", 0, 1, 0, list_command, _(
5036 "LIST [--inquire] [--recurse] [element[<TAB>child[..]]]\n"
5037 "If no element path is given then a newline separated list of root elements "
5038 "is returned with a data response. If given, then children of the specified "
5039 "element path are returned."
5040 "@*@*"
5041 "Each element path "
5042 "returned will have zero or more flags appened to it. These flags are "
5043 "delimited from the element path by a single space character. A flag itself "
5044 "is a single character. Flag @code{P} indicates that access to the element "
5045 "is denied. Flag @code{+} indicates that there are child nodes of "
5046 "the current element path. Flag @code{E} indicates that an element of the "
5047 "element path contained in a @var{target} attribute could not be found. Flag "
5048 "@code{O} indicates that a @var{target} attribute recursion limit was reached "
5049 "(@pxref{Configuration}). Flag @code{T}, followed by a single space character, "
5050 "then an element path, is the element path of the @var{target} attribute "
5051 "contained in the current element."
5052 "@*@*"
5053 "When a specified element path contains an error, beit from the final "
5054 "element in the path or any previous element, the path is still shown but "
5055 "will contain the error flag for the element with the error. Determining "
5056 "the actual element which contains the error is up to the client. This can be "
5057 "done by traversing the final element up to parent elements that contain the "
5058 "same error flag."
5059 "@*@*"
5060 "The option @option{--recurse} may be used to list the entire element tree "
5061 "for a specified element path or the entire tree for all root elements."
5062 "@*@*"
5063 "When the @option{--inquire} option is passed then all remaining non-option "
5064 "arguments are retrieved via a server @emph{INQUIRE}."
5067 new_command("REALPATH", 0, 1, 0, realpath_command, _(
5068 "REALPATH [--inquire] element[<TAB>child[..]]\n"
5069 "Resolves all @code{target} attributes of the specified element path and "
5070 "returns the result with a data response. @xref{Target Attribute}, for details."
5071 "@*@*"
5072 "When the @option{--inquire} option is passed then all remaining non-option "
5073 "arguments are retrieved via a server @emph{INQUIRE}."
5076 new_command("STORE", 0, 1, 0, store_command, _(
5077 "STORE element[<TAB>child[..]]<TAB>[content]\n"
5078 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
5079 "@*@*"
5080 "Creates a new element path or modifies the @var{content} of an existing "
5081 "element. If only a single element is specified then a new root element is "
5082 "created. Otherwise, elements are @key{TAB} delimited and the content will be "
5083 "set to the final @key{TAB} delimited element. If no @var{content} is "
5084 "specified after the final @key{TAB}, then the content of the existing "
5085 "element will be removed; or will be empty if creating a new element."
5086 "@*@*"
5087 "The only restriction of an element name is that it not contain whitespace "
5088 "characters. There is no other whitespace between the @key{TAB} delimited "
5089 "elements. It is recommended that the content of an element be base64 encoded "
5090 "when it contains control or @key{TAB} characters to prevent @abbr{XML} "
5091 "parsing and @command{pwmd} syntax errors."
5094 new_command("RENAME", 0, 1, 0, rename_command, _(
5095 "RENAME [--inquire] element[<TAB>child[..]] <value>\n"
5096 "Renames the specified @var{element} to the new @var{value}. If an element of "
5097 "the same name as the @var{value} already exists it will be overwritten."
5098 "@*@*"
5099 "When the @option{--inquire} option is passed then all remaining non-option "
5100 "arguments are retrieved via a server @emph{INQUIRE}."
5103 new_command("COPY", 0, 1, 0, copy_command, _(
5104 "COPY [--inquire] source[<TAB>child[..]] dest[<TAB>child[..]]\n"
5105 "Copies the entire element tree starting from the child node of the source "
5106 "element, to the destination element path. If the destination element path "
5107 "does not exist then it will be created; otherwise it is overwritten."
5108 "@*@*"
5109 "Note that attributes from the source element are merged into the "
5110 "destination element when the destination element path exists. When an "
5111 "attribute of the same name exists in both the source and destination "
5112 "elements then the destination attribute will be updated to the source "
5113 "attribute value."
5114 "@*@*"
5115 "When the @option{--inquire} option is passed then all remaining non-option "
5116 "arguments are retrieved via a server @emph{INQUIRE}."
5119 new_command("MOVE", 0, 1, 0, move_command, _(
5120 "MOVE [--inquire] source[<TAB>child[..]] [dest[<TAB>child[..]]]\n"
5121 "Moves the source element path to the destination element path. If the "
5122 "destination is not specified then it will be moved to the root node of the "
5123 "document. If the destination is specified and exists then it will be "
5124 "overwritten; otherwise non-existing elements of the destination element "
5125 "path will be created."
5126 "@*@*"
5127 "When the @option{--inquire} option is passed then all remaining non-option "
5128 "arguments are retrieved via a server @emph{INQUIRE}."
5131 new_command("DELETE", 0, 1, 0, delete_command, _(
5132 "DELETE [--inquire] element[<TAB>child[..]]\n"
5133 "Removes the specified element path and all of its children. This may break "
5134 "an element with a @code{target} attribute (@pxref{Target Attribute}) that "
5135 "refers to this element or any of its children."
5136 "@*@*"
5137 "When the @option{--inquire} option is passed then all remaining non-option "
5138 "arguments are retrieved via a server @emph{INQUIRE}."
5141 new_command("GET", 0, 1, 0, get_command, _(
5142 "GET [--inquire] element[<TAB>child[..]]\n"
5143 "Retrieves the content of the specified element. The content is returned "
5144 "with a data response."
5145 "@*@*"
5146 "When the @option{--inquire} option is passed then all remaining non-option "
5147 "arguments are retrieved via a server @emph{INQUIRE}."
5150 new_command("ATTR", 0, 1, 0, attr_command, _(
5151 "ATTR [--inquire] SET|GET|DELETE|LIST [<attribute>] element[<TAB>child[..]] ..\n"
5152 "@table @asis\n"
5153 "@item ATTR SET attribute element[<TAB>child[..]] [value]\n"
5154 " Stores or updates an @var{attribute} name and optional @var{value} of an "
5155 "element. When no @var{value} is specified any existing value will be removed."
5156 "@*@*"
5157 "@item ATTR DELETE attribute element[<TAB>child[..]]\n"
5158 " Removes an attribute from an element. If @var{attribute} is @code{_name} "
5159 "or @code{target} an error is returned. Use the @command{DELETE} command "
5160 "(@pxref{DELETE}) instead."
5161 "@*@*"
5162 "@item ATTR LIST element[<TAB>child[..]]\n"
5163 " Retrieves a newline separated list of attributes names and values "
5164 "from the specified element. Each attribute name and value is space delimited."
5165 "@*@*"
5166 "@item ATTR GET attribute element[<TAB>child[..]]\n"
5167 " Retrieves the value of an @var{attribute} from an element."
5168 "@end table\n"
5169 "@*@*"
5170 "When the @option{--inquire} option is passed then all remaining non-option "
5171 "arguments are retrieved via a server @emph{INQUIRE}."
5172 "@*@*"
5173 "@xref{Target Attribute}, for details about this special attribute and also "
5174 "@pxref{Other Attributes} for other attributes that are handled specially "
5175 "by @command{pwmd}."
5178 new_command("XPATH", 0, 1, 0, xpath_command, _(
5179 "XPATH [--inquire] <expression>[<TAB>[value]]\n"
5180 "Evaluates an XPath @var{expression}. If no @var{value} argument is "
5181 "specified it is assumed the expression is a request to return a result. "
5182 "Otherwise, the result is set to the @var{value} argument and the document is "
5183 "updated. If there is no @var{value} after the @key{TAB} character, the value "
5184 "is assumed to be empty and the document is updated. For example:"
5185 "@sp 1\n"
5186 "@example\n"
5187 "XPATH //element[@@_name='password']@key{TAB}\n"
5188 "@end example\n"
5189 "@sp 1\n"
5190 "would clear the content of all @var{password} elements in the data file "
5191 "while leaving off the trailing @key{TAB} would return all @var{password} "
5192 "elements in @abbr{XML} format."
5193 "@*@*"
5194 "When the @option{--inquire} option is passed then all remaining non-option "
5195 "arguments are retrieved via a server @emph{INQUIRE}."
5196 "@*@*"
5197 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
5198 "expression syntax."
5201 new_command("XPATHATTR", 0, 1, 0, xpathattr_command, _(
5202 "XPATHATTR [--inquire] SET|DELETE <name> <expression>[<TAB>[<value>]]\n"
5203 "Like the @code{XPATH} command (@pxref{XPATH}) but operates on element "
5204 "attributes and does not return a result. For the @var{SET} operation the "
5205 "@var{value} is optional but the field is required. If not specified then "
5206 "the attribute value will be empty. For example:"
5207 "@sp 1\n"
5208 "@example\n"
5209 "XPATHATTR SET password //element[@@_name='password']@key{TAB}\n"
5210 "@end example\n"
5211 "@sp 1\n"
5212 "would create a @var{password} attribute for each @var{password} element "
5213 "found in the document. The attribute value will be empty but still exist."
5214 "@*@*"
5215 "When the @option{--inquire} option is passed then all remaining non-option "
5216 "arguments are retrieved via a server @emph{INQUIRE}."
5217 "@*@*"
5218 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
5219 "expression syntax."
5222 new_command("IMPORT", 0, 1, 0, import_command, _(
5223 "IMPORT [--root=element[<TAB>child[..]]]\n"
5224 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
5225 "@*@*"
5226 "Like the @code{STORE} command (@pxref{STORE}), but the @var{content} "
5227 "argument is raw @abbr{XML} data. The content is created as a child of "
5228 "the element path specified with the @option{--root} option or at the "
5229 "document root when not specified. Existing elements of the same name will "
5230 "be overwritten."
5231 "@*@*"
5232 "The content must begin with an @abbr{XML} element node. @xref{Introduction}, "
5233 "for details."
5236 new_command("DUMP", 1, 1, 0, dump_command, _(
5237 "DUMP\n"
5238 "Shows the in memory @abbr{XML} document with indenting. @xref{XPATH}, for "
5239 "dumping a specific node."
5242 new_command("LOCK", 0, 0, 0, lock_command, _(
5243 "LOCK\n"
5244 "Locks the mutex associated with the opened file. This prevents other clients "
5245 "from sending commands to the same opened file until the client "
5246 "that sent this command either disconnects or sends the @code{UNLOCK} "
5247 "command. @xref{UNLOCK}."
5250 new_command("UNLOCK", 1, 0, 0, unlock_command, _(
5251 "UNLOCK\n"
5252 "Unlocks the file mutex which was locked with the @code{LOCK} command or "
5253 "a commands' @option{--lock} option (@pxref{LOCK}, @pxref{OPEN}, "
5254 "@pxref{ISCACHED})."
5257 new_command("GETCONFIG", 1, 1, 0, getconfig_command, _(
5258 "GETCONFIG [filename] <parameter>\n"
5259 "Returns the value of a @command{pwmd} configuration @var{parameter} with a "
5260 "data response. If no file has been opened then the value for @var{filename} "
5261 "or the default from the @var{global} section will be returned. If a file "
5262 "has been opened and no @var{filename} is specified, the value previously "
5263 "set with the @code{OPTION} command (@pxref{OPTION}) will be returned."
5266 new_command("OPTION", 1, 1, 0, option_command, _(
5267 "OPTION <NAME>=[<VALUE>]\n"
5268 "Sets a client option @var{name} to @var{value}. The value for an option is "
5269 "kept for the duration of the connection with the exception of the "
5270 "@command{pinentry} options which are defaults for all future connections "
5271 "(@pxref{Pinentry}). When @var{value} is empty the option is unset."
5272 "@*@*"
5273 "@table @asis\n"
5274 "@item DISABLE-PINENTRY\n"
5275 "Disable use of @command{pinentry} for passphrase retrieval. When @code{1}, a "
5276 "server inquire is sent to the client to obtain the passphrase. This option "
5277 "may be set as needed before the @code{OPEN} (@pxref{OPEN}), @code{PASSWD} "
5278 "(@pxref{PASSWD}) and @code{SAVE} (@pxref{SAVE}) commands. Set to @code{0} "
5279 "to use a @command{pinentry}."
5280 "@*@*"
5281 "@item DISPLAY\n"
5282 "Set or unset the X11 display to use when prompting for a passphrase."
5283 "@*@*"
5284 "@item TTYNAME\n"
5285 "Set the terminal device path to use when prompting for a passphrase."
5286 "@*@*"
5287 "@item TTYTYPE\n"
5288 "Set the terminal type for use with @option{TTYNAME}."
5289 "@*@*"
5290 "@item NAME\n"
5291 "Associates the thread ID of the connection with the specified textual "
5292 "representation. Useful for debugging log messages. May not contain whitespace."
5293 "@*@*"
5294 "@item LOCK-TIMEOUT\n"
5295 "When not @code{0}, the duration in tenths of a second to wait for the file "
5296 "mutex which has been locked by another thread to be released before returning "
5297 "an error. When @code{-1} the error will be returned immediately."
5298 "@*@*"
5299 "@item CLIENT-STATE\n"
5300 "When set to @code{1} then client state status messages for other clients are "
5301 "sent to the current client. The default is @code{0}."
5302 "@end table\n"
5305 new_command("LS", 1, 1, 0, ls_command, _(
5306 "LS\n"
5307 "Returns a newline separated list of data files stored in the data directory "
5308 "@file{HOMEDIR/data} (@pxref{Invoking}) with a data response."
5311 new_command("RESET", 1, 1, 0, NULL, _(
5312 "RESET\n"
5313 "Closes the currently opened file but keeps any previously set client options "
5314 "(@pxref{OPTION})."
5317 new_command("NOP", 1, 1, 0, NULL, _(
5318 "NOP\n"
5319 "Does nothing. Always returns successfully."
5322 /* !END-HELP-TEXT! */
5323 new_command ("CANCEL", 1, 1, 0, NULL, NULL);
5324 new_command ("END", 1, 1, 0, NULL, NULL);
5325 new_command ("BYE", 1, 1, 0, NULL, NULL);
5327 int i;
5328 for (i = 0; command_table[i]; i++);
5329 qsort (command_table, i - 1, sizeof (struct command_table_s *),
5330 sort_commands);
5333 gpg_error_t
5334 register_commands (assuan_context_t ctx)
5336 int i = 0, rc;
5338 for (; command_table[i]; i++)
5340 if (!command_table[i]->handler)
5341 continue;
5343 rc = assuan_register_command (ctx, command_table[i]->name,
5344 command_table[i]->handler,
5345 command_table[i]->help);
5346 if (rc)
5347 return rc;
5350 rc = assuan_register_bye_notify (ctx, bye_notify);
5351 if (rc)
5352 return rc;
5354 rc = assuan_register_reset_notify (ctx, reset_notify);
5355 if (rc)
5356 return rc;
5358 rc = assuan_register_pre_cmd_notify (ctx, command_startup);
5359 if (rc)
5360 return rc;
5362 return assuan_register_post_cmd_notify (ctx, command_finalize);