GENKEY: Require an invoking user with --subkey-of.
[pwmd.git] / src / commands.c
blob1995cf7f5c35b04db6a22caf40cd011f88b122f6
1 /*
2 Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015,
3 2016
4 Ben Kibbey <bjk@luxsci.net>
6 This file is part of pwmd.
8 Pwmd is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 2 of the License, or
11 (at your option) any later version.
13 Pwmd is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with Pwmd. If not, see <http://www.gnu.org/licenses/>.
21 #ifdef HAVE_CONFIG_H
22 #include <config.h>
23 #endif
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <unistd.h>
28 #include <err.h>
29 #include <errno.h>
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include <fcntl.h>
33 #include <ctype.h>
34 #include <dirent.h>
35 #include <pthread.h>
36 #include <stdint.h>
37 #include <assert.h>
38 #include <signal.h>
40 #include "pwmd-error.h"
41 #include <gcrypt.h>
43 #include "mem.h"
44 #include "xml.h"
45 #include "util-misc.h"
46 #include "common.h"
47 #include "rcfile.h"
48 #include "cache.h"
49 #include "commands.h"
50 #include "mutex.h"
51 #include "crypto.h"
52 #include "acl.h"
54 /* These are command option flags. */
55 #define OPT_INQUIRE 0x0001
56 #define OPT_NO_PASSPHRASE 0x0002
57 #define OPT_ASK 0x0004
58 #define OPT_LIST_RECURSE 0x0008
59 #define OPT_VERBOSE 0x0010
60 #define OPT_LOCK 0x0020
61 #define OPT_LOCK_ON_OPEN 0x0040
62 #define OPT_SIGN 0x0080
63 #define OPT_LIST_ALL 0x0100
64 #define OPT_DATA 0x0200
65 #define OPT_NO_AGENT 0x0400
66 #define OPT_SECRET_ONLY 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);
98 /* When 'status' is true the 'self' field of the status line will be false
99 * because we never send the STATE status message to the same client that
100 * initiated it. */
101 static char *
102 build_client_info_line (struct client_thread_s *thd, int status)
104 char *uid, *username = NULL;
105 char *line;
107 #ifdef WITH_GNUTLS
108 if (thd->remote)
109 uid = str_asprintf("#%s", thd->tls->fp);
110 else
112 uid = str_asprintf("%u", thd->peer->uid);
113 username = get_username (thd->peer->uid);
115 #else
116 uid = str_asprintf("%u", thd->peer->uid);
117 username = get_username (thd->peer->uid);
118 #endif
119 line = str_asprintf ("%p %s %s %s %u %u %u %s %s %u",
120 thd->tid,
121 thd->name ? thd->name : "-",
122 thd->cl && thd->cl->filename
123 && (thd->cl->flags & FLAG_OPEN)
124 ? thd->cl->filename : "/",
125 #ifdef WITH_GNUTLS
126 thd->remote ? thd->peeraddr : "-",
127 #else
128 "-",
129 #endif
130 thd->cl && thd->cl->flags & FLAG_HAS_LOCK ? 1 : 0,
131 !status && pthread_equal (pthread_self (), thd->tid) ? 1 : 0,
132 thd->state, uid,
133 #ifdef WITH_GNUTLS
134 thd->remote ? "-" : username,
135 #else
136 username,
137 #endif
138 thd->conntime
141 xfree (username);
142 xfree (uid);
143 return line;
146 void
147 update_client_state (struct client_s *client, unsigned s)
149 MUTEX_LOCK (&cn_mutex);
150 client->thd->state = s;
151 MUTEX_UNLOCK (&cn_mutex);
153 if (client->thd->state != CLIENT_STATE_UNKNOWN)
155 char *line = build_client_info_line (client->thd, 1);
157 pthread_cleanup_push (xfree, line);
158 if (line)
159 send_status_all_not_self (STATUS_STATE, "%s", line);
160 pthread_cleanup_pop (1);
164 static gpg_error_t
165 unlock_file_mutex (struct client_s *client, int remove)
167 gpg_error_t rc = 0;
169 // OPEN: keep the lock for the same file being reopened.
170 if (client->flags & FLAG_KEEP_LOCK && client->flags & FLAG_HAS_LOCK)
171 return 0;
173 if (!(client->flags & FLAG_HAS_LOCK))
174 return GPG_ERR_NOT_LOCKED;
176 rc = cache_unlock_mutex (client->filename, remove);
177 if (rc)
178 rc = GPG_ERR_INV_STATE;
179 else
180 client->flags &= ~(FLAG_HAS_LOCK | FLAG_LOCK_CMD);
182 return rc;
185 static gpg_error_t
186 lock_file_mutex (struct client_s *client, int add)
188 gpg_error_t rc = 0;
189 int timeout = config_get_integer (client->filename, "cache_timeout");
191 if (client->flags & FLAG_HAS_LOCK)
192 return 0;
194 rc = cache_lock_mutex (client->ctx, client->filename,
195 client->lock_timeout, add, timeout);
196 if (!rc)
197 client->flags |= FLAG_HAS_LOCK;
199 return rc;
202 static gpg_error_t
203 file_modified (struct client_s *client, struct command_table_s *cmd)
205 gpg_error_t rc = 0;
206 int type = !cmd->flock_type || (cmd->flock_type & FLOCK_TYPE_SH)
207 ? LOCK_SH : LOCK_EX;
209 if (!(client->flags & FLAG_OPEN))
210 return GPG_ERR_INV_STATE;
212 rc = lock_file_mutex (client, 0);
213 if (rc && rc != GPG_ERR_NO_DATA)
214 return rc;
216 rc = lock_flock (client->ctx, client->filename, type, &client->flock_fd);
217 if (!rc)
219 rc = validate_checksum (client, client->filename, NULL, NULL, NULL);
220 if (gpg_err_code (rc) == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
221 rc = 0;
222 else if (rc)
223 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
225 else if (gpg_err_code (rc) == GPG_ERR_ENOENT)
226 rc = 0;
228 /* FLAG_HAS_LOCK may have been set by the LOCK command or OPEN --lock. */
229 if ((cmd->unlock && !(client->flags & FLAG_HAS_LOCK)) || rc)
230 unlock_file_mutex (client, 0);
232 if (rc || !(cmd->flock_type & FLOCK_TYPE_KEEP))
233 unlock_flock (&client->flock_fd);
235 return rc;
238 static gpg_error_t
239 parse_xml (assuan_context_t ctx, int new)
241 struct client_s *client = assuan_get_pointer (ctx);
242 int cached = client->doc != NULL;
243 gpg_error_t rc = 0;
245 if (new)
247 client->doc = xml_new_document ();
248 if (client->doc)
250 xmlChar *result;
251 int len;
253 xmlDocDumpFormatMemory (client->doc, &result, &len, 0);
254 client->crypto->plaintext = result;
255 client->crypto->plaintext_size = len;
256 if (!client->crypto->plaintext)
258 xmlFreeDoc (client->doc);
259 client->doc = NULL;
260 rc = GPG_ERR_ENOMEM;
263 else
264 rc = GPG_ERR_ENOMEM;
266 else if (!cached)
267 rc = xml_parse_doc ((char *) client->crypto->plaintext,
268 client->crypto->plaintext_size,
269 (xmlDocPtr *)&client->doc);
271 return rc;
274 static void
275 free_client (struct client_s *client)
277 if (client->doc)
278 xmlFreeDoc (client->doc);
280 xfree (client->crc);
281 xfree (client->filename);
282 xfree (client->last_error);
283 crypto_free (client->crypto);
284 client->crypto = NULL;
287 void
288 reset_client (struct client_s *client)
290 assuan_context_t ctx = client->ctx;
291 struct client_thread_s *thd = client->thd;
292 long lock_timeout = client->lock_timeout;
293 xmlErrorPtr xml_error = client->xml_error;
294 int no_pinentry = (client->flags & FLAG_NO_PINENTRY);
295 int flock_fd = client->flock_fd;
297 unlock_file_mutex (client, client->flags & FLAG_NEW);
298 free_client (client);
299 memset (client, 0, sizeof (struct client_s));
300 client->flock_fd = flock_fd;
301 client->xml_error = xml_error;
302 client->ctx = ctx;
303 client->thd = thd;
304 client->lock_timeout = lock_timeout;
305 client->flags |= no_pinentry ? FLAG_NO_PINENTRY : 0;
308 static void
309 req_free (void *arg)
311 if (!arg)
312 return;
314 strv_free ((char **) arg);
317 static gpg_error_t
318 parse_open_opt_lock (void *data, void *value)
320 struct client_s *client = data;
322 (void)value;
323 client->opts |= OPT_LOCK_ON_OPEN;
324 return 0;
327 static gpg_error_t
328 parse_opt_inquire (void *data, void *value)
330 struct client_s *client = data;
332 (void) value;
333 client->opts |= OPT_INQUIRE;
334 return 0;
337 static gpg_error_t
338 update_checksum (struct client_s *client)
340 unsigned char *crc;
341 size_t len;
342 struct cache_data_s *cdata;
343 gpg_error_t rc = get_checksum (client->filename, &crc, &len);
345 if (rc)
346 return rc;
348 xfree (client->crc);
349 client->crc = crc;
350 cdata = cache_get_data (client->filename);
351 if (cdata)
353 xfree (cdata->crc);
354 cdata->crc = xmalloc (len);
355 memcpy (cdata->crc, crc, len);
358 return 0;
361 static gpg_error_t
362 validate_checksum (struct client_s *client, const char *filename,
363 struct cache_data_s *cdata, unsigned char **r_crc,
364 size_t *r_crclen)
366 unsigned char *crc;
367 size_t len;
368 gpg_error_t rc;
369 int n = 0;
371 if (cdata && !cdata->crc)
372 return GPG_ERR_CHECKSUM;
374 rc = get_checksum (filename, &crc, &len);
375 if (rc)
376 return rc;
378 if (cdata)
379 n = memcmp (cdata->crc, crc, len);
380 else if (client->crc)
381 n = memcmp (client->crc, crc, len);
383 if (!n && r_crc)
385 *r_crc = crc;
386 *r_crclen = len;
388 else
389 xfree (crc);
391 return n ? GPG_ERR_CHECKSUM : 0;
394 static gpg_error_t
395 open_command (assuan_context_t ctx, char *line)
397 gpg_error_t rc;
398 struct client_s *client = assuan_get_pointer (ctx);
399 char **req, *filename;
400 int same_file = 0;
401 assuan_peercred_t peer;
402 struct cache_data_s *cdata = NULL;
403 int cached = 0;
404 unsigned char *crc = NULL;
405 size_t crclen = 0;
406 struct argv_s *args[] = {
407 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_open_opt_lock},
408 NULL
411 rc = parse_options (&line, args, client, 1);
412 if (rc)
413 return send_error (ctx, rc);
415 req = str_split (line, " ", 2);
416 if (!req)
417 return send_error (ctx, GPG_ERR_SYNTAX);
419 rc = do_validate_peer (ctx, req[0], &peer);
420 if (rc == GPG_ERR_FORBIDDEN)
421 rc = peer_is_invoker (client);
423 if (rc)
425 strv_free (req);
426 return send_error (ctx, rc);
429 filename = req[0];
430 if (!valid_filename (filename))
432 strv_free (req);
433 return send_error (ctx, GPG_ERR_INV_VALUE);
436 pthread_cleanup_push ((void *)req_free, req);
437 /* This client may have locked a different file with ISCACHED --lock than
438 * the current filename. This will remove that lock. */
439 same_file = client->filename && !strcmp (filename, client->filename);
440 if (client->flags & FLAG_OPEN ||
441 (client->flags & FLAG_HAS_LOCK && !same_file))
443 unsigned opts = client->opts;
444 unsigned flags = client->flags;
446 if (same_file)
447 client->flags |= FLAG_KEEP_LOCK;
448 else if (client->flags & FLAG_NEW)
449 cache_clear (NULL, client->filename, 0);
451 reset_client (client);
452 client->opts = opts;
453 client->flags |= flags;
454 client->flags &= ~(FLAG_LOCK_CMD);
455 if (!same_file)
456 client->flags &= ~(FLAG_HAS_LOCK | FLAG_NEW);
459 client->filename = str_dup (filename);
460 if (!client->filename)
462 strv_free (req);
463 return send_error(ctx, GPG_ERR_ENOMEM);
466 /* Need to lock the mutex here because file_modified() cannot without
467 * knowing the filename. */
468 rc = lock_file_mutex (client, 1);
469 if (rc)
470 client->flags &= ~FLAG_OPEN;
472 if (!rc)
474 rc = lock_flock (ctx, filename, LOCK_SH, &client->flock_fd);
475 if (gpg_err_code (rc) == GPG_ERR_ENOENT)
476 rc = 0;
479 if (!rc)
481 char *keyfile = config_get_string (client->filename, "passphrase_file");
483 rc = crypto_init (&client->crypto, client->ctx, client->filename,
484 client->flags & FLAG_NO_PINENTRY, keyfile);
485 if (rc)
486 xfree (keyfile);
488 rc = open_check_file (client->filename, NULL, NULL, 1);
491 if (!rc || gpg_err_code (rc) == GPG_ERR_ENOENT)
493 cdata = cache_get_data (client->filename);
495 if (rc) // new file
497 rc = 0;
499 if (config_get_boolean ("global", "strict_open"))
500 rc = peer_is_invoker (client);
502 if (!rc)
504 client->flags |= FLAG_NEW;
505 // data file disappeared. clear the cache entry.
506 cache_clear (NULL, client->filename, 1);
507 cdata = NULL;
510 else if (cdata && cdata->doc) // cached document
512 int reload = 0;
513 int defer = 0;
515 if (!rc && !(client->flags & FLAG_NEW))
517 rc = validate_checksum (client, client->filename, cdata, &crc,
518 &crclen);
519 if (rc == GPG_ERR_CHECKSUM)
521 rc = 0;
522 reload = 1;
526 if (!rc)
528 rc = cache_iscached (client->filename, &defer, 0, 0);
529 if ((!rc || rc == GPG_ERR_ENOENT) && defer)
531 rc = 0;
532 reload = 2;
536 if (!rc && reload)
538 if (reload == 1)
539 log_write ("%s: %s", client->filename,
540 pwmd_strerror (GPG_ERR_CHECKSUM));
541 cache_clear (NULL, client->filename, 1);
542 cdata = NULL;
543 rc = crypto_decrypt (client, client->crypto);
545 #ifdef WITH_GNUTLS
546 else if (!rc)
548 if (client->thd->remote
549 && config_get_boolean (client->filename, "tcp_require_key")
550 && !(client->flags & FLAG_NEW))
551 rc = crypto_try_decrypt (client,
552 (client->flags & FLAG_NO_PINENTRY));
554 #endif
556 if (!rc && cdata)
558 client->crypto->plaintext = cdata->doc;
559 client->crypto->plaintext_size = cdata->size;
560 rc = cache_decrypt (client->crypto);
561 if (!rc)
563 cdata->doc = NULL;
564 cdata->size = 0;
565 strv_free (client->crypto->pubkey);
566 xfree (client->crypto->sigkey);
567 client->crypto->pubkey = strv_dup (cdata->pubkey);
568 client->crypto->sigkey = str_dup (cdata->sigkey);
569 cached = 1;
571 else
573 client->crypto->plaintext = NULL;
574 client->crypto->plaintext_size = 0;
578 else // existing file
580 cached = cdata != NULL;
581 rc = crypto_decrypt (client, client->crypto);
585 if (!rc)
587 rc = parse_xml (ctx, client->flags & FLAG_NEW);
588 if (!rc)
590 rc = cache_encrypt (client->crypto);
591 if (rc)
592 cache_clear (NULL, client->filename, 1);
593 else
595 int timeout = config_get_integer (client->filename,
596 "cache_timeout");
598 cache_free_data_once (cdata);
599 cdata = xcalloc (1, sizeof (struct cache_data_s));
600 cdata->doc = client->crypto->plaintext;
601 cdata->size = client->crypto->plaintext_size;
602 cdata->pubkey = strv_dup(client->crypto->pubkey);
603 cdata->sigkey = client->crypto->sigkey ? str_dup(client->crypto->sigkey) : NULL;
604 client->crypto->plaintext = NULL;
605 client->crypto->plaintext_size = 0;
607 if (cached) // wont increment the refcount
609 /* Prevent using another FD to update the checksum for a
610 * cached data file. The validity has already been
611 * verified. */
612 xfree (client->crc);
613 client->crc = xmalloc (crclen);
614 memcpy (client->crc, crc, crclen);
615 xfree (cdata->crc);
616 cdata->crc = xmalloc (crclen);
617 memcpy (cdata->crc, crc, crclen);
619 rc = cache_set_data (client->filename, cdata);
620 /* The cache entry may have been removed and cache_set_data()
621 * already sent STATUS_CACHE. */
622 if (!cache_iscached (client->filename, NULL, 0, 0))
623 rc = send_status (ctx, STATUS_CACHE, NULL);
625 else
626 rc = cache_add_file (client->filename, cdata, timeout);
631 pthread_cleanup_pop (1);
632 xfree (crc);
634 if (!rc && !(client->flags & FLAG_NEW) && !cached)
635 rc = update_checksum (client);
637 if (!rc)
639 client->flags |= FLAG_OPEN;
641 if (client->flags & FLAG_NEW)
642 rc = send_status (ctx, STATUS_NEWFILE, NULL);
644 if (!rc && (client->opts & OPT_LOCK_ON_OPEN))
645 rc = do_lock (client, 0);
648 if (rc)
650 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
652 if (client->flags & FLAG_NEW)
653 cache_clear (NULL, client->filename, 1);
655 crypto_free (client->crypto);
656 client->crypto = NULL;
657 client->flags &= ~FLAG_OPEN;
659 else
660 crypto_free_non_keys (client->crypto);
662 return send_error (ctx, rc);
665 /* If not the invoking_user or is an existing file, check that the list of user
666 * supplied key ID's are in the list of current key ID's obtained when
667 * decrypting the data file.
669 static gpg_error_t
670 permitted_to_save (struct client_s *client, const char **keys,
671 const char **value)
673 gpg_error_t rc = 0;
674 const char **v;
676 if ((client->flags & FLAG_NEW) || (client->opts & OPT_SYMMETRIC))
677 return 0;
679 rc = peer_is_invoker (client);
680 if (!rc)
681 return 0;
683 /* Empty match. */
684 if ((!value && !keys) || ((value && !*value) && (keys && !*keys)))
685 return 0;
687 for (v = value; v && *v; v++)
689 const char **k, *pv = *v;
690 int match = 0;
692 if (*pv == '0' && *(pv+1) == 'x')
693 pv += 2;
695 for (k = keys; k && *k; k++)
697 const char *pk = *k;
699 if (*pk == '0' && *(pk+1) == 'x')
700 pk += 2;
702 rc = !strcmp (pv, pk) ? 0 : GPG_ERR_FORBIDDEN;
703 if (rc)
704 rc = !strcmp (pv, *k) ? 0 : GPG_ERR_FORBIDDEN;
706 if (!rc)
708 match = 1;
709 break;
713 if (!match)
714 return GPG_ERR_FORBIDDEN;
717 return rc;
720 /* Requires that the keyid be a fingerprint in 16 byte form. */
721 static gpg_error_t
722 parse_save_opt_keyid_common (struct client_s *client, const char **list,
723 const char *value, char ***dst)
725 gpg_error_t rc = 0;
726 char **keys = NULL;
728 if (value && *value)
730 keys = str_split (value, ",", 0);
731 if (!keys)
732 return GPG_ERR_ENOMEM;
735 rc = crypto_keyid_to_16b (keys);
736 if (!rc)
737 rc = permitted_to_save (client, list, (const char **)keys);
739 if (!rc)
740 *dst = keys;
741 else
742 strv_free (keys);
744 return rc;
747 static gpg_error_t
748 parse_save_opt_keyid (void *data, void *value)
750 struct client_s *client = data;
751 const char *str = value;
752 char **dst = NULL;
753 gpg_error_t rc;
755 rc = parse_save_opt_keyid_common (client,
756 (const char **)client->crypto->pubkey,
757 str, &dst);
758 if (rc)
759 return rc;
761 client->crypto->save.pubkey = dst;
762 return 0;
765 static gpg_error_t
766 parse_save_opt_sign_keyid (void *data, void *value)
768 struct client_s *client = data;
769 const char *str = value;
770 char **dst = NULL;
771 gpg_error_t rc;
772 char **tmp = NULL;
774 if (client->crypto->sigkey)
776 if (!strv_printf (&tmp, "%s", client->crypto->sigkey))
777 return GPG_ERR_ENOMEM;
780 rc = parse_save_opt_keyid_common (client, (const char **)tmp, str, &dst);
781 strv_free (tmp);
782 if (rc)
783 return rc;
785 if (!dst)
786 client->opts |= OPT_NO_SIGNER;
787 else
788 client->crypto->save.sigkey = str_dup (*dst);
790 strv_free (dst);
791 return 0;
794 static gpg_error_t
795 parse_save_opt_inquire (struct client_s *client, unsigned opt)
797 if (opt == OPT_INQUIRE && !(client->flags & FLAG_NEW))
799 gpg_error_t rc = peer_is_invoker (client);
801 if (rc)
802 return rc;
805 client->opts |= opt;
806 return 0;
809 static gpg_error_t
810 parse_save_opt_inquire_keyparam (void *data, void *value)
812 (void)value;
813 return parse_save_opt_inquire (data, OPT_INQUIRE);
816 static gpg_error_t
817 parse_save_opt_inquire_keyid (void *data, void *value)
819 (void)value;
820 return parse_save_opt_inquire (data, OPT_INQUIRE_KEYID);
823 static gpg_error_t
824 parse_save_opt_symmetric (void *data, void *value)
826 struct client_s *client = data;
828 (void)value;
829 client->opts |= OPT_SYMMETRIC;
830 return 0;
833 static gpg_error_t
834 parse_save_opt_userid (void *data, void *value)
836 struct client_s *client = data;
838 if (!(client->flags & FLAG_NEW))
840 gpg_error_t rc = peer_is_invoker (client);
842 if (rc)
843 return rc;
846 client->crypto->save.userid = str_dup (value);
847 return client->crypto->save.userid ? 0 : GPG_ERR_ENOMEM;
850 static gpg_error_t
851 parse_save_opt_algo (void *data, void *value)
853 struct client_s *client = data;
855 client->crypto->save.algo = str_dup (value);
856 return client->crypto->save.algo ? 0 : GPG_ERR_ENOMEM;
859 static gpg_error_t
860 parse_save_opt_expire (void *data, void *value)
862 struct client_s *client = data;
863 gpg_error_t rc = 0;
864 char *p = NULL;
865 unsigned long t;
867 errno = 0;
868 t = strtoul (value, &p, 10);
870 if (!errno && p && *p)
871 rc = GPG_ERR_INV_VALUE;
872 else if (t == ULONG_MAX)
873 rc = GPG_ERR_INV_VALUE;
874 else if (errno)
875 rc = gpg_error_from_syserror ();
876 else
877 client->crypto->save.expire = t;
879 return rc;
882 static gpg_error_t
883 parse_save_opt_no_passphrase (void *data, void *value)
885 struct client_s *client = data;
887 (void)value;
888 client->crypto->save.flags |= GPGME_CREATE_NOPASSWD;
889 return 0;
892 /* Tests that the keys in new_keys are also in old_keys. */
893 static gpg_error_t
894 compare_keys (char **new_keys, char **old_keys)
896 char **o;
898 if (!old_keys || !*old_keys)
899 return 0;
901 crypto_keyid_to_16b (new_keys);
903 for (o = old_keys; *o; o++)
905 char **n;
907 for (n = new_keys; *n; n++)
909 if (!strcmp (*n, *o))
910 break;
913 if (!*n)
914 return GPG_ERR_NOT_FOUND;
917 return 0;
920 static gpg_error_t
921 inquire_keyid (struct client_s *client, unsigned opt)
923 gpg_error_t rc;
924 unsigned char *result = NULL;
925 size_t len;
926 const char *s;
927 char ***orig;
928 char ***save;
930 if (opt == OPT_INQUIRE_KEYID)
932 s = "KEYID";
933 orig = &client->crypto->pubkey;
934 save = &client->crypto->save.pubkey;
937 rc = assuan_inquire (client->ctx, s, &result, &len, 0);
938 if (!rc)
940 char **dst = NULL;
942 rc = parse_save_opt_keyid_common (client, (const char **)*orig,
943 (char *)result, &dst);
944 if (!rc)
945 *save = dst;
948 xfree (result);
949 return rc;
952 /* The caching test of gpg-agent is both a blessing and a curse. When a key
953 * lookup in its cache fails it tries the last successful key to be unlocked.
954 * This prevents pwmd from successfully clearing a signing key since the
955 * previous key, which more than likely belongs to the same keypair as the
956 * encryption/decryption key, will have the passphrase cached and therefore the
957 * signing key also cached. So we need to clear both the signing and encryption
958 * keys to get the effect of requiring a passphrase when generating a new
959 * keypair for an existing data file, or when the "require_save_key"
960 * configuration parameter is set. The "require_save_key" parameter is mostly a
961 * failsafe of the gpg-agent option --ignore-cache-for-signing since
962 * some/most/all users may fail to set it.
964 static gpg_error_t
965 save_command (assuan_context_t ctx, char *line)
967 struct client_s *client = assuan_get_pointer (ctx);
968 struct cache_data_s *cdata = NULL;
969 gpg_error_t rc = 0, cached = 0;
970 int defer = 0;
971 struct argv_s *args[] = {
972 &(struct argv_s) {"keyid", OPTION_TYPE_ARG, parse_save_opt_keyid},
973 &(struct argv_s) {"inquire-keyid", OPTION_TYPE_NOARG,
974 parse_save_opt_inquire_keyid },
975 &(struct argv_s) {"sign-keyid", OPTION_TYPE_OPTARG,
976 parse_save_opt_sign_keyid},
977 &(struct argv_s) {"inquire-keyparam", OPTION_TYPE_NOARG,
978 parse_save_opt_inquire_keyparam },
979 &(struct argv_s) {"userid", OPTION_TYPE_ARG,
980 parse_save_opt_userid},
981 &(struct argv_s) {"expire", OPTION_TYPE_ARG,
982 parse_save_opt_expire},
983 &(struct argv_s) {"algo", OPTION_TYPE_ARG,
984 parse_save_opt_algo},
985 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG,
986 parse_save_opt_no_passphrase},
987 &(struct argv_s) {"symmetric", OPTION_TYPE_NOARG,
988 parse_save_opt_symmetric },
989 NULL
992 crypto_free_save (&client->crypto->save);
994 if (!(client->flags & FLAG_NEW))
996 rc = crypto_is_symmetric (client->filename);
997 if (!rc || rc == GPG_ERR_BAD_DATA)
999 if (!rc)
1000 client->opts |= OPT_SYMMETRIC;
1002 rc = 0; // PKI
1006 if (rc)
1007 return send_error (ctx, rc);
1009 rc = parse_options (&line, args, client, 0);
1010 if (rc)
1011 return send_error (ctx, rc);
1014 if (config_get_boolean (client->filename, "require_save_key")
1015 || (client->opts & OPT_SYMMETRIC))
1016 client->opts |= OPT_ASK;
1018 rc = open_check_file (client->filename, NULL, NULL, 1);
1019 if (rc && gpg_err_code (rc) != GPG_ERR_ENOENT)
1021 log_write ("%s: %s", client->filename, pwmd_strerror (rc));
1022 return send_error (ctx, rc);
1025 if (!rc)
1026 cached = rc = cache_iscached (client->filename, &defer, 0, 1);
1028 if (gpg_err_code (rc) == GPG_ERR_ENOENT && (client->flags & FLAG_NEW))
1029 rc = 0;
1030 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
1031 rc = 0;
1033 if (rc)
1034 return send_error (ctx, rc);
1036 /* Specifying both a recipient and symmetric encryption is an error. */
1037 if (client->opts & OPT_INQUIRE_KEYID && client->opts & OPT_SYMMETRIC)
1039 return send_error (ctx, GPG_ERR_CONFLICT);
1041 else if ((client->opts & OPT_INQUIRE || client->crypto->save.userid) && client->opts & OPT_SYMMETRIC)
1043 return send_error (ctx, GPG_ERR_CONFLICT);
1045 /* Existing file with a recipient and wanting symmetric is an error. */
1046 else if (client->opts & OPT_SYMMETRIC && client->crypto->save.pubkey)
1048 return send_error (ctx, GPG_ERR_CONFLICT);
1050 else if (client->opts & OPT_INQUIRE_KEYID)
1052 if ((client->opts & OPT_INQUIRE) || (client->crypto->save.userid))
1053 return send_error (ctx, GPG_ERR_CONFLICT);
1055 if (client->opts & OPT_INQUIRE_KEYID)
1056 rc = inquire_keyid (client, OPT_INQUIRE_KEYID);
1058 else if ((client->crypto->save.pubkey || client->crypto->save.sigkey)
1059 && (client->opts & OPT_INQUIRE || client->crypto->save.userid))
1060 return send_error (ctx, GPG_ERR_CONFLICT);
1062 if (!rc)
1064 client->crypto->keyfile = config_get_string (client->filename,
1065 "passphrase_file");
1066 rc = crypto_init_ctx (client->crypto, (client->flags & FLAG_NO_PINENTRY),
1067 client->crypto->keyfile);
1070 if (!rc && (client->opts & OPT_INQUIRE || client->crypto->save.userid))
1072 /* Require a passphrase when generating a new key pair for an existing
1073 * file.
1075 if (!(client->flags & FLAG_NEW))
1077 rc = cache_clear_agent_keys (client->filename, 1, 1);
1078 if (!rc)
1080 rc = crypto_try_decrypt (client, client->flags & FLAG_NO_PINENTRY);
1081 client->opts &= ~OPT_ASK;
1085 if (!rc)
1087 client->crypto->flags |= CRYPTO_FLAG_NEWFILE;
1089 if (client->crypto->save.userid)
1090 rc = crypto_genkey (client, client->crypto, NULL);
1091 else
1093 unsigned char *params = NULL;
1094 size_t len;
1096 rc = assuan_inquire (client->ctx, "KEYPARAM", &params, &len, 0);
1097 if (!rc)
1099 pthread_cleanup_push ((void *)xfree, params);
1100 rc = crypto_genkey (client, client->crypto, params);
1101 pthread_cleanup_pop (1);
1106 else if (!rc && (client->flags & FLAG_NEW))
1108 if (!client->crypto->save.pubkey && !client->crypto->save.sigkey
1109 && !(client->opts & OPT_SYMMETRIC))
1111 client->crypto->flags |= CRYPTO_FLAG_NEWFILE;
1113 if (client->crypto->save.userid)
1114 rc = crypto_genkey (client, client->crypto, NULL);
1115 else
1117 char *params = crypto_default_key_params ();
1119 if (!params)
1120 rc = GPG_ERR_ENOMEM;
1122 if (!rc)
1124 pthread_cleanup_push ((void *)xfree, params);
1125 rc = crypto_genkey (client, client->crypto,
1126 (unsigned char *)params);
1127 pthread_cleanup_pop (1);
1131 else
1133 if (!client->crypto->save.pubkey && client->crypto->save.sigkey
1134 && !(client->opts & OPT_SYMMETRIC))
1135 rc = GPG_ERR_NO_PUBKEY;
1138 else if (!rc)
1140 cdata = cache_get_data (client->filename);
1141 if (cdata)
1143 if (client->crypto->save.pubkey)
1144 rc = compare_keys (client->crypto->save.pubkey, cdata->pubkey);
1146 /* Always allow a signer for symmetric data files. */
1147 if (!rc && client->crypto->save.sigkey
1148 && !(client->opts & OPT_SYMMETRIC))
1149 rc = !strcmp (client->crypto->save.sigkey, cdata->sigkey)
1150 ? 0 : GPG_ERR_NOT_FOUND;
1152 /* Prevent saving to a recipient who is not in the original recipient
1153 * list without a passphrase. */
1154 if (rc || (client->crypto->sigkey && client->opts & OPT_NO_SIGNER))
1155 client->opts |= OPT_ASK;
1157 if (rc == GPG_ERR_NOT_FOUND)
1159 rc = peer_is_invoker (client);
1160 if (rc == GPG_ERR_EACCES)
1161 rc = GPG_ERR_FORBIDDEN;
1164 if (!client->crypto->save.pubkey
1165 && !(client->opts & OPT_SYMMETRIC))
1166 client->crypto->save.pubkey = strv_dup (cdata->pubkey);
1168 if (!rc && !client->crypto->save.sigkey && cdata->sigkey
1169 && !(client->opts & OPT_NO_SIGNER))
1170 client->crypto->save.sigkey = str_dup (cdata->sigkey);
1171 else if (!rc && !client->crypto->save.sigkey
1172 && (client->opts & OPT_NO_SIGNER)
1173 && !(client->opts & OPT_SYMMETRIC))
1174 rc = GPG_ERR_NO_SIGNATURE_SCHEME;
1176 else
1178 client->crypto->save.pubkey = strv_dup (client->crypto->pubkey);
1179 client->crypto->save.sigkey = str_dup (client->crypto->sigkey);
1183 if (!rc && !(client->flags & FLAG_NEW))
1185 /* Fixes {NEW_,SIGN_}PASSPHRASE inquire keywords. See passphrase_cb(). */
1186 if (client->opts & OPT_SYMMETRIC)
1187 client->crypto->flags |= CRYPTO_FLAG_PASSWD;
1189 if (client->opts & OPT_ASK)
1191 rc = cache_clear_agent_keys (client->filename, 1, 1);
1192 if (!rc)
1193 rc = crypto_try_decrypt (client, client->flags & FLAG_NO_PINENTRY);
1197 if (!rc && client->opts & OPT_SYMMETRIC)
1198 client->crypto->flags |= CRYPTO_FLAG_PASSWD_NEW;
1200 if (!rc)
1201 rc = xml_update_element_mtime (client, xmlDocGetRootElement (client->doc));
1203 if (!rc)
1205 int size;
1207 xmlDocDumpFormatMemory (client->doc, &client->crypto->plaintext, &size,
1209 if (size > 0)
1210 client->crypto->plaintext_size = (size_t) size;
1211 else
1212 rc = GPG_ERR_ENOMEM;
1214 if (!rc)
1216 client->crypto->flags |= (client->opts & OPT_SYMMETRIC) ? CRYPTO_FLAG_SYMMETRIC : 0;
1217 client->crypto->flags |= (client->flags & FLAG_NEW) ? CRYPTO_FLAG_NEWFILE : 0;
1218 client->crypto->flags |= !(client->opts & OPT_SYMMETRIC) ? CRYPTO_FLAG_PASSWD_SIGN : 0;
1219 rc = crypto_encrypt (client, client->crypto);
1220 client->crypto->flags &= ~CRYPTO_FLAG_SYMMETRIC;
1223 if (!rc)
1225 rc = crypto_write_file (client->crypto);
1226 if (!rc)
1228 if (!cached) // no error
1229 cdata = cache_get_data (client->filename);
1232 if (!rc)
1234 rc = cache_encrypt (client->crypto);
1235 if (rc)
1237 cache_clear (NULL, client->filename, 1);
1238 strv_free (client->crypto->pubkey);
1239 client->crypto->pubkey = strv_dup (client->crypto->save.pubkey);
1240 xfree (client->crypto->sigkey);
1241 client->crypto->sigkey = str_dup (client->crypto->save.sigkey);
1242 client->flags &= ~(FLAG_NEW);
1246 if (!rc)
1248 int timeout = config_get_integer (client->filename,
1249 "cache_timeout");
1251 cache_free_data_once (cdata);
1252 cdata = xcalloc (1, sizeof (struct cache_data_s));
1253 cdata->doc = client->crypto->plaintext;
1254 client->crypto->plaintext = NULL;
1255 cdata->size = client->crypto->plaintext_size;
1256 client->crypto->plaintext_size = 0;
1257 cdata->pubkey = client->crypto->save.pubkey;
1258 client->crypto->save.pubkey = NULL;
1259 cdata->sigkey = client->crypto->save.sigkey;
1260 client->crypto->save.sigkey = NULL;
1262 /* Update in case the cache entry expires the next SAVE may not
1263 * have any known keys. */
1264 strv_free (client->crypto->pubkey);
1265 client->crypto->pubkey = strv_dup (cdata->pubkey);
1266 xfree (client->crypto->sigkey);
1267 client->crypto->sigkey = NULL;
1268 if (cdata->sigkey)
1269 client->crypto->sigkey = str_dup (cdata->sigkey);
1271 if (!cached) // no error and wont increment refcount
1272 rc = cache_set_data (client->filename, cdata);
1273 else
1274 rc = cache_add_file (client->filename, cdata, timeout);
1276 if (!rc && (cached || (client->flags & FLAG_NEW)))
1277 send_status_all (STATUS_CACHE, NULL);
1279 if (!rc)
1281 rc = update_checksum (client);
1282 client->flags &= ~(FLAG_NEW);
1288 crypto_free_non_keys (client->crypto);
1289 return send_error (ctx, rc);
1292 static gpg_error_t
1293 parse_genkey_opt_usage (void *data, void *v)
1295 struct client_s *client = data;
1296 char *value = v;
1298 if (!value || !*value)
1299 return GPG_ERR_INV_VALUE;
1300 else if (!strcmp (value, "sign"))
1301 client->crypto->save.flags |= GPGME_CREATE_SIGN;
1302 else if (!strcmp (value, "encrypt"))
1303 client->crypto->save.flags |= GPGME_CREATE_ENCR;
1304 else if (!strcmp (value, "default"))
1305 client->crypto->save.flags &= ~(GPGME_CREATE_ENCR|GPGME_CREATE_SIGN);
1306 else
1307 return GPG_ERR_INV_VALUE;
1309 return 0;
1312 gpg_error_t
1313 parse_genkey_opt_subkey_of (void *data, void *v)
1315 gpg_error_t rc;
1316 struct client_s *client = data;
1317 char *value = v;
1318 char *tmp[] = { value, NULL };
1319 gpgme_key_t *keys = NULL;
1321 rc = peer_is_invoker (client);
1322 if (rc)
1323 return rc;
1325 if (!value || !*value)
1326 return GPG_ERR_INV_VALUE;
1328 rc = crypto_list_keys (client->crypto, tmp, 1, &keys);
1329 if (rc)
1330 return rc;
1332 if (!keys || !*keys)
1334 crypto_free_key_list (keys);
1335 return GPG_ERR_NO_SECKEY;
1338 client->crypto->save.mainkey = keys;
1339 return 0;
1342 static gpg_error_t
1343 genkey_command (assuan_context_t ctx, char *line)
1345 struct client_s *client = assuan_get_pointer (ctx);
1346 struct crypto_s *crypto, *orig;
1347 gpg_error_t rc = 0;
1348 struct argv_s *args[] = {
1349 &(struct argv_s) {"inquire-keyparam", OPTION_TYPE_NOARG,
1350 parse_save_opt_inquire_keyparam },
1351 &(struct argv_s) {"userid", OPTION_TYPE_ARG,
1352 parse_save_opt_userid},
1353 &(struct argv_s) {"expire", OPTION_TYPE_ARG,
1354 parse_save_opt_expire},
1355 &(struct argv_s) {"algo", OPTION_TYPE_ARG,
1356 parse_save_opt_algo},
1357 &(struct argv_s) {"no-passphrase", OPTION_TYPE_NOARG,
1358 parse_save_opt_no_passphrase},
1359 &(struct argv_s) {"usage", OPTION_TYPE_ARG,
1360 parse_genkey_opt_usage},
1361 &(struct argv_s) {"subkey-of", OPTION_TYPE_ARG,
1362 parse_genkey_opt_subkey_of},
1363 NULL
1366 orig = client->crypto;
1367 rc = crypto_init (&crypto, ctx, client->filename,
1368 client->flags & FLAG_NO_PINENTRY, NULL);
1369 if (rc)
1370 return send_error (ctx, rc);
1372 client->crypto = crypto;
1373 rc = parse_options (&line, args, client, 0);
1374 if (rc)
1375 goto fail;
1377 if (!(client->opts & OPT_INQUIRE) && !client->crypto->save.userid
1378 && !client->crypto->save.mainkey)
1380 rc = GPG_ERR_SYNTAX;
1381 goto fail;
1384 client->crypto->flags |= CRYPTO_FLAG_NEWFILE;
1386 if (client->crypto->save.userid || client->crypto->save.mainkey)
1387 rc = crypto_genkey (client, client->crypto, NULL);
1388 else
1390 unsigned char *params = NULL;
1391 size_t len;
1393 rc = assuan_inquire (client->ctx, "KEYPARAM", &params, &len, 0);
1394 if (!rc)
1396 pthread_cleanup_push ((void *)xfree, params);
1397 rc = crypto_genkey (client, client->crypto, params);
1398 pthread_cleanup_pop (1);
1402 fail:
1403 crypto_free (crypto);
1404 client->crypto = orig;
1405 return send_error (ctx, rc);
1408 static gpg_error_t
1409 do_delete (assuan_context_t ctx, char *line)
1411 struct client_s *client = assuan_get_pointer (ctx);
1412 struct xml_request_s *req;
1413 xmlNodePtr n;
1414 gpg_error_t rc;
1416 rc = xml_new_request (client, line, XML_CMD_DELETE, &req);
1417 if (rc)
1418 return rc;
1420 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1421 xml_free_request (req);
1422 if (rc)
1423 return rc;
1425 rc = xml_is_element_owner (client, n);
1426 if (!rc)
1427 rc = xml_unlink_node (client, n);
1429 return rc;
1432 static gpg_error_t
1433 delete_command (assuan_context_t ctx, char *line)
1435 struct client_s *client = assuan_get_pointer (ctx);
1436 gpg_error_t rc;
1437 struct argv_s *args[] = {
1438 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1439 NULL
1442 rc = parse_options (&line, args, client, 1);
1443 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1444 rc = GPG_ERR_SYNTAX;
1445 if (rc)
1446 return send_error (ctx, rc);
1448 if (client->opts & OPT_INQUIRE)
1450 unsigned char *result;
1451 size_t len;
1453 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1454 if (rc)
1455 return send_error (ctx, rc);
1457 pthread_cleanup_push ((void *)xfree, result);
1458 rc = do_delete (ctx, (char *)result);
1459 pthread_cleanup_pop (1);
1461 else
1462 rc = do_delete (ctx, line);
1464 return send_error (ctx, rc);
1467 static gpg_error_t
1468 update_element_expirey (struct client_s *client, xmlNodePtr n)
1470 gpg_error_t rc = 0;
1471 xmlChar *expire, *incr;
1472 char *p;
1473 time_t e, e_orig, i;
1474 time_t now = time (NULL);
1476 expire = xml_attribute_value (n, (xmlChar *)"expire");
1477 if (!expire)
1478 return 0;
1480 errno = 0;
1481 e = strtoul ((char *)expire, &p, 10);
1482 if (errno || *p || e == ULONG_MAX || *expire == '-')
1484 xmlFree (expire);
1485 rc = GPG_ERR_ERANGE;
1486 goto fail;
1489 xmlFree (expire);
1490 incr = xml_attribute_value (n, (xmlChar *)"expire_increment");
1491 if (!incr)
1492 return 0;
1494 i = strtoul ((char *)incr, &p, 10);
1495 if (errno || *p || i == ULONG_MAX || *incr == '-')
1497 xmlFree (incr);
1498 rc = GPG_ERR_ERANGE;
1499 goto fail;
1502 xmlFree (incr);
1503 e_orig = e;
1504 e = now + i;
1505 p = str_asprintf ("%lu", e);
1506 if (!p)
1508 rc = GPG_ERR_ENOMEM;
1509 goto fail;
1512 rc = xml_add_attribute (client, n, "expire", p);
1513 xfree (p);
1514 if (!rc)
1515 rc = send_status (client->ctx, STATUS_EXPIRE, "%lu %lu", e_orig, e);
1517 fail:
1518 return rc;
1521 static gpg_error_t
1522 store_command (assuan_context_t ctx, char *line)
1524 struct client_s *client = assuan_get_pointer (ctx);
1525 gpg_error_t rc;
1526 size_t len;
1527 unsigned char *result;
1528 xmlNodePtr n, parent;
1529 int has_content;
1530 char *content = NULL;
1531 struct xml_request_s *req;
1533 if (line && *line)
1534 return send_error (ctx, GPG_ERR_SYNTAX);
1536 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1537 if (rc)
1538 return send_error (ctx, rc);
1540 rc = xml_new_request (client, (char *)result, XML_CMD_STORE, &req);
1541 xfree (result);
1542 if (rc)
1543 return send_error (ctx, rc);
1545 /* Prevent passing the element content around to save some memory. */
1546 len = strv_length (req->args);
1547 has_content = line[strlen (line) - 1] != '\t' && len > 1;
1548 if (*(req->args+1) && !xml_valid_element_path (req->args, has_content))
1550 xml_free_request (req);
1551 return send_error (ctx, GPG_ERR_INV_VALUE);
1554 if (has_content || !*req->args[len-1])
1556 has_content = 1;
1557 content = req->args[len-1];
1558 req->args[len-1] = NULL;
1561 if (strv_length (req->args) > 1)
1563 rc = xml_check_recursion (client, req);
1564 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
1565 goto fail;
1568 parent = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1570 if (!rc && len > 1)
1572 rc = xml_is_element_owner (client, parent);
1573 if (!rc)
1575 n = xml_find_text_node (parent->children);
1576 if (n)
1577 xmlNodeSetContent (n, (xmlChar *) content);
1578 else
1579 xmlNodeAddContent (parent, (xmlChar *) content);
1581 (void)xml_update_element_mtime (client, parent);
1582 (void)update_element_expirey (client, parent);
1586 fail:
1587 xfree (content);
1588 xml_free_request (req);
1589 return send_error (ctx, rc);
1592 static gpg_error_t
1593 xfer_data (assuan_context_t ctx, const char *line, int total)
1595 struct client_s *client = assuan_get_pointer (ctx);
1596 int to_send;
1597 int sent = 0;
1598 gpg_error_t rc = 0;
1599 int progress = config_get_integer ("global", "xfer_progress");
1600 int flush = 0;
1602 if (!(client->flags & FLAG_LOCK_CMD))
1603 rc = unlock_file_mutex (client, 0);
1604 if (rc && rc != GPG_ERR_NOT_LOCKED)
1605 return rc;
1607 progress =
1608 progress > 0 ? (progress / ASSUAN_LINELENGTH) * ASSUAN_LINELENGTH : 0;
1609 to_send = total < ASSUAN_LINELENGTH ? total : ASSUAN_LINELENGTH;
1610 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1612 if (rc)
1613 return rc;
1615 again:
1618 if (sent + to_send > total)
1619 to_send = total - sent;
1621 rc = assuan_send_data (ctx, flush ? NULL : (char *) line + sent,
1622 flush ? 0 : to_send);
1623 if (!rc)
1625 sent += flush ? 0 : to_send;
1627 if ((progress && !(sent % progress) && sent != total) ||
1628 (sent == total && flush))
1629 rc = send_status (ctx, STATUS_XFER, "%li %li", sent, total);
1631 if (!flush && !rc && sent == total)
1633 flush = 1;
1634 goto again;
1638 while (!rc && sent < total);
1640 return rc;
1643 static gpg_error_t
1644 do_get (assuan_context_t ctx, char *line)
1646 struct client_s *client = assuan_get_pointer (ctx);
1647 gpg_error_t rc;
1648 struct xml_request_s *req;
1649 xmlNodePtr n;
1651 rc = xml_new_request (client, line, XML_CMD_NONE, &req);
1652 if (rc)
1653 return rc;
1655 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
1656 if (!rc)
1658 if (n && n->children)
1660 xmlNodePtr tmp = n;
1662 n = xml_find_text_node (n->children);
1663 if (!n || !n->content || !*n->content)
1664 rc = GPG_ERR_NO_DATA;
1665 else
1667 rc = xfer_data (ctx, (char *) n->content, xmlStrlen (n->content));
1668 if (!rc)
1670 xmlChar *expire = xml_attribute_value (tmp,
1671 (xmlChar *)"expire");
1672 if (expire)
1674 time_t now = time (NULL);
1675 time_t e;
1676 char *p;
1678 errno = 0;
1679 e = strtoul ((char *)expire, &p, 10);
1680 if (errno || *p || e == ULONG_MAX || *expire == '-')
1681 log_write (_("invalid expire attribute value: %s"),
1682 expire);
1683 else if (now >= e)
1684 rc = send_status (ctx, STATUS_EXPIRE, "%lu 0", e);
1686 xmlFree (expire);
1691 else
1692 rc = GPG_ERR_NO_DATA;
1695 xml_free_request (req);
1696 return rc;
1699 static gpg_error_t
1700 get_command (assuan_context_t ctx, char *line)
1702 struct client_s *client = assuan_get_pointer (ctx);
1703 gpg_error_t rc;
1704 struct argv_s *args[] = {
1705 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1706 NULL
1709 rc = parse_options (&line, args, client, 1);
1710 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1711 rc = GPG_ERR_SYNTAX;
1712 if (rc)
1713 return send_error (ctx, rc);
1715 if (client->opts & OPT_INQUIRE)
1717 unsigned char *result;
1718 size_t len;
1720 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1721 if (rc)
1722 return send_error (ctx, rc);
1724 pthread_cleanup_push ((void *)xfree, result);
1725 rc = do_get (ctx, (char *)result);
1726 pthread_cleanup_pop (1);
1728 else
1729 rc = do_get (ctx, line);
1731 return send_error (ctx, rc);
1734 static void list_command_free1 (void *arg);
1735 static gpg_error_t
1736 realpath_command (assuan_context_t ctx, char *line)
1738 gpg_error_t rc;
1739 char **realpath = NULL;
1740 struct client_s *client = assuan_get_pointer (ctx);
1741 struct argv_s *args[] = {
1742 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1743 NULL
1746 rc = parse_options (&line, args, client, 1);
1747 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1748 rc = GPG_ERR_SYNTAX;
1749 if (rc)
1750 return send_error (ctx, rc);
1752 if (client->opts & OPT_INQUIRE)
1754 unsigned char *result;
1755 size_t len;
1757 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1758 if (rc)
1759 return send_error (ctx, rc);
1761 pthread_cleanup_push ((void *)xfree, result);
1762 (void)xml_resolve_path (client, client->doc, result, &realpath, &rc);
1763 pthread_cleanup_pop (1);
1765 else
1766 (void)xml_resolve_path (client, client->doc, (unsigned char *)line,
1767 &realpath, &rc);
1769 if (!rc)
1771 char *tmp = strv_join ((char *)"\t", realpath);
1773 strv_free (realpath);
1774 if (!tmp)
1775 return send_error (ctx, GPG_ERR_ENOMEM);
1777 pthread_cleanup_push ((void *)xfree, tmp);
1778 rc = xfer_data (ctx, tmp, strlen (tmp));
1779 pthread_cleanup_pop (1);
1782 return send_error (ctx, rc);
1785 static void
1786 list_command_free1 (void *arg)
1788 if (arg)
1789 string_free ((struct string_s *) arg, 1);
1792 static gpg_error_t
1793 parse_list_opt_recurse (void *data, void *value)
1795 struct client_s *client = data;
1797 (void)value;
1798 client->opts |= OPT_LIST_RECURSE;
1799 return 0;
1802 static gpg_error_t
1803 parse_opt_verbose (void *data, void *value)
1805 struct client_s *client = data;
1807 (void)value;
1808 client->opts |= OPT_VERBOSE;
1809 return 0;
1812 static gpg_error_t
1813 list_path_once (struct client_s *client, char *line,
1814 struct element_list_s *elements, struct string_s *result)
1816 gpg_error_t rc;
1818 rc = xml_create_path_list (client, client->doc, NULL, elements, line, 0);
1819 if (rc == GPG_ERR_ELOOP || rc == GPG_ERR_EACCES)
1820 rc = 0;
1822 if (!rc)
1824 int total = slist_length (elements->list);
1826 if (total)
1828 int i;
1830 for (i = 0; i < total; i++)
1832 char *tmp = slist_nth_data (elements->list, i);
1834 string_append_printf (result, "%s%s", tmp,
1835 i + 1 == total ? "" : "\n");
1838 else
1839 rc = GPG_ERR_NO_DATA;
1842 return rc;
1845 static gpg_error_t
1846 do_list (assuan_context_t ctx, char *line)
1848 struct client_s *client = assuan_get_pointer (ctx);
1849 gpg_error_t rc = GPG_ERR_NO_DATA;
1850 struct element_list_s *elements = NULL;
1852 if (!line || !*line)
1854 struct string_s *str = string_new (NULL);
1855 xmlNodePtr n;
1857 if (!str)
1858 return GPG_ERR_ENOMEM;
1860 pthread_cleanup_push ((void *)list_command_free1, str);
1861 n = xmlDocGetRootElement (client->doc);
1862 for (n = n->children; n; n = n->next)
1864 xmlChar *name;
1866 if (n->type != XML_ELEMENT_NODE)
1867 continue;
1869 name = xmlGetProp (n, (xmlChar *)"_name");
1870 if (!name)
1872 rc = GPG_ERR_ENOMEM;
1873 break;
1876 elements = xcalloc (1, sizeof (struct element_list_s));
1877 if (!elements)
1879 xmlFree (name);
1880 rc = GPG_ERR_ENOMEM;
1881 break;
1884 elements->prefix = string_new (NULL);
1885 if (!elements->prefix)
1887 xmlFree (name);
1888 xml_free_element_list (elements);
1889 rc = GPG_ERR_ENOMEM;
1890 break;
1893 elements->recurse = client->opts & OPT_LIST_RECURSE;
1894 elements->root_only = !elements->recurse;
1895 pthread_cleanup_push ((void *)xml_free_element_list, elements);
1896 rc = list_path_once (client, (char *)name, elements, str);
1897 xmlFree (name);
1898 pthread_cleanup_pop (1);
1899 if (rc)
1900 break;
1902 if (n->next)
1903 string_append (str, "\n");
1906 if (!rc)
1907 rc = xfer_data (ctx, str->str, str->len);
1909 pthread_cleanup_pop (1);
1910 return rc;
1913 elements = xcalloc (1, sizeof (struct element_list_s));
1914 if (!elements)
1915 return GPG_ERR_ENOMEM;
1917 elements->prefix = string_new (NULL);
1918 if (!elements->prefix)
1920 xml_free_element_list (elements);
1921 return GPG_ERR_ENOMEM;
1924 elements->recurse = client->opts & OPT_LIST_RECURSE;
1925 pthread_cleanup_push ((void *)xml_free_element_list, elements);
1926 struct string_s *str = string_new (NULL);
1927 pthread_cleanup_push ((void *)list_command_free1, str);
1928 rc = list_path_once (client, line, elements, str);
1929 if (!rc)
1930 rc = xfer_data (ctx, str->str, str->len);
1932 pthread_cleanup_pop (1);
1933 pthread_cleanup_pop (1);
1934 return rc;
1937 static gpg_error_t
1938 list_command (assuan_context_t ctx, char *line)
1940 struct client_s *client = assuan_get_pointer (ctx);
1941 gpg_error_t rc;
1942 struct argv_s *args[] = {
1943 &(struct argv_s) {"recurse", OPTION_TYPE_NOARG, parse_list_opt_recurse},
1944 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
1945 /* These are deprecated but kept for backward compatibility with older
1946 * clients. */
1947 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, NULL},
1948 &(struct argv_s) {"with-target", OPTION_TYPE_NOARG, NULL},
1949 &(struct argv_s) {"all", OPTION_TYPE_NOARG, parse_list_opt_recurse},
1950 &(struct argv_s) {"no-recurse", OPTION_TYPE_NOARG, NULL},
1951 NULL
1954 if (disable_list_and_dump == 1)
1955 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
1957 rc = parse_options (&line, args, client, 1);
1958 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
1959 rc = GPG_ERR_SYNTAX;
1960 if (rc)
1961 return send_error (ctx, rc);
1963 if (client->opts & OPT_INQUIRE)
1965 unsigned char *result;
1966 size_t len;
1968 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
1969 if (rc)
1970 return send_error (ctx, rc);
1972 pthread_cleanup_push ((void *)xfree, result);
1973 rc = do_list (ctx, (char *)result);
1974 pthread_cleanup_pop (1);
1976 else
1977 rc = do_list (ctx, line);
1979 return send_error (ctx, rc);
1982 #define RESUMABLE_ERROR(rc) (rc == GPG_ERR_ELOOP || rc == GPG_ERR_EACCES \
1983 || rc == GPG_ERR_ELEMENT_NOT_FOUND || !rc)
1985 * args[0] - element path
1987 static gpg_error_t
1988 attribute_list (assuan_context_t ctx, char **args)
1990 struct client_s *client = assuan_get_pointer (ctx);
1991 char **attrlist = NULL;
1992 int i = 0;
1993 int target = 0;
1994 xmlAttrPtr a;
1995 xmlNodePtr n, an, r;
1996 char *line;
1997 gpg_error_t rc;
1998 struct xml_request_s *req;
2000 if (!args || !args[0] || !*args[0])
2001 return GPG_ERR_SYNTAX;
2003 rc = xml_new_request (client, args[0], XML_CMD_ATTR_LIST, &req);
2004 if (rc)
2005 return rc;
2007 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2008 xml_free_request (req);
2009 if (rc)
2010 return rc;
2012 again:
2013 for (a = n->properties; a; a = a->next)
2015 char **pa;
2017 if (target && xml_reserved_attribute ((char *)a->name))
2018 continue;
2020 pa = xrealloc (attrlist, (i + 2) * sizeof (char *));
2021 if (!pa)
2023 if (attrlist)
2024 strv_free (attrlist);
2026 log_write ("%s(%i): %s", __FILE__, __LINE__,
2027 pwmd_strerror (GPG_ERR_ENOMEM));
2028 return GPG_ERR_ENOMEM;
2031 attrlist = pa;
2032 an = a->children;
2033 attrlist[i] = str_asprintf ("%s %s", (char *) a->name, an && an->content
2034 ? (char *)an->content : "");
2036 if (!attrlist[i])
2038 strv_free (attrlist);
2039 log_write ("%s(%i): %s", __FILE__, __LINE__,
2040 pwmd_strerror (GPG_ERR_ENOMEM));
2041 return GPG_ERR_ENOMEM;
2044 attrlist[++i] = NULL;
2047 if (!attrlist)
2048 return GPG_ERR_NO_DATA;
2050 if (!target)
2052 r = xml_resolve_path (client, client->doc, (xmlChar *)args[0], NULL, &rc);
2053 if (!RESUMABLE_ERROR (rc))
2055 strv_free (attrlist);
2056 return rc;
2058 else if (!rc && r != n)
2060 target = 1;
2061 n = r;
2062 goto again;
2065 rc = 0;
2068 line = strv_join ("\n", attrlist);
2069 if (!line)
2071 log_write ("%s(%i): %s", __FILE__, __LINE__,
2072 pwmd_strerror (GPG_ERR_ENOMEM));
2073 strv_free (attrlist);
2074 return GPG_ERR_ENOMEM;
2077 pthread_cleanup_push ((void *)xfree, line);
2078 pthread_cleanup_push ((void *)req_free, attrlist);
2079 rc = xfer_data (ctx, line, strlen (line));
2080 pthread_cleanup_pop (1);
2081 pthread_cleanup_pop (1);
2082 return rc;
2086 * args[0] - attribute
2087 * args[1] - element path
2089 static gpg_error_t
2090 attribute_delete (struct client_s *client, char **args)
2092 gpg_error_t rc;
2093 xmlNodePtr n;
2095 if (!args || !args[0] || !*args[0] || !args[1] || !*args[1])
2096 return GPG_ERR_SYNTAX;
2098 if (!strcmp (args[0], "_name") || !strcmp (args[0], "target"))
2099 return GPG_ERR_INV_ATTR;
2101 if (!xml_reserved_attribute (args[0]))
2102 n = xml_resolve_path (client, client->doc, (xmlChar *)args[1], NULL, &rc);
2103 else
2105 struct xml_request_s *req;
2107 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
2108 if (rc)
2109 return rc;
2111 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2112 xml_free_request (req);
2115 if (!rc)
2116 rc = xml_is_element_owner (client, n);
2118 if (!rc)
2119 rc = xml_delete_attribute (client, n, (xmlChar *) args[0]);
2121 return rc;
2125 * Creates the "target" attribute. When other commands encounter an element
2126 * with this attribute they follow the "target" after appending remaining
2127 * elements from the original element path to the target. The exception is the
2128 * ATTR command that operates on the element itself (for reserved attribute
2129 * names) and not the target.
2131 * If the source element path doesn't exist when using 'ATTR SET target', it is
2132 * created, but the destination element path must exist. This is simliar to the
2133 * ls(1) command: ln -s src dst.
2135 * args[0] - source element path
2136 * args[1] - destination element path
2138 static gpg_error_t
2139 set_target_attribute (struct client_s *client, char **args)
2141 struct xml_request_s *req = NULL;
2142 char **src, **dst;
2143 gpg_error_t rc;
2144 xmlNodePtr n;
2146 if (!args || !args[0] || !args[1])
2147 return GPG_ERR_SYNTAX;
2149 src = str_split (args[0], "\t", 0);
2150 if (!src)
2151 return GPG_ERR_SYNTAX;
2153 if (!xml_valid_element_path (src, 0))
2155 strv_free (src);
2156 return GPG_ERR_INV_VALUE;
2159 dst = str_split (args[1], "\t", 0);
2160 if (!dst)
2162 strv_free (src);
2163 return GPG_ERR_SYNTAX;
2166 // Be sure the destination element path exists. */
2167 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
2168 if (rc)
2169 goto fail;
2171 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2172 if (rc && rc != GPG_ERR_EACCES)
2173 goto fail;
2175 xml_free_request (req);
2176 req = NULL;
2178 if (!strcmp (args[0], args[1]))
2180 rc = GPG_ERR_EEXIST;
2181 goto fail;
2184 rc = xml_new_request (client, args[0], XML_CMD_ATTR_TARGET, &req);
2185 if (rc)
2186 goto fail;
2188 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2189 if (rc && rc != GPG_ERR_EACCES)
2190 goto fail;
2192 if (!rc)
2194 rc = xml_add_attribute (client, n, "target", args[1]);
2195 if (!rc)
2196 rc = xml_unlink_node (client, n->children);
2199 fail:
2200 strv_free (src);
2201 strv_free (dst);
2202 xml_free_request (req);
2203 return rc;
2207 * args[0] - attribute
2208 * args[1] - element path
2210 static gpg_error_t
2211 attribute_get (assuan_context_t ctx, char **args)
2213 struct client_s *client = assuan_get_pointer (ctx);
2214 xmlNodePtr n;
2215 xmlChar *a;
2216 gpg_error_t rc;
2217 struct xml_request_s *req;
2219 if (!args || !args[0] || !*args[0] || !args[1] || !*args[1])
2220 return GPG_ERR_SYNTAX;
2222 if (!xml_reserved_attribute (args[0]))
2223 n = xml_resolve_path (client, client->doc, (xmlChar *)args[1], NULL, &rc);
2224 else
2226 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
2227 if (rc)
2228 return rc;
2230 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2231 xml_free_request (req);
2234 if (rc)
2235 return rc;
2237 a = xmlGetProp (n, (xmlChar *) args[0]);
2238 if (!a)
2239 return GPG_ERR_NOT_FOUND;
2241 pthread_cleanup_push ((void *)xmlFree, a);
2243 if (*a)
2244 rc = xfer_data (ctx, (char *) a, xmlStrlen (a));
2245 else
2246 rc = GPG_ERR_NO_DATA;
2248 pthread_cleanup_pop (1);
2249 return rc;
2253 * args[0] - attribute
2254 * args[1] - element path
2255 * args[2] - value
2257 static gpg_error_t
2258 attribute_set (struct client_s *client, char **args)
2260 struct xml_request_s *req;
2261 gpg_error_t rc;
2262 xmlNodePtr n;
2264 if (!args || !args[0] || !args[1])
2265 return GPG_ERR_SYNTAX;
2268 * Reserved attribute names.
2270 if (!strcmp (args[0], "_name")) // Use the RENAME command instead
2271 return GPG_ERR_INV_ATTR;
2272 else if (!strcmp (args[0], "target"))
2273 return set_target_attribute (client, args + 1);
2274 else if (!xml_valid_attribute (args[0]))
2275 return GPG_ERR_INV_VALUE;
2277 if (!xml_valid_attribute_value (args[2]))
2278 return GPG_ERR_INV_VALUE;
2280 if (!xml_reserved_attribute (args[0]))
2282 n = xml_resolve_path (client, client->doc, (xmlChar *)args[1], NULL, &rc);
2283 if (!rc)
2285 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
2286 if (!rc)
2288 rc = xml_check_recursion (client, req);
2289 xml_free_request (req);
2293 else
2295 rc = xml_new_request (client, args[1], XML_CMD_ATTR, &req);
2296 if (rc)
2297 return rc;
2299 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
2300 xml_free_request (req);
2303 if (!rc)
2304 rc = xml_is_element_owner (client, n);
2306 if (!rc)
2307 rc = xml_add_attribute (client, n, args[0], args[2]);
2309 return rc;
2313 * req[0] - command
2314 * req[1] - attribute name or element path if command is LIST
2315 * req[2] - element path
2316 * req[2] - element path or value
2319 static gpg_error_t
2320 do_attr (assuan_context_t ctx, char *line)
2322 struct client_s *client = assuan_get_pointer (ctx);
2323 gpg_error_t rc = 0;
2324 char **req;
2326 req = str_split (line, " ", 4);
2327 if (!req || !req[0] || !req[1])
2329 strv_free (req);
2330 return GPG_ERR_SYNTAX;
2333 pthread_cleanup_push ((void *)req_free, req);
2335 if (strcasecmp (req[0], "SET") == 0)
2336 rc = attribute_set (client, req + 1);
2337 else if (strcasecmp (req[0], "GET") == 0)
2338 rc = attribute_get (ctx, req + 1);
2339 else if (strcasecmp (req[0], "DELETE") == 0)
2340 rc = attribute_delete (client, req + 1);
2341 else if (strcasecmp (req[0], "LIST") == 0)
2342 rc = attribute_list (ctx, req + 1);
2343 else
2344 rc = GPG_ERR_SYNTAX;
2346 client->flags &= ~(FLAG_ACL_IGNORE|FLAG_ACL_ERROR);
2347 pthread_cleanup_pop (1);
2348 return rc;
2351 static gpg_error_t
2352 attr_command (assuan_context_t ctx, char *line)
2354 struct client_s *client = assuan_get_pointer (ctx);
2355 gpg_error_t rc;
2356 struct argv_s *args[] = {
2357 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2358 NULL
2361 rc = parse_options (&line, args, client, 1);
2362 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2363 rc = GPG_ERR_SYNTAX;
2364 if (rc)
2365 return send_error (ctx, rc);
2367 if (client->opts & OPT_INQUIRE)
2369 unsigned char *result;
2370 size_t len;
2372 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2373 if (rc)
2374 return send_error (ctx, rc);
2376 pthread_cleanup_push ((void *)xfree, result);
2377 rc = do_attr (ctx, (char *)result);
2378 pthread_cleanup_pop (1);
2380 else
2381 rc = do_attr (ctx, line);
2383 return send_error (ctx, rc);
2386 static gpg_error_t
2387 parse_iscached_opt_lock (void *data, void *value)
2389 struct client_s *client = data;
2391 (void) value;
2392 client->opts |= OPT_LOCK;
2393 return 0;
2396 static gpg_error_t
2397 parse_iscached_opt_agent (void *data, void *value)
2399 struct client_s *client = data;
2401 (void) value;
2402 client->opts |= OPT_CACHE_AGENT;
2403 return 0;
2406 static gpg_error_t
2407 parse_iscached_opt_sign (void *data, void *value)
2409 struct client_s *client = data;
2411 (void) value;
2412 client->opts |= OPT_CACHE_SIGN;
2413 return 0;
2416 static gpg_error_t
2417 iscached_command (assuan_context_t ctx, char *line)
2419 struct client_s *client = assuan_get_pointer (ctx);
2420 gpg_error_t rc;
2421 int defer = 0;
2422 struct argv_s *args[] = {
2423 &(struct argv_s) {"lock", OPTION_TYPE_NOARG, parse_iscached_opt_lock},
2424 &(struct argv_s) {"agent", OPTION_TYPE_NOARG, parse_iscached_opt_agent},
2425 &(struct argv_s) {"sign", OPTION_TYPE_NOARG, parse_iscached_opt_sign},
2426 NULL
2429 if (!line || !*line)
2430 return send_error (ctx, GPG_ERR_SYNTAX);
2432 rc = parse_options (&line, args, client, 1);
2433 if (rc)
2434 return send_error (ctx, rc);
2435 else if (!valid_filename (line))
2436 return send_error (ctx, GPG_ERR_INV_VALUE);
2438 if (!(client->flags & FLAG_OPEN)
2439 && ((client->opts & OPT_CACHE_AGENT) || (client->opts & OPT_CACHE_SIGN)))
2440 return send_error (ctx, GPG_ERR_INV_STATE);
2442 rc = cache_iscached (line, &defer, (client->opts & OPT_CACHE_AGENT),
2443 (client->opts & OPT_CACHE_SIGN));
2444 if (!rc && defer)
2445 rc = GPG_ERR_NO_DATA;
2447 if (!rc)
2449 struct cache_data_s *cdata = cache_get_data (line);
2451 if (cdata)
2453 rc = validate_checksum (client, line, cdata, NULL, NULL);
2454 if (rc == GPG_ERR_CHECKSUM)
2455 rc = GPG_ERR_NO_DATA;
2459 if (client->opts & OPT_LOCK
2460 && (!rc || gpg_err_code (rc) == GPG_ERR_NO_DATA))
2462 gpg_error_t trc = rc;
2464 if (strcmp (line, client->filename))
2465 reset_client (client);
2467 xfree (client->filename);
2468 client->filename = str_dup (line);
2469 rc = do_lock (client, 1);
2470 if (!rc)
2471 rc = trc;
2474 return send_error (ctx, rc);
2477 static gpg_error_t
2478 clearcache_command (assuan_context_t ctx, char *line)
2480 struct client_s *client = assuan_get_pointer (ctx);
2481 gpg_error_t rc = 0, all_rc = 0;
2482 int i;
2483 int t;
2484 int all = 0;
2485 struct client_thread_s *once = NULL;
2486 unsigned count;
2488 cache_lock ();
2489 pthread_cleanup_push (cache_release_mutex, NULL);
2490 count = cache_file_count ();
2491 MUTEX_LOCK (&cn_mutex);
2492 pthread_cleanup_push ((void *)release_mutex_cb, &cn_mutex);
2494 if (!line || !*line)
2495 all = 1;
2497 t = slist_length (cn_thread_list);
2499 for (i = 0; i < t; i++)
2501 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
2502 assuan_peercred_t peer;
2504 if (!thd->cl)
2505 continue;
2507 /* Lock each connected clients' file mutex to prevent any other client
2508 * from accessing the cache entry (the file mutex is locked upon
2509 * command startup). The cache for the entry is not cleared if the
2510 * file mutex is locked by another client to prevent this function
2511 * from blocking. Rather, it returns an error.
2513 if (all)
2515 if (thd->cl->filename)
2517 rc = do_validate_peer (ctx, thd->cl->filename, &peer);
2518 /* The current client doesn't have permission to open the other
2519 * filename do to "access" configuration parameter in a filename
2520 * section. Since we are clearning all cache entries the error
2521 * will be returned later during cache_clear(). */
2522 if (rc)
2524 rc = 0;
2525 continue;
2528 else // Idle client without opened file?
2529 continue;
2531 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->filename, -1, 0, -1);
2532 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2534 /* The current client owns the lock. */
2535 if (pthread_equal (pthread_self (), thd->tid))
2536 rc = 0;
2537 else
2539 if (cache_iscached (thd->cl->filename, NULL, 0, 0)
2540 == GPG_ERR_NO_DATA)
2542 rc = 0;
2543 continue;
2546 /* The cache entry will be cleared when the other client
2547 * disconnects and cache_timer_thread() does its thing. */
2548 cache_defer_clear (thd->cl->filename);
2551 else if (gpg_err_code (rc) == GPG_ERR_NO_DATA)
2553 rc = 0;
2554 continue;
2557 if (!rc)
2559 rc = cache_clear (NULL, thd->cl->filename, 1);
2560 cache_unlock_mutex (thd->cl->filename, 0);
2563 if (rc)
2564 all_rc = rc;
2566 rc = 0;
2568 else
2570 /* A single data filename was specified. Lock only this data file
2571 * mutex and free the cache entry. */
2572 rc = do_validate_peer (ctx, line, &peer);
2573 if (rc == GPG_ERR_FORBIDDEN)
2574 rc = peer_is_invoker (client);
2576 if (rc == GPG_ERR_EACCES)
2577 rc = GPG_ERR_FORBIDDEN;
2579 if (!rc && thd->cl->filename && !strcmp (thd->cl->filename , line))
2581 rc = cache_lock_mutex (thd->cl->ctx, thd->cl->filename, -1, 0, -1);
2582 if (gpg_err_code (rc) == GPG_ERR_LOCKED)
2584 /* The current client owns the lock. */
2585 if (pthread_equal (pthread_self (), thd->tid))
2586 rc = 0;
2589 if (!rc)
2591 once = thd;
2592 rc = cache_clear (NULL, thd->cl->filename, 1);
2593 cache_unlock_mutex (thd->cl->filename, 0);
2595 else
2596 cache_defer_clear (thd->cl->filename);
2598 /* Found a client with the opened file. The cache entry has been
2599 * either cleared (self) or defered to be cleared. */
2600 break;
2605 /* Only connected clients' cache entries have been cleared. Now clear any
2606 * remaining cache entries without clients but only if there wasn't an
2607 * error from above since this would defeat the locking check of the
2608 * remaining entries. */
2609 if (all && !all_rc && cache_file_count ())
2611 rc = cache_clear (client, NULL, 1);
2612 if (rc == GPG_ERR_EACCES)
2613 rc = GPG_ERR_FORBIDDEN;
2616 /* No clients are using the specified file. */
2617 else if (!all_rc && !rc && !once)
2618 rc = cache_clear (NULL, line, 1);
2620 /* Release the connection mutex. */
2621 pthread_cleanup_pop (1);
2623 if (!rc || (cache_file_count () && count != cache_file_count ()))
2624 send_status_all (STATUS_CACHE, NULL);
2626 /* Release the cache mutex. */
2627 pthread_cleanup_pop (1);
2629 /* One or more files were locked while clearing all cache entries. */
2630 if (all_rc)
2631 rc = all_rc;
2633 return send_error (ctx, rc);
2636 static gpg_error_t
2637 cachetimeout_command (assuan_context_t ctx, char *line)
2639 struct client_s *client = assuan_get_pointer (ctx);
2640 int timeout;
2641 char **req = str_split (line, " ", 0);
2642 char *p;
2643 gpg_error_t rc = 0;
2644 assuan_peercred_t peer;
2646 if (!req || !*req || !req[1])
2648 strv_free (req);
2649 return send_error (ctx, GPG_ERR_SYNTAX);
2652 errno = 0;
2653 timeout = (int) strtol (req[1], &p, 10);
2654 if (errno != 0 || *p || timeout < -1)
2656 strv_free (req);
2657 return send_error (ctx, GPG_ERR_SYNTAX);
2660 rc = do_validate_peer (ctx, req[0], &peer);
2661 if (rc == GPG_ERR_FORBIDDEN)
2663 rc = peer_is_invoker (client);
2664 if (rc == GPG_ERR_EACCES)
2665 rc = GPG_ERR_FORBIDDEN;
2668 if (!rc)
2670 rc = cache_set_timeout (req[0], timeout);
2671 if (!rc || gpg_err_code (rc) == GPG_ERR_NOT_FOUND)
2673 rc = 0;
2674 MUTEX_LOCK (&rcfile_mutex);
2675 config_set_int_param (&global_config, req[0], "cache_timeout",
2676 req[1]);
2677 MUTEX_UNLOCK (&rcfile_mutex);
2681 strv_free (req);
2682 return send_error (ctx, rc);
2685 static gpg_error_t
2686 dump_command (assuan_context_t ctx, char *line)
2688 xmlChar *xml;
2689 int len;
2690 struct client_s *client = assuan_get_pointer (ctx);
2691 gpg_error_t rc;
2693 if (disable_list_and_dump == 1)
2694 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2696 if (line && *line)
2697 return send_error (ctx, GPG_ERR_SYNTAX);
2699 rc = peer_is_invoker(client);
2700 if (rc)
2701 return send_error (ctx, rc);
2703 xmlDocDumpFormatMemory (client->doc, &xml, &len, 1);
2705 if (!xml)
2707 log_write ("%s(%i): %s", __FILE__, __LINE__,
2708 pwmd_strerror (GPG_ERR_ENOMEM));
2709 return send_error (ctx, GPG_ERR_ENOMEM);
2712 pthread_cleanup_push ((void *)xmlFree, xml);
2713 rc = xfer_data (ctx, (char *) xml, len);
2714 pthread_cleanup_pop (1);
2715 return send_error (ctx, rc);
2718 static gpg_error_t
2719 getconfig_command (assuan_context_t ctx, char *line)
2721 struct client_s *client = assuan_get_pointer (ctx);
2722 gpg_error_t rc = 0;
2723 char filename[255] = { 0 }, param[747] = { 0 };
2724 char *p, *tmp = NULL, *fp = client->filename, *paramp = line;
2726 if (!line || !*line)
2727 return send_error (ctx, GPG_ERR_SYNTAX);
2729 if (strchr (line, ' '))
2731 int ret = sscanf (line, " %254[^ ] %746c", filename, param);
2733 if (ret <= 0)
2734 return send_error (ctx, gpg_error_from_syserror());
2735 paramp = param;
2736 fp = filename;
2739 if (fp && !valid_filename (fp))
2740 return send_error (ctx, GPG_ERR_INV_VALUE);
2742 paramp = str_down (paramp);
2743 p = config_get_value (fp ? fp : "global", paramp);
2744 if (!p)
2745 return send_error (ctx, GPG_ERR_UNKNOWN_OPTION);
2747 tmp = expand_homedir (p);
2748 xfree (p);
2749 if (!tmp)
2751 log_write ("%s(%i): %s", __FILE__, __LINE__,
2752 pwmd_strerror (GPG_ERR_ENOMEM));
2753 return send_error (ctx, GPG_ERR_ENOMEM);
2756 p = tmp;
2757 pthread_cleanup_push ((void *)xfree, p);
2758 rc = xfer_data (ctx, p, strlen (p));
2759 pthread_cleanup_pop (1);
2760 return send_error (ctx, rc);
2763 struct xpath_s
2765 xmlXPathContextPtr xp;
2766 xmlXPathObjectPtr result;
2767 xmlBufferPtr buf;
2768 char **req;
2771 static void
2772 xpath_command_free (void *arg)
2774 struct xpath_s *xpath = arg;
2776 if (!xpath)
2777 return;
2779 req_free (xpath->req);
2781 if (xpath->buf)
2782 xmlBufferFree (xpath->buf);
2784 if (xpath->result)
2785 xmlXPathFreeObject (xpath->result);
2787 if (xpath->xp)
2788 xmlXPathFreeContext (xpath->xp);
2791 static gpg_error_t
2792 do_xpath (assuan_context_t ctx, char *line)
2794 gpg_error_t rc;
2795 struct client_s *client = assuan_get_pointer (ctx);
2796 struct xpath_s _x = { 0 };
2797 struct xpath_s *xpath = &_x;
2799 if (!line || !*line)
2800 return GPG_ERR_SYNTAX;
2802 if ((xpath->req = str_split (line, "\t", 2)) == NULL)
2804 if (strv_printf (&xpath->req, "%s", line) == 0)
2805 return GPG_ERR_ENOMEM;
2808 xpath->xp = xmlXPathNewContext (client->doc);
2809 if (!xpath->xp)
2811 rc = GPG_ERR_BAD_DATA;
2812 goto fail;
2815 xpath->result =
2816 xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2817 if (!xpath->result)
2819 rc = GPG_ERR_BAD_DATA;
2820 goto fail;
2823 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2825 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2826 goto fail;
2829 rc = xml_recurse_xpath_nodeset (client, client->doc,
2830 xpath->result->nodesetval,
2831 (xmlChar *) xpath->req[1], &xpath->buf, 0,
2832 NULL);
2833 if (rc)
2834 goto fail;
2835 else if (!xpath->req[1] && !xmlBufferLength (xpath->buf))
2837 rc = GPG_ERR_NO_DATA;
2838 goto fail;
2840 else if (xpath->req[1])
2842 rc = 0;
2843 goto fail;
2846 pthread_cleanup_push ((void *)xpath_command_free, &xpath);
2847 rc = xfer_data (ctx, (char *) xmlBufferContent (xpath->buf),
2848 xmlBufferLength (xpath->buf));
2849 pthread_cleanup_pop (0);
2850 fail:
2851 xpath_command_free (xpath);
2852 return rc;
2855 static gpg_error_t
2856 xpath_command (assuan_context_t ctx, char *line)
2858 struct client_s *client = assuan_get_pointer (ctx);
2859 gpg_error_t rc;
2860 struct argv_s *args[] = {
2861 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2862 NULL
2865 if (disable_list_and_dump == 1)
2866 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2868 rc = peer_is_invoker(client);
2869 if (rc)
2870 return send_error (ctx, rc);
2872 rc = parse_options (&line, args, client, 1);
2873 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2874 rc = GPG_ERR_SYNTAX;
2875 if (rc)
2876 return send_error (ctx, rc);
2878 if (client->opts & OPT_INQUIRE)
2880 unsigned char *result;
2881 size_t len;
2883 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
2884 if (rc)
2885 return send_error (ctx, rc);
2887 pthread_cleanup_push ((void *)xfree, result);
2888 rc = do_xpath (ctx, (char *)result);
2889 pthread_cleanup_pop (1);
2891 else
2892 rc = do_xpath (ctx, line);
2894 return send_error (ctx, rc);
2897 static gpg_error_t
2898 do_xpathattr (assuan_context_t ctx, char *line)
2900 struct client_s *client = assuan_get_pointer (ctx);
2901 gpg_error_t rc;
2902 char **req = NULL;
2903 int cmd = 0; //SET
2904 struct xpath_s _x = { 0 };
2905 struct xpath_s *xpath = &_x;
2907 if (!line || !*line)
2908 return GPG_ERR_SYNTAX;
2910 if ((req = str_split (line, " ", 3)) == NULL)
2911 return GPG_ERR_ENOMEM;
2913 if (!req[0])
2915 rc = GPG_ERR_SYNTAX;
2916 goto fail;
2919 if (!strcasecmp (req[0], "SET"))
2920 cmd = 0;
2921 else if (!strcasecmp (req[0], "DELETE"))
2922 cmd = 1;
2923 else
2925 rc = GPG_ERR_SYNTAX;
2926 goto fail;
2929 if (!req[1] || !req[2])
2931 rc = GPG_ERR_SYNTAX;
2932 goto fail;
2935 if ((xpath->req = str_split (req[2], "\t", 3)) == NULL)
2937 rc = GPG_ERR_ENOMEM;
2938 goto fail;
2941 if (!xpath->req[0] || (!xpath->req[1] && !cmd) || (xpath->req[1] && cmd))
2943 rc = GPG_ERR_SYNTAX;
2944 goto fail;
2947 xpath->xp = xmlXPathNewContext (client->doc);
2948 if (!xpath->xp)
2950 rc = GPG_ERR_BAD_DATA;
2951 goto fail;
2954 xpath->result = xmlXPathEvalExpression ((xmlChar *) xpath->req[0], xpath->xp);
2955 if (!xpath->result)
2957 rc = GPG_ERR_BAD_DATA;
2958 goto fail;
2961 if (xmlXPathNodeSetIsEmpty (xpath->result->nodesetval))
2963 rc = GPG_ERR_ELEMENT_NOT_FOUND;
2964 goto fail;
2967 rc = xml_recurse_xpath_nodeset (client, client->doc,
2968 xpath->result->nodesetval,
2969 (xmlChar *) xpath->req[1], &xpath->buf, cmd,
2970 (xmlChar *) req[1]);
2972 fail:
2973 xpath_command_free (xpath);
2974 strv_free (req);
2975 return rc;
2978 /* XPATHATTR SET|DELETE <name> <expression>[<TAB>[value]] */
2979 static gpg_error_t
2980 xpathattr_command (assuan_context_t ctx, char *line)
2982 struct client_s *client = assuan_get_pointer (ctx);
2983 gpg_error_t rc;
2984 struct argv_s *args[] = {
2985 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
2986 NULL
2989 if (disable_list_and_dump == 1)
2990 return send_error (ctx, GPG_ERR_NOT_IMPLEMENTED);
2992 rc = peer_is_invoker(client);
2993 if (rc)
2994 return send_error (ctx, rc);
2996 rc = parse_options (&line, args, client, 1);
2997 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
2998 rc = GPG_ERR_SYNTAX;
2999 if (rc)
3000 return send_error (ctx, rc);
3002 if (client->opts & OPT_INQUIRE)
3004 unsigned char *result;
3005 size_t len;
3007 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3008 if (rc)
3009 return send_error (ctx, rc);
3011 pthread_cleanup_push ((void *)xfree, result);
3012 rc = do_xpathattr (ctx, (char *)result);
3013 pthread_cleanup_pop (1);
3015 else
3016 rc = do_xpathattr (ctx, line);
3018 return send_error (ctx, rc);
3021 static gpg_error_t
3022 do_import (struct client_s *client, const char *root_element,
3023 unsigned char *content)
3025 xmlDocPtr doc = NULL;
3026 xmlNodePtr n = NULL, root;
3027 gpg_error_t rc;
3028 struct string_s *str = NULL, *tstr = NULL;
3029 struct xml_request_s *req = NULL;
3031 if (!content || !*content)
3032 return GPG_ERR_SYNTAX;
3034 if (root_element)
3036 rc = xml_new_request (client, root_element, XML_CMD_STORE, &req);
3037 if (rc)
3039 xfree (content);
3040 return rc;
3043 if (!xml_valid_element_path (req->args, 0))
3045 xml_free_request (req);
3046 xfree (content);
3047 return GPG_ERR_INV_VALUE;
3051 str = string_new_content ((char *)content);
3052 tstr = string_prepend (str, "<pwmd>");
3053 if (tstr)
3055 str = tstr;
3056 tstr = string_append (str, "</pwmd>");
3057 if (!tstr)
3058 rc = GPG_ERR_ENOMEM;
3060 else
3061 rc = GPG_ERR_ENOMEM;
3063 if (rc)
3064 goto fail;
3066 doc = xmlReadDoc ((xmlChar *) str->str, NULL, "UTF-8", XML_PARSE_NOBLANKS);
3067 string_free (str, 1);
3068 if (!doc)
3070 rc = GPG_ERR_BAD_DATA;
3071 goto fail;
3074 root = xmlDocGetRootElement (doc);
3075 root = root->children;
3076 if (root->type != XML_ELEMENT_NODE)
3078 rc = GPG_ERR_BAD_DATA;
3079 goto fail;
3082 rc = xml_validate_import (client, root);
3083 if (rc)
3084 goto fail;
3086 if (req)
3088 /* Create the new specified root element path, if needed. */
3089 n = xml_find_elements (client, req, xmlDocGetRootElement (req->doc),
3090 &rc);
3091 if (rc)
3092 goto fail;
3094 /* Overwrite the children of the specified root element path. */
3095 (void)xml_unlink_node (client, n->children);
3096 n->children = NULL;
3098 else
3099 n = xmlDocGetRootElement (client->doc);
3101 if (n)
3103 xmlNodePtr copy;
3104 xmlChar *name = xml_attribute_value (root, (xmlChar *)"_name");
3106 if (!name)
3107 rc = GPG_ERR_BAD_DATA;
3108 else if (!req)
3110 /* No --root argument passed. Overwrite the current documents' root
3111 * element matching the root element of the imported data. */
3112 xml_free_request (req);
3113 req = NULL;
3114 rc = xml_new_request (client, (char *)name, XML_CMD_DELETE, &req);
3115 xmlFree (name);
3116 if (!rc)
3118 xmlNodePtr tmp;
3120 tmp = xml_find_elements (client, req,
3121 xmlDocGetRootElement (req->doc), &rc);
3122 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3123 goto fail;
3125 if (!rc)
3126 (void)xml_unlink_node (client, tmp);
3128 rc = 0;
3132 if (!rc)
3134 copy = xmlCopyNodeList (root);
3135 if (!copy)
3136 rc = GPG_ERR_ENOMEM;
3137 else
3139 n = xmlAddChildList (n, copy);
3140 if (!n)
3141 rc = GPG_ERR_ENOMEM;
3146 if (!rc && n && n->parent)
3147 rc = xml_update_element_mtime (client, n->parent);
3149 fail:
3150 xml_free_request (req);
3152 if (doc)
3153 xmlFreeDoc (doc);
3155 return rc;
3158 static gpg_error_t
3159 parse_import_opt_root (void *data, void *value)
3161 struct client_s *client = data;
3163 client->import_root = str_dup (value);
3164 return client->import_root ? 0 : GPG_ERR_ENOMEM;
3167 static gpg_error_t
3168 import_command (assuan_context_t ctx, char *line)
3170 gpg_error_t rc;
3171 struct client_s *client = assuan_get_pointer (ctx);
3172 unsigned char *result;
3173 size_t len;
3174 struct argv_s *args[] = {
3175 &(struct argv_s) {"root", OPTION_TYPE_ARG, parse_import_opt_root},
3176 NULL
3179 xfree (client->import_root);
3180 client->import_root = NULL;
3181 rc = parse_options (&line, args, client, 0);
3182 if (rc)
3183 return send_error (ctx, rc);
3185 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3186 if (rc)
3188 xfree (client->import_root);
3189 client->import_root = NULL;
3190 return send_error (ctx, rc);
3193 rc = do_import (client, client->import_root, result);
3194 xfree (client->import_root);
3195 client->import_root = NULL;
3196 return send_error (ctx, rc);
3199 static gpg_error_t
3200 do_lock (struct client_s *client, int add)
3202 gpg_error_t rc = lock_file_mutex (client, add);
3204 if (!rc)
3205 client->flags |= FLAG_LOCK_CMD;
3207 return rc;
3210 static gpg_error_t
3211 lock_command (assuan_context_t ctx, char *line)
3213 struct client_s *client = assuan_get_pointer (ctx);
3214 gpg_error_t rc;
3216 if (line && *line)
3217 return send_error (ctx, GPG_ERR_SYNTAX);
3219 rc = do_lock (client, 0);
3220 return send_error (ctx, rc);
3223 static gpg_error_t
3224 unlock_command (assuan_context_t ctx, char *line)
3226 struct client_s *client = assuan_get_pointer (ctx);
3227 gpg_error_t rc;
3229 if (line && *line)
3230 return send_error (ctx, GPG_ERR_SYNTAX);
3232 rc = unlock_file_mutex (client, 0);
3233 return send_error (ctx, rc);
3236 static void
3237 get_set_env (const char *name, const char *value)
3239 if (value && *value)
3240 setenv (name, value, 1);
3241 else
3242 unsetenv (name);
3245 static gpg_error_t
3246 option_command (assuan_context_t ctx, char *line)
3248 struct client_s *client = assuan_get_pointer (ctx);
3249 gpg_error_t rc = 0;
3250 char namebuf[255] = { 0 };
3251 char *name = namebuf;
3252 char *value = NULL, *p, *tmp = NULL;
3254 p = strchr (line, '=');
3255 if (!p)
3257 strncpy (namebuf, line, sizeof(namebuf));
3258 namebuf[sizeof(namebuf)-1] = 0;
3260 else
3262 strncpy (namebuf, line, strlen (line)-strlen (p));
3263 namebuf[sizeof(namebuf)-1] = 0;
3264 value = p+1;
3267 log_write2 ("OPTION name='%s' value='%s'", name, value);
3269 if (strcasecmp (name, (char *) "lock-timeout") == 0)
3271 long n = 0;
3273 if (value)
3275 n = strtol (value, &tmp, 10);
3276 if (tmp && *tmp)
3277 return send_error (ctx, GPG_ERR_INV_VALUE);
3280 client->lock_timeout = n;
3282 else if (strcasecmp (name, (char *) "client-state") == 0)
3284 long n = 0;
3286 if (value)
3288 n = strtol (value, &tmp, 10);
3289 if ((tmp && *tmp) || (n < 0 || n > 1))
3290 return send_error (ctx, GPG_ERR_INV_VALUE);
3291 client->client_state = n;
3293 else
3294 client->client_state = 0;
3296 else if (strcasecmp (name, (char *) "NAME") == 0)
3298 if (value && strchr (value, ' '))
3299 rc = GPG_ERR_INV_VALUE;
3300 else
3302 tmp = pthread_getspecific (thread_name_key);
3303 pthread_setspecific (thread_name_key, NULL);
3304 xfree (tmp);
3306 MUTEX_LOCK (&cn_mutex);
3307 xfree (client->thd->name);
3308 client->thd->name = NULL;
3309 if (value && *value)
3311 pthread_setspecific (thread_name_key, str_dup (value));
3312 client->thd->name = str_dup (value);
3314 MUTEX_UNLOCK (&cn_mutex);
3317 else if (strcasecmp (name, "disable-pinentry") == 0)
3319 int n = 1;
3321 if (value && *value)
3323 n = (int) strtol (value, &tmp, 10);
3324 if (*tmp || n < 0 || n > 1)
3325 return send_error (ctx, GPG_ERR_INV_VALUE);
3328 if (n)
3329 client->flags |= FLAG_NO_PINENTRY;
3330 else
3331 client->flags &= ~FLAG_NO_PINENTRY;
3333 else if (strcasecmp (name, "ttyname") == 0)
3335 get_set_env ("GPG_TTY", value);
3337 else if (strcasecmp (name, "ttytype") == 0)
3339 get_set_env ("TERM", value);
3341 else if (strcasecmp (name, "display") == 0)
3343 get_set_env ("DISPLAY", value);
3345 else if (strcasecmp (name, "lc_messages") == 0)
3348 else if (strcasecmp (name, "lc_ctype") == 0)
3351 else if (strcasecmp (name, "desc") == 0)
3354 else if (strcasecmp (name, "pinentry-timeout") == 0)
3357 else
3358 rc = GPG_ERR_UNKNOWN_OPTION;
3360 return send_error (ctx, rc);
3363 static gpg_error_t
3364 do_rename (assuan_context_t ctx, char *line)
3366 struct client_s *client = assuan_get_pointer (ctx);
3367 char **args, *p;
3368 xmlNodePtr src, dst;
3369 struct string_s *str = NULL, *tstr;
3370 struct xml_request_s *req;
3371 gpg_error_t rc;
3373 args = str_split (line, " ", 0);
3374 if (!args || strv_length (args) != 2)
3376 strv_free (args);
3377 return GPG_ERR_SYNTAX;
3380 if (!xml_valid_element ((xmlChar *) args[1]))
3382 strv_free (args);
3383 return GPG_ERR_INV_VALUE;
3386 rc = xml_new_request (client, args[0], XML_CMD_RENAME, &req);
3387 if (rc)
3389 strv_free (args);
3390 return rc;
3393 src = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3394 if (rc)
3395 goto fail;
3397 rc = xml_is_element_owner (client, src);
3398 if (rc)
3399 goto fail;
3401 xmlChar *a = xmlGetProp (src, (xmlChar *) "_name");
3402 if (!a)
3404 rc = GPG_ERR_ENOMEM;
3405 goto fail;
3408 /* To prevent unwanted effects:
3410 * <element _name="a"><element _name="b"/></element>
3412 * RENAME a<TAB>b b
3414 if (xmlStrEqual (a, (xmlChar *) args[1]))
3416 xmlFree (a);
3417 rc = GPG_ERR_EEXIST;
3418 goto fail;
3421 xmlFree (a);
3422 str = string_new (args[0]);
3423 if (!str)
3425 rc = GPG_ERR_ENOMEM;
3426 goto fail;
3429 p = strrchr (str->str, '\t');
3430 if (p)
3431 tstr = string_truncate (str, strlen (str->str)-strlen (p));
3432 else
3433 tstr = string_truncate (str, 0);
3435 if (!tstr)
3437 string_free (str, 1);
3438 rc = GPG_ERR_ENOMEM;
3439 goto fail;
3442 str = tstr;
3443 tstr = string_append_printf (str, "%s%s", str->len ? "\t" : "", args[1]);
3444 if (!tstr)
3446 string_free (str, 1);
3447 rc = GPG_ERR_ENOMEM;
3448 goto fail;
3451 str = tstr;
3452 xml_free_request (req);
3453 rc = xml_new_request (client, str->str, XML_CMD_RENAME, &req);
3454 string_free (str, 1);
3455 if (rc)
3457 req = NULL;
3458 goto fail;
3461 dst = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3462 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3463 goto fail;
3465 rc = 0;
3467 /* Target may exist:
3469 * <element _name="a"/>
3470 * <element _name="b" target="a"/>
3472 * RENAME b a
3474 if (src == dst)
3476 rc = GPG_ERR_EEXIST;
3477 goto fail;
3480 if (dst)
3482 rc = xml_is_element_owner (client, dst);
3483 if (rc)
3484 goto fail;
3486 rc = xml_add_attribute (client, src, "_name", args[1]);
3487 if (!rc)
3488 xml_unlink_node (client, dst);
3490 else
3491 rc = xml_add_attribute (client, src, "_name", args[1]);
3493 fail:
3494 xml_free_request (req);
3495 strv_free (args);
3496 return rc;
3499 static gpg_error_t
3500 rename_command (assuan_context_t ctx, char *line)
3502 struct client_s *client = assuan_get_pointer (ctx);
3503 gpg_error_t rc;
3504 struct argv_s *args[] = {
3505 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3506 NULL
3509 rc = parse_options (&line, args, client, 1);
3510 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3511 rc = GPG_ERR_SYNTAX;
3512 if (rc)
3513 return send_error (ctx, rc);
3515 if (client->opts & OPT_INQUIRE)
3517 unsigned char *result;
3518 size_t len;
3520 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3521 if (rc)
3522 return send_error (ctx, rc);
3524 pthread_cleanup_push ((void *)xfree, result);
3525 rc = do_rename (ctx, (char *)result);
3526 pthread_cleanup_pop (1);
3528 else
3529 rc = do_rename (ctx, line);
3531 return send_error (ctx, rc);
3534 static gpg_error_t
3535 do_copy (assuan_context_t ctx, char *line)
3537 struct client_s *client = assuan_get_pointer (ctx);
3538 char **args, **targs;
3539 xmlNodePtr src, dst, tree = NULL;
3540 struct xml_request_s *req;
3541 gpg_error_t rc;
3543 args = str_split (line, " ", 0);
3544 if (!args || strv_length (args) != 2)
3546 strv_free (args);
3547 return GPG_ERR_SYNTAX;
3550 targs = str_split (args[1], "\t", 0);
3551 if (!targs)
3553 strv_free (args);
3554 return GPG_ERR_SYNTAX;
3557 if (!xml_valid_element_path (targs, 0))
3559 strv_free (args);
3560 strv_free (targs);
3561 return GPG_ERR_INV_VALUE;
3563 strv_free (targs);
3565 rc = xml_new_request (client, args[0], XML_CMD_NONE, &req);
3566 if (rc)
3568 strv_free (args);
3569 return rc;
3572 src = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3573 if (rc)
3574 goto fail;
3576 tree = xmlCopyNodeList (src);
3577 if (!tree)
3579 rc = GPG_ERR_ENOMEM;
3580 goto fail;
3583 xml_free_request (req);
3584 /* Create the destination element path if it does not exist. */
3585 rc = xml_new_request (client, args[1], XML_CMD_STORE, &req);
3586 if (rc)
3588 req = NULL;
3589 goto fail;
3592 dst = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3593 if (rc)
3594 goto fail;
3596 rc = xml_is_element_owner (client, dst);
3597 if (rc)
3598 goto fail;
3600 rc = xml_validate_target (client, req->doc, args[1], src);
3601 if (rc || src == dst)
3603 rc = rc ? rc : GPG_ERR_EEXIST;
3604 goto fail;
3607 /* Merge any attributes from the src node to the initial dst node. */
3608 for (xmlAttrPtr attr = tree->properties; attr; attr = attr->next)
3610 if (xmlStrEqual (attr->name, (xmlChar *) "_name"))
3611 continue;
3613 xmlAttrPtr a = xmlHasProp (dst, attr->name);
3614 if (a)
3615 xmlRemoveProp (a);
3617 xmlChar *tmp = xmlNodeGetContent (attr->children);
3618 xmlNewProp (dst, attr->name, tmp);
3619 xmlFree (tmp);
3620 /* Create the default attributes. */
3621 rc = xml_add_attribute (client, dst, NULL, NULL);
3624 xmlNodePtr n = dst->children;
3625 (void)xml_unlink_node (client, n);
3626 dst->children = NULL;
3628 if (tree->children)
3630 n = xmlCopyNodeList (tree->children);
3631 if (!n)
3633 rc = GPG_ERR_ENOMEM;
3634 goto fail;
3637 n = xmlAddChildList (dst, n);
3638 if (!n)
3640 rc = GPG_ERR_ENOMEM;
3641 goto fail;
3644 rc = xml_update_element_mtime (client, xmlDocGetRootElement (client->doc)
3645 == dst->parent ? dst : dst->parent);
3648 fail:
3649 if (tree)
3650 (void)xml_unlink_node (client, tree);
3652 xml_free_request (req);
3653 strv_free (args);
3654 return rc;
3657 static gpg_error_t
3658 copy_command (assuan_context_t ctx, char *line)
3660 struct client_s *client = assuan_get_pointer (ctx);
3661 gpg_error_t rc;
3662 struct argv_s *args[] = {
3663 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3664 NULL
3667 rc = parse_options (&line, args, client, 1);
3668 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3669 rc = GPG_ERR_SYNTAX;
3670 if (rc)
3671 return send_error (ctx, rc);
3673 if (client->opts & OPT_INQUIRE)
3675 unsigned char *result;
3676 size_t len;
3678 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3679 if (rc)
3680 return send_error (ctx, rc);
3682 pthread_cleanup_push ((void *)xfree, result);
3683 rc = do_copy (ctx, (char *)result);
3684 pthread_cleanup_pop (1);
3686 else
3687 rc = do_copy (ctx, line);
3689 return send_error (ctx, rc);
3692 static gpg_error_t
3693 do_move (assuan_context_t ctx, char *line)
3695 struct client_s *client = assuan_get_pointer (ctx);
3696 char **args;
3697 xmlNodePtr src, dst;
3698 struct xml_request_s *req;
3699 gpg_error_t rc;
3701 args = str_split (line, " ", 0);
3702 if (!args || strv_length (args) != 2)
3704 strv_free (args);
3705 return GPG_ERR_SYNTAX;
3708 if (*args[1])
3710 char **targs = str_split (args[1], "\t", 0);
3711 if (!targs)
3713 strv_free (args);
3714 return GPG_ERR_ENOMEM;
3717 if (!xml_valid_element_path (targs, 0))
3719 strv_free (targs);
3720 strv_free (args);
3721 return GPG_ERR_INV_VALUE;
3724 strv_free (targs);
3727 rc = xml_new_request (client, args[0], XML_CMD_MOVE, &req);
3728 if (rc)
3730 strv_free (args);
3731 return rc;
3734 src = xml_find_elements (client, req, xmlDocGetRootElement (req->doc), &rc);
3735 if (rc)
3736 goto fail;
3738 rc = xml_is_element_owner (client, src);
3739 if (rc)
3740 goto fail;
3742 xml_free_request (req);
3743 req = NULL;
3744 if (*args[1])
3746 rc = xml_new_request (client, args[1], XML_CMD_NONE, &req);
3747 if (rc)
3748 goto fail;
3750 dst = xml_find_elements (client, req, xmlDocGetRootElement (req->doc),
3751 &rc);
3753 else
3754 dst = xmlDocGetRootElement (client->doc);
3756 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3757 goto fail;
3759 rc = 0;
3761 for (xmlNodePtr n = dst; n; n = n->parent)
3763 if (n == src)
3765 rc = GPG_ERR_EEXIST;
3766 goto fail;
3770 if (dst)
3772 xmlChar *a = xml_attribute_value (src, (xmlChar *) "_name");
3773 xmlNodePtr dup = xml_find_element (client, dst->children, (char *) a, &rc);
3775 xmlFree (a);
3776 if (rc && rc != GPG_ERR_ELEMENT_NOT_FOUND)
3777 goto fail;
3779 rc = 0;
3781 if (dup)
3783 if (dup == src)
3785 rc = GPG_ERR_EEXIST;
3786 goto fail;
3789 if (dst == xmlDocGetRootElement (client->doc))
3791 xmlNodePtr n = src;
3792 int match = 0;
3794 while (n->parent && n->parent != dst)
3795 n = n->parent;
3797 a = xml_attribute_value (n, (xmlChar *) "_name");
3798 xmlChar *b = xml_attribute_value (src, (xmlChar *) "_name");
3800 if (xmlStrEqual (a, b))
3802 match = 1;
3803 xmlUnlinkNode (src);
3804 (void)xml_unlink_node (client, n);
3807 xmlFree (a);
3808 xmlFree (b);
3810 if (!match)
3811 (void)xml_unlink_node (client, dup);
3813 else
3814 xmlUnlinkNode (dup);
3818 if (!dst && *req->args)
3820 struct xml_request_s *nreq = NULL;
3821 xmlChar *name = xml_attribute_value (src, (xmlChar *) "_name");
3823 if (src->parent == xmlDocGetRootElement (client->doc)
3824 && !strcmp ((char *) name, *req->args))
3826 xmlFree (name);
3827 rc = GPG_ERR_EEXIST;
3828 goto fail;
3831 xmlFree (name);
3832 rc = xml_new_request (client, args[1], XML_CMD_STORE, &nreq);
3833 if (!rc)
3835 dst = xml_find_elements (client, nreq,
3836 xmlDocGetRootElement (nreq->doc), &rc);
3837 xml_free_request (nreq);
3840 if (rc)
3841 goto fail;
3844 xml_update_element_mtime (client, src->parent);
3845 xmlUnlinkNode (src);
3847 dst = xmlAddChildList (dst, src);
3848 if (!dst)
3849 rc = GPG_ERR_ENOMEM;
3850 else
3851 xml_update_element_mtime (client, dst->parent);
3853 fail:
3854 xml_free_request (req);
3855 strv_free (args);
3856 return rc;
3859 static gpg_error_t
3860 move_command (assuan_context_t ctx, char *line)
3862 struct client_s *client = assuan_get_pointer (ctx);
3863 gpg_error_t rc;
3864 struct argv_s *args[] = {
3865 &(struct argv_s) {"inquire", OPTION_TYPE_NOARG, parse_opt_inquire},
3866 NULL
3869 rc = parse_options (&line, args, client, 1);
3870 if (!rc && (client->opts & OPT_INQUIRE) && line && *line)
3871 rc = GPG_ERR_SYNTAX;
3872 if (rc)
3873 return send_error (ctx, rc);
3875 if (client->opts & OPT_INQUIRE)
3877 unsigned char *result;
3878 size_t len;
3880 rc = assuan_inquire (ctx, "DATA", &result, &len, 0);
3881 if (rc)
3882 return send_error (ctx, rc);
3884 pthread_cleanup_push ((void *)xfree, result);
3885 rc = do_move (ctx, (char *)result);
3886 pthread_cleanup_pop (1);
3888 else
3889 rc = do_move (ctx, line);
3891 return send_error (ctx, rc);
3894 static gpg_error_t
3895 ls_command (assuan_context_t ctx, char *line)
3897 gpg_error_t rc;
3898 char *tmp;
3899 char *dir;
3900 DIR *d;
3901 char *list = NULL;
3902 #ifdef HAVE_READDIR_R
3903 size_t len;
3904 struct dirent *cur = NULL, *p;
3905 #else
3906 struct dirent *cur = NULL;
3907 #endif
3909 if (line && *line)
3910 return send_error (ctx, GPG_ERR_SYNTAX);
3912 tmp = str_asprintf ("%s/data", homedir);
3913 dir = expand_homedir (tmp);
3914 xfree (tmp);
3915 if (!dir)
3916 return send_error (ctx, GPG_ERR_ENOMEM);
3918 d = opendir (dir);
3919 rc = gpg_error_from_errno (errno);
3921 if (!d)
3923 xfree (dir);
3924 return send_error (ctx, rc);
3927 #ifdef HAVE_READDIR_R
3928 len = offsetof (struct dirent, d_name) + pathconf (dir, _PC_NAME_MAX) + 1;
3929 p = xmalloc (len);
3930 if (!p)
3932 xfree (dir);
3933 closedir (d);
3934 return send_error (ctx, GPG_ERR_ENOMEM);
3936 pthread_cleanup_push (xfree, p);
3937 #endif
3939 pthread_cleanup_push ((void *)closedir, d);
3940 xfree (dir);
3941 rc = 0;
3943 #ifdef HAVE_READDIR_R
3944 while (!readdir_r (d, p, &cur) && cur)
3945 #else
3946 while ((cur = readdir (d)))
3947 #endif
3949 rc = open_check_file (cur->d_name, NULL, NULL, 1);
3950 if (rc)
3951 continue;
3953 tmp = str_asprintf ("%s%s\n", list ? list : "", cur->d_name);
3954 if (!tmp)
3956 if (list)
3957 xfree (list);
3959 rc = GPG_ERR_ENOMEM;
3960 break;
3963 xfree (list);
3964 list = tmp;
3967 pthread_cleanup_pop (1); // closedir (d)
3968 #ifdef HAVE_READDIR_R
3969 pthread_cleanup_pop (1); // xfree (p)
3970 #endif
3972 if (rc)
3973 return send_error (ctx, rc);
3975 if (!list)
3976 return send_error (ctx, GPG_ERR_NO_DATA);
3978 list[strlen (list) - 1] = 0;
3979 pthread_cleanup_push (xfree, list);
3980 rc = xfer_data (ctx, list, strlen (list));
3981 pthread_cleanup_pop (1);
3982 return send_error (ctx, rc);
3985 static gpg_error_t
3986 bye_notify (assuan_context_t ctx, char *line)
3988 struct client_s *cl = assuan_get_pointer (ctx);
3989 gpg_error_t ret = 0;
3991 (void)line;
3992 update_client_state (cl, CLIENT_STATE_DISCON);
3994 #ifdef WITH_GNUTLS
3995 cl->disco = 1;
3996 if (cl->thd->remote)
3998 int rc;
4002 struct timeval tv = { 0, 50000 };
4004 rc = gnutls_bye (cl->thd->tls->ses, GNUTLS_SHUT_RDWR);
4005 if (rc == GNUTLS_E_AGAIN)
4006 select (0, NULL, NULL, NULL, &tv);
4008 while (rc == GNUTLS_E_AGAIN);
4010 #endif
4012 /* This will let assuan_process_next() return. */
4013 if (fcntl (cl->thd->fd, F_SETFL, O_NONBLOCK) == -1)
4015 cl->last_rc = gpg_error_from_errno (errno);
4016 ret = cl->last_rc;
4019 cl->last_rc = 0; // BYE command result
4020 return ret;
4023 static gpg_error_t
4024 reset_notify (assuan_context_t ctx, char *line)
4026 struct client_s *client = assuan_get_pointer (ctx);
4028 (void)line;
4029 if (client)
4030 reset_client (client);
4032 return 0;
4036 * This is called before every Assuan command.
4038 static gpg_error_t
4039 command_startup (assuan_context_t ctx, const char *name)
4041 struct client_s *client = assuan_get_pointer (ctx);
4042 gpg_error_t rc;
4043 struct command_table_s *cmd = NULL;
4045 log_write2 ("command='%s'", name);
4046 client->last_rc = client->opts = 0;
4048 for (int i = 0; command_table[i]; i++)
4050 if (!strcasecmp (name, command_table[i]->name))
4052 if (command_table[i]->ignore_startup)
4053 return 0;
4054 cmd = command_table[i];
4055 break;
4059 if (!cmd)
4060 return GPG_ERR_UNKNOWN_COMMAND;
4062 client->last_rc = rc = gpg_error (file_modified (client, cmd));
4063 if (!rc)
4064 update_client_state (client, CLIENT_STATE_COMMAND);
4066 return rc;
4070 * This is called after every Assuan command.
4072 static void
4073 command_finalize (assuan_context_t ctx, gpg_error_t rc)
4075 struct client_s *client = assuan_get_pointer (ctx);
4077 if (!(client->flags & FLAG_LOCK_CMD))
4078 unlock_file_mutex (client, 0);
4080 unlock_flock (&client->flock_fd);
4081 log_write2 (_("command completed: rc=%u"), rc ? rc : client->last_rc);
4082 client->last_rc = gpg_error (GPG_ERR_UNKNOWN_COMMAND);
4083 #ifdef WITH_GNUTLS
4084 client->thd->buffer_timeout = client->thd->last_buffer_size = 0;
4085 #endif
4086 if (client->thd->state != CLIENT_STATE_DISCON)
4087 update_client_state (client, CLIENT_STATE_IDLE);
4090 static gpg_error_t
4091 parse_help_opt_html (void *data, void *value)
4093 struct client_s *client = data;
4095 (void) value;
4096 client->opts |= OPT_HTML;
4097 return 0;
4100 static gpg_error_t
4101 help_command (assuan_context_t ctx, char *line)
4103 gpg_error_t rc;
4104 int i;
4105 struct client_s *client = assuan_get_pointer (ctx);
4106 struct argv_s *args[] = {
4107 &(struct argv_s) {"html", OPTION_TYPE_NOARG, parse_help_opt_html},
4108 NULL
4111 rc = parse_options (&line, args, client, 1);
4112 if (rc)
4113 return send_error (ctx, rc);
4115 if (!line || !*line)
4117 char *tmp;
4118 char *help = str_dup (_("Usage: HELP [--html] [<COMMAND>]\n"
4119 "For commands that take an element path as an argument, each element is "
4120 "separated with an ASCII @key{TAB} character (ASCII 0x09)."
4121 "@*@*COMMANDS:"));
4123 for (i = 0; command_table[i]; i++)
4125 if (!command_table[i]->help)
4126 continue;
4128 /* @npxref{} won't put a "See " or "see " in front of the command.
4129 * It's not a texinfo command but needed for --html. */
4130 tmp = str_asprintf ("%s %s%s%s", help,
4131 client->opts & OPT_HTML ? "@npxref{" : "",
4132 command_table[i]->name,
4133 client->opts & OPT_HTML ? "}" : "");
4134 xfree (help);
4135 help = tmp;
4138 tmp = strip_texi_and_wrap (help, client->opts & OPT_HTML);
4139 xfree (help);
4140 pthread_cleanup_push ((void *)xfree, tmp);
4141 rc = xfer_data (ctx, tmp, strlen (tmp));
4142 pthread_cleanup_pop (1);
4143 return send_error (ctx, rc);
4146 for (i = 0; command_table[i]; i++)
4148 if (!strcasecmp (line, command_table[i]->name))
4150 char *help, *tmp;
4152 if (!command_table[i]->help)
4153 break;
4155 help = strip_texi_and_wrap (command_table[i]->help,
4156 client->opts & OPT_HTML);
4157 tmp = str_asprintf ("%s%s",
4158 (client->opts & OPT_HTML) ? "" : _("Usage: "),
4159 help);
4160 xfree (help);
4161 pthread_cleanup_push ((void *)xfree, tmp);
4162 rc = xfer_data (ctx, tmp, strlen (tmp));
4163 pthread_cleanup_pop (1);
4164 return send_error (ctx, rc);
4168 return send_error (ctx, GPG_ERR_INV_NAME);
4171 static void
4172 new_command (const char *name, int ignore, int unlock, int flock_type,
4173 gpg_error_t (*handler) (assuan_context_t, char *),
4174 const char *help)
4176 int i = 0;
4177 struct command_table_s **tmp;
4179 if (command_table)
4180 for (i = 0; command_table[i]; i++);
4182 tmp = xrealloc (command_table, (i + 2) * sizeof (struct command_table_s *));
4183 assert (tmp);
4184 command_table = tmp;
4185 command_table[i] = xcalloc (1, sizeof (struct command_table_s));
4186 command_table[i]->name = name;
4187 command_table[i]->handler = handler;
4188 command_table[i]->ignore_startup = ignore;
4189 command_table[i]->unlock = unlock;
4190 command_table[i]->flock_type = flock_type;
4191 command_table[i++]->help = help;
4192 command_table[i] = NULL;
4195 void
4196 deinit_commands ()
4198 int i;
4200 for (i = 0; command_table[i]; i++)
4201 xfree (command_table[i]);
4203 xfree (command_table);
4206 static int
4207 sort_commands (const void *arg1, const void *arg2)
4209 struct command_table_s *const *a = arg1;
4210 struct command_table_s *const *b = arg2;
4212 if (!*a || !*b)
4213 return 0;
4214 else if (*a && !*b)
4215 return 1;
4216 else if (!*a && *b)
4217 return -1;
4219 return strcmp ((*a)->name, (*b)->name);
4222 static gpg_error_t
4223 passwd_command (assuan_context_t ctx, char *line)
4225 struct client_s *client = assuan_get_pointer (ctx);
4226 gpg_error_t rc;
4228 (void)line;
4229 rc = peer_is_invoker (client);
4230 if (rc == GPG_ERR_EACCES)
4231 return send_error (ctx, GPG_ERR_FORBIDDEN);
4232 else if (rc)
4233 return send_error (ctx, rc);
4235 if (client->flags & FLAG_NEW)
4236 return send_error (ctx, GPG_ERR_INV_STATE);
4238 client->crypto->keyfile = config_get_string (client->filename,
4239 "passphrase_file");
4240 rc = crypto_init_ctx (client->crypto, client->flags & FLAG_NO_PINENTRY,
4241 client->crypto->keyfile);
4242 if (rc)
4243 return send_error (ctx, rc);
4245 if (!rc)
4246 rc = crypto_passwd (client, client->crypto);
4248 crypto_free_non_keys (client->crypto);
4249 return send_error (ctx, rc);
4252 static gpg_error_t
4253 parse_opt_data (void *data, void *value)
4255 struct client_s *client = data;
4257 (void) value;
4258 client->opts |= OPT_DATA;
4259 return 0;
4262 static gpg_error_t
4263 send_client_list (assuan_context_t ctx)
4265 struct client_s *client = assuan_get_pointer (ctx);
4266 gpg_error_t rc = 0;
4268 if (client->opts & OPT_VERBOSE)
4270 unsigned i, t;
4271 char **list = NULL;
4272 char *line;
4274 MUTEX_LOCK (&cn_mutex);
4275 pthread_cleanup_push ((void *)release_mutex_cb, &cn_mutex);
4276 t = slist_length (cn_thread_list);
4278 for (i = 0; i < t; i++)
4280 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
4281 char *tmp;
4283 if (thd->state == CLIENT_STATE_UNKNOWN)
4284 continue;
4286 tmp = build_client_info_line (thd, 0);
4287 if (tmp)
4289 char **l = strv_cat (list, tmp);
4290 if (!l)
4291 rc = GPG_ERR_ENOMEM;
4292 else
4293 list = l;
4295 else
4296 rc = GPG_ERR_ENOMEM;
4298 if (rc)
4300 strv_free (list);
4301 break;
4305 pthread_cleanup_pop (1);
4306 if (rc)
4307 return rc;
4309 line = strv_join ("\n", list);
4310 strv_free (list);
4311 pthread_cleanup_push ((void *)xfree, line);
4312 rc = xfer_data (ctx, line, strlen (line));
4313 pthread_cleanup_pop (1);
4314 return rc;
4317 if (client->opts & OPT_DATA)
4319 char buf[ASSUAN_LINELENGTH];
4321 MUTEX_LOCK (&cn_mutex);
4322 snprintf (buf, sizeof (buf), "%u", slist_length (cn_thread_list));
4323 MUTEX_UNLOCK (&cn_mutex);
4324 rc = xfer_data (ctx, buf, strlen (buf));
4326 else
4327 rc = send_status (ctx, STATUS_CLIENTS, NULL);
4329 return rc;
4332 static gpg_error_t
4333 getinfo_command (assuan_context_t ctx, char *line)
4335 struct client_s *client = assuan_get_pointer (ctx);
4336 gpg_error_t rc;
4337 char buf[ASSUAN_LINELENGTH];
4338 struct argv_s *args[] = {
4339 &(struct argv_s) {"data", OPTION_TYPE_NOARG, parse_opt_data},
4340 &(struct argv_s) {"verbose", OPTION_TYPE_NOARG, parse_opt_verbose},
4341 NULL
4344 rc = parse_options (&line, args, client, 1);
4345 if (rc)
4346 return send_error (ctx, rc);
4348 if (!strcasecmp (line, "clients"))
4350 rc = send_client_list (ctx);
4352 else if (!strcasecmp (line, "cache"))
4354 if (client->opts & OPT_DATA)
4356 snprintf (buf, sizeof (buf), "%u", cache_file_count ());
4357 rc = xfer_data (ctx, buf, strlen (buf));
4359 else
4360 rc = send_status (ctx, STATUS_CACHE, NULL);
4362 else if (!strcasecmp (line, "pid"))
4364 pid_t pid = getpid ();
4366 snprintf (buf, sizeof (buf), "%u", pid);
4367 rc = xfer_data (ctx, buf, strlen (buf));
4369 else if (!strcasecmp (line, "version"))
4371 char *tmp = str_asprintf ("0x%06x %s", VERSION_HEX,
4372 #ifdef WITH_GNUTLS
4373 "GNUTLS "
4374 #endif
4375 #ifdef WITH_LIBACL
4376 "ACL "
4377 #endif
4378 "");
4379 pthread_cleanup_push (xfree, tmp);
4380 rc = xfer_data (ctx, tmp, strlen (tmp));
4381 pthread_cleanup_pop (1);
4383 else if (!strcasecmp (line, "last_error"))
4385 if (client->last_error)
4386 rc = xfer_data (ctx, client->last_error, strlen (client->last_error));
4387 else
4388 rc = GPG_ERR_NO_DATA;
4390 else if (!strcasecmp (line, "user"))
4392 char *user = NULL;
4394 #ifdef WITH_GNUTLS
4395 if (client->thd->remote)
4396 user = str_asprintf ("#%s", client->thd->tls->fp);
4397 else
4398 user = get_username (client->thd->peer->uid);
4399 #else
4400 user = get_username (client->thd->peer->uid);
4401 #endif
4402 if (user)
4404 pthread_cleanup_push ((void *)xfree, user);
4405 rc = xfer_data (ctx, user, strlen (user));
4406 pthread_cleanup_pop (1);
4408 else
4409 rc = GPG_ERR_NO_DATA;
4411 else
4412 rc = gpg_error (GPG_ERR_SYNTAX);
4414 return send_error (ctx, rc);
4417 static gpg_error_t
4418 parse_listkeys_opt_secret_only (void *data, void *value)
4420 struct client_s *client = data;
4422 (void) value;
4423 client->opts |= OPT_SECRET_ONLY;
4424 return 0;
4427 static gpg_error_t
4428 parse_keyinfo_opt_learn (void *data, void *value)
4430 struct client_s *client = data;
4432 (void)value;
4433 client->opts |= OPT_KEYINFO_LEARN;
4434 return 0;
4437 static gpg_error_t
4438 keyinfo_command (assuan_context_t ctx, char *line)
4440 struct client_s *client = assuan_get_pointer (ctx);
4441 gpg_error_t rc = 0;
4442 char **keys = NULL, **p = NULL;
4443 int sym = 0;
4444 struct argv_s *args[] = {
4445 &(struct argv_s) {"learn", OPTION_TYPE_NOARG, parse_keyinfo_opt_learn},
4446 NULL
4449 rc = parse_options (&line, args, client, 0);
4450 if (rc)
4451 return send_error (ctx, rc);
4453 if (line && *line)
4454 return send_error (ctx, GPG_ERR_SYNTAX);
4456 if (!(client->flags & FLAG_OPEN))
4457 return send_error (ctx, GPG_ERR_INV_STATE);
4459 if (client->opts & OPT_KEYINFO_LEARN)
4461 rc = cache_agent_command ("LEARN");
4462 return send_error (ctx, rc);
4465 if (client->flags & FLAG_NEW)
4466 return send_error (ctx, GPG_ERR_NO_DATA);
4468 rc = lock_flock (ctx, client->filename, FLOCK_TYPE_SH, &client->flock_fd);
4469 if (rc)
4470 return send_error (ctx, rc);
4472 rc = crypto_is_symmetric (client->filename);
4473 unlock_flock (&client->flock_fd);
4474 if (!rc)
4475 sym = 1;
4476 else if (rc != GPG_ERR_BAD_DATA)
4477 return send_error (ctx, rc);
4479 rc = 0;
4480 if (!sym)
4482 p = strv_catv (keys, client->crypto->pubkey);
4483 if (!p)
4484 rc = GPG_ERR_ENOMEM;
4485 else
4486 keys = p;
4489 if (!rc && client->crypto->sigkey)
4491 if (!strv_printf (&keys, "S%s", client->crypto->sigkey))
4493 strv_free (keys);
4494 return send_error (ctx, GPG_ERR_ENOMEM);
4498 if (!rc)
4500 if (keys)
4502 line = strv_join ("\n", keys);
4503 strv_free (keys);
4504 pthread_cleanup_push ((void *)xfree, line);
4505 if (line)
4506 rc = xfer_data (ctx, line, strlen (line));
4507 else
4508 rc = GPG_ERR_ENOMEM;
4510 pthread_cleanup_pop (1);
4512 else
4513 rc = GPG_ERR_NO_DATA;
4515 else
4516 strv_free (keys);
4518 return send_error (ctx, rc);
4521 static gpg_error_t
4522 kill_command (assuan_context_t ctx, char *line)
4524 struct client_s *client = assuan_get_pointer (ctx);
4525 gpg_error_t rc;
4526 unsigned i, t;
4528 if (!line || !*line)
4529 return send_error (ctx, GPG_ERR_SYNTAX);
4531 MUTEX_LOCK (&cn_mutex);
4532 pthread_cleanup_push ((void *)release_mutex_cb, &cn_mutex);
4533 t = slist_length (cn_thread_list);
4534 rc = GPG_ERR_ESRCH;
4536 for (i = 0; i < t; i++)
4538 struct client_thread_s *thd = slist_nth_data (cn_thread_list, i);
4539 char *tmp = str_asprintf ("%p", thd->tid);
4541 if (strcmp (line, tmp))
4543 xfree (tmp);
4544 continue;
4547 xfree (tmp);
4548 rc = peer_is_invoker (client);
4549 if (!rc)
4551 #ifdef HAVE_PTHREAD_CANCEL
4552 pthread_cancel (thd->tid);
4553 #else
4554 pthread_kill (thd->tid, SIGUSR2);
4555 #endif
4556 break;
4558 else if (rc == GPG_ERR_EACCES)
4559 rc = GPG_ERR_FORBIDDEN;
4560 else if (rc)
4561 break;
4563 if (config_get_boolean ("global", "strict_kill"))
4564 break;
4566 #ifdef WITH_GNUTLS
4567 if (client->thd->remote && thd->remote)
4569 if (!thd->tls || !thd->tls->fp)
4571 rc = GPG_ERR_INV_STATE;
4572 break;
4574 if (!strcmp (client->thd->tls->fp, thd->tls->fp))
4576 #ifdef HAVE_PTHREAD_CANCEL
4577 pthread_cancel (thd->tid);
4578 #else
4579 pthread_kill (thd->tid, SIGUSR2);
4580 #endif
4581 break;
4584 else if (!client->thd->remote && !thd->remote)
4585 #endif
4587 if (client->thd->peer->uid == thd->peer->uid)
4589 #ifdef HAVE_PTHREAD_CANCEL
4590 pthread_cancel (thd->tid);
4591 #else
4592 pthread_kill (thd->tid, SIGUSR2);
4593 #endif
4596 break;
4599 pthread_cleanup_pop (1);
4600 return send_error (ctx, rc);
4603 static gpg_error_t
4604 listkeys_command (assuan_context_t ctx, char *line)
4606 struct client_s *client = assuan_get_pointer (ctx);
4607 struct crypto_s *crypto = NULL;
4608 char **pattern = NULL;
4609 gpgme_key_t *keys = NULL;
4610 char **result = NULL;
4611 gpg_error_t rc;
4612 struct argv_s *args[] = {
4613 &(struct argv_s) {"secret-only", OPTION_TYPE_NOARG,
4614 parse_listkeys_opt_secret_only },
4615 NULL
4618 rc = parse_options (&line, args, client, 1);
4619 if (rc)
4620 return send_error (ctx, rc);
4622 rc = crypto_init (&crypto, client->ctx, client->filename,
4623 client->flags & FLAG_NO_PINENTRY, NULL);
4624 if (rc)
4625 return send_error (ctx, rc);
4627 pthread_cleanup_push ((void *)crypto_free, crypto);
4628 pattern = str_split (line, ",", 0);
4629 pthread_cleanup_push ((void *)(void *)strv_free, pattern);
4630 rc = crypto_list_keys (crypto, pattern, client->opts & OPT_SECRET_ONLY,
4631 &keys);
4632 pthread_cleanup_pop (1);
4633 pthread_cleanup_pop (1);
4634 if (!rc)
4636 int i;
4638 for (i = 0; keys[i]; i++)
4640 char *p = crypto_key_info (keys[i]);
4641 char **r;
4643 if (!p)
4645 rc = GPG_ERR_ENOMEM;
4646 break;
4649 r = strv_cat (result, p);
4650 if (!r)
4652 rc = GPG_ERR_ENOMEM;
4653 break;
4656 result = r;
4659 if (!i)
4660 rc = GPG_ERR_NO_DATA;
4662 crypto_free_key_list (keys);
4665 if (!rc)
4667 line = strv_join ("\n", result);
4668 strv_free (result);
4669 pthread_cleanup_push ((void *)xfree, line);
4670 if (!line)
4671 rc = GPG_ERR_ENOMEM;
4672 else
4673 rc = xfer_data (ctx, line, strlen (line));
4675 pthread_cleanup_pop (1);
4677 else
4678 strv_free (result);
4680 if (gpg_err_code (rc) == GPG_ERR_NO_PUBKEY
4681 || gpg_err_code (rc) == GPG_ERR_NO_SECKEY)
4682 rc = GPG_ERR_NO_DATA;
4684 return send_error (ctx, rc);
4687 void
4688 init_commands ()
4690 /* !BEGIN-HELP-TEXT!
4692 * This comment is used as a marker to generate the offline documentation
4693 * found in doc/pwmd.info. The indentation needs to be kept for the awk
4694 * script to determine where commands begin and end.
4696 new_command("HELP", 1, 1, 0, help_command, _(
4697 "HELP [--html] [<COMMAND>]\n"
4698 "Show available commands or command specific help text."
4699 "@*@*"
4700 "The @option{--html} option will output the help text in HTML format."
4703 new_command("KILL", 1, 0, 0, kill_command, _(
4704 "KILL <thread_id>\n"
4705 "Terminates the client identified by @var{thread_id} and releases any file "
4706 "lock or other resources it has held. See @code{GETINFO} (@pxref{GETINFO}) "
4707 "for details about listing connected clients. An @code{invoking_user} "
4708 "(@pxref{Configuration}) may kill any client while others may only kill "
4709 "clients of the same @code{UID} or @abbr{TLS} fingerprint."
4712 new_command("LISTKEYS", 1, 0, 0, listkeys_command, _(
4713 "LISTKEYS [--secret-only] [pattern[,<pattern>]]\n"
4714 "Returns a new line separated list of key information matching a comma "
4715 "separated list of @var{pattern}'s. When option @option{--secret-only} is "
4716 "specified, only keys matching @var{pattern} that also have a secret key "
4717 "available will be returned."
4720 new_command("KEYINFO", 1, 0, 0, keyinfo_command, _(
4721 "KEYINFO [--learn]\n"
4722 "Returns a new line separated list of key ID's that the currently opened "
4723 "data file has recipients and signers for. If the key is a signing key it "
4724 "will be prefixed with an @code{S}. If the file is a new one, or has no "
4725 "signers in the case of being symmetrically encrypted, the error code "
4726 "@code{GPG_ERR_NO_DATA} is returned."
4727 "@*@*"
4728 "When the @option{--learn} option is passed, keys on a smartcard will be "
4729 "imported."
4732 new_command("GETINFO", 1, 1, 0, getinfo_command, _(
4733 "GETINFO [--data] [--verbose] CACHE | CLIENTS | PID | USER | LAST_ERROR | VERSION\n"
4734 "Get server and other information. The information is returned via a status "
4735 "message (@pxref{Status Messages}) unless otherwise noted or @option{--data} "
4736 "is specified."
4737 "@*@*"
4738 "@var{CACHE} returns the number of cached documents."
4739 "@*@*"
4740 "@var{CLIENTS} returns the number of "
4741 "connected clients via a status message or a list of connected clients when "
4742 "the @option{--verbose} parameter is used (implies @option{--data}). A "
4743 "verbose line of a client list contains "
4744 "space delimited "
4745 "fields: the thread ID, client name, opened file (@code{/} if none opened), "
4746 "IP address if remote, file lock status, whether the current client is self "
4747 "or not, client state (see below), "
4748 "user ID or TLS fingerprint of the connected client, username if the "
4749 "client is a local one else @code{-}, and finally the time stamp of when the "
4750 "client connected."
4751 "@*@*"
4752 "Client state @code{0} is an unknown client state, state @code{1} indicates "
4753 "the client has connected but hasn't completed initializing, state @code{2} "
4754 "indicates that the client is idle, state @code{3} means the "
4755 "client is in a command and state @code{4} means the client is disconnecting. "
4756 "@*@*"
4757 "@var{PID} returns the process ID number of the server via a data response."
4758 "@*@*"
4759 "@var{VERSION} returns the server version number and compile-time features "
4760 "via a data response with each being space delimited."
4761 "@*@*"
4762 "@var{LAST_ERROR} returns a detailed description of the last failed command "
4763 "via a data response, when available."
4764 "@*@*"
4765 "@var{USER} returns the username or @abbr{TLS} hash of the connected client "
4766 "via a data response."
4769 new_command("PASSWD", 0, 0, FLOCK_TYPE_EX|FLOCK_TYPE_KEEP, passwd_command, _(
4770 "PASSWD\n"
4771 "Changes the passphrase of the secret key required to open the current "
4772 "data file. If the data file is symmetrically encrypted, the error "
4773 "@code{GPG_ERR_NOT_SUPPORTED} is returned. When symmetrically encrypted, "
4774 "the @code{SAVE} command (@pxref{SAVE}) should be used instead to prevent "
4775 "this command saving any unwanted changes to the @abbr{XML} document."
4776 "@*@*"
4777 "This command is not available to non-invoking clients "
4778 "(@pxref{Access Control})."
4781 new_command("OPEN", 1, 1, FLOCK_TYPE_SH|FLOCK_TYPE_KEEP, open_command, _(
4782 "OPEN [--lock] <filename>\n"
4783 "Opens @var{filename}. When the @var{filename} is not found on the "
4784 "file-system then a new in-memory document will be created. If the file is "
4785 "found, it is looked for in the file cache and when found no passphrase will "
4786 "be required to open it. When not cached, @cite{pinentry(1)} will be used to "
4787 "retrieve the passphrase for decryption unless @option{disable-pinentry} "
4788 "(@pxref{OPTION}) was specified in which case @command{pwmd} will "
4789 "@emph{INQUIRE} the client for the passphrase. Note than when configuration "
4790 "option @option{strict_open} is enabled and the client is not an "
4791 "@option{invoking_user}, an error will be returned when the data file does "
4792 "not exist."
4793 "@*@*"
4794 "When the @option{--lock} option is passed then the file mutex will be "
4795 "locked as if the @code{LOCK} command (@pxref{LOCK}) had been sent after the "
4796 "file had been opened."
4799 new_command("GENKEY", 1, 1, 0, genkey_command, _(
4800 "GENKEY --inquire-keyparam | --subkey-of=fpr | --userid=\"str\" [--expire=N] [--algo=\"str\"] [--no-passphrase] [--usage=\"default|sign|encrypt\"\n"
4801 "Generates a new key based on option arguments. One of "
4802 "@option{--inquire-keyparam}, @option{--subkey-of} or @option{--userid} is "
4803 "required. The @option{--subkey-of} option will generate a subkey for the key "
4804 "of the specified fingerprint."
4807 new_command("SAVE", 0, 0, FLOCK_TYPE_EX|FLOCK_TYPE_KEEP, save_command, _(
4808 "SAVE [--symmetric] [--inquire-keyparam | --userid=\"str\" [--expire=N] [--algo=\"str\"] [--no-passphrase]] [--keyid=<fpr>[,..] | [--inquire-keyid]] [--sign-keyid=<fpr>]\n"
4809 "Writes the in-memory @abbr{XML} document to disk. The file written to is the "
4810 "file that was opened using the @code{OPEN} command (@pxref{OPEN}). If the "
4811 "file is a new one or the option @option{--inquire-keyparam} was passed, a "
4812 "new keypair will be generated and @cite{pinentry(1)} will be used to prompt "
4813 "for the passphrase of the secret key to be used for signing."
4814 "@*@*"
4815 "The @option{--inquire-keyparam} option will send an "
4816 "@emph{INQUIRE} to the client to obtain the key parameters to use for "
4817 "generating a new keypair. The inquired data is expected to be in "
4818 "@cite{gnupg} @abbr{XML} format. See the @cite{gnupg} documentation for "
4819 "details. The @option{--userid} option will also generate a new keypair using "
4820 "the optional @option{--algo} algorithm with an optional expiration "
4821 "specified with @option{--expire}. The @option{--no-passphrase} will prevent "
4822 "requiring a passphrase for the newly generated key when used with "
4823 "@option{--userid}. Note that when either "
4824 "@option{--inquire-keyparam} or @option{--userid} is specified a new keypair "
4825 "will be "
4826 "generated reguardless if the file is a new one and that the passphrase for "
4827 "the current file will be required before generating the new keypair. This "
4828 "option is available to non-invoking clients (@pxref{Access Control}) only "
4829 "when the file is a new one."
4830 "@*@*"
4831 "You can encrypt the data file to a recipient other than the one that it "
4832 "was encrypted with by passing the @option{--keyid} or "
4833 "@option{--inquire-keyid} option with a comma separated list of "
4834 "public encryption key fingerprints as its argument. Use the "
4835 "@command{LISTKEYS} command (@pxref{LISTKEYS}) to show key information by "
4836 "pattern. The @option{--sign-keyid} option may also be used to sign the data "
4837 "file with an alternate key by specifying the fingerprint of a signing key. "
4838 "Only one signing key is supported unlike the @option{--keyid} option. "
4839 "A passphrase to decrypt the data file "
4840 "will be required when one or more of the original encryption keys or signing "
4841 "key are not found in either of these two options' arguments or when the data "
4842 "file is symmetrically encrypted, reguardless of the @code{require_save_key} "
4843 "configuration parameter. The original encryption keys and signing key will be "
4844 "used when either of these options are not specified."
4845 "@*@*"
4846 "The @option{--keyid} and @option{--sign-keyid} options are not available "
4847 "to non-invoking clients "
4848 "(@pxref{Access Control}) when the recipients or signer do not match those "
4849 "that were used when the file was @code{OPEN}'ed."
4850 "@*@*"
4851 "The @option{--symmetric} option specifies that a new data file be "
4852 "conventionally encrypted. These types of data files do not use a recipient "
4853 "public key but may be signed by using the @option{--sign-keyid} option. "
4854 "To remove the signing key from a symmtrically encrypted data file, leave the "
4855 "option value empty."
4856 "@*@*"
4857 "Note that you cannot change encryption schemes once a data file has been "
4858 "saved."
4861 new_command("ISCACHED", 1, 0, 0, iscached_command, _(
4862 "ISCACHED [--lock] [--agent [--sign]] <filename>\n"
4863 "Determines the file cache status of the specified @var{filename}. "
4864 "The default is to test whether the filename is cached in memory. Passing "
4865 "option @option{--agent} will test the @command{gpg-agent} cache for at most "
4866 "one cached key used for opening the data file (@pxref{OPEN}). To test if "
4867 "a signing key is cached, pass @option{--sign} along with @option{--agent}. "
4868 "Both the @option{--agent} and @option{--sign} options require an opened data "
4869 "file."
4870 "@*@*"
4871 "An @emph{OK} response is returned if the specified @var{filename} is found "
4872 "in the cache. If not found in the cache but exists on the filesystem "
4873 "then @code{GPG_ERR_NO_DATA} is returned. Otherwise a filesystem error is "
4874 "returned."
4875 "@*@*"
4876 "The @option{--lock} option will lock the file mutex of @var{filename} when "
4877 "the file exists; it does not need to be opened nor cached. The lock will be "
4878 "released when the client exits or sends the @code{UNLOCK} command "
4879 "(@pxref{UNLOCK}). When this option is passed the current data file is closed."
4882 new_command("CLEARCACHE", 1, 1, 0, clearcache_command, _(
4883 "CLEARCACHE [<filename>]\n"
4884 "Clears a file cache entry for all or the specified @var{filename}. Note that "
4885 "this will also clear any @command{gpg-agent} cached keys which may cause "
4886 "problems if another data file shares the same keys as @var{filename}."
4887 "@*@*"
4888 "When clearing all cache entries a permissions test is done against the "
4889 "current client based on the @var{allowed} configuration parameter in a "
4890 "@var{filename} section. Both a cache entry may be cleared and an error "
4891 "returned depending on cached data files and client permissions."
4894 new_command("CACHETIMEOUT", 1, 1, 0, cachetimeout_command, _(
4895 "CACHETIMEOUT <filename> <seconds>\n"
4896 "The time in @var{seconds} until @var{filename} will be removed from the "
4897 "cache. @code{-1} will keep the cache entry forever, @code{0} will require "
4898 "the passphrase for each @code{OPEN} command (@pxref{OPEN}) or @code{SAVE} "
4899 "(@pxref{SAVE}) command. @xref{Configuration}, and the @code{cache_timeout} "
4900 "parameter."
4903 new_command("LIST", 0, 1, 0, list_command, _(
4904 "LIST [--inquire] [--recurse] [element[<TAB>child[..]]]\n"
4905 "If no element path is given then a newline separated list of root elements "
4906 "is returned with a data response. If given, then children of the specified "
4907 "element path are returned."
4908 "@*@*"
4909 "Each element path "
4910 "returned will have zero or more flags appened to it. These flags are "
4911 "delimited from the element path by a single space character. A flag itself "
4912 "is a single character. Flag @code{P} indicates that access to the element "
4913 "is denied. Flag @code{+} indicates that there are child nodes of "
4914 "the current element path. Flag @code{E} indicates that an element of the "
4915 "element path contained in a @var{target} attribute could not be found. Flag "
4916 "@code{O} indicates that a @var{target} attribute recursion limit was reached "
4917 "(@pxref{Configuration}). Flag @code{T}, followed by a single space character, "
4918 "then an element path, is the element path of the @var{target} attribute "
4919 "contained in the current element."
4920 "@*@*"
4921 "When a specified element path contains an error, beit from the final "
4922 "element in the path or any previous element, the path is still shown but "
4923 "will contain the error flag for the element with the error. Determining "
4924 "the actual element which contains the error is up to the client. This can be "
4925 "done by traversing the final element up to parent elements that contain the "
4926 "same error flag."
4927 "@*@*"
4928 "The option @option{--recurse} may be used to list the entire element tree "
4929 "for a specified element path or the entire tree for all root elements."
4930 "@*@*"
4931 "When the @option{--inquire} option is passed then all remaining non-option "
4932 "arguments are retrieved via a server @emph{INQUIRE}."
4935 new_command("REALPATH", 0, 1, 0, realpath_command, _(
4936 "REALPATH [--inquire] element[<TAB>child[..]]\n"
4937 "Resolves all @code{target} attributes of the specified element path and "
4938 "returns the result with a data response. @xref{Target Attribute}, for details."
4939 "@*@*"
4940 "When the @option{--inquire} option is passed then all remaining non-option "
4941 "arguments are retrieved via a server @emph{INQUIRE}."
4944 new_command("STORE", 0, 1, 0, store_command, _(
4945 "STORE element[<TAB>child[..]]<TAB>[content]\n"
4946 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
4947 "@*@*"
4948 "Creates a new element path or modifies the @var{content} of an existing "
4949 "element. If only a single element is specified then a new root element is "
4950 "created. Otherwise, elements are @key{TAB} delimited and the content will be "
4951 "set to the final @key{TAB} delimited element. If no @var{content} is "
4952 "specified after the final @key{TAB}, then the content of the existing "
4953 "element will be removed; or will be empty if creating a new element."
4954 "@*@*"
4955 "The only restriction of an element name is that it not contain whitespace "
4956 "characters. There is no other whitespace between the @key{TAB} delimited "
4957 "elements. It is recommended that the content of an element be base64 encoded "
4958 "when it contains control or @key{TAB} characters to prevent @abbr{XML} "
4959 "parsing and @command{pwmd} syntax errors."
4962 new_command("RENAME", 0, 1, 0, rename_command, _(
4963 "RENAME [--inquire] element[<TAB>child[..]] <value>\n"
4964 "Renames the specified @var{element} to the new @var{value}. If an element of "
4965 "the same name as the @var{value} already exists it will be overwritten."
4966 "@*@*"
4967 "When the @option{--inquire} option is passed then all remaining non-option "
4968 "arguments are retrieved via a server @emph{INQUIRE}."
4971 new_command("COPY", 0, 1, 0, copy_command, _(
4972 "COPY [--inquire] source[<TAB>child[..]] dest[<TAB>child[..]]\n"
4973 "Copies the entire element tree starting from the child node of the source "
4974 "element, to the destination element path. If the destination element path "
4975 "does not exist then it will be created; otherwise it is overwritten."
4976 "@*@*"
4977 "Note that attributes from the source element are merged into the "
4978 "destination element when the destination element path exists. When an "
4979 "attribute of the same name exists in both the source and destination "
4980 "elements then the destination attribute will be updated to the source "
4981 "attribute value."
4982 "@*@*"
4983 "When the @option{--inquire} option is passed then all remaining non-option "
4984 "arguments are retrieved via a server @emph{INQUIRE}."
4987 new_command("MOVE", 0, 1, 0, move_command, _(
4988 "MOVE [--inquire] source[<TAB>child[..]] [dest[<TAB>child[..]]]\n"
4989 "Moves the source element path to the destination element path. If the "
4990 "destination is not specified then it will be moved to the root node of the "
4991 "document. If the destination is specified and exists then it will be "
4992 "overwritten; otherwise non-existing elements of the destination element "
4993 "path will be created."
4994 "@*@*"
4995 "When the @option{--inquire} option is passed then all remaining non-option "
4996 "arguments are retrieved via a server @emph{INQUIRE}."
4999 new_command("DELETE", 0, 1, 0, delete_command, _(
5000 "DELETE [--inquire] element[<TAB>child[..]]\n"
5001 "Removes the specified element path and all of its children. This may break "
5002 "an element with a @code{target} attribute (@pxref{Target Attribute}) that "
5003 "refers to this element or any of its children."
5004 "@*@*"
5005 "When the @option{--inquire} option is passed then all remaining non-option "
5006 "arguments are retrieved via a server @emph{INQUIRE}."
5009 new_command("GET", 0, 1, 0, get_command, _(
5010 "GET [--inquire] element[<TAB>child[..]]\n"
5011 "Retrieves the content of the specified element. The content is returned "
5012 "with a data response."
5013 "@*@*"
5014 "When the @option{--inquire} option is passed then all remaining non-option "
5015 "arguments are retrieved via a server @emph{INQUIRE}."
5018 new_command("ATTR", 0, 1, 0, attr_command, _(
5019 "ATTR [--inquire] SET|GET|DELETE|LIST [<attribute>] element[<TAB>child[..]] ..\n"
5020 "@table @asis\n"
5021 "@item ATTR SET attribute element[<TAB>child[..]] [value]\n"
5022 " Stores or updates an @var{attribute} name and optional @var{value} of an "
5023 "element. When no @var{value} is specified any existing value will be removed."
5024 "@*@*"
5025 "@item ATTR DELETE attribute element[<TAB>child[..]]\n"
5026 " Removes an attribute from an element. If @var{attribute} is @code{_name} "
5027 "or @code{target} an error is returned. Use the @command{DELETE} command "
5028 "(@pxref{DELETE}) instead."
5029 "@*@*"
5030 "@item ATTR LIST element[<TAB>child[..]]\n"
5031 " Retrieves a newline separated list of attributes names and values "
5032 "from the specified element. Each attribute name and value is space delimited."
5033 "@*@*"
5034 "@item ATTR GET attribute element[<TAB>child[..]]\n"
5035 " Retrieves the value of an @var{attribute} from an element."
5036 "@end table\n"
5037 "@*@*"
5038 "When the @option{--inquire} option is passed then all remaining non-option "
5039 "arguments are retrieved via a server @emph{INQUIRE}."
5040 "@*@*"
5041 "@xref{Target Attribute}, for details about this special attribute and also "
5042 "@pxref{Other Attributes} for other attributes that are handled specially "
5043 "by @command{pwmd}."
5046 new_command("XPATH", 0, 1, 0, xpath_command, _(
5047 "XPATH [--inquire] <expression>[<TAB>[value]]\n"
5048 "Evaluates an XPath @var{expression}. If no @var{value} argument is "
5049 "specified it is assumed the expression is a request to return a result. "
5050 "Otherwise, the result is set to the @var{value} argument and the document is "
5051 "updated. If there is no @var{value} after the @key{TAB} character, the value "
5052 "is assumed to be empty and the document is updated. For example:"
5053 "@sp 1\n"
5054 "@example\n"
5055 "XPATH //element[@@_name='password']@key{TAB}\n"
5056 "@end example\n"
5057 "@sp 1\n"
5058 "would clear the content of all @var{password} elements in the data file "
5059 "while leaving off the trailing @key{TAB} would return all @var{password} "
5060 "elements in @abbr{XML} format."
5061 "@*@*"
5062 "When the @option{--inquire} option is passed then all remaining non-option "
5063 "arguments are retrieved via a server @emph{INQUIRE}."
5064 "@*@*"
5065 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
5066 "expression syntax."
5069 new_command("XPATHATTR", 0, 1, 0, xpathattr_command, _(
5070 "XPATHATTR [--inquire] SET|DELETE <name> <expression>[<TAB>[<value>]]\n"
5071 "Like the @code{XPATH} command (@pxref{XPATH}) but operates on element "
5072 "attributes and does not return a result. For the @var{SET} operation the "
5073 "@var{value} is optional but the field is required. If not specified then "
5074 "the attribute value will be empty. For example:"
5075 "@sp 1\n"
5076 "@example\n"
5077 "XPATHATTR SET password //element[@@_name='password']@key{TAB}\n"
5078 "@end example\n"
5079 "@sp 1\n"
5080 "would create a @var{password} attribute for each @var{password} element "
5081 "found in the document. The attribute value will be empty but still exist."
5082 "@*@*"
5083 "When the @option{--inquire} option is passed then all remaining non-option "
5084 "arguments are retrieved via a server @emph{INQUIRE}."
5085 "@*@*"
5086 "See @url{http://www.w3schools.com/xpath/xpath_syntax.asp} for @abbr{XPATH} "
5087 "expression syntax."
5090 new_command("IMPORT", 0, 1, 0, import_command, _(
5091 "IMPORT [--root=element[<TAB>child[..]]]\n"
5092 "This command uses a server @emph{INQUIRE} to retrieve data from the client."
5093 "@*@*"
5094 "Like the @code{STORE} command (@pxref{STORE}), but the @var{content} "
5095 "argument is raw @abbr{XML} data. The content is created as a child of "
5096 "the element path specified with the @option{--root} option or at the "
5097 "document root when not specified. Existing elements of the same name will "
5098 "be overwritten."
5099 "@*@*"
5100 "The content must begin with an @abbr{XML} element node. @xref{Introduction}, "
5101 "for details."
5104 new_command("DUMP", 0, 1, 0, dump_command, _(
5105 "DUMP\n"
5106 "Shows the in memory @abbr{XML} document with indenting. @xref{XPATH}, for "
5107 "dumping a specific node."
5110 new_command("LOCK", 0, 0, 0, lock_command, _(
5111 "LOCK\n"
5112 "Locks the mutex associated with the opened file. This prevents other clients "
5113 "from sending commands to the same opened file until the client "
5114 "that sent this command either disconnects or sends the @code{UNLOCK} "
5115 "command. @xref{UNLOCK}."
5118 new_command("UNLOCK", 1, 0, 0, unlock_command, _(
5119 "UNLOCK\n"
5120 "Unlocks the file mutex which was locked with the @code{LOCK} command or "
5121 "a commands' @option{--lock} option (@pxref{LOCK}, @pxref{OPEN}, "
5122 "@pxref{ISCACHED})."
5125 new_command("GETCONFIG", 1, 1, 0, getconfig_command, _(
5126 "GETCONFIG [filename] <parameter>\n"
5127 "Returns the value of a @command{pwmd} configuration @var{parameter} with a "
5128 "data response. If no file has been opened then the value for @var{filename} "
5129 "or the default from the @var{global} section will be returned. If a file "
5130 "has been opened and no @var{filename} is specified, the value previously "
5131 "set with the @code{OPTION} command (@pxref{OPTION}) will be returned."
5134 new_command("OPTION", 1, 1, 0, option_command, _(
5135 "OPTION <NAME>=[<VALUE>]\n"
5136 "Sets a client option @var{name} to @var{value}. The value for an option is "
5137 "kept for the duration of the connection with the exception of the "
5138 "@command{pinentry} options which are defaults for all future connections "
5139 "(@pxref{Pinentry}). When @var{value} is empty the option is unset."
5140 "@*@*"
5141 "@table @asis\n"
5142 "@item DISABLE-PINENTRY\n"
5143 "Disable use of @command{pinentry} for passphrase retrieval. When @code{1}, a "
5144 "server inquire is sent to the client to obtain the passphrase. This option "
5145 "may be set as needed before the @code{OPEN} (@pxref{OPEN}), @code{PASSWD} "
5146 "(@pxref{PASSWD}) and @code{SAVE} (@pxref{SAVE}) commands. Set to @code{0} "
5147 "to use a @command{pinentry}."
5148 "@*@*"
5149 "@item DISPLAY\n"
5150 "Set or unset the X11 display to use when prompting for a passphrase."
5151 "@*@*"
5152 "@item TTYNAME\n"
5153 "Set the terminal device path to use when prompting for a passphrase."
5154 "@*@*"
5155 "@item TTYTYPE\n"
5156 "Set the terminal type for use with @option{TTYNAME}."
5157 "@*@*"
5158 "@item NAME\n"
5159 "Associates the thread ID of the connection with the specified textual "
5160 "representation. Useful for debugging log messages. May not contain whitespace."
5161 "@*@*"
5162 "@item LOCK-TIMEOUT\n"
5163 "When not @code{0}, the duration in tenths of a second to wait for the file "
5164 "mutex which has been locked by another thread to be released before returning "
5165 "an error. When @code{-1} the error will be returned immediately."
5166 "@*@*"
5167 "@item CLIENT-STATE\n"
5168 "When set to @code{1} then client state status messages for other clients are "
5169 "sent to the current client. The default is @code{0}."
5170 "@end table\n"
5173 new_command("LS", 1, 1, 0, ls_command, _(
5174 "LS\n"
5175 "Returns a newline separated list of data files stored in the data directory "
5176 "@file{HOMEDIR/data} (@pxref{Invoking}) with a data response."
5179 new_command("RESET", 1, 1, 0, NULL, _(
5180 "RESET\n"
5181 "Closes the currently opened file but keeps any previously set client options "
5182 "(@pxref{OPTION})."
5185 new_command("NOP", 1, 1, 0, NULL, _(
5186 "NOP\n"
5187 "Does nothing. Always returns successfully."
5190 /* !END-HELP-TEXT! */
5191 new_command ("CANCEL", 1, 1, 0, NULL, NULL);
5192 new_command ("END", 1, 1, 0, NULL, NULL);
5193 new_command ("BYE", 1, 1, 0, NULL, NULL);
5195 int i;
5196 for (i = 0; command_table[i]; i++);
5197 qsort (command_table, i - 1, sizeof (struct command_table_s *),
5198 sort_commands);
5201 gpg_error_t
5202 register_commands (assuan_context_t ctx)
5204 int i = 0, rc;
5206 for (; command_table[i]; i++)
5208 if (!command_table[i]->handler)
5209 continue;
5211 rc = assuan_register_command (ctx, command_table[i]->name,
5212 command_table[i]->handler,
5213 command_table[i]->help);
5214 if (rc)
5215 return rc;
5218 rc = assuan_register_bye_notify (ctx, bye_notify);
5219 if (rc)
5220 return rc;
5222 rc = assuan_register_reset_notify (ctx, reset_notify);
5223 if (rc)
5224 return rc;
5226 rc = assuan_register_pre_cmd_notify (ctx, command_startup);
5227 if (rc)
5228 return rc;
5230 return assuan_register_post_cmd_notify (ctx, command_finalize);