Fix client state race condition.
[pwmd.git] / src / commands.c
blobfc99e39463538f7b619f8d41dbc257c094dc27b6
1 /*
2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015,
3 2016, 2017
4 Ben Kibbey <bjk@luxsci.net>
6 This file is part of pwmd.
8 Pwmd is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 2 of the License, or
11 (at your option) any later version.
13 Pwmd is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
21 #ifdef HAVE_CONFIG_H
22 #include <config.h>
23 #endif
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <err.h>
29 #include <errno.h>
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <fcntl.h>
33 #include <ctype.h>
34 #include <dirent.h>
35 #include <pthread.h>
36 #include <stdint.h>
37 #include <assert.h>
38 #include <signal.h>
40 #include "pwmd-error.h"
41 #include <gcrypt.h>
43 #include "mem.h"
44 #include "xml.h"
45 #include "util-misc.h"
46 #include "common.h"
47 #include "rcfile.h"
48 #include "cache.h"
49 #include "commands.h"
50 #include "mutex.h"
51 #include "crypto.h"
52 #include "acl.h"
54 /* These are command option flags. */
55 #define OPT_INQUIRE 0x0001
56 #define OPT_NO_PASSPHRASE 0x0002
57 #define OPT_ASK 0x0004
58 #define OPT_LIST_RECURSE 0x0008
59 #define OPT_VERBOSE 0x0010
60 #define OPT_LOCK 0x0020
61 #define OPT_LOCK_ON_OPEN 0x0040
62 #define OPT_SIGN 0x0080
63 #define OPT_LIST_ALL 0x0100
64 #define OPT_DATA 0x0200
65 #define OPT_NO_AGENT 0x0400
66 #define OPT_SECRET 0x0800
67 #define OPT_INQUIRE_KEYID 0x1000
68 #define OPT_SYMMETRIC 0x4000
69 #define OPT_NO_SIGNER 0x8000
70 #define OPT_HTML 0x10000
71 #define OPT_CACHE_AGENT 0x20000
72 #define OPT_CACHE_SIGN 0x40000
73 #define OPT_KEYINFO_LEARN 0x80000
75 #define FLOCK_TYPE_NONE 0
76 #define FLOCK_TYPE_SH 0x0001
77 #define FLOCK_TYPE_EX 0x0002
78 #define FLOCK_TYPE_KEEP 0x0004
80 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 pthread_cleanup_push (xfree, crc);
361 cdata = cache_get_data (client->filename, NULL);
362 pthread_cleanup_pop (0);
363 if (cdata)
365 xfree (cdata->crc);
366 cdata->crc = xmalloc (len);
367 memcpy (cdata->crc, crc, len);
370 if (!from_crc)
371 xfree (crc);
372 return 0;
375 static gpg_error_t
376 validate_checksum (struct client_s *client, const char *filename,
377 struct cache_data_s *cdata, unsigned char **r_crc,
378 size_t *r_crclen)
380 unsigned char *crc;
381 size_t len;
382 gpg_error_t rc;
383 int n = 0;
385 if (cdata && !cdata->crc)
386 return GPG_ERR_CHECKSUM;
388 rc = get_checksum (filename, &crc, &len);
389 if (rc)
390 return rc;
392 if (client->crc)
393 n = memcmp (client->crc, crc, len);
394 else if ((client->flags & FLAG_NEW) && cache_get_data (filename, NULL))
395 n = 1;
397 if (!n && cdata)
398 n = memcmp (cdata->crc, crc, len);
400 if (!n && r_crc)
402 *r_crc = crc;
403 *r_crclen = len;
405 else
406 xfree (crc);
408 return n ? GPG_ERR_CHECKSUM : 0;
411 static gpg_error_t
412 open_command (assuan_context_t ctx, char *line)
414 gpg_error_t rc;
415 struct client_s *client = assuan_get_pointer (ctx);
416 int same_file = 0;
417 assuan_peercred_t peer;
418 struct cache_data_s *cdata = NULL;
419 int cached = 0;
420 unsigned char *crc = NULL;
421 size_t crclen = 0;
422 int plaintext = 0;
423 struct argv_s *args[] = {
424 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_open_opt_lock},
425 NULL
428 rc = parse_options (&line, args, client, 1);
429 if (rc)
430 return send_error (ctx, rc);
432 rc = do_validate_peer (ctx, line, &peer);
433 if (rc == GPG_ERR_FORBIDDEN)
435 rc = peer_is_invoker (client);
436 if (rc == GPG_ERR_EACCES)
437 rc = GPG_ERR_FORBIDDEN;
440 if (rc)
441 return send_error (ctx, rc);
443 if (!valid_filename (line))
444 return send_error (ctx, GPG_ERR_INV_VALUE);
446 /* This client may have locked a different file with ISCACHED --lock than
447 * the current filename. This will remove that lock. */
448 same_file = client->filename && !strcmp (line, client->filename);
449 if (client->flags & FLAG_OPEN ||
450 (client->flags & FLAG_HAS_LOCK && !same_file))
452 unsigned opts = client->opts;
453 unsigned flags = client->flags;
455 if (same_file)
456 client->flags |= FLAG_KEEP_LOCK;
458 /* Another client wrote to the same data file as currently opened. */
459 if (cache_get_data (client->filename, NULL))
460 flags &= ~FLAG_NEW;
461 /* Remove cache entry for the new file that hadn't been written. */
462 else if (client->flags & FLAG_NEW)
463 cache_clear (NULL, client->filename, 0, 0);
465 reset_client (client);
466 client->opts = opts;
467 client->flags |= flags;
468 client->flags &= ~(FLAG_LOCK_CMD);
469 if (!same_file)
470 client->flags &= ~(FLAG_HAS_LOCK | FLAG_NEW);
473 client->filename = str_dup (line);
474 if (!client->filename)
475 return send_error(ctx, GPG_ERR_ENOMEM);
477 /* Need to lock the mutex here because file_modified() cannot without
478 * knowing the filename. */
479 rc = lock_file_mutex (client, 1);
480 if (rc)
481 client->flags &= ~FLAG_OPEN;
483 if (!rc)
485 rc = lock_flock (ctx, client->filename, LOCK_SH, &client->flock_fd);
486 if (gpg_err_code (rc) == GPG_ERR_ENOENT)
487 rc = 0;
490 if (!rc)
492 char *keyfile = config_get_string (client->filename, "passphrase_file");
494 rc = crypto_init (&client->crypto, client->ctx, client->filename,
495 client->flags & FLAG_NO_PINENTRY, keyfile);
496 if (rc)
497 xfree (keyfile);
498 else
499 rc = open_check_file (client->filename, NULL, NULL, 1);
502 if (!rc || gpg_err_code (rc) == GPG_ERR_ENOENT)
504 int reload = 0;
505 int defer = 0;
507 if (rc) // new file
509 rc = 0;
511 if (config_get_boolean ("global", "strict_open"))
513 rc = peer_is_invoker (client);
514 if (rc == GPG_ERR_EACCES)
515 rc = GPG_ERR_FORBIDDEN;
518 if (!rc)
520 client->flags |= FLAG_NEW;
521 // data file disappeared. clear the cache entry.
522 cache_clear (NULL, client->filename, 1, 1);
523 cdata = NULL;
526 goto done;
529 cdata = cache_get_data (client->filename, &defer);
530 if (cdata && !defer
531 && !cache_plaintext_get (client->filename, &client->doc))
533 rc = validate_checksum (client, client->filename, cdata, &crc,
534 &crclen);
535 if (rc)
537 log_write ("%s: %s", client->filename,
538 pwmd_strerror (rc));
539 cache_plaintext_release (&client->doc);
540 if (rc == GPG_ERR_CHECKSUM)
542 cache_clear (NULL, client->filename, 1, 1);
543 cdata = NULL;
544 goto decrypt;
548 #ifdef WITH_GNUTLS
549 if (!rc && client->thd->remote
550 && config_get_boolean (client->filename, "tcp_require_key")
551 && !(client->flags & FLAG_NEW))
553 rc = crypto_try_decrypt (client,
554 (client->flags & FLAG_NO_PINENTRY));
556 #endif
557 if (!rc)
559 strv_free (client->crypto->pubkey);
560 client->crypto->pubkey = NULL;
561 if (cdata->pubkey)
562 client->crypto->pubkey = strv_dup (cdata->pubkey);
564 xfree (client->crypto->sigkey);
565 client->crypto->sigkey = NULL;
566 if (cdata->sigkey)
567 client->crypto->sigkey = str_dup (cdata->sigkey);
569 cached = 1;
570 plaintext = 1;
573 else if (cdata && cdata->doc) // cached document
575 if (!rc && !(client->flags & FLAG_NEW))
577 rc = validate_checksum (client, client->filename, cdata, &crc,
578 &crclen);
579 if (rc == GPG_ERR_CHECKSUM)
581 rc = 0;
582 reload = 1;
586 if (!rc)
588 rc = cache_iscached (client->filename, &defer, 0, 0);
589 if ((!rc || rc == GPG_ERR_ENOENT) && defer)
591 rc = 0;
592 reload = 2;
596 if (!rc && reload)
598 if (reload == 1)
599 log_write ("%s: %s", client->filename,
600 pwmd_strerror (GPG_ERR_CHECKSUM));
601 cache_clear (NULL, client->filename, 1, 1);
602 cdata = NULL;
603 rc = crypto_decrypt (client, client->crypto);
605 #ifdef WITH_GNUTLS
606 else if (!rc)
608 if (client->thd->remote
609 && config_get_boolean (client->filename, "tcp_require_key")
610 && !(client->flags & FLAG_NEW))
611 rc = crypto_try_decrypt (client,
612 (client->flags & FLAG_NO_PINENTRY));
614 #endif
616 if (!rc && cdata)
618 client->crypto->plaintext = cdata->doc;
619 client->crypto->plaintext_size = cdata->size;
620 rc = cache_decrypt (client->crypto);
621 if (!rc)
623 cdata->doc = NULL;
624 cdata->size = 0;
626 strv_free (client->crypto->pubkey);
627 client->crypto->pubkey = NULL;
628 if (cdata->pubkey)
629 client->crypto->pubkey = strv_dup (cdata->pubkey);
631 xfree (client->crypto->sigkey);
632 client->crypto->sigkey = NULL;
633 if (cdata->sigkey)
634 client->crypto->sigkey = str_dup (cdata->sigkey);
636 cached = 1;
638 else
640 client->crypto->plaintext = NULL;
641 client->crypto->plaintext_size = 0;
645 else // existing file
647 decrypt:
648 cached = cdata != NULL;
649 rc = crypto_decrypt (client, client->crypto);
653 done:
654 if (!rc && !plaintext)
656 rc = parse_xml (ctx, client->flags & FLAG_NEW);
657 if (!rc)
659 rc = cache_encrypt (client->crypto);
660 if (rc)
661 cache_clear (NULL, client->filename, 1, 1);
662 else
664 long timeout = config_get_long (client->filename,
665 "cache_timeout");
667 cache_free_data_once (cdata);
668 cdata = xcalloc (1, sizeof (struct cache_data_s));
669 cdata->doc = client->crypto->plaintext;
670 cdata->size = client->crypto->plaintext_size;
671 cdata->pubkey = strv_dup(client->crypto->pubkey);
672 cdata->sigkey = client->crypto->sigkey ? str_dup(client->crypto->sigkey) : NULL;
673 client->crypto->plaintext = NULL;
674 client->crypto->plaintext_size = 0;
676 if (cached) // wont increment the refcount
678 if (crclen)
680 xfree (client->crc);
681 client->crc = NULL;
682 xfree (cdata->crc);
683 cdata->crc = xmalloc (crclen);
684 memcpy (cdata->crc, crc, crclen);
687 rc = cache_set_data (client->filename, cdata);
688 /* The cache entry may have been removed and cache_set_data()
689 * already sent STATUS_CACHE. */
690 if (!cache_iscached (client->filename, NULL, 0, 0))
691 rc = send_status (ctx, STATUS_CACHE, NULL);
693 else
694 rc = cache_add_file (client->filename, cdata, timeout);
696 if (!rc)
697 cache_plaintext_set (client->filename, client->doc, 0);
701 else if (!rc)
703 xfree (client->crc);
704 client->crc = NULL;
705 if (crc)
707 client->crc = xmalloc (crclen);
708 memcpy (client->crc, crc, crclen);
712 xfree (crc);
714 if (!rc && !(client->flags & FLAG_NEW) && !cached)
715 rc = update_checksum (client, NULL, 0);
717 if (!rc)
719 client->flags |= FLAG_OPEN;
721 if (client->flags & FLAG_NEW)
722 rc = send_status (ctx, STATUS_NEWFILE, NULL);
724 if (!rc && (client->opts & OPT_LOCK_ON_OPEN))
725 rc = do_lock (client, 0);
728 if (rc)
730 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
732 if (client->flags & FLAG_NEW)
733 cache_clear (NULL, client->filename, 1, 1);
735 crypto_free (client->crypto);
736 client->crypto = NULL;
737 client->flags &= ~FLAG_OPEN;
738 cache_plaintext_release (&client->doc);
740 else
741 crypto_free_non_keys (client->crypto);
743 return send_error (ctx, rc);
746 /* If not the invoking_user or is an existing file, check that the list of user
747 * supplied key ID's are in the list of current key ID's obtained when
748 * decrypting the data file.
750 static gpg_error_t
751 permitted_to_save (struct client_s *client, const char **keys,
752 const char **value)
754 gpg_error_t rc = 0;
755 const char **v;
757 if ((client->flags & FLAG_NEW) || (client->opts & OPT_SYMMETRIC))
758 return 0;
760 rc = peer_is_invoker (client);
761 if (!rc)
762 return 0;
763 else if (rc == GPG_ERR_EACCES)
764 rc = GPG_ERR_FORBIDDEN;
765 else if (rc)
766 return rc;
768 /* Empty match. */
769 if ((!value && !keys) || ((value && !*value) && (keys && !*keys)))
770 return 0;
772 for (v = value; v && *v; v++)
774 const char **k, *pv = *v;
775 int match = 0;
777 if (*pv == '0' && *(pv+1) == 'x')
778 pv += 2;
780 for (k = keys; k && *k; k++)
782 const char *pk = *k;
784 if (*pk == '0' && *(pk+1) == 'x')
785 pk += 2;
787 rc = !strcmp (pv, pk) ? 0 : GPG_ERR_FORBIDDEN;
788 if (rc)
789 rc = !strcmp (pv, *k) ? 0 : GPG_ERR_FORBIDDEN;
791 if (!rc)
793 match = 1;
794 break;
798 if (!match)
799 return GPG_ERR_FORBIDDEN;
802 return rc;
805 /* Requires that the keyid be a fingerprint in 16 byte form. */
806 static gpg_error_t
807 parse_save_opt_keyid_common (struct client_s *client, const char **list,
808 const char *value, char ***dst)
810 gpg_error_t rc = 0;
811 char **keys = NULL;
813 if (value && *value)
815 keys = str_split (value, ",", 0);
816 if (!keys)
817 return GPG_ERR_ENOMEM;
820 rc = crypto_keyid_to_16b (keys);
821 if (!rc)
822 rc = permitted_to_save (client, list, (const char **)keys);
824 if (!rc)
825 *dst = keys;
826 else
827 strv_free (keys);
829 return rc;
832 static gpg_error_t
833 parse_save_opt_keyid (void *data, void *value)
835 struct client_s *client = data;
836 const char *str = value;
837 char **dst = NULL;
838 gpg_error_t rc;
840 rc = parse_save_opt_keyid_common (client,
841 (const char **)client->crypto->pubkey,
842 str, &dst);
843 if (rc)
844 return rc;
846 client->crypto->save.pubkey = dst;
847 return 0;
850 static gpg_error_t
851 parse_save_opt_sign_keyid (void *data, void *value)
853 struct client_s *client = data;
854 const char *str = value;
855 char **dst = NULL;
856 gpg_error_t rc;
857 char **tmp = NULL;
859 if (client->crypto->sigkey)
861 if (!strv_printf (&tmp, "%s", client->crypto->sigkey))
862 return GPG_ERR_ENOMEM;
865 rc = parse_save_opt_keyid_common (client, (const char **)tmp, str, &dst);
866 strv_free (tmp);
867 if (rc)
868 return rc;
870 if (!dst)
871 client->opts |= OPT_NO_SIGNER;
872 else
873 client->crypto->save.sigkey = str_dup (*dst);
875 strv_free (dst);
876 return 0;
879 static gpg_error_t
880 parse_save_opt_inquire_keyid (void *data, void *value)
882 struct client_s *client = data;
884 (void)value;
886 if (!(client->flags & FLAG_NEW))
888 gpg_error_t rc = peer_is_invoker (client);
890 if (rc)
891 return rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc;
894 client->opts |= OPT_INQUIRE_KEYID;
895 return 0;
898 static gpg_error_t
899 parse_save_opt_symmetric (void *data, void *value)
901 struct client_s *client = data;
903 (void)value;
904 client->opts |= OPT_SYMMETRIC;
905 return 0;
908 static gpg_error_t
909 parse_genkey_opt_userid (void *data, void *value)
911 struct client_s *client = data;
913 if (!(client->flags & FLAG_NEW))
915 gpg_error_t rc = peer_is_invoker (client);
917 if (rc)
918 return rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc;
921 client->crypto->save.userid = str_dup (value);
922 return client->crypto->save.userid ? 0 : GPG_ERR_ENOMEM;
925 static gpg_error_t
926 parse_genkey_opt_algo (void *data, void *value)
928 struct client_s *client = data;
930 client->crypto->save.algo = str_dup (value);
931 return client->crypto->save.algo ? 0 : GPG_ERR_ENOMEM;
934 static gpg_error_t
935 parse_genkey_opt_expire (void *data, void *value)
937 struct client_s *client = data;
938 gpg_error_t rc = 0;
939 char *p = NULL;
940 unsigned long t;
942 errno = 0;
943 t = strtoul (value, &p, 10);
945 if (!errno && p && *p)
946 rc = GPG_ERR_INV_VALUE;
947 else if (t == ULONG_MAX)
948 rc = GPG_ERR_INV_VALUE;
949 else if (errno)
950 rc = gpg_error_from_syserror ();
951 else
952 client->crypto->save.expire = t;
954 return rc;
957 static gpg_error_t
958 parse_genkey_opt_no_passphrase (void *data, void *value)
960 struct client_s *client = data;
962 (void)value;
963 client->crypto->save.flags |= GPGME_CREATE_NOPASSWD;
964 return 0;
967 /* Tests that the keys in new_keys are also in old_keys. */
968 static gpg_error_t
969 compare_keys (char **new_keys, char **old_keys)
971 char **o;
973 if (!old_keys || !*old_keys)
974 return 0;
976 crypto_keyid_to_16b (new_keys);
978 for (o = old_keys; *o; o++)
980 char **n;
982 for (n = new_keys; *n; n++)
984 if (!strcmp (*n, *o))
985 break;
988 if (!*n)
989 return GPG_ERR_NOT_FOUND;
992 return 0;
995 static gpg_error_t
996 inquire_keyid (struct client_s *client)
998 gpg_error_t rc;
999 unsigned char *result = NULL;
1000 size_t len;
1001 const char *s = "KEYID";
1002 char ***orig;
1003 char ***save;
1005 orig = &client->crypto->pubkey;
1006 save = &client->crypto->save.pubkey;
1007 rc = assuan_inquire (client->ctx, s, &result, &len, 0);
1008 if (!rc)
1010 char **dst = NULL;
1012 rc = parse_save_opt_keyid_common (client, (const char **)*orig,
1013 (char *)result, &dst);
1014 if (!rc)
1015 *save = dst;
1018 xfree (result);
1019 return rc;
1023 /* When a key lookup in gpg-agent's cache fails, the agent tries the last
1024 * successful key to be unlocked. This prevents pwmd from successfully
1025 * clearing a signing key since the previous key, which more than likely
1026 * belongs to the same keypair as the encryption/decryption key, will have the
1027 * passphrase cached and therefore the signing key also cached. So we need to
1028 * clear both the signing and encryption keys to get the effect of requiring a
1029 * passphrase when generating a new keypair for an existing data file, or when
1030 * the "require_save_key" configuration parameter is set. This parameter is
1031 * mostly a failsafe of the gpg-agent option --ignore-cache-for-signing since
1032 * some/most/all users may fail to set it.
1034 static gpg_error_t
1035 save_command (assuan_context_t ctx, char *line)
1037 struct client_s *client = assuan_get_pointer (ctx);
1038 struct cache_data_s *cdata = NULL;
1039 int sym = 0;
1040 gpg_error_t rc = 0, cache_rc = 0;
1041 int defer = 0;
1042 struct argv_s *args[] = {
1043 &(struct argv_s) {"keyid", OPTION_TYPE_ARG, parse_save_opt_keyid},
1044 &(struct argv_s) {"inquire-keyid", OPTION_TYPE_NOARG,
1045 parse_save_opt_inquire_keyid },
1046 &(struct argv_s) {"sign-keyid", OPTION_TYPE_OPTARG,
1047 parse_save_opt_sign_keyid},
1048 &(struct argv_s) {"symmetric", OPTION_TYPE_NOARG,
1049 parse_save_opt_symmetric },
1050 NULL
1053 crypto_free_save (&client->crypto->save);
1054 client->crypto->save.expire = DEFAULT_EXPIRE;
1056 rc = crypto_is_symmetric (client->filename);
1057 if (!rc || rc == GPG_ERR_BAD_DATA || rc == GPG_ERR_ENOENT)
1059 if (!rc)
1061 client->opts |= OPT_SYMMETRIC;
1062 sym = 1;
1064 else if (rc == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
1065 rc = 0; // New file
1066 else
1067 rc = 0; // PKI
1070 if (rc)
1071 return send_error (ctx, rc);
1073 rc = parse_options (&line, args, client, 0);
1074 if (rc)
1075 return send_error (ctx, rc);
1077 if (config_get_boolean (client->filename, "require_save_key")
1078 || (client->opts & OPT_SYMMETRIC))
1079 client->opts |= OPT_ASK;
1081 rc = open_check_file (client->filename, NULL, NULL, 1);
1082 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
1084 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
1085 return send_error (ctx, rc);
1088 if (!rc)
1089 cache_rc = rc = cache_iscached (client->filename, &defer, 0, 1);
1091 if (gpg_err_code (rc) == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
1092 rc = 0;
1093 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
1094 rc = 0;
1096 if (rc)
1097 return send_error (ctx, rc);
1099 /* Specifying both a recipient and symmetric encryption is an error. */
1100 if ((client->opts & OPT_INQUIRE_KEYID) && (client->opts & OPT_SYMMETRIC))
1101 return send_error (ctx, GPG_ERR_CONFLICT);
1102 /* Existing file with a recipient and wanting symmetric is an error. */
1103 else if ((client->opts & OPT_SYMMETRIC) && client->crypto->save.pubkey)
1104 return send_error (ctx, GPG_ERR_CONFLICT);
1105 else if (client->crypto->save.pubkey && (client->opts & OPT_INQUIRE_KEYID))
1106 return send_error (ctx, GPG_ERR_CONFLICT);
1107 else if (!sym && (client->opts & OPT_SYMMETRIC) && !(client->flags & FLAG_NEW))
1108 return send_error (ctx, GPG_ERR_CONFLICT);
1109 /* New file that is not symmetric without either a recipient or signer. */
1110 else if ((client->flags & FLAG_NEW) && !(client->opts & OPT_SYMMETRIC)
1111 && (!client->crypto->save.pubkey || !client->crypto->save.sigkey))
1112 return send_error (ctx, GPG_ERR_SYNTAX);
1113 else if (client->opts & OPT_INQUIRE_KEYID)
1114 rc = inquire_keyid (client);
1116 if (!rc)
1118 client->crypto->keyfile = config_get_string (client->filename,
1119 "passphrase_file");
1120 rc = crypto_init_ctx (client->crypto, (client->flags & FLAG_NO_PINENTRY),
1121 client->crypto->keyfile);
1124 if (!rc && (client->flags & FLAG_NEW))
1126 /* Require --keyid when --sign-keyid exists to keep KEYINFO
1127 * synchronized. */
1128 if (!client->crypto->save.pubkey && client->crypto->save.sigkey
1129 && !(client->opts & OPT_SYMMETRIC))
1130 rc = GPG_ERR_NO_PUBKEY;
1132 else if (!rc)
1134 cdata = cache_get_data (client->filename, NULL);
1135 if (cdata)
1137 if (client->crypto->save.pubkey)
1138 rc = compare_keys (client->crypto->save.pubkey, cdata->pubkey);
1140 /* Always allow a signer for symmetric data files. */
1141 if (!rc && client->crypto->save.sigkey
1142 && !(client->opts & OPT_SYMMETRIC))
1143 rc = !strcmp (client->crypto->save.sigkey, cdata->sigkey)
1144 ? 0 : GPG_ERR_NOT_FOUND;
1146 /* Prevent saving to a recipient who is not in the original recipient
1147 * list without a passphrase. */
1148 if (rc || (client->crypto->sigkey && (client->opts & OPT_NO_SIGNER)))
1149 client->opts |= OPT_ASK;
1151 if (rc == GPG_ERR_NOT_FOUND)
1153 rc = peer_is_invoker (client);
1154 if (rc == GPG_ERR_EACCES)
1155 rc = GPG_ERR_FORBIDDEN;
1158 if (!client->crypto->save.pubkey
1159 && !(client->opts & OPT_SYMMETRIC))
1160 client->crypto->save.pubkey = strv_dup (cdata->pubkey);
1162 if (!rc && !client->crypto->save.sigkey && cdata->sigkey
1163 && !(client->opts & OPT_NO_SIGNER))
1164 client->crypto->save.sigkey = str_dup (cdata->sigkey);
1165 else if (!rc && !client->crypto->save.sigkey
1166 && (client->opts & OPT_NO_SIGNER)
1167 && !(client->opts & OPT_SYMMETRIC))
1168 rc = GPG_ERR_NO_SIGNATURE_SCHEME;
1170 else
1172 client->crypto->save.pubkey = strv_dup (client->crypto->pubkey);
1173 client->crypto->save.sigkey = str_dup (client->crypto->sigkey);
1177 if (!rc && !(client->flags & FLAG_NEW))
1179 /* Fixes {NEW_,SIGN_}PASSPHRASE inquire keywords. See passphrase_cb(). */
1180 if (client->opts & OPT_SYMMETRIC)
1181 client->crypto->flags |= CRYPTO_FLAG_PASSWD;
1183 if (client->opts & OPT_ASK)
1185 rc = cache_clear_agent_keys (client->filename, 1, 1);
1186 if (!rc)
1187 rc = crypto_try_decrypt (client, client->flags & FLAG_NO_PINENTRY);
1191 if (!rc && client->opts & OPT_SYMMETRIC)
1192 client->crypto->flags |= CRYPTO_FLAG_PASSWD_NEW;
1194 if (!rc)
1195 rc = xml_update_element_mtime (client, xmlDocGetRootElement (client->doc));
1197 if (!rc)
1199 int size;
1201 xmlDocDumpFormatMemory (client->doc, &client->crypto->plaintext, &size,
1203 if (size > 0)
1204 client->crypto->plaintext_size = (size_t) size;
1205 else
1206 rc = GPG_ERR_ENOMEM;
1208 if (!rc)
1210 client->crypto->flags |= (client->opts & OPT_SYMMETRIC) ? CRYPTO_FLAG_SYMMETRIC : 0;
1211 client->crypto->flags |= (client->flags & FLAG_NEW) ? CRYPTO_FLAG_NEWFILE : 0;
1212 client->crypto->flags |= !(client->opts & OPT_SYMMETRIC) ? CRYPTO_FLAG_PASSWD_SIGN : 0;
1213 rc = crypto_encrypt (client, client->crypto);
1214 client->crypto->flags &= ~CRYPTO_FLAG_SYMMETRIC;
1217 if (!rc)
1219 unsigned char *crc = NULL;
1220 size_t crclen = 0;
1222 rc = crypto_write_file (client->crypto, &crc, &crclen);
1223 pthread_cleanup_push ((void *)xfree, crc);
1224 if (!rc)
1226 if (!cache_rc)
1227 cdata = cache_get_data (client->filename, NULL);
1228 else
1229 cdata = xcalloc (1, sizeof (struct cache_data_s));
1232 if (!rc)
1234 rc = cache_encrypt (client->crypto);
1235 if (rc)
1237 cache_clear (NULL, client->filename, 1, 1);
1238 client->flags &= ~(FLAG_NEW);
1240 strv_free (client->crypto->pubkey);
1241 client->crypto->pubkey = NULL;
1242 if (client->crypto->save.pubkey)
1243 client->crypto->pubkey = strv_dup (client->crypto->save.pubkey);
1245 xfree (client->crypto->sigkey);
1246 client->crypto->sigkey = NULL;
1247 if (client->crypto->save.sigkey)
1248 client->crypto->sigkey = str_dup (client->crypto->save.sigkey);
1252 if (!rc)
1254 long timeout = config_get_long (client->filename, "cache_timeout");
1255 xmlDocPtr doc = xmlCopyDoc (client->doc, 1);
1257 if (!doc)
1258 rc = GPG_ERR_ENOMEM;
1260 if (!rc)
1262 cache_plaintext_release (&client->doc);
1263 strv_free (cdata->pubkey);
1264 cdata->pubkey = client->crypto->save.pubkey;
1265 client->crypto->save.pubkey = NULL;
1267 xfree (cdata->sigkey);
1268 cdata->sigkey = client->crypto->save.sigkey;
1269 client->crypto->save.sigkey = NULL;
1271 xfree (cdata->crc);
1272 cdata->crc = NULL;
1274 /* cache_encrypt() does in-place encryption */
1275 xfree (cdata->doc);
1276 cdata->doc = client->crypto->plaintext;
1277 client->crypto->plaintext = NULL;
1278 cdata->size = client->crypto->plaintext_size;
1279 client->crypto->plaintext_size = 0;
1281 client->doc = doc;
1282 cache_plaintext_set (client->filename, client->doc, 0);
1284 /* Update in case the cache entry expires the next SAVE may
1285 * not have any known keys. */
1286 strv_free (client->crypto->pubkey);
1287 client->crypto->pubkey = NULL;
1288 if (cdata->pubkey)
1289 client->crypto->pubkey = strv_dup (cdata->pubkey);
1291 xfree (client->crypto->sigkey);
1292 client->crypto->sigkey = NULL;
1293 if (cdata->sigkey)
1294 client->crypto->sigkey = str_dup (cdata->sigkey);
1296 if (!cache_rc) // wont increment refcount
1297 rc = cache_set_data (client->filename, cdata);
1298 else
1299 rc = cache_add_file (client->filename, cdata, timeout);
1302 if (!rc && (cache_rc || (client->flags & FLAG_NEW)))
1303 send_status_all (STATUS_CACHE, NULL);
1305 if (!rc)
1307 rc = update_checksum (client, crc, crclen);
1308 client->flags &= ~(FLAG_NEW);
1312 pthread_cleanup_pop (1);
1313 if (!rc)
1314 client->did_cow = 0;
1318 crypto_free_non_keys (client->crypto);
1319 return send_error (ctx, rc);
1322 static gpg_error_t
1323 parse_genkey_opt_usage (void *data, void *v)
1325 struct client_s *client = data;
1326 char *value = v;
1328 if (!value || !*value)
1329 return GPG_ERR_INV_VALUE;
1330 else if (!strcmp (value, "sign"))
1331 client->crypto->save.flags |= GPGME_CREATE_SIGN;
1332 else if (!strcmp (value, "encrypt"))
1333 client->crypto->save.flags |= GPGME_CREATE_ENCR;
1334 else if (!strcmp (value, "default"))
1335 client->crypto->save.flags &= ~(GPGME_CREATE_ENCR|GPGME_CREATE_SIGN);
1336 else
1337 return GPG_ERR_INV_VALUE;
1339 return 0;
1342 gpg_error_t
1343 parse_genkey_opt_subkey_of (void *data, void *v)
1345 gpg_error_t rc;
1346 struct client_s *client = data;
1347 char *value = v;
1348 char *tmp[] = { value, NULL };
1349 gpgme_key_t *keys = NULL;
1351 rc = peer_is_invoker (client);
1352 if (rc)
1353 return rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc;
1355 if (!value || !*value)
1356 return GPG_ERR_INV_VALUE;
1358 rc = crypto_list_keys (client->crypto, tmp, 1, &keys);
1359 if (rc)
1360 return rc;
1362 if (!keys || !*keys)
1364 crypto_free_key_list (keys);
1365 return GPG_ERR_NO_SECKEY;
1368 client->crypto->save.mainkey = keys;
1369 return 0;
1372 static gpg_error_t
1373 genkey_command (assuan_context_t ctx, char *line)
1375 struct client_s *client = assuan_get_pointer (ctx);
1376 struct crypto_s *crypto, *orig;
1377 gpg_error_t rc = 0;
1378 struct argv_s *args[] = {
1379 &(struct argv_s) {"userid", OPTION_TYPE_ARG,
1380 parse_genkey_opt_userid},
1381 &(struct argv_s) {"expire", OPTION_TYPE_ARG,
1382 parse_genkey_opt_expire},
1383 &(struct argv_s) {"algo", OPTION_TYPE_ARG,
1384 parse_genkey_opt_algo},
1385 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG,
1386 parse_genkey_opt_no_passphrase},
1387 &(struct argv_s) {"usage", OPTION_TYPE_ARG,
1388 parse_genkey_opt_usage},
1389 &(struct argv_s) {"subkey-of", OPTION_TYPE_ARG,
1390 parse_genkey_opt_subkey_of},
1391 NULL
1394 orig = client->crypto;
1395 rc = crypto_init (&crypto, ctx, client->filename,
1396 client->flags & FLAG_NO_PINENTRY, NULL);
1397 if (rc)
1398 return send_error (ctx, rc);
1400 client->crypto = crypto;
1401 rc = parse_options (&line, args, client, 0);
1402 if (rc)
1403 goto fail;
1405 if (!client->crypto->save.userid && !client->crypto->save.mainkey)
1407 rc = GPG_ERR_SYNTAX;
1408 goto fail;
1411 client->crypto->flags |= CRYPTO_FLAG_NEWFILE;
1413 if (client->crypto->save.userid || client->crypto->save.mainkey)
1414 rc = crypto_genkey (client, client->crypto);
1416 fail:
1417 crypto_free (crypto);
1418 client->crypto = orig;
1419 return send_error (ctx, rc);
1422 static gpg_error_t
1423 do_delete (assuan_context_t ctx, char *line)
1425 struct client_s *client = assuan_get_pointer (ctx);
1426 struct xml_request_s *req;
1427 xmlNodePtr n;
1428 gpg_error_t rc;
1430 rc = xml_new_request (client, line, XML_CMD_DELETE, &req);
1431 if (rc)
1432 return rc;
1434 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1435 xml_free_request (req);
1436 if (rc)
1437 return rc;
1439 rc = xml_is_element_owner (client, n);
1440 if (!rc)
1441 rc = xml_unlink_node (client, n);
1443 return rc;
1446 /* Won't update cdata->plaintext. Other clients are working on the original or
1447 * copy of the same document. The first client to SAVE wins and requires others
1448 * to reopen the data file do to a checksum error. */
1449 static gpg_error_t
1450 copy_on_write (struct client_s *client)
1452 struct cache_data_s *cdata;
1454 if (client->did_cow)
1455 return 0;
1457 cdata = cache_get_data (client->filename, NULL);
1458 if (cdata)
1460 gpg_error_t rc;
1461 xmlDocPtr doc = xmlCopyDoc (client->doc, 1);
1463 if (!doc)
1464 return GPG_ERR_ENOMEM;
1466 rc = cache_plaintext_set (client->filename, doc, 1);
1467 if (rc)
1469 xmlFree (doc);
1470 return rc;
1473 (void)cache_plaintext_release (&client->doc);
1474 client->doc = doc;
1475 client->did_cow = 1;
1476 return 0;
1479 return GPG_ERR_NO_DATA;
1482 static gpg_error_t
1483 delete_command (assuan_context_t ctx, char *line)
1485 struct client_s *client = assuan_get_pointer (ctx);
1486 gpg_error_t rc;
1487 struct argv_s *args[] = {
1488 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1489 NULL
1492 rc = parse_options (&line, args, client, 1);
1493 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1494 rc = GPG_ERR_SYNTAX;
1495 if (rc)
1496 return send_error (ctx, rc);
1498 rc = copy_on_write (client);
1499 if (rc)
1500 return send_error (ctx, rc);
1502 if (client->opts & OPT_INQUIRE)
1504 unsigned char *result;
1505 size_t len;
1507 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1508 if (rc)
1509 return send_error (ctx, rc);
1511 pthread_cleanup_push ((void *)xfree, result);
1512 rc = do_delete (ctx, (char *)result);
1513 pthread_cleanup_pop (1);
1515 else
1516 rc = do_delete (ctx, line);
1518 return send_error (ctx, rc);
1521 static gpg_error_t
1522 update_element_expirey (struct client_s *client, xmlNodePtr n)
1524 gpg_error_t rc = 0;
1525 xmlChar *expire, *incr;
1526 char *p;
1527 time_t e, e_orig, i;
1528 time_t now = time (NULL);
1530 expire = xml_attribute_value (n, (xmlChar *)"expire");
1531 if (!expire)
1532 return 0;
1534 errno = 0;
1535 e = strtoul ((char *)expire, &p, 10);
1536 if (errno || *p || e == ULONG_MAX || *expire == '-')
1538 xmlFree (expire);
1539 rc = GPG_ERR_ERANGE;
1540 goto fail;
1543 xmlFree (expire);
1544 incr = xml_attribute_value (n, (xmlChar *)"expire_increment");
1545 if (!incr)
1546 return 0;
1548 i = strtoul ((char *)incr, &p, 10);
1549 if (errno || *p || i == ULONG_MAX || *incr == '-')
1551 xmlFree (incr);
1552 rc = GPG_ERR_ERANGE;
1553 goto fail;
1556 xmlFree (incr);
1557 e_orig = e;
1558 e = now + i;
1559 p = str_asprintf ("%lu", e);
1560 if (!p)
1562 rc = GPG_ERR_ENOMEM;
1563 goto fail;
1566 rc = xml_add_attribute (client, n, "expire", p);
1567 xfree (p);
1568 if (!rc)
1569 rc = send_status (client->ctx, STATUS_EXPIRE, "%lu %lu", e_orig, e);
1571 fail:
1572 return rc;
1575 static gpg_error_t
1576 store_command (assuan_context_t ctx, char *line)
1578 struct client_s *client = assuan_get_pointer (ctx);
1579 gpg_error_t rc;
1580 size_t len;
1581 unsigned char *result;
1582 xmlNodePtr n, parent;
1583 int has_content;
1584 char *content = NULL;
1585 struct xml_request_s *req;
1587 if (line && *line)
1588 return send_error (ctx, GPG_ERR_SYNTAX);
1590 rc = copy_on_write (client);
1591 if (rc)
1592 return send_error (ctx, rc);
1594 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1595 if (rc)
1596 return send_error (ctx, rc);
1598 rc = xml_new_request (client, (char *)result, XML_CMD_STORE, &req);
1599 xfree (result);
1600 if (rc)
1601 return send_error (ctx, rc);
1603 /* Prevent passing the element content around to save some memory. */
1604 len = strv_length (req->args);
1605 has_content = line && line[strlen (line) - 1] != '\t' && len > 1;
1606 if (*(req->args+1) && !xml_valid_element_path (req->args, has_content))
1608 xml_free_request (req);
1609 return send_error (ctx, GPG_ERR_INV_VALUE);
1612 if (has_content || !*req->args[len-1])
1614 content = req->args[len-1];
1615 req->args[len-1] = NULL;
1618 if (strv_length (req->args) > 1)
1620 rc = xml_check_recursion (client, req);
1621 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
1622 goto fail;
1625 parent = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1627 if (!rc && len > 1)
1629 rc = xml_is_element_owner (client, parent);
1630 if (!rc)
1632 n = xml_find_text_node (parent->children);
1633 if (n)
1634 xmlNodeSetContent (n, (xmlChar *) content);
1635 else
1636 xmlNodeAddContent (parent, (xmlChar *) content);
1638 (void)xml_update_element_mtime (client, parent);
1639 (void)update_element_expirey (client, parent);
1643 fail:
1644 xfree (content);
1645 xml_free_request (req);
1646 return send_error (ctx, rc);
1649 static gpg_error_t
1650 xfer_data (assuan_context_t ctx, const char *line, int total)
1652 struct client_s *client = assuan_get_pointer (ctx);
1653 int to_send;
1654 int sent = 0;
1655 gpg_error_t rc = 0;
1656 int progress = config_get_integer ("global", "xfer_progress");
1657 int flush = 0;
1659 if (!(client->flags & FLAG_LOCK_CMD))
1660 rc = unlock_file_mutex (client, 0);
1661 if (rc && rc != GPG_ERR_NOT_LOCKED)
1662 return rc;
1664 progress =
1665 progress > 0 ? (progress / ASSUAN_LINELENGTH) * ASSUAN_LINELENGTH : 0;
1666 to_send = total < ASSUAN_LINELENGTH ? total : ASSUAN_LINELENGTH;
1667 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1669 if (rc)
1670 return rc;
1672 again:
1675 if (sent + to_send > total)
1676 to_send = total - sent;
1678 rc = assuan_send_data (ctx, flush ? NULL : (char *) line + sent,
1679 flush ? 0 : to_send);
1680 if (!rc)
1682 sent += flush ? 0 : to_send;
1684 if ((progress && !(sent % progress) && sent != total) ||
1685 (sent == total && flush))
1686 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1688 if (!flush && !rc && sent == total)
1690 flush = 1;
1691 goto again;
1695 while (!rc && sent < total);
1697 return rc;
1700 static gpg_error_t
1701 do_get (assuan_context_t ctx, char *line)
1703 struct client_s *client = assuan_get_pointer (ctx);
1704 gpg_error_t rc;
1705 struct xml_request_s *req;
1706 xmlNodePtr n;
1708 rc = xml_new_request (client, line, XML_CMD_NONE, &req);
1709 if (rc)
1710 return rc;
1712 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1713 if (!rc)
1715 if (n && n->children)
1717 xmlNodePtr tmp = n;
1719 n = xml_find_text_node (n->children);
1720 if (!n || !n->content || !*n->content)
1721 rc = GPG_ERR_NO_DATA;
1722 else
1724 rc = xfer_data (ctx, (char *) n->content, xmlStrlen (n->content));
1725 if (!rc)
1727 xmlChar *expire = xml_attribute_value (tmp,
1728 (xmlChar *)"expire");
1729 if (expire)
1731 time_t now = time (NULL);
1732 time_t e;
1733 char *p;
1735 errno = 0;
1736 e = strtoul ((char *)expire, &p, 10);
1737 if (errno || *p || e == ULONG_MAX || *expire == '-')
1738 log_write (_("invalid expire attribute value: %s"),
1739 expire);
1740 else if (now >= e)
1741 rc = send_status (ctx, STATUS_EXPIRE, "%lu 0", e);
1743 xmlFree (expire);
1748 else
1749 rc = GPG_ERR_NO_DATA;
1752 xml_free_request (req);
1753 return rc;
1756 static gpg_error_t
1757 get_command (assuan_context_t ctx, char *line)
1759 struct client_s *client = assuan_get_pointer (ctx);
1760 gpg_error_t rc;
1761 struct argv_s *args[] = {
1762 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1763 NULL
1766 rc = parse_options (&line, args, client, 1);
1767 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1768 rc = GPG_ERR_SYNTAX;
1769 if (rc)
1770 return send_error (ctx, rc);
1772 if (client->opts & OPT_INQUIRE)
1774 unsigned char *result;
1775 size_t len;
1777 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1778 if (rc)
1779 return send_error (ctx, rc);
1781 pthread_cleanup_push ((void *)xfree, result);
1782 rc = do_get (ctx, (char *)result);
1783 pthread_cleanup_pop (1);
1785 else
1786 rc = do_get (ctx, line);
1788 return send_error (ctx, rc);
1791 static void list_command_free1 (void *arg);
1792 static gpg_error_t
1793 realpath_command (assuan_context_t ctx, char *line)
1795 gpg_error_t rc;
1796 char **realpath = NULL;
1797 struct client_s *client = assuan_get_pointer (ctx);
1798 struct argv_s *args[] = {
1799 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1800 NULL
1803 rc = parse_options (&line, args, client, 1);
1804 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1805 rc = GPG_ERR_SYNTAX;
1806 if (rc)
1807 return send_error (ctx, rc);
1809 if (client->opts & OPT_INQUIRE)
1811 unsigned char *result;
1812 size_t len;
1814 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1815 if (rc)
1816 return send_error (ctx, rc);
1818 pthread_cleanup_push ((void *)xfree, result);
1819 (void)xml_resolve_path (client, client->doc, result, &realpath, &rc);
1820 pthread_cleanup_pop (1);
1822 else
1823 (void)xml_resolve_path (client, client->doc, (unsigned char *)line,
1824 &realpath, &rc);
1826 if (!rc)
1828 char *tmp = strv_join ((char *)"\t", realpath);
1830 strv_free (realpath);
1831 if (!tmp)
1832 return send_error (ctx, GPG_ERR_ENOMEM);
1834 pthread_cleanup_push ((void *)xfree, tmp);
1835 rc = xfer_data (ctx, tmp, strlen (tmp));
1836 pthread_cleanup_pop (1);
1839 return send_error (ctx, rc);
1842 static void
1843 list_command_free1 (void *arg)
1845 if (arg)
1846 string_free ((struct string_s *) arg, 1);
1849 static gpg_error_t
1850 parse_list_opt_recurse (void *data, void *value)
1852 struct client_s *client = data;
1854 (void)value;
1855 client->opts |= OPT_LIST_RECURSE;
1856 return 0;
1859 static gpg_error_t
1860 parse_opt_verbose (void *data, void *value)
1862 struct client_s *client = data;
1864 (void)value;
1865 client->opts |= OPT_VERBOSE;
1866 return 0;
1869 static gpg_error_t
1870 list_path_once (struct client_s *client, char *line,
1871 struct element_list_s *elements, struct string_s *result)
1873 gpg_error_t rc;
1875 rc = xml_create_path_list (client, client->doc, NULL, elements, line, 0);
1876 if (rc == GPG_ERR_ELOOP || rc == GPG_ERR_EACCES)
1877 rc = 0;
1879 if (!rc)
1881 int total = slist_length (elements->list);
1883 if (total)
1885 int i;
1887 for (i = 0; i < total; i++)
1889 char *tmp = slist_nth_data (elements->list, i);
1891 string_append_printf (result, "%s%s", tmp,
1892 i + 1 == total ? "" : "\n");
1895 else
1896 rc = GPG_ERR_NO_DATA;
1899 return rc;
1902 static gpg_error_t
1903 do_list (assuan_context_t ctx, char *line)
1905 struct client_s *client = assuan_get_pointer (ctx);
1906 gpg_error_t rc = GPG_ERR_NO_DATA;
1907 struct element_list_s *elements = NULL;
1909 if (!line || !*line)
1911 struct string_s *str = string_new (NULL);
1912 xmlNodePtr n;
1914 if (!str)
1915 return GPG_ERR_ENOMEM;
1917 pthread_cleanup_push ((void *)list_command_free1, str);
1918 n = xmlDocGetRootElement (client->doc);
1919 for (n = n->children; n; n = n->next)
1921 xmlChar *name;
1923 if (n->type != XML_ELEMENT_NODE)
1924 continue;
1926 name = xmlGetProp (n, (xmlChar *)"_name");
1927 if (!name)
1929 rc = GPG_ERR_ENOMEM;
1930 break;
1933 elements = xcalloc (1, sizeof (struct element_list_s));
1934 if (!elements)
1936 xmlFree (name);
1937 rc = GPG_ERR_ENOMEM;
1938 break;
1941 elements->prefix = string_new (NULL);
1942 if (!elements->prefix)
1944 xmlFree (name);
1945 xml_free_element_list (elements);
1946 rc = GPG_ERR_ENOMEM;
1947 break;
1950 elements->recurse = client->opts & OPT_LIST_RECURSE;
1951 elements->root_only = !elements->recurse;
1952 pthread_cleanup_push ((void *)xml_free_element_list, elements);
1953 rc = list_path_once (client, (char *)name, elements, str);
1954 xmlFree (name);
1955 pthread_cleanup_pop (1);
1956 if (rc)
1957 break;
1959 if (n->next)
1960 string_append (str, "\n");
1963 if (!rc)
1964 rc = xfer_data (ctx, str->str, str->len);
1966 pthread_cleanup_pop (1);
1967 return rc;
1970 elements = xcalloc (1, sizeof (struct element_list_s));
1971 if (!elements)
1972 return GPG_ERR_ENOMEM;
1974 elements->prefix = string_new (NULL);
1975 if (!elements->prefix)
1977 xml_free_element_list (elements);
1978 return GPG_ERR_ENOMEM;
1981 elements->recurse = client->opts & OPT_LIST_RECURSE;
1982 pthread_cleanup_push ((void *)xml_free_element_list, elements);
1983 struct string_s *str = string_new (NULL);
1984 pthread_cleanup_push ((void *)list_command_free1, str);
1985 rc = list_path_once (client, line, elements, str);
1986 if (!rc)
1987 rc = xfer_data (ctx, str->str, str->len);
1989 pthread_cleanup_pop (1);
1990 pthread_cleanup_pop (1);
1991 return rc;
1994 static gpg_error_t
1995 list_command (assuan_context_t ctx, char *line)
1997 struct client_s *client = assuan_get_pointer (ctx);
1998 gpg_error_t rc;
1999 struct argv_s *args[] = {
2000 &(struct argv_s) {"recurse", OPTION_TYPE_NOARG, parse_list_opt_recurse},
2001 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2002 /* These are deprecated but kept for backward compatibility with older
2003 * clients. */
2004 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, NULL},
2005 &(struct argv_s) {"with-target", OPTION_TYPE_NOARG, NULL},
2006 &(struct argv_s) {"all", OPTION_TYPE_NOARG, parse_list_opt_recurse},
2007 &(struct argv_s) {"no-recurse", OPTION_TYPE_NOARG, NULL},
2008 NULL
2011 if (disable_list_and_dump == 1)
2012 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2014 rc = parse_options (&line, args, client, 1);
2015 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2016 rc = GPG_ERR_SYNTAX;
2017 if (rc)
2018 return send_error (ctx, rc);
2020 if (client->opts & OPT_INQUIRE)
2022 unsigned char *result;
2023 size_t len;
2025 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2026 if (rc)
2027 return send_error (ctx, rc);
2029 pthread_cleanup_push ((void *)xfree, result);
2030 rc = do_list (ctx, (char *)result);
2031 pthread_cleanup_pop (1);
2033 else
2034 rc = do_list (ctx, line);
2036 return send_error (ctx, rc);
2039 #define RESUMABLE_ERROR(rc) (rc == GPG_ERR_ELOOP || rc == GPG_ERR_EACCES \
2040 || rc == GPG_ERR_ELEMENT_NOT_FOUND || !rc)
2042 * args[0] - element path
2044 static gpg_error_t
2045 attribute_list (assuan_context_t ctx, char **args)
2047 struct client_s *client = assuan_get_pointer (ctx);
2048 char **attrlist = NULL;
2049 int i = 0;
2050 int target = 0;
2051 xmlAttrPtr a;
2052 xmlNodePtr n, an, r;
2053 char *line;
2054 gpg_error_t rc;
2055 struct xml_request_s *req;
2057 if (!args || !args[0] || !*args[0])
2058 return GPG_ERR_SYNTAX;
2060 rc = xml_new_request (client, args[0], XML_CMD_ATTR_LIST, &req);
2061 if (rc)
2062 return rc;
2064 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2065 xml_free_request (req);
2066 if (rc)
2067 return rc;
2069 again:
2070 for (a = n->properties; a; a = a->next)
2072 char **pa;
2074 if (target && xml_reserved_attribute ((char *)a->name))
2075 continue;
2077 pa = xrealloc (attrlist, (i + 2) * sizeof (char *));
2078 if (!pa)
2080 if (attrlist)
2081 strv_free (attrlist);
2083 log_write ("%s(%i): %s", __FILE__, __LINE__,
2084 pwmd_strerror (GPG_ERR_ENOMEM));
2085 return GPG_ERR_ENOMEM;
2088 attrlist = pa;
2089 an = a->children;
2090 attrlist[i] = str_asprintf ("%s %s", (char *) a->name, an && an->content
2091 ? (char *)an->content : "");
2093 if (!attrlist[i])
2095 strv_free (attrlist);
2096 log_write ("%s(%i): %s", __FILE__, __LINE__,
2097 pwmd_strerror (GPG_ERR_ENOMEM));
2098 return GPG_ERR_ENOMEM;
2101 attrlist[++i] = NULL;
2104 if (!attrlist)
2105 return GPG_ERR_NO_DATA;
2107 if (!target)
2109 r = xml_resolve_path (client, client->doc, (xmlChar *)args[0], NULL, &rc);
2110 if (!RESUMABLE_ERROR (rc))
2112 strv_free (attrlist);
2113 return rc;
2115 else if (!rc && r != n)
2117 target = 1;
2118 n = r;
2119 goto again;
2122 rc = 0;
2125 line = strv_join ("\n", attrlist);
2126 if (!line)
2128 log_write ("%s(%i): %s", __FILE__, __LINE__,
2129 pwmd_strerror (GPG_ERR_ENOMEM));
2130 strv_free (attrlist);
2131 return GPG_ERR_ENOMEM;
2134 pthread_cleanup_push ((void *)xfree, line);
2135 pthread_cleanup_push ((void *)req_free, attrlist);
2136 rc = xfer_data (ctx, line, strlen (line));
2137 pthread_cleanup_pop (1);
2138 pthread_cleanup_pop (1);
2139 return rc;
2143 * args[0] - attribute
2144 * args[1] - element path
2146 static gpg_error_t
2147 attribute_delete (struct client_s *client, char **args)
2149 gpg_error_t rc;
2150 xmlNodePtr n;
2152 if (!args || !args[0] || !*args[0] || !args[1] || !*args[1])
2153 return GPG_ERR_SYNTAX;
2155 if (!strcmp (args[0], "_name") || !strcmp (args[0], "target"))
2156 return GPG_ERR_INV_ATTR;
2158 rc = copy_on_write (client);
2159 if (rc)
2160 return rc;
2162 if (!xml_reserved_attribute (args[0]))
2163 n = xml_resolve_path (client, client->doc, (xmlChar *)args[1], NULL, &rc);
2164 else
2166 struct xml_request_s *req;
2168 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
2169 if (rc)
2170 return rc;
2172 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2173 xml_free_request (req);
2176 if (!rc)
2177 rc = xml_is_element_owner (client, n);
2179 if (!rc)
2180 rc = xml_delete_attribute (client, n, (xmlChar *) args[0]);
2182 return rc;
2186 * Creates the "target" attribute. When other commands encounter an element
2187 * with this attribute they follow the "target" after appending remaining
2188 * elements from the original element path to the target. The exception is the
2189 * ATTR command that operates on the element itself (for reserved attribute
2190 * names) and not the target.
2192 * If the source element path doesn't exist when using 'ATTR SET target', it is
2193 * created, but the destination element path must exist. This is simliar to the
2194 * ls(1) command: ln -s src dst.
2196 * args[0] - source element path
2197 * args[1] - destination element path
2199 static gpg_error_t
2200 set_target_attribute (struct client_s *client, char **args)
2202 struct xml_request_s *req = NULL;
2203 char **src, **dst;
2204 gpg_error_t rc;
2205 xmlNodePtr n;
2207 if (!args || !args[0] || !args[1])
2208 return GPG_ERR_SYNTAX;
2210 src = str_split (args[0], "\t", 0);
2211 if (!src)
2212 return GPG_ERR_SYNTAX;
2214 if (!xml_valid_element_path (src, 0))
2216 strv_free (src);
2217 return GPG_ERR_INV_VALUE;
2220 dst = str_split (args[1], "\t", 0);
2221 if (!dst)
2223 strv_free (src);
2224 return GPG_ERR_SYNTAX;
2227 rc = copy_on_write (client);
2228 if (rc)
2229 goto fail;
2231 // Be sure the destination element path exists. */
2232 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
2233 if (rc)
2234 goto fail;
2236 (void)xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2237 if (rc && rc != GPG_ERR_EACCES)
2238 goto fail;
2240 xml_free_request (req);
2241 req = NULL;
2243 if (!strcmp (args[0], args[1]))
2245 rc = GPG_ERR_EEXIST;
2246 goto fail;
2249 rc = xml_new_request (client, args[0], XML_CMD_ATTR_TARGET, &req);
2250 if (rc)
2251 goto fail;
2253 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2254 if (rc && rc != GPG_ERR_EACCES)
2255 goto fail;
2257 if (!rc)
2259 rc = xml_add_attribute (client, n, "target", args[1]);
2260 if (!rc)
2261 rc = xml_unlink_node (client, n->children);
2264 fail:
2265 strv_free (src);
2266 strv_free (dst);
2267 xml_free_request (req);
2268 return rc;
2272 * args[0] - attribute
2273 * args[1] - element path
2275 static gpg_error_t
2276 attribute_get (assuan_context_t ctx, char **args)
2278 struct client_s *client = assuan_get_pointer (ctx);
2279 xmlNodePtr n;
2280 xmlChar *a;
2281 gpg_error_t rc;
2282 struct xml_request_s *req;
2284 if (!args || !args[0] || !*args[0] || !args[1] || !*args[1])
2285 return GPG_ERR_SYNTAX;
2287 if (!xml_reserved_attribute (args[0]))
2288 n = xml_resolve_path (client, client->doc, (xmlChar *)args[1], NULL, &rc);
2289 else
2291 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
2292 if (rc)
2293 return rc;
2295 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2296 xml_free_request (req);
2299 if (rc)
2300 return rc;
2302 a = xmlGetProp (n, (xmlChar *) args[0]);
2303 if (!a)
2304 return GPG_ERR_NOT_FOUND;
2306 pthread_cleanup_push ((void *)xmlFree, a);
2308 if (*a)
2309 rc = xfer_data (ctx, (char *) a, xmlStrlen (a));
2310 else
2311 rc = GPG_ERR_NO_DATA;
2313 pthread_cleanup_pop (1);
2314 return rc;
2318 * args[0] - attribute
2319 * args[1] - element path
2320 * args[2] - value
2322 static gpg_error_t
2323 attribute_set (struct client_s *client, char **args)
2325 struct xml_request_s *req;
2326 gpg_error_t rc;
2327 xmlNodePtr n;
2329 if (!args || !args[0] || !args[1])
2330 return GPG_ERR_SYNTAX;
2333 * Reserved attribute names.
2335 if (!strcmp (args[0], "_name")) // Use the RENAME command instead
2336 return GPG_ERR_INV_ATTR;
2337 else if (!strcmp (args[0], "target"))
2338 return set_target_attribute (client, args + 1);
2339 else if (!xml_valid_attribute (args[0]))
2340 return GPG_ERR_INV_VALUE;
2342 if (!xml_valid_attribute_value (args[2]))
2343 return GPG_ERR_INV_VALUE;
2345 rc = copy_on_write (client);
2346 if (rc)
2347 return rc;
2349 if (!xml_reserved_attribute (args[0]))
2351 n = xml_resolve_path (client, client->doc, (xmlChar *)args[1], NULL, &rc);
2352 if (!rc)
2354 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
2355 if (!rc)
2357 rc = xml_check_recursion (client, req);
2358 xml_free_request (req);
2362 else
2364 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
2365 if (rc)
2366 return rc;
2368 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2369 xml_free_request (req);
2372 if (!rc)
2373 rc = xml_is_element_owner (client, n);
2375 if (!rc)
2376 rc = xml_add_attribute (client, n, args[0], args[2]);
2378 return rc;
2382 * req[0] - command
2383 * req[1] - attribute name or element path if command is LIST
2384 * req[2] - element path
2385 * req[2] - element path or value
2388 static gpg_error_t
2389 do_attr (assuan_context_t ctx, char *line)
2391 struct client_s *client = assuan_get_pointer (ctx);
2392 gpg_error_t rc = 0;
2393 char **req;
2395 req = str_split (line, " ", 4);
2396 if (!req || !req[0] || !req[1])
2398 strv_free (req);
2399 return GPG_ERR_SYNTAX;
2402 pthread_cleanup_push ((void *)req_free, req);
2404 if (strcasecmp (req[0], "SET") == 0)
2405 rc = attribute_set (client, req + 1);
2406 else if (strcasecmp (req[0], "GET") == 0)
2407 rc = attribute_get (ctx, req + 1);
2408 else if (strcasecmp (req[0], "DELETE") == 0)
2409 rc = attribute_delete (client, req + 1);
2410 else if (strcasecmp (req[0], "LIST") == 0)
2411 rc = attribute_list (ctx, req + 1);
2412 else
2413 rc = GPG_ERR_SYNTAX;
2415 client->flags &= ~(FLAG_ACL_IGNORE|FLAG_ACL_ERROR);
2416 pthread_cleanup_pop (1);
2417 return rc;
2420 static gpg_error_t
2421 attr_command (assuan_context_t ctx, char *line)
2423 struct client_s *client = assuan_get_pointer (ctx);
2424 gpg_error_t rc;
2425 struct argv_s *args[] = {
2426 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2427 NULL
2430 rc = parse_options (&line, args, client, 1);
2431 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2432 rc = GPG_ERR_SYNTAX;
2433 if (rc)
2434 return send_error (ctx, rc);
2436 if (client->opts & OPT_INQUIRE)
2438 unsigned char *result;
2439 size_t len;
2441 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2442 if (rc)
2443 return send_error (ctx, rc);
2445 pthread_cleanup_push ((void *)xfree, result);
2446 rc = do_attr (ctx, (char *)result);
2447 pthread_cleanup_pop (1);
2449 else
2450 rc = do_attr (ctx, line);
2452 return send_error (ctx, rc);
2455 static gpg_error_t
2456 parse_iscached_opt_lock (void *data, void *value)
2458 struct client_s *client = data;
2460 (void) value;
2461 client->opts |= OPT_LOCK;
2462 return 0;
2465 static gpg_error_t
2466 parse_iscached_opt_agent (void *data, void *value)
2468 struct client_s *client = data;
2470 (void) value;
2471 client->opts |= OPT_CACHE_AGENT;
2472 return 0;
2475 static gpg_error_t
2476 parse_iscached_opt_sign (void *data, void *value)
2478 struct client_s *client = data;
2480 (void) value;
2481 client->opts |= OPT_CACHE_SIGN;
2482 return 0;
2485 static gpg_error_t
2486 iscached_command (assuan_context_t ctx, char *line)
2488 struct client_s *client = assuan_get_pointer (ctx);
2489 gpg_error_t rc;
2490 int defer = 0;
2491 struct argv_s *args[] = {
2492 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_iscached_opt_lock},
2493 &(struct argv_s) {"agent", OPTION_TYPE_NOARG, parse_iscached_opt_agent},
2494 &(struct argv_s) {"sign", OPTION_TYPE_NOARG, parse_iscached_opt_sign},
2495 NULL
2498 if (!line || !*line)
2499 return send_error (ctx, GPG_ERR_SYNTAX);
2501 rc = parse_options (&line, args, client, 1);
2502 if (rc)
2503 return send_error (ctx, rc);
2504 else if (!valid_filename (line))
2505 return send_error (ctx, GPG_ERR_INV_VALUE);
2507 if (!(client->flags & FLAG_OPEN)
2508 && ((client->opts & OPT_CACHE_AGENT) || (client->opts & OPT_CACHE_SIGN)))
2509 return send_error (ctx, GPG_ERR_INV_STATE);
2511 rc = cache_iscached (line, &defer, (client->opts & OPT_CACHE_AGENT),
2512 (client->opts & OPT_CACHE_SIGN));
2513 if (!rc && defer)
2514 rc = GPG_ERR_NO_DATA;
2516 if (!rc)
2518 struct cache_data_s *cdata = cache_get_data (line, NULL);
2520 if (cdata)
2522 rc = validate_checksum (client, line, cdata, NULL, NULL);
2523 if (rc == GPG_ERR_CHECKSUM)
2524 rc = GPG_ERR_NO_DATA;
2528 if (client->opts & OPT_LOCK
2529 && (!rc || gpg_err_code (rc) == GPG_ERR_NO_DATA))
2531 gpg_error_t trc = rc;
2533 if (strcmp (line, client->filename))
2534 reset_client (client);
2536 xfree (client->filename);
2537 client->filename = str_dup (line);
2538 rc = do_lock (client, 1);
2539 if (!rc)
2540 rc = trc;
2543 return send_error (ctx, rc);
2546 static gpg_error_t
2547 clearcache_command (assuan_context_t ctx, char *line)
2549 struct client_s *client = assuan_get_pointer (ctx);
2550 gpg_error_t rc = 0, all_rc = 0;
2551 int i;
2552 int t;
2553 int all = 0;
2554 struct client_thread_s *once = NULL;
2555 unsigned count;
2557 cache_lock ();
2558 pthread_cleanup_push (cache_release_mutex, NULL);
2559 count = cache_file_count ();
2560 MUTEX_LOCK (&cn_mutex);
2561 pthread_cleanup_push ((void *)release_mutex_cb, &cn_mutex);
2563 if (!line || !*line)
2564 all = 1;
2566 t = slist_length (cn_thread_list);
2568 for (i = 0; i < t; i++)
2570 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2571 assuan_peercred_t peer;
2573 if (!thd->cl)
2574 continue;
2576 /* Lock each connected clients' file mutex to prevent any other client
2577 * from accessing the cache entry (the file mutex is locked upon
2578 * command startup). The cache for the entry is not cleared if the
2579 * file mutex is locked by another client to prevent this function
2580 * from blocking. Rather, it returns an error.
2582 if (all)
2584 if (thd->cl->filename)
2586 rc = do_validate_peer (ctx, thd->cl->filename, &peer);
2587 /* The current client doesn't have permission to open the other
2588 * filename do to "access" configuration parameter in a filename
2589 * section. Since we are clearning all cache entries the error
2590 * will be returned later during cache_clear(). */
2591 if (rc)
2593 rc = 0;
2594 continue;
2597 else // Idle client without opened file?
2598 continue;
2600 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->filename, -1, 0, -1);
2601 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2603 /* The current client owns the lock. */
2604 if (pthread_equal (pthread_self (), thd->tid))
2605 rc = 0;
2606 else
2608 if (cache_iscached (thd->cl->filename, NULL, 0, 0)
2609 == GPG_ERR_NO_DATA)
2611 rc = 0;
2612 continue;
2615 /* The cache entry will be cleared when the other client
2616 * disconnects and cache_timer_thread() does its thing. */
2617 cache_defer_clear (thd->cl->filename);
2620 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
2622 rc = 0;
2623 continue;
2626 if (!rc)
2628 rc = cache_clear (NULL, thd->cl->filename, 1, 0);
2629 cache_unlock_mutex (thd->cl->filename, 0);
2632 if (rc)
2633 all_rc = rc;
2635 rc = 0;
2637 else
2639 /* A single data filename was specified. Lock only this data file
2640 * mutex and free the cache entry. */
2641 rc = do_validate_peer (ctx, line, &peer);
2642 if (rc == GPG_ERR_FORBIDDEN)
2643 rc = peer_is_invoker (client);
2645 if (rc == GPG_ERR_EACCES)
2646 rc = GPG_ERR_FORBIDDEN;
2648 if (!rc && thd->cl->filename && !strcmp (thd->cl->filename , line))
2650 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->filename, -1, 0, -1);
2651 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2653 /* The current client owns the lock. */
2654 if (pthread_equal (pthread_self (), thd->tid))
2655 rc = 0;
2658 if (!rc)
2660 once = thd;
2661 rc = cache_clear (NULL, thd->cl->filename, 1, 0);
2662 cache_unlock_mutex (thd->cl->filename, 0);
2664 else
2665 cache_defer_clear (thd->cl->filename);
2667 /* Found a client with the opened file. The cache entry has been
2668 * either cleared (self) or defered to be cleared. */
2669 break;
2674 /* Only connected clients' cache entries have been cleared. Now clear any
2675 * remaining cache entries without clients but only if there wasn't an
2676 * error from above since this would defeat the locking check of the
2677 * remaining entries. */
2678 if (all && !all_rc && cache_file_count ())
2680 rc = cache_clear (client, NULL, 1, 0);
2681 if (rc == GPG_ERR_EACCES)
2682 rc = GPG_ERR_FORBIDDEN;
2685 /* No clients are using the specified file. */
2686 else if (!all_rc && !rc && !once)
2687 rc = cache_clear (NULL, line, 1, 0);
2689 /* Release the connection mutex. */
2690 pthread_cleanup_pop (1);
2692 if (!rc || (cache_file_count () && count != cache_file_count ()))
2693 send_status_all (STATUS_CACHE, NULL);
2695 /* Release the cache mutex. */
2696 pthread_cleanup_pop (1);
2698 /* One or more files were locked while clearing all cache entries. */
2699 if (all_rc)
2700 rc = all_rc;
2702 return send_error (ctx, rc);
2705 static gpg_error_t
2706 cachetimeout_command (assuan_context_t ctx, char *line)
2708 struct client_s *client = assuan_get_pointer (ctx);
2709 long timeout;
2710 char **req = str_split (line, " ", 0);
2711 char *p;
2712 gpg_error_t rc = 0;
2713 assuan_peercred_t peer;
2715 if (!req || !*req || !req[1] || !*req[1])
2717 strv_free (req);
2718 return send_error (ctx, GPG_ERR_SYNTAX);
2721 errno = 0;
2722 timeout = strtol (req[1], &p, 10);
2723 if (errno != 0 || *p || timeout < (long)-1)
2725 strv_free (req);
2726 return send_error (ctx, GPG_ERR_SYNTAX);
2729 rc = do_validate_peer (ctx, req[0], &peer);
2730 if (rc == GPG_ERR_FORBIDDEN)
2732 rc = peer_is_invoker (client);
2733 if (rc == GPG_ERR_EACCES)
2734 rc = GPG_ERR_FORBIDDEN;
2737 if (!rc)
2739 rc = cache_set_timeout (req[0], timeout);
2740 if (!rc || gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
2742 rc = 0;
2743 MUTEX_LOCK (&rcfile_mutex);
2744 config_set_long_param (&global_config, req[0], "cache_timeout",
2745 req[1]);
2746 MUTEX_UNLOCK (&rcfile_mutex);
2750 strv_free (req);
2751 return send_error (ctx, rc);
2754 static gpg_error_t
2755 dump_command (assuan_context_t ctx, char *line)
2757 xmlChar *xml;
2758 int len;
2759 struct client_s *client = assuan_get_pointer (ctx);
2760 gpg_error_t rc;
2762 if (disable_list_and_dump == 1)
2763 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2765 if (line && *line)
2766 return send_error (ctx, GPG_ERR_SYNTAX);
2768 rc = peer_is_invoker(client);
2769 if (rc)
2770 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
2772 xmlDocDumpFormatMemory (client->doc, &xml, &len, 1);
2774 if (!xml)
2776 log_write ("%s(%i): %s", __FILE__, __LINE__,
2777 pwmd_strerror (GPG_ERR_ENOMEM));
2778 return send_error (ctx, GPG_ERR_ENOMEM);
2781 pthread_cleanup_push ((void *)xmlFree, xml);
2782 rc = xfer_data (ctx, (char *) xml, len);
2783 pthread_cleanup_pop (1);
2784 return send_error (ctx, rc);
2787 static gpg_error_t
2788 getconfig_command (assuan_context_t ctx, char *line)
2790 struct client_s *client = assuan_get_pointer (ctx);
2791 gpg_error_t rc = 0;
2792 char filename[255] = { 0 }, param[747] = { 0 };
2793 char *p, *tmp = NULL, *fp = client->filename, *paramp = line;
2795 if (!line || !*line)
2796 return send_error (ctx, GPG_ERR_SYNTAX);
2798 if (strchr (line, ' '))
2800 int ret = sscanf (line, " %254[^ ] %746c", filename, param);
2802 if (ret <= 0)
2803 return send_error (ctx, gpg_error_from_syserror());
2804 paramp = param;
2805 fp = filename;
2808 if (fp && !valid_filename (fp))
2809 return send_error (ctx, GPG_ERR_INV_VALUE);
2811 paramp = str_down (paramp);
2812 p = config_get_value (fp ? fp : "global", paramp);
2813 if (!p)
2814 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2816 tmp = expand_homedir (p);
2817 xfree (p);
2818 if (!tmp)
2820 log_write ("%s(%i): %s", __FILE__, __LINE__,
2821 pwmd_strerror (GPG_ERR_ENOMEM));
2822 return send_error (ctx, GPG_ERR_ENOMEM);
2825 p = tmp;
2826 pthread_cleanup_push ((void *)xfree, p);
2827 rc = xfer_data (ctx, p, strlen (p));
2828 pthread_cleanup_pop (1);
2829 return send_error (ctx, rc);
2832 struct xpath_s
2834 xmlXPathContextPtr xp;
2835 xmlXPathObjectPtr result;
2836 xmlBufferPtr buf;
2837 char **req;
2840 static void
2841 xpath_command_free (void *arg)
2843 struct xpath_s *xpath = arg;
2845 if (!xpath)
2846 return;
2848 req_free (xpath->req);
2850 if (xpath->buf)
2851 xmlBufferFree (xpath->buf);
2853 if (xpath->result)
2854 xmlXPathFreeObject (xpath->result);
2856 if (xpath->xp)
2857 xmlXPathFreeContext (xpath->xp);
2860 static gpg_error_t
2861 do_xpath (assuan_context_t ctx, char *line)
2863 gpg_error_t rc;
2864 struct client_s *client = assuan_get_pointer (ctx);
2865 struct xpath_s _x = { 0 };
2866 struct xpath_s *xpath = &_x;
2868 if (!line || !*line)
2869 return GPG_ERR_SYNTAX;
2871 if ((xpath->req = str_split (line, "\t", 2)) == NULL)
2873 if (strv_printf (&xpath->req, "%s", line) == 0)
2874 return GPG_ERR_ENOMEM;
2877 if (xpath->req[1])
2879 rc = copy_on_write (client);
2880 if (rc)
2881 goto fail;
2884 xpath->xp = xmlXPathNewContext (client->doc);
2885 if (!xpath->xp)
2887 rc = GPG_ERR_BAD_DATA;
2888 goto fail;
2891 xpath->result =
2892 xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2893 if (!xpath->result)
2895 rc = GPG_ERR_BAD_DATA;
2896 goto fail;
2899 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2901 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2902 goto fail;
2905 rc = xml_recurse_xpath_nodeset (client, client->doc,
2906 xpath->result->nodesetval,
2907 (xmlChar *) xpath->req[1], &xpath->buf, 0,
2908 NULL);
2909 if (rc)
2910 goto fail;
2911 else if (!xpath->req[1] && !xmlBufferLength (xpath->buf))
2913 rc = GPG_ERR_NO_DATA;
2914 goto fail;
2916 else if (xpath->req[1])
2918 rc = 0;
2919 goto fail;
2922 pthread_cleanup_push ((void *)xpath_command_free, &xpath);
2923 rc = xfer_data (ctx, (char *) xmlBufferContent (xpath->buf),
2924 xmlBufferLength (xpath->buf));
2925 pthread_cleanup_pop (0);
2926 fail:
2927 xpath_command_free (xpath);
2928 return rc;
2931 static gpg_error_t
2932 xpath_command (assuan_context_t ctx, char *line)
2934 struct client_s *client = assuan_get_pointer (ctx);
2935 gpg_error_t rc;
2936 struct argv_s *args[] = {
2937 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2938 NULL
2941 if (disable_list_and_dump == 1)
2942 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2944 rc = peer_is_invoker(client);
2945 if (rc)
2946 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
2948 rc = parse_options (&line, args, client, 1);
2949 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2950 rc = GPG_ERR_SYNTAX;
2951 if (rc)
2952 return send_error (ctx, rc);
2954 if (client->opts & OPT_INQUIRE)
2956 unsigned char *result;
2957 size_t len;
2959 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2960 if (rc)
2961 return send_error (ctx, rc);
2963 pthread_cleanup_push ((void *)xfree, result);
2964 rc = do_xpath (ctx, (char *)result);
2965 pthread_cleanup_pop (1);
2967 else
2968 rc = do_xpath (ctx, line);
2970 return send_error (ctx, rc);
2973 static gpg_error_t
2974 do_xpathattr (assuan_context_t ctx, char *line)
2976 struct client_s *client = assuan_get_pointer (ctx);
2977 gpg_error_t rc;
2978 char **req = NULL;
2979 int cmd = 0; //SET
2980 struct xpath_s _x = { 0 };
2981 struct xpath_s *xpath = &_x;
2983 if (!line || !*line)
2984 return GPG_ERR_SYNTAX;
2986 if ((req = str_split (line, " ", 3)) == NULL)
2987 return GPG_ERR_ENOMEM;
2989 if (!req[0])
2991 rc = GPG_ERR_SYNTAX;
2992 goto fail;
2995 if (!strcasecmp (req[0], "SET"))
2996 cmd = 0;
2997 else if (!strcasecmp (req[0], "DELETE"))
2998 cmd = 1;
2999 else
3001 rc = GPG_ERR_SYNTAX;
3002 goto fail;
3005 if (!req[1] || !req[2])
3007 rc = GPG_ERR_SYNTAX;
3008 goto fail;
3011 if ((xpath->req = str_split (req[2], "\t", 3)) == NULL)
3013 rc = GPG_ERR_ENOMEM;
3014 goto fail;
3017 if (!xpath->req[0] || (!xpath->req[1] && !cmd) || (xpath->req[1] && cmd))
3019 rc = GPG_ERR_SYNTAX;
3020 goto fail;
3023 rc = copy_on_write (client);
3024 if (rc)
3025 goto fail;
3027 xpath->xp = xmlXPathNewContext (client->doc);
3028 if (!xpath->xp)
3030 rc = GPG_ERR_BAD_DATA;
3031 goto fail;
3034 xpath->result = xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
3035 if (!xpath->result)
3037 rc = GPG_ERR_BAD_DATA;
3038 goto fail;
3041 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
3043 rc = GPG_ERR_ELEMENT_NOT_FOUND;
3044 goto fail;
3047 rc = xml_recurse_xpath_nodeset (client, client->doc,
3048 xpath->result->nodesetval,
3049 (xmlChar *) xpath->req[1], &xpath->buf, cmd,
3050 (xmlChar *) req[1]);
3052 fail:
3053 xpath_command_free (xpath);
3054 strv_free (req);
3055 return rc;
3058 /* XPATHATTR SET|DELETE <name> <expression>[<TAB>[value]] */
3059 static gpg_error_t
3060 xpathattr_command (assuan_context_t ctx, char *line)
3062 struct client_s *client = assuan_get_pointer (ctx);
3063 gpg_error_t rc;
3064 struct argv_s *args[] = {
3065 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3066 NULL
3069 if (disable_list_and_dump == 1)
3070 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
3072 rc = peer_is_invoker(client);
3073 if (rc)
3074 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
3076 rc = parse_options (&line, args, client, 1);
3077 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3078 rc = GPG_ERR_SYNTAX;
3079 if (rc)
3080 return send_error (ctx, rc);
3082 if (client->opts & OPT_INQUIRE)
3084 unsigned char *result;
3085 size_t len;
3087 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3088 if (rc)
3089 return send_error (ctx, rc);
3091 pthread_cleanup_push ((void *)xfree, result);
3092 rc = do_xpathattr (ctx, (char *)result);
3093 pthread_cleanup_pop (1);
3095 else
3096 rc = do_xpathattr (ctx, line);
3098 return send_error (ctx, rc);
3101 static gpg_error_t
3102 do_import (struct client_s *client, const char *root_element,
3103 unsigned char *content)
3105 xmlDocPtr doc = NULL;
3106 xmlNodePtr n = NULL, root;
3107 gpg_error_t rc = 0;
3108 struct string_s *str = NULL, *tstr = NULL;
3109 struct xml_request_s *req = NULL;
3111 if (!content || !*content)
3112 return GPG_ERR_SYNTAX;
3114 if (root_element)
3116 rc = xml_new_request (client, root_element, XML_CMD_STORE, &req);
3117 if (rc)
3119 xfree (content);
3120 return rc;
3123 if (!xml_valid_element_path (req->args, 0))
3125 xml_free_request (req);
3126 xfree (content);
3127 return GPG_ERR_INV_VALUE;
3131 str = string_new_content ((char *)content);
3132 tstr = string_prepend (str, "<pwmd>");
3133 if (tstr)
3135 str = tstr;
3136 tstr = string_append (str, "</pwmd>");
3137 if (!tstr)
3138 rc = GPG_ERR_ENOMEM;
3140 else
3141 rc = GPG_ERR_ENOMEM;
3143 if (rc)
3144 goto fail;
3146 doc = xmlReadDoc ((xmlChar *) str->str, NULL, "UTF-8", XML_PARSE_NOBLANKS);
3147 string_free (str, 1);
3148 if (!doc)
3150 rc = GPG_ERR_BAD_DATA;
3151 goto fail;
3154 root = xmlDocGetRootElement (doc);
3155 root = root->children;
3156 if (root->type != XML_ELEMENT_NODE)
3158 rc = GPG_ERR_BAD_DATA;
3159 goto fail;
3162 rc = xml_validate_import (client, root);
3163 if (rc)
3164 goto fail;
3166 if (req)
3168 /* Create the new specified root element path, if needed. */
3169 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc),
3170 &rc);
3171 if (rc)
3172 goto fail;
3174 /* Overwrite the children of the specified root element path. */
3175 (void)xml_unlink_node (client, n->children);
3176 n->children = NULL;
3178 else
3179 n = xmlDocGetRootElement (client->doc);
3181 if (n)
3183 xmlNodePtr copy;
3184 xmlChar *name = xml_attribute_value (root, (xmlChar *)"_name");
3186 if (!name)
3187 rc = GPG_ERR_BAD_DATA;
3188 else if (!req)
3190 /* No --root argument passed. Overwrite the current documents' root
3191 * element matching the root element of the imported data. */
3192 xml_free_request (req);
3193 req = NULL;
3194 rc = xml_new_request (client, (char *)name, XML_CMD_DELETE, &req);
3195 xmlFree (name);
3196 if (!rc)
3198 xmlNodePtr tmp;
3200 tmp = xml_find_elements (client, req,
3201 xmlDocGetRootElement (req->doc), &rc);
3202 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3203 goto fail;
3205 if (!rc)
3206 (void)xml_unlink_node (client, tmp);
3208 rc = 0;
3212 if (!rc)
3214 copy = xmlCopyNodeList (root);
3215 if (!copy)
3216 rc = GPG_ERR_ENOMEM;
3217 else
3219 n = xmlAddChildList (n, copy);
3220 if (!n)
3221 rc = GPG_ERR_ENOMEM;
3226 if (!rc && n && n->parent)
3227 rc = xml_update_element_mtime (client, n->parent);
3229 fail:
3230 xml_free_request (req);
3232 if (doc)
3233 xmlFreeDoc (doc);
3235 return rc;
3238 static gpg_error_t
3239 parse_import_opt_root (void *data, void *value)
3241 struct client_s *client = data;
3243 client->import_root = str_dup (value);
3244 return client->import_root ? 0 : GPG_ERR_ENOMEM;
3247 static gpg_error_t
3248 import_command (assuan_context_t ctx, char *line)
3250 gpg_error_t rc;
3251 struct client_s *client = assuan_get_pointer (ctx);
3252 unsigned char *result;
3253 size_t len;
3254 struct argv_s *args[] = {
3255 &(struct argv_s) {"root", OPTION_TYPE_ARG, parse_import_opt_root},
3256 NULL
3259 xfree (client->import_root);
3260 client->import_root = NULL;
3261 rc = parse_options (&line, args, client, 0);
3262 if (rc)
3263 return send_error (ctx, rc);
3265 rc = copy_on_write (client);
3266 if (rc)
3267 return send_error (ctx, rc);
3269 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3270 if (rc)
3272 xfree (client->import_root);
3273 client->import_root = NULL;
3274 return send_error (ctx, rc);
3277 rc = do_import (client, client->import_root, result);
3278 xfree (client->import_root);
3279 client->import_root = NULL;
3280 return send_error (ctx, rc);
3283 static gpg_error_t
3284 do_lock (struct client_s *client, int add)
3286 gpg_error_t rc = lock_file_mutex (client, add);
3288 if (!rc)
3289 client->flags |= FLAG_LOCK_CMD;
3291 return rc;
3294 static gpg_error_t
3295 lock_command (assuan_context_t ctx, char *line)
3297 struct client_s *client = assuan_get_pointer (ctx);
3298 gpg_error_t rc;
3300 if (line && *line)
3301 return send_error (ctx, GPG_ERR_SYNTAX);
3303 rc = do_lock (client, 0);
3304 return send_error (ctx, rc);
3307 static gpg_error_t
3308 unlock_command (assuan_context_t ctx, char *line)
3310 struct client_s *client = assuan_get_pointer (ctx);
3311 gpg_error_t rc;
3313 if (line && *line)
3314 return send_error (ctx, GPG_ERR_SYNTAX);
3316 rc = unlock_file_mutex (client, 0);
3317 return send_error (ctx, rc);
3320 static void
3321 get_set_env (const char *name, const char *value)
3323 if (value && *value)
3324 setenv (name, value, 1);
3325 else
3326 unsetenv (name);
3329 static gpg_error_t
3330 option_command (assuan_context_t ctx, char *line)
3332 struct client_s *client = assuan_get_pointer (ctx);
3333 gpg_error_t rc = 0;
3334 char namebuf[255] = { 0 };
3335 char *name = namebuf;
3336 char *value = NULL, *p, *tmp = NULL;
3338 p = strchr (line, '=');
3339 if (!p)
3341 strncpy (namebuf, line, sizeof(namebuf));
3342 namebuf[sizeof(namebuf)-1] = 0;
3344 else
3346 strncpy (namebuf, line, strlen (line)-strlen (p));
3347 namebuf[sizeof(namebuf)-1] = 0;
3348 value = p+1;
3351 log_write2 ("OPTION name='%s' value='%s'", name, value);
3353 if (strcasecmp (name, (char *) "lock-timeout") == 0)
3355 long n = 0;
3357 if (value)
3359 n = strtol (value, &tmp, 10);
3360 if (tmp && *tmp)
3361 return send_error (ctx, GPG_ERR_INV_VALUE);
3364 client->lock_timeout = n;
3366 else if (strcasecmp (name, (char *) "client-state") == 0)
3368 long n = 0;
3370 MUTEX_LOCK (&client->thd->status_mutex);
3371 if (value)
3373 n = strtol (value, &tmp, 10);
3374 if ((tmp && *tmp) || (n < 0 || n > 1))
3376 MUTEX_UNLOCK (&client->thd->status_mutex);
3377 return send_error (ctx, GPG_ERR_INV_VALUE);
3379 client->client_state = n;
3381 else
3382 client->client_state = 0;
3383 MUTEX_UNLOCK (&client->thd->status_mutex);
3385 else if (strcasecmp (name, (char *) "NAME") == 0)
3387 if (value && strchr (value, ' '))
3388 rc = GPG_ERR_INV_VALUE;
3389 else
3391 MUTEX_LOCK (&cn_mutex);
3392 tmp = pthread_getspecific (thread_name_key);
3393 pthread_setspecific (thread_name_key, NULL);
3394 xfree (tmp);
3395 xfree (client->thd->name);
3396 client->thd->name = NULL;
3397 if (value && *value)
3399 pthread_setspecific (thread_name_key, str_dup (value));
3400 client->thd->name = str_dup (value);
3402 MUTEX_UNLOCK (&cn_mutex);
3405 else if (strcasecmp (name, "disable-pinentry") == 0)
3407 int n = 1;
3409 if (value && *value)
3411 n = (int) strtol (value, &tmp, 10);
3412 if (*tmp || n < 0 || n > 1)
3413 return send_error (ctx, GPG_ERR_INV_VALUE);
3416 if (n)
3417 client->flags |= FLAG_NO_PINENTRY;
3418 else
3419 client->flags &= ~FLAG_NO_PINENTRY;
3421 else if (strcasecmp (name, "ttyname") == 0)
3423 get_set_env ("GPG_TTY", value);
3425 else if (strcasecmp (name, "ttytype") == 0)
3427 get_set_env ("TERM", value);
3429 else if (strcasecmp (name, "display") == 0)
3431 get_set_env ("DISPLAY", value);
3433 else if (strcasecmp (name, "lc_messages") == 0)
3436 else if (strcasecmp (name, "lc_ctype") == 0)
3439 else if (strcasecmp (name, "desc") == 0)
3442 else if (strcasecmp (name, "pinentry-timeout") == 0)
3445 else
3446 rc = GPG_ERR_UNKNOWN_OPTION;
3448 return send_error (ctx, rc);
3451 static gpg_error_t
3452 do_rename (assuan_context_t ctx, char *line)
3454 struct client_s *client = assuan_get_pointer (ctx);
3455 char **args, *p;
3456 xmlNodePtr src, dst;
3457 struct string_s *str = NULL, *tstr;
3458 struct xml_request_s *req;
3459 gpg_error_t rc;
3461 args = str_split (line, " ", 0);
3462 if (!args || strv_length (args) != 2)
3464 strv_free (args);
3465 return GPG_ERR_SYNTAX;
3468 if (!xml_valid_element ((xmlChar *) args[1]))
3470 strv_free (args);
3471 return GPG_ERR_INV_VALUE;
3474 rc = xml_new_request (client, args[0], XML_CMD_RENAME, &req);
3475 if (rc)
3477 strv_free (args);
3478 return rc;
3481 src = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3482 if (rc)
3483 goto fail;
3485 rc = xml_is_element_owner (client, src);
3486 if (rc)
3487 goto fail;
3489 xmlChar *a = xmlGetProp (src, (xmlChar *) "_name");
3490 if (!a)
3492 rc = GPG_ERR_ENOMEM;
3493 goto fail;
3496 /* To prevent unwanted effects:
3498 * <element _name="a"><element _name="b"/></element>
3500 * RENAME a<TAB>b b
3502 if (xmlStrEqual (a, (xmlChar *) args[1]))
3504 xmlFree (a);
3505 rc = GPG_ERR_EEXIST;
3506 goto fail;
3509 xmlFree (a);
3510 str = string_new (args[0]);
3511 if (!str)
3513 rc = GPG_ERR_ENOMEM;
3514 goto fail;
3517 p = strrchr (str->str, '\t');
3518 if (p)
3519 tstr = string_truncate (str, strlen (str->str)-strlen (p));
3520 else
3521 tstr = string_truncate (str, 0);
3523 if (!tstr)
3525 string_free (str, 1);
3526 rc = GPG_ERR_ENOMEM;
3527 goto fail;
3530 str = tstr;
3531 tstr = string_append_printf (str, "%s%s", str->len ? "\t" : "", args[1]);
3532 if (!tstr)
3534 string_free (str, 1);
3535 rc = GPG_ERR_ENOMEM;
3536 goto fail;
3539 str = tstr;
3540 xml_free_request (req);
3541 rc = xml_new_request (client, str->str, XML_CMD_RENAME, &req);
3542 string_free (str, 1);
3543 if (rc)
3545 req = NULL;
3546 goto fail;
3549 dst = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3550 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3551 goto fail;
3553 rc = 0;
3555 /* Target may exist:
3557 * <element _name="a"/>
3558 * <element _name="b" target="a"/>
3560 * RENAME b a
3562 if (src == dst)
3564 rc = GPG_ERR_EEXIST;
3565 goto fail;
3568 if (dst)
3570 rc = xml_is_element_owner (client, dst);
3571 if (rc)
3572 goto fail;
3574 rc = xml_add_attribute (client, src, "_name", args[1]);
3575 if (!rc)
3576 xml_unlink_node (client, dst);
3578 else
3579 rc = xml_add_attribute (client, src, "_name", args[1]);
3581 fail:
3582 xml_free_request (req);
3583 strv_free (args);
3584 return rc;
3587 static gpg_error_t
3588 rename_command (assuan_context_t ctx, char *line)
3590 struct client_s *client = assuan_get_pointer (ctx);
3591 gpg_error_t rc;
3592 struct argv_s *args[] = {
3593 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3594 NULL
3597 rc = parse_options (&line, args, client, 1);
3598 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3599 rc = GPG_ERR_SYNTAX;
3600 if (rc)
3601 return send_error (ctx, rc);
3603 rc = copy_on_write (client);
3604 if (rc)
3605 return send_error (ctx, rc);
3607 if (client->opts & OPT_INQUIRE)
3609 unsigned char *result;
3610 size_t len;
3612 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3613 if (rc)
3614 return send_error (ctx, rc);
3616 pthread_cleanup_push ((void *)xfree, result);
3617 rc = do_rename (ctx, (char *)result);
3618 pthread_cleanup_pop (1);
3620 else
3621 rc = do_rename (ctx, line);
3623 return send_error (ctx, rc);
3626 static gpg_error_t
3627 do_copy (assuan_context_t ctx, char *line)
3629 struct client_s *client = assuan_get_pointer (ctx);
3630 char **args, **targs;
3631 xmlNodePtr src, dst, tree = NULL;
3632 struct xml_request_s *req;
3633 gpg_error_t rc;
3635 args = str_split (line, " ", 0);
3636 if (!args || strv_length (args) != 2)
3638 strv_free (args);
3639 return GPG_ERR_SYNTAX;
3642 targs = str_split (args[1], "\t", 0);
3643 if (!targs)
3645 strv_free (args);
3646 return GPG_ERR_SYNTAX;
3649 if (!xml_valid_element_path (targs, 0))
3651 strv_free (args);
3652 strv_free (targs);
3653 return GPG_ERR_INV_VALUE;
3655 strv_free (targs);
3657 rc = xml_new_request (client, args[0], XML_CMD_NONE, &req);
3658 if (rc)
3660 strv_free (args);
3661 return rc;
3664 src = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3665 if (rc)
3666 goto fail;
3668 tree = xmlCopyNodeList (src);
3669 if (!tree)
3671 rc = GPG_ERR_ENOMEM;
3672 goto fail;
3675 xml_free_request (req);
3676 /* Create the destination element path if it does not exist. */
3677 rc = xml_new_request (client, args[1], XML_CMD_STORE, &req);
3678 if (rc)
3680 req = NULL;
3681 goto fail;
3684 dst = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3685 if (rc)
3686 goto fail;
3688 rc = xml_is_element_owner (client, dst);
3689 if (rc)
3690 goto fail;
3692 rc = xml_validate_target (client, req->doc, args[1], src);
3693 if (rc || src == dst)
3695 rc = rc ? rc : GPG_ERR_EEXIST;
3696 goto fail;
3699 /* Merge any attributes from the src node to the initial dst node. */
3700 for (xmlAttrPtr attr = tree->properties; attr; attr = attr->next)
3702 if (xmlStrEqual (attr->name, (xmlChar *) "_name"))
3703 continue;
3705 xmlAttrPtr a = xmlHasProp (dst, attr->name);
3706 if (a)
3707 xmlRemoveProp (a);
3709 xmlChar *tmp = xmlNodeGetContent (attr->children);
3710 xmlNewProp (dst, attr->name, tmp);
3711 xmlFree (tmp);
3712 /* Create the default attributes. */
3713 rc = xml_add_attribute (client, dst, NULL, NULL);
3716 xmlNodePtr n = dst->children;
3717 (void)xml_unlink_node (client, n);
3718 dst->children = NULL;
3720 if (tree->children)
3722 n = xmlCopyNodeList (tree->children);
3723 if (!n)
3725 rc = GPG_ERR_ENOMEM;
3726 goto fail;
3729 n = xmlAddChildList (dst, n);
3730 if (!n)
3732 rc = GPG_ERR_ENOMEM;
3733 goto fail;
3736 rc = xml_update_element_mtime (client, xmlDocGetRootElement (client->doc)
3737 == dst->parent ? dst : dst->parent);
3740 fail:
3741 if (tree)
3742 (void)xml_unlink_node (client, tree);
3744 xml_free_request (req);
3745 strv_free (args);
3746 return rc;
3749 static gpg_error_t
3750 copy_command (assuan_context_t ctx, char *line)
3752 struct client_s *client = assuan_get_pointer (ctx);
3753 gpg_error_t rc;
3754 struct argv_s *args[] = {
3755 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3756 NULL
3759 rc = parse_options (&line, args, client, 1);
3760 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3761 rc = GPG_ERR_SYNTAX;
3762 if (rc)
3763 return send_error (ctx, rc);
3765 rc = copy_on_write (client);
3766 if (rc)
3767 return send_error (ctx, rc);
3769 if (client->opts & OPT_INQUIRE)
3771 unsigned char *result;
3772 size_t len;
3774 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3775 if (rc)
3776 return send_error (ctx, rc);
3778 pthread_cleanup_push ((void *)xfree, result);
3779 rc = do_copy (ctx, (char *)result);
3780 pthread_cleanup_pop (1);
3782 else
3783 rc = do_copy (ctx, line);
3785 return send_error (ctx, rc);
3788 static gpg_error_t
3789 do_move (assuan_context_t ctx, char *line)
3791 struct client_s *client = assuan_get_pointer (ctx);
3792 char **args;
3793 xmlNodePtr src, dst;
3794 struct xml_request_s *req;
3795 gpg_error_t rc;
3797 args = str_split (line, " ", 0);
3798 if (!args || strv_length (args) != 2)
3800 strv_free (args);
3801 return GPG_ERR_SYNTAX;
3804 if (*args[1])
3806 char **targs = str_split (args[1], "\t", 0);
3807 if (!targs)
3809 strv_free (args);
3810 return GPG_ERR_ENOMEM;
3813 if (!xml_valid_element_path (targs, 0))
3815 strv_free (targs);
3816 strv_free (args);
3817 return GPG_ERR_INV_VALUE;
3820 strv_free (targs);
3823 rc = xml_new_request (client, args[0], XML_CMD_MOVE, &req);
3824 if (rc)
3826 strv_free (args);
3827 return rc;
3830 src = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3831 if (rc)
3832 goto fail;
3834 rc = xml_is_element_owner (client, src);
3835 if (rc)
3836 goto fail;
3838 xml_free_request (req);
3839 req = NULL;
3840 if (*args[1])
3842 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
3843 if (rc)
3844 goto fail;
3846 dst = xml_find_elements (client, req, xmlDocGetRootElement (req->doc),
3847 &rc);
3849 else
3850 dst = xmlDocGetRootElement (client->doc);
3852 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3853 goto fail;
3855 rc = 0;
3857 for (xmlNodePtr n = dst; n; n = n->parent)
3859 if (n == src)
3861 rc = GPG_ERR_EEXIST;
3862 goto fail;
3866 if (dst)
3868 xmlChar *a = xml_attribute_value (src, (xmlChar *) "_name");
3869 xmlNodePtr dup = xml_find_element (client, dst->children, (char *) a, &rc);
3871 xmlFree (a);
3872 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3873 goto fail;
3875 rc = 0;
3877 if (dup)
3879 if (dup == src)
3881 rc = GPG_ERR_EEXIST;
3882 goto fail;
3885 if (dst == xmlDocGetRootElement (client->doc))
3887 xmlNodePtr n = src;
3888 int match = 0;
3890 while (n->parent && n->parent != dst)
3891 n = n->parent;
3893 a = xml_attribute_value (n, (xmlChar *) "_name");
3894 xmlChar *b = xml_attribute_value (src, (xmlChar *) "_name");
3896 if (xmlStrEqual (a, b))
3898 match = 1;
3899 xmlUnlinkNode (src);
3900 (void)xml_unlink_node (client, n);
3903 xmlFree (a);
3904 xmlFree (b);
3906 if (!match)
3907 (void)xml_unlink_node (client, dup);
3909 else
3910 xmlUnlinkNode (dup);
3914 if (!dst && req && req->args && *req->args)
3916 struct xml_request_s *nreq = NULL;
3917 xmlChar *name = xml_attribute_value (src, (xmlChar *) "_name");
3919 if (src->parent == xmlDocGetRootElement (client->doc)
3920 && !strcmp ((char *) name, *req->args))
3922 xmlFree (name);
3923 rc = GPG_ERR_EEXIST;
3924 goto fail;
3927 xmlFree (name);
3928 rc = xml_new_request (client, args[1], XML_CMD_STORE, &nreq);
3929 if (!rc)
3931 dst = xml_find_elements (client, nreq,
3932 xmlDocGetRootElement (nreq->doc), &rc);
3933 xml_free_request (nreq);
3936 if (rc)
3937 goto fail;
3940 xml_update_element_mtime (client, src->parent);
3941 xmlUnlinkNode (src);
3943 dst = xmlAddChildList (dst, src);
3944 if (!dst)
3945 rc = GPG_ERR_ENOMEM;
3946 else
3947 xml_update_element_mtime (client, dst->parent);
3949 fail:
3950 xml_free_request (req);
3951 strv_free (args);
3952 return rc;
3955 static gpg_error_t
3956 move_command (assuan_context_t ctx, char *line)
3958 struct client_s *client = assuan_get_pointer (ctx);
3959 gpg_error_t rc;
3960 struct argv_s *args[] = {
3961 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3962 NULL
3965 rc = parse_options (&line, args, client, 1);
3966 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3967 rc = GPG_ERR_SYNTAX;
3968 if (rc)
3969 return send_error (ctx, rc);
3971 rc = copy_on_write (client);
3972 if (rc)
3973 return send_error (ctx, rc);
3975 if (client->opts & OPT_INQUIRE)
3977 unsigned char *result;
3978 size_t len;
3980 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3981 if (rc)
3982 return send_error (ctx, rc);
3984 pthread_cleanup_push ((void *)xfree, result);
3985 rc = do_move (ctx, (char *)result);
3986 pthread_cleanup_pop (1);
3988 else
3989 rc = do_move (ctx, line);
3991 return send_error (ctx, rc);
3994 static int
3995 sort_files (const void *arg1, const void *arg2)
3997 char *const *a = arg1;
3998 char *const *b = arg2;
4000 return strcmp (*a, *b);
4003 static gpg_error_t
4004 ls_command (assuan_context_t ctx, char *line)
4006 gpg_error_t rc;
4007 char *tmp;
4008 char *dir;
4009 DIR *d;
4010 char *list = NULL;
4011 char **v = NULL;
4012 #ifdef HAVE_READDIR_R
4013 size_t len;
4014 struct dirent *cur = NULL, *p;
4015 #else
4016 struct dirent *cur = NULL;
4017 #endif
4019 if (line && *line)
4020 return send_error (ctx, GPG_ERR_SYNTAX);
4022 tmp = str_asprintf ("%s/data", homedir);
4023 dir = expand_homedir (tmp);
4024 xfree (tmp);
4025 if (!dir)
4026 return send_error (ctx, GPG_ERR_ENOMEM);
4028 d = opendir (dir);
4029 rc = gpg_error_from_errno (errno);
4031 if (!d)
4033 xfree (dir);
4034 return send_error (ctx, rc);
4037 #ifdef HAVE_READDIR_R
4038 len = offsetof (struct dirent, d_name) + pathconf (dir, _PC_NAME_MAX) + 1;
4039 p = xmalloc (len);
4040 if (!p)
4042 xfree (dir);
4043 closedir (d);
4044 return send_error (ctx, GPG_ERR_ENOMEM);
4046 pthread_cleanup_push (xfree, p);
4047 #endif
4049 pthread_cleanup_push ((void *)closedir, d);
4050 xfree (dir);
4051 rc = 0;
4053 #ifdef HAVE_READDIR_R
4054 while (!readdir_r (d, p, &cur) && cur)
4055 #else
4056 while ((cur = readdir (d)))
4057 #endif
4059 char **vtmp;
4061 pthread_cleanup_push ((void *)strv_free, v);
4062 rc = open_check_file (cur->d_name, NULL, NULL, 1);
4063 if (rc)
4064 continue;
4066 tmp = str_dup (cur->d_name);
4067 if (!tmp)
4069 rc = GPG_ERR_ENOMEM;
4070 break;
4073 vtmp = strv_cat (v, tmp);
4074 if (!vtmp)
4076 xfree (tmp);
4077 rc = GPG_ERR_ENOMEM;
4078 break;
4081 v = vtmp;
4082 pthread_cleanup_pop (0);
4085 pthread_cleanup_pop (1); // closedir (d)
4086 #ifdef HAVE_READDIR_R
4087 pthread_cleanup_pop (1); // xfree (p)
4088 #endif
4090 if (rc && rc != GPG_ERR_ENODEV)
4092 strv_free (v);
4093 return send_error (ctx, rc);
4096 rc = 0;
4097 if (v && *v)
4099 unsigned n, t = strv_length (v);
4101 qsort (v, t, sizeof (char **), sort_files);
4103 for (n = 0; n < t; n++)
4105 tmp = str_asprintf ("%s%s\n", list ? list : "", v[n]);
4106 if (!tmp)
4108 xfree (list);
4109 rc = GPG_ERR_ENOMEM;
4110 break;
4113 xfree (list);
4114 list = tmp;
4118 strv_free (v);
4119 if (!list)
4120 return send_error (ctx, GPG_ERR_NO_DATA);
4122 list[strlen (list) - 1] = 0;
4123 pthread_cleanup_push (xfree, list);
4124 rc = xfer_data (ctx, list, strlen (list));
4125 pthread_cleanup_pop (1);
4126 return send_error (ctx, rc);
4129 static gpg_error_t
4130 bye_notify (assuan_context_t ctx, char *line)
4132 struct client_s *cl = assuan_get_pointer (ctx);
4133 gpg_error_t ret = 0;
4135 (void)line;
4136 update_client_state (cl, CLIENT_STATE_DISCON);
4138 #ifdef WITH_GNUTLS
4139 cl->disco = 1;
4140 if (cl->thd->remote)
4142 int rc;
4146 struct timeval tv = { 0, 50000 };
4148 rc = gnutls_bye (cl->thd->tls->ses, GNUTLS_SHUT_RDWR);
4149 if (rc == GNUTLS_E_AGAIN)
4150 select (0, NULL, NULL, NULL, &tv);
4152 while (rc == GNUTLS_E_AGAIN);
4154 #endif
4156 /* This will let assuan_process_next() return. */
4157 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
4159 cl->last_rc = gpg_error_from_errno (errno);
4160 ret = cl->last_rc;
4163 cl->last_rc = 0; // BYE command result
4164 return ret;
4167 static gpg_error_t
4168 reset_notify (assuan_context_t ctx, char *line)
4170 struct client_s *client = assuan_get_pointer (ctx);
4172 (void)line;
4173 if (client)
4174 reset_client (client);
4176 return 0;
4180 * This is called before every Assuan command.
4182 static gpg_error_t
4183 command_startup (assuan_context_t ctx, const char *name)
4185 struct client_s *client = assuan_get_pointer (ctx);
4186 gpg_error_t rc;
4187 struct command_table_s *cmd = NULL;
4189 log_write2 ("command='%s'", name);
4190 client->last_rc = client->opts = 0;
4192 for (int i = 0; command_table[i]; i++)
4194 if (!strcasecmp (name, command_table[i]->name))
4196 if (command_table[i]->ignore_startup)
4197 return 0;
4198 cmd = command_table[i];
4199 break;
4203 if (!cmd)
4204 return GPG_ERR_UNKNOWN_COMMAND;
4206 client->last_rc = rc = gpg_error (file_modified (client, cmd));
4207 if (!rc)
4208 update_client_state (client, CLIENT_STATE_COMMAND);
4210 return rc;
4214 * This is called after every Assuan command.
4216 static void
4217 command_finalize (assuan_context_t ctx, gpg_error_t rc)
4219 struct client_s *client = assuan_get_pointer (ctx);
4221 if (!(client->flags & FLAG_LOCK_CMD))
4222 unlock_file_mutex (client, 0);
4224 unlock_flock (&client->flock_fd);
4225 log_write2 (_("command completed: rc=%u"), rc ? rc : client->last_rc);
4226 client->last_rc = gpg_error (GPG_ERR_UNKNOWN_COMMAND);
4227 #ifdef WITH_GNUTLS
4228 client->thd->buffer_timeout = client->thd->last_buffer_size = 0;
4229 #endif
4230 if (client->thd->state != CLIENT_STATE_DISCON)
4231 update_client_state (client, CLIENT_STATE_IDLE);
4234 static gpg_error_t
4235 parse_help_opt_html (void *data, void *value)
4237 struct client_s *client = data;
4239 (void) value;
4240 client->opts |= OPT_HTML;
4241 return 0;
4244 static gpg_error_t
4245 help_command (assuan_context_t ctx, char *line)
4247 gpg_error_t rc;
4248 int i;
4249 struct client_s *client = assuan_get_pointer (ctx);
4250 struct argv_s *args[] = {
4251 &(struct argv_s) {"html", OPTION_TYPE_NOARG, parse_help_opt_html},
4252 NULL
4255 rc = parse_options (&line, args, client, 1);
4256 if (rc)
4257 return send_error (ctx, rc);
4259 if (!line || !*line)
4261 char *tmp;
4262 char *help = str_dup (_("Usage: HELP [--html] [<COMMAND>]\n"
4263 "For commands that take an element path as an argument, each element is "
4264 "separated with an ASCII @key{TAB} character (ASCII 0x09)."
4265 "@*@*COMMANDS:"));
4267 for (i = 0; command_table[i]; i++)
4269 if (!command_table[i]->help)
4270 continue;
4272 /* @npxref{} won't put a "See " or "see " in front of the command.
4273 * It's not a texinfo command but needed for --html. */
4274 tmp = str_asprintf ("%s %s%s%s", help,
4275 client->opts & OPT_HTML ? "@npxref{" : "",
4276 command_table[i]->name,
4277 client->opts & OPT_HTML ? "}" : "");
4278 xfree (help);
4279 help = tmp;
4282 tmp = strip_texi_and_wrap (help, client->opts & OPT_HTML);
4283 xfree (help);
4284 pthread_cleanup_push ((void *)xfree, tmp);
4285 rc = xfer_data (ctx, tmp, strlen (tmp));
4286 pthread_cleanup_pop (1);
4287 return send_error (ctx, rc);
4290 for (i = 0; command_table[i]; i++)
4292 if (!strcasecmp (line, command_table[i]->name))
4294 char *help, *tmp;
4296 if (!command_table[i]->help)
4297 break;
4299 help = strip_texi_and_wrap (command_table[i]->help,
4300 client->opts & OPT_HTML);
4301 tmp = str_asprintf ("%s%s",
4302 (client->opts & OPT_HTML) ? "" : _("Usage: "),
4303 help);
4304 xfree (help);
4305 pthread_cleanup_push ((void *)xfree, tmp);
4306 rc = xfer_data (ctx, tmp, strlen (tmp));
4307 pthread_cleanup_pop (1);
4308 return send_error (ctx, rc);
4312 return send_error (ctx, GPG_ERR_INV_NAME);
4315 static void
4316 new_command (const char *name, int ignore, int unlock, int flock_type,
4317 gpg_error_t (*handler) (assuan_context_t, char *),
4318 const char *help)
4320 int i = 0;
4321 struct command_table_s **tmp;
4323 if (command_table)
4324 for (i = 0; command_table[i]; i++);
4326 tmp = xrealloc (command_table, (i + 2) * sizeof (struct command_table_s *));
4327 assert (tmp);
4328 command_table = tmp;
4329 command_table[i] = xcalloc (1, sizeof (struct command_table_s));
4330 command_table[i]->name = name;
4331 command_table[i]->handler = handler;
4332 command_table[i]->ignore_startup = ignore;
4333 command_table[i]->unlock = unlock;
4334 command_table[i]->flock_type = flock_type;
4335 command_table[i++]->help = help;
4336 command_table[i] = NULL;
4339 void
4340 deinit_commands ()
4342 int i;
4344 for (i = 0; command_table[i]; i++)
4345 xfree (command_table[i]);
4347 xfree (command_table);
4350 static int
4351 sort_commands (const void *arg1, const void *arg2)
4353 struct command_table_s *const *a = arg1;
4354 struct command_table_s *const *b = arg2;
4356 if (!*a || !*b)
4357 return 0;
4358 else if (*a && !*b)
4359 return 1;
4360 else if (!*a && *b)
4361 return -1;
4363 return strcmp ((*a)->name, (*b)->name);
4366 static gpg_error_t
4367 passwd_command (assuan_context_t ctx, char *line)
4369 struct client_s *client = assuan_get_pointer (ctx);
4370 gpg_error_t rc;
4372 (void)line;
4373 rc = peer_is_invoker (client);
4374 if (rc)
4375 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
4377 if (client->flags & FLAG_NEW)
4378 return send_error (ctx, GPG_ERR_INV_STATE);
4380 client->crypto->keyfile = config_get_string (client->filename,
4381 "passphrase_file");
4382 rc = crypto_init_ctx (client->crypto, client->flags & FLAG_NO_PINENTRY,
4383 client->crypto->keyfile);
4384 if (rc)
4385 return send_error (ctx, rc);
4387 if (!rc)
4388 rc = crypto_passwd (client, client->crypto);
4390 crypto_free_non_keys (client->crypto);
4391 return send_error (ctx, rc);
4394 static gpg_error_t
4395 parse_opt_data (void *data, void *value)
4397 struct client_s *client = data;
4399 (void) value;
4400 client->opts |= OPT_DATA;
4401 return 0;
4404 static gpg_error_t
4405 send_client_list (assuan_context_t ctx)
4407 struct client_s *client = assuan_get_pointer (ctx);
4408 gpg_error_t rc = 0;
4410 if (client->opts & OPT_VERBOSE)
4412 unsigned i, t;
4413 char **list = NULL;
4414 char *line;
4416 MUTEX_LOCK (&cn_mutex);
4417 pthread_cleanup_push ((void *)release_mutex_cb, &cn_mutex);
4418 t = slist_length (cn_thread_list);
4420 for (i = 0; i < t; i++)
4422 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
4423 char *tmp;
4425 if (thd->state == CLIENT_STATE_UNKNOWN)
4426 continue;
4428 tmp = build_client_info_line (thd, 0);
4429 if (tmp)
4431 char **l = strv_cat (list, tmp);
4432 if (!l)
4433 rc = GPG_ERR_ENOMEM;
4434 else
4435 list = l;
4437 else
4438 rc = GPG_ERR_ENOMEM;
4440 if (rc)
4442 strv_free (list);
4443 break;
4447 pthread_cleanup_pop (1);
4448 if (rc)
4449 return rc;
4451 line = strv_join ("\n", list);
4452 strv_free (list);
4453 pthread_cleanup_push ((void *)xfree, line);
4454 rc = xfer_data (ctx, line, strlen (line));
4455 pthread_cleanup_pop (1);
4456 return rc;
4459 if (client->opts & OPT_DATA)
4461 char buf[ASSUAN_LINELENGTH];
4463 MUTEX_LOCK (&cn_mutex);
4464 snprintf (buf, sizeof (buf), "%u", slist_length (cn_thread_list));
4465 MUTEX_UNLOCK (&cn_mutex);
4466 rc = xfer_data (ctx, buf, strlen (buf));
4468 else
4469 rc = send_status (ctx, STATUS_CLIENTS, NULL);
4471 return rc;
4474 static gpg_error_t
4475 getinfo_command (assuan_context_t ctx, char *line)
4477 struct client_s *client = assuan_get_pointer (ctx);
4478 gpg_error_t rc;
4479 char buf[ASSUAN_LINELENGTH];
4480 struct argv_s *args[] = {
4481 &(struct argv_s) {"data", OPTION_TYPE_NOARG, parse_opt_data},
4482 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_opt_verbose},
4483 NULL
4486 rc = parse_options (&line, args, client, 1);
4487 if (rc)
4488 return send_error (ctx, rc);
4490 if (!strcasecmp (line, "clients"))
4492 rc = send_client_list (ctx);
4494 else if (!strcasecmp (line, "cache"))
4496 if (client->opts & OPT_DATA)
4498 snprintf (buf, sizeof (buf), "%u", cache_file_count ());
4499 rc = xfer_data (ctx, buf, strlen (buf));
4501 else
4502 rc = send_status (ctx, STATUS_CACHE, NULL);
4504 else if (!strcasecmp (line, "pid"))
4506 pid_t pid = getpid ();
4508 snprintf (buf, sizeof (buf), "%u", pid);
4509 rc = xfer_data (ctx, buf, strlen (buf));
4511 else if (!strcasecmp (line, "version"))
4513 char *tmp = str_asprintf ("0x%06x %s", VERSION_HEX,
4514 #ifdef WITH_GNUTLS
4515 "GNUTLS "
4516 #endif
4517 #ifdef WITH_LIBACL
4518 "ACL "
4519 #endif
4520 "");
4521 pthread_cleanup_push (xfree, tmp);
4522 rc = xfer_data (ctx, tmp, strlen (tmp));
4523 pthread_cleanup_pop (1);
4525 else if (!strcasecmp (line, "last_error"))
4527 if (client->last_error)
4528 rc = xfer_data (ctx, client->last_error, strlen (client->last_error));
4529 else
4530 rc = GPG_ERR_NO_DATA;
4532 else if (!strcasecmp (line, "user"))
4534 char *user = NULL;
4536 #ifdef WITH_GNUTLS
4537 if (client->thd->remote)
4538 user = str_asprintf ("#%s", client->thd->tls->fp);
4539 else
4540 user = get_username (client->thd->peer->uid);
4541 #else
4542 user = get_username (client->thd->peer->uid);
4543 #endif
4544 if (user)
4546 pthread_cleanup_push ((void *)xfree, user);
4547 rc = xfer_data (ctx, user, strlen (user));
4548 pthread_cleanup_pop (1);
4550 else
4551 rc = GPG_ERR_NO_DATA;
4553 else
4554 rc = gpg_error (GPG_ERR_SYNTAX);
4556 return send_error (ctx, rc);
4559 static gpg_error_t
4560 parse_opt_secret (void *data, void *value)
4562 struct client_s *client = data;
4564 (void) value;
4565 client->opts |= OPT_SECRET;
4566 return 0;
4569 static gpg_error_t
4570 parse_keyinfo_opt_learn (void *data, void *value)
4572 struct client_s *client = data;
4574 (void)value;
4575 client->opts |= OPT_KEYINFO_LEARN;
4576 return 0;
4579 static gpg_error_t
4580 keyinfo_command (assuan_context_t ctx, char *line)
4582 struct client_s *client = assuan_get_pointer (ctx);
4583 gpg_error_t rc = 0;
4584 char **keys = NULL, **p = NULL;
4585 int sym = 0;
4586 struct argv_s *args[] = {
4587 &(struct argv_s) {"learn", OPTION_TYPE_NOARG, parse_keyinfo_opt_learn},
4588 NULL
4591 rc = parse_options (&line, args, client, 0);
4592 if (rc)
4593 return send_error (ctx, rc);
4595 if (line && *line)
4596 return send_error (ctx, GPG_ERR_SYNTAX);
4598 if (!(client->flags & FLAG_OPEN))
4599 return send_error (ctx, GPG_ERR_INV_STATE);
4601 if (client->opts & OPT_KEYINFO_LEARN)
4603 rc = cache_agent_command ("LEARN");
4604 return send_error (ctx, rc);
4607 if (client->flags & FLAG_NEW)
4608 return send_error (ctx, GPG_ERR_NO_DATA);
4610 rc = lock_flock (ctx, client->filename, FLOCK_TYPE_SH, &client->flock_fd);
4611 if (rc)
4612 return send_error (ctx, rc);
4614 rc = crypto_is_symmetric (client->filename);
4615 unlock_flock (&client->flock_fd);
4616 if (!rc)
4617 sym = 1;
4618 else if (rc != GPG_ERR_BAD_DATA)
4619 return send_error (ctx, rc);
4621 rc = 0;
4622 if (!sym)
4624 p = strv_catv (keys, client->crypto->pubkey);
4625 if (!p)
4626 rc = GPG_ERR_ENOMEM;
4627 else
4628 keys = p;
4631 if (!rc && client->crypto->sigkey)
4633 if (!strv_printf (&keys, "S%s", client->crypto->sigkey))
4635 strv_free (keys);
4636 return send_error (ctx, GPG_ERR_ENOMEM);
4640 if (!rc)
4642 if (keys)
4644 line = strv_join ("\n", keys);
4645 strv_free (keys);
4646 pthread_cleanup_push ((void *)xfree, line);
4647 if (line)
4648 rc = xfer_data (ctx, line, strlen (line));
4649 else
4650 rc = GPG_ERR_ENOMEM;
4652 pthread_cleanup_pop (1);
4654 else
4655 rc = GPG_ERR_NO_DATA;
4657 else
4658 strv_free (keys);
4660 return send_error (ctx, rc);
4663 static gpg_error_t
4664 deletekey_command (assuan_context_t ctx, char *line)
4666 gpg_error_t rc;
4667 struct client_s *client = assuan_get_pointer (ctx);
4668 struct crypto_s *crypto = NULL;
4669 char *keys[] = { NULL, NULL };
4670 gpgme_key_t *result;
4671 char **p = NULL;
4673 if (!(client->flags & FLAG_OPEN))
4674 return send_error (ctx, GPG_ERR_INV_STATE);
4676 rc = peer_is_invoker (client);
4677 if (rc)
4678 return send_error (ctx, (rc == GPG_ERR_EACCES ? GPG_ERR_FORBIDDEN : rc));
4680 if (client->flags & FLAG_NO_PINENTRY)
4681 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
4683 if (!*line)
4684 return send_error (ctx, GPG_ERR_SYNTAX);
4686 rc = crypto_keyid_to_16b_once (line);
4687 if (rc)
4688 return send_error (ctx, rc);
4690 for (p = client->crypto->pubkey; p && *p; p++)
4692 if (!strcmp (*p, line))
4693 break;
4696 if (!p)
4698 if (client->crypto->sigkey && strcmp (client->crypto->sigkey, line))
4699 return send_error (ctx, GPG_ERR_FORBIDDEN);
4700 else if (!client->crypto->sigkey)
4701 return send_error (ctx, GPG_ERR_NO_SECKEY);
4704 rc = crypto_init (&crypto, client->ctx, client->filename,
4705 client->flags & FLAG_NO_PINENTRY, NULL);
4706 if (rc)
4707 return send_error (ctx, rc);
4709 pthread_cleanup_push ((void *)crypto_free, crypto);
4710 keys[0] = line;
4711 rc = crypto_list_keys (crypto, keys, 1, &result);
4712 if (!rc)
4714 pthread_cleanup_push ((void *)crypto_free_key_list, result);
4715 rc = crypto_delete_key (client, crypto, *result, 1);
4716 pthread_cleanup_pop (1);
4719 pthread_cleanup_pop (1);
4720 if (gpg_err_source (rc) == GPG_ERR_SOURCE_GPGME
4721 && gpg_err_code (rc) == GPG_ERR_CANCELED)
4722 rc = gpg_error (GPG_ERR_NOT_CONFIRMED);
4724 return send_error (ctx, rc);
4727 static gpg_error_t
4728 kill_command (assuan_context_t ctx, char *line)
4730 struct client_s *client = assuan_get_pointer (ctx);
4731 gpg_error_t rc;
4732 unsigned i, t;
4734 if (!line || !*line)
4735 return send_error (ctx, GPG_ERR_SYNTAX);
4737 MUTEX_LOCK (&cn_mutex);
4738 pthread_cleanup_push ((void *)release_mutex_cb, &cn_mutex);
4739 t = slist_length (cn_thread_list);
4740 rc = GPG_ERR_ESRCH;
4742 for (i = 0; i < t; i++)
4744 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
4745 char *tmp = str_asprintf ("%p", thd->tid);
4747 if (strcmp (line, tmp))
4749 xfree (tmp);
4750 continue;
4753 xfree (tmp);
4754 rc = peer_is_invoker (client);
4755 if (!rc)
4757 #ifdef HAVE_PTHREAD_CANCEL
4758 pthread_cancel (thd->tid);
4759 #else
4760 pthread_kill (thd->tid, SIGUSR2);
4761 #endif
4762 break;
4764 else if (rc == GPG_ERR_EACCES)
4765 rc = GPG_ERR_FORBIDDEN;
4766 else if (rc)
4767 break;
4769 if (config_get_boolean ("global", "strict_kill"))
4770 break;
4772 #ifdef WITH_GNUTLS
4773 if (client->thd->remote && thd->remote)
4775 if (!thd->tls || !thd->tls->fp)
4777 rc = GPG_ERR_INV_STATE;
4778 break;
4780 if (!strcmp (client->thd->tls->fp, thd->tls->fp))
4782 #ifdef HAVE_PTHREAD_CANCEL
4783 pthread_cancel (thd->tid);
4784 #else
4785 pthread_kill (thd->tid, SIGUSR2);
4786 #endif
4787 break;
4790 else if (!client->thd->remote && !thd->remote)
4791 #endif
4793 if (client->thd->peer->uid == thd->peer->uid)
4795 #ifdef HAVE_PTHREAD_CANCEL
4796 pthread_cancel (thd->tid);
4797 #else
4798 pthread_kill (thd->tid, SIGUSR2);
4799 #endif
4802 break;
4805 pthread_cleanup_pop (1);
4806 return send_error (ctx, rc);
4809 static gpg_error_t
4810 listkeys_command (assuan_context_t ctx, char *line)
4812 struct client_s *client = assuan_get_pointer (ctx);
4813 struct crypto_s *crypto = NULL;
4814 char **pattern = NULL;
4815 gpgme_key_t *keys = NULL;
4816 char **result = NULL;
4817 gpg_error_t rc;
4818 struct argv_s *args[] = {
4819 &(struct argv_s) {"secret-only", OPTION_TYPE_NOARG, parse_opt_secret},
4820 NULL
4823 rc = parse_options (&line, args, client, 1);
4824 if (rc)
4825 return send_error (ctx, rc);
4827 rc = crypto_init (&crypto, client->ctx, client->filename,
4828 client->flags & FLAG_NO_PINENTRY, NULL);
4829 if (rc)
4830 return send_error (ctx, rc);
4832 pthread_cleanup_push ((void *)crypto_free, crypto);
4833 pattern = str_split (line, ",", 0);
4834 pthread_cleanup_push ((void *)(void *)strv_free, pattern);
4835 rc = crypto_list_keys (crypto, pattern, client->opts & OPT_SECRET,
4836 &keys);
4837 pthread_cleanup_pop (1);
4838 pthread_cleanup_pop (1);
4839 if (!rc)
4841 int i;
4843 for (i = 0; keys[i]; i++)
4845 char *p = crypto_key_info (keys[i]);
4846 char **r;
4848 if (!p)
4850 rc = GPG_ERR_ENOMEM;
4851 break;
4854 r = strv_cat (result, p);
4855 if (!r)
4857 rc = GPG_ERR_ENOMEM;
4858 break;
4861 result = r;
4864 if (!i)
4865 rc = GPG_ERR_NO_DATA;
4867 crypto_free_key_list (keys);
4870 if (!rc)
4872 line = strv_join ("\n", result);
4873 strv_free (result);
4874 pthread_cleanup_push ((void *)xfree, line);
4875 if (!line)
4876 rc = GPG_ERR_ENOMEM;
4877 else
4878 rc = xfer_data (ctx, line, strlen (line));
4880 pthread_cleanup_pop (1);
4882 else
4883 strv_free (result);
4885 if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
4886 || gpg_err_code (rc) == GPG_ERR_NO_SECKEY)
4887 rc = GPG_ERR_NO_DATA;
4889 return send_error (ctx, rc);
4892 void
4893 init_commands ()
4895 /* !BEGIN-HELP-TEXT!
4897 * This comment is used as a marker to generate the offline documentation
4898 * found in doc/pwmd.info. The indentation needs to be kept for the awk
4899 * script to determine where commands begin and end.
4901 new_command("HELP", 1, 1, 0, help_command, _(
4902 "HELP [--html] [<COMMAND>]\n"
4903 "Show available commands or command specific help text."
4904 "@*@*"
4905 "The @option{--html} option will output the help text in HTML format."
4908 new_command("DELETEKEY", 1, 1, FLOCK_TYPE_SH|FLOCK_TYPE_KEEP, deletekey_command, _(
4909 "DELETEKEY <keyid>\n"
4910 "Deletes the secret key associated with key @var{keyid} from the keyring. "
4911 "Note that when the key is deleted, the current or other data files using "
4912 "this key will no longer be able to be opened."
4915 new_command("KILL", 1, 0, 0, kill_command, _(
4916 "KILL <thread_id>\n"
4917 "Terminates the client identified by @var{thread_id} and releases any file "
4918 "lock or other resources it has held. See @code{GETINFO} (@pxref{GETINFO}) "
4919 "for details about listing connected clients. An @code{invoking_user} "
4920 "(@pxref{Configuration}) may kill any client while others may only kill "
4921 "clients of the same @code{UID} or @abbr{TLS} fingerprint."
4924 new_command("LISTKEYS", 1, 0, 0, listkeys_command, _(
4925 "LISTKEYS [--secret-only] [pattern[,<pattern>]]\n"
4926 "Returns a new line separated list of key information matching a comma "
4927 "separated list of @var{pattern}'s. When option @option{--secret-only} is "
4928 "specified, only keys matching @var{pattern} that also have a secret key "
4929 "available will be returned."
4932 new_command("KEYINFO", 1, 0, 0, keyinfo_command, _(
4933 "KEYINFO [--learn]\n"
4934 "Returns a new line separated list of key ID's that the currently opened "
4935 "data file has recipients and signers for. If the key is a signing key it "
4936 "will be prefixed with an @code{S}. If the file is a new one, or has no "
4937 "signers in the case of being symmetrically encrypted, the error code "
4938 "@code{GPG_ERR_NO_DATA} is returned."
4939 "@*@*"
4940 "When the @option{--learn} option is passed, keys on a smartcard will be "
4941 "imported."
4944 new_command("GETINFO", 1, 1, 0, getinfo_command, _(
4945 "GETINFO [--data] [--verbose] CACHE | CLIENTS | PID | USER | LAST_ERROR | VERSION\n"
4946 "Get server and other information. The information is returned via a status "
4947 "message (@pxref{Status Messages}) unless otherwise noted or @option{--data} "
4948 "is specified."
4949 "@*@*"
4950 "@var{CACHE} returns the number of cached documents."
4951 "@*@*"
4952 "@var{CLIENTS} returns the number of "
4953 "connected clients via a status message or a list of connected clients when "
4954 "the @option{--verbose} parameter is used (implies @option{--data}). A "
4955 "verbose line of a client list contains "
4956 "space delimited "
4957 "fields: the thread ID, client name, opened file (@code{/} if none opened), "
4958 "IP address if remote, file lock status, whether the current client is self "
4959 "or not, client state (see below), "
4960 "user ID or TLS fingerprint of the connected client, username if the "
4961 "client is a local one else @code{-}, and finally the time stamp of when the "
4962 "client connected."
4963 "@*@*"
4964 "Client state @code{0} is an unknown client state, state @code{1} indicates "
4965 "the client has connected but hasn't completed initializing, state @code{2} "
4966 "indicates that the client is idle, state @code{3} means the "
4967 "client is in a command and state @code{4} means the client is disconnecting. "
4968 "@*@*"
4969 "@var{PID} returns the process ID number of the server via a data response."
4970 "@*@*"
4971 "@var{VERSION} returns the server version number and compile-time features "
4972 "via a data response with each being space delimited."
4973 "@*@*"
4974 "@var{LAST_ERROR} returns a detailed description of the last failed command "
4975 "via a data response, when available."
4976 "@*@*"
4977 "@var{USER} returns the username or @abbr{TLS} hash of the connected client "
4978 "via a data response."
4981 new_command("PASSWD", 0, 0, FLOCK_TYPE_EX|FLOCK_TYPE_KEEP, passwd_command, _(
4982 "PASSWD\n"
4983 "Changes the passphrase of the secret key required to open the current "
4984 "data file. If the data file is symmetrically encrypted, the error "
4985 "@code{GPG_ERR_NOT_SUPPORTED} is returned. When symmetrically encrypted, "
4986 "the @code{SAVE} command (@pxref{SAVE}) should be used instead to prevent "
4987 "this command saving any unwanted changes to the @abbr{XML} document."
4988 "@*@*"
4989 "This command is not available to non-invoking clients "
4990 "(@pxref{Access Control})."
4993 new_command("OPEN", 1, 1, FLOCK_TYPE_SH|FLOCK_TYPE_KEEP, open_command, _(
4994 "OPEN [--lock] <filename>\n"
4995 "Opens @var{filename}. When the @var{filename} is not found on the "
4996 "file-system then a new in-memory document will be created. If the file is "
4997 "found, it is looked for in the file cache and when found no passphrase will "
4998 "be required to open it. When not cached, @cite{pinentry(1)} will be used to "
4999 "retrieve the passphrase for decryption unless @option{disable-pinentry} "
5000 "(@pxref{OPTION}) was specified in which case @command{pwmd} will "
5001 "@emph{INQUIRE} the client for the passphrase. Note than when configuration "
5002 "option @option{strict_open} is enabled and the client is not an "
5003 "@option{invoking_user}, an error will be returned when the data file does "
5004 "not exist."
5005 "@*@*"
5006 "When the @option{--lock} option is passed then the file mutex will be "
5007 "locked as if the @code{LOCK} command (@pxref{LOCK}) had been sent after the "
5008 "file had been opened."
5011 new_command("GENKEY", 1, 1, 0, genkey_command, _(
5012 "GENKEY --subkey-of=fpr | --userid=\"str\" [--expire=N] [--algo=\"str\"] [--no-passphrase] [--usage=\"default|sign|encrypt\"\n"
5013 "Generates a new key based on option arguments. One of "
5014 "@option{--subkey-of} or @option{--userid} is "
5015 "required. The @option{--subkey-of} option will generate a subkey for the key "
5016 "of the specified fingerprint."
5019 new_command("SAVE", 0, 0, FLOCK_TYPE_EX|FLOCK_TYPE_KEEP, save_command, _(
5020 "SAVE [--sign-keyid=[<fpr>]] [--symmetric | --keyid=<fpr>[,..] | --inquire-keyid]\n"
5021 "Writes the in-memory @abbr{XML} document to disk. The file written to is the "
5022 "file that was opened when using the @code{OPEN} command (@pxref{OPEN})."
5023 "@*@*"
5024 "If the file is a new one, one of @option{--symmetric}, @option{--keyid} or"
5025 "@option{--inquire-keyid} is required. When not @option{--symmetric}, option "
5026 "@option{--sign-keyid} is also required, but optional otherwise."
5027 "@*@*"
5028 "You can encrypt the data file to a recipient other than the one that it "
5029 "was originally encrypted with by passing the @option{--keyid} or "
5030 "@option{--inquire-keyid} option with a comma separated list of "
5031 "public encryption key fingerprints as its argument. Use the "
5032 "@command{LISTKEYS} command (@pxref{LISTKEYS}) to show key information by "
5033 "pattern. The @option{--sign-keyid} option may also be used to sign the data "
5034 "file with an alternate key by specifying the fingerprint of a signing key. "
5035 "Only one signing key is supported unlike the @option{--keyid} option. "
5036 "A passphrase to decrypt the data file "
5037 "will be required when one or more of the original encryption keys or signing "
5038 "key are not found in either of these two options' arguments or when the data "
5039 "file is symmetrically encrypted reguardless of the @code{require_save_key} "
5040 "configuration parameter. The original encryption keys and signing key will be "
5041 "used when neither of these options are specified."
5042 "@*@*"
5043 "The @option{--keyid} and @option{--sign-keyid} options are not available "
5044 "to non-invoking clients "
5045 "(@pxref{Access Control}) when the recipients or signer do not match those "
5046 "that were used when the file was @code{OPEN}'ed."
5047 "@*@*"
5048 "The @option{--symmetric} option specifies that a new data file be "
5049 "conventionally encrypted. These types of data files do not use a recipient "
5050 "public key but may optionally be signed by using the @option{--sign-keyid} "
5051 "option. To remove the signing key from a symmtrically encrypted data file, "
5052 "leave the option value empty."
5053 "@*@*"
5054 "Note that you cannot change encryption schemes once a data file has been "
5055 "saved."
5058 new_command("ISCACHED", 1, 0, 0, iscached_command, _(
5059 "ISCACHED [--lock] [--agent [--sign]] <filename>\n"
5060 "Determines the file cache status of the specified @var{filename}. "
5061 "The default is to test whether the filename is cached in memory. Passing "
5062 "option @option{--agent} will test the @command{gpg-agent} cache for at most "
5063 "one cached key used for opening the data file (@pxref{OPEN}). To test if "
5064 "a signing key is cached, pass @option{--sign} along with @option{--agent}. "
5065 "Both the @option{--agent} and @option{--sign} options require an opened data "
5066 "file."
5067 "@*@*"
5068 "An @emph{OK} response is returned if the specified @var{filename} is found "
5069 "in the cache. If not found in the cache but exists on the filesystem "
5070 "then @code{GPG_ERR_NO_DATA} is returned. Otherwise a filesystem error is "
5071 "returned."
5072 "@*@*"
5073 "The @option{--lock} option will lock the file mutex of @var{filename} when "
5074 "the file exists; it does not need to be opened nor cached. The lock will be "
5075 "released when the client exits or sends the @code{UNLOCK} command "
5076 "(@pxref{UNLOCK}). When this option is passed the current data file is closed."
5079 new_command("CLEARCACHE", 1, 1, 0, clearcache_command, _(
5080 "CLEARCACHE [<filename>]\n"
5081 "Clears a file cache entry for all or the specified @var{filename}. Note that "
5082 "this will also clear any @command{gpg-agent} cached keys which may cause "
5083 "problems if another data file shares the same keys as @var{filename}."
5084 "@*@*"
5085 "When clearing all cache entries a permissions test is done against the "
5086 "current client based on the @var{allowed} configuration parameter in a "
5087 "@var{filename} section. Both a cache entry may be cleared and an error "
5088 "returned depending on cached data files and client permissions."
5091 new_command("CACHETIMEOUT", 1, 1, 0, cachetimeout_command, _(
5092 "CACHETIMEOUT <filename> <seconds>\n"
5093 "The time in @var{seconds} until @var{filename} will be removed from the "
5094 "cache. @code{-1} will keep the cache entry forever, @code{0} will require "
5095 "the passphrase for each @code{OPEN} command (@pxref{OPEN}) or @code{SAVE} "
5096 "(@pxref{SAVE}) command. @xref{Configuration}, and the @code{cache_timeout} "
5097 "parameter."
5100 new_command("LIST", 0, 1, 0, list_command, _(
5101 "LIST [--inquire] [--recurse] [element[<TAB>child[..]]]\n"
5102 "If no element path is given then a newline separated list of root elements "
5103 "is returned with a data response. If given, then children of the specified "
5104 "element path are returned."
5105 "@*@*"
5106 "Each element path "
5107 "returned will have zero or more flags appened to it. These flags are "
5108 "delimited from the element path by a single space character. A flag itself "
5109 "is a single character. Flag @code{P} indicates that access to the element "
5110 "is denied. Flag @code{+} indicates that there are child nodes of "
5111 "the current element path. Flag @code{E} indicates that an element of the "
5112 "element path contained in a @var{target} attribute could not be found. Flag "
5113 "@code{O} indicates that a @var{target} attribute recursion limit was reached "
5114 "(@pxref{Configuration}). Flag @code{T}, followed by a single space character, "
5115 "then an element path, is the element path of the @var{target} attribute "
5116 "contained in the current element."
5117 "@*@*"
5118 "When a specified element path contains an error, beit from the final "
5119 "element in the path or any previous element, the path is still shown but "
5120 "will contain the error flag for the element with the error. Determining "
5121 "the actual element which contains the error is up to the client. This can be "
5122 "done by traversing the final element up to parent elements that contain the "
5123 "same error flag."
5124 "@*@*"
5125 "The option @option{--recurse} may be used to list the entire element tree "
5126 "for a specified element path or the entire tree for all root elements."
5127 "@*@*"
5128 "When the @option{--inquire} option is passed then all remaining non-option "
5129 "arguments are retrieved via a server @emph{INQUIRE}."
5132 new_command("REALPATH", 0, 1, 0, realpath_command, _(
5133 "REALPATH [--inquire] element[<TAB>child[..]]\n"
5134 "Resolves all @code{target} attributes of the specified element path and "
5135 "returns the result with a data response. @xref{Target Attribute}, for details."
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("STORE", 0, 1, 0, store_command, _(
5142 "STORE element[<TAB>child[..]]<TAB>[content]\n"
5143 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
5144 "@*@*"
5145 "Creates a new element path or modifies the @var{content} of an existing "
5146 "element. If only a single element is specified then a new root element is "
5147 "created. Otherwise, elements are @key{TAB} delimited and the content will be "
5148 "set to the final @key{TAB} delimited element. If no @var{content} is "
5149 "specified after the final @key{TAB}, then the content of the existing "
5150 "element will be removed; or will be empty if creating a new element."
5151 "@*@*"
5152 "The only restriction of an element name is that it not contain whitespace "
5153 "characters. There is no other whitespace between the @key{TAB} delimited "
5154 "elements. It is recommended that the content of an element be base64 encoded "
5155 "when it contains control or @key{TAB} characters to prevent @abbr{XML} "
5156 "parsing and @command{pwmd} syntax errors."
5159 new_command("RENAME", 0, 1, 0, rename_command, _(
5160 "RENAME [--inquire] element[<TAB>child[..]] <value>\n"
5161 "Renames the specified @var{element} to the new @var{value}. If an element of "
5162 "the same name as the @var{value} already exists it will be overwritten."
5163 "@*@*"
5164 "When the @option{--inquire} option is passed then all remaining non-option "
5165 "arguments are retrieved via a server @emph{INQUIRE}."
5168 new_command("COPY", 0, 1, 0, copy_command, _(
5169 "COPY [--inquire] source[<TAB>child[..]] dest[<TAB>child[..]]\n"
5170 "Copies the entire element tree starting from the child node of the source "
5171 "element, to the destination element path. If the destination element path "
5172 "does not exist then it will be created; otherwise it is overwritten."
5173 "@*@*"
5174 "Note that attributes from the source element are merged into the "
5175 "destination element when the destination element path exists. When an "
5176 "attribute of the same name exists in both the source and destination "
5177 "elements then the destination attribute will be updated to the source "
5178 "attribute value."
5179 "@*@*"
5180 "When the @option{--inquire} option is passed then all remaining non-option "
5181 "arguments are retrieved via a server @emph{INQUIRE}."
5184 new_command("MOVE", 0, 1, 0, move_command, _(
5185 "MOVE [--inquire] source[<TAB>child[..]] [dest[<TAB>child[..]]]\n"
5186 "Moves the source element path to the destination element path. If the "
5187 "destination is not specified then it will be moved to the root node of the "
5188 "document. If the destination is specified and exists then it will be "
5189 "overwritten; otherwise non-existing elements of the destination element "
5190 "path will be created."
5191 "@*@*"
5192 "When the @option{--inquire} option is passed then all remaining non-option "
5193 "arguments are retrieved via a server @emph{INQUIRE}."
5196 new_command("DELETE", 0, 1, 0, delete_command, _(
5197 "DELETE [--inquire] element[<TAB>child[..]]\n"
5198 "Removes the specified element path and all of its children. This may break "
5199 "an element with a @code{target} attribute (@pxref{Target Attribute}) that "
5200 "refers to this element or any of its children."
5201 "@*@*"
5202 "When the @option{--inquire} option is passed then all remaining non-option "
5203 "arguments are retrieved via a server @emph{INQUIRE}."
5206 new_command("GET", 0, 1, 0, get_command, _(
5207 "GET [--inquire] element[<TAB>child[..]]\n"
5208 "Retrieves the content of the specified element. The content is returned "
5209 "with a data response."
5210 "@*@*"
5211 "When the @option{--inquire} option is passed then all remaining non-option "
5212 "arguments are retrieved via a server @emph{INQUIRE}."
5215 new_command("ATTR", 0, 1, 0, attr_command, _(
5216 "ATTR [--inquire] SET|GET|DELETE|LIST [<attribute>] element[<TAB>child[..]] ..\n"
5217 "@table @asis\n"
5218 "@item ATTR SET attribute element[<TAB>child[..]] [value]\n"
5219 " Stores or updates an @var{attribute} name and optional @var{value} of an "
5220 "element. When no @var{value} is specified any existing value will be removed."
5221 "@*@*"
5222 "@item ATTR DELETE attribute element[<TAB>child[..]]\n"
5223 " Removes an attribute from an element. If @var{attribute} is @code{_name} "
5224 "or @code{target} an error is returned. Use the @command{DELETE} command "
5225 "(@pxref{DELETE}) instead."
5226 "@*@*"
5227 "@item ATTR LIST element[<TAB>child[..]]\n"
5228 " Retrieves a newline separated list of attributes names and values "
5229 "from the specified element. Each attribute name and value is space delimited."
5230 "@*@*"
5231 "@item ATTR GET attribute element[<TAB>child[..]]\n"
5232 " Retrieves the value of an @var{attribute} from an element."
5233 "@end table\n"
5234 "@*@*"
5235 "When the @option{--inquire} option is passed then all remaining non-option "
5236 "arguments are retrieved via a server @emph{INQUIRE}."
5237 "@*@*"
5238 "@xref{Target Attribute}, for details about this special attribute and also "
5239 "@pxref{Other Attributes} for other attributes that are handled specially "
5240 "by @command{pwmd}."
5243 new_command("XPATH", 0, 1, 0, xpath_command, _(
5244 "XPATH [--inquire] <expression>[<TAB>[value]]\n"
5245 "Evaluates an XPath @var{expression}. If no @var{value} argument is "
5246 "specified it is assumed the expression is a request to return a result. "
5247 "Otherwise, the result is set to the @var{value} argument and the document is "
5248 "updated. If there is no @var{value} after the @key{TAB} character, the value "
5249 "is assumed to be empty and the document is updated. For example:"
5250 "@sp 1\n"
5251 "@example\n"
5252 "XPATH //element[@@_name='password']@key{TAB}\n"
5253 "@end example\n"
5254 "@sp 1\n"
5255 "would clear the content of all @var{password} elements in the data file "
5256 "while leaving off the trailing @key{TAB} would return all @var{password} "
5257 "elements in @abbr{XML} format."
5258 "@*@*"
5259 "When the @option{--inquire} option is passed then all remaining non-option "
5260 "arguments are retrieved via a server @emph{INQUIRE}."
5261 "@*@*"
5262 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
5263 "expression syntax."
5266 new_command("XPATHATTR", 0, 1, 0, xpathattr_command, _(
5267 "XPATHATTR [--inquire] SET|DELETE <name> <expression>[<TAB>[<value>]]\n"
5268 "Like the @code{XPATH} command (@pxref{XPATH}) but operates on element "
5269 "attributes and does not return a result. For the @var{SET} operation the "
5270 "@var{value} is optional but the field is required. If not specified then "
5271 "the attribute value will be empty. For example:"
5272 "@sp 1\n"
5273 "@example\n"
5274 "XPATHATTR SET password //element[@@_name='password']@key{TAB}\n"
5275 "@end example\n"
5276 "@sp 1\n"
5277 "would create a @var{password} attribute for each @var{password} element "
5278 "found in the document. The attribute value will be empty but still exist."
5279 "@*@*"
5280 "When the @option{--inquire} option is passed then all remaining non-option "
5281 "arguments are retrieved via a server @emph{INQUIRE}."
5282 "@*@*"
5283 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
5284 "expression syntax."
5287 new_command("IMPORT", 0, 1, 0, import_command, _(
5288 "IMPORT [--root=element[<TAB>child[..]]]\n"
5289 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
5290 "@*@*"
5291 "Like the @code{STORE} command (@pxref{STORE}), but the @var{content} "
5292 "argument is raw @abbr{XML} data. The content is created as a child of "
5293 "the element path specified with the @option{--root} option or at the "
5294 "document root when not specified. Existing elements of the same name will "
5295 "be overwritten."
5296 "@*@*"
5297 "The content must begin with an @abbr{XML} element node. @xref{Introduction}, "
5298 "for details."
5301 new_command("DUMP", 1, 1, 0, dump_command, _(
5302 "DUMP\n"
5303 "Shows the in memory @abbr{XML} document with indenting. @xref{XPATH}, for "
5304 "dumping a specific node."
5307 new_command("LOCK", 0, 0, 0, lock_command, _(
5308 "LOCK\n"
5309 "Locks the mutex associated with the opened file. This prevents other clients "
5310 "from sending commands to the same opened file until the client "
5311 "that sent this command either disconnects or sends the @code{UNLOCK} "
5312 "command. @xref{UNLOCK}."
5315 new_command("UNLOCK", 1, 0, 0, unlock_command, _(
5316 "UNLOCK\n"
5317 "Unlocks the file mutex which was locked with the @code{LOCK} command or "
5318 "a commands' @option{--lock} option (@pxref{LOCK}, @pxref{OPEN}, "
5319 "@pxref{ISCACHED})."
5322 new_command("GETCONFIG", 1, 1, 0, getconfig_command, _(
5323 "GETCONFIG [filename] <parameter>\n"
5324 "Returns the value of a @command{pwmd} configuration @var{parameter} with a "
5325 "data response. If no file has been opened then the value for @var{filename} "
5326 "or the default from the @var{global} section will be returned. If a file "
5327 "has been opened and no @var{filename} is specified, the value previously "
5328 "set with the @code{OPTION} command (@pxref{OPTION}) will be returned."
5331 new_command("OPTION", 1, 1, 0, option_command, _(
5332 "OPTION <NAME>=[<VALUE>]\n"
5333 "Sets a client option @var{name} to @var{value}. The value for an option is "
5334 "kept for the duration of the connection with the exception of the "
5335 "@command{pinentry} options which are defaults for all future connections "
5336 "(@pxref{Pinentry}). When @var{value} is empty the option is unset."
5337 "@*@*"
5338 "@table @asis\n"
5339 "@item DISABLE-PINENTRY\n"
5340 "Disable use of @command{pinentry} for passphrase retrieval. When @code{1}, a "
5341 "server inquire is sent to the client to obtain the passphrase. This option "
5342 "may be set as needed before the @code{OPEN} (@pxref{OPEN}), @code{PASSWD} "
5343 "(@pxref{PASSWD}) and @code{SAVE} (@pxref{SAVE}) commands. Set to @code{0} "
5344 "to use a @command{pinentry}."
5345 "@*@*"
5346 "@item DISPLAY\n"
5347 "Set or unset the X11 display to use when prompting for a passphrase."
5348 "@*@*"
5349 "@item TTYNAME\n"
5350 "Set the terminal device path to use when prompting for a passphrase."
5351 "@*@*"
5352 "@item TTYTYPE\n"
5353 "Set the terminal type for use with @option{TTYNAME}."
5354 "@*@*"
5355 "@item NAME\n"
5356 "Associates the thread ID of the connection with the specified textual "
5357 "representation. Useful for debugging log messages. May not contain whitespace."
5358 "@*@*"
5359 "@item LOCK-TIMEOUT\n"
5360 "When not @code{0}, the duration in tenths of a second to wait for the file "
5361 "mutex which has been locked by another thread to be released before returning "
5362 "an error. When @code{-1} the error will be returned immediately."
5363 "@*@*"
5364 "@item CLIENT-STATE\n"
5365 "When set to @code{1} then client state status messages for other clients are "
5366 "sent to the current client. The default is @code{0}."
5367 "@end table\n"
5370 new_command("LS", 1, 1, 0, ls_command, _(
5371 "LS\n"
5372 "Returns a newline separated list of data files stored in the data directory "
5373 "@file{HOMEDIR/data} (@pxref{Invoking}) with a data response."
5376 new_command("RESET", 1, 1, 0, NULL, _(
5377 "RESET\n"
5378 "Closes the currently opened file but keeps any previously set client options "
5379 "(@pxref{OPTION})."
5382 new_command("NOP", 1, 1, 0, NULL, _(
5383 "NOP\n"
5384 "Does nothing. Always returns successfully."
5387 /* !END-HELP-TEXT! */
5388 new_command ("CANCEL", 1, 1, 0, NULL, NULL);
5389 new_command ("END", 1, 1, 0, NULL, NULL);
5390 new_command ("BYE", 1, 1, 0, NULL, NULL);
5392 int i;
5393 for (i = 0; command_table[i]; i++);
5394 qsort (command_table, i - 1, sizeof (struct command_table_s *),
5395 sort_commands);
5398 gpg_error_t
5399 register_commands (assuan_context_t ctx)
5401 int i = 0, rc;
5403 for (; command_table[i]; i++)
5405 if (!command_table[i]->handler)
5406 continue;
5408 rc = assuan_register_command (ctx, command_table[i]->name,
5409 command_table[i]->handler,
5410 command_table[i]->help);
5411 if (rc)
5412 return rc;
5415 rc = assuan_register_bye_notify (ctx, bye_notify);
5416 if (rc)
5417 return rc;
5419 rc = assuan_register_reset_notify (ctx, reset_notify);
5420 if (rc)
5421 return rc;
5423 rc = assuan_register_pre_cmd_notify (ctx, command_startup);
5424 if (rc)
5425 return rc;
5427 return assuan_register_post_cmd_notify (ctx, command_finalize);